Compare commits

..
Author SHA1 Message Date
Mohamed Boudra fa6df8a959 fix(app): keep the composer's remembered provider in its picker
The picker leaves out providers that aren't installed, except the one
holding the picker's current choice. The schedule form and metadata page
passed that choice; the new-agent composer didn't, so a remembered
provider not installed on this host vanished from the picker and the
trigger read "Select model" with no reason given. The builder now requires
every caller to say what its current choice is, or null.
2026-11-14 14:41:27 +01:00
Mohamed Boudra ec179aa01e fix(app): don't leave a re-added provider's sheet stuck on Removing...
The setup step and the model picker's gear keep a provider's sheet
mounted after it closes, keyed by provider. A finished removal stayed
set in that sheet, so adding the same provider back reopened it with
Remove spinning and disabled. A finished removal now ends when the host
lists the provider again.
2026-11-14 14:24:04 +01:00
Mohamed Boudra 0563654cb0 fix(app): show progress on the provider page's in-flight buttons
Remove, Add model and the diagnostic re-run now show their work on the
pressed control, like the page's Refresh and Update: a spinner, no
further presses and, on a labelled button, "Removing..." or "Adding...".

Remove kept its label and only disabled itself, and the page went blank
mid-removal: the daemon publishes the provider list without the removed
provider before it answers the config patch, so the body had nothing to
show and each frame's title fell back to the raw id. The removal now
keeps the entry the user confirmed, and one hook feeds the frame's title
and the body, so both keep showing the provider until the page closes.
The in-flight state also starts after confirmation, not while the
dialog is open.

The diagnostic sheet's header icon buttons had lost the base branch's
spinner and dimming; SheetHeaderIconButton now takes loading and
disabled, the way Button does.
2026-11-14 14:12:14 +01:00
Mohamed Boudra 6ead9a9e0b fix(app): show the not-found notice when a provider is removed elsewhere
The page hid the notice for any provider it had shown before, to cover its own Remove. A removal from another client, the CLI or a plugin then left the page blank with no way to tell why. The page now owns its Remove: while that runs and once it succeeds the body shows nothing, and any other absence says the provider isn't on this host.

The removal e2e routes only the e2e daemon's socket, so the fixture's port-6767 guard stays in force.
2026-11-14 13:14:12 +01:00
Mohamed Boudra 4d740fd4dd fix(app): don't call a just-removed provider missing while its page closes
The daemon can publish the provider list without the removed provider before it answers the config patch, so the page said "This provider isn't on this host" until the answer arrived and it navigated away; in a sheet, through the exit animation as well. A page that has shown its provider now shows nothing once it leaves the list. The not-found notice is for a page that never found its provider. The removal e2e holds the config answer so it always sees that order.
2026-11-14 13:03:21 +01:00
Mohamed Boudra ddc45fe1c1 fix(app): show a provider page's loading and not-found states
A provider page opened from its URL (a reload, a cold start, a shared link) rendered its title over nothing until the host's providers arrived, and forever when the id named a provider the host doesn't have. The page body now says Loading..., that the host is offline, that the providers couldn't be read, or that the provider isn't on this host, in the same notice card the provider list uses when it is offline. The page and both sheet frames share the body.
2026-11-14 12:51:41 +01:00
Mohamed Boudra 4ed83a0ef0 refactor(app): name the provider picker's connection and saved-choice options
Callers passed a bare true to reach the saved-choice argument.
2026-11-14 12:11:38 +01:00
Mohamed Boudra 969b2938e9 test(app): wait for an added catalog provider's probe before continuing
Adding a provider opens its page only after the daemon probes it, which can outlast the default expect timeout on CI.
2026-11-14 12:04:12 +01:00
Mohamed Boudra b759977818 fix(app): keep a saved provider choice visible when it is not installed
The provider picker drops unavailable providers. A schedule or metadata-generation setting saved against such a provider then showed Select model. The picker now keeps the saved provider, labelled Unavailable, so the user sees what is set and can change it.
2026-11-14 12:04:12 +01:00
Mohamed Boudra 35acb5a914 fix(app): say Not installed for a disabled provider that is not installed
A disabled provider's snapshot status is unavailable, so the row said Disabled even when the binary was missing. The installation inspection is checked first, so Not installed wins over Disabled.
2026-11-14 12:04:11 +01:00
Mohamed Boudra 0869f6df33 fix(app): don't open a provider's page after its Add sheet was closed
Adding a provider waits for the daemon to probe it. If the user closed the sheet during that wait, the completed add still navigated to the provider's page. The add now remembers which sheet session started it and only opens the page if that session is still current.
2026-11-14 12:04:11 +01:00
Mohamed Boudra 18b19f1e78 fix(app): let screen readers read a settings row's state line
The row's button carries the row's name as its label, so only the title is hidden from assistive tech now; the hint below it (a provider's version, error or Not installed) is read again.

The Enter-on-switch test now dispatches its key events synchronously inside one act. An awaited keyboard call let the Switch's animation run a frame after the test, which Vitest reported as an unhandled error and failed the run.
2026-11-14 12:04:11 +01:00
Mohamed Boudra 37c99c12b1 test(app): find the provider page's buttons in the compact sheet
On compact layouts AdaptiveModalSheet puts its testID on the header only,
so buttons in the page body cannot be found inside it. The spec looks them
up on the page, as it did before the page moved into the sheet.
2026-11-14 11:43:25 +01:00
Mohamed Boudra bf3d6b5fe0 test(app): give the Unistyles stub the light theme's full colours
Since the stub started applying withUnistyles theme mappings, a mapping
reading a colour the stub's theme lacked crashed: the markdown styles read
colors.terminal and failed the plan card disclosure tests. The stub's
colours now start from the light theme, with its own values pinned on top.
2026-11-14 11:43:25 +01:00
Mohamed Boudra 4c072573fe fix(app): reserve a control's height only on rows that open something
The previous change gave every card row a control's minimum height and
the design doc said so, but rows built directly on settingsStyles.row
(66 uses) never got it: a single-line row was 48px or 64px depending on
which code path built it.

The minimum now belongs to SettingsRowHeader, the row with an optional
control slot, so a list where only some rows carry a switch keeps one
height. SettingsRow and hand-built rows take their content's height again,
as on the base branch, and the doc states the narrower rule.
2026-11-14 11:43:25 +01:00
Mohamed Boudra ee4c26f48e fix(app): keep a settings row's switch out of the row's button
The provider row's switch rendered inside the row's <button>. That is
invalid markup, and keys reached both: Enter on the switch toggled it and
also opened the provider's page, and Space on it opened the page without
toggling.

SettingsRowHeader now lays its press target under the row's content as a
sibling of the control. The content lets presses through to the button and
stays out of the accessibility tree, where the button's label already names
the row. Hover is tracked on the row, so it holds over the switch.
2026-11-14 11:43:24 +01:00
Mohamed Boudra 19d791777e fix(app): title a provider's Settings page like a project's
The page title and the detail header both named the provider. The screen
now titles it "Providers" and the page names the provider once, the way a
project's page does.
2026-11-14 10:56:38 +01:00
Mohamed Boudra b2a83d335f fix(app): keep a provider row's error to one line
A long or multi-line error wrapped the hint to two lines with the dot
centred between them. The row cuts it to one line; the provider's page
shows it in full.
2026-11-14 10:56:38 +01:00
Mohamed Boudra c523b3ad9b fix(app): keep settings rows one height and on one icon rail on phones
On touch layouts a switch reserves a 44px control, so in the provider list
rows with a switch stood 10px taller than "Not installed" rows without one.
Card rows now reserve a default control's height, the rule nested rows
already follow.

A compact SettingsRow wrapped with a full `gap`, which added 12px on top of
the leading slot's margin: catalog icons sat 24px from their labels instead
of 12px. The wrap only needs space between lines, so it uses `rowGap`.
2026-11-14 10:56:37 +01:00
Mohamed Boudra 4858e62270 docs: describe the provider list and pages as they are now 2026-11-14 10:26:19 +01:00
Mohamed Boudra d6efcc453b feat(app): open setup's provider pages over the setup card
The detail and Add provider sheets take the setup card's frame and a back
arrow, so they read as pages of setup instead of a sheet over it. The step
is renamed "Your providers" to match the list it shows.
2026-11-14 10:24:00 +01:00
Mohamed Boudra 2e90865134 feat(app): show each provider's version, updates and faults in the list
Each row now says how its provider is: version and model count, Update
available, a spinner while an update runs, a red dot with the error, or
Not installed / Disabled. Only a broken provider gets a dot, and a
provider that is not installed has no switch, since the model picker
already leaves it out. The kebab is gone; Remove lives on the detail.

Rows read the same installation and update queries as the detail, so
opening a provider costs no new requests. Hosts without
providerInstallation still get a correct list from the snapshot alone.

Add provider is a "+ Provider" button in the header and a muted last row;
both open one sheet with search and catalog rows, replacing the tile grid.
After Add, the new provider's detail opens.

The row is the settings kit's detail row, which gains a leading icon, a
hint status (spinner, error dot, or a held line) and a control before the
chevron. The Unistyles test stub now applies withUnistyles theme mappings,
so browser tests render components that read colours through the theme.
2026-11-14 10:17:29 +01:00
Mohamed Boudra 603c52b294 feat(app): open a provider's detail as a Settings page or a sheet
Settings → Providers now pushes a provider page, like Projects and Plugins;
the model picker gear and setup keep a sheet. Both frame one body, ordered
error, Enabled, Installation, Models, Troubleshooting, Danger zone, so the
old sheet's sticky footer and Retry button are gone. Refresh lives once, in
the Troubleshooting status row.

The page header (back link, icon, title) moves into the shared settings kit
so projects, plugins and providers line up on the same rails.
2026-11-14 10:17:29 +01:00
Mohamed Boudra 737792ad7c fix(app): leave providers that are not installed out of the model picker
An agent's own provider stays in its selector, labelled Unavailable.
2026-11-14 10:17:29 +01:00
Mohamed Boudra 3edd502aac test(server): name the provider PATH test for what it shows
The availability check that gates a Copilot spawn still looks on the daemon's
PATH, so the copy on the provider's PATH is not always the one agents launch.
2026-11-14 10:16:17 +01:00
Mohamed Boudra bd3d86749c fix(server): show and update the provider CLI its agents launch
The installation contract found the CLI on the daemon's PATH, while agents
spawn the bare command with the provider's environment. A provider whose env
sets PATH could launch one copy and show and update another, so an update
succeeded while new agents kept the old version. The CLI is now resolved with
the provider's environment.

The section test's check-state table now always names the text it expects, so
no case can skip its assertion.
2026-11-14 10:04:21 +01:00
Mohamed Boudra b152308340 fix(app): keep a running update's progress visible whatever the inspection reads
Update carries the update's progress, but its row rendered only while the inspection read
"installed". An inspection that ran during the update (on reopen or Refresh) could read loading,
not installed or failed while the binary was replaced, and the sheet then showed nothing about the
running update. The Updates row now stays while an update runs.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 2bd55c5ff7 fix(app): show a provider update's progress on its Update button
The pressed button carries an action's progress everywhere else in Settings: Button's own
loading state with a present-participle label, as Browser data's Clear and Project settings'
Save do. Update now does the same, reading "Updating..." from the tap until the update settles,
and the update's row holds only the output while it runs, then the result. This replaces the
row-owned spinner from the previous commit, which no other surface uses.

The installation's in-flight labels use three dots like their siblings.
2026-11-14 09:39:41 +01:00
Mohamed Boudra f7a442f4d4 fix(app): show one progress indicator per provider update and refresh
While an update ran, the Update button and the update's row each showed a spinner. The button's
spinner also widened it, and the row's leading spinner shifted the title when the update settled.
The update's row now owns progress from the tap until the update settles: it shows the update
starting before the host answers, so the indicator never moves, and the Update button only
disables.

Refresh blanked the Installation rows while the provider was asked again, then moved "Checking…"
from the Version row to the Updates row. The rows now keep their last answers until the new ones
arrive, and the Refresh button shows the refresh until both the models and the installation are
read again.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 1f79e07feb fix(app): let update output scroll inside the provider sheet on Android
The output box is a ScrollView nested in the sheet's scrolling body. Android hands the drag to the outer ScrollView unless the inner one sets nestedScrollEnabled, so only the last 240px of a long update's output was readable. The tool-call detail views set the same flag.
2026-11-14 09:39:41 +01:00
Mohamed Boudra c7f55fd13f feat(app): offer provider updates whether or not an update check answers
Update and Update instructions lived inside the row that appeared only after
checkForUpdates answered, so Copilot and OpenCode, which declare update but no
check, never offered either. A check is a convenience: the Updates row now
shows for an installed provider that offers an update, keeps Update or Update
instructions in place in every check state (none, checking, up to date,
available, couldn't check), and shows what the check knows as a hint beside
it. A provider that offers no update still shows the check's answer once it
has one. The daemon already ran update without a check; a test now says so.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 7349b26b56 test(app): keep the custom model check sensitive to a Remove button pushed off the sheet
scrollIntoViewIfNeeded on the Remove button scrolled the overflow-hidden model
card sideways too, so the check passed with the long-id layout fix undone.
Scroll only the Custom models heading into view, which moves the sheet
vertically and leaves the card at scrollLeft 0. With the layout fix undone the
spec now fails at 1200px and 390px again.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 0d9cf2b982 test(app): scroll custom model rows into view before checking them
The provider sheet now shows an Installation section above the model
lists. At 390x1000 the custom model row sits under the sheet footer
until scrolled. The spec checks that a long model id leaves its Remove
button reachable. It had assumed the row needed no vertical scroll.
2026-11-14 09:39:41 +01:00
Mohamed Boudra dc4379ee01 fix(muse): report the build the update check compares
Paseo reuses a cached update check while inspect reports the same
version string. Muse reported 1.4.18 but compared its build
(1.4.18-R8600.1), so a new build of the same release kept the stale
"Update available" for up to an hour. The contract docs now say to
include everything the check compares in the reported version.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 8e0a18f595 fix(providers): share one update check when two clients reopen after a version change 2026-11-14 09:39:41 +01:00
Mohamed Boudra b927be1bc7 test(app): assert provider installation states are visible 2026-11-14 09:39:41 +01:00
Mohamed Boudra e755886c4f fix(providers): keep update checks within their own deadline
Tying a cached check to its version made every check wait for a fresh
inspection, which could add the 20 s inspect deadline to the 25 s check
deadline. A check now never starts an inspection. It waits on one only
when the inspection is cached or already running and the check would
reuse a cached answer. When it asks the provider, it records the version
afterwards.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 857808f7c9 fix(app): refresh provider version after an update settles while disconnected
The installation and update queries were invalidated only by a live
succeeded progress event. A connection dropped mid-update delivered the
settled operation as a snapshot on reconnect, which left the old version
and Update on screen. A success the view saw running now rereads them
whether it arrives as progress or as a snapshot.
2026-11-14 09:39:41 +01:00
Mohamed Boudra ad5e76b133 fix(providers): reuse a cached update check only for the version it answered
The previous fix dropped the cached check after an inspection settled
with a new version. On reopen the app sends inspect and check together,
so the check answered from the stale entry before the inspection
settled. A cached check now records the installed version it was
computed against and is reused only when the current inspection, shared
if in flight, reports the same version.
2026-11-14 09:39:41 +01:00
Mohamed Boudra d7e8099288 docs(providers): say when Update instructions shows 2026-11-14 09:39:41 +01:00
Mohamed Boudra 27bbf5355b fix(providers): keep update checks in step with the installed version
A conclusive check is cached for an hour and was not tied to the version
it answered for. After a CLI updated outside Paseo, settings showed the
new version and still offered Update to it. When an inspection reports a
different version, the cached check is dropped. Versions are compared
for equality, so they stay opaque.

The release comparison dropped prerelease suffixes, so Codex
0.200.0-alpha.1 looked current against 0.200.0. A prerelease now comes
before the release with the same numbers. Two different prereleases of
the same release are reported as unknown.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 3536689ffb fix(app): bound update output and show refresh failures in provider settings
The screen appended every progress chunk with no limit while open, so a
noisy updater grew memory and never showed the truncation note that a
reopened screen shows. Progress now folds with the daemon's 64 KiB limit.

A manual refresh stored its result and failure outside the queries the
screen reads, so a failed refresh brought back the old answer with no
warning. Refresh now runs through those queries. It passes staleTime 0
because the app's default staleTime of Infinity would otherwise answer
from the cache.

The not-connected error uses the translated string the i18n check
requires.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 322c542eaf chore(protocol): mark provider installation as shipping in v0.17.0
main is on the 0.16 beta series, and a promotion ships the tested beta's
content without pulling from main, so this lands in the next minor.
2026-11-14 09:39:40 +01:00
Mohamed Boudra fa8dcb372a docs(providers): document the provider installation contract
Plugin authors get the contract in the provider guide, with a worked
example that reports a version, checks for an update and runs the CLI's
own updater, and every field, deadline and cache in the reference.
The internal provider and plugin docs record why the three callbacks are
separate, that versions are opaque, that Paseo adds no verification to
an update, and how the plugin bridge carries and cancels each request.
2026-11-14 09:39:40 +01:00
Mohamed Boudra 59ab8b8c1f feat(providers): report installation for the remaining providers
Copilot, OpenCode, Pi, Oh My Pi, Antigravity and Hoplite now show an
install link and the installed version in provider settings. Each one
declares only what its CLI offers:

- Update checks ask the source the CLI's own updater reads: Pi's
  latest-version endpoint, `omp update --check`, and Hoplite's
  latest.json. Copilot and OpenCode resolve their release inside the
  binary, so they declare no check.
- Updates run the CLI's own command: `copilot update`, `opencode
  upgrade`, `pi update --self` (leaves Pi packages alone), `omp update`.
  Antigravity and Hoplite document no self-update.

OpenCode's success message asks for a daemon restart, because all
OpenCode agents share one server that keeps running the old version.
2026-11-14 09:39:40 +01:00
Mohamed Boudra 75a1ccdcee feat(providers): run provider updates from provider settings
Providers can declare `update(context)`, and the Installation section shows an Update
button when an update is available. The daemon owns the operation: one per provider,
joined by later requests, kept in memory past client disconnects, streamed to subscribers
through an owned subscription, and aborted only when the daemon stops. The provider's
answer is the outcome; the daemon adds no verification. After success it drops the cached
inspection and update check and refreshes discovery, without restarting agents.

Codex and Claude run their own `update` subcommand and pass the output through. Muse has
no update subcommand, so it does not declare one.

Updater output is capped at 64 KiB per update so a chatty updater cannot grow daemon memory.
Starting an update requires daemon.manage because it runs commands on the host.
2026-11-14 09:39:40 +01:00
Mohamed Boudra 4b67d035ce feat(providers): show available updates in provider settings
Providers can now declare `installation.checkForUpdates`, returning
`current`, `available` with opaque `versions` and `message`, or `unknown`.
The provider decides what counts as newer; Paseo shows its answer as
written and never parses or compares versions.

The check is its own RPC, `provider.installation.check_updates`, so the
installed version never waits on a network lookup. The daemon caches a
conclusive answer for an hour and an inconclusive one for 30s, shares
in-flight calls, and deadlines the call at 25s, below the plugin RPC
timeout. A throw or timeout comes back as `error`, which the app shows as
inconclusive, never as up to date. The sheet's Refresh bypasses the cache.

Codex and Claude Code read the release source their own updaters use:
the Homebrew cask for cask installs, otherwise the GitHub latest release
for Codex and the configured `autoUpdatesChannel` for Claude Code.
`codex doctor --json` reports the same answer but scans local state and
took close to a minute, so it is not used. Muse compares its build with
the launcher's channel manifest, the same rule the launcher updates by.

The install link now shows whenever the provider declares `installUrl`
and is not reported installed: the Install button for `not_installed`, a
quieter "Install instructions" link when the check failed or the
provider only links to a guide.
2026-11-14 09:39:40 +01:00
Mohamed Boudra 5afbd0d7d3 feat(providers): show installed version and install link in provider settings
Providers can now declare `installation`: install and update links plus an
`inspect` callback that reports installed state and an opaque version string.
Built-in clients and plugin providers share one contract; plugins receive the
daemon-resolved launch with `resolved: false` when the executable is missing,
so they can report not installed instead of failing.

The daemon calls `inspect` only on the new
`provider.installation.inspect.request` RPC, never from availability probing,
discovery or session creation, so a slow version probe cannot delay agents.
Results are cached per client for 30s, deadlined at 20s, and links survive a
failed probe. The app gates the provider sheet's Installation row on
`server_info.features.providerInstallation`, so older hosts show nothing new.
2026-11-14 09:39:40 +01:00
391 changed files with 12062 additions and 16617 deletions
+6 -1
View File
@@ -530,7 +530,7 @@
}
},
// Press feedback is owned by the primitives in components/ui. Raw pressable burn-down:
// 85 files. They may only leave this list.
// 94 files. They may only leave this list.
{
"files": [
"packages/app/src/components/ui/**/*.{ts,tsx}",
@@ -539,9 +539,12 @@
"packages/app/src/agent-skills/selection-sheet.tsx",
"packages/app/src/agent-stream/chat-outline/rail.web.tsx",
"packages/app/src/agent-stream/view.tsx",
"packages/app/src/changelog/internal/changelog-sheet.tsx",
"packages/app/src/command-center/command-center.tsx",
"packages/app/src/components/adaptive-modal-sheet.tsx",
"packages/app/src/components/add-project-flow.tsx",
"packages/app/src/components/agent-list.tsx",
"packages/app/src/components/app-diagnostic-sheet.tsx",
"packages/app/src/components/attachment-lightbox.tsx",
"packages/app/src/components/attachment-pill.tsx",
"packages/app/src/components/combined-model-selector.tsx",
@@ -580,6 +583,7 @@
"packages/app/src/components/terminal-emulator-native-grid.native.tsx",
"packages/app/src/components/terminal-pane.tsx",
"packages/app/src/components/toast-host.tsx",
"packages/app/src/components/tool-call-sheet.tsx",
"packages/app/src/components/welcome-screen.tsx",
"packages/app/src/components/workspace-hover-card.tsx",
"packages/app/src/components/zoomable-viewport/toolbar.tsx",
@@ -615,6 +619,7 @@
"packages/app/src/screens/workspace/scripts/workspace-scripts-button.tsx",
"packages/app/src/screens/workspace/workspace-desktop-tabs-row.tsx",
"packages/app/src/screens/workspace/workspace-tab-presentation.tsx",
"packages/app/src/tool-calls/detail-level/overview/sheet.tsx",
"packages/app/src/usage/sidebar-item.tsx",
"packages/app/src/usage/window-bar.tsx",
"packages/app/src/workspace-labels/manager-modal.tsx",
+1 -13
View File
@@ -186,8 +186,7 @@ Drop a hunk when the installed LegendList ships its fix.
`modules/paseo-scroll` replaces React Native's scroll view on both platforms with a subclass:
Android's `PaseoScrollView` and iOS's `PaseoScrollViewComponentView`.
`VisibleContentPositionClampTest` and `SelectableTextTouchTest` cover Android; iOS has no native
test harness.
`VisibleContentPositionClampTest` covers Android; iOS has no native test harness.
**Content clamp.** A mount that shrinks the content while `maintainVisibleContentPosition` is set
applies the shrink twice on both platforms: the scroll view clamps its offset to the new end during
@@ -207,16 +206,5 @@ React Native 0.88 skips the adjustment for a removed anchor
and skip its correction while the user drags ([user scroll](#user-scroll)). This one has no React
Native counterpart; it stays while the timeline uses the pin.
**Touched text (Android).** Chat text is selectable, and Android focuses selectable text when it is
touched. React Native scrolls a newly focused view fully into view, so tapping a link or a word, or
long-pressing to select, in a message partly off screen moved the timeline by up to a screen.
`PaseoScrollView` skips that scroll when the focused view is selectable, non-editable text in touch
mode. The text keeps focus, and a streaming reply's new text collapses its selection to the start,
which asks to reveal the reply's first line; that request is skipped too while nothing is selected.
A change in the timeline's height, such as the composer below it growing, also reveals the focused
view, and is skipped the same way. Inputs, focus moved by a keyboard, and a selection the user drags
still scroll into view. The inverted timeline guarded this with a rule tied to the inversion, which
went with it; keep this one while chat text is selectable.
Remove the content clamp and removed-anchor overrides once the installed React Native includes
their fixes.
+4 -4
View File
@@ -186,10 +186,10 @@ This is the Android counterpart of the iOS local-simulator flow in [development.
## Scroll view corrections
`modules/paseo-scroll` replaces React Native's vertical scroll view with `PaseoScrollView`, which
keeps React Native's scroll manager interface and corrects how the chat timeline holds its position.
[agent-stream-disclosure.md](agent-stream-disclosure.md#scroll-view-corrections) lists the
corrections and the React Native issues they work around. Its instrumentation tests run the scroll
view in a real window, mounting through React Native's own mounting manager and injecting touches:
keeps React Native's scroll manager interface and corrects `maintainVisibleContentPosition` for the
chat timeline. [agent-stream-disclosure.md](agent-stream-disclosure.md#scroll-view-corrections)
lists the corrections and the React Native issues they work around. Its instrumentation test,
`VisibleContentPositionClampTest`, mounts through React Native's own mounting manager:
```bash
cd packages/app/android
+8 -10
View File
@@ -20,7 +20,7 @@ A semantic element used in three or more places is a primitive. One of a kind is
Primitives live in `packages/app/src/components/ui/` and `packages/app/src/components/headers/`. Card and row layout live in `packages/app/src/styles/settings.ts`. Section structure lives in `packages/app/src/screens/settings/settings-section.tsx`.
A pressable styled to look like a button is wrong; the button is `<Button>` (`packages/app/src/components/ui/button.tsx`). A pressable wrapping an icon is wrong; the icon action is `<ToolbarButton>` (`packages/app/src/components/ui/pane-content-toolbar.tsx`), which owns the hitbox, the rounded `interactionHighlight` fill on hover and press, the compact size, and the tooltip. Rows on a menu surface are `<MenuItem>`, or `<ComposerTrackRow>` in a track panel; other rows are `<PressHighlight>` (`packages/app/src/components/ui/press-highlight.tsx`), which owns the pressed feedback: pass the pressed fill as `highlightStyle` and never paint it in your own style. iOS and web paint that fill; Android draws the platform ripple over the content instead, clipped to the row's corners. On native, feedback waits for a short press delay so a scroll that claims the touch shows none. Content that knocks out of the row's surface, such as a badge ring, follows the fill through `onHighlightChange`. A bare `<Text>` styled to look like a section header is wrong; the section header is `<SettingsSection>` (`packages/app/src/components/settings/headings/settings-section.tsx`). A docs link in its header is its `link` prop, which renders `Label ↗` on the title's rail; a ghost button with an arrow is wrong. A custom `Modal` for a confirmation is wrong; the confirmation is `confirmDialog` (`packages/app/src/utils/confirm-dialog.ts`). A hand-rolled overflow menu is wrong; the menu is `<DropdownMenu>` (`packages/app/src/components/ui/dropdown-menu.tsx`). A hand-rolled status pill is wrong; the pill is `<StatusBadge>` (`packages/app/src/components/ui/status-badge.tsx`). A circle pinned over a scrolling surface is wrong; the floating action is `<FloatingActionButton>` (`packages/app/src/components/ui/floating-action-button.tsx`), one per surface, and the surface reserves `FLOATING_ACTION_BUTTON_CLEARANCE` below its content so the button never traps the last row.
A pressable styled to look like a button is wrong; the button is `<Button>` (`packages/app/src/components/ui/button.tsx`). A pressable wrapping an icon is wrong; the icon action is `<ToolbarButton>` (`packages/app/src/components/ui/pane-content-toolbar.tsx`), which owns the hitbox, the rounded `interactionHighlight` fill on hover and press, the compact size, and the tooltip. Rows on a menu surface are `<MenuItem>`, or `<ComposerTrackRow>` in a track panel; other rows are `<PressHighlight>` (`packages/app/src/components/ui/press-highlight.tsx`), which uses React Native’s press lifecycle on native with a short press delay so scrolling cancels pending feedback. A bare `<Text>` styled to look like a section header is wrong; the section header is `<SettingsSection>` (`packages/app/src/components/settings/headings/settings-section.tsx`). A docs link in its header is its `link` prop, which renders `Label ↗` on the title's rail; a ghost button with an arrow is wrong. A custom `Modal` for a confirmation is wrong; the confirmation is `confirmDialog` (`packages/app/src/utils/confirm-dialog.ts`). A hand-rolled overflow menu is wrong; the menu is `<DropdownMenu>` (`packages/app/src/components/ui/dropdown-menu.tsx`). A hand-rolled status pill is wrong; the pill is `<StatusBadge>` (`packages/app/src/components/ui/status-badge.tsx`). A circle pinned over a scrolling surface is wrong; the floating action is `<FloatingActionButton>` (`packages/app/src/components/ui/floating-action-button.tsx`), one per surface, and the surface reserves `FLOATING_ACTION_BUTTON_CLEARANCE` below its content so the button never traps the last row.
Before adding a new component, read `components/ui/`. The primitive usually exists.
@@ -114,8 +114,6 @@ Five primitives. The pick is determined by option count, the need to search, and
`<AdaptiveModalSheet>` owns the presentation. Its content inset — the gutter that puts sheet content on the same rails as the sheet header — and compact bottom safe-area padding are the sheet's, not the caller's. A caller declares layout intent through `contentStyle` and never branches on form factor to add its own margins. If a sheet's first snap point is shorter than its header, content, and safe-area clearance, raise that snap point rather than moving the sheet container.
The sheet header (`SheetHeaderView`) is the only sheet title row. A sheet that brings its own Gorhom modal still renders it. Back, Close and every action passed through `header.actions` are `SheetHeaderIconButton`, so all of them get the header island's chrome, as `CompactHeader` does: one frame, glyph, colour and hover. The first and last buttons hang into the row's padding, so their glyphs sit on the content rail.
`confirmDialog` is for destructive yes/no and imperative confirmation. Promise-based: `await confirmDialog({ destructive: true, ... })`. Anything where a wrong click loses work.
Three themes is `DropdownMenu`. Thirty hosts is `Combobox`. A label and a value is `AdaptiveModalSheet`. "Are you sure?" is `confirmDialog`.
@@ -134,9 +132,9 @@ A section or group explains itself through the `info` prop on `<SettingsSection>
Cards inside a section sit closer than sections. Rows inside a card touch — only the divider separates them. The rhythm is page → spacious; section → spacious; card → tight.
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. A row that opens something (`<SettingsDetailRow>`, a collapsible row's header) is at least as tall as one holding a default control, so a list where only some of those rows carry a switch keeps one row height. Other rows take their content's height. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`).
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand.
The whitespace is the design.
@@ -207,11 +205,11 @@ Terminology:
## 11. States
Loading is inline by default. `<LoadingSpinner size={14} color={foregroundMuted} />` sits next to the thing it relates to (`packages/app/src/screens/settings/providers-section.tsx:227-231`). Page-level loading is a centered `<LoadingSpinner size="large">` (`packages/app/src/screens/sessions-screen.tsx:69-72`). Card-level loading is a single short line, not a spinner. In-row dropdown items use `<DropdownMenuItem status="pending" pendingLabel="Removing...">`; the menu item handles its own pending state.
Loading is inline by default. `<LoadingSpinner size={14} color={foregroundMuted} />` leads the line it relates to, never trails a label: a settings row's hint takes `hintStatus="busy"` while its work runs, and `hintStatus="pending"` holds the line with a skeleton until its value is read (`packages/app/src/components/settings/row-header.tsx`). Page-level loading is a centered `<LoadingSpinner size="large">` (`packages/app/src/screens/sessions-screen.tsx:69-72`). Card-level loading is a single short line, not a spinner. In-row dropdown items use `<DropdownMenuItem status="pending" pendingLabel="Removing...">`; the menu item handles its own pending state.
Screen-level empty states use a centered, muted noun phrase and at most one ghost button (`packages/app/src/screens/sessions-screen.tsx`). Sidebar list empty states use a quiet bordered card with a left-aligned `sm` title, a muted `sm` description, and `sm` `<Button>` actions. Use `secondary` for the primary action and `outline` for a secondary action (`packages/app/src/components/sidebar/empty-states.tsx`). Keep both forms short and free of illustrations.
Inline errors are a single sentence in `palette.red[300]` `xs`, sitting under the field or inside the card it relates to (`packages/app/src/screens/settings/providers-section.tsx:115-119`).
Inline errors are a single sentence in `palette.red[300]` `xs`, sitting under the field or inside the card it relates to (`packages/app/src/components/ui/form-field.tsx`). A settings row that is broken says so in its hint with `hintStatus="error"`: a red dot and the error in `statusDanger`.
Page-level alerts — informational notices, success confirmations, warnings, or recoverable errors that need a small visible block on the page — use `<Alert>` (`packages/app/src/components/ui/alert.tsx`). Variants: `default`, `info`, `success`, `warning`, `error`. The chrome is quiet by design: a 1px tinted border, transparent background, a small variant-tinted icon, the title in the variant accent, the description in `foregroundMuted`. Actions go in the `children` slot as `<Button variant="outline">` — recovery actions are low-frequency and outline keeps them quiet alongside the alert's accent (`packages/app/src/screens/project-settings-screen.tsx`). One `<Alert>` at a time per region.
@@ -233,13 +231,13 @@ Changing state must not move the layout. A row that grows when its badge arrives
The row anatomy is a content column with an optional trailing slot. Inside a card the row is `settingsStyles.row`. Inside a sidebar list the row carries its own padding and `borderRadius.lg` per item (`packages/app/src/components/sidebar-workspace-list.tsx:2614-2625`).
Rows that drill into a detail lead with a chevron in the trailing slot (`ChevronRight`, `iconSize.sm`, `foregroundMuted`). The whole row is the `<Pressable>`. Pair-device row (`packages/app/src/screens/settings/host-page.tsx:644-668`), provider row (`packages/app/src/screens/settings/providers-section.tsx:92-132`), project row in the projects list. A fixed right chevron means navigation. An expandable row uses a trailing right chevron that rotates down when expanded (`SettingsCollapsibleRow`); pressing the row reveals its child rows in place.
A trailing chevron opens a detail, as a page or a sheet (`ChevronRight`, `iconSize.sm`, `foregroundMuted`). The whole row is the pressable; use `<SettingsDetailRow>`. Pair-device row (`packages/app/src/screens/settings/host-page.tsx`), provider row (`packages/app/src/provider-settings/internal/provider-row.tsx`), project row in the projects list. A fixed right chevron means navigation. An expandable row uses a trailing right chevron that rotates down when expanded (`SettingsCollapsibleRow`); pressing the row reveals its child rows in place.
Kebab menus (`<DropdownMenu>` with `<MoreVertical size={14} />` trigger) are for actions on the row, not navigation. Trigger style: `padding: 2`, `borderRadius: 4`, hover background `surface2`. Menu position: `align="end"`. Items use `<DropdownMenuItem leading={<Icon size={14} color={foregroundMuted} />} ...>`. Visibility is `isHovered || isTouchPlatform` — hover-revealed on web, always visible on native (`packages/app/src/components/sidebar-workspace-list.tsx:684-770`).
A row may carry both a chevron and a kebab when both navigation and row-level actions apply. Chevron sits at the end; kebab sits before it.
Switches and segmented controls also sit in the trailing slot. A row that both navigates and toggles is a `<Pressable>` with a `<Switch>` in the trailing slot — the switch calls `event.stopPropagation()` so the row press does not fire (`packages/app/src/screens/settings/providers-section.tsx:92-132`). Sidebar items that hold a status dot, a count, and a kebab follow the same rule (`packages/app/src/components/sidebar-workspace-list.tsx`).
Switches and segmented controls also sit in the trailing slot. A row that both navigates and toggles passes its `<Switch>` as the `control` of `<SettingsDetailRow>`, before the chevron; the switch stops the press from reaching the row (`packages/app/src/provider-settings/internal/provider-row.tsx`). A list the user adds to ends with a muted `<SettingsAddRow>`. Sidebar items that hold a status dot, a count, and a kebab follow the same rule (`packages/app/src/components/sidebar-workspace-list.tsx`).
Selected state on rows in a desktop list+detail uses `surfaceSidebarHover` as the background (`packages/app/src/screens/projects-screen.tsx`). Selected state on rows in the sidebar list uses `surface2` (`packages/app/src/components/agent-list.tsx:563-571`).
@@ -288,7 +286,7 @@ New status pills use `<StatusBadge>`. Identity, shortcut, and interactive link b
| Pattern | Reference |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| List+detail (compact stack, desktop sidebar+pane) | `packages/app/src/screens/settings-screen.tsx`, `packages/app/src/screens/projects-screen.tsx` |
| Detail card+row | `packages/app/src/screens/settings/host-page.tsx`, `packages/app/src/screens/settings/providers-section.tsx` |
| Detail card+row | `packages/app/src/screens/settings/host-page.tsx`, `packages/app/src/provider-settings/internal/provider-list.tsx` |
| Section grouping inside a card list | `packages/app/src/screens/settings/settings-section.tsx` |
| Form modal (label + input fields, primary + cancel) | `packages/app/src/hosts/add-host/internal/add-host-modal.tsx`, `packages/app/src/hosts/add-host/internal/pair-link-modal.tsx`, `packages/app/src/components/project-picker-modal.tsx` |
| Destructive confirmation | `confirmDialog` invoked from `packages/app/src/screens/settings/host-page.tsx:541-547` |
+1 -1
View File
@@ -49,7 +49,7 @@ than downloading a published desktop release.
- The **server itself** (e.g. when launched by the desktop app or `npm run start`) defaults to `~/.paseo` (see `packages/server/src/server/paseo-home.ts`).
- **Repo dev scripts** default to `$ROOT/.dev/paseo-home`, where `$ROOT` is the current checkout or worktree root. This keeps all dev state scoped to the checkout instead of the packaged desktop app.
- **`npm run cli -- ...`** runs through the same dev-home wrapper as the dev scripts, so the in-repo CLI automatically targets the current checkout's `.dev/paseo-home` and configured dev daemon endpoint.
- **Paseo-created worktrees** seed `$PASEO_WORKTREE_PATH/.dev/paseo-home` from `$PASEO_SOURCE_CHECKOUT_PATH/.dev/paseo-home` by copying agent and project JSON metadata and configuration. Both this setup and `PASEO_DEV_SEED_HOME` use the same seeder, which disables `agents.resumeOnStartup` in the copied config. Startup repairs copied running records without resuming agents or sending recovery prompts. Schedules and heartbeats (stored under `schedules/`), runtime files, identities, sockets, and logs are not copied. Existing nonempty homes are left unchanged unless explicitly reset. Copied agents still reference the original provider sessions and working directories: manually prompting one reaches that real session.
- **Paseo-created worktrees** seed `$PASEO_WORKTREE_PATH/.dev/paseo-home` from `$PASEO_SOURCE_CHECKOUT_PATH/.dev/paseo-home` by copying durable JSON metadata. Runtime files like pid files, sockets, and logs are not copied.
- **This repo's worktree setup** also best-effort seeds `packages/app/ios` and the newest `.dev/ios-build` entry from the source checkout so iOS simulator services can reuse native project and Xcode cache state when it is safe enough to do so.
Override knobs:
+9 -39
View File
@@ -7,12 +7,12 @@ canonical files and are trying to add or change one.
## Canonical files
| File | Use case |
| ------------------------------------- | ----------------------------------------------------------------- |
| `components/ui/combobox.tsx` | Anchored picker with search; mobile falls back to bottom sheet |
| `components/ui/tooltip.tsx` | Non-interactive hover/long-press tooltip |
| `components/ui/hover-card.tsx` | Desktop-web hover card the pointer can move onto; Portal |
| `components/ui/autocomplete-popover/` | Slash-command autocomplete anchored to the focused composer input |
| File | Use case |
| ---------------------------------------- | ----------------------------------------------------------------- |
| `components/ui/combobox.tsx` | Anchored picker with search; mobile falls back to bottom sheet |
| `components/ui/tooltip.tsx` | Non-interactive hover/long-press tooltip |
| `components/ui/hover-card.tsx` | Desktop-web hover card the pointer can move onto; Portal |
| `components/ui/autocomplete-popover.tsx` | Slash-command autocomplete anchored to the focused composer input |
Each handles a different mix of concerns: combobox owns input focus, tooltip is
non-interactive, hover-card is web-only desktop, autocomplete keeps the composer
@@ -65,10 +65,6 @@ Two escape hatches in the codebase:
Android can detach the IME from an underlying TextInput. Fine for combobox
(it has its own input) and tooltip (no input). **Not** fine for autocomplete
(the composer's input must stay focused so the user keeps typing).
Use `@/components/ui/modal`, not React Native's `Modal`. On Android, React Native lays out a
modal's first frames at the screen size minus the status and navigation bars, then grows it to
the full edge-to-edge window, so a full-screen backdrop stops short of the bottom and snaps
down. The wrapper sizes the content to the window from the first frame.
- **`<Portal>` from `@gorhom/portal`** (hover-card, autocomplete-popover) —
hoists the React subtree to a fixed mount point whose bounds cover the
screen. Same window, same IME, hit-test works because the new parent is
@@ -284,22 +280,6 @@ popover or leaves it behind the keyboard. `measureAtRest` measures through
Fabric's transform-free `measureLayout` instead. Re-measure when `isMoving`
settles; the composer's resting position changes as the draft grows.
A measured rect is an asynchronous copy, so it lands after the anchor's new
layout has painted. The composer resizes while the autocomplete is open: a
wrapped line, cleared text, a window resize. On web a `ResizeObserver` reads
the anchor's rect against the layer and commits the placement with `flushSync`,
which runs after layout and before paint. On native a Reanimated frame callback
reads only the anchor's height on the UI thread and holds its bottom edge at
the rest measurement. A height carries no transform. On iOS the absolute
position does not reliably include one: the keyboard lift runs on the native
driver and reaches the shadow tree only when the view re-renders. The
fixed-bottom model is wrong for the centered New workspace composer on tablets,
which grows around its middle, and for width or x changes. The popover is off
there by half the growth, or by the old width, until the next rest measurement.
Keep the portal's `KeyboardTranslateView` host-sized with
`pointerEvents="box-none"` and position the popover inside it, so the popover
moves without leaving its parent's bounds (Gotcha 1).
The provider also reconciles iOS from the controller's native `onEnd` event.
The controller's stock iOS shared values update at move start and during an
interactive move, but not at the terminal event, so JS contention can otherwise
@@ -442,11 +422,9 @@ gets that 0 and draws over the navigation bar.
- A Gorhom sheet reads the inset inside its children, which render in the app's sheet host. See
`CompactSheetBody`, `MenuSheetScrollView` and `ComboboxSheetFrame`.
- An RN `Modal` passes the call site's context straight through, so wrap its content in
`WindowSafeArea` from `@/window-layout` and read the inset below that. It provides the insets of
the whole window, published by `WindowLayoutProvider`. Do not put a `SafeAreaProvider` inside the
modal: on Android it measures the dialog window, whose bottom inset reads 24, then 0, then 24
again over the first frames, and everything padded by it jumps. See `attachment-lightbox.tsx`.
- An RN `Modal` passes the call site's context straight through, so put a `SafeAreaProvider`
inside it and read the inset below that. The modal is its own window, and the provider measures
it. See `attachment-lightbox.tsx`.
## Recipe for a new anchored panel
@@ -475,14 +453,6 @@ Before you write a new one, ask:
`top` paints over its anchor until the next placement lands, about 150 ms
on Android. Web hides this because React commits the resize and the
re-placement in one task.
7. **Does the panel hold a list that reads away from its anchor?** Make the
anchor edge the list's resting scroll position: an inverted list, as in
`components/ui/autocomplete.tsx`. On Android a scroll command issued after
the rows commit reaches the screen one or two frames after them, so a list
scrolled to its anchor edge paints its far end first. Give each result set
its own list with a `key`, so it starts at the anchor edge with the rows
that fill the panel. A list that mounts every result holds the panel's
first frame until the last row is ready.
Then copy the closest canonical file and trim.
-2
View File
@@ -59,8 +59,6 @@ Register keyboard handling with `useOverlayRegistration` from `@/keyboard`.
Pass the surface's open state, layer, handled keys and `onKeyDown`. The highest
layer gets first refusal; the latest registration wins a tie. Native registration
does not need a DOM ref. Web adds focus trapping and restoration through its adapter.
Declaring Tab takes it from the web focus trap and hands it to `onKeyDown`; the command
center rotates its tabs with it. Native sources drop Tab from the declarations.
Capture a global overlay’s layer in state for its opening lifetime. Memo caches can
be discarded or removed by React Compiler; recomputing against the registry lets an
+12
View File
@@ -510,6 +510,18 @@ before calling status; it exposes your diagnostic through the normal provider di
A command-backed provider without status is available when its executable resolves. Providers with
neither command nor status retain connection-based availability.
Implement optional `installation` to fill the **Installation** section of provider settings. The
bridge sends each callback as a `provider.installation.*` request carrying the launch `status`
receives plus `resolved`. `resolved: false` means the executable was not found and `command` is
the configured name, so answer `not_installed` instead of spawning it. Inspect and update-check
requests use the 30 s plugin request timeout; the daemon's 25 s update-check deadline sits below
it, so a slow check reports that deadline. `update` has no request timeout and streams output
through `provider.installation.report`. When the daemon stops waiting on any of the three, it
sends `provider.installation.cancel`, which aborts the callback's `signal`.
The rules shared with built-ins are in [providers.md](providers.md#installation-and-updates); the
author contract is in the
[public provider guide](../public-docs/plugins/providers.md#report-installation-and-updates).
A same-ID config entry without `extends` overrides the plugin's `enabled`, `command`, `env`, label,
description, and model configuration through the normal provider registry. `enabled: false` disables
selection and discovery. An entry with `extends` defines the user's own provider, shadows the plugin,
+44
View File
@@ -263,6 +263,50 @@ promise for completion: equal results, including equal discovery timestamps, emi
---
## Installation and updates
The provider list and the **Installation** section of a provider's page read `AgentClient.installation`. Built-ins set
it on the client; plugins set `ProviderRegistration.installation`, which the plugin bridge maps to
the same interface. `ProviderInstallations` in `packages/server/src/server/agent/provider-installation/`
owns deadlines, caching and the one running update per provider, so a provider only answers.
Declare only what the vendor offers:
- `installUrl` and `updateUrl` link the vendor's own install and update docs.
- `inspect` reports the version the CLI prints. Versions are opaque: Paseo shows them as written
and never parses or compares them.
- `checkForUpdates` asks the source the CLI's own updater reads, such as the vendor's release
endpoint or the CLI's `update --check`. Leave it out when that source is inside the binary or
depends on how the CLI was installed, which is why Copilot and OpenCode have no check. Do not
build a release lookup of your own.
- `update` runs the CLI's own update command and passes its output through, using
`runUpdateCommand`. Paseo adds no verification, signature check or rollback, so the update does
exactly what the same command does in a terminal.
The three calls are separate because they cost differently. `inspect` runs for every provider
whenever the provider list shows, because each row states its version; a provider's page shares the
row's request. It has a 20 s deadline and a 30 s cache. `checkForUpdates` usually reaches the
network, so the app asks only after `inspect` reports the CLI installed, and a conclusive answer
holds for an hour while `inspect` reports the same version string. Report every part of the version
the check compares, such as Muse's build, or a CLI updated outside Paseo keeps its stale answer. `update` runs for minutes, streams output, and is aborted only when the daemon
stops.
The update check only informs. Once `inspect` reports the CLI installed, the app offers **Update**
for a provider that declares `update`, or **Update instructions** for one that declares only
`updateUrl`, whatever the check answers and whether the provider has one. The check's answer shows
beside the action when it has one. Copilot and OpenCode have no check, so they show **Update** alone.
Write the success message for the provider's process model. A CLI that Paseo starts once per agent
uses `updatedForNewAgents()`. OpenCode agents share one server that keeps the old binary running,
so its message asks the user to restart the daemon.
`createCliInstallation()` covers a CLI that prints `--version` and updates with a subcommand. It
resolves the configured command, so a profile that extends a built-in reports and updates the CLI
that profile launches. Clients for `extends: "acp"` providers declare no installation.
Test with fake executables, as `providers/provider-update-checks.test.ts` does. Running a real
updater during development replaces the CLI on your machine.
## Usage sources
See the [public usage source reference](../public-docs/plugins/reference.md#usage-sources) for the
+4 -5
View File
@@ -95,11 +95,10 @@ Provider message IDs are not guaranteed for every displayed item. Paseo-generate
Actions that address a point in chat history, such as Fork, use the daemon timeline `epoch` plus the projected item's `seqEnd`. The app carries that position on the rendered assistant item for both live and fetched history. When adjacent projected chunks merge, the merged item retains the newer chunk's position.
The daemon validates the epoch and locates the projected item at the selected position. A fork
includes projected items through that checkpoint. A tool call that started before the checkpoint
and changed after it, such as background work that outlives a reply, is copied as still running:
the projection keeps only its latest payload, so its state at the checkpoint can't be read back.
Plugin cards are not copied. A position from another epoch, or one that is gone, is refused;
forking the current context remains available.
includes projected items through that checkpoint. If an item the fork copies spans the checkpoint
and changed afterward, the daemon refuses that fork with an actionable error: discarded historical
payloads cannot be reconstructed from sequence metadata. Plugin cards are not copied, so a card
updated after the checkpoint does not block it. Forking the current context remains available.
## Resume behavior
@@ -15,7 +15,8 @@ import {
expectProviderInstalledInSettings,
findAcpCatalogProvider,
installAcpCatalogProvider,
openAddProviderArea,
openAddProvider,
openProviderDetail,
openSettingsHost,
openSettingsHostSection,
seedSavedSettingsHosts,
@@ -47,7 +48,7 @@ test.describe("ACP provider catalog", () => {
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openAddProviderArea(page);
await openAddProvider(page);
await installAcpCatalogProvider(page, ACP_PROVIDER.name);
await expectProviderInstalledInSettings(page, ACP_PROVIDER.name);
@@ -69,7 +70,7 @@ test("adds fx from the catalog with only a config entry", async ({ page }, testI
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openAddProviderArea(page);
await openAddProvider(page);
await findAcpCatalogProvider(page, "fx");
await page.screenshot({ path: testInfo.outputPath("fx-catalog.png") });
@@ -104,7 +105,7 @@ for (const theme of ["light", "dark"] as const) {
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
await openAddProviderArea(page);
await openAddProvider(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-catalog-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
@@ -127,7 +128,7 @@ for (const theme of ["light", "dark"] as const) {
testInfo.outputPath(`hoplite-removed-${theme}.json`),
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
);
await openAddProviderArea(page);
await openAddProvider(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-removed-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
@@ -140,11 +141,11 @@ for (const theme of ["light", "dark"] as const) {
}
async function removeHoplite(page: import("@playwright/test").Page): Promise<void> {
await page.getByTestId("provider-actions-hoplite").click();
await openProviderDetail(page, "Hoplite");
page.once("dialog", (dialog) => {
void dialog.accept();
});
await page.getByTestId("provider-remove-hoplite").click();
await page.getByTestId("provider-remove").click();
}
test("unsupported host asks for an update without writing Hoplite config", async ({
@@ -164,7 +165,7 @@ test("unsupported host asks for an update without writing Hoplite config", async
await openSettings(page);
await openSettingsHost(page, outdatedDaemon.serverId);
await openSettingsHostSection(page, outdatedDaemon.serverId, "providers");
await openAddProviderArea(page);
await openAddProvider(page);
await page.getByRole("button", { name: "Add Hoplite", exact: true }).click();
const errorToast = page.getByTestId("app-toast-message");
await expect(errorToast).toHaveText("Update the host to add Hoplite.");
@@ -5,7 +5,7 @@ import { seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { openAgentRoute } from "../support/helpers/mock-agent";
import { resetSeededPageState, openSessions } from "../support/helpers/archive-tab";
test("agent list age advances and command center says just now for a fresh workspace", async ({
test("agent list age advances and command center says just now for a fresh agent", async ({
page,
}) => {
const session = await seedMockAgentWorkspace({
@@ -23,10 +23,10 @@ test("agent list age advances and command center says just now for a fresh works
const commandCenter = await openCommandCenter(page);
await commandCenter.getByTestId("command-center-input").fill("Relative time agent");
const workspaceResult = commandCenter.getByTestId(
`command-center-workspace-${getServerId()}:${session.workspaceId}`,
const agentResult = commandCenter.getByTestId(
`command-center-agent-${getServerId()}:${session.agentId}`,
);
await expect(workspaceResult.getByTestId("command-center-result-timestamp")).toContainText(
await expect(agentResult.getByTestId("command-center-result-timestamp")).toContainText(
"just now",
);
await page.keyboard.press("Escape");
@@ -1,12 +1,5 @@
import { expect, test } from "../support/fixtures";
import { openSettings } from "../support/helpers/app";
import {
closeCommandCenter,
expectCommandCenterTab,
expectCommandCenterTabs,
openCommandCenter,
selectCommandCenterTab,
} from "../support/helpers/command-center";
import { openCommandCenter } from "../support/helpers/command-center";
import {
delayDirectorySuggestionResponses,
holdDirectorySuggestionResponses,
@@ -24,7 +17,6 @@ import {
} from "../support/helpers/command-center-scroll";
import { expectFileTabOpen } from "../support/helpers/file-explorer";
import { gotoWorkspace } from "../support/helpers/launcher";
import { getServerId } from "../support/helpers/server-id";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
const FILE_PATH =
@@ -75,7 +67,7 @@ test("workspace file search stays geometrically stable through delayed loading a
const panel = page.getByTestId("command-center-panel");
await expect(panel).toBeVisible({ timeout: 30_000 });
await expectCommandCenterTab(panel, "Files");
await expect(panel.getByRole("button", { name: "Files" })).toBeVisible();
await startCommandCenterLayoutObservation(page);
await panel.getByTestId("command-center-input").fill(FILE_NAME);
@@ -105,90 +97,26 @@ test("workspace file search stays geometrically stable through delayed loading a
}
});
test("command center tabs rotate with Tab and never move the header", async ({ page }) => {
test("dropping the files scope leaves the search row the same height", async ({ page }) => {
const seeded = await seedWorkspace({
repoPrefix: "command-center-tabs-",
title: "Tab rotation",
repoPrefix: "command-center-file-search-scope-",
title: "Scope chip height",
});
try {
await gotoWorkspace(page, seeded.workspaceId);
await page.keyboard.press("Meta+P");
const panel = page.getByTestId("command-center-panel");
await expect(panel).toBeVisible({ timeout: 30_000 });
const header = panel.getByTestId("command-center-header");
const input = panel.getByTestId("command-center-input");
const scoped = await header.boundingBox();
await test.step("⌘P opens on Files and Backspace on an empty field returns to All", async () => {
await page.keyboard.press("Meta+P");
await expect(panel).toBeVisible({ timeout: 30_000 });
await expectCommandCenterTab(panel, "Files");
await page.keyboard.press("Backspace");
await expectCommandCenterTab(panel, "All");
});
await page.getByTestId("command-center-files-scope").click();
await expect(page.getByTestId("command-center-files-scope")).toHaveCount(0);
const unscoped = await header.boundingBox();
const results = panel.getByTestId("command-center-results");
const headerOnAll = await header.boundingBox();
const resultsTopOnAll = (await results.boundingBox())?.y;
await test.step("Tab walks forward and wraps; Shift+Tab walks back", async () => {
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "Workspaces");
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "Files");
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "Actions");
expect(await header.boundingBox()).toEqual(headerOnAll);
expect((await results.boundingBox())?.y).toBe(resultsTopOnAll);
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "All");
await page.keyboard.press("Shift+Tab");
await expectCommandCenterTab(panel, "Actions");
await page.keyboard.press("Shift+Tab");
await expectCommandCenterTab(panel, "Files");
});
await test.step("rotating keeps the query", async () => {
await input.fill("tab rot");
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "Actions");
await expect(input).toHaveValue("tab rot");
});
await test.step("clicking a tab keeps typing in the search field", async () => {
await selectCommandCenterTab(panel, "Workspaces");
await page.keyboard.press("Backspace");
await expect(input).toHaveValue("tab ro");
await expect(
panel.getByTestId(`command-center-workspace-${getServerId()}:${seeded.workspaceId}`),
).toBeVisible();
});
await test.step("⌘K opens on All", async () => {
await page.keyboard.press("Escape");
await expect(panel).not.toBeVisible();
await page.keyboard.press("Meta+K");
await expectCommandCenterTab(panel, "All");
});
await test.step("in a workspace every tab is offered", async () => {
await expectCommandCenterTabs(panel, ["All", "Workspaces", "Files", "Actions"]);
});
await test.step("outside a workspace there is no Files tab, and Tab skips it", async () => {
const outside = { workspaceOpen: false };
await closeCommandCenter(page);
await openSettings(page);
await page.keyboard.press("Meta+K");
await expectCommandCenterTab(panel, "All", outside);
await expectCommandCenterTabs(panel, ["All", "Workspaces", "Actions"]);
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "Workspaces", outside);
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "Actions", outside);
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "All", outside);
await page.keyboard.press("Shift+Tab");
await expectCommandCenterTab(panel, "Actions", outside);
});
expect(scoped?.height).toBe(unscoped?.height);
} finally {
await seeded.cleanup();
}
@@ -7,8 +7,8 @@ import {
searchCommandCenter,
warmCommandCenterRows,
expectOnlyCommandCenterRowRendered,
expectCommandCenterWorkspaceWindow,
scrollToOldestCommandCenterWorkspace,
expectCommandCenterAgentWindow,
scrollToOldestCommandCenterAgent,
} from "../support/helpers/command-center-performance";
import { gotoAppShell } from "../support/helpers/app";
import {
@@ -19,7 +19,7 @@ import {
expectPrimaryCommandCenterActions,
expectTightTwoLineResultSpacing,
expectVisibleKeyboardNavigationNotToScroll,
expectRecentWorkspacesUntilSearch,
expectWorkspaceResultsToBeLimitedUntilSearch,
observeCommandCenterScroll,
openCommandCenterWithKeyboard,
} from "../support/helpers/command-center-scroll";
@@ -63,9 +63,9 @@ test("Command Center preserves manual scrolling through live updates and resumes
await expectCommandCenterToRemainAtTheTop(page);
await expectPrimaryCommandCenterActions(panel);
await expectVisibleKeyboardNavigationNotToScroll(page, panel);
// All leads with the most recent workspaces, so the last one seeded leads it.
// The empty query lists the most recent workspaces, so the last one seeded leads it.
await expectTightTwoLineResultSpacing(panel, "Command Center Scroll 08");
await expectRecentWorkspacesUntilSearch(panel);
await expectWorkspaceResultsToBeLimitedUntilSearch(panel);
const offset = await scrollCommandCenterAwayFromSelection(page, panel);
await seeded.client.setWorkspaceTitle(newestWorkspaceId, "Command Center Scroll renamed");
await expect(panel.getByText("Command Center Scroll renamed", { exact: true })).toHaveCount(1);
@@ -76,50 +76,42 @@ test("Command Center preserves manual scrolling through live updates and resumes
}
});
test("live search updates render only the changed row and keep workspaces virtualized", async ({
test("live search updates render only the changed row and keep agents virtualized", async ({
page,
}) => {
test.setTimeout(120_000);
const seeded = await seedSearchableCommandCenter();
const agentWorkspaceRowId = `workspace:${getServerId()}:${seeded.workspaceId}`;
try {
await observeCommandCenterRowRenders(page);
await gotoAppShell(page);
const panel = await openCommandCenterWithKeyboard(page);
await searchCommandCenter(panel, "Search agent");
await expect(panel.getByText("Search agent 059", { exact: true })).toBeVisible();
await warmCommandCenterRows(page);
await expectCommandCenterAgentWindow(panel, seeded.agents.length);
await test.step("renaming a matched agent re-renders only its workspace", async () => {
await searchCommandCenter(panel, "Search agent 002");
const agentLine = panel
.getByTestId(`command-center-workspace-${getServerId()}:${seeded.workspaceId}`)
.getByTestId("command-center-workspace-agent");
await expect(agentLine).toHaveText("Search agent 002");
await warmCommandCenterRows(page);
await seeded.client.updateAgent(seeded.agents[2].id, { name: "Search agent 002 revised" });
await expect(agentLine).toHaveText("Search agent 002 revised");
await expectOnlyCommandCenterRowRendered(page, agentWorkspaceRowId);
});
await seeded.client.updateAgent(seeded.agents[59].id, { name: "Search agent 059 revised" });
await expect(panel.getByText("Search agent 059 revised", { exact: true })).toBeVisible();
await expectOnlyCommandCenterRowRendered(
page,
`agent:${getServerId()}:${seeded.agents[59].id}`,
);
await test.step("renaming a workspace re-renders only its row", async () => {
await searchCommandCenter(panel, "Search workspace");
await expect(panel.getByText("Search workspace 039", { exact: true })).toBeVisible();
await warmCommandCenterRows(page);
await seeded.client.setWorkspaceTitle(
seeded.workspaces[39].id,
"Search workspace 039 revised",
);
await expect(panel.getByText("Search workspace 039 revised", { exact: true })).toBeVisible();
await expectOnlyCommandCenterRowRendered(
page,
`workspace:${getServerId()}:${seeded.workspaces[39].id}`,
);
});
await searchCommandCenter(panel, "Search workspace");
await expect(panel.getByText("Search workspace 039", { exact: true })).toBeVisible();
await warmCommandCenterRows(page);
await seeded.client.setWorkspaceTitle(seeded.workspaces[39].id, "Search workspace 039 revised");
await expect(panel.getByText("Search workspace 039 revised", { exact: true })).toBeVisible();
await expectOnlyCommandCenterRowRendered(
page,
`workspace:${getServerId()}:${seeded.workspaces[39].id}`,
);
await test.step("a long list mounts only a window of rows", async () => {
await expectCommandCenterWorkspaceWindow(panel, seeded.workspaces.length + 1);
await scrollToOldestCommandCenterWorkspace(panel);
await expect(panel.getByText("Search workspace 000", { exact: true })).toBeVisible();
await expectCommandCenterWorkspaceWindow(panel, seeded.workspaces.length + 1);
});
await searchCommandCenter(panel, "Search agent");
await warmCommandCenterRows(page);
await scrollToOldestCommandCenterAgent(panel);
await expect(panel.getByText("Search agent 000", { exact: true })).toBeVisible();
await expectCommandCenterAgentWindow(panel, seeded.agents.length);
} finally {
await seeded.cleanup();
}
@@ -4,12 +4,7 @@ import { test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { createIdleAgent } from "../support/helpers/archive-tab";
import { expectAgentTabActive } from "../support/helpers/launcher";
import {
commandCenterSection,
expectCommandCenterTab,
openCommandCenter,
selectCommandCenterTab,
} from "../support/helpers/command-center";
import { openCommandCenter } from "../support/helpers/command-center";
import { addOfflineHostAndReload } from "../support/helpers/hosts";
import { expectAppRoute } from "../support/helpers/route-assertions";
import { seedWorkspace } from "../support/helpers/seed-client";
@@ -26,7 +21,9 @@ const AGENT_TITLE = "Fix checkout retries";
test.describe("Command center workspaces", () => {
test.describe.configure({ timeout: 180_000 });
test("workspace results overlay live status", async ({ page }) => {
test("agent and workspace results retain their icons and overlay live status", async ({
page,
}) => {
const workspace = await seedRunningMockAgentWorkspace({
repoPrefix: "command-center-status-",
title: "Review checkout retries",
@@ -37,13 +34,15 @@ test.describe("Command center workspaces", () => {
await openAgentRoute(page, workspace);
await expectAgentTabActive(page, workspace.agentId);
const panel = await openCommandCenter(page);
// Recent workspaces leaves out the open one; the Workspaces tab lists every workspace.
await selectCommandCenterTab(panel, "Workspaces");
const agent = panel.getByTestId(`command-center-agent-${getServerId()}:${workspace.agentId}`);
const row = panel.getByTestId(
`command-center-workspace-${getServerId()}:${workspace.workspaceId}`,
);
await expect(agent.getByRole("progressbar", { name: "Agent running" })).toBeVisible();
await expect(row.getByRole("progressbar", { name: "Agent running" })).toBeVisible();
await expect(agent.getByRole("img", { name: "Mock agent" })).toBeVisible();
await workspace.client.cancelAgent(workspace.agentId);
await expect(agent.getByRole("progressbar")).toHaveCount(0);
await expect(row.getByRole("progressbar")).toHaveCount(0);
} finally {
await workspace.cleanup();
@@ -81,11 +80,9 @@ test.describe("Command center workspaces", () => {
});
const panel = await openCommandCenter(page);
await selectCommandCenterTab(panel, "Workspaces");
const row = panel.getByTestId(
`command-center-workspace-${getServerId()}:${seeded.workspaceId}`,
);
const agentLine = row.getByTestId("command-center-workspace-agent");
await expect(row).toBeVisible({ timeout: 30_000 });
await expect(row).toContainText(WORKSPACE_TITLE);
await expect(row).toContainText(WORKSPACE_BRANCH);
@@ -95,151 +92,65 @@ test.describe("Command center workspaces", () => {
await expect(subtitle).toContainText(PRIMARY_HOST_LABEL);
await expect(subtitle).toContainText(seeded.projectDisplayName);
await expect(subtitle).toContainText(WORKSPACE_BRANCH);
await expect(agentLine).toHaveCount(0);
await test.step("a workspace matches on its own fields", async () => {
const input = panel.getByTestId("command-center-input");
for (const query of [
PRIMARY_HOST_LABEL,
WORKSPACE_BRANCH,
WORKSPACE_TITLE,
seeded.projectDisplayName,
]) {
await input.fill(query);
await expect(row).toBeVisible();
await expect(agentLine).toHaveCount(0);
}
// `cwd` is never shown, so it must never match.
await input.fill(seeded.repoPath);
await expect(row).not.toBeVisible();
// The agent subtitle is unchanged by the shared-helper refactor.
const agentRow = panel.getByTestId(`command-center-agent-${getServerId()}:${agent.id}`);
await expect(agentRow).toContainText(AGENT_TITLE);
await expect(agentRow).toContainText(PRIMARY_HOST_LABEL);
await expect(agentRow).toContainText(WORKSPACE_TITLE);
await expect(agentRow).not.toContainText(seeded.repoPath);
const workspaceSectionTop = await panel
.getByText("Workspaces", { exact: true })
.evaluate((element) => element.getBoundingClientRect().top);
const agentSectionTop = await panel
.getByText("Agents", { exact: true })
.evaluate((element) => element.getBoundingClientRect().top);
expect(workspaceSectionTop).toBeLessThan(agentSectionTop);
const input = panel.getByTestId("command-center-input");
await input.fill(PRIMARY_HOST_LABEL);
await expect(row).toBeVisible();
await expect(agentRow).toBeVisible();
await input.fill(WORKSPACE_BRANCH);
await expect(row).toBeVisible();
await expect(agentRow).not.toBeVisible();
await input.fill(WORKSPACE_TITLE);
await expect(row).toBeVisible();
await expect(agentRow).toBeVisible();
await input.fill(seeded.repoPath);
await expect(agentRow).toBeVisible();
await expect(row).not.toBeVisible();
// The project name is now part of the workspace searchText.
await input.fill(seeded.projectDisplayName);
await expect(row).toBeVisible();
await input.fill(AGENT_TITLE);
await expect(agentRow).toBeVisible();
await expect(row).not.toBeVisible();
await input.fill(WORKSPACE_TITLE);
await page.keyboard.press("Enter");
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), seeded.workspaceId), {
timeout: 30_000,
});
await test.step("an agent title finds its workspace and names the agent", async () => {
await panel.getByTestId("command-center-input").fill(AGENT_TITLE);
await expect(agentLine).toHaveText(AGENT_TITLE);
await expect(panel.getByText("Agents", { exact: true })).toHaveCount(0);
await test.step("find an agent and open its workspace tab", async () => {
const agentPanel = await openCommandCenter(page);
await agentPanel.getByTestId("command-center-input").fill(AGENT_TITLE);
await page.keyboard.press("Enter");
await expectAgentTabActive(page, agent.id);
});
await test.step("a workspace match opens the workspace", async () => {
const searchAgain = await openCommandCenter(page);
await expectCommandCenterTab(searchAgain, "All");
await searchAgain.getByTestId("command-center-input").fill(WORKSPACE_TITLE);
await page.keyboard.press("Enter");
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), seeded.workspaceId), {
timeout: 30_000,
});
});
} finally {
await seeded.cleanup();
}
});
test("All leads with the three most recent workspaces other than the open one", async ({
page,
}) => {
const older = [];
for (const title of ["Recent oldest", "Recent third", "Recent second", "Recent newest"]) {
older.push(await seedWorkspace({ repoPrefix: "command-center-recent-", title }));
}
const current = await seedWorkspace({
repoPrefix: "command-center-recent-",
title: "Open one",
});
try {
await page.goto(buildHostWorkspaceRoute(getServerId(), current.workspaceId));
const panel = await openCommandCenter(page);
await expectCommandCenterTab(panel, "All");
await expect(commandCenterSection(panel, "Recent workspaces")).toBeVisible();
const rowOf = (workspaceId: string) =>
panel.getByTestId(`command-center-workspace-${getServerId()}:${workspaceId}`);
await expect(rowOf(older[3].workspaceId)).toBeVisible({ timeout: 30_000 });
await expect(rowOf(older[2].workspaceId)).toBeVisible();
await expect(rowOf(older[1].workspaceId)).toBeVisible();
await expect(rowOf(older[0].workspaceId)).toHaveCount(0);
await expect(rowOf(current.workspaceId)).toHaveCount(0);
await expect(commandCenterSection(panel, "Workspaces")).toHaveCount(0);
// The newest recent workspace is selected, so Enter goes straight back to it.
await page.keyboard.press("Enter");
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), older[3].workspaceId), {
timeout: 30_000,
});
} finally {
for (const seeded of [current, ...older]) await seeded.cleanup();
}
});
test("archived workspaces follow active matches and open where they can be unarchived", async ({
page,
}) => {
const active = await seedWorkspace({
repoPrefix: "command-center-archived-active-",
title: "Billing dashboard",
});
const archived = await seedWorkspace({
repoPrefix: "command-center-archived-",
title: "Billing cleanup",
});
try {
await createIdleAgent(archived.client, {
cwd: archived.repoPath,
workspaceId: archived.workspaceId,
title: "Audit invoice totals",
});
expect((await archived.client.archiveWorkspace(archived.workspaceId)).error).toBeNull();
await gotoAppShell(page);
const panel = await openCommandCenter(page);
const input = panel.getByTestId("command-center-input");
const activeRow = panel.getByTestId(
`command-center-workspace-${getServerId()}:${active.workspaceId}`,
);
const archivedRow = panel.getByTestId(
`command-center-workspace-${getServerId()}:${archived.workspaceId}`,
);
await test.step("an empty query never lists archived workspaces", async () => {
await selectCommandCenterTab(panel, "Workspaces");
await expect(activeRow).toBeVisible({ timeout: 30_000 });
await expect(archivedRow).toHaveCount(0);
});
await test.step("a query lists the archived workspace after the active one", async () => {
await input.fill("billing");
await expect(archivedRow).toBeVisible({ timeout: 30_000 });
await expect(archivedRow).toContainText("Archived");
await expect(activeRow).not.toContainText("Archived");
const activeTop = (await activeRow.boundingBox())?.y ?? Number.NaN;
const archivedTop = (await archivedRow.boundingBox())?.y ?? Number.NaN;
expect(archivedTop).toBeGreaterThan(activeTop);
});
await test.step("an agent title finds the archived workspace on All", async () => {
// Opened from the app shell, outside any workspace.
await selectCommandCenterTab(panel, "All", { workspaceOpen: false });
await input.fill("invoice totals");
await expect(archivedRow.getByTestId("command-center-workspace-agent")).toHaveText(
"Audit invoice totals",
{ timeout: 30_000 },
);
await expect(activeRow).toHaveCount(0);
});
await test.step("opening it lands where the workspace can be unarchived", async () => {
await page.keyboard.press("Enter");
await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expect(page.getByRole("button", { name: "Unarchive", exact: true })).toBeVisible();
});
} finally {
await active.cleanup();
await archived.cleanup();
}
});
test("single-host workspace subtitle omits the host and shows project · branch", async ({
page,
}) => {
@@ -318,7 +229,7 @@ test.describe("Compact sidebar inspection", () => {
title: "Compact destination",
});
try {
await createIdleAgent(seeded.client, {
const agent = await createIdleAgent(seeded.client, {
cwd: seeded.repoPath,
workspaceId: seeded.workspaceId,
title: "Compact root agent",
@@ -335,10 +246,7 @@ test.describe("Compact sidebar inspection", () => {
await openSidebar(page);
const agentSearch = await openCommandCenter(page);
await agentSearch.getByTestId("command-center-input").fill("Compact root agent");
await agentSearch
.getByTestId(`command-center-workspace-${getServerId()}:${seeded.workspaceId}`)
.getByTestId("command-center-workspace-agent")
.click();
await agentSearch.getByTestId(`command-center-agent-${getServerId()}:${agent.id}`).click();
await expect(page.getByRole("button", { name: "Open menu", exact: true })).toBeVisible();
await expect(
page.getByRole("textbox", { name: "Message agent...", exact: true }),
@@ -787,13 +787,9 @@ test.describe("Composer autocomplete", () => {
await input.press("ArrowDown");
await input.press("ArrowDown");
await input.press("h");
// On web the search reads the cursor after paint, so the input's value runs ahead of
// the list. Wait on the list itself: /tdd is hidden only while the search is "h", and
// back only once the search is "" again.
await expect(popover.getByText("/tdd", { exact: true })).toHaveCount(0);
await expect(popover.getByText("/help", { exact: true }).first()).toBeVisible();
await input.press("Backspace");
await expect(input).toHaveValue("/");
await expect(popover.getByText("/tdd", { exact: true }).first()).toBeVisible();
await input.press("Enter");
await expect(input).toHaveValue("/tdd ");
@@ -148,23 +148,6 @@ for (const scenario of [
});
}
test("retrying failed agent initialization keeps the plugin metadata set on New workspace", async ({
creation,
startup,
composerMetadata,
}) => {
await creation.openWorkspaceForm("local");
await composerMetadata.set({ "composer-metadata.tag": "kept" });
await creation.submitPrompt("Start the tagged task.", "Create");
await creation.expectAgentStillStarting();
await startup.fail();
await creation.expectStartupFailure();
await creation.expectOneCreatedWorkspace();
await creation.submitPrompt("Start the tagged task.");
await creation.expectAgentCount(1);
await creation.expectAgentMetadata({ "composer-metadata.tag": "kept" });
});
test("an edited agent draft starts after its first start failed", async ({
creation,
startup,
@@ -125,15 +125,12 @@ test.describe("Tab creation", () => {
}) => {
await gotoWorkspace(page, workspace.workspaceId);
await assertNewTabMenuTriggerVisible(page);
await pressNewTabShortcut(page);
const newTabs = page
.locator('[data-testid^="workspace-tab-tab_"]')
.filter({ hasText: "New tab" });
// The workspace opens on a New tab of its own; count from the tab the shortcut adds.
await expect(newTabs.first()).toBeVisible();
const openedCount = await newTabs.count();
await pressNewTabShortcut(page);
await expect(newTabs).toHaveCount(openedCount + 1);
const countBefore = openedCount + 1;
const countBefore = await newTabs.count();
const draftCount = await countTabsOfKind(page, "draft");
await test.step("opening the plus menu leaves the current tabs intact", async () => {
@@ -160,22 +160,6 @@ test.describe("New workspace entry points", () => {
}
});
test("Ctrl+N opens the project picker with search focused", async ({ page }) => {
const seeded: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-shortcut-" });
try {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openGlobalNewWorkspaceComposer(page);
await openGlobalNewWorkspaceComposer(page);
await page.goBack();
await openNewWorkspaceProjectPickerWithShortcut(page, "Control+N");
} finally {
await seeded.cleanup();
}
});
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
page,
}) => {
+54 -4
View File
@@ -6,6 +6,7 @@ import {
addProjectFromSetup,
continueSetup,
expectSetupStep,
expectSheetCoversSetupCard,
finishSetup,
goToSetupStep,
hostGivesAgentsPaseoTools,
@@ -23,6 +24,7 @@ import {
recordFirstLaunch,
setupModal,
setupPrimaryButton,
setupSheet,
showSetupAgainFromSettings,
skipSetup,
startSetupHost,
@@ -35,7 +37,11 @@ import {
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { enableRelayAndExpectOffer } from "../support/helpers/pair-device";
import { seedWorkspace } from "../support/helpers/seed-client";
import { openSettingsHostSection } from "../support/helpers/settings";
import {
installAcpCatalogProvider,
openAddProvider,
openSettingsHostSection,
} from "../support/helpers/settings";
import { createTempDirectory, createTempGitRepo } from "../support/helpers/workspace";
// Midnight's muted foreground (#9a9db0), which the step description is drawn in.
@@ -59,11 +65,28 @@ test("a new user is walked through setup once", async ({ page }, testInfo) => {
await test.step("Providers shows the same provider list as Settings", async () => {
await continueSetup(page);
await expectSetupStep(page, "Your agents");
await expectSetupStep(page, "Your providers");
await expect(setupModal(page).getByTestId("host-page-providers-card")).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("2-providers.png") });
});
await test.step("a provider's detail and Add provider cover the setup card and lead back to it", async () => {
await setupModal(page)
.getByRole("button", { name: "Claude provider details", exact: true })
.click();
const detail = setupSheet(page, "provider-settings-sheet");
await expectSheetCoversSetupCard(page, detail);
await detail.getByRole("button", { name: "Back to providers", exact: true }).click();
await expect(detail).toHaveCount(0);
await setupModal(page).getByTestId("provider-list-add").click();
const add = setupSheet(page, "add-provider-sheet");
await expectSheetCoversSetupCard(page, add);
await page.keyboard.press("Escape");
await expect(add).toHaveCount(0);
await expectSetupStep(page, "Your providers");
});
await test.step("with no agent history, Add project opens the regular flow and the folder shows as added", async () => {
await continueSetup(page);
await expectSetupStep(page, "Add your projects");
@@ -103,6 +126,33 @@ test("a new user is walked through setup once", async ({ page }, testInfo) => {
}
});
test("a provider removed in setup can be added back and removed again", async ({ page }) => {
test.setTimeout(180_000);
const host = await startSetupHost("re-add");
const detail = setupSheet(page, "provider-settings-sheet");
const remove = detail.getByTestId("provider-remove");
page.on("dialog", (dialog) => void dialog.accept());
try {
await openAppAsNewUser(page, host);
await continueSetup(page);
await expectSetupStep(page, "Your providers");
await openAddProvider(page);
await installAcpCatalogProvider(page, "Junie");
await remove.click();
await expect(detail).toHaveCount(0);
// Adding it back opens the same provider's sheet, which must not still be removing it.
await openAddProvider(page);
await installAcpCatalogProvider(page, "Junie");
await expect(remove).toHaveText("Remove");
await expect(remove).toBeEnabled();
} finally {
await host.close();
}
});
test("a new user goes from the loading screen straight into setup", async ({ page }) => {
const host = await startSetupHost("first-launch");
@@ -145,7 +195,7 @@ test("changing the theme keeps the setup window in place on every step", async (
for (const title of [
"Welcome to Paseo",
"Your agents",
"Your providers",
"Add your projects",
"Let agents use Paseo",
"Take your agents with you",
@@ -418,7 +468,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await openAppAsNewUser(page, host);
await step("Welcome to Paseo");
await primary("Continue").click();
await step("Your agents");
await step("Your providers");
await primary("Continue").click();
await step("Add your projects");
await primary("Continue").click();
@@ -1,21 +1,22 @@
import { ACP_PROVIDER_ICON_SVGS } from "../../src/assets/acp-provider-icons";
import { expect, test, type Page } from "../support/fixtures";
import type { TestInfo } from "@playwright/test";
import type { Locator, TestInfo } from "@playwright/test";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { getServerId } from "../support/helpers/server-id";
import {
findAcpCatalogProvider,
openAddProviderArea,
openAddProvider,
openSettingsHost,
openSettingsHostSection,
} from "../support/helpers/settings";
async function openProviderCatalog(page: Page) {
async function openProviderCatalog(page: Page, viewport?: { width: number; height: number }) {
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openAddProviderArea(page);
if (viewport) await page.setViewportSize(viewport);
await openAddProvider(page);
}
async function expectProviderArtwork(
@@ -25,11 +26,11 @@ async function expectProviderArtwork(
name: string,
) {
await findAcpCatalogProvider(page, name);
// Catalog tiles have no semantic role; scope artwork to the named provider's tile.
const icon = page.getByTestId(`provider-catalog-tile-${id}`).locator("svg").first();
// Catalog rows have no semantic role of their own; scope artwork to the named provider's row.
const icon = page.getByTestId(`provider-catalog-row-${id}`).locator("svg").first();
await expect(icon).toBeVisible();
// Provider artwork is 24px; the generic PackagePlus fallback is 20px.
await expect.soft(icon).toHaveAttribute("width", "24");
// Artwork draws at the provider list's icon size, so the catalog and the list share a rail.
await expect.soft(icon).toHaveAttribute("width", "16");
const expectedPaths = await page.evaluate((xml) => {
const document = new DOMParser().parseFromString(xml, "image/svg+xml");
return Array.from(document.querySelectorAll("path"), (path) => path.getAttribute("d")!);
@@ -49,3 +50,20 @@ test("#7087: the provider catalog shows Devin, Hermes, and Kiro artwork", async
await expectProviderArtwork(page, testInfo, "hermes", "Hermes");
await expectProviderArtwork(page, testInfo, "kiro", "Kiro CLI");
});
/** The space between a row's icon and its label, as drawn. */
async function gapAfterIcon(row: Locator, label: string): Promise<number> {
const icon = await row.locator("svg").first().boundingBox();
const text = await row.getByText(label, { exact: true }).boundingBox();
if (!icon || !text) throw new Error(`${label} has no icon or label on screen`);
return text.x - (icon.x + icon.width);
}
test("catalog rows keep the provider list's icon rail on a phone", async ({ page }) => {
await openProviderCatalog(page, { width: 390, height: 844 });
await findAcpCatalogProvider(page, "Kiro CLI");
const listGap = await gapAfterIcon(page.getByTestId("provider-row-claude"), "Claude");
const catalogGap = await gapAfterIcon(page.getByTestId("provider-catalog-row-kiro"), "Kiro CLI");
expect(catalogGap).toBe(listGap);
});
@@ -0,0 +1,54 @@
import { expect, test } from "../support/fixtures";
import { openCustomModels, removeCustomModel } from "../support/helpers/custom-models";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
// A pressed control shows its own progress while the daemon answers, the way Button's `loading`
// does: a spinner in place of its icon, no further presses and, on a labelled button, a
// present-participle label.
const MODEL_ID = "in-flight-model";
test.describe("provider page work in flight", () => {
test("says Adding... on the Add button while a custom model is saved", async ({ page }) => {
const gate = await installDaemonWebSocketGate(page);
await openCustomModels(page);
await page.getByRole("button", { name: "Add model", exact: true }).click();
const sheet = page.getByTestId("add-custom-model-sheet");
await page.getByPlaceholder("e.g. openai/gpt-5").fill(MODEL_ID);
gate.holdNextServerMessage("set_daemon_config_response");
await sheet.getByRole("button", { name: "Add", exact: true }).click();
await gate.waitForHeldServerMessage("set_daemon_config_response");
const adding = sheet.getByRole("button", { name: "Adding...", exact: true });
await expect(adding.getByRole("progressbar")).toBeVisible();
await expect(adding).toBeDisabled();
gate.releaseHeldServerMessage("set_daemon_config_response");
await expect(sheet).toBeHidden({ timeout: 30_000 });
await removeCustomModel(page, MODEL_ID);
});
test("shows the diagnostic report running again on its re-run button", async ({ page }) => {
const gate = await installDaemonWebSocketGate(page);
await openCustomModels(page);
await page.getByRole("button", { name: "Diagnostic report", exact: true }).click();
const sheet = page.getByTestId("provider-diagnostic-sheet");
const rerun = sheet.getByRole("button", { name: "Refresh diagnostic", exact: true });
await expect(rerun).toBeEnabled({ timeout: 30_000 });
// Copy has a report to copy once the first run is in.
await expect(sheet.getByRole("button", { name: "Copy diagnostic" })).toBeEnabled();
gate.holdNextServerMessage("provider_diagnostic_response");
await rerun.click();
await gate.waitForHeldServerMessage("provider_diagnostic_response");
const running = sheet.getByRole("button", { name: "Refreshing diagnostic", exact: true });
await expect(running.getByRole("progressbar")).toBeVisible();
await expect(running).toBeDisabled();
gate.releaseHeldServerMessage("provider_diagnostic_response");
await expect(rerun).toBeEnabled({ timeout: 30_000 });
});
});
@@ -2,11 +2,15 @@ import type { Dialog } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { getServerId } from "../support/helpers/server-id";
import {
expectProviderInstalledInSettings,
expectProviderNotOnHost,
installAcpCatalogProvider,
openAddProviderArea,
leaveProviderDetail,
openAddProvider,
openProviderDetail,
openSettingsHost,
openSettingsHostSection,
} from "../support/helpers/settings";
@@ -62,13 +66,39 @@ async function clickRemoveProviderAndAcceptWarning(page: Page): Promise<Dialog>
expect(dialog.message()).toContain("This deletes the provider entry from config.json.");
void dialog.accept();
});
await page.getByTestId(`provider-remove-${CUSTOM_PROVIDER.id}`).click();
await page.getByTestId("provider-remove").click();
if (!warning) {
throw new Error("Expected a provider removal confirmation dialog, but none was shown.");
}
return warning;
}
const MISSING_NOTICE = '[data-testid="provider-detail-missing"]';
/** Records whether the page ever says its provider isn't on the host, however briefly. */
async function watchForMissingNotice(page: Page): Promise<void> {
await page.evaluate((selector) => {
const flags = window as unknown as { sawMissingNotice?: boolean };
flags.sawMissingNotice = false;
new MutationObserver(() => {
if (document.querySelector(selector)) flags.sawMissingNotice = true;
}).observe(document.body, { childList: true, subtree: true });
}, MISSING_NOTICE);
}
async function expectMissingNoticeNeverShown(page: Page): Promise<void> {
const saw = await page.evaluate(
() => (window as unknown as { sawMissingNotice?: boolean }).sawMissingNotice,
);
expect(saw).toBe(false);
}
/**
* The daemon publishes the provider list without the removed provider before it answers the config
* patch. Holding the answer keeps the page in that window.
*/
const CONFIG_RESPONSE = "set_daemon_config_response";
test.describe("provider removal", () => {
test("removes a custom provider from Settings", async ({ page }) => {
test.setTimeout(120_000);
@@ -79,20 +109,39 @@ test.describe("provider removal", () => {
try {
await removeCustomProvider(client);
const gate = await installDaemonWebSocketGate(page);
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await expect(page.getByTestId("provider-actions-claude")).toHaveCount(0);
await openAddProviderArea(page);
// A built-in provider has no Danger zone.
await openProviderDetail(page, "Claude");
await expect(page.getByTestId("provider-remove")).toHaveCount(0);
await leaveProviderDetail(page);
await openAddProvider(page);
await installAcpCatalogProvider(page, CUSTOM_PROVIDER.name);
await expectProviderInstalledInSettings(page, CUSTOM_PROVIDER.name);
await expectProviderSource(client, "custom");
await page.getByTestId(`provider-actions-${CUSTOM_PROVIDER.id}`).click();
await expect(page.getByTestId(`provider-remove-${CUSTOM_PROVIDER.id}`)).toBeVisible();
await openProviderDetail(page, CUSTOM_PROVIDER.name);
await expect(page.getByTestId("provider-remove")).toBeVisible();
await watchForMissingNotice(page);
gate.holdNextServerMessage(CONFIG_RESPONSE);
await clickRemoveProviderAndAcceptWarning(page);
await gate.waitForHeldServerMessage(CONFIG_RESPONSE);
await expectProviderSource(client, undefined);
// Until the removal is answered, the page keeps the provider and the pressed button says so.
const removeButton = page.getByTestId("provider-remove");
await expect(removeButton).toHaveText("Removing...");
await expect(removeButton.getByRole("progressbar")).toBeVisible();
await expect(removeButton).toBeDisabled();
await expect(page.getByTestId("provider-detail-title")).toHaveText(CUSTOM_PROVIDER.name);
gate.releaseHeldServerMessage(CONFIG_RESPONSE);
// Removing leaves the provider's page for the list, without first calling it missing.
await expect(page.getByTestId("provider-list")).toBeVisible();
await expectMissingNoticeNeverShown(page);
await expect(
page.getByRole("button", {
@@ -100,7 +149,33 @@ test.describe("provider removal", () => {
exact: true,
}),
).toHaveCount(0);
await expectProviderSource(client, undefined);
} finally {
await removeCustomProvider(client).catch(() => undefined);
await client.close().catch(() => undefined);
}
});
test("says a provider removed elsewhere while its page is open isn't on this host", async ({
page,
}) => {
test.setTimeout(120_000);
const client = await connectDaemonClient<ProviderRemovalDaemonClient>({
clientIdPrefix: "provider-removal-e2e",
});
try {
await removeCustomProvider(client);
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openAddProvider(page);
await installAcpCatalogProvider(page, CUSTOM_PROVIDER.name);
await expectProviderInstalledInSettings(page, CUSTOM_PROVIDER.name);
await openProviderDetail(page, CUSTOM_PROVIDER.name);
await removeCustomProvider(client);
await expectProviderNotOnHost(page);
} finally {
await removeCustomProvider(client).catch(() => undefined);
await client.close().catch(() => undefined);
@@ -130,7 +205,9 @@ test.describe("provider removal", () => {
exact: true,
});
await expect(pluginProviderRow).toBeVisible();
await expect(page.getByTestId(`provider-actions-${PLUGIN_PROVIDER.id}`)).toHaveCount(0);
await openProviderDetail(page, PLUGIN_PROVIDER.name);
await expect(page.getByTestId("provider-remove")).toHaveCount(0);
await leaveProviderDetail(page);
// The provider survives a removeProviders patch pointed at it: the
// plugin, not config.json, owns the definition.
@@ -97,7 +97,7 @@ async function hasFocusWithin(locator: Locator): Promise<boolean> {
async function expectProviderSettingsVisible(page: Page) {
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
await expect(page.getByRole("button", { name: "Add model" })).toBeVisible();
await expect(page.getByRole("button", { name: "Diagnostic", exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Diagnostic report" })).toBeVisible();
}
async function exerciseProviderSettingsStack(page: Page) {
@@ -109,7 +109,7 @@ async function exerciseProviderSettingsStack(page: Page) {
await expect(page.getByPlaceholder("e.g. openai/gpt-5")).not.toBeVisible({ timeout: 10_000 });
await expectProviderSettingsVisible(page);
await page.getByRole("button", { name: "Diagnostic", exact: true }).click();
await page.getByRole("button", { name: "Diagnostic report" }).click();
await expect(page.getByTestId("provider-diagnostic-sheet")).toBeVisible({ timeout: 10_000 });
await page.getByRole("button", { name: /Refresh diagnostic/ }).click();
await expect(page.getByTestId("provider-diagnostic-sheet")).toBeVisible({ timeout: 10_000 });
@@ -118,7 +118,7 @@ async function exerciseProviderSettingsStack(page: Page) {
await page.getByRole("button", { name: "Refresh", exact: true }).click();
await expectProviderSettingsVisible(page);
await expect(page.getByText("Updated just now", { exact: true })).toBeVisible({
await expect(page.getByText("Checked just now", { exact: true })).toBeVisible({
timeout: 30_000,
});
}
@@ -15,6 +15,9 @@ import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon
import { getServerId } from "../support/helpers/server-id";
import {
expectSettingsHeader,
expectProviderNotOnHost,
expectProviderPageLoaded,
gotoProviderPage,
openSettingsHost,
openHostSection,
expectHostLabelDisplayed,
@@ -262,6 +265,20 @@ test.describe("Settings host page", () => {
});
});
test.describe("provider page from its URL", () => {
test("loads a provider's page on a cold visit", async ({ page }) => {
await gotoAppShell(page);
await gotoProviderPage(page, getServerId(), "claude");
await expectProviderPageLoaded(page, "Claude");
});
test("says a provider the host doesn't have isn't on this host", async ({ page }) => {
await gotoAppShell(page);
await gotoProviderPage(page, getServerId(), "not-a-provider");
await expectProviderNotOnHost(page);
});
});
test("restart recovery defaults off and persists opt-in and custom prompt", async ({ page }) => {
const serverId = getServerId();
await gotoAppShell(page);
+17 -123
View File
@@ -8,7 +8,6 @@ import { gotoAppShell, openSettings } from "../support/helpers/app";
import { addConnectedHostAndReload } from "../support/helpers/hosts";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import { openSettingsSection } from "../support/helpers/settings";
import { gate } from "../support/helpers/context-window";
import { getServerId } from "../support/helpers/server-id";
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
import {
@@ -34,12 +33,7 @@ import {
pinRow,
openUsageOptions,
closeUsageOptions,
pickUsageHost,
usageModalHost,
dragUsageCardAbove,
expectUsageCardOrder,
expectUsageOptionsFitContent,
setUsageCardOn,
showUsageAs,
refreshAllUsage,
togglePin,
@@ -99,6 +93,10 @@ async function qaScreenshot(page: Page, name: string, target: "page" | "summary"
await page.screenshot({ path: file });
}
function hostFilter(page: Page) {
return page.locator('[data-testid="usage-host-filter-trigger"]:visible');
}
function weeklyReport(sourceId: string, usedPct: number): UsageReportEntry {
return {
id: `${sourceId}:a`,
@@ -110,14 +108,6 @@ function weeklyReport(sourceId: string, usedPct: number): UsageReportEntry {
};
}
function accountReport(sourceId: string, account: string, usedPct: number): UsageReportEntry {
return {
...weeklyReport(sourceId, usedPct),
id: `${sourceId}:${account}`,
account: { label: account },
};
}
function installReversedUsageRefresh(page: Page) {
const initial = [weeklyReport("opencode", 31), weeklyReport("openai", 12)];
const refreshed = [weeklyReport("openai", 22), weeklyReport("opencode", 41)];
@@ -130,15 +120,15 @@ 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, ["12% Weekly", "31% Weekly"]);
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([
"openai plan",
"opencode plan",
"openai plan",
]);
await expectPinnedUsage(page, summary);
}
@@ -153,7 +143,7 @@ async function refreshUsageAndWaitForReports(page: Page, usage: UsageReportsFixt
}
test.describe("usage modal", () => {
test("opens from the sidebar on the host's reports, with no host named for one host", async ({
test("opens from the sidebar on the host's reports, with no host filter for one host", async ({
page,
}) => {
test.setTimeout(120_000);
@@ -193,7 +183,7 @@ test.describe("usage modal", () => {
const group = page.getByTestId(`usage-host-${serverId}`);
await expect(group.getByText("Alpha plan", { exact: true })).toBeVisible({ timeout: 10_000 });
await expect(page.getByTestId("usage-modal-host")).toHaveCount(0);
await expect(hostFilter(page)).toHaveCount(0);
await qaScreenshot(page, "usage-modal-one-host");
await expect(group.getByText("31% used")).toBeVisible();
await expect(group.getByText("Beta plan", { exact: true })).toBeVisible();
@@ -210,61 +200,15 @@ test.describe("usage modal", () => {
}) => {
const usage = await installReversedUsageRefresh(page);
await openUsageSummaryAtWidth(page, width);
// Reports arrive opencode first; cards and the summary stay alphabetical.
await expectUsageProviderOrder(page, ["12% Weekly", "31% Weekly"]);
await expectUsageProviderOrder(page, ["31% Weekly", "12% Weekly"]);
await qaScreenshot(page, `usage-order-${width}-before-refresh`);
await refreshUsageAndWaitForReports(page, usage);
await expectUsageProviderOrder(page, ["22% Weekly", "41% Weekly"]);
await expectUsageProviderOrder(page, ["41% Weekly", "22% Weekly"]);
await qaScreenshot(page, `usage-order-${width}-after-refresh`);
});
}
test("keeps a card turned off and a dragged order after a reload", async ({ page }) => {
test.setTimeout(120_000);
await installUsageReportsFixture(page, {
lists: [
[
accountReport("beta", "work", 12),
weeklyReport("alpha", 31),
accountReport("beta", "home", 20),
],
],
});
await gotoAppShell(page);
// Three windows leave no room for labels in the summary, so it reads percents.
await expectPinnedUsage(page, ["31%", "20%", "12%"]);
await openUsageFromItem(page);
await expectUsageCardOrder(page, ["alpha:a", "beta:home", "beta:work"]);
// Without the pointer over the card, keyboard focus on its handle shows the handle.
await page.mouse.move(0, 0);
const alphaHandle = page
.getByTestId("usage-report-alpha:a")
.getByRole("button", { name: "Reorder alpha plan", exact: true });
await expect(alphaHandle).toHaveCSS("opacity", "0");
await alphaHandle.focus();
await expect(alphaHandle).toHaveCSS("opacity", "1");
await alphaHandle.blur();
// The off card collapses to its header, which still names the account.
await setUsageCardOn(page, "beta plan (work)", false);
const work = page.getByTestId("usage-report-beta:work");
await expect(work.getByText("12% used")).toHaveCount(0);
await expect(work.getByText("work", { exact: true })).toBeVisible();
await expectPinnedUsage(page, ["31% Weekly", "20% Weekly"]);
await dragUsageCardAbove(page, "beta:home", "alpha:a");
await expectUsageCardOrder(page, ["beta:home", "alpha:a", "beta:work"]);
await expectPinnedUsage(page, ["20% Weekly", "31% Weekly"]);
await page.reload();
await expectPinnedUsage(page, ["20% Weekly", "31% Weekly"]);
await openUsageFromItem(page);
await expectUsageCardOrder(page, ["beta:home", "alpha:a", "beta:work"]);
await expect(page.getByTestId("usage-report-beta:work").getByText("12% used")).toHaveCount(0);
});
test("refreshes one report from its card", async ({ page }) => {
test.setTimeout(120_000);
const serverId = getServerId();
@@ -376,11 +320,9 @@ test.describe("usage modal", () => {
);
try {
await installUsageReportsFixture(page, { lists: [[weeklyReport("alpha", 31)]] });
// The second host's reports wait until the test lets them through, like a slow host.
const secondaryReports = gate();
await installUsageReportsFixture(page, {
port: secondary.port,
lists: [{ stream: [secondaryReports.promise, weeklyReport("beta", 12)] }],
lists: [[weeklyReport("beta", 12)]],
});
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
@@ -394,15 +336,12 @@ test.describe("usage modal", () => {
await openUsageFromItem(page);
await expect(page.getByTestId(`usage-host-${primaryServerId}`)).toBeVisible();
await expect(usageModalHost(page)).toHaveText("localhost");
await pickUsageHost(page, secondary.serverId);
// Until its reports arrive, the picked host loads; it never shows the first host's cards.
const secondaryBody = page.getByTestId(`usage-host-${secondary.serverId}`);
await expect(secondaryBody.getByText("Loading usage...")).toBeVisible();
await expect(page.getByTestId("usage-modal-body").getByText("31% used")).toHaveCount(0);
await expect(usageModalHost(page)).toHaveText("Secondary box");
secondaryReports.open();
await expect(secondaryBody.getByText("12% used")).toBeVisible({ timeout: 30_000 });
await hostFilter(page).click();
await page.getByTestId(`usage-host-filter-item-${secondary.serverId}`).click();
await expect(
page.getByTestId(`usage-host-${secondary.serverId}`).getByText("12% used"),
).toBeVisible({ timeout: 30_000 });
await expect(hostFilter(page)).toContainText("Secondary box");
await qaScreenshot(page, "usage-modal-picked-host");
await expectPinnedUsage(page, ["12% Weekly"]);
@@ -421,51 +360,6 @@ test.describe("usage modal", () => {
await secondary.close().catch(() => undefined);
}
});
test("on a phone, picking a host in Settings keeps Usage open on that host", async ({ page }) => {
test.setTimeout(420_000);
const longName = "build-box-eu-west-gpu-runner-02.internal";
const secondary = await startIsolatedHostDaemon(
`srv_usage_${randomUUID().replaceAll("-", "").slice(0, 12)}`,
);
try {
await installUsageReportsFixture(page, { lists: [[weeklyReport("alpha", 31)]] });
await installUsageReportsFixture(page, {
port: secondary.port,
lists: [[weeklyReport("beta", 12)]],
});
await page.setViewportSize({ width: 375, height: 812 });
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
serverId: secondary.serverId,
label: longName,
port: secondary.port,
});
await openCompactSidebar(page);
await openUsageFromItem(page);
await pickUsageHost(page, secondary.serverId);
// The sheet stays up once Settings has closed over it, showing the picked host's cards.
await expect(
page.getByTestId(`usage-host-${secondary.serverId}`).getByText("12% used"),
).toBeVisible({ timeout: 30_000 });
await expect(usageModalHost(page)).toHaveText(longName);
// The long name truncates under the title; the title itself reads in full.
const title = page.locator('[data-testid="usage-modal-title"]:visible');
await expect(title).toHaveText("Usage");
expect(await title.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(
true,
);
const host = usageModalHost(page);
expect(await host.evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(
true,
);
await qaScreenshot(page, "usage-phone-picked-long-host");
} finally {
await secondary.close().catch(() => undefined);
}
});
});
const loginWindows: UsageReportEntry["report"] = {
@@ -318,11 +318,10 @@ test.describe("Usage item", () => {
await test.step("pinning Claude 5-hour and Codex weekly shows both in the Usage item", async () => {
await expect(screen.getByText("Claude", { exact: true })).toBeVisible({ timeout: 10_000 });
// One host: Settings has no Host row, and the title no host under it.
await expect(page.getByTestId("usage-modal-host")).toHaveCount(0);
await openUsageOptions(page);
await expect(page.getByTestId("usage-options-host")).toHaveCount(0);
await closeUsageOptions(page);
// One host: no host filter, as on History.
await expect(page.locator('[data-testid="usage-host-filter-trigger"]:visible')).toHaveCount(
0,
);
await togglePin(screen, "Claude", "Weekly");
await expectPinnedUsage(page, ["31% 5h", "7% 5h", "12% wk"]);
await expect(pinRow(screen, "Claude", "Session")).toBeChecked();
@@ -14,7 +14,6 @@ import { connectSeedClient } from "../support/helpers/seed-client";
import { createTempGitRepo } from "../support/helpers/workspace";
import { getWorkspaceTabTestIds } from "../support/helpers/workspace-tabs";
import {
archivedToast,
archiveFromRowButton,
createGatedTeardown,
expectDirectoryPresence,
@@ -26,7 +25,6 @@ import {
resizeSidebarToMinimum,
rowArchiveButton,
rowKebab,
scrollSidebarListToEnd,
undoButton,
workspaceRow,
workspaceTitleWidth,
@@ -121,41 +119,6 @@ test.describe("Workspace archive undo", () => {
expect(shortcutBox.x - (labelBox.x + labelBox.width)).toBeLessThanOrEqual(8.5);
});
test("a long list ends just below its last row, and the toast over it moves no row", async ({
page,
}) => {
await page.clock.install({ time: Date.now() });
const fillers: Array<{ path: string; cleanup: () => Promise<void> }> = [];
const fillerProjectIds: string[] = [];
try {
for (let index = 0; index < 10; index += 1) {
const repo = await createTempGitRepo(`archive-toast-filler-${index}-`);
fillers.push(repo);
fillerProjectIds.push((await openProjectViaDaemon(client, repo.path)).projectId);
}
const worktree = await seedWorktree(page, "archive-toast-long-list");
const resting = await scrollSidebarListToEnd(page);
expect(resting.listBottom - resting.rowBottoms.at(-1)!).toBeLessThan(resting.rowHeight);
await archiveFromRowButton(page, worktree.workspaceId);
await page.mouse.move(0, 0);
const withToast = await scrollSidebarListToEnd(page);
const toastBox = await archivedToast(page).boundingBox();
if (!toastBox) throw new Error("Toast is not laid out");
expect(toastBox.y + toastBox.height).toBeLessThanOrEqual(withToast.listBottom);
await outlastUndoWindow(page);
await expect(archivedToast(page)).toHaveCount(0);
expect(await scrollSidebarListToEnd(page)).toEqual(withToast);
} finally {
for (const projectId of fillerProjectIds) {
await client.removeProject(projectId).catch(() => undefined);
}
for (const repo of fillers) await repo.cleanup().catch(() => undefined);
}
});
test("an archive that fails after the sidebar was replaced still shows its error", async ({
page,
}) => {
@@ -5,34 +5,27 @@ import path from "node:path";
import type { Dialog, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { daemonWsRoutePattern } from "../support/helpers/daemon-port";
import {
archiveWorkspaceFromDaemon,
connectNewWorkspaceDaemonClient,
createWorktreeViaDaemon,
openProjectViaDaemon,
} from "../support/helpers/new-workspace";
import { expectAppRoute } from "../support/helpers/route-assertions";
import { getServerId } from "../support/helpers/server-id";
import {
clickArchiveWorkspaceMenuItem,
expectWorkspaceAbsentFromSidebar,
} from "../support/helpers/sidebar";
import { createTempGitRepo } from "../support/helpers/workspace";
import {
rowArchiveButton,
undoButton,
workspaceRow,
} from "../support/helpers/workspace-archive-undo";
import {
waitForSidebarHydration,
waitForWorkspaceInSidebar,
} from "../support/helpers/workspace-ui";
import { buildHostWorkspaceRoute } from "@/utils/host-routes";
type DaemonClient = Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
async function seedRiskyWorktree(client: DaemonClient, worktreeDirectory: string): Promise<void> {
async function seedRiskyWorktree(
client: Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>,
worktreeDirectory: string,
): Promise<void> {
// The daemon only reports unpushed commits when the branch has a configured
// upstream (aheadOfOrigin is computed against `branch.<name>.merge`). Push the
// worktree branch at its current head first so it tracks origin with 0 ahead,
@@ -62,189 +55,35 @@ async function seedRiskyWorktree(client: DaemonClient, worktreeDirectory: string
const dirtyFile = path.join(worktreeDirectory, "DIRTY.md");
await writeFile(dirtyFile, "# dirty\n");
await refreshCheckout(client, worktreeDirectory);
}
async function refreshCheckout(client: DaemonClient, directory: string): Promise<void> {
const refreshed = await client.checkoutRefresh(directory);
const refreshed = await client.checkoutRefresh(worktreeDirectory);
if (!refreshed.success) {
throw new Error(`Failed to refresh checkout for ${directory}`);
throw new Error(`Failed to refresh checkout for ${worktreeDirectory}`);
}
}
// The archive confirmation is a synchronous web `window.confirm()` that opens once the app has
// read the worktree's git state from the host. Wait for the dialog itself: on web the click does
// not resolve until it is answered, so answer it from the event.
async function answerArchiveWarning(
// The archive confirmation is a synchronous web `window.confirm()`. The click that
// opens it does not resolve until the dialog is answered, so the handler must
// accept/dismiss inline — awaiting the dialog only *after* the click deadlocks, as
// the click waits for an answer that is gated behind that same click.
async function clickArchiveAndAnswerWarning(
page: Page,
workspaceId: string,
answer: "accept" | "dismiss",
openArchive: () => Promise<void>,
): Promise<Dialog> {
const warning = page.waitForEvent("dialog", { timeout: 10_000 }).then(async (dialog) => {
await (answer === "accept" ? dialog.accept() : dialog.dismiss());
return dialog;
let warning: Dialog | undefined;
page.once("dialog", (dialog) => {
warning = dialog;
void (answer === "accept" ? dialog.accept() : dialog.dismiss());
});
await openArchive();
return await warning;
}
// A clean Paseo worktree's primary git action in the workspace header is Archive.
function gitActionsArchiveButton(page: Page) {
return page.getByTestId("changes-primary-cta").and(page.getByLabel("Archive workspace"));
}
async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<void> {
await workspaceRow(page, workspaceId).hover();
await rowArchiveButton(page, workspaceId).click();
}
interface SessionEnvelope {
type?: unknown;
message?: {
type?: unknown;
workspaceId?: unknown;
cwd?: unknown;
payload?: Record<string, unknown>;
};
}
function parseSessionEnvelope(message: string): SessionEnvelope | null {
try {
return JSON.parse(message) as SessionEnvelope;
} catch {
return null;
await clickArchiveWorkspaceMenuItem(page, workspaceId);
if (!warning) {
throw new Error("Expected an archive confirmation dialog, but none was shown.");
}
}
function removeGitStatusFromDescriptors(value: unknown, workspaceId: string): number {
if (Array.isArray(value)) {
return value.reduce<number>(
(count, item) => count + removeGitStatusFromDescriptors(item, workspaceId),
0,
);
}
if (!value || typeof value !== "object") return 0;
const record = value as Record<string, unknown>;
let count = 0;
if (record.id === workspaceId && "workspaceDirectory" in record) {
delete record.gitRuntime;
record.diffStat = null;
count += 1;
}
for (const child of Object.values(record)) {
count += removeGitStatusFromDescriptors(child, workspaceId);
}
return count;
}
/**
* Relays the app's connection to the daemon. Every workspace descriptor for `workspaceId` reaches
* the app without git status, as the host sends it before its first checkout snapshot of the
* worktree, so the sidebar row has nothing cached to warn from. `failCheckoutStatusFor` turns the
* host's checkout status answer for that directory into a git error.
*/
async function relayDaemon(
page: Page,
input: { workspaceId: string; failCheckoutStatusFor?: string },
) {
let descriptorRewrites = 0;
let archiveRequests = 0;
await page.routeWebSocket(daemonWsRoutePattern(), (browser) => {
const server = browser.connectToServer();
browser.onMessage((message) => {
if (typeof message === "string") {
const request = parseSessionEnvelope(message)?.message;
if (
request?.type === "archive_workspace_request" &&
request.workspaceId === input.workspaceId
) {
archiveRequests += 1;
}
}
server.send(message);
});
server.onMessage((message) => {
if (typeof message !== "string") {
browser.send(message);
return;
}
const envelope = parseSessionEnvelope(message);
const response = envelope?.message;
if (
input.failCheckoutStatusFor &&
response?.type === "checkout_status_response" &&
response.payload?.cwd === input.failCheckoutStatusFor
) {
response.payload = {
...response.payload,
isGit: false,
isPaseoOwnedWorktree: false,
repoRoot: null,
currentBranch: null,
isDirty: null,
baseRef: null,
aheadBehind: null,
aheadOfOrigin: null,
behindOfOrigin: null,
hasRemote: false,
remoteUrl: null,
error: { code: "UNKNOWN", message: "git status failed" },
};
browser.send(JSON.stringify(envelope));
return;
}
if (!envelope || !message.includes(input.workspaceId)) {
browser.send(message);
return;
}
descriptorRewrites += removeGitStatusFromDescriptors(envelope, input.workspaceId);
browser.send(JSON.stringify(envelope));
});
});
return {
descriptorRewrites: () => descriptorRewrites,
archiveRequests: () => archiveRequests,
};
}
/**
* Holds the app's next checkout status request for `directory` once armed, so a test can act
* while the archive waits for the host's answer.
*/
async function holdCheckoutStatusRequest(page: Page, directory: string) {
let armed = false;
let held: (() => void) | null = null;
await page.routeWebSocket(daemonWsRoutePattern(), (browser) => {
const server = browser.connectToServer();
browser.onMessage((message) => {
const request = typeof message === "string" ? parseSessionEnvelope(message)?.message : null;
if (
armed &&
!held &&
request?.type === "checkout_status_request" &&
request.cwd === directory
) {
held = () => server.send(message);
return;
}
server.send(message);
});
server.onMessage((message) => browser.send(message));
});
return {
arm: () => {
armed = true;
},
waitForHeld: () => expect.poll(() => held !== null).toBe(true),
release: () => {
if (!held) throw new Error("No checkout status request is held");
held();
},
};
return warning;
}
test.describe("Workspace archive risk warning for worktree backing", () => {
let client: DaemonClient;
let client: Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
let tempRepo: { path: string; cleanup: () => Promise<void> };
const createdWorktreeDirectories = new Set<string>();
@@ -264,53 +103,36 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
await tempRepo?.cleanup().catch(() => undefined);
});
async function createWorktree(slug: string) {
const project = await openProjectViaDaemon(client, tempRepo.path);
const worktree = await createWorktreeViaDaemon(client, {
cwd: tempRepo.path,
slug: `${slug}-${Date.now()}`,
});
createdWorktreeDirectories.add(worktree.workspaceDirectory);
expect(existsSync(worktree.workspaceDirectory)).toBe(true);
return { ...worktree, project };
}
async function openSidebarRow(page: Page, workspaceId: string): Promise<void> {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await waitForWorkspaceInSidebar(page, { serverId: getServerId(), workspaceId });
}
async function expectWorktreeKept(page: Page, worktree: { workspaceId: string }) {
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible({ timeout: 10_000 });
}
async function hostListsWorkspace(workspaceId: string): Promise<boolean> {
const { entries } = await client.fetchWorkspaces();
return entries.some((entry) => entry.id === workspaceId);
}
test("a risky workspace archive is gated by confirmation and removes its worktree after acceptance", async ({
page,
}) => {
const worktree = await createWorktree("archive-risk");
await seedRiskyWorktree(client, worktree.workspaceDirectory);
await openSidebarRow(page, worktree.workspaceId);
const serverId = getServerId();
await openProjectViaDaemon(client, tempRepo.path);
const worktree = await createWorktreeViaDaemon(client, {
cwd: tempRepo.path,
slug: `archive-risk-${Date.now()}`,
});
createdWorktreeDirectories.add(worktree.workspaceDirectory);
expect(existsSync(worktree.workspaceDirectory)).toBe(true);
const firstWarning = await answerArchiveWarning(page, "dismiss", () =>
clickArchiveWorkspaceMenuItem(page, worktree.workspaceId),
);
await seedRiskyWorktree(client, worktree.workspaceDirectory);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await waitForWorkspaceInSidebar(page, { serverId, workspaceId: worktree.workspaceId });
const firstWarning = await clickArchiveAndAnswerWarning(page, worktree.workspaceId, "dismiss");
expect(firstWarning.type()).toBe("confirm");
expect(firstWarning.message()).toContain(`Archive "${worktree.workspaceName}"?`);
expect(firstWarning.message()).toContain("Uncommitted changes");
expect(firstWarning.message()).toContain("1 unpushed commit");
await expectWorktreeKept(page, worktree);
await expect(
page.getByTestId(`sidebar-workspace-row-${serverId}:${worktree.workspaceId}`),
).toBeVisible({ timeout: 10_000 });
expect(existsSync(worktree.workspaceDirectory)).toBe(true);
const secondWarning = await answerArchiveWarning(page, "accept", () =>
clickArchiveWorkspaceMenuItem(page, worktree.workspaceId),
);
const secondWarning = await clickArchiveAndAnswerWarning(page, worktree.workspaceId, "accept");
expect(secondWarning.message()).toContain("Uncommitted changes");
expect(secondWarning.message()).toContain("1 unpushed commit");
@@ -321,128 +143,4 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
createdWorktreeDirectories.delete(worktree.workspaceDirectory);
});
test("the row's archive button warns from the host's git state while the row has none, and Cancel keeps the worktree", async ({
page,
}) => {
const worktree = await createWorktree("archive-risk-uncached");
await seedRiskyWorktree(client, worktree.workspaceDirectory);
const relay = await relayDaemon(page, { workspaceId: worktree.workspaceId });
await openSidebarRow(page, worktree.workspaceId);
expect(relay.descriptorRewrites()).toBeGreaterThan(0);
const warning = await answerArchiveWarning(page, "dismiss", () =>
clickRowArchiveButton(page, worktree.workspaceId),
);
expect(warning.message()).toContain(`Archive "${worktree.workspaceName}"?`);
expect(warning.message()).toContain("Uncommitted changes");
expect(warning.message()).toContain("1 unpushed commit");
await expectWorktreeKept(page, worktree);
expect(relay.archiveRequests()).toBe(0);
expect(existsSync(path.join(worktree.workspaceDirectory, "DIRTY.md"))).toBe(true);
});
test("a worktree holding only new files warns when the repository hides untracked files", async ({
page,
}) => {
execSync("git config status.showUntrackedFiles no", { cwd: tempRepo.path, stdio: "ignore" });
const worktree = await createWorktree("archive-risk-untracked");
await writeFile(path.join(worktree.workspaceDirectory, "NEW.md"), "# not yet added\n");
await refreshCheckout(client, worktree.workspaceDirectory);
await openSidebarRow(page, worktree.workspaceId);
const warning = await answerArchiveWarning(page, "dismiss", () =>
clickRowArchiveButton(page, worktree.workspaceId),
);
expect(warning.message()).toContain(`Archive "${worktree.workspaceName}"?`);
expect(warning.message()).toContain("Uncommitted changes");
await expectWorktreeKept(page, worktree);
expect(existsSync(path.join(worktree.workspaceDirectory, "NEW.md"))).toBe(true);
});
test("a failed git read shows its error and keeps the worktree", async ({ page }) => {
const worktree = await createWorktree("archive-risk-read-failure");
await seedRiskyWorktree(client, worktree.workspaceDirectory);
const relay = await relayDaemon(page, {
workspaceId: worktree.workspaceId,
failCheckoutStatusFor: worktree.workspaceDirectory,
});
await openSidebarRow(page, worktree.workspaceId);
await clickRowArchiveButton(page, worktree.workspaceId);
await expect(page.getByTestId("app-toast-message")).toHaveText("git status failed");
await expectWorktreeKept(page, worktree);
expect(relay.archiveRequests()).toBe(0);
expect(existsSync(worktree.workspaceDirectory)).toBe(true);
});
// Archives the open worktree with `startArchive`, opens the project's main workspace while the
// host's checkout status answer is held, then lets the answer through.
async function archiveWhileOpeningAnotherWorkspace(
page: Page,
slug: string,
startArchive: (worktree: { workspaceId: string }) => Promise<void>,
): Promise<string> {
const serverId = getServerId();
const worktree = await createWorktree(slug);
const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory);
await openSidebarRow(page, worktree.workspaceId);
await workspaceRow(page, worktree.workspaceId).click();
await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId));
statusRequest.arm();
await startArchive(worktree);
await statusRequest.waitForHeld();
await workspaceRow(page, worktree.project.workspaceId).click();
const openedRoute = buildHostWorkspaceRoute(serverId, worktree.project.workspaceId);
await expectAppRoute(page, openedRoute);
statusRequest.release();
await expect(undoButton(page)).toBeVisible();
// The redirect runs before the archive request, so once the host has archived the worktree
// any redirect has already happened.
await expect
.poll(() => hostListsWorkspace(worktree.workspaceId), { timeout: 30_000 })
.toBe(false);
return openedRoute;
}
test("opening another workspace while the host answers keeps it open after a row archive", async ({
page,
}) => {
const openedRoute = await archiveWhileOpeningAnotherWorkspace(
page,
"archive-risk-switch-row",
(worktree) => clickRowArchiveButton(page, worktree.workspaceId),
);
await expectAppRoute(page, openedRoute);
});
test("opening another workspace while the host answers keeps it open after a git actions archive", async ({
page,
}) => {
const openedRoute = await archiveWhileOpeningAnotherWorkspace(
page,
"archive-risk-switch-git",
() => gitActionsArchiveButton(page).click(),
);
await expectAppRoute(page, openedRoute);
});
test("archiving the open worktree from its git actions leaves it for a new workspace", async ({
page,
}) => {
const worktree = await createWorktree("archive-risk-git-redirect");
await openSidebarRow(page, worktree.workspaceId);
await workspaceRow(page, worktree.workspaceId).click();
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), worktree.workspaceId));
await gitActionsArchiveButton(page).click();
await expect.poll(() => new URL(page.url()).pathname).toBe("/new");
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
});
});
@@ -1,27 +0,0 @@
# Android Usage drop regressions
Use a device you own and fixed reports from an isolated daemon. Keep recordings in `.artifacts/`. Do not upload recordings containing account details.
## Same-slot drop
Open Usage with two cards that fit without scrolling. Run:
```sh
ANDROID_SERIAL=emulator-5580 node packages/app/e2e/mobile/usage-drag/android.mjs
```
Set `PASEO_DEVICE_SESSION` to reuse your Agent Device session. The test holds the first handle, moves within its slot, drops it, then swipes the sheet body. It asserts sheet movement while the finger is still down: after release, the sheet can snap back to its starting position.
## Old-order frame
Record a drop with Android `screenrecord`. Include the original order, the held arrangement, the release, and at least five seconds after release. Take a reference screenshot before recording. Use fixed labels that stay visible throughout the drop.
Create a JSON map of label names to screenshot rectangles `[x, y, width, height]`, in physical pixels. Crop each label tightly, without changing text or the pointer. Install `opencv-python-headless` in a local virtual environment under `.artifacts/`, then run:
```sh
.artifacts/frames-venv/bin/python packages/app/e2e/mobile/usage-drag/frames.py \
--reference .artifacts/before.png --labels .artifacts/labels.json \
.artifacts/drop-up.mp4 .artifacts/drop-down.mp4
```
The check requires recognized labels in the first and last frames and a changed final order. After every label first reaches its final slot, it fails on any frame showing all original slots again. It prints the offending frame numbers for each recording. This exercises the Android compositor; a JavaScript render test cannot establish which intermediate commit reached the screen.
@@ -1,71 +0,0 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { setTimeout } from "node:timers/promises";
// Open Usage with a fixture whose cards fit without scrolling before running.
// A same-slot drop must release the list's recognizer so a body swipe moves the sheet.
const serial = process.env.ANDROID_SERIAL;
assert.ok(serial, "Set ANDROID_SERIAL to the device owned by this test");
const session = process.env.PASEO_DEVICE_SESSION ?? "usage-drag-regression";
const artifacts = resolve(".artifacts/usage-drag-regression");
mkdirSync(artifacts, { recursive: true });
function ad(...args) {
return execFileSync(
"agent-device",
[...args, "--platform", "android", "--serial", serial, "--session", session],
{ encoding: "utf8", timeout: 30_000 },
);
}
function adb(...args) {
return execFileSync("adb", ["-s", serial, ...args], { timeout: 30_000 });
}
function snapshot() {
return JSON.parse(ad("snapshot", "--json")).data.nodes;
}
function touch(kind, x, y) {
adb("shell", "input", "motionevent", kind, String(Math.round(x)), String(Math.round(y)));
}
try {
ad("open", process.env.PASEO_MOBILE_APP_ID ?? "sh.paseo.debug");
const nodes = snapshot();
writeFileSync(resolve(artifacts, "before.json"), JSON.stringify(nodes));
const handle = nodes.find((node) => node.identifier === "usage-card-drag-handle");
const list = nodes.find((node) => node.identifier === "usage-list");
assert.ok(handle?.rect && list?.rect, "Open Usage with a visible card handle");
const x = handle.rect.x + handle.rect.width / 2;
const y = handle.rect.y + handle.rect.height / 2;
touch("DOWN", x, y);
await setTimeout(600);
touch("MOVE", x, y + 60);
await setTimeout(200);
touch("MOVE", x, y + 90);
touch("MOVE", x, y + 60);
ad("screenshot", resolve(artifacts, "dragging.png"));
touch("UP", x, y + 60);
await setTimeout(2000);
ad("screenshot", resolve(artifacts, "dropped.png"));
const swipeX = list.rect.x + list.rect.width / 2;
touch("DOWN", swipeX, y + 80);
for (let offset = 90; offset <= 500; offset += 10) {
touch("MOVE", swipeX, y + offset);
}
const during = snapshot();
writeFileSync(resolve(artifacts, "during.json"), JSON.stringify(during));
ad("screenshot", resolve(artifacts, "during.png"));
touch("UP", swipeX, y + 500);
await setTimeout(1500);
const after = snapshot();
writeFileSync(resolve(artifacts, "after.json"), JSON.stringify(after));
ad("screenshot", resolve(artifacts, "after.png"));
const beforeSheet = nodes.find((node) => node.label === "Bottom sheet handle");
const afterSheet = during.find((node) => node.label === "Bottom sheet handle");
assert.ok(beforeSheet?.rect, "Usage must start as a sheet");
assert.ok(
!afterSheet || afterSheet.rect.y > beforeSheet.rect.y + 50,
"A body swipe after a same-slot drop must move the sheet",
);
} finally {
ad("close");
}
@@ -1,59 +0,0 @@
"""Check native drop recordings against visible row labels (requires opencv-python-headless).
Supply a before screenshot and a JSON map of label names to [x, y, width, height].
A recording must start in the original order and end in a different order. Once
all labels reach their final slots, any frame returning to the original slots fails.
Keep the pointer clear of the labels and use fixed fixture data.
"""
import argparse
import json
from pathlib import Path
import cv2
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--reference", required=True)
parser.add_argument("--labels", required=True)
parser.add_argument("--top", type=int, default=0)
parser.add_argument("--bottom", type=int)
parser.add_argument("videos", nargs="+")
args = parser.parse_args()
reference = cv2.imread(args.reference, cv2.IMREAD_GRAYSCALE)
assert reference is not None, "Cannot read reference image"
labels = json.loads(Path(args.labels).read_text())
results = []
for video in args.videos:
capture = cv2.VideoCapture(video)
frames = []
while True:
ok, image = capture.read()
if not ok:
break
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
positions = {}
for label, (x, y, width, height) in labels.items():
template = reference[y:y + height, x:x + width]
matches = cv2.matchTemplate(gray[args.top:args.bottom, x:x + width], template, cv2.TM_CCOEFF_NORMED)
_, confidence, _, point = cv2.minMaxLoc(matches)
positions[label] = (point[1] + args.top, confidence)
frames.append(positions)
capture.release()
assert frames, f"No frames in {video}"
initial, final = frames[0], frames[-1]
assert all(confidence >= 0.95 for _, confidence in initial.values()), f"Unrecognized initial labels: {video}"
assert all(confidence >= 0.95 for _, confidence in final.values()), f"Unrecognized final labels: {video}"
assert sorted(initial, key=lambda key: initial[key][0]) != sorted(final, key=lambda key: final[key][0]), f"Drop did not reorder: {video}"
def matches_slots(frame, target):
return all(confidence >= 0.95 and abs(y - target[label][0]) <= 2
for label, (y, confidence) in frame.items())
reached_final = False
wrong = []
for number, frame in enumerate(frames, start=1):
reached_final = reached_final or matches_slots(frame, final)
if reached_final and matches_slots(frame, initial):
wrong.append(number)
results.append({"recording": video, "oldOrderFrames": wrong, "count": len(wrong)})
print(json.dumps(results, indent=2))
raise SystemExit(1 if any(result["count"] for result in results) else 0)
+2 -50
View File
@@ -1,8 +1,6 @@
import { mkdtemp, writeFile, rm, rename } from "node:fs/promises";
import { tmpdir } from "node:os";
import { writeFile, rm, rename } from "node:fs/promises";
import path from "node:path";
import type { Page } from "@playwright/test";
import { copyPluginExample, pluginRequirements } from "./helpers/plugin-fixture";
import { copyPluginExample } from "./helpers/plugin-fixture";
import { connectNewWorkspaceDaemonClient } from "./helpers/new-workspace";
import { test as base } from "./fixtures";
import {
@@ -16,7 +14,6 @@ import { delayBrowserAgentCreatedStatus } from "./helpers/new-workspace";
export const test = base.extend<{
startup: { release(): Promise<void>; fail(): Promise<void> };
promptRejection: void;
composerMetadata: { set(patch: Record<string, string>): Promise<void> };
creation: Awaited<ReturnType<typeof createCreationScenario>>;
promptRetry: ReturnType<typeof createPromptRetryScenario>;
agentRetries: Awaited<ReturnType<typeof retryNextAgentCreation>>;
@@ -101,39 +98,6 @@ export default function contribute(server) {
await client.close();
}
},
composerMetadata: async ({ page }, provide) => {
const client = await connectNewWorkspaceDaemonClient();
const previous = await client.getDaemonConfig();
const directory = await mkdtemp(path.join(tmpdir(), "paseo-composer-metadata-"));
try {
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: "composer-metadata", requirements: pluginRequirements }),
);
await writeFile(
path.join(directory, "index.client.tsx"),
`import { useComposer } from "@getpaseo/plugin/client";
function Holder() {
globalThis.metadataComposer = useComposer();
return null;
}
export default function contribute(client) {
client.addComposerItem({ id: "holder", Component: Holder });
return () => {};
}`,
);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await provide({ set: (patch) => setComposerMetadata(page, patch) });
} finally {
await client.removePlugin("composer-metadata");
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
await rm(directory, { recursive: true, force: true });
await client.close();
}
},
creation: async ({ page }, provide) => {
const creation = await createCreationScenario(page);
try {
@@ -162,15 +126,3 @@ export default function contribute(client) {
}
},
});
type MetadataComposerGlobal = typeof globalThis & {
metadataComposer?: { setMetadata(patch: Record<string, string>): Promise<void> };
};
async function setComposerMetadata(page: Page, patch: Record<string, string>) {
await page.waitForFunction(() => (globalThis as MetadataComposerGlobal).metadataComposer);
await page.evaluate(
(value) => (globalThis as MetadataComposerGlobal).metadataComposer!.setMetadata(value),
patch,
);
}
@@ -21,6 +21,7 @@ export interface OlderTimelinePagesGate {
getRepeatedEntryCount(): number;
getOwnedEntryCountContaining(text: string): number;
releasePage(pageNumber: number): void;
waitForRequestCount(count: number): Promise<void>;
}
export interface DaemonHydrationGate {
@@ -370,6 +371,15 @@ export async function holdAgentOlderTimelinePages(
const ownedEntries = new Map<string, string>();
const releasedPages = new Set<number>();
const delayedForwards = new Map<number, Array<() => void>>();
const requestWaiters = new Map<number, Array<() => void>>();
const resolveRequestWaiters = () => {
for (const [count, resolvers] of requestWaiters) {
if (requestCount < count) continue;
requestWaiters.delete(count);
for (const resolve of resolvers) resolve();
}
};
const routePattern =
daemonPort === undefined ? daemonWsRoutePattern() : wsRoutePatternForPort(String(daemonPort));
@@ -383,6 +393,7 @@ export async function holdAgentOlderTimelinePages(
sessionMessage.direction === "before"
) {
requestCount += 1;
resolveRequestWaiters();
}
server.send(message);
});
@@ -428,6 +439,14 @@ export async function holdAgentOlderTimelinePages(
for (const forward of delayedForwards.get(pageNumber) ?? []) forward();
delayedForwards.delete(pageNumber);
},
waitForRequestCount(count) {
if (requestCount >= count) return Promise.resolve();
return new Promise<void>((resolve) => {
const resolvers = requestWaiters.get(count) ?? [];
resolvers.push(resolve);
requestWaiters.set(count, resolvers);
});
},
};
}
@@ -26,7 +26,7 @@ const SURFACE_SELECTORS = {
input: '[data-testid="command-center-input"]',
fileSearchStatus: '[data-testid="command-center-file-search-status"]',
results: '[data-testid="command-center-results"]',
tabs: '[data-testid="command-center-tabs"]',
scope: '[data-testid="command-center-files-scope"]',
fileRow: '[data-testid^="command-center-file-row-"]',
fileIcon: '[data-testid="command-center-file-icon"]',
fileLine: '[data-testid="command-center-file-line"]',
@@ -11,7 +11,7 @@ export async function seedSearchableCommandCenter() {
});
try {
const agents = [];
for (let index = 0; index < 3; index += 1) {
for (let index = 0; index < 60; index += 1) {
agents.push(
await createMockIdleAgent(seed.client, {
cwd: seed.repoPath,
@@ -49,27 +49,11 @@ export async function searchCommandCenter(panel: Locator, query: string) {
}
export async function warmCommandCenterRows(page: Page) {
// FlatList fills its overscan window in timed batches after the first visible frame,
// and a slow runner can still be mounting rows long after it. Start counting only
// once a quiet period passes with no row render.
await expect
.poll(() => page.evaluate(countRowRendersOverQuietPeriod), {
intervals: [0],
timeout: 15_000,
})
.toBe(0);
}
// Runs in the page: resets the render profile and counts row renders over two frames and 300ms.
async function countRowRendersOverQuietPeriod() {
globalThis.__PASEO_RENDER_PROFILE_REASONS__ = {};
await new Promise<void>((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
);
await new Promise((resolve) => setTimeout(resolve, 300));
return Object.keys(globalThis.__PASEO_RENDER_PROFILE_REASONS__ ?? {}).filter((id) =>
id.startsWith("CommandCenterResultRow:"),
).length;
// FlatList fills its overscan window in timed batches after the first visible frame.
await page.waitForTimeout(600);
await page.evaluate(() => {
globalThis.__PASEO_RENDER_PROFILE_REASONS__ = {};
});
}
export async function expectOnlyCommandCenterRowRendered(page: Page, resultId: string) {
@@ -89,17 +73,16 @@ export async function expectOnlyCommandCenterRowRendered(page: Page, resultId: s
expect(renders).toEqual({ [`CommandCenterResultRow:${resultId}`]: { render: 1 } });
}
const WORKSPACE_ROWS =
'[data-testid^="command-center-workspace-"]:not([data-testid="command-center-workspace-subtitle"]):not([data-testid="command-center-workspace-agent"])';
/** The list mounts a window of rows, not every match. */
export async function expectCommandCenterWorkspaceWindow(panel: Locator, total: number) {
const count = await panel.locator(WORKSPACE_ROWS).count();
export async function expectCommandCenterAgentWindow(panel: Locator, total: number) {
const rows = panel.locator(
'[data-testid^="command-center-agent-"]:not([data-testid="command-center-agent-subtitle"])',
);
const count = await rows.count();
expect(count).toBeGreaterThan(0);
expect(count).toBeLessThan(total);
}
export async function scrollToOldestCommandCenterWorkspace(panel: Locator) {
export async function scrollToOldestCommandCenterAgent(panel: Locator) {
await panel.getByTestId("command-center-results").evaluate((element) => {
element.scrollTop = element.scrollHeight;
element.dispatchEvent(new Event("scroll"));
@@ -22,9 +22,14 @@ export async function observeCommandCenterScroll(page: Page): Promise<void> {
const discoverPanel = new MutationObserver(() => {
const panel = document.querySelector<HTMLElement>('[data-testid="command-center-panel"]');
const viewport = panel?.querySelector<HTMLElement>('[data-testid="command-center-results"]');
const firstResult = viewport?.querySelector<HTMLElement>('[role="button"]');
if (!viewport || !firstResult) return;
const firstResult = panel?.querySelector<HTMLElement>('[role="button"]');
if (!panel || !firstResult) return;
let viewport = firstResult.parentElement;
while (viewport && viewport !== panel && viewport.scrollHeight <= viewport.clientHeight) {
viewport = viewport.parentElement;
}
if (!viewport || viewport === panel) return;
discoverPanel.disconnect();
let frame = 0;
@@ -114,8 +119,15 @@ export async function expectVisibleKeyboardNavigationNotToScroll(
for (let index = 0; index < 4; index += 1) await page.keyboard.press("ArrowDown");
const scrollSamples = await panel
.getByTestId("command-center-results")
.evaluate(async (viewport) => {
.getByRole("button")
.first()
.evaluate(async (firstResult) => {
let viewport = firstResult.parentElement;
while (viewport && viewport.scrollHeight <= viewport.clientHeight) {
viewport = viewport.parentElement;
}
if (!viewport) throw new Error("Could not find the command center scroll viewport");
const samples: number[] = [];
for (let frame = 0; frame < 20; frame += 1) {
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
@@ -127,8 +139,7 @@ export async function expectVisibleKeyboardNavigationNotToScroll(
expect(Math.max(...scrollSamples)).toBe(0);
}
/** All leads with three recent workspaces; a query searches every workspace. */
export async function expectRecentWorkspacesUntilSearch(panel: Locator): Promise<void> {
export async function expectWorkspaceResultsToBeLimitedUntilSearch(panel: Locator): Promise<void> {
const workspaces = panel.locator(
'[data-testid^="command-center-workspace-"]:not([data-testid="command-center-workspace-subtitle"])',
);
@@ -139,11 +150,9 @@ export async function expectRecentWorkspacesUntilSearch(panel: Locator): Promise
),
).size;
await expect(panel.getByText("Recent workspaces", { exact: true })).toBeVisible();
await expect.poll(distinctWorkspaceCount).toBe(3);
await expect.poll(distinctWorkspaceCount).toBe(5);
await panel.getByTestId("command-center-input").fill("Command Center Scroll");
await expect(panel.getByText("Recent workspaces", { exact: true })).toHaveCount(0);
await expect.poll(distinctWorkspaceCount).toBe(9);
}
@@ -1,20 +1,5 @@
import { expect, type Locator, type Page } from "@playwright/test";
export type CommandCenterTabName = "All" | "Workspaces" | "Files" | "Actions";
const TAB_PLACEHOLDERS: Record<CommandCenterTabName, string> = {
All: "Search workspaces, files, and actions...",
Workspaces: "Search workspaces...",
Files: "Search files...",
Actions: "Search actions...",
};
/** Outside a workspace there are no files to search, so All does not offer them. */
const TAB_PLACEHOLDERS_WITHOUT_WORKSPACE: Record<CommandCenterTabName, string> = {
...TAB_PLACEHOLDERS,
All: "Search workspaces and actions...",
};
// Opens the command center / global search palette from the sidebar and returns its panel.
export async function openCommandCenter(page: Page): Promise<Locator> {
await page.getByTestId("sidebar-search").click();
@@ -27,46 +12,3 @@ export async function closeCommandCenter(page: Page): Promise<void> {
await page.keyboard.press("Escape");
await expect(page.getByTestId("command-center-panel")).not.toBeVisible();
}
function commandCenterTab(panel: Locator, name: CommandCenterTabName): Locator {
return panel.getByTestId("command-center-tabs").getByRole("button", { name, exact: true });
}
export async function selectCommandCenterTab(
panel: Locator,
name: CommandCenterTabName,
options: { workspaceOpen?: boolean } = {},
): Promise<void> {
await commandCenterTab(panel, name).click();
await expectCommandCenterTab(panel, name, options);
}
/**
* The tab is selected and the search field asks for what that tab lists. Pass
* `{ workspaceOpen: false }` when the command center was opened outside a workspace.
*/
export async function expectCommandCenterTab(
panel: Locator,
name: CommandCenterTabName,
options: { workspaceOpen?: boolean } = {},
): Promise<void> {
const placeholders =
options.workspaceOpen === false ? TAB_PLACEHOLDERS_WITHOUT_WORKSPACE : TAB_PLACEHOLDERS;
await expect(commandCenterTab(panel, name)).toHaveAttribute("aria-selected", "true");
await expect(panel.getByTestId("command-center-input")).toHaveAttribute(
"placeholder",
placeholders[name],
);
}
/** Exactly these tabs are offered, in this order. */
export async function expectCommandCenterTabs(
panel: Locator,
names: readonly CommandCenterTabName[],
): Promise<void> {
await expect(panel.getByTestId("command-center-tabs").getByRole("button")).toHaveText([...names]);
}
export function commandCenterSection(panel: Locator, title: string): Locator {
return panel.getByTestId("command-center-results").getByText(title, { exact: true });
}
@@ -258,16 +258,6 @@ export async function createCreationScenario(page: Page) {
.filter(({ agent }) => agent.workspaceId === workspaceId)
.map(({ agent }) => agent.id);
},
async expectAgentMetadata(metadata: Record<string, unknown>) {
await expect
.poll(
async () =>
(await project.client.fetchAgents()).entries.find(
({ agent }) => agent.workspaceId === workspaceId,
)?.agent.metadata,
)
.toEqual(metadata);
},
async expectAgentTitle(title: string) {
await expect
.poll(
@@ -25,7 +25,7 @@ export async function addCustomModel(page: Page, id: string): Promise<void> {
}
export async function removeCustomModel(page: Page, id: string): Promise<void> {
await page.getByRole("textbox", { name: "Search models" }).fill(id);
await searchModels(page, id);
const remove = page.getByRole("button", { name: `Remove ${id}`, exact: true });
await expect(remove).toBeInViewport({ ratio: 1 });
await remove.click();
@@ -33,8 +33,20 @@ export async function removeCustomModel(page: Page, id: string): Promise<void> {
}
export async function expectCustomModelRetained(page: Page, id: string): Promise<void> {
await page.getByRole("textbox", { name: "Search models" }).fill(id);
await searchModels(page, id);
await expect(page.getByRole("button", { name: `Remove ${id}`, exact: true })).toBeInViewport({
ratio: 1,
});
}
/**
* Filters the model list and scrolls the sheet down to the custom models, since other sections push
* them below the fold at phone width. Only the section heading is scrolled into view: scrolling the
* row itself would also slide its card sideways and hide a Remove button pushed past the right edge.
*/
async function searchModels(page: Page, id: string): Promise<void> {
await page.getByRole("textbox", { name: "Search models" }).fill(id);
await page
.getByText("Custom models", { exact: true })
.evaluate((heading) => heading.scrollIntoView({ block: "start" }));
}
@@ -33,10 +33,8 @@ async function createRunningMockAgent(
return { id: agent.id, title };
}
// Agents are found through their workspace: the query names the agent, the row shows it.
async function searchCommandCenter(page: Page, query: string): Promise<void> {
async function openCommandCenter(page: Page): Promise<void> {
await page.getByTestId("sidebar-search").click();
await page.getByTestId("command-center-input").fill(query);
}
export class DirectoryBootstrapScenario {
@@ -80,10 +78,8 @@ export class DirectoryBootstrapScenario {
const workspaceLink = this.page.getByText(workspace.projectDisplayName, { exact: true });
await expect(workspaceLink).toHaveCount(1);
await expect(workspaceLink).toBeVisible();
await searchCommandCenter(this.page, agent.title);
const agentLink = this.page
.getByTestId("command-center-workspace-agent")
.getByText(agent.title, { exact: true });
await openCommandCenter(this.page);
const agentLink = this.page.getByText(agent.title, { exact: true });
await expect(agentLink).toHaveCount(1);
await expect(agentLink).toBeVisible();
await this.page.keyboard.press("Escape");
@@ -115,10 +111,8 @@ export class DirectoryBootstrapScenario {
const workspaceLink = this.page.getByText(workspace.projectDisplayName, { exact: true });
await expect(workspaceLink).toHaveCount(1);
await expect(workspaceLink).toBeVisible();
await searchCommandCenter(this.page, agent.title);
const agentLink = this.page
.getByTestId("command-center-workspace-agent")
.getByText(agent.title, { exact: true });
await openCommandCenter(this.page);
const agentLink = this.page.getByText(agent.title, { exact: true });
await expect(agentLink).toHaveCount(1);
await expect(agentLink).toBeVisible();
await agentLink.click();
@@ -232,11 +232,8 @@ export async function expectNewWorkspaceControlsEnabled(page: Page): Promise<voi
});
}
export async function openNewWorkspaceProjectPickerWithShortcut(
page: Page,
shortcut = "Control+P",
): Promise<void> {
await page.keyboard.press(shortcut);
export async function openNewWorkspaceProjectPickerWithShortcut(page: Page): Promise<void> {
await page.keyboard.press("Control+P");
const searchInput = page.getByPlaceholder("Search projects");
await expect(searchInput).toBeVisible({ timeout: 30_000 });
@@ -86,6 +86,17 @@ export function setupModal(page: Page): Locator {
return page.getByTestId("onboarding-modal").getByRole("dialog");
}
/** A sheet opened from a setup step, which should sit exactly on the setup card. */
export function setupSheet(page: Page, testID: "provider-settings-sheet" | "add-provider-sheet") {
return page.getByTestId(testID).getByRole("dialog");
}
export async function expectSheetCoversSetupCard(page: Page, sheet: Locator): Promise<void> {
await expect(sheet).toBeVisible();
const card = await setupModal(page).boundingBox();
await expect.poll(() => sheet.boundingBox()).toEqual(card);
}
export async function expectSetupStep(page: Page, title: string): Promise<void> {
await expect(setupModal(page).getByRole("heading", { name: title, exact: true })).toBeVisible({
timeout: 60_000,
@@ -106,10 +106,12 @@ export async function verifyProviderSettings({
await test.step("provider settings render the registered icon", async () => {
await openSettings(page);
await openSettingsHostSection(page, getServerId(), "providers");
await expectProviderIcon(
page.getByRole("button", { name: "Direct provider example provider details", exact: true }),
iconPaths,
);
// The row's button lies under its content, so the icon is in the row, beside the button.
const opener = page.getByRole("button", {
name: "Direct provider example provider details",
exact: true,
});
await expectProviderIcon(page.getByTestId(/^provider-row-/).filter({ has: opener }), iconPaths);
await capture(page, testInfo, "provider-settings");
await page.getByTestId("settings-back-to-workspace").click();
});
@@ -131,7 +131,6 @@ export interface SeedDaemonClient {
currentModeId: string | null;
status: string;
title?: string | null;
metadata?: Record<string, unknown>;
};
}>;
}>;
+44 -2
View File
@@ -507,8 +507,8 @@ export async function serveJson(page: Page, url: string, body: unknown): Promise
});
}
export async function openAddProviderArea(page: Page): Promise<void> {
await page.getByTestId("host-page-add-provider-card").scrollIntoViewIfNeeded();
export async function openAddProvider(page: Page): Promise<void> {
await page.getByTestId("provider-list-add").click();
await expect(page.getByRole("textbox", { name: "Search providers" })).toBeVisible();
}
@@ -520,17 +520,59 @@ export async function findAcpCatalogProvider(page: Page, providerName: string):
export async function installAcpCatalogProvider(page: Page, providerName: string): Promise<void> {
await findAcpCatalogProvider(page, providerName);
await page.getByRole("button", { name: `Add ${providerName}`, exact: true }).click();
// The sheet closes once the add is done. Adding probes the new provider, which can outlast an
// assertion's default wait.
await expect(page.getByRole("textbox", { name: "Search providers" })).toHaveCount(0, {
timeout: 60_000,
});
}
/** Adding opens the new provider's page; its row waits in the list behind it. */
export async function expectProviderInstalledInSettings(
page: Page,
providerName: string,
): Promise<void> {
await expect(page.getByTestId("provider-detail-title")).toHaveText(providerName);
await page.getByTestId("provider-detail-back").click();
await expect(
page.getByRole("button", { name: `${providerName} provider details`, exact: true }),
).toBeVisible();
}
export async function openProviderDetail(page: Page, providerName: string): Promise<void> {
await page.getByRole("button", { name: `${providerName} provider details`, exact: true }).click();
await expect(page.getByTestId("provider-detail-title")).toHaveText(providerName);
}
/** Load a provider's Settings page from its URL, as a reload or a shared link does. */
export async function gotoProviderPage(
page: Page,
serverId: string,
providerId: string,
): Promise<void> {
await page.goto(
`/settings/hosts/${encodeURIComponent(serverId)}/providers/${encodeURIComponent(providerId)}`,
);
}
export async function expectProviderPageLoaded(page: Page, providerName: string): Promise<void> {
await expect(page.getByTestId("provider-detail-title")).toHaveText(providerName, {
timeout: 30_000,
});
await expect(page.getByText("Provider status")).toBeVisible({ timeout: 30_000 });
}
export async function expectProviderNotOnHost(page: Page): Promise<void> {
await expect(page.getByText("This provider isn't on this host")).toBeVisible({
timeout: 30_000,
});
}
export async function leaveProviderDetail(page: Page): Promise<void> {
await page.getByTestId("provider-detail-back").click();
await expect(page.getByTestId("provider-list")).toBeVisible();
}
export async function expectHostNoDaemonLifecycleRow(page: Page): Promise<void> {
await expect(page.getByTestId("host-page-daemon-lifecycle-card")).toHaveCount(0);
}
@@ -427,11 +427,7 @@ export async function holdOlderHistoryPages(
const loader = page.getByTestId("load-older-history-spinner");
return {
async expectRequestedPages(count) {
await expect
.poll(() => gate.getRequestCount(), {
message: `older history requests ${count} page(s)`,
})
.toBeGreaterThanOrEqual(count);
await gate.waitForRequestCount(count);
expect(gate.getRequestCount()).toBe(count);
},
async expectSettledWithRequestedPages(count) {
@@ -147,46 +147,6 @@ export function usageModal(page: Page): Locator {
return visible(page, "usage-modal-body");
}
/** The Usage modal's cards, top to bottom, by report id. */
export async function expectUsageCardOrder(page: Page, reportIds: string[]): Promise<void> {
const cards = usageModal(page).locator('[data-testid^="usage-report-"]');
await expect(cards).toHaveCount(reportIds.length);
await expect
.poll(() =>
cards.evaluateAll((nodes) =>
nodes.map((node) => node.getAttribute("data-testid")?.slice("usage-report-".length)),
),
)
.toEqual(reportIds);
}
/** Turns a card on or off from its header switch, named by its source and account. */
export async function setUsageCardOn(page: Page, name: string, on: boolean): Promise<void> {
const cardSwitch = usageModal(page).getByRole("switch", { name: `Show ${name}`, exact: true });
await cardSwitch.click();
await expect(cardSwitch).toBeChecked({ checked: on });
}
/** Drags a card by its handle until it sits above another card, with the mouse. */
export async function dragUsageCardAbove(
page: Page,
reportId: string,
targetReportId: string,
): Promise<void> {
const card = usageModal(page).getByTestId(`usage-report-${reportId}`);
const target = usageModal(page).getByTestId(`usage-report-${targetReportId}`);
await card.hover();
const handle = await card.getByTestId("usage-card-drag-handle").boundingBox();
const targetBox = await target.boundingBox();
if (!handle || !targetBox) throw new Error("Both cards must be on screen to drag.");
const x = handle.x + handle.width / 2;
await page.mouse.move(x, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(x, handle.y + handle.height / 2 - 10, { steps: 3 });
await page.mouse.move(x, targetBox.y + 4, { steps: 12 });
await page.mouse.up();
}
/** Each pinned window as it reads: its percent and short label, "31% 5h". */
export async function expectPinnedUsage(page: Page, windows: string[]): Promise<void> {
const pinned = usageItem(page).getByTestId("sidebar-usage-pinned-window");
@@ -207,18 +167,14 @@ export function pinRow(scope: Locator, source: string, window: string): Locator
/**
* A report card whose window rows do not pin: no pin toggle, no pin glyph, and nothing focusable
* but the header's buttons and on/off switch, so no row presses or highlights on hover.
* but buttons, so no row presses or highlights on hover.
*/
export async function expectUnpinnableRows(card: Locator): Promise<void> {
await expect(card.getByRole("checkbox")).toHaveCount(0);
await expect(card.locator('[data-testid^="usage-pin-"]')).toHaveCount(0);
const focusable = await card
.locator("[tabindex]")
.evaluateAll(
(nodes) =>
nodes.filter((node) => !["button", "switch"].includes(node.getAttribute("role") ?? ""))
.length,
);
.evaluateAll((nodes) => nodes.filter((node) => node.getAttribute("role") !== "button").length);
expect(focusable).toBe(0);
}
@@ -317,19 +273,6 @@ export async function openUsageOptions(page: Page): Promise<void> {
await expect(visible(page, "usage-display-used")).toBeVisible();
}
/** Picks the host Usage shows, from the Host row of its Settings. */
export async function pickUsageHost(page: Page, serverId: string): Promise<void> {
await openUsageOptions(page);
await visible(page, "usage-options-host").click();
await visible(page, `usage-options-host-${serverId}`).click();
await expect(page.getByTestId("usage-display-used")).toHaveCount(0);
}
/** The host Usage shows, under its title; absent with a single host. */
export function usageModalHost(page: Page): Locator {
return visible(page, "usage-modal-host");
}
export function usageOptionsSurface(page: Page): Locator {
return page
.locator(
@@ -162,38 +162,3 @@ export function createGatedTeardown(): GatedTeardown {
release: () => writeFileSync(releasePath, "release\n"),
};
}
export function archivedToast(page: Page) {
return page.getByTestId("workspace-archived-toast");
}
export interface SidebarListLayout {
/** Bottom edge of the list's visible area. */
listBottom: number;
/** Bottom edges of the visible project and workspace rows, top to bottom. */
rowBottoms: number[];
rowHeight: number;
}
/** Scrolls the sidebar's workspace list to its end and reads where its rows sit. */
export async function scrollSidebarListToEnd(page: Page): Promise<SidebarListLayout> {
const list = page.getByTestId("sidebar-project-workspace-list-scroll");
await list.evaluate((element) => {
element.scrollTop = element.scrollHeight;
});
return list.evaluate((element) => {
const visible = element.getBoundingClientRect();
const rows = Array.from(
element.querySelectorAll<HTMLElement>(
'[data-testid^="sidebar-workspace-row-"],[data-testid^="sidebar-project-row-"]',
),
)
.map((row) => row.getBoundingClientRect())
.filter((row) => row.height > 0 && row.bottom > visible.top && row.top < visible.bottom);
return {
listBottom: visible.bottom,
rowBottoms: rows.map((row) => row.bottom).sort((a, b) => a - b),
rowHeight: Math.min(...rows.map((row) => row.height)),
};
});
}
@@ -1,282 +0,0 @@
package sh.paseo.scroll
import android.app.Activity
import android.content.Intent
import android.os.SystemClock
import android.text.InputType
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.soloader.OpenSourceMergedSoMapping
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.views.scroll.ReactScrollView
import com.facebook.react.views.scroll.ReactScrollViewManager
import com.facebook.react.views.view.ReactViewGroup
import com.facebook.soloader.SoLoader
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* Touches on chat text in the timeline's scroll view. Chat text is selectable, so a tap or a long
* press focuses it, and the focus may not scroll the timeline. The touches are injected into a real
* window, so touch mode, focus and the selection controller run as on device.
*/
@RunWith(AndroidJUnit4::class)
class SelectableTextTouchTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private var activity: Activity? = null
@After fun finish() {
activity?.finish()
}
// A reply whose top is on screen and whose bottom is below the viewport.
@Test fun tappingTextThatRunsBelowTheViewportKeepsTheOffset() {
val timeline = openTimeline(edge = Edge.TOP)
timeline.tap(visibleY = EDGE_Y + 100)
assertTrue("The tap focuses the text", timeline.textHasFocus())
assertEquals("Offset after the tap", OFFSET, timeline.settledScrollY())
}
// A reply whose bottom is on screen and whose top is above the viewport, like a link at its end.
@Test fun tappingTextThatStartsAboveTheViewportKeepsTheOffset() {
val timeline = openTimeline(edge = Edge.BOTTOM)
timeline.tap(visibleY = EDGE_Y - 100)
assertTrue("The tap focuses the text", timeline.textHasFocus())
assertEquals("Offset after the tap", OFFSET, timeline.settledScrollY())
}
// A reply that is still streaming gets new text while the user's tap holds its focus.
@Test fun aStreamingUpdateToTappedTextKeepsTheOffset() {
val timeline = openTimeline(edge = Edge.BOTTOM)
timeline.tap(visibleY = EDGE_Y - 100)
assertTrue("The tap focuses the text", timeline.textHasFocus())
timeline.updateText("$CHAT_TEXT\nOne more line of the reply.")
assertEquals("Offset after the update", OFFSET, timeline.settledScrollY())
}
// The timeline changes height while tapped text holds focus, as when the composer above the
// keyboard loses its queued message.
@Test fun aTimelineResizeAfterATapKeepsTheOffset() {
val timeline = openTimeline(edge = Edge.TOP)
timeline.tap(visibleY = EDGE_Y + 100)
assertTrue("The tap focuses the text", timeline.textHasFocus())
timeline.resize(height = VIEWPORT + 200)
assertEquals("Offset after the resize", OFFSET, timeline.settledScrollY())
}
@Test fun longPressSelectsAWordAndKeepsTheOffset() {
val timeline = openTimeline(edge = Edge.TOP)
val word = timeline.wordAt(visibleY = EDGE_Y + 100)
timeline.longPress(visibleY = EDGE_Y + 100)
assertEquals("Selected text", word, timeline.selectedText())
assertEquals("Offset after the long press", OFFSET, timeline.settledScrollY())
}
// Inputs in the timeline, such as an agent's question form, still scroll into view to be typed in.
@Test fun tappingAnInputThatRunsBelowTheViewportRevealsIt() {
val timeline = openTimeline(edge = Edge.TOP, editable = true)
timeline.tap(visibleY = EDGE_Y + 100)
assertTrue("The tap focuses the input", timeline.textHasFocus())
assertNotEquals("Offset after the tap", OFFSET, timeline.settledScrollY())
}
private inner class Timeline(private val scroll: ReactScrollView, private val text: TextView) {
fun scrollTo(y: Int) {
instrumentation.runOnMainSync { scroll.scrollTo(0, y) }
awaitFrames(2)
}
fun tap(visibleY: Int) {
val downTime = SystemClock.uptimeMillis()
touch(downTime, MotionEvent.ACTION_DOWN, visibleY)
touch(downTime, MotionEvent.ACTION_UP, visibleY)
}
fun longPress(visibleY: Int) {
val downTime = SystemClock.uptimeMillis()
touch(downTime, MotionEvent.ACTION_DOWN, visibleY)
SystemClock.sleep(ViewConfiguration.getLongPressTimeout() * 2L)
touch(downTime, MotionEvent.ACTION_UP, visibleY)
}
fun resize(height: Int) {
instrumentation.runOnMainSync {
scroll.layoutParams = scroll.layoutParams.apply { this.height = height }
}
}
// Replaces the text and lays it out again at its top, the way a streaming reply mounts.
fun updateText(value: String) {
instrumentation.runOnMainSync {
text.setText(value)
text.measure(exact(WIDTH), unspecified())
text.layout(0, text.top, WIDTH, text.top + text.measuredHeight)
}
}
fun textHasFocus(): Boolean {
awaitFrames(2)
var focused = false
instrumentation.runOnMainSync { focused = text.isFocused }
return focused
}
fun selectedText(): String {
awaitFrames(2)
var selected = ""
instrumentation.runOnMainSync {
selected = text.text.substring(text.selectionStart, text.selectionEnd)
}
return selected
}
/** The word under [visibleY] at the current offset. */
fun wordAt(visibleY: Int): String {
var word = ""
instrumentation.runOnMainSync {
val chars = text.text
val y = scroll.scrollY + visibleY - text.top
val offset = text.getOffsetForPosition(TOUCH_X - text.left, y.toFloat())
var start = offset
var end = offset
while (start > 0 && chars[start - 1].isLetterOrDigit()) start--
while (end < chars.length && chars[end].isLetterOrDigit()) end++
word = chars.substring(start, end)
}
assertTrue("The touch lands on a word", word.isNotEmpty())
return word
}
fun settledScrollY(): Int {
var previous = scrollY()
repeat(60) {
awaitFrames(3)
val current = scrollY()
if (current == previous) return current
previous = current
}
throw AssertionError("Offset never settled")
}
private fun scrollY(): Int {
var y = 0
instrumentation.runOnMainSync { y = scroll.scrollY }
return y
}
// Injected through the window like a finger, which puts the window in touch mode.
private fun touch(downTime: Long, action: Int, visibleY: Int) {
val location = IntArray(2)
instrumentation.runOnMainSync { scroll.getLocationOnScreen(location) }
val x = location[0] + TOUCH_X
val y = location[1] + visibleY.toFloat()
val event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), action, x, y, 0)
instrumentation.sendPointerSync(event)
event.recycle()
}
fun awaitFrames(count: Int) {
repeat(count) {
instrumentation.waitForIdleSync()
SystemClock.sleep(16)
}
}
}
/** Which edge of the text is on screen, at [EDGE_Y]; the other is past the viewport. */
private enum class Edge { TOP, BOTTOM }
/** A timeline scrolled to [OFFSET] with one block of chat text taller than the viewport. */
private fun openTimeline(edge: Edge, editable: Boolean = false): Timeline {
val started =
instrumentation.startActivitySync(
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
activity = started
lateinit var timeline: Timeline
instrumentation.runOnMainSync {
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(started)
SoLoader.init(started, OpenSourceMergedSoMapping)
val reactContext = MountingReactContext(started.applicationContext)
val context = ThemedReactContext(reactContext, started)
val manager =
PaseoScrollPackage().createViewManager(reactContext, ReactScrollViewManager.REACT_CLASS)
as ReactScrollViewManager
val scroll = manager.createViewInstance(context)
val content = ReactViewGroup(context)
val text =
if (editable) {
// Selectable, as React Native's TextInput makes itself when attached, so only being a text
// editor tells it apart from chat text. No input connection: building one runs React
// Native's focus search through Fabric, which this context does not run.
object : EditText(context) {
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? = null
}.apply {
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE
setTextIsSelectable(true)
}
} else {
// How enriched-markdown and React Native's <Text selectable> set up chat text.
TextView(context).apply { setTextIsSelectable(true) }
}
text.setText(CHAT_TEXT)
content.addView(text)
scroll.addView(content)
started.setContentView(
FrameLayout(started).apply { addView(scroll, FrameLayout.LayoutParams(WIDTH, VIEWPORT)) }
)
// Fabric lays out React content; nothing in a React view group lays out its children itself.
content.layout(0, 0, WIDTH, CONTENT_HEIGHT)
text.measure(exact(WIDTH), unspecified())
assertTrue("The text is taller than the viewport", text.measuredHeight > VIEWPORT)
val top = if (edge == Edge.TOP) OFFSET + EDGE_Y else OFFSET + EDGE_Y - text.measuredHeight
text.layout(0, top, WIDTH, top + text.measuredHeight)
timeline = Timeline(scroll, text)
}
timeline.awaitFrames(2)
timeline.scrollTo(OFFSET)
assertEquals("Starts at the offset", OFFSET, timeline.settledScrollY())
return timeline
}
private fun exact(size: Int) = View.MeasureSpec.makeMeasureSpec(size, View.MeasureSpec.EXACTLY)
private fun unspecified() = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
private companion object {
const val WIDTH = 600
const val TOUCH_X = WIDTH / 2f
const val VIEWPORT = 800
const val CONTENT_HEIGHT = 6000
const val OFFSET = 2400
// Below the plain activity's action bar, which overlays the top of the window.
const val EDGE_Y = 500
val CHAT_TEXT = List(30) { "Line $it of a reply in the chat timeline." }.joinToString("\n")
}
}
@@ -1,12 +1,10 @@
package sh.paseo.scroll;
import android.content.Context;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.facebook.react.R;
import com.facebook.react.views.scroll.MaintainVisibleScrollPositionHelper;
@@ -14,7 +12,7 @@ import com.facebook.react.views.scroll.ReactScrollView;
import com.facebook.react.views.scroll.ReactScrollViewHelper;
/**
* React Native's vertical scroll view with five corrections. Java, because the content-position
* React Native's vertical scroll view with two corrections. Java, because the content-position
* config type is internal to React Native's Kotlin module.
*/
final class PaseoScrollView extends ReactScrollView {
@@ -29,7 +27,6 @@ final class PaseoScrollView extends ReactScrollView {
private @Nullable MaintainVisibleScrollPositionHelper.Config visibleContentPosition = null;
private boolean isClampPending = false;
private boolean isUserDragging = false;
private boolean isFocusRevealSkipped = false;
PaseoScrollView(Context context) {
super(context);
@@ -54,56 +51,6 @@ final class PaseoScrollView extends ReactScrollView {
super.scrollToPreservingMomentum(x, y);
}
// Chat text is selectable (enriched-markdown's text views and <Text selectable>), and selectable
// text takes focus when touched: a tap on a link, a word, or a long-press to select. React Native
// scrolls a newly focused child fully into view, so touching a reply that is partly off screen
// scrolled the timeline by up to a screen under the user's finger. Text the user touched is
// already where they are looking, so its focus does not scroll. Inputs, and focus moved by a
// keyboard, still scroll into view.
@Override
public void requestChildFocus(View child, View focused) {
if (isTouchedReadOnlyText(focused)) {
requestChildFocusWithoutScroll(child, focused);
return;
}
super.requestChildFocus(child, focused);
}
// Focused text asks to reveal its selection whenever the selection changes. A streaming reply
// replaces its text, which collapses the selection to the start, so a reply that kept focus from
// a touch scrolled the timeline back to its first line on the next update. Read-only text has no
// caret, so a collapsed selection has nothing to reveal. A selection the user drags still does.
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
View focused = findFocus();
if (isTouchedReadOnlyText(focused) && !((TextView) focused).hasSelection()) return false;
return super.requestChildRectangleOnScreen(child, rectangle, immediate);
}
// When the scroll view changes height, Android scrolls the focused view into view again. Touched
// chat text keeps focus, so the composer growing or shrinking below the timeline realigned it.
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
isFocusRevealSkipped = isTouchedReadOnlyText(findFocus());
try {
super.onSizeChanged(w, h, oldw, oldh);
} finally {
isFocusRevealSkipped = false;
}
}
@Override
protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
if (isFocusRevealSkipped) return 0;
return super.computeScrollDeltaToGetChildRectOnScreen(rect);
}
private static boolean isTouchedReadOnlyText(@Nullable View view) {
if (!(view instanceof TextView) || !view.isInTouchMode()) return false;
TextView text = (TextView) view;
return text.isTextSelectable() && !text.onCheckIsTextEditor();
}
// The drag begins where React Native emits onScrollBeginDrag.
@Override
protected void handleInterceptedTouchEvent(MotionEvent ev) {
-6
View File
@@ -23,12 +23,6 @@ export default defineConfig({
// spec on one worker avoids repeating its file-level setup across daemons.
fullyParallel: false,
workers: Number(process.env.E2E_WORKERS ?? (process.env.CI ? "2" : "1")),
// Workspace packages are already compiled. Tests import them at run time, so
// on a cold cache every worker transpiles the same files and writes them into
// Playwright's shared transform cache without locking. A worker that reads an
// entry mid-write loads an empty module and fails with "does not provide an
// export named".
build: { external: ["**/packages/*/dist/**"] },
retries: process.env.CI ? 1 : 0,
reporter: [["list"]],
use: {
@@ -49,21 +49,8 @@ afterEach(() => {
host.remove();
});
type OlderHistoryInput = Pick<
StreamRenderInput,
"onNearHistoryStart" | "hasOlderHistory" | "olderHistoryProgressKey"
>;
interface MountTimelineOptions {
olderHistory?: OlderHistoryInput;
isMobileBreakpoint?: boolean;
}
function mountTimeline(
historyMounted: StreamItem[],
{ olderHistory, isMobileBreakpoint = true }: MountTimelineOptions = {},
) {
const strategy = createWebStreamStrategy({ isMobileBreakpoint });
function mountTimeline(historyMounted: StreamItem[]) {
const strategy = createWebStreamStrategy({ isMobileBreakpoint: true });
const viewportRef = React.createRef<StreamViewportHandle>();
const input: StreamRenderInput = {
agentId: "agent",
@@ -89,7 +76,6 @@ function mountTimeline(
baseListContentContainerStyle: null,
forwardListContentContainerStyle: null,
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
...olderHistory,
};
const render = (segments: Partial<StreamRenderInput["segments"]>) =>
root.render(strategy.render({ ...input, segments: { ...input.segments, ...segments } }));
@@ -114,20 +100,8 @@ function mountTimeline(
scrollTo: (top: number) => {
scrollContainer.scrollTop = top;
},
// A wheel listener runs before the browser applies the scroll the wheel causes.
wheelUpTo: (top: number) => {
scrollContainer.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -1000 }));
scrollContainer.scrollTop = top;
},
distanceFromEnd: () =>
scrollContainer.scrollHeight - scrollContainer.clientHeight - scrollContainer.scrollTop,
scrollTop: () => scrollContainer.scrollTop,
scrollUp: (distance: number) =>
act(() => {
scrollContainer.dispatchEvent(new WheelEvent("wheel", { deltaY: -distance }));
scrollContainer.scrollTop -= distance;
scrollContainer.dispatchEvent(new Event("scroll"));
}),
// Resize observers and the hold's settle run on animation frames.
settle: () =>
act(async () => {
@@ -139,53 +113,6 @@ function mountTimeline(
}
describe("web disclosure hold", () => {
it.each([{ isMobileBreakpoint: true }, { isMobileBreakpoint: false }])(
"keeps the reading position when mounted history becomes virtualized (compact: $isMobileBreakpoint)",
async (options) => {
const history = Array.from({ length: 80 }, (_, index) => row(index));
const timeline = mountTimeline(history, options);
await timeline.settle();
timeline.scrollUp(600);
await timeline.settle();
const offset = timeline.scrollTop();
const readingTop = timeline.rowTop("message-64");
expect(offset).toBeGreaterThan(0);
timeline.render({
historyVirtualized: history.slice(0, 60),
historyMounted: history.slice(60),
});
await timeline.settle();
expect(timeline.scrollTop()).toBe(offset);
expect(timeline.rowTop("message-64")).toBe(readingTop);
},
);
it.each([{ isMobileBreakpoint: true }, { isMobileBreakpoint: false }])(
"keeps following output when mounted history becomes virtualized at the end (compact: $isMobileBreakpoint)",
async (options) => {
const history = Array.from({ length: 80 }, (_, index) => row(index));
const timeline = mountTimeline(history, options);
await timeline.settle();
timeline.render({
historyVirtualized: history.slice(0, 60),
historyMounted: history.slice(60),
});
await timeline.settle();
expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1);
timeline.render({
historyVirtualized: history.slice(0, 60),
historyMounted: history.slice(60),
liveHead: [row(80)],
});
await timeline.settle();
expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1);
},
);
it("keeps the trigger's top when an anchored toggle at the bottom opens rows below it, and stops following", async () => {
const history = [1, 2, 3, 4, 5, 6].map((index) => row(index));
const timeline = mountTimeline(history);
@@ -281,32 +208,3 @@ describe("web disclosure hold", () => {
expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1);
});
});
describe("web history start", () => {
it("loads older history when an upward wheel lands at the start after the reader stopped following", async () => {
let olderHistoryLoads = 0;
const history = [1, 2, 3, 4, 5, 6].map((index) => row(index));
const timeline = mountTimeline(history, {
olderHistory: {
hasOlderHistory: true,
olderHistoryProgressKey: "epoch:1",
onNearHistoryStart: async () => {
olderHistoryLoads += 1;
return true;
},
},
});
await timeline.settle();
// Opening a row at the bottom stops following output without any scroll.
timeline.hold("message-5", () =>
timeline.render({ historyMounted: [...history.slice(0, 5), row(7, 200), history[5]!] }),
);
await timeline.settle();
expect(olderHistoryLoads).toBe(0);
timeline.wheelUpTo(0);
await timeline.settle();
expect(olderHistoryLoads).toBe(1);
});
});
+6 -19
View File
@@ -457,8 +457,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const rowVirtualizer = useVirtualizer({
count: segments.historyVirtualized.length,
enabled: shouldUseVirtualizer,
// History can become virtualized after the reader has already scrolled the mounted rows.
initialOffset: () => scrollContainerRef.current?.scrollTop ?? 0,
initialRect: {
width: scrollContainerRef.current?.clientWidth ?? 0,
height: scrollContainerRef.current?.clientHeight ?? 0,
@@ -607,15 +605,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
window.performance.now() + UPWARD_INPUT_EVIDENCE_TIMEOUT_MS;
}, []);
const hasUpwardInputEvidence = useCallback(() => {
const mouseGesture = mouseScrollGestureRef.current;
return (
mouseGesture?.kind === "scrollbar" ||
(mouseGesture?.kind === "autoscroll" && mouseGesture.hasUpwardEvidence) ||
window.performance.now() < upwardInputEvidenceUntilRef.current
);
}, []);
useLayoutEffect(() => {
if (isActive) {
return;
@@ -802,16 +791,16 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - USER_SCROLL_DELTA_EPSILON;
const scrolledDown =
currentScrollTop > lastKnownScrollTopRef.current + USER_SCROLL_DELTA_EPSILON;
const userScrolledUp = scrolledUp && hasUpwardInputEvidence();
const mouseGesture = mouseScrollGestureRef.current;
const hasUpwardInputEvidence =
mouseGesture?.kind === "scrollbar" ||
(mouseGesture?.kind === "autoscroll" && mouseGesture.hasUpwardEvidence) ||
window.performance.now() < upwardInputEvidenceUntilRef.current;
if (!followOutputRef.current && isAtBottom && scrolledDown && !isJumpSettling()) {
setFollowOutput(true);
} else if (followOutputRef.current && userScrolledUp) {
} else if (followOutputRef.current && scrolledUp && hasUpwardInputEvidence) {
stopFollowingOutputFromUserIntent();
} else if (userScrolledUp) {
// Wheel listeners can run before or after the browser applies the scroll, so the
// upward scroll itself re-arms loading when it reaches the start.
rearmHistoryStartFromUserIntent();
}
lastKnownScrollTopRef.current = currentScrollTop;
@@ -822,10 +811,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
evaluateHistoryStart();
}, [
evaluateHistoryStart,
hasUpwardInputEvidence,
isJumpSettling,
readingAnchor,
rearmHistoryStartFromUserIntent,
stopFollowingOutputFromUserIntent,
updateScrollMetrics,
]);
+1
View File
@@ -934,6 +934,7 @@ function RootStack() {
<Stack.Screen name="settings/hosts/[serverId]/plugins/[pluginId]/[screenId]" />
<Stack.Screen name="settings/hosts/[serverId]/projects/index" />
<Stack.Screen name="settings/hosts/[serverId]/projects/[projectId]" />
<Stack.Screen name="settings/hosts/[serverId]/providers/[providerId]" />
</ThemedStack>
);
}
@@ -0,0 +1,24 @@
import { useLocalSearchParams } from "expo-router";
import { useMemo } from "react";
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
import SettingsScreen from "@/screens/settings-screen";
import { normalizeProjectSettingsRouteId } from "@/utils/host-routes";
export default function SettingsHostProviderDetailRoute() {
const params = useLocalSearchParams<{
serverId?: string | string[];
providerId?: string | string[];
}>();
const serverId = normalizeProjectSettingsRouteId(params.serverId);
const providerId = normalizeProjectSettingsRouteId(params.providerId);
const view = useMemo(
() => ({ kind: "provider" as const, serverId, providerId }),
[providerId, serverId],
);
return (
<HostRouteBootstrapBoundary>
<SettingsScreen view={view} />
</HostRouteBootstrapBoundary>
);
}
@@ -1,5 +0,0 @@
export type { ArchivedWorkspace, ArchivedWorkspaceAgent } from "./internal/group";
export {
useArchivedWorkspaceSearch,
type ArchivedWorkspaceSearch,
} from "./internal/use-archived-workspace-search";
@@ -1,128 +0,0 @@
import { describe, expect, it } from "vitest";
import type { AggregatedAgent } from "@/hooks/use-aggregated-agents";
import { groupArchivedWorkspaces } from "./group";
const T0 = Date.parse("2026-11-01T10:00:00.000Z");
const minutes = (count: number) => new Date(T0 + count * 60_000);
function historyAgent(input: {
id: string;
serverId?: string;
workspaceId?: string | null;
title?: string | null;
activeAt: number;
archivedAt?: number | null;
workspaceName?: string | null;
branch?: string | null;
cwd?: string;
}): AggregatedAgent {
const cwd = input.cwd ?? "/repos/payments";
return {
id: input.id,
serverId: input.serverId ?? "host-a",
serverLabel: input.serverId ?? "host-a",
title: input.title ?? null,
status: "closed",
turn: { phase: "open", turnId: null, startedAt: null, cancellationRequestId: null },
lastActivityAt: minutes(input.activeAt),
cwd,
workspaceId: input.workspaceId === undefined ? "ws-1" : input.workspaceId,
provider: "claude",
requiresAttention: false,
attentionReason: null,
attentionTimestamp: null,
archivedAt: input.archivedAt == null ? null : minutes(input.archivedAt),
createdAt: minutes(0),
labels: {},
projectPlacement: {
projectKey: "prj-payments",
projectName: "payments",
workspaceName: input.workspaceName === undefined ? "Billing cleanup" : input.workspaceName,
checkout: {
cwd,
isGit: true,
currentBranch: input.branch === undefined ? "billing-cleanup" : input.branch,
remoteUrl: null,
worktreeRoot: cwd,
isPaseoOwnedWorktree: false,
mainRepoRoot: null,
},
},
} as AggregatedAgent;
}
const NO_ACTIVE = new Map<string, ReadonlySet<string>>();
describe("groupArchivedWorkspaces", () => {
it("folds a workspace's agents into one entry led by its most recent agent", () => {
const [workspace] = groupArchivedWorkspaces({
agents: [
historyAgent({ id: "older", title: "Audit invoices", activeAt: 1, archivedAt: 5 }),
historyAgent({ id: "newer", title: "Fix totals", activeAt: 3, archivedAt: 4 }),
],
activeIds: NO_ACTIVE,
});
expect(workspace).toMatchObject({
key: "host-a:ws-1",
serverId: "host-a",
workspaceId: "ws-1",
name: "Billing cleanup",
projectName: "payments",
projectKey: "prj-payments",
branch: "billing-cleanup",
archivedAt: minutes(5),
});
expect(workspace.agents.map((agent) => agent.id)).toEqual(["newer", "older"]);
});
it("leaves out workspaces that are still active on their host", () => {
const workspaces = groupArchivedWorkspaces({
agents: [historyAgent({ id: "a", activeAt: 1, archivedAt: 2 })],
activeIds: new Map([["host-a", new Set(["ws-1"])]]),
});
expect(workspaces).toEqual([]);
});
it("leaves out an inactive workspace none of whose agents were archived", () => {
const workspaces = groupArchivedWorkspaces({
agents: [historyAgent({ id: "a", activeAt: 1, archivedAt: null })],
activeIds: NO_ACTIVE,
});
expect(workspaces).toEqual([]);
});
it("keeps the same workspace ID on two hosts apart and lists the latest archive first", () => {
const workspaces = groupArchivedWorkspaces({
agents: [
historyAgent({ id: "a", serverId: "host-a", activeAt: 1, archivedAt: 2 }),
historyAgent({ id: "b", serverId: "host-b", activeAt: 1, archivedAt: 9 }),
],
activeIds: NO_ACTIVE,
});
expect(workspaces.map((workspace) => workspace.key)).toEqual(["host-b:ws-1", "host-a:ws-1"]);
});
it("skips agents with no workspace and names an unnamed workspace after its folder", () => {
const workspaces = groupArchivedWorkspaces({
agents: [
historyAgent({ id: "loose", workspaceId: null, activeAt: 1, archivedAt: 2 }),
historyAgent({
id: "a",
workspaceName: null,
branch: null,
cwd: "/repos/receipts",
activeAt: 1,
archivedAt: 2,
}),
],
activeIds: NO_ACTIVE,
});
expect(workspaces).toHaveLength(1);
expect(workspaces[0]).toMatchObject({ name: "receipts", branch: null });
});
});
@@ -1,87 +0,0 @@
import type { AggregatedAgent } from "@/hooks/use-aggregated-agents";
export interface ArchivedWorkspaceAgent {
id: string;
title: string | null;
provider: string;
}
/** A workspace the user archived, as agent history describes it. */
export interface ArchivedWorkspace {
/** `serverId:workspaceId` */
key: string;
serverId: string;
workspaceId: string;
name: string;
projectName: string | null;
/** The host's project ID. */
projectKey: string | null;
branch: string | null;
/** The latest archive time among its agents. */
archivedAt: Date;
/** Its agents in this history page, most recently active first. Never empty. */
agents: ArchivedWorkspaceAgent[];
}
/** Which workspaces each host still lists as active. */
export type ActiveWorkspaceIdsByServer = ReadonlyMap<string, ReadonlySet<string>>;
function lastPathSegment(path: string): string {
const parts = path.split(/[\\/]/).filter(Boolean);
return parts[parts.length - 1] ?? path;
}
function checkoutBranch(agent: AggregatedAgent): string | null {
const checkout = agent.projectPlacement?.checkout;
return checkout?.isGit ? checkout.currentBranch : null;
}
/**
* Folds agent history into one entry per archived workspace, newest archive first. A
* workspace its host still lists is active, so it is left out. So is an inactive workspace
* with no archived agent: the user never put it away (a background workspace, for example).
*/
export function groupArchivedWorkspaces(input: {
agents: readonly AggregatedAgent[];
activeIds: ActiveWorkspaceIdsByServer;
}): ArchivedWorkspace[] {
const byKey = new Map<string, ArchivedWorkspace & { archivedAtOrNull: Date | null }>();
const newestFirst = [...input.agents].sort(
(left, right) => right.lastActivityAt.getTime() - left.lastActivityAt.getTime(),
);
for (const agent of newestFirst) {
const workspaceId = agent.workspaceId;
if (!workspaceId || input.activeIds.get(agent.serverId)?.has(workspaceId)) continue;
const key = `${agent.serverId}:${workspaceId}`;
const archivedAt = agent.archivedAt ? new Date(agent.archivedAt) : null;
const summary = { id: agent.id, title: agent.title ?? null, provider: agent.provider };
const existing = byKey.get(key);
if (existing) {
existing.agents.push(summary);
if (archivedAt && (!existing.archivedAtOrNull || archivedAt > existing.archivedAtOrNull)) {
existing.archivedAtOrNull = archivedAt;
}
continue;
}
// The most recent agent describes the workspace: it saw its latest name and branch.
const placement = agent.projectPlacement;
byKey.set(key, {
key,
serverId: agent.serverId,
workspaceId,
name: placement?.workspaceName || lastPathSegment(agent.cwd),
projectName: placement?.projectName ?? null,
projectKey: placement?.projectKey ?? null,
branch: checkoutBranch(agent),
archivedAt: archivedAt ?? new Date(0),
archivedAtOrNull: archivedAt,
agents: [summary],
});
}
const archived: ArchivedWorkspace[] = [];
for (const { archivedAtOrNull, ...workspace } of byKey.values()) {
if (archivedAtOrNull) archived.push({ ...workspace, archivedAt: archivedAtOrNull });
}
return archived.sort((left, right) => right.archivedAt.getTime() - left.archivedAt.getTime());
}
@@ -1,83 +0,0 @@
import { useMemo } from "react";
import { useShallow } from "zustand/shallow";
import { useAgentHistory } from "@/hooks/use-agent-history";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import {
groupArchivedWorkspaces,
type ActiveWorkspaceIdsByServer,
type ArchivedWorkspace,
} from "./group";
const SEARCH_DEBOUNCE_MS = 200;
const NO_WORKSPACES: Record<string, ReadonlyMap<string, WorkspaceDescriptor>> = {};
const NO_ARCHIVED_WORKSPACES: ArchivedWorkspace[] = [];
export interface ArchivedWorkspaceSearch {
/** Newest archive first. Empty without a query. */
workspaces: ArchivedWorkspace[];
/**
* The host matched these for the current query. Its search forgives typos, so its matches
* can include rows the caller cannot match itself. False while the previous query's
* results stand in for the next one; those rows must still match the query on their own.
*/
matchedByHost: boolean;
/** Still searching for the current query, debounce included. */
pending: boolean;
}
function useActiveWorkspaceIds(enabled: boolean): ActiveWorkspaceIdsByServer {
// Each host's workspace map is replaced only when its workspaces change, so this does not
// re-render on agent activity.
const workspacesByServer = useSessionStore(
useShallow((state) =>
enabled
? Object.fromEntries(
Object.entries(state.sessions).map(([serverId, session]) => [
serverId,
session.workspaces,
]),
)
: NO_WORKSPACES,
),
);
return useMemo(
() =>
new Map(
Object.entries(workspacesByServer).map(([serverId, workspaces]) => [
serverId,
new Set(workspaces.keys()),
]),
),
[workspacesByServer],
);
}
/**
* Archived workspaces whose name, project, branch, or agent titles match `query`, searched on
* every host that supports history search. Hosts that predate it contribute nothing.
*/
export function useArchivedWorkspaceSearch(
query: string,
options: { enabled: boolean },
): ArchivedWorkspaceSearch {
const trimmed = query.trim();
const search = useDebouncedValue(trimmed, SEARCH_DEBOUNCE_MS);
const enabled = options.enabled && trimmed.length > 0;
const activeIds = useActiveWorkspaceIds(enabled);
const history = useAgentHistory({
search,
enabled: enabled && search.length > 0,
searchableHostsOnly: true,
keepPreviousResults: true,
});
const workspaces = useMemo(
() =>
enabled
? groupArchivedWorkspaces({ agents: history.agents, activeIds })
: NO_ARCHIVED_WORKSPACES,
[activeIds, enabled, history.agents],
);
const matchedByHost = search === trimmed && !history.isLoading && !history.isPreviousResults;
return { workspaces, matchedByHost, pending: enabled && !matchedByHost };
}
@@ -39,21 +39,6 @@ function createDeferred<T>() {
return { promise, resolve, reject };
}
/**
* Resolves a pending lookup and waits until React Query has delivered the result. It delivers on a
* timer, which would otherwise fire after the test, when jsdom is gone.
*/
async function resolveLookupAndDeliver(
lookup: ReturnType<typeof createDeferred<DirectorySuggestionResult>>,
result: DirectorySuggestionResult,
): Promise<void> {
await act(async () => {
lookup.resolve(result);
await lookup.promise;
await new Promise((resolve) => setTimeout(resolve, 0));
});
}
interface OpenedFile {
target: InlinePathTarget;
disposition: OpenFileDisposition;
@@ -337,12 +322,11 @@ describe("useFileLink", () => {
act(() => {
result.current.setWorkspaceRoot("/Users/test/other");
});
await resolveLookupAndDeliver(
deferred,
resolvedSuggestions([{ path: "docs/dumm.md", kind: "file" }]),
);
deferred.resolve(resolvedSuggestions([{ path: "docs/dumm.md", kind: "file" }]));
expect(getDirectorySuggestions).toHaveBeenCalledTimes(1);
await waitFor(() => {
expect(getDirectorySuggestions).toHaveBeenCalledTimes(1);
});
expect(openedFiles).toEqual([]);
});
});
@@ -1,71 +0,0 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { persistAttachmentFromBlob } from "@/attachments/service";
import type { AttachmentMetadata } from "@/attachments/types";
import { type AttachmentPreviewUrl, useAttachmentPreviewUrl } from "./use-attachment-preview-url";
let root: Root;
let container: HTMLDivElement;
let latest: AttachmentPreviewUrl | null = null;
function PreviewProbe({ attachment }: { attachment: AttachmentMetadata | null }) {
latest = useAttachmentPreviewUrl(attachment);
return null;
}
async function render(attachment: AttachmentMetadata | null) {
await act(async () => root.render(<PreviewProbe attachment={attachment} />));
}
async function waitForReady(): Promise<string> {
await vi.waitFor(() => expect(latest?.status).toBe("ready"));
if (latest?.status !== "ready") throw new Error("preview never resolved");
return latest.url;
}
beforeEach(() => {
vi.stubGlobal("React", React);
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
latest = null;
});
afterEach(() => {
act(() => root.unmount());
container.remove();
vi.unstubAllGlobals();
});
it("never hands back a URL it already released when the same attachment returns", async () => {
const attachment = await persistAttachmentFromBlob({
blob: new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" }),
mimeType: "image/png",
fileName: "shot.png",
});
await render(attachment);
const released = await waitForReady();
await render(null);
await render(attachment);
expect(latest).not.toEqual({ status: "ready", url: released });
expect(await waitForReady()).not.toBe(released);
});
it("retries a failed attachment from loading when it returns", async () => {
const stored = await persistAttachmentFromBlob({
blob: new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" }),
mimeType: "image/png",
fileName: "shot.png",
});
const missing = { ...stored, id: "missing-attachment", storageKey: "missing-attachment" };
await render(missing);
await vi.waitFor(() => expect(latest?.status).toBe("failed"));
await render(null);
await render(missing);
expect(latest).toEqual({ status: "loading" });
});
@@ -2,75 +2,62 @@ import { useEffect, useRef, useState } from "react";
import type { AttachmentMetadata } from "@/attachments/types";
import { releaseAttachmentPreviewUrl, resolveAttachmentPreviewUrl } from "@/attachments/service";
export type AttachmentPreviewUrl =
| { status: "loading" }
| { status: "ready"; url: string }
| { status: "failed" };
const LOADING: AttachmentPreviewUrl = { status: "loading" };
const FAILED: AttachmentPreviewUrl = { status: "failed" };
function attachmentKey(attachment: AttachmentMetadata | null | undefined): string | null {
if (!attachment) return null;
return [attachment.id, attachment.storageType, attachment.storageKey, attachment.mimeType].join(
"\u0000",
);
}
/**
* Resolves a displayable URL for a stored attachment. Stays `loading` until the URL for the
* current attachment resolves, so a caller never shows a failure, or the previous attachment's
* URL, while the next one is still resolving. A missing attachment stays `loading`.
*/
export function useAttachmentPreviewUrl(
attachment: AttachmentMetadata | null | undefined,
): AttachmentPreviewUrl {
const [resolved, setResolved] = useState<{
key: string;
preview: AttachmentPreviewUrl;
} | null>(null);
): string | null {
const [url, setUrl] = useState<string | null>(null);
const activeAttachmentRef = useRef<AttachmentMetadata | null>(null);
const attachmentRef = useRef(attachment);
attachmentRef.current = attachment;
const key = attachmentKey(attachment);
const id = attachment?.id;
const storageType = attachment?.storageType;
const storageKey = attachment?.storageKey;
const mimeType = attachment?.mimeType;
useEffect(() => {
const current = attachmentRef.current;
if (!current || key === null) {
return;
}
let disposed = false;
let currentUrl: string | null = null;
const current = attachmentRef.current;
activeAttachmentRef.current = current ?? null;
if (!current) {
setUrl(null);
return;
}
void (async () => {
try {
const url = await resolveAttachmentPreviewUrl(current);
const resolved = await resolveAttachmentPreviewUrl(current);
if (disposed) {
await releaseAttachmentPreviewUrl({ attachment: current, url });
await releaseAttachmentPreviewUrl({ attachment: current, url: resolved });
return;
}
currentUrl = url;
setResolved({ key, preview: { status: "ready", url } });
currentUrl = resolved;
setUrl(resolved);
} catch (error) {
console.error("[attachments] Failed to resolve preview URL", {
attachmentId: current.id,
error,
});
if (!disposed) {
setResolved({ key, preview: FAILED });
setUrl(null);
}
}
})();
return () => {
disposed = true;
if (currentUrl) {
void releaseAttachmentPreviewUrl({ attachment: current, url: currentUrl });
const activeAttachment = activeAttachmentRef.current;
if (!currentUrl || !activeAttachment) {
return;
}
// A result lives only as long as its lookup. Kept, the same attachment coming back would
// read a released URL, or an old failure, until the next lookup lands.
setResolved((previous) => (previous?.key === key ? null : previous));
void releaseAttachmentPreviewUrl({
attachment: activeAttachment,
url: currentUrl,
});
};
}, [key]);
}, [id, storageType, storageKey, mimeType]);
return resolved !== null && resolved.key === key ? resolved.preview : LOADING;
return url;
}
@@ -1,18 +1,18 @@
import { memo, useCallback, useMemo, useState } from "react";
import { Text, View } from "react-native";
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import { ExternalLink, Gift } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
AdaptiveModalSheet,
SheetHeaderIconButton,
type SheetHeader,
} from "@/components/adaptive-modal-sheet";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { MarkdownRenderer } from "@/components/markdown/renderer";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import {
iconButtonChromeGlyphSize,
iconButtonChromeStyle,
} from "@/components/ui/icon-button-chrome";
import { StatusBadge } from "@/components/ui/status-badge";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { resolveAppVersion } from "@/utils/app-version";
@@ -28,9 +28,12 @@ import {
const WEBSITE_CHANGELOG_URL = "https://paseo.sh/changelog";
const ThemedGift = withUnistyles(Gift);
const ThemedExternalLink = withUnistyles(ExternalLink);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const sheetLeadingIcon = <ThemedGift size={ICON_SIZE.md} uniProps={mutedColorMapping} />;
const websiteButtonStyle = (state: PressableStateCallbackType & { hovered?: boolean }) =>
iconButtonChromeStyle({ size: "large", state });
interface ChangelogSheetProps {
visible: boolean;
@@ -51,12 +54,19 @@ export function ChangelogSheet({ visible, onClose }: ChangelogSheetProps) {
title: t("changelog.title"),
leading: sheetLeadingIcon,
actions: (
<SheetHeaderIconButton
icon={ExternalLink}
label={t("changelog.openWebsite")}
<Pressable
onPress={handleOpenWebsite}
hitSlop={8}
style={websiteButtonStyle}
accessibilityRole="button"
accessibilityLabel={t("changelog.openWebsite")}
testID="changelog-open-website"
/>
>
<ThemedExternalLink
size={iconButtonChromeGlyphSize("large")}
uniProps={mutedColorMapping}
/>
</Pressable>
),
}),
[handleOpenWebsite, t],
+293 -410
View File
@@ -24,12 +24,10 @@ import {
useSyncExternalStore,
} from "react";
import { useTranslation } from "react-i18next";
import { Check, ChevronRight } from "lucide-react-native";
import { Check, ChevronRight, Folder, X } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { BottomSheetFlatList, type BottomSheetFlatListMethods } from "@gorhom/bottom-sheet";
import { resolveAgentLabel } from "@/agent-presentation";
import { useArchivedWorkspaceSearch, type ArchivedWorkspace } from "@/archived-workspaces";
import { ArchivedBadge } from "@/components/archived-badge";
import { useAgentDescriptor, resolveAgentLabel } from "@/agent-presentation";
import { StatusIcon } from "@/components/status-icon";
import { useWorkspaceStatus } from "@/workspace-status";
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
@@ -37,14 +35,12 @@ import type { Theme } from "@/styles/theme";
import { HighlightedText, type HighlightedTextProps } from "@/components/ui/highlighted-text";
import { findHighlightRanges } from "@/components/ui/highlighted-text-segments";
import { MaterialFileIcon } from "@/components/material-file-icon";
import { useProviderIcon } from "@/components/provider-icons";
import { ProjectIconView } from "@/components/project-icon-view";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { Shortcut } from "@/components/ui/shortcut";
import {
IsolatedBottomSheetModal,
@@ -52,20 +48,18 @@ import {
} from "@/components/ui/isolated-bottom-sheet-modal";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { useAggregatedAgents, type AggregatedAgent } from "@/hooks/use-aggregated-agents";
import { useAggregatedAgents } from "@/hooks/use-aggregated-agents";
import { useProjects } from "@/hooks/use-projects";
import { useTimeAgo } from "@/hooks/use-time-ago";
import { createProjectIconTarget } from "@/projects/icon-target";
import { useProjectIcons } from "@/projects/icons";
import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root";
import { useHostRuntimeConnectionStatuses, useHosts } from "@/runtime/host-runtime";
import { useHydratedWorkspaceServerIds } from "@/stores/session-store-hooks";
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
import { useHosts } from "@/runtime/host-runtime";
import {
navigateToWorkspace,
useActiveWorkspaceSelection,
} from "@/stores/navigation-active-workspace-store";
useKeyboardShortcutsStore,
type CommandCenterScope,
} from "@/stores/keyboard-shortcuts-store";
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
import {
clearCommandCenterFocusRestoreElement,
@@ -73,8 +67,8 @@ import {
} from "@/utils/command-center-focus-restore";
import { focusWithRetries } from "@/utils/web-focus";
import { navigateToAgent } from "@/utils/navigate-to-agent";
import { shortenPath } from "@/utils/shorten-path";
import { projectIconPlaceholderLabelFromDisplayName } from "@/utils/project-display-name";
import { getProjectSummaryForHostProject } from "@/utils/projects";
import {
COMMAND_CENTER_LINE_HEIGHT,
COMMAND_CENTER_LIST_METRICS,
@@ -82,23 +76,21 @@ import {
type CommandCenterListMetrics,
} from "./list-metrics";
import { useCommandCenterContributions } from "./provider";
import { createWorkspaceRanker } from "./workspace-search";
import { filterAndRankWorkspaces } from "./workspace-search";
import {
buildContributionSections,
filterAndRankBuiltInResults,
joinSubtitleParts,
PINNED_SECTION_BAND,
projectCommandCenterRows,
type CommandCenterAgentResult,
type CommandCenterFileResult,
type CommandCenterListRow,
type CommandCenterResult,
type CommandCenterWorkspaceAgent,
type CommandCenterResultSection,
type CommandCenterSearchFields,
type CommandCenterWorkspaceResult,
} from "./results";
import { buildCommandCenterSections } from "./sections";
import {
availableCommandCenterTabs,
resolveCommandCenterTab,
rotateCommandCenterTab,
type CommandCenterTab,
} from "./tabs";
import { createCommandCenterInteraction, type CommandCenterInteraction } from "./interaction";
import { useWorkspaceFileSearch } from "./workspace-file-search";
@@ -108,16 +100,23 @@ const ThemedBottomSheetTextInput = withUnistyles(TextInput, (theme) => ({
const ThemedTextInput = withUnistyles(TextInput, (theme) => ({
placeholderTextColor: theme.colors.foregroundMuted,
}));
const ThemedFolder = withUnistyles(Folder, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedCheck = withUnistyles(Check, (theme) => ({ color: theme.colors.foreground }));
const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({
color: theme.colors.foregroundMuted,
}));
const ThemedX = withUnistyles(X, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner, (theme) => ({
color: theme.colors.foregroundMuted,
}));
const COMMAND_CENTER_SNAP_POINTS = ["60%", "90%"];
const KEYBOARD_SHOULD_PERSIST_TAPS = "always" as const;
/** `cwd` is not rendered, so a path match must never outrank a match on text the user can see. */
function agentSearchFields(result: CommandCenterAgentResult): CommandCenterSearchFields {
return { visible: [result.title, result.subtitle], hidden: [result.agent.cwd] };
}
function createWorkspaceResultAction(serverId: string, workspaceId: string) {
return () => {
clearCommandCenterFocusRestoreElement();
@@ -125,73 +124,28 @@ function createWorkspaceResultAction(serverId: string, workspaceId: string) {
};
}
function createAgentResultAction(serverId: string) {
return (agentId: string) => {
function createAgentResultAction(serverId: string, agentId: string) {
return () => {
clearCommandCenterFocusRestoreElement();
navigateToAgent({ serverId, agentId });
};
}
const NO_WORKSPACE_AGENTS: readonly CommandCenterWorkspaceAgent[] = [];
/** Each workspace's titled agents, most recent first, keyed `serverId:workspaceId`. */
function groupWorkspaceAgents(
agents: readonly AggregatedAgent[],
): Map<string, CommandCenterWorkspaceAgent[]> {
const byWorkspace = new Map<string, CommandCenterWorkspaceAgent[]>();
const newestFirst = [...agents].sort(
(left, right) => right.lastActivityAt.getTime() - left.lastActivityAt.getTime(),
);
for (const agent of newestFirst) {
const title = resolveAgentLabel(agent.title);
if (!agent.workspaceId || !title) continue;
const key = `${agent.serverId}:${agent.workspaceId}`;
const list = byWorkspace.get(key) ?? [];
list.push({ id: agent.id, title, provider: agent.provider });
byWorkspace.set(key, list);
}
return byWorkspace;
}
function createArchivedAgentAction(serverId: string, workspaceId: string) {
// Opening on an agent with the tab pinned is what offers Unarchive, as History does.
return (agentId: string) => {
clearCommandCenterFocusRestoreElement();
navigateToAgent({ serverId, agentId, workspaceId, pin: true });
};
}
function titledAgents(
agents: readonly { id: string; title: string | null; provider: string }[],
): CommandCenterWorkspaceAgent[] {
return agents.flatMap((agent) => {
const title = resolveAgentLabel(agent.title);
return title ? [{ id: agent.id, title, provider: agent.provider }] : [];
});
}
interface WorkspaceRows {
active: CommandCenterWorkspaceResult[];
archived: CommandCenterWorkspaceResult[];
/** The workspace list has not loaded yet, so rows are still arriving. */
loading: boolean;
}
/**
* Build every workspace row. Deliberately not keyed on `query`: none of this work depends on
* what was typed. Ordering belongs to the workspace ranker, which ranks on every keystroke.
* Archived rows come from the host's history search, so they change with its results.
* Build every pinned row. Deliberately not keyed on `query`: none of this work depends on what
* was typed. Ordering belongs to `filterAndRankBuiltInResults`, which ranks on every keystroke.
*/
function useWorkspaceRows(
open: boolean,
archivedWorkspaces: readonly ArchivedWorkspace[],
): WorkspaceRows {
const previousRows = useRef(new Map<string, CommandCenterWorkspaceResult>());
const { agents, isInitialLoad: agentsLoading } = useAggregatedAgents({ demand: open });
const { projects, isLoading: projectsLoading } = useProjects({ enabled: open });
const hosts = useHosts();
const workspacesArriving = useWorkspacesArriving(open, hosts);
const showHost = hosts.length > 1;
function useBuiltInRows(open: boolean): {
workspaces: CommandCenterWorkspaceResult[];
agents: CommandCenterAgentResult[];
} {
const { t } = useTranslation();
const previousRows = useRef(
new Map<string, CommandCenterAgentResult | CommandCenterWorkspaceResult>(),
);
const { agents } = useAggregatedAgents({ demand: open });
const { projects } = useProjects({ enabled: open });
const showHost = useHosts().length > 1;
const iconTargets = useMemo(
() =>
open
@@ -209,26 +163,24 @@ function useWorkspaceRows(
);
const iconDataByProjectViewKey = useProjectIcons({ projects: iconTargets });
const active = useMemo(() => {
return useMemo(() => {
if (!open) {
previousRows.current.clear();
return [];
return { workspaces: [], agents: [] };
}
// Workspace IDs identify immutable navigation targets. Reuse their callbacks and unchanged
// Built-in IDs identify immutable navigation targets. Reuse their callbacks and unchanged
// row data so a directory update does not invalidate every mounted ResultRow.
const nextRows = new Map<string, CommandCenterWorkspaceResult>();
const preserve = (row: CommandCenterWorkspaceResult): CommandCenterWorkspaceResult => {
const nextRows = new Map<string, CommandCenterAgentResult | CommandCenterWorkspaceResult>();
const preserve = <T extends CommandCenterAgentResult | CommandCenterWorkspaceResult>(
row: T,
): T => {
const previous = previousRows.current.get(row.id);
if (previous) {
row.run = previous.run;
row.openAgent = previous.openAgent;
}
const stable = previous && equal(previous, row) ? previous : row;
if (previous) row.run = previous.run;
const stable = previous && equal(previous, row) ? (previous as T) : row;
nextRows.set(row.id, stable);
return stable;
};
const agentsByWorkspace = groupWorkspaceAgents(agents);
const rows: CommandCenterWorkspaceResult[] = [];
const allWorkspaces: CommandCenterWorkspaceResult[] = [];
for (const project of projects) {
const workspaceProject = {
viewKey: project.viewKey,
@@ -238,11 +190,10 @@ function useWorkspaceRows(
for (const host of project.hosts) {
for (const workspace of host.workspaces) {
if (workspace.archivingAt) continue;
const key = `${host.serverId}:${workspace.id}`;
rows.push(
allWorkspaces.push(
preserve({
kind: "workspace",
id: `workspace:${key}`,
id: `workspace:${host.serverId}:${workspace.id}`,
title: workspace.title ?? workspace.name,
subtitle: joinSubtitleParts([
showHost ? host.serverName : null,
@@ -254,93 +205,66 @@ function useWorkspaceRows(
project: workspaceProject,
changeRequestNumber: workspace.changeRequestNumber,
activityAt: workspace.statusEnteredAt,
agents: agentsByWorkspace.get(key) ?? NO_WORKSPACE_AGENTS,
matchedAgent: null,
archived: false,
background: workspace.background,
run: createWorkspaceResultAction(host.serverId, workspace.id),
openAgent: createAgentResultAction(host.serverId),
}),
);
}
}
}
previousRows.current = nextRows;
return rows;
}, [agents, iconDataByProjectViewKey, open, projects, showHost]);
const archived = useMemo(() => {
const activeIds = new Set(active.map((row) => row.id));
const hostLabels = new Map(hosts.map((host) => [host.serverId, host.label]));
return archivedWorkspaces.flatMap<CommandCenterWorkspaceResult>((workspace) => {
const id = `workspace:${workspace.key}`;
// The host's history can trail its workspace list; the active row wins.
if (activeIds.has(id)) return [];
const project = workspace.projectKey
? getProjectSummaryForHostProject(projects, workspace.serverId, workspace.projectKey)
const workspaceTitleByKey = new Map(
allWorkspaces.map((workspace) => [workspace.id.slice("workspace:".length), workspace.title]),
);
const agentRows = agents.map<CommandCenterAgentResult>((agent) => {
const workspaceTitle = agent.workspaceId
? workspaceTitleByKey.get(`${agent.serverId}:${agent.workspaceId}`)
: undefined;
const projectName = project?.projectName ?? workspace.projectName ?? workspace.name;
const openAgent = createArchivedAgentAction(workspace.serverId, workspace.workspaceId);
const latestAgentId = workspace.agents[0].id;
return [
{
kind: "workspace",
id,
title: workspace.name,
subtitle: joinSubtitleParts([
showHost ? (hostLabels.get(workspace.serverId) ?? workspace.serverId) : null,
projectName,
workspace.branch,
]),
serverId: workspace.serverId,
workspaceId: workspace.workspaceId,
project: {
viewKey: project?.viewKey ?? `archived:${workspace.key}`,
name: projectName,
iconDataUri: project ? (iconDataByProjectViewKey.get(project.viewKey) ?? null) : null,
},
changeRequestNumber: null,
activityAt: workspace.archivedAt,
agents: titledAgents(workspace.agents),
matchedAgent: null,
archived: true,
background: false,
run: () => openAgent(latestAgentId),
openAgent,
},
];
return preserve({
kind: "agent",
id: `agent:${agent.serverId}:${agent.id}`,
agent,
title: resolveAgentLabel(agent.title) ?? t("workspace.tabs.loading"),
subtitle: joinSubtitleParts([
showHost ? agent.serverLabel : null,
workspaceTitle ?? shortenPath(agent.cwd),
]),
activityAt: agent.lastActivityAt,
run: createAgentResultAction(agent.serverId, agent.id),
});
});
}, [active, archivedWorkspaces, hosts, iconDataByProjectViewKey, projects, showHost]);
return {
active,
archived,
// Opening a workspace route loads that workspace before the rest of the directory, so rows
// are no sign that the list is complete.
loading: agentsLoading || projectsLoading || workspacesArriving,
};
previousRows.current = nextRows;
return { workspaces: allWorkspaces, agents: agentRows };
}, [agents, iconDataByProjectViewKey, open, projects, showHost, t]);
}
/**
* An online host's workspaces have not arrived yet. Its agent directory reports ready before
* the workspace snapshot lands, so until then the workspace rows are incomplete.
*/
function useWorkspacesArriving(open: boolean, hosts: readonly { serverId: string }[]): boolean {
const serverIds = useMemo(() => (open ? hosts.map((host) => host.serverId) : []), [hosts, open]);
const connectionStatuses = useHostRuntimeConnectionStatuses(serverIds);
const hydratedServerIds = useHydratedWorkspaceServerIds(serverIds);
return serverIds.some(
(serverId) =>
connectionStatuses.get(serverId) === "online" && !hydratedServerIds.includes(serverId),
);
function useBuiltInSections(open: boolean, query: string): CommandCenterResultSection[] {
const { t } = useTranslation();
const rows = useBuiltInRows(open);
return useMemo(() => {
if (!open) return [];
return [
{
id: "workspaces",
band: PINNED_SECTION_BAND,
rank: 2,
title: t("shell.commandCenter.workspaces"),
results: filterAndRankWorkspaces(rows.workspaces, query),
},
{
id: "agents",
band: PINNED_SECTION_BAND,
rank: 3,
title: t("shell.commandCenter.agents"),
results: filterAndRankBuiltInResults(rows.agents, query, agentSearchFields),
},
];
}, [open, query, rows, t]);
}
interface CommandCenterState {
open: boolean;
/** The tabs on offer, in the order Tab walks them. */
tabs: readonly CommandCenterTab[];
tab: CommandCenterTab;
selectTab(tab: CommandCenterTab): void;
scope: CommandCenterScope;
clearScope(): void;
query: string;
setQuery(query: string): void;
activeId: string | null;
@@ -351,7 +275,7 @@ interface CommandCenterState {
fileSearchError: string | null;
close(): void;
select(result: CommandCenterResult): void;
key(event: { key: string; shiftKey?: boolean }): boolean;
key(key: string): boolean;
}
function useCommandCenterState(
@@ -361,95 +285,62 @@ function useCommandCenterState(
const keyboardActionDispatcher = useKeyboardActionDispatcher();
const { t } = useTranslation();
const open = useKeyboardShortcutsStore((state) => state.commandCenterOpen);
const requestedTab = useKeyboardShortcutsStore((state) => state.commandCenterTab);
const scope = useKeyboardShortcutsStore((state) => state.commandCenterScope);
const setOpen = useKeyboardShortcutsStore((state) => state.setCommandCenterOpen);
const setTab = useKeyboardShortcutsStore((state) => state.setCommandCenterTab);
const setScope = useKeyboardShortcutsStore((state) => state.setCommandCenterScope);
const snapshot = useCommandCenterContributions();
const inputRef = useRef<EditingTextInputHandle>(null);
const previousOpenRef = useRef(open);
const { query, activeId } = useSyncExternalStore(interaction.subscribe, interaction.getSnapshot);
const activeWorkspace = useActiveWorkspaceSelection();
const hasWorkspace = activeWorkspace !== null;
const tabs = useMemo(() => availableCommandCenterTabs({ hasWorkspace }), [hasWorkspace]);
const tab = resolveCommandCenterTab(requestedTab, tabs);
const showBackground = useSidebarViewStore((state) => state.showBackground);
const listsWorkspaces = tab === "all" || tab === "workspaces";
const archivedSearch = useArchivedWorkspaceSearch(query, {
enabled: open && listsWorkspaces,
});
const workspaceRows = useWorkspaceRows(open, archivedSearch.workspaces);
const [rankWorkspaces] = useState(createWorkspaceRanker);
const currentWorkspaceId = activeWorkspace
? `workspace:${activeWorkspace.serverId}:${activeWorkspace.workspaceId}`
: null;
const builtInSections = useBuiltInSections(open, query);
const {
entries: fileSearchEntries,
loading: fileSearchLoading,
error: fileSearchError,
openFile,
} = useWorkspaceFileSearch({
enabled:
open &&
tabs.includes("files") &&
(tab === "files" || (tab === "all" && Boolean(query.trim()))),
enabled: open && (scope === "files" || Boolean(query.trim())),
query,
});
const files = useMemo(
() =>
fileSearchEntries.map<CommandCenterFileResult>((entry) => ({
kind: "file",
id: `file:${entry.path}`,
filePath: entry.path,
title: entry.name,
subtitle: entry.directory,
run: () => openFile(entry.path),
})),
[fileSearchEntries, openFile],
);
const sections = useMemo(
() =>
open
? buildCommandCenterSections({
tab,
query,
rankWorkspaces,
workspaces: workspaceRows.active,
archivedWorkspaces: workspaceRows.archived,
archivedMatchedByHost: archivedSearch.matchedByHost,
showBackground,
currentWorkspaceId,
contributions: snapshot.contributions,
files,
titles: {
recentWorkspaces: t("shell.commandCenter.recentWorkspaces"),
workspaces: t("shell.commandCenter.workspaces"),
files: t("shell.commandCenter.files"),
},
})
: [],
[
archivedSearch.matchedByHost,
currentWorkspaceId,
files,
open,
query,
rankWorkspaces,
showBackground,
snapshot.contributions,
t,
tab,
workspaceRows,
],
const fileSections = useMemo<CommandCenterResultSection[]>(() => {
const results = fileSearchEntries.map<CommandCenterFileResult>((entry) => ({
kind: "file",
id: `file:${entry.path}`,
filePath: entry.path,
title: entry.name,
subtitle: entry.directory,
run: () => openFile(entry.path),
}));
// File rows are matched by the daemon, so they carry no client-side score and cannot be
// relevance-compared against the rows that do. Pinning them keeps the section comparator
// total: band is decided before any score is read.
return [
{
id: "files",
band: PINNED_SECTION_BAND,
rank: 4,
title: t("shell.commandCenter.files"),
results,
},
];
}, [fileSearchEntries, openFile, t]);
const contributionSections = useMemo(
() => buildContributionSections(snapshot.contributions, query),
[query, snapshot.contributions],
);
const projection = useMemo(
() => projectCommandCenterRows(sections, listMetrics),
[listMetrics, sections],
() =>
projectCommandCenterRows(
scope === "files"
? fileSections
: [...contributionSections, ...fileSections, ...builtInSections],
listMetrics,
),
[builtInSections, contributionSections, fileSections, listMetrics, scope],
);
const loading =
fileSearchLoading || (listsWorkspaces && (archivedSearch.pending || workspaceRows.loading));
useLayoutEffect(() => {
interaction.update({ open, tab, query, projection, loading });
}, [interaction, open, tab, query, projection, loading]);
interaction.update({ open, scope, query, projection, loading: fileSearchLoading });
}, [interaction, open, scope, query, projection, fileSearchLoading]);
const close = useCallback(() => setOpen(false), [setOpen]);
const select = useCallback(
@@ -459,29 +350,16 @@ function useCommandCenterState(
},
[setOpen],
);
const selectTab = useCallback(
(next: CommandCenterTab) => {
setTab(next);
// A tab click must not take typing away from the search field.
inputRef.current?.focus();
},
[setTab],
);
const key = useCallback(
(event: { key: string; shiftKey?: boolean }): boolean => {
(pressed: string): boolean => {
if (!open) return false;
const pressed = event.key;
const results = projection.selectableResults;
if (pressed === "Escape") {
close();
return true;
}
if (pressed === "Tab") {
setTab(rotateCommandCenterTab(tab, event.shiftKey ? "previous" : "next", tabs));
return true;
}
if (pressed === "Backspace" && !query.trim() && tab !== "all") {
setTab("all");
if (pressed === "Backspace" && !query.trim() && scope) {
setScope(null);
return true;
}
if (pressed === "Enter") {
@@ -499,10 +377,9 @@ function useCommandCenterState(
projection.selectableResults,
query,
activeId,
tab,
tabs,
scope,
select,
setTab,
setScope,
interaction,
],
);
@@ -528,9 +405,8 @@ function useCommandCenterState(
return {
open,
tabs,
tab,
selectTab,
scope,
clearScope: () => setScope(null),
query,
setQuery: interaction.setQuery,
activeId,
@@ -660,38 +536,55 @@ function SubtitleWithTimestamp({
);
}
/**
* The third line of a workspace that matched only through one of its agents: which agent, so the
* user can tell why the row is here. It starts on the title's rail.
*/
function MatchedAgentLine({
agent,
serverId,
const providerIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
function AgentResultContent({
result,
query,
backdrop,
}: {
agent: CommandCenterWorkspaceAgent;
serverId: string;
result: CommandCenterAgentResult;
query: string;
backdrop: SurfaceBackdrop;
}) {
const ProviderIcon = useProviderIcon(agent.provider, serverId);
const Icon = useMemo(() => withUnistyles(ProviderIcon, providerIconMapping), [ProviderIcon]);
const agent = result.agent;
const descriptor = useAgentDescriptor(
{ kind: "agent", agentId: agent.id },
{ serverId: agent.serverId },
);
const Icon = useMemo(
() => withUnistyles(descriptor.icon, providerIconMapping),
[descriptor.icon],
);
return (
<View style={styles.agentLine} testID="command-center-workspace-agent">
<View style={styles.agentLineIcon}>
<Icon size={12} />
<View style={styles.rowContent} testID={`command-center-agent-${agent.serverId}:${agent.id}`}>
<View style={styles.rowMain}>
<View style={styles.iconSlot}>
<StatusIcon statusBucket={descriptor.statusBucket} size={16} backdrop={backdrop}>
<View accessibilityRole="image" accessibilityLabel={descriptor.subtitle}>
<Icon size={16} />
</View>
</StatusIcon>
</View>
<View style={styles.textContent}>
<QueryHighlightedText
query={query}
text={result.title}
style={styles.title}
numberOfLines={1}
/>
<SubtitleWithTimestamp
query={query}
subtitle={result.subtitle}
activityAt={result.activityAt}
testID="command-center-agent-subtitle"
/>
</View>
</View>
<QueryHighlightedText
query={query}
text={agent.title}
style={[styles.subtitle, styles.subtitleText]}
numberOfLines={1}
/>
</View>
);
}
const providerIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
function WorkspaceResultIcon({
result,
backdrop,
@@ -702,27 +595,24 @@ function WorkspaceResultIcon({
const statusBucket = useWorkspaceStatus(result.serverId, result.workspaceId);
return (
<StatusIcon statusBucket={statusBucket} size={16} backdrop={backdrop}>
<DecorativeProjectIcon project={result.project} />
<View accessibilityElementsHidden importantForAccessibility="no-hide-descendants" aria-hidden>
<WorkspaceProjectIcon project={result.project} />
</View>
</StatusIcon>
);
}
/**
* The same project icon the sidebar's workspace rows lead with: its image, or a lettered square.
* Hidden from assistive tech so the fallback's initial does not prefix the row's name.
*/
function DecorativeProjectIcon({ project }: { project: CommandCenterWorkspaceResult["project"] }) {
/** The same project icon the sidebar's workspace rows lead with: its image, or a lettered square. */
function WorkspaceProjectIcon({ project }: { project: CommandCenterWorkspaceResult["project"] }) {
const initial = projectIconPlaceholderLabelFromDisplayName(project.name).charAt(0).toUpperCase();
return (
<View accessibilityElementsHidden importantForAccessibility="no-hide-descendants" aria-hidden>
<ProjectIconView
iconDataUri={project.iconDataUri}
initial={initial}
projectViewKey={project.viewKey}
size={16}
textStyle={styles.projectIconFallbackText}
/>
</View>
<ProjectIconView
iconDataUri={project.iconDataUri}
initial={initial}
projectViewKey={project.viewKey}
size={16}
textStyle={styles.projectIconFallbackText}
/>
);
}
@@ -760,18 +650,17 @@ function ResultContent({
</View>
);
}
if (result.kind === "agent") {
return <AgentResultContent result={result} query={query} backdrop={backdrop} />;
}
if (result.kind === "workspace") {
const key = result.id.slice("workspace:".length);
return (
<View style={styles.rowContent} testID={`command-center-workspace-${key}`}>
<View style={styles.rowMain}>
{/* Decorative: the fallback icon's initial must not prefix the row's accessible name. */}
<View style={styles.iconSlot}>
{/* An archived workspace runs nothing, so it has no status to show. */}
{result.archived ? (
<DecorativeProjectIcon project={result.project} />
) : (
<WorkspaceResultIcon result={result} backdrop={backdrop} />
)}
<WorkspaceResultIcon result={result} backdrop={backdrop} />
</View>
<View style={styles.textContent}>
<QueryHighlightedText
@@ -786,16 +675,8 @@ function ResultContent({
activityAt={result.activityAt}
testID="command-center-workspace-subtitle"
/>
{result.matchedAgent ? (
<MatchedAgentLine
agent={result.matchedAgent}
serverId={result.serverId}
query={query}
/>
) : null}
</View>
</View>
{result.archived ? <ArchivedBadge /> : null}
</View>
);
}
@@ -880,24 +761,9 @@ function SectionRow({ row }: { row: Extract<CommandCenterListRow, { kind: "secti
}
// Escape arrives without asking; it is registered for `agent.interrupt` anyway.
// Backspace stays off deliberately — on web it returns a tab to All when the field is empty,
// Backspace stays off deliberately — the palette pops its scope with it on web,
// but a registered command would stop the search field deleting text.
const TAB_PLACEHOLDER_KEYS = {
all: "shell.commandCenter.placeholder",
workspaces: "shell.commandCenter.workspacePlaceholder",
files: "shell.commandCenter.filePlaceholder",
actions: "shell.commandCenter.actionPlaceholder",
} as const satisfies Record<CommandCenterTab, string>;
/** The search field names what the tab searches; All names only the kinds on offer. */
function placeholderKey(tab: CommandCenterTab, tabs: readonly CommandCenterTab[]) {
if (tab === "all" && !tabs.includes("files")) {
return "shell.commandCenter.placeholderWithoutFiles";
}
return TAB_PLACEHOLDER_KEYS[tab];
}
export function CommandCenter() {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
@@ -1009,42 +875,22 @@ export function CommandCenter() {
: {}),
scrollEventThrottle: 16,
};
const submit = useCallback(() => state.key({ key: "Enter" }), [state]);
const submit = useCallback(() => state.key("Enter"), [state]);
const handleOverlayKeyDown = useCallback(
(event: KeyboardInputEvent) => {
if (!state.key(event)) return false;
if (!state.key(event.key)) return false;
event.preventDefault();
return true;
},
[state],
);
const setOverlayScope = useOverlayRegistration({
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown", "Tab"],
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
active: state.open,
layer: modalLayer,
onKeyDown: handleOverlayKeyDown,
});
const tabOptions = useMemo<SegmentedControlOption<CommandCenterTab>[]>(
() =>
state.tabs.map((tab) => ({
value: tab,
label: t(`shell.commandCenter.tabs.${tab}`),
testID: `command-center-tab-${tab}`,
})),
[state.tabs, t],
);
const tabs = (
<SegmentedControl
options={tabOptions}
value={state.tab}
onValueChange={state.selectTab}
size="sm"
testID="command-center-tabs"
/>
);
const placeholder = t(placeholderKey(state.tab, state.tabs));
if (showBottomSheet) {
return (
<IsolatedBottomSheetModal
@@ -1064,28 +910,32 @@ export function CommandCenter() {
accessible={false}
>
<OverlayLayerProvider layer={modalLayer}>
<View style={styles.header} testID="command-center-header">
<View style={styles.searchRow}>
<ThemedBottomSheetTextInput
testID="command-center-input"
ref={bottomSheetInputRef}
initialValue={state.query}
variant="bottom-sheet"
onChangeText={state.setQuery}
onSubmitEditing={submit}
placeholder={placeholder}
style={[styles.input, styles.growingInput]}
autoCapitalize="none"
autoCorrect={false}
autoFocus
/>
<FileSearchLoadingIndicator
loading={state.fileSearchLoading}
label={t("shell.commandCenter.searchingFiles")}
/>
</View>
<View style={[styles.bottomSheetHeader, styles.searchRow]} testID="command-center-header">
{state.scope === "files" ? (
<ScopeChip label={t("shell.commandCenter.files")} onRemove={state.clearScope} />
) : null}
<ThemedBottomSheetTextInput
testID="command-center-input"
ref={bottomSheetInputRef}
initialValue={state.query}
variant="bottom-sheet"
onChangeText={state.setQuery}
onSubmitEditing={submit}
placeholder={
state.scope === "files"
? t("shell.commandCenter.filePlaceholder")
: t("shell.commandCenter.placeholder")
}
style={[styles.input, styles.growingInput]}
autoCapitalize="none"
autoCorrect={false}
autoFocus
/>
<FileSearchLoadingIndicator
loading={state.fileSearchLoading}
label={t("shell.commandCenter.searchingFiles")}
/>
</View>
<View style={styles.tabBar}>{tabs}</View>
{fileSearchError}
<BottomSheetFlatList ref={bottomSheetListRef} {...commonListProps} />
</OverlayLayerProvider>
@@ -1099,26 +949,30 @@ export function CommandCenter() {
<View style={styles.overlay}>
<Pressable style={styles.backdrop} onPress={state.close} />
<View ref={setOverlayScope} testID="command-center-panel" style={styles.panel}>
<View style={styles.header} testID="command-center-header">
<View style={styles.searchRow}>
<ThemedTextInput
testID="command-center-input"
ref={state.inputRef}
initialValue={state.query}
onChangeText={state.setQuery}
placeholder={placeholder}
style={[styles.input, styles.growingInput]}
autoCapitalize="none"
autoCorrect={false}
autoFocus
/>
<FileSearchLoadingIndicator
loading={state.fileSearchLoading}
label={t("shell.commandCenter.searchingFiles")}
/>
</View>
<View style={[styles.header, styles.searchRow]} testID="command-center-header">
{state.scope === "files" ? (
<ScopeChip label={t("shell.commandCenter.files")} onRemove={state.clearScope} />
) : null}
<ThemedTextInput
testID="command-center-input"
ref={state.inputRef}
initialValue={state.query}
onChangeText={state.setQuery}
placeholder={
state.scope === "files"
? t("shell.commandCenter.filePlaceholder")
: t("shell.commandCenter.placeholder")
}
style={[styles.input, styles.growingInput]}
autoCapitalize="none"
autoCorrect={false}
autoFocus
/>
<FileSearchLoadingIndicator
loading={state.fileSearchLoading}
label={t("shell.commandCenter.searchingFiles")}
/>
</View>
<View style={styles.tabBar}>{tabs}</View>
{fileSearchError}
<FlatList ref={listRef} {...commonListProps} />
</View>
@@ -1144,6 +998,25 @@ function FileSearchLoadingIndicator({ loading, label }: { loading: boolean; labe
);
}
// The chip sits at the input's own height and type size so it reads as the scope of the field
// rather than a badge dropped into the query. Its 28px matches the input's line box, so showing or
// dropping the scope cannot resize the header.
function ScopeChip({ label, onRemove }: { label: string; onRemove(): void }) {
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={label}
onPress={onRemove}
style={styles.scopeChip}
testID="command-center-files-scope"
>
<ThemedFolder size={14} strokeWidth={2.2} />
<Text style={styles.scopeChipLabel}>{label}</Text>
<ThemedX size={12} strokeWidth={2.2} />
</Pressable>
);
}
const styles = StyleSheet.create((theme) => ({
overlay: {
flex: 1,
@@ -1170,12 +1043,11 @@ const styles = StyleSheet.create((theme) => ({
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
// Below the divider, above the list. The first section label brings its own top gap, so the
// pills sit with equal space above and below. A fixed bar, so switching tabs never moves the
// field or the list.
tabBar: {
bottomSheetHeader: {
paddingHorizontal: theme.spacing[4],
paddingTop: COMMAND_CENTER_SECTION_GAP,
paddingVertical: theme.spacing[3],
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
input: {
fontSize: theme.fontSize.base,
@@ -1186,6 +1058,25 @@ const styles = StyleSheet.create((theme) => ({
growingInput: { flex: 1, minWidth: 0 },
searchRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
fileSearchStatus: { width: 14, height: 14, alignItems: "center", justifyContent: "center" },
scopeChip: {
// Stretching to the row rather than setting a height keeps the chip exactly as tall as the
// input's line box, so showing or dropping the scope can never resize the header.
alignSelf: "stretch",
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
marginRight: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius.md,
borderWidth: 1,
borderColor: theme.colors.borderAccent,
backgroundColor: theme.colors.surface2,
},
scopeChipLabel: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: "500",
},
results: { flex: 1 },
// Sections and rows take their height from list-metrics; these styles only place content in it.
section: { justifyContent: "flex-end" },
@@ -1238,14 +1129,6 @@ const styles = StyleSheet.create((theme) => ({
},
subtitleLine: { flexDirection: "row", minWidth: 0 },
subtitleText: { flexShrink: 1, minWidth: 0 },
agentLine: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
minWidth: 0,
height: COMMAND_CENTER_LINE_HEIGHT.agent,
},
agentLineIcon: { width: 12, alignItems: "center", justifyContent: "center" },
iconSlot: {
width: 16,
height: COMMAND_CENTER_LINE_HEIGHT.singleLine,
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { createCommandCenterInteraction } from "./interaction";
import { projectCommandCenterRows, type CommandCenterFileResult } from "./results";
import type { CommandCenterTab } from "./tabs";
import type { CommandCenterScope } from "@/stores/keyboard-shortcuts-store";
function results(ids = ["a", "b", "c", "d"]) {
return projectCommandCenterRows(
@@ -21,17 +21,17 @@ function results(ids = ["a", "b", "c", "d"]) {
})),
},
],
{ singleLineRow: 40, twoLineRow: 60, threeLineRow: 80, sectionTitle: 20, sectionDivider: 10 },
{ singleLineRow: 40, twoLineRow: 60, sectionTitle: 20, sectionDivider: 10 },
);
}
function setup(options: { tab?: CommandCenterTab; measured?: boolean } = {}) {
function setup(options: { scope?: CommandCenterScope; measured?: boolean } = {}) {
const offsets: number[] = [];
const model = createCommandCenterInteraction((offset) => offsets.push(offset));
const publish = (ids = ["a", "b", "c", "d"], loading = false) =>
model.update({
open: true,
tab: options.tab ?? "all",
scope: options.scope ?? null,
query: model.getSnapshot().query,
projection: results(ids),
loading,
@@ -53,45 +53,6 @@ describe("Command Center interaction", () => {
expect(offsets).toEqual([]);
});
it("follows the first result while results load, so Enter does not run what rendered first", () => {
const { model, publish } = setup();
model.setQuery("");
// Recent workspaces lead All and arrive after the actions below them.
publish(["new-workspace", "settings"], true);
expect(model.getSnapshot().activeId).toBe("new-workspace");
publish(["recent", "new-workspace", "settings"]);
expect(model.getSnapshot().activeId).toBe("recent");
});
it("keeps the selected row when settled results reorder", () => {
const { model, publish } = setup();
expect(model.getSnapshot().activeId).toBe("a");
// Another workspace's agent changed status, so it moves to the top of Recent workspaces.
publish(["b", "a", "c", "d"]);
expect(model.getSnapshot().activeId).toBe("a");
});
it("keeps the selected row when results land above it after the query settled", () => {
const { model, publish } = setup();
model.setQuery("invoice");
// Files arrive while archived workspaces are still being searched.
publish(["file-1", "file-2"], true);
expect(model.getSnapshot().activeId).toBe("file-1");
publish(["archived", "file-1", "file-2"]);
expect(model.getSnapshot().activeId).toBe("archived");
publish(["archived-2", "archived", "file-1", "file-2"]);
expect(model.getSnapshot().activeId).toBe("archived");
});
it("keeps the user's pick while results are still loading", () => {
const { model, publish } = setup();
model.setQuery("q");
publish(["a", "b"], true);
model.move("next");
publish(["z", "a", "b"], true);
expect(model.getSnapshot().activeId).toBe("b");
});
it("reveals only clipped keyboard selections and wraps around", () => {
const { model, offsets } = setup();
expect(model.move("next")).toBe(true);
@@ -159,7 +120,7 @@ describe("Command Center interaction", () => {
});
it("waits for scoped search results instead of revealing the previous query's rows", () => {
const { model, offsets, publish } = setup({ tab: "files" });
const { model, offsets, publish } = setup({ scope: "files" });
model.scrolled(100);
model.setQuery("new");
publish(["a", "b"], true);
@@ -171,7 +132,7 @@ describe("Command Center interaction", () => {
});
it("manual interaction cancels a reveal awaiting search results", () => {
const { model, offsets, publish } = setup({ tab: "files" });
const { model, offsets, publish } = setup({ scope: "files" });
model.setQuery("new");
publish([], true);
model.beginManualScroll();
@@ -192,29 +153,13 @@ describe("Command Center interaction", () => {
expect(offsets).toEqual([]);
});
it("tab changes select the first result and return the list to the top", () => {
it("scope changes reset selection and request a reveal", () => {
const { model, offsets } = setup();
model.move("next");
model.move("next");
model.move("next");
model.scrolled(100);
model.update({ open: true, tab: "files", query: "", projection: results(), loading: false });
model.update({ open: true, scope: "files", query: "", projection: results(), loading: false });
expect(model.getSnapshot().activeId).toBe("a");
expect(offsets.at(-1)).toBe(0);
});
it("tab changes keep the query", () => {
const { model, publish } = setup();
model.setQuery("b");
publish(["b"]);
model.update({
open: true,
tab: "workspaces",
query: "b",
projection: results(["b"]),
loading: false,
});
expect(model.getSnapshot()).toEqual({ query: "b", activeId: "b" });
expect(offsets).toEqual([20, 20]);
});
it("close discards the old query, metrics, and deferred reveal", () => {
@@ -222,7 +167,7 @@ describe("Command Center interaction", () => {
model.setQuery("old");
publish();
model.move("previous");
model.update({ open: false, tab: "all", query: "old", projection: results(), loading: false });
model.update({ open: false, scope: null, query: "old", projection: results(), loading: false });
model.layout(80);
expect(model.getSnapshot()).toEqual({ query: "", activeId: null });
expect(offsets).toEqual([]);
+11 -30
View File
@@ -1,9 +1,9 @@
import type { CommandCenterScope } from "@/stores/keyboard-shortcuts-store";
import {
moveActiveResultId,
preserveActiveResultId,
type CommandCenterListProjection,
} from "./results";
import type { CommandCenterTab } from "./tabs";
interface Snapshot {
query: string;
@@ -12,28 +12,21 @@ interface Snapshot {
interface ResultsInput {
open: boolean;
tab: CommandCenterTab;
scope: CommandCenterScope;
query: string;
projection: CommandCenterListProjection;
/** A source of this query's and tab's results is still loading. */
loading: boolean;
}
/**
* While a query's or tab's results are still loading, the selection follows the first result,
* so Enter right after opening runs what ends up on top rather than whatever rendered first.
* Once they have all loaded, or the user moves the selection, it stays on its row by ID through
* any later reordering. Permission to move the viewport lasts for one user command.
*/
/** Selection persists; permission to move the viewport lasts for one user command. */
export function createCommandCenterInteraction(scrollToOffset: (offset: number) => void) {
let snapshot: Snapshot = { query: "", activeId: null };
const listeners = new Set<() => void>();
let open = false;
let tab: CommandCenterTab = "all";
let scope: CommandCenterScope = null;
let projection: CommandCenterListProjection | null = null;
let loading = false;
let revealPending = false;
let followingFirst = true;
let offset = 0;
let visibleLength = 0;
@@ -45,8 +38,8 @@ export function createCommandCenterInteraction(scrollToOffset: (offset: number)
function reveal() {
if (!open || !revealPending || !projection || visibleLength <= 0) return;
// The Files tab keeps its previous entries while the next query is loading.
if (tab === "files" && loading) return;
// Scoped file search keeps its previous entries while the next query is loading.
if (scope === "files" && loading) return;
if (!snapshot.activeId) {
if (!loading) revealPending = false;
return;
@@ -74,10 +67,9 @@ export function createCommandCenterInteraction(scrollToOffset: (offset: number)
};
},
update(input: ResultsInput) {
const tabChanged = open && input.open && tab !== input.tab;
const resetSelection = input.open && (!open || tabChanged);
const resetSelection = input.open && (!open || scope !== input.scope);
open = input.open;
tab = input.tab;
scope = input.scope;
if (!open) {
projection = null;
revealPending = false;
@@ -88,44 +80,33 @@ export function createCommandCenterInteraction(scrollToOffset: (offset: number)
}
if (resetSelection) {
revealPending = true;
followingFirst = true;
publish({ ...snapshot, activeId: null });
}
// A tab is a different list: it starts at its top, section label included.
if (tabChanged && offset !== 0) {
offset = 0;
scrollToOffset(0);
}
// A query command invalidates the old projection until React supplies its new results.
if (input.query !== snapshot.query) return;
projection = input.projection;
loading = input.loading;
if (tab !== "files" || !loading) {
if (scope !== "files" || !loading) {
publish({
...snapshot,
activeId: followingFirst
? (projection.selectableResults[0]?.id ?? null)
: preserveActiveResultId(snapshot.activeId, projection.selectableResults),
activeId: preserveActiveResultId(snapshot.activeId, projection.selectableResults),
});
if (!loading) followingFirst = false;
}
reveal();
},
setQuery(query: string) {
projection = null;
revealPending = true;
followingFirst = true;
publish({ query, activeId: null });
},
move(direction: "next" | "previous"): boolean {
if (
!open ||
!projection ||
(tab === "files" && loading) ||
(scope === "files" && loading) ||
projection.selectableResults.length === 0
)
return false;
followingFirst = false;
publish({
...snapshot,
activeId: moveActiveResultId(snapshot.activeId, projection.selectableResults, direction),
@@ -16,8 +16,6 @@ export const COMMAND_CENTER_LINE_HEIGHT = {
singleLine: 20,
title: 18,
subtitle: 16,
/** The matched-agent line under a workspace's subtitle. */
agent: 16,
sectionLabel: 16,
} as const;
@@ -28,8 +26,6 @@ const SECTION_DIVIDER_THICKNESS = 1;
export interface CommandCenterListMetrics {
singleLineRow: number;
twoLineRow: number;
/** A workspace row that also names the agent the query matched. */
threeLineRow: number;
/** A section label and the gaps around it. */
sectionTitle: number;
/** The rule between two sections and the gaps around it. */
@@ -41,7 +37,6 @@ function listMetrics(rowInset: number): CommandCenterListMetrics {
return {
singleLineRow: rowInset + line.singleLine + rowInset,
twoLineRow: rowInset + line.title + line.subtitle + rowInset,
threeLineRow: rowInset + line.title + line.subtitle + line.agent + rowInset,
sectionTitle: COMMAND_CENTER_SECTION_GAP + line.sectionLabel + COMMAND_CENTER_SECTION_GAP,
sectionDivider:
COMMAND_CENTER_SECTION_GAP + SECTION_DIVIDER_THICKNESS + COMMAND_CENTER_SECTION_GAP,
+45 -47
View File
@@ -3,6 +3,7 @@ import type { CommandCenterContribution } from "./contributions";
import { COMMAND_CENTER_LIST_METRICS } from "./list-metrics";
import {
buildContributionSections,
filterAndRankBuiltInResults,
joinSubtitleParts,
moveActiveResultId,
PINNED_SECTION_BAND,
@@ -10,7 +11,6 @@ import {
projectCommandCenterRows,
type CommandCenterWorkspaceResult,
} from "./results";
import { createWorkspaceRanker } from "./workspace-search";
function contribution(input: {
id: string;
@@ -118,12 +118,7 @@ function workspace(
project: { viewKey: "project", name: "project", iconDataUri: null },
changeRequestNumber: null,
activityAt,
agents: [],
matchedAgent: null,
archived: false,
background: false,
run: () => undefined,
openAgent: () => undefined,
};
}
@@ -189,40 +184,6 @@ describe("Command Center result projection", () => {
expect(sectionResultIds(buildContributionSections(contributions, "home"))).toEqual(["home"]);
});
it("lists query-only actions without a query when asked to browse them", () => {
const contributions = [
contribution({ id: "settings", group: "actions", groupRank: 0 }),
contribution({ id: "opus", group: "models", groupRank: 1, visibility: "query" }),
];
expect(
sectionResultIds(buildContributionSections(contributions, "", { includeQueryOnly: true })),
).toEqual(["settings", "opus"]);
});
it("gives a workspace row matched through an agent room for its agent line", () => {
const matched = {
...workspace("workspace:matched"),
matchedAgent: { id: "agent", title: "Add receipt emails", provider: "mock" },
};
const projection = projectCommandCenterRows(
[
{
id: "workspaces",
band: PINNED_SECTION_BAND,
rank: 2,
results: [workspace("workspace:plain"), matched],
},
],
metrics,
);
expect(projection.rows.map((row) => row.height)).toEqual([
metrics.twoLineRow,
metrics.threeLineRow,
]);
expect(metrics.threeLineRow).toBeGreaterThan(metrics.twoLineRow);
});
it("preserves active selection by id and falls back to the first result", () => {
const first = workspace("workspace:first");
const second = workspace("workspace:second");
@@ -525,9 +486,25 @@ describe("Command Center query tokenization", () => {
});
});
describe("workspace ranking", () => {
const rank = (rows: readonly CommandCenterWorkspaceResult[], query: string) =>
createWorkspaceRanker()(rows, query).map((row) => row.id);
describe("filterAndRankBuiltInResults", () => {
const visibleOnly = (row: CommandCenterWorkspaceResult) => ({
visible: [row.title, row.subtitle],
hidden: [],
});
it("shows the five most recent rows for an empty query", () => {
const rows = Array.from({ length: 8 }, (_, index) =>
workspace(`w${index}`, `w${index}`, "host", minutesAgo(8 - index)),
);
expect(filterAndRankBuiltInResults(rows, "", visibleOnly).map((row) => row.id)).toEqual([
"w7",
"w6",
"w5",
"w4",
"w3",
]);
});
it("puts the best match first even when it sorts last alphabetically", () => {
const rows = [
@@ -537,7 +514,22 @@ describe("workspace ranking", () => {
];
// Alphabetically this is Alpha, Label, Zebra. "lab des" only matches Label as Design.
expect(rank(rows, "lab des")).toEqual(["c"]);
expect(filterAndRankBuiltInResults(rows, "lab des", visibleOnly).map((row) => row.id)).toEqual([
"c",
]);
});
it("ranks a title match above a match that only the hidden field reached", () => {
const rows = [workspace("hidden-hit", "Unrelated"), workspace("title-hit", "Deploy")];
const fields = (row: CommandCenterWorkspaceResult) =>
row.id === "hidden-hit"
? { visible: [row.title], hidden: ["deploy"] }
: { visible: [row.title], hidden: [] };
expect(filterAndRankBuiltInResults(rows, "deploy", fields).map((row) => row.id)).toEqual([
"title-hit",
"hidden-hit",
]);
});
it("orders rows in the same match tier by recency, not by where the word sits", () => {
@@ -547,7 +539,10 @@ describe("workspace ranking", () => {
workspace("newer", "design the cli interface to expose usage data", "host", minutesAgo(5)),
];
expect(rank(rows, "usage")).toEqual(["newer", "older"]);
expect(filterAndRankBuiltInResults(rows, "usage", visibleOnly).map((row) => row.id)).toEqual([
"newer",
"older",
]);
});
it("keeps a better match tier above a more recent weaker match", () => {
@@ -556,13 +551,16 @@ describe("workspace ranking", () => {
workspace("whole-word", "Usage hover card", "host", minutesAgo(600)),
];
expect(rank(rows, "usage")).toEqual(["whole-word", "subsequence"]);
expect(filterAndRankBuiltInResults(rows, "usage", visibleOnly).map((row) => row.id)).toEqual([
"whole-word",
"subsequence",
]);
});
it("drops a row when one token matches nothing", () => {
const rows = [workspace("a", "Label as Design")];
expect(rank(rows, "lab zzz")).toEqual([]);
expect(filterAndRankBuiltInResults(rows, "lab zzz", visibleOnly)).toEqual([]);
});
});
+51 -48
View File
@@ -1,15 +1,12 @@
import type { AggregatedAgent } from "@/hooks/use-aggregated-agents";
import {
compareMatchScores,
type MatchClass,
type MatchScore,
scoreTextFields,
textFieldsMatchClass,
} from "@getpaseo/protocol/search/text-match";
import type { CommandCenterContribution } from "./contributions";
import type { CommandCenterListMetrics } from "./list-metrics";
/** Sections pinned above every contribution section. */
export const LEADING_SECTION_BAND = -1;
/** Sections that reorder by how well they match the query. */
export const CONTRIBUTION_SECTION_BAND = 0;
/** Sections pinned below every contribution section regardless of match quality. */
@@ -53,13 +50,6 @@ export interface CommandCenterWorkspaceProject {
iconDataUri: string | null;
}
/** An agent a workspace can be found by. Agents are never results of their own. */
export interface CommandCenterWorkspaceAgent {
id: string;
title: string;
provider: string;
}
export interface CommandCenterWorkspaceResult {
kind: "workspace";
id: string;
@@ -70,19 +60,18 @@ export interface CommandCenterWorkspaceResult {
project: CommandCenterWorkspaceProject;
/** PR/MR number backing this workspace, so a number query can match it exactly. */
changeRequestNumber: number | null;
/** Last activity, or when it was archived for an archived workspace. */
activityAt: Date | null;
/** The workspace's agents, most recent first. Part of what the workspace matches on. */
agents: readonly CommandCenterWorkspaceAgent[];
/** The agent the query matched better than the workspace's own text. Drawn as a third line. */
matchedAgent: CommandCenterWorkspaceAgent | null;
archived: boolean;
/** Started by automation rather than the user. Found by a query, never listed as recent. */
background: boolean;
/** Opens the workspace and lets its default tab selection apply. */
run(): void;
/** Opens the workspace on this agent's tab. */
openAgent(agentId: string): void;
}
export interface CommandCenterAgentResult {
kind: "agent";
id: string;
agent: AggregatedAgent;
title: string;
subtitle: string;
activityAt: Date | null;
run(): void;
}
export interface CommandCenterFileResult {
@@ -105,12 +94,13 @@ export interface CommandCenterContributionResult {
export type CommandCenterResult =
| CommandCenterWorkspaceResult
| CommandCenterAgentResult
| CommandCenterFileResult
| CommandCenterContributionResult;
export interface CommandCenterResultSection {
id: string;
/** LEADING, CONTRIBUTION or PINNED_SECTION_BAND. Compared before anything else. */
/** CONTRIBUTION_SECTION_BAND or PINNED_SECTION_BAND. Compared before anything else. */
band: number;
rank: number;
title?: string;
@@ -172,14 +162,6 @@ export function scoreSearchFields(
return match ? { fieldRank: KEYWORD_FIELD_RANK, match } : null;
}
/** How closely the query matched the fields; see `MatchClass`. Null when it does not match. */
export function searchFieldsMatchClass(
query: string,
fields: CommandCenterSearchFields,
): MatchClass | null {
return textFieldsMatchClass(query, [...fields.visible, ...fields.hidden]);
}
/** Join non-empty subtitle parts with " · ", dropping null/undefined/empty. */
export function joinSubtitleParts(parts: readonly (string | null | undefined)[]): string {
return parts.filter((part): part is string => Boolean(part)).join(" · ");
@@ -199,18 +181,12 @@ function contributionSearchFields(
return { visible, hidden: contribution.keywords };
}
/** How many lines of text the row draws, which decides its height. */
function resultLineCount(result: CommandCenterResult): 1 | 2 | 3 {
if (result.kind === "workspace") return result.matchedAgent ? 3 : 2;
if (result.kind === "file") return 1;
/** Whether the row draws a second, subtitle line under its title. */
function hasSubtitleLine(result: CommandCenterResult): boolean {
if (result.kind === "workspace" || result.kind === "agent") return true;
if (result.kind === "file") return false;
const presentation = result.contribution.presentation;
return presentation.kind === "action" && presentation.subtitle ? 2 : 1;
}
function resultHeight(result: CommandCenterResult, metrics: CommandCenterListMetrics): number {
const lines = resultLineCount(result);
if (lines === 3) return metrics.threeLineRow;
return lines === 2 ? metrics.twoLineRow : metrics.singleLineRow;
return presentation.kind === "action" && Boolean(presentation.subtitle);
}
/**
@@ -235,7 +211,10 @@ function resultScore(result: CommandCenterResult): CommandCenterScore | undefine
return result.kind === "contribution" ? result.score : undefined;
}
/** A built-in row that orders by how recently it saw activity. */
/** Rows shown when nothing has been typed, per pinned category. */
const DEFAULT_CATEGORY_RESULT_LIMIT = 5;
/** A built-in row (workspace or agent) that orders by how recently it saw activity. */
export interface CommandCenterRecentRow {
activityAt: Date | null;
}
@@ -256,20 +235,44 @@ export function compareBuiltInScores(left: CommandCenterScore, right: CommandCen
}
/**
* Group contributions into their sections, ranked by the query. `includeQueryOnly` lists the
* contributions that otherwise wait for a query, for a list whose whole job is browsing them.
* Filter and rank already-built rows. Rows in, rows out — building them needs translations,
* navigation callbacks and the project tree, none of which matching cares about, so that stays
* with the caller and this stays testable without mounting React.
*
* Rows rank by `compareBuiltInScores`; rows that rank equally, including every row of an empty
* query, go most recent first.
*/
export function filterAndRankBuiltInResults<Row extends CommandCenterRecentRow>(
rows: readonly Row[],
query: string,
fieldsOf: (row: Row) => CommandCenterSearchFields,
): Row[] {
if (!query.trim()) {
return [...rows].sort(compareByRecency).slice(0, DEFAULT_CATEGORY_RESULT_LIMIT);
}
const scored: { row: Row; score: CommandCenterScore }[] = [];
for (const row of rows) {
const score = scoreSearchFields(query, fieldsOf(row));
if (score) scored.push({ row, score });
}
scored.sort(
(left, right) =>
compareBuiltInScores(left.score, right.score) || compareByRecency(left.row, right.row),
);
return scored.map((entry) => entry.row);
}
export function buildContributionSections(
contributions: readonly CommandCenterContribution[],
query: string,
options: { includeQueryOnly?: boolean } = {},
): CommandCenterResultSection[] {
const groups = new Map<string, MutableCommandCenterResultSection>();
const registryIndexById = new Map<string, number>();
const hasQuery = Boolean(query.trim());
for (const [index, contribution] of contributions.entries()) {
if (contribution.visibility === "query" && !hasQuery && !options.includeQueryOnly) continue;
if (contribution.visibility === "query" && !hasQuery) continue;
let score: CommandCenterScore | undefined;
if (hasQuery) {
// The score is the filter: null means no token found a home, so the row is out.
@@ -348,7 +351,7 @@ export function projectCommandCenterRows(
offset += sectionHeight;
}
for (const result of section.results) {
const height = resultHeight(result, metrics);
const height = hasSubtitleLine(result) ? metrics.twoLineRow : metrics.singleLineRow;
offsets.push(offset);
rowIndexByResultId.set(result.id, rows.length);
rows.push({ kind: "result", key: result.id, result, height });
@@ -1,181 +0,0 @@
import { describe, expect, it } from "vitest";
import type { CommandCenterContribution } from "./contributions";
import type { CommandCenterFileResult, CommandCenterWorkspaceResult } from "./results";
import { COMMAND_CENTER_LIST_METRICS } from "./list-metrics";
import { projectCommandCenterRows } from "./results";
import { buildCommandCenterSections } from "./sections";
import type { CommandCenterTab } from "./tabs";
import { createWorkspaceRanker } from "./workspace-search";
function workspace(
id: string,
options: {
daysAgo?: number;
title?: string;
archived?: boolean;
background?: boolean;
agentTitle?: string;
} = {},
): CommandCenterWorkspaceResult {
return {
kind: "workspace",
id: `workspace:server:${id}`,
serverId: "server",
workspaceId: id,
title: options.title ?? id,
subtitle: "project · main",
project: { viewKey: "project", name: "project", iconDataUri: null },
changeRequestNumber: null,
activityAt: new Date(Date.UTC(2026, 9, 30) - (options.daysAgo ?? 0) * 86_400_000),
agents: options.agentTitle
? [{ id: `${id}-agent`, title: options.agentTitle, provider: "mock" }]
: [],
matchedAgent: null,
archived: options.archived ?? false,
background: options.background ?? false,
run: () => undefined,
openAgent: () => undefined,
};
}
function action(id: string, group: string, visibility: "always" | "query" = "always") {
return {
id,
group,
groupRank: group === "workspace" ? 0 : 1,
rank: 0,
keywords: [],
visibility,
run: () => undefined,
presentation: { kind: "action", title: id, sectionTitle: group },
} satisfies CommandCenterContribution;
}
const file: CommandCenterFileResult = {
kind: "file",
id: "file:src/index.ts",
filePath: "src/index.ts",
title: "index.ts",
subtitle: "src",
run: () => undefined,
};
const workspaces = [
workspace("current", { daysAgo: 0 }),
workspace("payments", { daysAgo: 1, title: "Payments refactor" }),
// Started by automation; more recent than the workspaces below it.
workspace("nightly", { daysAgo: 1.5, title: "Nightly triage", background: true }),
workspace("onboarding", { daysAgo: 2, title: "Onboarding flow", agentTitle: "Add receipts" }),
workspace("docs", { daysAgo: 3, title: "Docs site" }),
workspace("search", { daysAgo: 4, title: "Search ranking" }),
];
const archived = [workspace("billing", { title: "Billing cleanup", archived: true })];
const contributions = [
action("New agent", "workspace"),
action("Settings", "actions"),
action("Group by status", "actions", "query"),
];
function listed(
tab: CommandCenterTab,
query: string,
options: { archivedMatchedByHost?: boolean; showBackground?: boolean } = {},
) {
const sections = buildCommandCenterSections({
tab,
query,
rankWorkspaces: createWorkspaceRanker(),
workspaces,
archivedWorkspaces: query ? archived : [],
archivedMatchedByHost: options.archivedMatchedByHost ?? true,
showBackground: options.showBackground ?? false,
currentWorkspaceId: "workspace:server:current",
contributions,
files: [file],
titles: { recentWorkspaces: "Recent workspaces", workspaces: "Workspaces", files: "Files" },
});
return projectCommandCenterRows(sections, COMMAND_CENTER_LIST_METRICS.desktop).rows.map((row) =>
row.kind === "section" ? `# ${row.title ?? ""}` : row.key,
);
}
describe("command center tabs", () => {
it("All leads with the three most recent workspaces, then actions, before a query", () => {
expect(listed("all", "")).toEqual([
"# Recent workspaces",
"workspace:server:payments",
"workspace:server:onboarding",
"workspace:server:docs",
"# workspace",
"New agent",
"# actions",
"Settings",
]);
});
it("lists background workspaces unqueried only as the sidebar does; a query finds them", () => {
expect(listed("all", "")).not.toContain("workspace:server:nightly");
expect(listed("all", "", { showBackground: true })).not.toContain("workspace:server:nightly");
expect(listed("workspaces", "")).not.toContain("workspace:server:nightly");
expect(listed("workspaces", "", { showBackground: true })).toContain(
"workspace:server:nightly",
);
expect(listed("all", "nightly")).toContain("workspace:server:nightly");
expect(listed("workspaces", "nightly")).toContain("workspace:server:nightly");
});
it("All ranks every kind of result for a query, archived workspaces after active ones", () => {
expect(listed("all", "i")).toEqual(
expect.arrayContaining(["Settings", "file:src/index.ts", "workspace:server:billing"]),
);
const rows = listed("all", "ing");
const workspaceRows = rows.filter((row) => row.startsWith("workspace:"));
expect(workspaceRows.at(-1)).toBe("workspace:server:billing");
expect(rows).not.toContain("# Recent workspaces");
});
it("Workspaces lists every workspace, current included, most recent first", () => {
expect(listed("workspaces", "")).toEqual([
"# Workspaces",
"workspace:server:current",
"workspace:server:payments",
"workspace:server:onboarding",
"workspace:server:docs",
"workspace:server:search",
]);
});
it("Workspaces finds a workspace through its agent and appends archived matches", () => {
expect(listed("workspaces", "receipts")).toEqual([
"# Workspaces",
"workspace:server:onboarding",
"workspace:server:billing",
]);
});
it("keeps archived rows the host did not match for this query only if they match it", () => {
// The previous query's archived results stand in while the next search loads.
expect(listed("workspaces", "receipts", { archivedMatchedByHost: false })).toEqual([
"# Workspaces",
"workspace:server:onboarding",
]);
expect(listed("workspaces", "billing", { archivedMatchedByHost: false })).toEqual([
"# Workspaces",
"workspace:server:billing",
]);
});
it("Files lists only files", () => {
expect(listed("files", "")).toEqual(["# Files", "file:src/index.ts"]);
});
it("Actions lists every action, including those that otherwise wait for a query", () => {
expect(listed("actions", "")).toEqual([
"# workspace",
"New agent",
"# actions",
"Settings",
"Group by status",
]);
});
});
-120
View File
@@ -1,120 +0,0 @@
import type { CommandCenterContribution } from "./contributions";
import {
buildContributionSections,
LEADING_SECTION_BAND,
PINNED_SECTION_BAND,
type CommandCenterFileResult,
type CommandCenterResultSection,
type CommandCenterWorkspaceResult,
} from "./results";
import type { CommandCenterTab } from "./tabs";
import type { WorkspaceRanker } from "./workspace-search";
/**
* How many workspaces All leads with before anything is typed. Background workspaces are left
* out, as the sidebar leaves them out by default.
*/
const RECENT_WORKSPACE_LIMIT = 3;
export interface CommandCenterSectionTitles {
recentWorkspaces: string;
workspaces: string;
files: string;
}
export interface CommandCenterSectionsInput {
tab: CommandCenterTab;
query: string;
rankWorkspaces: WorkspaceRanker;
workspaces: readonly CommandCenterWorkspaceResult[];
/** Archived workspaces the host found for the query. Empty without a query. */
archivedWorkspaces: readonly CommandCenterWorkspaceResult[];
/**
* The host matched the archived workspaces for this exact query. Its search forgives typos,
* so its matches stay even when the client cannot score them. Results from the previous
* query must match on their own.
*/
archivedMatchedByHost: boolean;
/**
* The sidebar's Show background preference. Without a query, Workspaces lists background
* workspaces only when the sidebar does; a query finds them either way.
*/
showBackground: boolean;
/** The open workspace's result ID. Recent workspaces leaves it out: the user is already there. */
currentWorkspaceId: string | null;
contributions: readonly CommandCenterContribution[];
files: readonly CommandCenterFileResult[];
titles: CommandCenterSectionTitles;
}
function recentWorkspacesSection(input: CommandCenterSectionsInput): CommandCenterResultSection {
const recent = input
.rankWorkspaces(input.workspaces, "")
.filter((workspace) => workspace.id !== input.currentWorkspaceId && !workspace.background)
.slice(0, RECENT_WORKSPACE_LIMIT);
return {
id: "recent-workspaces",
band: LEADING_SECTION_BAND,
rank: 0,
title: input.titles.recentWorkspaces,
results: recent,
};
}
/** Active matches first; archived ones are appended, so active rows never move when they land. */
function workspacesSection(input: CommandCenterSectionsInput): CommandCenterResultSection {
const listed =
input.query.trim() || input.showBackground
? input.workspaces
: input.workspaces.filter((workspace) => !workspace.background);
const active = input.rankWorkspaces(listed, input.query);
const archived = input.query.trim()
? input.rankWorkspaces(input.archivedWorkspaces, input.query, {
keepUnmatched: input.archivedMatchedByHost,
})
: [];
return {
id: "workspaces",
band: PINNED_SECTION_BAND,
rank: 2,
title: input.titles.workspaces,
results: [...active, ...archived],
};
}
function filesSection(input: CommandCenterSectionsInput): CommandCenterResultSection {
// File rows are matched by the daemon, so they carry no client-side score and cannot be
// relevance-compared against the rows that do. Pinning them keeps the section comparator
// total: band is decided before any score is read.
return {
id: "files",
band: PINNED_SECTION_BAND,
rank: 4,
title: input.titles.files,
results: input.files,
};
}
/**
* The sections a tab shows. All mixes every kind and leads with recent workspaces until
* something is typed; every other tab lists everything of its one kind.
*/
export function buildCommandCenterSections(
input: CommandCenterSectionsInput,
): CommandCenterResultSection[] {
switch (input.tab) {
case "all": {
const actions = buildContributionSections(input.contributions, input.query);
if (!input.query.trim()) return [recentWorkspacesSection(input), ...actions];
return [...actions, workspacesSection(input), filesSection(input)];
}
case "workspaces":
return [workspacesSection(input)];
case "files":
return [filesSection(input)];
case "actions":
return buildContributionSections(input.contributions, input.query, {
includeQueryOnly: true,
});
}
}
@@ -1,43 +0,0 @@
import { describe, expect, it } from "vitest";
import {
availableCommandCenterTabs,
resolveCommandCenterTab,
rotateCommandCenterTab,
type CommandCenterTab,
} from "./tabs";
const IN_WORKSPACE = availableCommandCenterTabs({ hasWorkspace: true });
const NO_WORKSPACE = availableCommandCenterTabs({ hasWorkspace: false });
function walk(available: readonly CommandCenterTab[], direction: "next" | "previous") {
const walked: CommandCenterTab[] = ["all"];
for (let step = 0; step < available.length; step += 1) {
walked.push(rotateCommandCenterTab(walked[walked.length - 1], direction, available));
}
return walked;
}
describe("command center tabs", () => {
it("walks All, Workspaces, Files, Actions in a workspace and wraps", () => {
expect(walk(IN_WORKSPACE, "next")).toEqual(["all", "workspaces", "files", "actions", "all"]);
expect(walk(IN_WORKSPACE, "previous")).toEqual([
"all",
"actions",
"files",
"workspaces",
"all",
]);
});
it("offers no Files tab outside a workspace, and Tab skips it", () => {
expect(NO_WORKSPACE).toEqual(["all", "workspaces", "actions"]);
expect(walk(NO_WORKSPACE, "next")).toEqual(["all", "workspaces", "actions", "all"]);
expect(walk(NO_WORKSPACE, "previous")).toEqual(["all", "actions", "workspaces", "all"]);
});
it("opens a requested tab only when it is on offer", () => {
expect(resolveCommandCenterTab("files", IN_WORKSPACE)).toBe("files");
expect(resolveCommandCenterTab("files", NO_WORKSPACE)).toBe("all");
expect(resolveCommandCenterTab("actions", NO_WORKSPACE)).toBe("actions");
});
});
-39
View File
@@ -1,39 +0,0 @@
/**
* The command center's tabs, in the order Tab walks them. All shows every kind of result; each
* other tab shows one kind.
*/
const COMMAND_CENTER_TABS = ["all", "workspaces", "files", "actions"] as const;
export type CommandCenterTab = (typeof COMMAND_CENTER_TABS)[number];
/**
* The tabs on offer, in the order Tab walks them. Files searches the open workspace, so it is
* offered only when a workspace is open; without one, All lists no files either.
*/
export function availableCommandCenterTabs(context: {
hasWorkspace: boolean;
}): readonly CommandCenterTab[] {
return context.hasWorkspace
? COMMAND_CENTER_TABS
: COMMAND_CENTER_TABS.filter((tab) => tab !== "files");
}
/** The tab to show for a requested one: itself when on offer, otherwise All. */
export function resolveCommandCenterTab(
requested: CommandCenterTab,
available: readonly CommandCenterTab[],
): CommandCenterTab {
return available.includes(requested) ? requested : "all";
}
/** The available tab after (or before) `tab`, wrapping at either end. */
export function rotateCommandCenterTab(
tab: CommandCenterTab,
direction: "next" | "previous",
available: readonly CommandCenterTab[],
): CommandCenterTab {
const index = available.indexOf(tab);
const delta = direction === "next" ? 1 : -1;
const count = available.length;
return available[(index + delta + count) % count];
}
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { CommandCenterWorkspaceAgent, CommandCenterWorkspaceResult } from "./results";
import { createWorkspaceRanker } from "./workspace-search";
import type { CommandCenterWorkspaceResult } from "./results";
import { filterAndRankWorkspaces } from "./workspace-search";
function workspace(input: {
id: string;
@@ -8,8 +8,6 @@ function workspace(input: {
subtitle?: string;
changeRequestNumber?: number | null;
activityAt?: Date | null;
agents?: readonly CommandCenterWorkspaceAgent[];
opened?: string[];
}): CommandCenterWorkspaceResult {
return {
kind: "workspace",
@@ -21,24 +19,15 @@ function workspace(input: {
project: { viewKey: "project", name: "project", iconDataUri: null },
changeRequestNumber: input.changeRequestNumber ?? null,
activityAt: input.activityAt ?? null,
agents: input.agents ?? [],
matchedAgent: null,
archived: false,
background: false,
run: () => input.opened?.push("workspace"),
openAgent: (agentId) => input.opened?.push(agentId),
run: () => undefined,
};
}
function agent(id: string, title: string): CommandCenterWorkspaceAgent {
return { id, title, provider: "mock" };
}
function ids(rows: readonly CommandCenterWorkspaceResult[], query: string): string[] {
return createWorkspaceRanker()(rows, query).map((row) => row.id);
return filterAndRankWorkspaces(rows, query).map((row) => row.id);
}
describe("workspace ranking", () => {
describe("filterAndRankWorkspaces", () => {
const subject = workspace({
id: "payments",
title: "Payments refactor",
@@ -107,214 +96,4 @@ describe("workspace ranking", () => {
});
expect(ids([older, newer], "usage")).toEqual(["newer", "older"]);
});
it("lists every workspace most recent first when the query is empty", () => {
const rows = Array.from({ length: 8 }, (_, index) =>
workspace({ id: `w${index}`, activityAt: new Date(2026, 0, index + 1) }),
);
expect(ids(rows, "")).toEqual(["w7", "w6", "w5", "w4", "w3", "w2", "w1", "w0"]);
});
it("matches a workspace through one of its agents and names that agent", () => {
const receipts = agent("agent-receipts", "Add receipt emails");
const row = workspace({
id: "onboarding",
title: "Onboarding flow",
agents: [agent("agent-welcome", "Polish welcome screen"), receipts],
});
const [ranked] = createWorkspaceRanker()([row], "receipt");
expect(ranked.id).toBe("onboarding");
expect(ranked.matchedAgent).toEqual(receipts);
});
it("names no agent when the workspace's own text matched", () => {
const row = workspace({
id: "payments",
title: "Payments refactor",
agents: [agent("agent-payments", "Payments retries")],
});
const [ranked] = createWorkspaceRanker()([row], "payments");
expect(ranked.matchedAgent).toBeNull();
});
it("ranks a workspace's own match above an equally good match through an agent", () => {
const viaAgent = workspace({
id: "via-agent",
title: "Onboarding flow",
activityAt: new Date("2026-10-17T00:00:00Z"),
agents: [agent("a", "Receipt emails")],
});
const own = workspace({
id: "own",
title: "Receipt redesign",
activityAt: new Date("2026-10-01T00:00:00Z"),
});
expect(ids([viaAgent, own], "receipt")).toEqual(["own", "via-agent"]);
});
it("picks the best-matching agent for the line", () => {
const row = workspace({
id: "w",
title: "Onboarding",
agents: [agent("loose", "Reconcile cash receipts later"), agent("exact", "receipts")],
});
const [ranked] = createWorkspaceRanker()([row], "receipts");
expect(ranked.matchedAgent?.id).toBe("exact");
});
it("matches a query split between the workspace's text and an agent's title", () => {
const login = agent("agent-login", "Fix login retries");
const row = workspace({ id: "payments", title: "payments", agents: [login] });
const [ranked] = createWorkspaceRanker()([row], "payments login");
expect(ranked?.id).toBe("payments");
expect(ranked?.matchedAgent).toEqual(login);
});
it("names the agent when it matches better than a loose match on the workspace's text", () => {
const opened: string[] = [];
const login = agent("agent-login", "Fix login retries");
const row = workspace({
id: "long-input",
title: "Long input",
// "login" is a subsequence of "long-input", the weakest kind of match.
subtitle: "Local · paseo · feature/long-input",
agents: [login],
opened,
});
const [ranked] = createWorkspaceRanker()([row], "login");
expect(ranked?.matchedAgent).toEqual(login);
ranked?.run();
expect(opened).toEqual(["agent-login"]);
});
it("keeps a change-request hit on the workspace even when an agent's title names the number", () => {
const opened: string[] = [];
const row = workspace({
id: "payments",
title: "Payments refactor",
changeRequestNumber: 42,
agents: [agent("agent-review", "Address PR 42 review comments")],
opened,
});
const rank = createWorkspaceRanker();
for (const query of ["42", "pr 42", "#42"]) {
const [ranked] = rank([row], query);
expect(ranked?.matchedAgent).toBeNull();
ranked?.run();
}
expect(opened).toEqual(["workspace", "workspace", "workspace"]);
});
it("names no agent while the workspace's own text matches every keystroke contiguously", () => {
const row = workspace({
id: "fix-login-bug",
title: "fix-login-bug",
subtitle: "paseo · fix/login-bug",
agents: [agent("agent-login", "Login page fix")],
});
const rank = createWorkspaceRanker();
for (const query of ["l", "lo", "log", "logi", "login"]) {
expect(rank([row], query)[0]?.matchedAgent).toBeNull();
}
});
it("names no agent whose one-word title matches better than the workspace's whole word", () => {
const row = workspace({
id: "review-queue",
title: "Review queue",
agents: [agent("agent-review", "Review")],
});
expect(createWorkspaceRanker()([row], "review")[0]?.matchedAgent).toBeNull();
});
it("ranks a better match through an agent above a looser match on a workspace's own text", () => {
const loose = workspace({
id: "loose-own",
title: "Long input",
subtitle: "Local · paseo · feature/long-input",
activityAt: new Date("2026-10-17T00:00:00Z"),
});
const viaAgent = workspace({
id: "via-agent",
title: "Auth",
activityAt: new Date("2026-10-01T00:00:00Z"),
agents: [agent("a", "login page")],
});
expect(ids([loose, viaAgent], "login")).toEqual(["via-agent", "loose-own"]);
});
it("keeps a workspace that also matches on its own name first while typing an agent's title", () => {
const ownAndAgent = workspace({
id: "oauth-refactor",
activityAt: new Date("2026-10-17T00:00:00Z"),
agents: [agent("agent-a", "Auth flow fix")],
});
const agentOnly = workspace({
id: "cleanup",
activityAt: new Date("2026-10-01T00:00:00Z"),
agents: [agent("agent-b", "Auth flow fix")],
});
for (const query of ["a", "au", "auth", "auth f", "auth fl", "auth flow"]) {
expect(ids([ownAndAgent, agentOnly], query)).toEqual(["oauth-refactor", "cleanup"]);
}
});
it("ranks a word match on a workspace's name above a newer one that matches only inside a word", () => {
const rank = createWorkspaceRanker();
const authService = workspace({
id: "auth-service",
activityAt: new Date("2026-10-01T00:00:00Z"),
});
const oauthRefactor = workspace({
id: "oauth-refactor",
activityAt: new Date("2026-10-17T00:00:00Z"),
agents: [agent("agent-auth", "Auth flow fix")],
});
const authRows = rank([oauthRefactor, authService], "auth");
expect(authRows.map((row) => row.id)).toEqual(["auth-service", "oauth-refactor"]);
// The row that matched through its agent says so.
expect(authRows[1]?.matchedAgent?.title).toBe("Auth flow fix");
const fixLogin = workspace({ id: "fix-login", activityAt: new Date("2026-10-17T00:00:00Z") });
const prefixedThing = workspace({
id: "prefixed-thing",
activityAt: new Date("2026-10-01T00:00:00Z"),
agents: [agent("agent-fix", "Fix")],
});
const fixRows = rank([prefixedThing, fixLogin], "fix");
expect(fixRows.map((row) => row.id)).toEqual(["fix-login", "prefixed-thing"]);
expect(fixRows[1]?.matchedAgent?.title).toBe("Fix");
});
it("opens the matched agent's tab, and the workspace otherwise", () => {
const opened: string[] = [];
const row = workspace({
id: "w",
title: "Onboarding flow",
agents: [agent("agent-receipts", "Add receipt emails")],
opened,
});
const rank = createWorkspaceRanker();
rank([row], "receipt")[0].run();
rank([row], "onboarding")[0].run();
expect(opened).toEqual(["agent-receipts", "workspace"]);
});
it("returns the same row object across keystrokes while the matched agent holds", () => {
const row = workspace({
id: "w",
title: "Onboarding flow",
agents: [agent("agent-receipts", "Add receipt emails")],
});
const rank = createWorkspaceRanker();
expect(rank([row], "rece")[0]).toBe(rank([row], "receipt")[0]);
expect(rank([row], "onboard")[0]).toBe(row);
});
it("keeps rows the host already matched when asked to, without an agent line", () => {
const row = workspace({ id: "archived", title: "Billing cleanup" });
const rank = createWorkspaceRanker();
expect(rank([row], "billign")).toEqual([]);
expect(rank([row], "billign", { keepUnmatched: true })).toEqual([row]);
});
});
@@ -1,12 +1,9 @@
import { compareMatchClasses, type MatchClass } from "@getpaseo/protocol/search/text-match";
import {
compareBuiltInScores,
compareByRecency,
filterAndRankBuiltInResults,
scoreSearchFields,
searchFieldsMatchClass,
type CommandCenterScore,
type CommandCenterSearchFields,
type CommandCenterWorkspaceAgent,
type CommandCenterWorkspaceResult,
} from "./results";
@@ -27,176 +24,41 @@ function parseChangeRequestQuery(query: string): number | null {
return Number.isSafeInteger(number) ? number : null;
}
/** Within a match class, a match on the workspace's own text ranks ahead of one through an agent. */
const OWN_MATCH = 0;
const AGENT_MATCH = 1;
/** The host matched it (typo-tolerant, server-side) but nothing here does. Archived rows only. */
const HOST_MATCH = 2;
/** How a row matched: its class decides first, its score within the class. */
interface Candidate {
matchClass: MatchClass;
score: CommandCenterScore;
}
interface ScoredWorkspace {
workspace: CommandCenterWorkspaceResult;
via: typeof OWN_MATCH | typeof AGENT_MATCH | typeof HOST_MATCH;
/** The match the row shows, which is also the one it ranks by. */
candidate: Candidate | null;
agent: CommandCenterWorkspaceAgent | null;
score: CommandCenterScore | null;
changeRequestHit: boolean;
}
function ownSearchFields(workspace: CommandCenterWorkspaceResult) {
function searchFields(workspace: CommandCenterWorkspaceResult) {
return { visible: [workspace.title, workspace.subtitle], hidden: [] };
}
/** An agent is found through its own title and its workspace's text together. */
function agentSearchFields(
workspace: CommandCenterWorkspaceResult,
agent: CommandCenterWorkspaceAgent,
) {
return { visible: [workspace.title, workspace.subtitle, agent.title], hidden: [] };
}
function scoreCandidate(query: string, fields: CommandCenterSearchFields): Candidate | null {
const score = scoreSearchFields(query, fields);
const matchClass = searchFieldsMatchClass(query, fields);
return score && matchClass ? { matchClass, score } : null;
}
function compareCandidates(left: Candidate, right: Candidate): number {
return (
compareMatchClasses(left.matchClass, right.matchClass) ||
compareBuiltInScores(left.score, right.score)
);
}
/**
* Change-request hits first, host-only matches last; then match class, the workspace's own text
* ahead of an agent, match quality, and recency.
*/
function compareScoredWorkspaces(left: ScoredWorkspace, right: ScoredWorkspace): number {
if (left.changeRequestHit !== right.changeRequestHit) {
return left.changeRequestHit ? -1 : 1;
}
if ((left.via === HOST_MATCH) !== (right.via === HOST_MATCH)) {
return left.via === HOST_MATCH ? 1 : -1;
}
if (left.candidate && right.candidate) {
const classDelta = compareMatchClasses(left.candidate.matchClass, right.candidate.matchClass);
if (classDelta !== 0) return classDelta;
}
if (left.via !== right.via) return left.via - right.via;
if (left.candidate && right.candidate) {
const scoreDelta = compareBuiltInScores(left.candidate.score, right.candidate.score);
if (left.score && right.score) {
const scoreDelta = compareBuiltInScores(left.score, right.score);
if (scoreDelta !== 0) return scoreDelta;
}
return compareByRecency(left.workspace, right.workspace);
}
interface AgentMatch extends Candidate {
agent: CommandCenterWorkspaceAgent;
}
/**
* The workspace's best-matching agent. Each agent is scored together with the workspace's
* text, so a query split across the two finds it. Agents arrive most recent first, so a tie
* keeps the newer one.
*/
function agentMatch(workspace: CommandCenterWorkspaceResult, query: string): AgentMatch | null {
let best: AgentMatch | null = null;
for (const agent of workspace.agents) {
const candidate = scoreCandidate(query, agentSearchFields(workspace, agent));
if (candidate && (!best || compareCandidates(candidate, best) < 0)) {
best = { agent, ...candidate };
}
}
return best;
}
export type WorkspaceRanker = (
export function filterAndRankWorkspaces(
workspaces: readonly CommandCenterWorkspaceResult[],
query: string,
options?: { keepUnmatched?: boolean },
) => CommandCenterWorkspaceResult[];
): CommandCenterWorkspaceResult[] {
if (!query.trim()) return filterAndRankBuiltInResults(workspaces, query, searchFields);
/**
* Rank workspaces for a query, best match first. A workspace matches on its own title, project,
* branch and change request, or on those together with the title of one of its agents. It is
* matched through an agent only when the agent matches in a closer class than its own text
* (see `MatchClass`), never on a change-request hit; such a match comes back naming that agent,
* and opens it. Each row ranks by the match it shows.
*
* An empty query lists every workspace, most recent first. `keepUnmatched` keeps rows nothing
* here matches, ranked last: archived rows come from the host's own search, which is
* typo-tolerant, so the host is the authority on whether they match.
*
* The ranker remembers the row it made for each workspace and agent, so a row matched through
* the same agent is the same object on every keystroke and its list row does not re-render.
*/
export function createWorkspaceRanker(): WorkspaceRanker {
const viaAgent = new WeakMap<
CommandCenterWorkspaceResult,
Map<string, CommandCenterWorkspaceResult>
>();
function matchedThrough(
workspace: CommandCenterWorkspaceResult,
agent: CommandCenterWorkspaceAgent,
): CommandCenterWorkspaceResult {
let rows = viaAgent.get(workspace);
if (!rows) {
rows = new Map();
viaAgent.set(workspace, rows);
}
let row = rows.get(agent.id);
if (!row) {
row = { ...workspace, matchedAgent: agent, run: () => workspace.openAgent(agent.id) };
rows.set(agent.id, row);
}
return row;
const changeRequestNumber = parseChangeRequestQuery(query);
const matches: ScoredWorkspace[] = [];
for (const workspace of workspaces) {
const score = scoreSearchFields(query, searchFields(workspace));
const changeRequestHit =
changeRequestNumber !== null && workspace.changeRequestNumber === changeRequestNumber;
if (score || changeRequestHit) matches.push({ workspace, score, changeRequestHit });
}
return (workspaces, query, options = {}) => {
if (!query.trim()) return [...workspaces].sort(compareByRecency);
const changeRequestNumber = parseChangeRequestQuery(query);
const matches: ScoredWorkspace[] = [];
for (const workspace of workspaces) {
const changeRequestHit =
changeRequestNumber !== null && workspace.changeRequestNumber === changeRequestNumber;
const own = scoreCandidate(query, ownSearchFields(workspace));
// A change-request hit is the workspace's own answer to the query.
const throughAgent = changeRequestHit ? null : agentMatch(workspace, query);
// An agent is named only when it matches in a closer class than the workspace's own text.
if (
throughAgent &&
(!own || compareMatchClasses(throughAgent.matchClass, own.matchClass) < 0)
) {
matches.push({
workspace,
via: AGENT_MATCH,
candidate: throughAgent,
agent: throughAgent.agent,
changeRequestHit,
});
} else if (own || changeRequestHit) {
matches.push({ workspace, via: OWN_MATCH, candidate: own, agent: null, changeRequestHit });
} else if (options.keepUnmatched) {
matches.push({
workspace,
via: HOST_MATCH,
candidate: null,
agent: null,
changeRequestHit,
});
}
}
matches.sort(compareScoredWorkspaces);
return matches.map((match) =>
match.agent ? matchedThrough(match.workspace, match.agent) : match.workspace,
);
};
matches.sort(compareScoredWorkspaces);
return matches.map((match) => match.workspace);
}
@@ -1,76 +0,0 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { RotateCw, Settings } from "lucide-react-native";
import { afterEach, describe, expect, it } from "vitest";
import {
InlineHeaderView,
SheetHeaderIconButton,
SheetHeaderView,
type SheetHeader,
} from "@/components/adaptive-modal-sheet";
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function noop() {}
const LONG_TITLE =
"A sheet title long enough to fill the whole header row on a phone and then some more";
const header: SheetHeader = {
title: LONG_TITLE,
actions: (
<>
<SheetHeaderIconButton icon={RotateCw} label="Refresh" onPress={noop} testID="refresh" />
<SheetHeaderIconButton icon={Settings} label="Settings" onPress={noop} testID="settings" />
</>
),
};
function mount(node: React.ReactNode) {
container = document.createElement("div");
container.style.width = "390px";
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(node));
}
function rectOf(testID: string): DOMRect {
const found = document.querySelector(`[data-testid="${testID}"]`);
if (!(found instanceof HTMLElement)) throw new Error(`Nothing rendered as ${testID}`);
return found.getBoundingClientRect();
}
/** Each button keeps its own width, follows the previous one and stays inside the row. */
function expectButtonsInRow(testIDs: string[]) {
const row = container?.getBoundingClientRect();
if (!row) throw new Error("Nothing mounted");
const rects = testIDs.map(rectOf);
for (const [index, rect] of rects.entries()) {
expect(rect.width).toBeGreaterThan(0);
expect(rect.right).toBeLessThanOrEqual(row.right + 1);
const previous = rects[index - 1];
if (previous) expect(rect.left).toBeGreaterThanOrEqual(previous.right);
}
}
describe("sheet header with a long title", () => {
it("truncates the title and keeps the actions and Close in place", () => {
mount(<SheetHeaderView header={header} onClose={noop} closeTestID="close" />);
expectButtonsInRow(["refresh", "settings", "close"]);
});
it("does the same in the inline header", () => {
mount(<InlineHeaderView header={header} />);
expectButtonsInRow(["refresh", "settings"]);
});
});
@@ -3,7 +3,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import type { ComponentProps, ReactNode } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { Keyboard, Text, View } from "react-native";
import { Keyboard, Pressable, Text, View } from "react-native";
import type { DimensionValue, StyleProp, ViewProps, ViewStyle } from "react-native";
import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -23,21 +23,13 @@ import {
useIsolatedBottomSheetVisibility,
} from "@/components/ui/isolated-bottom-sheet-modal";
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { ScrollView } from "@/components/ui/scroll-view";
import { isWeb } from "@/constants/platform";
import { useKeyboardVisibility } from "@/hooks/use-keyboard-visibility";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
import { DismissBackdrop } from "@/components/ui/dismiss-backdrop";
import {
IconButtonChromeProvider,
iconButtonChromeGlyphSize,
iconButtonChromeHang,
mutedIconColorMapping,
} from "@/components/ui/icon-button-chrome";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
export { AdaptiveTextInput, type AdaptiveTextInputProps } from "@/components/adaptive-text-input";
// Horizontal indent token shared by the sheet header (title, back arrow,
@@ -46,6 +38,11 @@ export { AdaptiveTextInput, type AdaptiveTextInputProps } from "@/components/ada
// match this padding.
export const SHEET_HORIZONTAL_PADDING_SCALE = 6;
// The header's close button grows outward from its glyph, so the glyph's
// trailing rail is the content inset plus this padding. Rows whose trailing
// glyph should line up with the X must reach the same rail.
export const SHEET_HEADER_CLOSE_PADDING_SCALE = 2;
/** The one height a sheet takes when it shows a whole pane rather than sizing to its content. */
export const FULL_SHEET_SNAP_POINTS = ["92%"];
@@ -67,7 +64,6 @@ export interface SheetHeaderBack {
export interface SheetHeader {
title: string;
titleTestID?: string;
subtitle?: ReactNode;
back?: SheetHeaderBack;
leading?: ReactNode;
@@ -76,10 +72,9 @@ export interface SheetHeader {
}
const SCROLL_CONTENT_GROW = { flexGrow: 1 };
// Header buttons hang by how far their frame reaches past the glyph, so the edge glyphs sit on the
// content rail and a 44pt touch frame does not grow the row.
const HEADER_BUTTON_HANG = iconButtonChromeHang("large");
const ABSOLUTE_FILL_STYLE = { ...StyleSheet.absoluteFill };
const NATIVE_DIALOG_SNAP_POINTS = ["100%"];
const HEADER_ICON_SIZE = 16;
const styles = StyleSheet.create((theme) => ({
nativeDialogSurface: {
@@ -112,24 +107,20 @@ const styles = StyleSheet.create((theme) => ({
borderBottomWidth: 1,
borderBottomColor: theme.colors.surface2,
},
// One height for every sheet header whatever its buttons; a hung 44pt touch frame fits inside it.
headerRow: {
minHeight: 64,
paddingHorizontal: theme.spacing[SHEET_HORIZONTAL_PADDING_SCALE],
paddingVertical: theme.spacing[4],
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
headerBack: {
marginVertical: HEADER_BUTTON_HANG,
marginLeft: HEADER_BUTTON_HANG,
headerBackButton: {
borderRadius: theme.borderRadius.lg,
},
headerLeadingSlot: {
alignItems: "center",
justifyContent: "center",
},
// The title takes the room the buttons leave and truncates; the buttons never shrink.
headerTitleGroup: {
flex: 1,
gap: theme.spacing[1],
@@ -139,17 +130,23 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
},
subtitle: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
headerTrailing: {
headerActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
flexShrink: 0,
marginVertical: HEADER_BUTTON_HANG,
marginRight: HEADER_BUTTON_HANG,
},
closeButton: {
padding: theme.spacing[SHEET_HEADER_CLOSE_PADDING_SCALE],
borderRadius: theme.borderRadius.lg,
},
headerIconButtonInactive: {
opacity: theme.opacity[50],
},
headerIconBox: {
width: HEADER_ICON_SIZE,
height: HEADER_ICON_SIZE,
alignItems: "center",
justifyContent: "center",
},
// Without a header the close button floats over the card's top-right corner.
floatingClose: {
@@ -190,7 +187,6 @@ const styles = StyleSheet.create((theme) => ({
},
inlineTitle: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
color: theme.colors.foreground,
@@ -358,92 +354,71 @@ function SheetContent({ style, children }: { style: StyleProp<ViewStyle>; childr
return <View style={[styles.sheetContent, style]}>{children}</View>;
}
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const ThemedHeaderGlyph = withUnistyles(function HeaderGlyph({
icon: Icon,
size,
color,
}: {
icon: LucideIcon;
size: number;
color?: string;
}) {
return <Icon size={size} color={color} />;
});
/**
* The one icon button of a sheet header: the back arrow, the close X, and every action passed
* through `SheetHeader.actions`. Inside a header it takes the header island's chrome, so all of them
* share one frame, glyph, colour and hover. `busy` swaps the glyph for a spinner and holds presses.
* An icon action in a sheet header's trailing rail, drawn like the Close button so a header's
* actions line up with it at one size. Pass it through `SheetHeader.actions`. Like `Button`, a
* loading action shows a spinner in place of its icon and, like a disabled one, is dimmed and
* cannot be pressed.
*/
export function SheetHeaderIconButton({
icon,
label,
icon: Icon,
accessibilityLabel,
onPress,
busy = false,
loading = false,
disabled = false,
testID,
}: {
icon: LucideIcon;
/** The accessible name, also shown as the desktop tooltip. */
label: string;
accessibilityLabel: string;
onPress: () => void;
busy?: boolean;
loading?: boolean;
disabled?: boolean;
testID?: string;
}) {
const compact = useIsCompactFormFactor();
const glyphSize = iconButtonChromeGlyphSize("large", compact);
const { theme } = useUnistyles();
const inactive = disabled || loading;
const style = useMemo(
() => [styles.closeButton, inactive && styles.headerIconButtonInactive],
[inactive],
);
const accessibilityState = useMemo(
() => ({ disabled: inactive, busy: loading }),
[inactive, loading],
);
return (
<ToolbarButton
label={label}
compact={compact}
disabled={disabled || busy}
<Pressable
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
accessibilityState={accessibilityState}
disabled={inactive}
style={style}
onPress={onPress}
testID={testID}
>
{busy ? (
<ThemedLoadingSpinner size={glyphSize} uniProps={mutedIconColorMapping} />
) : (
<ThemedHeaderGlyph icon={icon} size={glyphSize} uniProps={mutedIconColorMapping} />
)}
</ToolbarButton>
);
}
function SheetHeaderBackButton({ back }: { back: SheetHeaderBack }) {
const { t } = useTranslation();
return (
<View style={styles.headerBack}>
<SheetHeaderIconButton
icon={ArrowLeft}
label={back.accessibilityLabel ?? back.label ?? t("common.actions.back")}
onPress={back.onPress}
testID="sheet-header-back"
/>
</View>
);
}
/** A plain-text header subtitle: one muted line under the title that truncates, never the title. */
export function SheetHeaderSubtitle({ text, testID }: { text: string; testID?: string }) {
return (
<Text style={styles.subtitle} numberOfLines={1} testID={testID}>
{text}
</Text>
{({ pressed }) => {
const color = pressed ? theme.colors.foreground : theme.colors.foregroundMuted;
if (!loading) return <Icon size={HEADER_ICON_SIZE} color={color} />;
// The spinner sits in the icon's box, so the header does not move while it runs.
return (
<View style={styles.headerIconBox}>
<LoadingSpinner size={HEADER_ICON_SIZE} color={color} />
</View>
);
}}
</Pressable>
);
}
export function SheetHeaderView({
header,
onClose,
showCloseButton = true,
testID,
closeTestID,
}: {
header: SheetHeader;
onClose: () => void;
showCloseButton?: boolean;
testID?: string;
closeTestID?: string;
}) {
const { theme } = useUnistyles();
const { t } = useTranslation();
@@ -451,6 +426,8 @@ export function SheetHeaderView({
() => [styles.title, { color: theme.colors.foreground }],
[theme.colors.foreground],
);
const back = header.back;
const handleBackPress = back?.onPress;
const search = header.search;
const handleSearchChange = useCallback(
(value: string) => {
@@ -461,27 +438,40 @@ export function SheetHeaderView({
return (
<View style={styles.headerContainer} testID={testID}>
<IconButtonChromeProvider value="header-island">
<View style={styles.headerRow}>
{header.back ? <SheetHeaderBackButton back={header.back} /> : null}
{header.leading ? <View style={styles.headerLeadingSlot}>{header.leading}</View> : null}
<View style={styles.headerTitleGroup}>
<Text style={titleStyle} numberOfLines={1} testID={header.titleTestID}>
{header.title}
</Text>
{header.subtitle}
</View>
<View style={styles.headerTrailing}>
{header.actions}
<SheetHeaderIconButton
icon={X}
label={t("common.actions.close")}
onPress={onClose}
testID={closeTestID}
/>
</View>
<View style={styles.headerRow}>
{handleBackPress ? (
<Pressable
onPress={handleBackPress}
hitSlop={8}
style={styles.headerBackButton}
accessibilityRole="button"
accessibilityLabel={back?.accessibilityLabel ?? back?.label ?? t("common.actions.back")}
testID="sheet-header-back"
>
{({ pressed }) => (
<ArrowLeft
size={18}
color={pressed ? theme.colors.foreground : theme.colors.foregroundMuted}
/>
)}
</Pressable>
) : null}
{header.leading ? <View style={styles.headerLeadingSlot}>{header.leading}</View> : null}
<View style={styles.headerTitleGroup}>
<Text style={titleStyle} numberOfLines={1}>
{header.title}
</Text>
{header.subtitle}
</View>
</IconButtonChromeProvider>
{header.actions ? <View style={styles.headerActions}>{header.actions}</View> : null}
{showCloseButton ? (
<SheetHeaderIconButton
icon={X}
accessibilityLabel={t("common.actions.close")}
onPress={onClose}
/>
) : null}
</View>
{search ? (
<View style={styles.searchRow}>
<Search size={theme.iconSize.md} color={theme.colors.foregroundMuted} />
@@ -507,21 +497,39 @@ export function SheetHeaderView({
export function InlineHeaderView({ header }: { header: SheetHeader }) {
const { theme } = useUnistyles();
const { t } = useTranslation();
const hasInlineRow = Boolean(header.back || header.leading || header.actions);
const back = header.back;
const handleBackPress = back?.onPress;
const hasInlineRow = Boolean(handleBackPress || header.leading || header.actions);
if (!hasInlineRow && !header.search) return null;
return (
<View>
{hasInlineRow ? (
<IconButtonChromeProvider value="header-island">
<View style={styles.inlineHeaderRow}>
{header.back ? <SheetHeaderBackButton back={header.back} /> : null}
{header.leading ? <View style={styles.headerLeadingSlot}>{header.leading}</View> : null}
<Text style={styles.inlineTitle} numberOfLines={1} testID={header.titleTestID}>
{header.title}
</Text>
{header.actions ? <View style={styles.headerTrailing}>{header.actions}</View> : null}
</View>
</IconButtonChromeProvider>
<View style={styles.inlineHeaderRow}>
{handleBackPress ? (
<Pressable
onPress={handleBackPress}
hitSlop={8}
style={styles.headerBackButton}
accessibilityRole="button"
accessibilityLabel={
back?.accessibilityLabel ?? back?.label ?? t("common.actions.back")
}
testID="sheet-header-back"
>
{({ pressed }) => (
<ArrowLeft
size={16}
color={pressed ? theme.colors.foreground : theme.colors.foregroundMuted}
/>
)}
</Pressable>
) : null}
{header.leading ? <View style={styles.headerLeadingSlot}>{header.leading}</View> : null}
<Text style={styles.inlineTitle} numberOfLines={1}>
{header.title}
</Text>
{header.actions ? <View style={styles.headerActions}>{header.actions}</View> : null}
</View>
) : null}
{header.search ? (
<View style={styles.inlineSearchRow}>
@@ -566,6 +574,11 @@ export interface AdaptiveModalSheetProps {
* corner, and the compact sheet closes from its handle.
*/
header?: SheetHeader;
/**
* Leave out the header's close button when `header.back` is the only way out, as for a sheet
* that stands in for a page of the surface beneath it. Escape still closes the sheet.
*/
showCloseButton?: boolean;
visible: boolean;
onClose: () => void;
onDismiss?: () => void;
@@ -596,6 +609,7 @@ export interface AdaptiveModalSheetProps {
*/
function CompactSheetBody({
header,
showCloseButton,
onClose,
testID,
footer,
@@ -606,6 +620,7 @@ function CompactSheetBody({
children,
}: {
header?: SheetHeader;
showCloseButton: boolean;
onClose: () => void;
testID?: string;
footer: ReactNode;
@@ -635,7 +650,14 @@ function CompactSheetBody({
);
return (
<SheetVisibleFrame footer={footerView}>
{header ? <SheetHeaderView header={header} onClose={onClose} testID={testID} /> : null}
{header ? (
<SheetHeaderView
header={header}
onClose={onClose}
showCloseButton={showCloseButton}
testID={testID}
/>
) : null}
<View style={[styles.compactStaticContent, bodyStyle]}>
{scrollable ? (
<ScrollView
@@ -662,6 +684,7 @@ function CompactSheetBody({
export function AdaptiveModalSheet({
header,
showCloseButton = true,
visible,
onClose,
onDismiss,
@@ -789,6 +812,7 @@ export function AdaptiveModalSheet({
<OverlayLayerProvider layer={modalLayer}>
<CompactSheetBody
header={header}
showCloseButton={showCloseButton}
onClose={onClose}
testID={testID}
footer={footerView}
@@ -808,7 +832,9 @@ export function AdaptiveModalSheet({
desktopHeight == null ? styles.desktopStaticContent : styles.compactStaticContent;
const cardInner = (
<OverlayLayerProvider layer={modalLayer}>
{header ? <SheetHeaderView header={header} onClose={onClose} /> : null}
{header ? (
<SheetHeaderView header={header} onClose={onClose} showCloseButton={showCloseButton} />
) : null}
<View style={[scrollable ? styles.desktopScrollContainer : desktopStaticStyle, bodyStyle]}>
{scrollable ? (
<ScrollView
@@ -825,18 +851,24 @@ export function AdaptiveModalSheet({
</View>
{footerView}
{header ? null : (
<IconButtonChromeProvider value="header-island">
<View style={styles.floatingClose}>
<SheetHeaderIconButton icon={X} label={t("common.actions.close")} onPress={onClose} />
</View>
</IconButtonChromeProvider>
<View style={styles.floatingClose}>
<SheetHeaderIconButton
icon={X}
accessibilityLabel={t("common.actions.close")}
onPress={onClose}
/>
</View>
)}
</OverlayLayerProvider>
);
const desktopContent = (
<View style={desktopOverlayStyle} testID={testID}>
<DismissBackdrop label={t("common.actions.dismiss")} onPress={onClose} />
<Pressable
accessibilityLabel={t("common.actions.dismiss")}
style={ABSOLUTE_FILL_STYLE}
onPress={onClose}
/>
<View ref={setOverlayScope} style={desktopCardStyle} role="dialog" aria-modal tabIndex={-1}>
{cardInner}
</View>
+14 -4
View File
@@ -17,12 +17,11 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { useTimeAgo } from "@/hooks/use-time-ago";
import { type AggregatedAgent } from "@/hooks/use-aggregated-agents";
import { useSessionStore } from "@/stores/session-store";
import { ChevronRight } from "lucide-react-native";
import { Archive, ChevronRight } from "lucide-react-native";
import { useProviderIcon } from "@/components/provider-icons";
import { navigateToAgent } from "@/utils/navigate-to-agent";
import { useArchiveAgent } from "@/hooks/use-archive-agent";
import { HighlightedText } from "@/components/ui/highlighted-text";
import { ArchivedBadge } from "@/components/archived-badge";
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/status-badge";
import { findHighlightRanges } from "@/components/ui/highlighted-text-segments";
@@ -100,30 +99,36 @@ function formatDateSectionLabel(t: TFunction, section: DateSectionKey): string {
function SessionBadge({
label,
icon,
tone = "neutral",
}: {
label: string;
icon?: ReactElement;
tone?: "neutral" | "warning" | "danger";
}) {
let variant: StatusBadgeVariant = "muted";
if (tone === "warning") variant = "warning";
else if (tone === "danger") variant = "error";
return <StatusBadge label={label} variant={variant} />;
return <StatusBadge label={label} variant={variant} leading={icon} />;
}
function SessionRowBadges({
agent,
archivedIcon,
pendingPermissionCount,
showDesktopAttention,
}: {
agent: AggregatedAgent;
archivedIcon: ReactElement;
pendingPermissionCount: number;
showDesktopAttention: boolean;
}) {
const { t } = useTranslation();
return (
<>
{agent.archivedAt ? <ArchivedBadge /> : null}
{agent.archivedAt ? (
<SessionBadge label={t("agentList.badges.archived")} icon={archivedIcon} />
) : null}
{pendingPermissionCount > 0 ? (
<SessionBadge
label={t("agentList.badges.pending", { count: pendingPermissionCount })}
@@ -209,6 +214,10 @@ function SessionRow({
const handlePress = useCallback(() => onPress(agent), [onPress, agent]);
const handleLongPress = useCallback(() => onLongPress(agent), [onLongPress, agent]);
const archivedIcon = useMemo(
() => <Archive size={theme.fontSize.sm} color={theme.colors.foregroundMuted} />,
[theme.fontSize.sm, theme.colors.foregroundMuted],
);
const showDesktopAttention =
!isMobile && showAttentionIndicator && Boolean(agent.requiresAttention);
@@ -252,6 +261,7 @@ function SessionRow({
) : null}
<SessionRowBadges
agent={agent}
archivedIcon={archivedIcon}
pendingPermissionCount={pendingPermissionCount}
showDesktopAttention={showDesktopAttention}
/>
@@ -1,15 +1,11 @@
import * as Clipboard from "expo-clipboard";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Platform, Text, View } from "react-native";
import { Platform, Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import { Copy, RotateCw } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import {
AdaptiveModalSheet,
SheetHeaderIconButton,
type SheetHeader,
} from "@/components/adaptive-modal-sheet";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { ScrollableCodeSurface, SurfaceCard } from "@/components/ui/scrollable-code-surface";
import { useToast } from "@/contexts/toast-context";
@@ -46,6 +42,8 @@ interface DiagnosticCollectionResult {
}
const SNAP_POINTS = ["55%", "88%"];
const ThemedCopy = withUnistyles(Copy);
const ThemedRotateCw = withUnistyles(RotateCw);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
@@ -152,31 +150,68 @@ export function AppDiagnosticSheet({
.catch(() => toast.error(t("settings.diagnostics.app.copyFailed")));
}, [diagnostic, t, toast]);
const iconButtonStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.iconButton,
(Boolean(hovered) || pressed) && styles.iconButtonHovered,
],
[],
);
const disabledIconButtonStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.iconButton,
(Boolean(hovered) || pressed) && Boolean(diagnostic) && styles.iconButtonHovered,
diagnostic ? null : styles.disabled,
],
[diagnostic],
);
const header = useMemo<SheetHeader>(
() => ({
title: t("settings.diagnostics.app.title"),
actions: (
<>
<SheetHeaderIconButton
icon={Copy}
label={t("settings.diagnostics.app.copyAccessibility")}
<View style={styles.headerActions}>
<Pressable
onPress={handleCopyPress}
disabled={!diagnostic}
/>
<SheetHeaderIconButton
icon={RotateCw}
label={
hitSlop={8}
style={disabledIconButtonStyle}
accessibilityRole="button"
accessibilityLabel={t("settings.diagnostics.app.copyAccessibility")}
>
<ThemedCopy size={ICON_SIZE.sm} uniProps={foregroundMutedColorMapping} />
</Pressable>
<Pressable
onPress={handleRefreshPress}
disabled={loading}
hitSlop={8}
style={iconButtonStyle}
accessibilityRole="button"
accessibilityLabel={
loading
? t("settings.diagnostics.app.refreshingAccessibility")
: t("settings.diagnostics.app.refreshAccessibility")
}
onPress={handleRefreshPress}
busy={loading}
/>
</>
>
{loading ? (
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={foregroundMutedColorMapping} />
) : (
<ThemedRotateCw size={ICON_SIZE.sm} uniProps={foregroundMutedColorMapping} />
)}
</Pressable>
</View>
),
}),
[diagnostic, handleCopyPress, handleRefreshPress, loading, t],
[
diagnostic,
disabledIconButtonStyle,
handleCopyPress,
handleRefreshPress,
iconButtonStyle,
loading,
t,
],
);
return (
@@ -307,6 +342,24 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
color: theme.colors.foregroundMuted,
},
headerActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
iconButton: {
width: 28,
height: 28,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
},
iconButtonHovered: {
backgroundColor: theme.colors.surface2,
},
disabled: {
opacity: 0.5,
},
statusDot: {
width: 8,
height: 8,
@@ -1,17 +0,0 @@
import { Archive } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { withUnistyles } from "react-native-unistyles";
import { StatusBadge } from "@/components/ui/status-badge";
const ThemedArchive = withUnistyles(Archive, (theme) => ({
size: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
}));
const ARCHIVE_ICON = <ThemedArchive />;
/** Marks a session or workspace the user archived, wherever archived items are listed. */
export function ArchivedBadge() {
const { t } = useTranslation();
return <StatusBadge label={t("agentList.badges.archived")} leading={ARCHIVE_ICON} />;
}
@@ -1,149 +0,0 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { persistAttachmentFromBlob } from "@/attachments/service";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { i18n } from "@/i18n/i18next";
import { WindowLayoutProvider } from "@/window-layout";
import { AttachmentLightbox, type ImageLightboxSource } from "./attachment-lightbox";
interface FrameSample {
image: { x: number; y: number; width: number; height: number } | null;
error: boolean;
}
function nextFrame(): Promise<number> {
return new Promise((resolve) => requestAnimationFrame(resolve));
}
function createPng(width: number, height: number): Promise<Blob> {
const canvas = new OffscreenCanvas(width, height);
const context = canvas.getContext("2d");
if (!context) throw new Error("Canvas 2D context unavailable");
context.fillStyle = "#3a7";
context.fillRect(0, 0, width, height);
return canvas.convertToBlob({ type: "image/png" });
}
function noop() {}
function isPainted(element: Element): boolean {
for (let node: Element | null = element; node; node = node.parentElement) {
if (Number(getComputedStyle(node).opacity) === 0) return false;
}
return true;
}
/** What the next paint will show: the visible lightbox image box, and whether the error is up. */
function sampleFrame(): FrameSample {
const image = document.querySelector('[data-testid="attachment-lightbox-image"]');
const rect = image?.getBoundingClientRect();
const visible = image && rect && rect.width > 0 && rect.height > 0 && isPainted(image);
return {
image: visible
? {
x: Math.round(rect.x),
y: Math.round(rect.y),
width: Math.round(rect.width),
height: Math.round(rect.height),
}
: null,
error: (document.body.textContent ?? "").includes("Couldn't load image"),
};
}
/** Samples every frame from the open until the image has held one box for 20 frames. */
async function recordOpening(open: () => void): Promise<FrameSample[]> {
const samples: FrameSample[] = [];
open();
let stableFrames = 0;
for (let frame = 0; frame < 300 && stableFrames < 20; frame += 1) {
await nextFrame();
const sample = sampleFrame();
const previous = samples.at(-1);
stableFrames =
sample.image && JSON.stringify(sample.image) === JSON.stringify(previous?.image)
? stableFrames + 1
: 0;
samples.push(sample);
}
return samples;
}
let root: Root;
let container: HTMLDivElement;
beforeEach(async () => {
vi.stubGlobal("React", React);
await i18n.changeLanguage("en");
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
document.body.replaceChildren();
vi.unstubAllGlobals();
});
function renderLightbox(source: ImageLightboxSource | null) {
root.render(
<SafeAreaProvider>
<WindowLayoutProvider>
<AttachmentLightbox source={source} onClose={noop} />
</WindowLayoutProvider>
</SafeAreaProvider>,
);
}
async function expectOpeningPaintsOnlyTheFittedImage(source: ImageLightboxSource) {
const samples = await recordOpening(() => renderLightbox(source));
const fitted = samples.at(-1)?.image;
expect(fitted, "the image never settled").toBeTruthy();
expect(samples.filter((sample) => sample.error)).toEqual([]);
expect(
samples.filter(
(sample) => sample.image && JSON.stringify(sample.image) !== JSON.stringify(fitted),
),
).toEqual([]);
}
describe("AttachmentLightbox opening in the browser", () => {
it("paints the fitted attachment image as its first image frame", async () => {
const metadata = await persistAttachmentFromBlob({
blob: await createPng(2400, 1600),
mimeType: "image/png",
fileName: "screenshot.png",
});
await expectOpeningPaintsOnlyTheFittedImage({ type: "attachment", metadata });
});
it("paints only the fitted image when the same attachment opens again", async () => {
const metadata = await persistAttachmentFromBlob({
blob: await createPng(2400, 1600),
mimeType: "image/png",
fileName: "screenshot.png",
});
const source: ImageLightboxSource = { type: "attachment", metadata };
await expectOpeningPaintsOnlyTheFittedImage(source);
await act(async () => renderLightbox(null));
await expectOpeningPaintsOnlyTheFittedImage(source);
});
it("shows an image the browser reports no natural size for", async () => {
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>';
const uri = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
await expectOpeningPaintsOnlyTheFittedImage({ type: "uri", uri });
});
it("paints the fitted timeline image as its first image frame", async () => {
const uri = URL.createObjectURL(await createPng(2400, 1600));
await expectOpeningPaintsOnlyTheFittedImage({ type: "uri", uri });
});
});
@@ -4,7 +4,6 @@ import { createRoot, type Root } from "react-dom/client";
import { JSDOM } from "jsdom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AttachmentMetadata } from "@/attachments/types";
import type { AttachmentPreviewUrl } from "@/attachments/use-attachment-preview-url";
import { AttachmentLightbox, type ImageLightboxSource } from "./attachment-lightbox";
const { theme, imageMetadata, useAttachmentPreviewUrlMock } = vi.hoisted(() => {
@@ -39,9 +38,9 @@ const { theme, imageMetadata, useAttachmentPreviewUrlMock } = vi.hoisted(() => {
return {
theme: hoistedTheme,
imageMetadata: hoistedImageMetadata,
useAttachmentPreviewUrlMock: vi.fn<
(metadata: AttachmentMetadata | null) => AttachmentPreviewUrl
>(() => ({ status: "ready", url: "blob:preview" })),
useAttachmentPreviewUrlMock: vi.fn<(metadata: AttachmentMetadata | null) => string | null>(
() => "blob:preview",
),
};
});
const attachmentSource: ImageLightboxSource = { type: "attachment", metadata: imageMetadata };
@@ -74,13 +73,10 @@ vi.mock("react-i18next", () => ({
}));
vi.mock("react-native-safe-area-context", () => ({
SafeAreaProvider: ({ children }: { children?: React.ReactNode }) => children,
useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
}));
vi.mock("@/window-layout", () => ({
WindowSafeArea: ({ children }: { children?: React.ReactNode }) => children,
}));
vi.mock("react-native-gesture-handler", () => ({
GestureHandlerRootView: ({ children }: { children?: React.ReactNode }) =>
React.createElement("div", { "data-testid": "gesture-handler-root" }, children),
@@ -155,7 +151,7 @@ beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
useAttachmentPreviewUrlMock.mockReturnValue({ status: "ready", url: "blob:preview" });
useAttachmentPreviewUrlMock.mockReturnValue("blob:preview");
});
afterEach(() => {
@@ -233,22 +229,14 @@ describe("AttachmentLightbox", () => {
expect(onClose).toHaveBeenCalledTimes(1);
});
it("shows error text when the preview URL fails to resolve", () => {
useAttachmentPreviewUrlMock.mockReturnValue({ status: "failed" });
it("shows error text when the preview URL resolves to null", () => {
useAttachmentPreviewUrlMock.mockReturnValue(null);
render(<AttachmentLightbox source={attachmentSource} onClose={vi.fn()} />);
expect(queryByTestId("attachment-lightbox-image")).toBeNull();
expect(document.body.textContent ?? "").toContain("Couldn't load image");
});
it("shows neither the image nor an error while the preview URL resolves", () => {
useAttachmentPreviewUrlMock.mockReturnValue({ status: "loading" });
render(<AttachmentLightbox source={attachmentSource} onClose={vi.fn()} />);
expect(queryByTestId("attachment-lightbox-image")).toBeNull();
expect(document.body.textContent ?? "").not.toContain("Couldn't load image");
});
it("closes on Escape key on web", () => {
const onClose = vi.fn();
render(<AttachmentLightbox source={attachmentSource} onClose={onClose} />);
@@ -4,21 +4,17 @@ import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react
import { Pressable, Text, View } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { StyleSheet } from "react-native-unistyles";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { SafeAreaProvider, useSafeAreaInsets } from "react-native-safe-area-context";
import { X } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import type { AttachmentMetadata } from "@/attachments/types";
import {
type AttachmentPreviewUrl,
useAttachmentPreviewUrl,
} from "@/attachments/use-attachment-preview-url";
import { useAttachmentPreviewUrl } from "@/attachments/use-attachment-preview-url";
import { isNative } from "@/constants/platform";
import { SPACING } from "@/styles/theme";
import { WindowChromeRootRegion } from "@/utils/desktop-window";
import { ZoomableImage } from "@/components/zoomable-viewport/image";
import type { ViewportSize } from "@/components/zoomable-viewport/geometry";
import { useGlobalOverlayLayer } from "@/lib/overlay-root";
import { WindowSafeArea } from "@/window-layout";
export type ImageLightboxSource =
| { type: "attachment"; metadata: AttachmentMetadata }
@@ -35,13 +31,10 @@ const LIGHTBOX_FIT = { padding: SPACING[4], maxWidth: 960, maxHeight: 640 };
export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps) {
const { t } = useTranslation();
const metadata = source?.type === "attachment" ? source.metadata : null;
const attachmentPreview = useAttachmentPreviewUrl(metadata);
const image: AttachmentPreviewUrl =
source?.type === "uri" ? { status: "ready", url: source.uri } : attachmentPreview;
const url = image.status === "ready" ? image.url : null;
const attachmentUrl = useAttachmentPreviewUrl(metadata);
const url = source?.type === "uri" ? source.uri : attachmentUrl;
const contentSize = source?.type === "uri" ? source.contentSize : undefined;
const [errored, setErrored] = useState(false);
const failed = errored || image.status === "failed";
const modalLayer = useGlobalOverlayLayer("modal", source !== null);
useEffect(() => {
@@ -83,12 +76,14 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
return null;
}
const hasError = errored || !url;
return (
<Modal transparent animationType="fade" statusBarTranslucent visible onRequestClose={onClose}>
<ModalRoot style={styles.root}>
{/* The modal draws over the whole window: its insets are the window's, not the ones left
where the image was opened (inside a sheet tab, the bottom one is already spent). */}
<WindowSafeArea>
{/* The modal is its own window: its insets are the window's, not the ones left where the
image was opened (inside a sheet tab, the bottom one is already spent). */}
<SafeAreaProvider>
<WindowChromeRootRegion corners="both">
<View ref={setOverlayScope} style={styles.root}>
<Pressable
@@ -99,10 +94,9 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
style={styles.backdrop}
/>
<LightboxImageArea>
{failed ? (
{hasError ? (
<Text style={styles.errorText}>{t("message.attachments.imageLoadFailed")}</Text>
) : null}
{!failed && url ? (
) : (
<ZoomableImage
accessibilityLabel={t("composer.attachments.openImage")}
actions={actions}
@@ -114,11 +108,11 @@ export function AttachmentLightbox({ source, onClose }: AttachmentLightboxProps)
testID="attachment-lightbox"
uri={url}
/>
) : null}
)}
</LightboxImageArea>
</View>
</WindowChromeRootRegion>
</WindowSafeArea>
</SafeAreaProvider>
</ModalRoot>
</Modal>
);
@@ -133,10 +133,9 @@ export function AttachmentLabel({ icon, title, subtitle }: AttachmentLabelProps)
/** Square image preview pill body. */
export function AttachmentThumbnail({ metadata }: { metadata: AttachmentMetadata }) {
const preview = useAttachmentPreviewUrl(metadata);
const uri = preview.status === "ready" ? preview.url : null;
const source = useMemo(() => (uri ? { uri } : null), [uri]);
if (!source) {
const uri = useAttachmentPreviewUrl(metadata);
const source = useMemo(() => ({ uri: uri ?? "" }), [uri]);
if (!uri) {
return <View style={styles.thumbnailPlaceholder} />;
}
return <Image source={source} style={styles.thumbnail} />;
@@ -1,45 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createDragHold } from "./drag-hold";
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
function hold() {
const onArm = vi.fn();
return { onArm, hold: createDragHold({ delayMs: 180, slopPx: 4, onArm }) };
}
describe("createDragHold", () => {
it("arms once the finger has stayed within the slop for the delay", () => {
const { onArm, hold: dragHold } = hold();
dragHold.begin({ x: 10, y: 10 });
dragHold.move({ x: 12, y: 13 });
vi.advanceTimersByTime(180);
expect(onArm).toHaveBeenCalledTimes(1);
});
it("never arms when the finger moves past the slop first, as when a scroll starts", () => {
const { onArm, hold: dragHold } = hold();
dragHold.begin({ x: 10, y: 10 });
dragHold.move({ x: 10, y: 20 });
vi.advanceTimersByTime(500);
expect(onArm).not.toHaveBeenCalled();
});
it("never arms when the finger lifts before the delay", () => {
const { onArm, hold: dragHold } = hold();
dragHold.begin({ x: 10, y: 10 });
vi.advanceTimersByTime(100);
dragHold.cancel();
vi.advanceTimersByTime(500);
expect(onArm).not.toHaveBeenCalled();
});
});
@@ -1,51 +0,0 @@
export interface TouchPoint {
x: number;
y: number;
}
export interface DragHold {
begin: (point: TouchPoint) => void;
move: (point: TouchPoint) => void;
cancel: () => void;
}
/**
* A hold that arms a drag once the finger has stayed put for `delayMs`. Moving further than
* `slopPx` from where the touch began cancels it, so a scroll that starts on a handle stays a
* scroll. The sidebar rows arm on the same delay and slop.
*/
export function createDragHold({
delayMs,
slopPx,
onArm,
}: {
delayMs: number;
slopPx: number;
onArm: () => void;
}): DragHold {
let timer: ReturnType<typeof setTimeout> | null = null;
let start: TouchPoint | null = null;
function cancel() {
if (timer) clearTimeout(timer);
timer = null;
start = null;
}
return {
begin(point) {
cancel();
start = point;
timer = setTimeout(() => {
timer = null;
start = null;
onArm();
}, delayMs);
},
move(point) {
if (!start) return;
if (Math.hypot(point.x - start.x, point.y - start.y) > slopPx) cancel();
},
cancel,
};
}
@@ -1,14 +0,0 @@
import { describe, expect, it } from "vitest";
import { movedItemKey } from "./native-drop";
const byValue = (item: string): string => item;
describe("movedItemKey", () => {
it("names the item at its new slot", () => {
expect(movedItemKey({ data: ["b", "c", "a"], from: 0, to: 2 }, byValue)).toBe("a");
});
it("names nothing when the item is released in the slot it started in", () => {
expect(movedItemKey({ data: ["a", "b", "c"], from: 1, to: 1 }, byValue)).toBeNull();
});
});
@@ -1,17 +0,0 @@
export interface NativeDrop<T> {
data: T[];
from: number;
to: number;
}
/**
* The key of the item a native drop moved, or null when the item was released in the slot it
* started in. The native list reports every release; web reports only drops that moved an item.
*/
export function movedItemKey<T>(
{ data, from, to }: NativeDrop<T>,
keyExtractor: (item: T, index: number) => string,
): string | null {
if (from === to) return null;
return keyExtractor(data[to], to);
}
@@ -24,7 +24,7 @@ export function useDragReorderState<T>({
}: {
data: T[];
keyExtractor: (item: T, index: number) => string;
onDragEnd?: (items: T[], movedKey: string) => void;
onDragEnd?: (items: T[]) => void;
onDragBegin?: () => void;
disabled?: boolean;
}): DragReorderState<T> {
@@ -50,14 +50,13 @@ export function useDragReorderState<T>({
dispatch({ type: "clear" });
if (disabled) return;
const activeId = String(active.id);
const reordered = reorderItemsOnDragEnd({
items,
activeId,
activeId: String(active.id),
overId: over ? String(over.id) : null,
keyExtractor,
});
if (reordered) onDragEnd?.(reordered, activeId);
if (reordered) onDragEnd?.(reordered);
},
[data, disabled, keyExtractor, onDragEnd, state.dragItems],
);
@@ -1,94 +1,16 @@
import { RefreshControl, View, type GestureResponderEvent } from "react-native";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import * as Haptics from "expo-haptics";
import { RefreshControl } from "react-native";
import { useCallback, useMemo, useState } from "react";
import DraggableFlatList, {
NestableDraggableFlatList,
type RenderItemParams,
} from "react-native-draggable-flatlist";
import type { GestureType } from "react-native-gesture-handler";
import { useUnistyles } from "react-native-unistyles";
import { useContentDrag } from "@/components/ui/scroll-view";
import { createDragHold } from "./drag-reorder/drag-hold";
import { movedItemKey } from "./drag-reorder/native-drop";
import type {
DraggableListHandleProps,
DraggableListProps,
DraggableRenderItemInfo,
} from "./draggable-list.types";
import type { DraggableListProps, DraggableRenderItemInfo } from "./draggable-list.types";
export type { DraggableListHandleProps, DraggableListProps, DraggableRenderItemInfo };
/** The row's `drag()`, for its handle. */
const RowDragContext = createContext<(() => void) | null>(null);
// The list only accepts drag() once its pan gesture has begun for this touch, and that begin
// reaches JS after the touch does. Same hold and slop as the sidebar rows' drag arm.
const HANDLE_HOLD_MS = 180;
const HANDLE_HOLD_SLOP_PX = 4;
function touchPoint(event: GestureResponderEvent) {
return { x: event.nativeEvent.pageX, y: event.nativeEvent.pageY };
}
/**
* On native the handle has no accessibility role or label: a screen reader cannot hold and drag,
* and announcing a control whose activation does nothing misleads. The label is for web, where
* the keyboard reorders through it.
*/
export function DraggableListHandle({ testID, style, children }: DraggableListHandleProps) {
const drag = useContext(RowDragContext);
const hold = useMemo(
() =>
drag
? createDragHold({
delayMs: HANDLE_HOLD_MS,
slopPx: HANDLE_HOLD_SLOP_PX,
onArm: () => {
void Haptics.selectionAsync().catch(() => {});
drag();
},
})
: null,
[drag],
);
useEffect(() => () => hold?.cancel(), [hold]);
const startHold = useCallback(
(event: GestureResponderEvent) => hold?.begin(touchPoint(event)),
[hold],
);
const moveHold = useCallback(
(event: GestureResponderEvent) => hold?.move(touchPoint(event)),
[hold],
);
const cancelHold = useCallback(() => hold?.cancel(), [hold]);
return (
<View
onTouchStart={startHold}
onTouchMove={moveHold}
onTouchEnd={cancelHold}
onTouchCancel={cancelHold}
style={style}
testID={testID}
>
{children}
</View>
);
}
export type { DraggableListProps, DraggableRenderItemInfo };
const SCROLL_ENABLED_FLEX_STYLE = { flex: 1 };
// A drop remounts every row between the drag's start and end slots (see the draggable-flatlist
// patch), so state held inside a rendered row resets when a drop moves it. Keep state that must
// survive a reorder in the list's owner, keyed by row.
export function DraggableList<T>({
data,
keyExtractor,
@@ -115,12 +37,6 @@ export function DraggableList<T>({
}: DraggableListProps<T>) {
const { theme } = useUnistyles();
const [isDragging, setIsDragging] = useState(false);
// Inside a sheet the sheet would otherwise take the vertical move from an armed row.
const contentDrag = useContentDrag();
const { attach: attachContentDrag } = contentDrag;
const dragGestureRef = useRef<GestureType | undefined>(undefined);
// Passive effects run after the list's gesture detector has attached and filled the ref.
useEffect(() => attachContentDrag?.(dragGestureRef), [attachContentDrag]);
// Pass the ref directly to DraggableFlatList - it handles gesture
// coordination internally for nestable lists.
@@ -143,31 +59,27 @@ export function DraggableList<T>({
drag,
isActive,
};
return <RowDragContext.Provider value={drag}>{renderItem(info)}</RowDragContext.Provider>;
return renderItem(info);
},
[renderItem],
);
const handleDragEnd = useCallback(
(drop: { data: T[]; from: number; to: number }) => {
({ data: newData }: { data: T[] }) => {
setIsDragging(false);
contentDrag.setActive(false);
const moved = movedItemKey(drop, keyExtractor);
if (moved !== null) onDragEnd(drop.data, moved);
onDragEnd(newData);
},
[contentDrag, keyExtractor, onDragEnd],
[onDragEnd],
);
const handleDragBegin = useCallback(() => {
setIsDragging(true);
contentDrag.setActive(true);
onDragBeginProp?.();
}, [contentDrag, onDragBeginProp]);
}, [onDragBeginProp]);
const handleRelease = useCallback(() => {
setIsDragging(false);
contentDrag.setActive(false);
}, [contentDrag]);
}, []);
const showRefreshControl = Boolean(onRefresh) && (!isDragging || Boolean(refreshing));
const resolvedContainerStyle =
@@ -205,14 +117,9 @@ export function DraggableList<T>({
ListEmptyComponent={ListEmptyComponent}
showsVerticalScrollIndicator={showsVerticalScrollIndicator}
scrollEnabled={scrollEnabled}
// A list that doesn't scroll shows every row, so it renders them all in its first commit.
// FlatList's default first render is 10 rows; a nested list remounted by a drop would paint
// 10 rows, then grow on a later commit.
initialNumToRender={scrollEnabled ? undefined : data.length}
extraData={extraData}
simultaneousHandlers={simultaneousHandlers}
dragGestureHostPresented={gestureHostPresented}
dragGestureRef={attachContentDrag ? dragGestureRef : undefined}
// Higher activation distance reduces accidental drag capture while nested
// lists are inside a scroll container.
activationDistance={20}
@@ -1,4 +1,4 @@
import type { ReactElement, ReactNode, MutableRefObject } from "react";
import type { ReactElement, MutableRefObject } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import type { GestureType } from "react-native-gesture-handler";
@@ -12,18 +12,6 @@ export interface DraggableListDragHandleProps {
setActivatorNodeRef?: (node: unknown) => void;
}
/**
* The grip a row is dragged by, rendered anywhere inside `renderItem`. Pointer drags start from
* it on web (with `useDragHandle`); touch drags start after a short hold on native.
*/
export interface DraggableListHandleProps {
/** Names the keyboard-reorderable handle on web. Native leaves the handle out of accessibility. */
accessibilityLabel: string;
testID?: string;
style?: StyleProp<ViewStyle>;
children: ReactNode;
}
export interface DraggableRenderItemInfo<T> {
item: T;
index: number;
@@ -36,8 +24,7 @@ export interface DraggableListProps<T> {
data: T[];
keyExtractor: (item: T, index: number) => string;
renderItem: (info: DraggableRenderItemInfo<T>) => ReactElement;
/** The new order, and the key of the item the user moved to reach it. */
onDragEnd: (data: T[], movedKey: string) => void;
onDragEnd: (data: T[]) => void;
style?: StyleProp<ViewStyle>;
/** Outer container style (useful for nested, non-scrolling lists). */
containerStyle?: StyleProp<ViewStyle>;
@@ -1,110 +0,0 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
DraggableList,
DraggableListHandle,
type DraggableRenderItemInfo,
} from "./draggable-list.web";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
interface Item {
id: string;
}
function keyExtractor(item: Item): string {
return item.id;
}
function noop() {}
let root: Root | null = null;
let container: HTMLDivElement | null = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function renderRowWithHandle(info: DraggableRenderItemInfo<Item>) {
return (
<div>
<DraggableListHandle accessibilityLabel={`Move ${info.item.id}`} testID="row-handle">
<span>grip</span>
</DraggableListHandle>
<span data-testid="row-body">{info.item.id}</span>
</div>
);
}
function renderList(onDragBegin: () => void) {
act(() => {
root?.render(
<DraggableList
data={[{ id: "one" }, { id: "two" }]}
keyExtractor={keyExtractor}
renderItem={renderRowWithHandle}
onDragEnd={noop}
onDragBegin={onDragBegin}
useDragHandle
/>,
);
});
}
function byTestId(testID: string): HTMLElement {
const found = container?.querySelector(`[data-testid="${testID}"]`);
if (!(found instanceof HTMLElement)) throw new Error(`Nothing rendered as ${testID}`);
return found;
}
/** Press on the element's centre, move the mouse down by `distance`, and release. */
function pressAndMove(element: HTMLElement, distance: number) {
const { left, top, width, height } = element.getBoundingClientRect();
const x = left + width / 2;
const y = top + height / 2;
act(() => {
element.dispatchEvent(
new MouseEvent("mousedown", { bubbles: true, button: 0, clientX: x, clientY: y }),
);
});
act(() => {
document.dispatchEvent(
new MouseEvent("mousemove", { bubbles: true, clientX: x, clientY: y + distance }),
);
});
act(() => {
document.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
});
}
describe("DraggableListHandle on web", () => {
it("starts the row's drag from the handle, and only from the handle", () => {
const onDragBegin = vi.fn();
renderList(onDragBegin);
pressAndMove(byTestId("row-body"), 20);
expect(onDragBegin).not.toHaveBeenCalled();
pressAndMove(byTestId("row-handle"), 20);
expect(onDragBegin).toHaveBeenCalledTimes(1);
});
it("is a labelled button rather than dnd-kit's sortable", () => {
renderList(noop);
const handle = byTestId("row-handle");
expect(handle.getAttribute("role")).toBe("button");
expect(handle.getAttribute("aria-label")).toBe("Move one");
expect(handle.getAttribute("aria-roledescription")).toBeNull();
});
});
@@ -1,13 +1,4 @@
import {
createContext,
memo,
useCallback,
useContext,
useMemo,
useRef,
type ReactElement,
type Ref,
} from "react";
import { memo, useCallback, useMemo, useRef, type ReactElement } from "react";
import { ScrollView, View } from "react-native";
import {
DndContext,
@@ -26,52 +17,10 @@ import {
useSortable,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type {
DraggableListDragHandleProps,
DraggableListHandleProps,
DraggableListProps,
DraggableRenderItemInfo,
} from "./draggable-list.types";
import type { DraggableListProps, DraggableRenderItemInfo } from "./draggable-list.types";
import { getDragActivationConstraints, useDragReorderState } from "./drag-reorder";
export type { DraggableListHandleProps, DraggableListProps, DraggableRenderItemInfo };
/** The row's dnd-kit activator, for its handle. Absent unless the list uses drag handles. */
const RowHandleContext = createContext<DraggableListDragHandleProps | undefined>(undefined);
// React Native's style types have no `cursor: "grab"`; react-native-web passes it through.
const GRAB_CURSOR = { cursor: "grab" } as object;
export function DraggableListHandle({
accessibilityLabel,
testID,
style,
children,
}: DraggableListHandleProps) {
const handle = useContext(RowHandleContext);
// The handle is a labelled button; dnd-kit's own role, focus stop and "sortable" description
// would replace that.
const {
role: _role,
tabIndex: _tabIndex,
"aria-roledescription": _roleDescription,
...attributes
} = handle?.attributes ?? {};
const handleStyle = useMemo(() => [GRAB_CURSOR, style], [style]);
return (
<View
{...attributes}
{...handle?.listeners}
ref={handle?.setActivatorNodeRef as unknown as Ref<View>}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
style={handleStyle}
testID={testID}
>
{children}
</View>
);
}
export type { DraggableListProps, DraggableRenderItemInfo };
const restrictToVerticalAxis: Modifier = ({ transform }) => ({
...transform,
@@ -228,9 +177,7 @@ function SortableItemInner<T>({
return (
<div {...wrapperProps} style={style}>
<RowHandleContext.Provider value={dragHandleProps}>
{renderItem(info)}
</RowHandleContext.Provider>
{renderItem(info)}
</div>
);
}
@@ -5,8 +5,6 @@ import {
useHostRuntimeConnectionStatus,
} from "@/runtime/host-runtime";
export const HOST_STATUS_DOT_SIZE = 8;
export function HostStatusDot({ serverId }: { serverId: string }) {
const status = useHostRuntimeConnectionStatus(serverId);
@@ -21,8 +19,8 @@ function statusStyle(status: HostRuntimeConnectionStatus) {
const styles = StyleSheet.create((theme) => ({
dot: {
width: HOST_STATUS_DOT_SIZE,
height: HOST_STATUS_DOT_SIZE,
width: 8,
height: 8,
borderRadius: theme.borderRadius.full,
},
dotOnline: {
@@ -1,12 +1,8 @@
import { useCallback, useMemo, useRef, useState, type ReactElement } from "react";
import { Text, View } from "react-native";
import { Server } from "lucide-react-native";
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import { ChevronDown, Server } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HOST_STATUS_DOT_SIZE } from "@/components/host-status-dot";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
import { mapLayout } from "@/components/ui/control-sizing";
import { density } from "@/styles/density";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import type { Theme } from "@/styles/theme";
import {
ALL_HOSTS_OPTION_ID,
getHostPickerLabel,
@@ -16,8 +12,7 @@ import {
} from "@/components/hosts/host-picker";
const ThemedServer = withUnistyles(Server);
// The height a hung trigger keeps: one line of its base-size label.
const LABEL_LINE = 20;
const ThemedChevronDown = withUnistyles(ChevronDown);
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
export interface HostFilterProps {
@@ -29,28 +24,20 @@ export interface HostFilterProps {
* manager edits a single host's catalog, so "all" is not an answer it could carry out.
*/
includeAllHost?: boolean;
/**
* Hang the trigger into the surrounding padding, for a trigger that leads a column such as a
* modal body: its leading glyph's ink sits on the content rail and it adds only a label line to
* the column, so the column's own gap sets the rhythm. The frame still grows outward on hover.
*/
hang?: boolean;
triggerTestID?: string;
hostOptionTestID?: (serverId: string) => string;
}
/**
* The "All hosts / <host>" host picker shared by History, Schedules, Usage, the label manager and
* The "All hosts / <host>" host pill shared by History, Schedules, Usage, the label manager and
* plugin screens: an anchored HostPicker, hidden by the caller when only one host exists. Without
* `includeAllHost` it picks the one host a surface shows. Its trigger is the Settings host
* trigger; a long host name truncates instead of pushing the row.
* `includeAllHost` it picks the one host a surface shows.
*/
export function HostFilter({
hosts,
selectedHost,
onSelectHost,
includeAllHost = true,
hang = false,
triggerTestID,
hostOptionTestID,
}: HostFilterProps): ReactElement {
@@ -63,21 +50,12 @@ export function HostFilter({
);
const handleFilterOpen = useCallback(() => setIsFilterOpen(true), []);
const showsAllHosts = selectedHost === ALL_HOSTS_OPTION_ID;
const slotStyle = useMemo(
() => [
styles.triggerSlot,
hang && styles.triggerSlotHang,
hang && (showsAllHosts ? styles.glyphHang : styles.dotHang),
],
[hang, showsAllHosts],
);
const triggerStyle = useCallback(
({ pressed, hovered }: { pressed: boolean; hovered: boolean }) => [
styles.trigger,
hovered && styles.triggerHovered,
pressed && styles.triggerPressed,
const filterTriggerStyle = useCallback(
({ pressed, hovered = false }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.filterTrigger,
Boolean(hovered) && styles.filterTriggerHovered,
pressed && styles.filterTriggerPressed,
],
[],
);
@@ -96,73 +74,54 @@ export function HostFilter({
desktopPlacement="bottom-start"
hostOptionTestID={hostOptionTestID}
>
<View style={slotStyle}>
<ComboboxTrigger
ref={filterAnchorRef}
<View ref={filterAnchorRef} collapsable={false} style={styles.filterTriggerWrap}>
<Pressable
onPress={handleFilterOpen}
style={triggerStyle}
style={filterTriggerStyle}
testID={triggerTestID}
accessibilityRole="button"
accessibilityLabel={`Filter: ${selectedHostLabel}`}
>
{showsAllHosts ? (
<ThemedServer size={ICON_SIZE.sm} uniProps={mutedColorMapping} />
{selectedHost === ALL_HOSTS_OPTION_ID ? (
<ThemedServer size={14} uniProps={mutedColorMapping} />
) : (
<HostStatusDotSlot serverId={selectedHost} />
)}
<Text style={styles.label} numberOfLines={1}>
<Text style={styles.filterTriggerText} numberOfLines={1}>
{selectedHostLabel}
</Text>
</ComboboxTrigger>
<ThemedChevronDown size={14} uniProps={mutedColorMapping} />
</Pressable>
</View>
</HostPicker>
);
}
const styles = StyleSheet.create((theme) => ({
// A row around the trigger keeps it as wide as its label in a column, and centred like any other
// item in a row.
triggerSlot: {
flexDirection: "row",
flexShrink: 1,
minWidth: 0,
maxWidth: "100%",
filterTriggerWrap: {
alignSelf: "flex-start",
},
// Hangs the frame's height down to a label line.
triggerSlotHang: {
marginVertical: mapLayout(density.tightRowHeight, (height) => (LABEL_LINE - height) / 2),
},
// Hangs the padding, so the server glyph's box sits on the rail.
glyphHang: {
marginLeft: -theme.spacing[2],
},
// Hangs the padding and the dot's inset in its icon slot, so the dot's ink sits on the rail.
dotHang: {
marginLeft: -(theme.spacing[2] + (ICON_SIZE.sm - HOST_STATUS_DOT_SIZE) / 2),
},
// The Settings host trigger: a borderless row that fills on hover and press.
trigger: {
flexShrink: 1,
minWidth: 0,
maxWidth: "100%",
filterTrigger: {
flexDirection: "row",
alignItems: "center",
minHeight: density.tightRowHeight,
paddingVertical: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius.lg,
gap: theme.spacing[1.5],
alignSelf: "flex-start",
paddingVertical: theme.spacing[1.5],
paddingHorizontal: theme.spacing[3],
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface1,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
},
triggerHovered: {
filterTriggerHovered: {
backgroundColor: theme.colors.surface2,
},
triggerPressed: {
backgroundColor: theme.colors.surface2,
filterTriggerPressed: {
backgroundColor: theme.colors.surface3,
},
label: {
flexShrink: 1,
minWidth: 0,
filterTriggerText: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
fontWeight: theme.fontWeight.medium,
},
}));
@@ -1,47 +0,0 @@
import { useCallback, useMemo, type ReactElement } from "react";
import { View } from "react-native";
import { HostStatusDot } from "@/components/host-status-dot";
import { MenuItem } from "@/components/ui/menu";
interface HostMenuItemProps {
serverId: string;
label: string;
selected: boolean;
onSelect: (serverId: string) => void;
/** Off for a multi-select page, where choosing a host is one of several toggles. */
closeOnSelect?: boolean;
testID?: string;
statusTestID?: string;
}
/** A host as a menu option: its live status dot leads, and the chosen host carries the check. */
export function HostMenuItem({
serverId,
label,
selected,
onSelect,
closeOnSelect = true,
testID,
statusTestID,
}: HostMenuItemProps): ReactElement {
const handleSelect = useCallback(() => onSelect(serverId), [onSelect, serverId]);
const leading = useMemo(
() => (
<View testID={statusTestID}>
<HostStatusDot serverId={serverId} />
</View>
),
[serverId, statusTestID],
);
return (
<MenuItem
selected={selected}
closeOnSelect={closeOnSelect}
leading={leading}
onSelect={handleSelect}
testID={testID}
>
{label}
</MenuItem>
);
}
@@ -164,25 +164,6 @@ vi.mock("@/components/adaptive-modal-sheet", () => ({
{children}
</section>
) : null,
SheetHeaderIconButton: ({
label,
onPress,
busy,
testID,
}: {
label: string;
onPress: () => void;
busy?: boolean;
testID?: string;
}) => (
<button
type="button"
aria-label={label}
disabled={busy}
onClick={onPress}
data-testid={testID}
/>
),
}));
vi.mock("react-native", async () => {
@@ -9,11 +9,7 @@ import type {
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
import { ChevronDown, Inbox, Layers, RotateCw } from "lucide-react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
AdaptiveModalSheet,
SheetHeaderIconButton,
type SheetHeader,
} from "@/components/adaptive-modal-sheet";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { ImportSessionList } from "@/components/import-session-list";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
@@ -220,6 +216,36 @@ function ProviderErrorBannerRow({
);
}
function RefreshAction({ isRefreshing, onPress }: { isRefreshing: boolean; onPress: () => void }) {
const { theme } = useUnistyles();
const { t } = useTranslation();
const pressableStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [
styles.refreshButton,
pressed && styles.refreshButtonPressed,
],
[],
);
return (
<Pressable
onPress={onPress}
disabled={isRefreshing}
accessibilityLabel={t("importSession.actions.refresh")}
accessibilityRole="button"
testID="import-session-refresh"
style={pressableStyle}
>
<View style={styles.refreshIconSlot}>
{isRefreshing ? (
<LoadingSpinner color={theme.colors.foregroundMuted} />
) : (
<RotateCw size={16} color={theme.colors.foregroundMuted} />
)}
</View>
</Pressable>
);
}
function ScopeSubtitle({
hostLabel,
isScoped,
@@ -749,15 +775,7 @@ export function ImportSessionSheet({
},
}
: {}),
actions: (
<SheetHeaderIconButton
icon={RotateCw}
label={t("importSession.actions.refresh")}
onPress={handleRefresh}
busy={isRefreshing}
testID="import-session-refresh"
/>
),
actions: <RefreshAction isRefreshing={isRefreshing} onPress={handleRefresh} />,
}),
[handleRefresh, handleShowAll, hostLabel, isRefreshing, scopeCwd, supportsSearch, t, visible],
);
@@ -1081,4 +1099,18 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
textAlign: "center",
},
refreshButton: {
padding: theme.spacing[2],
marginRight: theme.spacing[1],
borderRadius: theme.borderRadius.lg,
},
refreshButtonPressed: {
backgroundColor: theme.colors.surface2,
},
refreshIconSlot: {
width: 16,
height: 16,
alignItems: "center",
justifyContent: "center",
},
}));
+35 -12
View File
@@ -35,7 +35,7 @@ import {
type AgentProfilePickerRow as AgentProfilePickerRowModel,
type AgentProfileSeed,
} from "@/agent-profiles";
import { SheetHeaderIconButton, type SheetHeader } from "@/components/adaptive-modal-sheet";
import type { SheetHeader } from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
@@ -74,13 +74,14 @@ const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const ThemedPencil = withUnistyles(Pencil);
const ThemedPlus = withUnistyles(Plus);
const ThemedSearch = withUnistyles(Search);
const ThemedSettings = withUnistyles(Settings);
function ProviderSettingsAction({
label,
accessibilityLabel,
provider,
serverId,
}: {
label: string;
accessibilityLabel: string;
provider: string;
serverId: string | null;
}) {
@@ -91,13 +92,17 @@ function ProviderSettingsAction({
}, [overlayParentLayer, provider, serverId]);
return (
<SheetHeaderIconButton
icon={Settings}
label={label}
<Pressable
onPress={handlePress}
disabled={!serverId}
hitSlop={8}
style={iconButtonStyle}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
testID={`selector-header-settings-${provider}`}
/>
>
<HeaderSettingsIcon disabled={!serverId} />
</Pressable>
);
}
@@ -183,6 +188,10 @@ const foregroundExtraMutedMapping = (theme: Theme) => ({
color: theme.colors.foregroundExtraMuted,
});
const headerSettingsMapping = (disabled: boolean) => (theme: Theme) => ({
color: disabled ? theme.colors.border : theme.colors.foregroundMuted,
});
interface ModelBrowserInput {
providers: ProviderSelectorProvider[];
selectedProvider: string;
@@ -269,6 +278,11 @@ export function ModelProviderGlyph({
return <Icon size={size} strokeWidth={strokeWidth} color={color} />;
}
function HeaderSettingsIcon({ disabled }: { disabled: boolean }) {
const uniProps = useMemo(() => headerSettingsMapping(disabled), [disabled]);
return <ThemedSettings size={ICON_SIZE.sm} uniProps={uniProps} />;
}
function iconButtonStyle({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) {
return [
styles.rowIconButton,
@@ -381,11 +395,15 @@ export function useModelBrowser({
),
back: singleProviderView ? undefined : { onPress: showAll },
actions: (
<ProviderSettingsAction
serverId={serverId}
provider={view.providerId}
label={t("modelSelector.openProviderSettings", { provider: view.providerLabel })}
/>
<View style={styles.headerActionRow}>
<ProviderSettingsAction
serverId={serverId}
provider={view.providerId}
accessibilityLabel={t("modelSelector.openProviderSettings", {
provider: view.providerLabel,
})}
/>
</View>
),
search: {
onChange: handleSearchQueryChange,
@@ -1568,6 +1586,11 @@ export function ModelBrowser({
}
const styles = StyleSheet.create((theme) => ({
headerActionRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
profilesContainer: {
backgroundColor: theme.colors.surface1,
borderBottomWidth: 1,

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