mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-16 21:34:59 +00:00
Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06a16b63b8 | ||
|
|
454c1b4813 | ||
|
|
4f97abc62a | ||
|
|
39db933e6b | ||
|
|
a7a12ef4cd | ||
|
|
0273b6b614 | ||
|
|
8c88b83cd8 | ||
|
|
b55955541e | ||
|
|
2c5f5a1485 | ||
|
|
685e113358 | ||
|
|
28322f1519 | ||
|
|
4421f0473a | ||
|
|
2a432b1e0a | ||
|
|
1c175b36b3 | ||
|
|
aa9984b899 | ||
|
|
c4ff5599c7 | ||
|
|
ef146bc62d | ||
|
|
2e4dab0556 | ||
|
|
aa988dd8a8 | ||
|
|
781cb8d5b0 | ||
|
|
116b0a9190 | ||
|
|
5a7a60ae50 | ||
|
|
dd06bc0833 | ||
|
|
2eba291a8e | ||
|
|
96a143efe9 | ||
|
|
fe59a6c1a2 | ||
|
|
a5015dba80 | ||
|
|
da3be528e9 | ||
|
|
dc2dfdab93 | ||
|
|
fee32c9594 | ||
|
|
5b1baa0e72 | ||
|
|
fed8624516 | ||
|
|
5f89e666d0 | ||
|
|
41d6dc9cd7 | ||
|
|
6f685d37be | ||
|
|
286d528b71 | ||
|
|
8ff657cd4a | ||
|
|
45a991415f | ||
|
|
1ee13fff51 | ||
|
|
635b63a22b | ||
|
|
008eeaf18e | ||
|
|
ed8aa9ada8 | ||
|
|
7286d3ef81 | ||
|
|
a349856600 | ||
|
|
6016d3582e | ||
|
|
c1d7d56b71 | ||
|
|
2bd9e9d87f | ||
|
|
6e2fee462f | ||
|
|
cec92d0be6 | ||
|
|
b407990699 | ||
|
|
fc36438f03 | ||
|
|
0fb6473a4b | ||
|
|
a730ad1924 | ||
|
|
42c7b7f886 | ||
|
|
85fb5b436d | ||
|
|
c81f38d7ca | ||
|
|
be487ce65f | ||
|
|
0e0ebc7c9e | ||
|
|
7f3967d288 | ||
|
|
ade902f195 | ||
|
|
1bd94ac2b0 | ||
|
|
7deb338d4c | ||
|
|
2fa0e4b169 | ||
|
|
d11239fd95 |
+1
-6
@@ -530,7 +530,7 @@
|
||||
}
|
||||
},
|
||||
// Press feedback is owned by the primitives in components/ui. Raw pressable burn-down:
|
||||
// 94 files. They may only leave this list.
|
||||
// 85 files. They may only leave this list.
|
||||
{
|
||||
"files": [
|
||||
"packages/app/src/components/ui/**/*.{ts,tsx}",
|
||||
@@ -539,12 +539,9 @@
|
||||
"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",
|
||||
@@ -583,7 +580,6 @@
|
||||
"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",
|
||||
@@ -619,7 +615,6 @@
|
||||
"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",
|
||||
|
||||
@@ -156,8 +156,10 @@ keeps following.
|
||||
|
||||
Following resumes only for a gesture that ends within 1 px of the end, either when the finger lifts
|
||||
or when momentum stops. A release past the end counts: iOS bounces back to the end, and lines that
|
||||
land during the bounce must keep scrolling in. A release anywhere short of the end stays detached
|
||||
with the scroll-to-bottom pill, so the rows the user let go of never move.
|
||||
land during the bounce must keep scrolling in. A release short of the end stays detached with the scroll-to-bottom pill unless you submitted
|
||||
another prompt during that gesture. That submit requests the end after the gesture finishes;
|
||||
a new drag after submitting takes ownership again. Rewind and tail-fetch completions do not
|
||||
override a scroll away because they can arrive after the action that requested them.
|
||||
|
||||
### Draw distance
|
||||
|
||||
@@ -186,7 +188,8 @@ 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` covers Android; iOS has no native test harness.
|
||||
`VisibleContentPositionClampTest` and `SelectableTextTouchTest` cover 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
|
||||
@@ -206,5 +209,16 @@ 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
@@ -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 `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:
|
||||
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:
|
||||
|
||||
```bash
|
||||
cd packages/app/android
|
||||
|
||||
+10
-8
@@ -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 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.
|
||||
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.
|
||||
|
||||
Before adding a new component, read `components/ui/`. The primitive usually exists.
|
||||
|
||||
@@ -114,6 +114,8 @@ 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`.
|
||||
@@ -132,9 +134,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. 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 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 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.
|
||||
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`).
|
||||
|
||||
The whitespace is the design.
|
||||
|
||||
@@ -205,11 +207,11 @@ Terminology:
|
||||
|
||||
## 11. States
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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/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`.
|
||||
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`).
|
||||
|
||||
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.
|
||||
|
||||
@@ -231,13 +233,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`).
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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 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`).
|
||||
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`).
|
||||
|
||||
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`).
|
||||
|
||||
@@ -286,7 +288,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/provider-settings/internal/provider-list.tsx` |
|
||||
| Detail card+row | `packages/app/src/screens/settings/host-page.tsx`, `packages/app/src/screens/settings/providers-section.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
@@ -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 durable JSON metadata. Runtime files like pid files, sockets, and logs are not copied.
|
||||
- **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.
|
||||
- **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:
|
||||
|
||||
+39
-9
@@ -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.tsx` | 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/` | 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,6 +65,10 @@ 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
|
||||
@@ -280,6 +284,22 @@ 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
|
||||
@@ -422,9 +442,11 @@ 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 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`.
|
||||
- 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`.
|
||||
|
||||
## Recipe for a new anchored panel
|
||||
|
||||
@@ -453,6 +475,14 @@ 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.
|
||||
|
||||
|
||||
@@ -59,6 +59,8 @@ 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,6 +12,8 @@ Every block is separated by one gap, `density.blockGap`: 12 on compact layouts,
|
||||
|
||||
Workspace file links use the shared file-link resolver. The workspace supplies its client, root and open-file action once; chat can supply the agent's more specific context. URLs use the same link press path. Recognized inline-code paths stay tappable. The library callback carries the tapped occurrence’s syntax context. Preserve it when opening files: explicit Markdown links decode URL escapes, while recognized inline-code paths preserve literal percent characters and use suffix lookup. Identical URL strings in different occurrences must stay distinct. Explicit absolute workspace links receive a relative hover title; existing authored titles remain intact. Inside a workspace, forge references such as `#12` and `owner/repo#12` are recognized in prose (not code) and open the workspace forge; the reference pattern comes before path recognition so `group/project#12` is not read as a path. See [forge providers](forge-providers.md#gotchas).
|
||||
|
||||
Pass `external` for author-controlled Markdown from outside the host, such as a plugin README. It follows the registry's overview contract in `packages/protocol/src/plugin-overview.ts`, which the website also uses: only absolute https links and images work, and any other destination renders as its label or alt text. The parser still autolinks bare `http://`, `www.` and email text, so a link press checks the URL again and opens only https. None of the workspace recognition above applies, so `Node.js` is prose, not a file. The lines of a paragraph join, as they do on the README's forge.
|
||||
|
||||
Resolve workspace image paths over the existing session RPC, then give the library a cached native file URL or web blob URL. HTTP(S) images pass through unchanged. This preserves relay, SSH and local socket connections, which do not expose a daemon HTTP endpoint. Each mounted renderer owns its image acquisition identity, so a later reply reads a rewritten path again while the earlier mounted reply retains its snapshot. Image taps open the attachment lightbox. File previews resolve relative images against the Markdown file's directory. An image alone on its line becomes its own paragraph before the library sees it, so it renders as a block on every platform; the library only treats sole-child paragraph images as blocks, and with hard soft breaks every newline is a break node, which left own-line images inline on iOS and web. Images that share a line with text stay inline at line height and keep their aspect ratio. A linked image counts as an image, so review-bot badges such as `[](url) Confidence` stay inline on web; the library's web renderer only checked direct paragraph children, so it rendered them as full-width block images (local patch in `patches/react-native-enriched-markdown+*.patch`).
|
||||
|
||||
## Engine constraints
|
||||
|
||||
+4
-15
@@ -510,18 +510,6 @@ 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,
|
||||
@@ -885,9 +873,10 @@ await paseo.agents.ref(agentId).timeline.append({
|
||||
The daemon stamps the runtime `pluginId`; plugin code never supplies it. Reusing the same `id`
|
||||
replaces the previous row from that plugin on live clients and fresh timeline fetches. Rows live in
|
||||
the daemon's in-memory timeline and survive scroll, refetch, and reconnect, but not a daemon
|
||||
restart. A row without an installed renderer shows an unavailable placeholder. Serialized `data`
|
||||
must be at most 64 KiB; the daemon rejects a larger append instead of storing a payload that cannot
|
||||
be rendered intact. The daemon advertises this RPC through
|
||||
restart. A row without an installed renderer shows an unavailable placeholder. `kind` must match
|
||||
`/^[a-z][a-z0-9-]*$/`, the rule `addTimelineRenderer` enforces; the daemon rejects any other kind.
|
||||
Serialized `data` must be at most 64 KiB; the daemon rejects a larger append instead of storing a
|
||||
payload that cannot be rendered intact. The daemon advertises this RPC through
|
||||
`server_info.features.pluginTimelineItems`.
|
||||
|
||||
## Contribute client slash commands
|
||||
|
||||
@@ -263,50 +263,6 @@ 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
|
||||
|
||||
@@ -95,10 +95,11 @@ 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. 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.
|
||||
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.
|
||||
|
||||
## Resume behavior
|
||||
|
||||
|
||||
@@ -15,8 +15,7 @@ import {
|
||||
expectProviderInstalledInSettings,
|
||||
findAcpCatalogProvider,
|
||||
installAcpCatalogProvider,
|
||||
openAddProvider,
|
||||
openProviderDetail,
|
||||
openAddProviderArea,
|
||||
openSettingsHost,
|
||||
openSettingsHostSection,
|
||||
seedSavedSettingsHosts,
|
||||
@@ -48,7 +47,7 @@ test.describe("ACP provider catalog", () => {
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, getServerId());
|
||||
await openSettingsHostSection(page, getServerId(), "providers");
|
||||
await openAddProvider(page);
|
||||
await openAddProviderArea(page);
|
||||
|
||||
await installAcpCatalogProvider(page, ACP_PROVIDER.name);
|
||||
await expectProviderInstalledInSettings(page, ACP_PROVIDER.name);
|
||||
@@ -70,7 +69,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 openAddProvider(page);
|
||||
await openAddProviderArea(page);
|
||||
|
||||
await findAcpCatalogProvider(page, "fx");
|
||||
await page.screenshot({ path: testInfo.outputPath("fx-catalog.png") });
|
||||
@@ -105,7 +104,7 @@ for (const theme of ["light", "dark"] as const) {
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
|
||||
).toHaveCount(0);
|
||||
await openAddProvider(page);
|
||||
await openAddProviderArea(page);
|
||||
await findAcpCatalogProvider(page, "Hoplite");
|
||||
await page.screenshot({ path: testInfo.outputPath(`hoplite-catalog-${theme}.png`) });
|
||||
await installAcpCatalogProvider(page, "Hoplite");
|
||||
@@ -128,7 +127,7 @@ for (const theme of ["light", "dark"] as const) {
|
||||
testInfo.outputPath(`hoplite-removed-${theme}.json`),
|
||||
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
|
||||
);
|
||||
await openAddProvider(page);
|
||||
await openAddProviderArea(page);
|
||||
await findAcpCatalogProvider(page, "Hoplite");
|
||||
await page.screenshot({ path: testInfo.outputPath(`hoplite-removed-${theme}.png`) });
|
||||
await installAcpCatalogProvider(page, "Hoplite");
|
||||
@@ -141,11 +140,11 @@ for (const theme of ["light", "dark"] as const) {
|
||||
}
|
||||
|
||||
async function removeHoplite(page: import("@playwright/test").Page): Promise<void> {
|
||||
await openProviderDetail(page, "Hoplite");
|
||||
await page.getByTestId("provider-actions-hoplite").click();
|
||||
page.once("dialog", (dialog) => {
|
||||
void dialog.accept();
|
||||
});
|
||||
await page.getByTestId("provider-remove").click();
|
||||
await page.getByTestId("provider-remove-hoplite").click();
|
||||
}
|
||||
|
||||
test("unsupported host asks for an update without writing Hoplite config", async ({
|
||||
@@ -165,7 +164,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 openAddProvider(page);
|
||||
await openAddProviderArea(page);
|
||||
await page.getByRole("button", { name: "Add Hoplite", exact: true }).click();
|
||||
const errorToast = page.getByTestId("app-toast-message");
|
||||
await expect(errorToast).toHaveText("Update the host to add Hoplite.");
|
||||
|
||||
@@ -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 agent", async ({
|
||||
test("agent list age advances and command center says just now for a fresh workspace", async ({
|
||||
page,
|
||||
}) => {
|
||||
const session = await seedMockAgentWorkspace({
|
||||
@@ -23,10 +23,10 @@ test("agent list age advances and command center says just now for a fresh agent
|
||||
|
||||
const commandCenter = await openCommandCenter(page);
|
||||
await commandCenter.getByTestId("command-center-input").fill("Relative time agent");
|
||||
const agentResult = commandCenter.getByTestId(
|
||||
`command-center-agent-${getServerId()}:${session.agentId}`,
|
||||
const workspaceResult = commandCenter.getByTestId(
|
||||
`command-center-workspace-${getServerId()}:${session.workspaceId}`,
|
||||
);
|
||||
await expect(agentResult.getByTestId("command-center-result-timestamp")).toContainText(
|
||||
await expect(workspaceResult.getByTestId("command-center-result-timestamp")).toContainText(
|
||||
"just now",
|
||||
);
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import { openWorkspaceFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
|
||||
import { projectEquivalenceViewKey } from "../support/helpers/project-view-key";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { expectWorkspaceAbsentFromSidebar } from "../support/helpers/sidebar";
|
||||
|
||||
async function isWorkspaceListed(seeded: SeededWorkspace): Promise<boolean> {
|
||||
const result = await seeded.client.fetchWorkspaces();
|
||||
return result.entries.some((entry) => entry.id === seeded.workspaceId);
|
||||
}
|
||||
|
||||
async function expectWorkspaceArchivedOnDaemon(seeded: SeededWorkspace): Promise<void> {
|
||||
await expect.poll(() => isWorkspaceListed(seeded), { timeout: 30_000 }).toBe(false);
|
||||
}
|
||||
|
||||
test.describe("Command center archive for a non-Git workspace", () => {
|
||||
test("archives a plain directory workspace from the command center", async ({ page }) => {
|
||||
const title = "Command Center Directory Archive";
|
||||
const seeded = await seedWorkspace({ repoPrefix: "cc-archive-dir-", title, git: false });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openWorkspaceFromCommandCenter(page, seeded, title);
|
||||
|
||||
const panel = await openCommandCenter(page);
|
||||
await panel.getByTestId("command-center-input").fill("archive");
|
||||
const archive = panel.getByRole("button", { name: /^Archive(?: workspace)?(?:\s|$)/ });
|
||||
await expect(archive).toBeVisible({ timeout: 30_000 });
|
||||
await archive.click();
|
||||
|
||||
await expectWorkspaceAbsentFromSidebar(page, seeded.workspaceId);
|
||||
expect(existsSync(seeded.repoPath)).toBe(true);
|
||||
} finally {
|
||||
await seeded.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives a plain directory workspace from the command center with the sidebar closed", async ({
|
||||
page,
|
||||
}) => {
|
||||
const title = "Command Center Directory Archive Closed Sidebar";
|
||||
const seeded = await seedWorkspace({ repoPrefix: "cc-archive-dir-closed-", title, git: false });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openWorkspaceFromCommandCenter(page, seeded, title);
|
||||
|
||||
await page.getByTestId("menu-button").click();
|
||||
await expect(page.getByTestId("sidebar-search")).toBeHidden({ timeout: 10_000 });
|
||||
|
||||
const modifier = process.platform === "darwin" ? "Meta" : "Control";
|
||||
await page.keyboard.press(`${modifier}+k`);
|
||||
const panel = page.getByTestId("command-center-panel");
|
||||
await expect(panel).toBeVisible({ timeout: 30_000 });
|
||||
await panel.getByTestId("command-center-input").fill("archive");
|
||||
const archive = panel.getByRole("button", { name: /^Archive(?: workspace)?(?:\s|$)/ });
|
||||
await expect(archive).toBeVisible({ timeout: 30_000 });
|
||||
await archive.click();
|
||||
|
||||
await expectWorkspaceArchivedOnDaemon(seeded);
|
||||
} finally {
|
||||
await seeded.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives a plain directory workspace from the command center with its project collapsed", async ({
|
||||
page,
|
||||
}) => {
|
||||
const title = "Command Center Directory Archive Collapsed Project";
|
||||
const seeded = await seedWorkspace({
|
||||
repoPrefix: "cc-archive-dir-collapsed-",
|
||||
title,
|
||||
git: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openWorkspaceFromCommandCenter(page, seeded, title);
|
||||
|
||||
const workspaceRow = page.getByTestId(
|
||||
`sidebar-workspace-row-${getServerId()}:${seeded.workspaceId}`,
|
||||
);
|
||||
await expect(workspaceRow).toBeVisible({ timeout: 30_000 });
|
||||
await page
|
||||
.getByTestId(`sidebar-project-row-${projectEquivalenceViewKey(seeded.projectKey)}`)
|
||||
.first()
|
||||
.click();
|
||||
await expect(workspaceRow).toHaveCount(0, { timeout: 10_000 });
|
||||
|
||||
const panel = await openCommandCenter(page);
|
||||
await panel.getByTestId("command-center-input").fill("archive");
|
||||
const archive = panel.getByRole("button", { name: /^Archive(?: workspace)?(?:\s|$)/ });
|
||||
await expect(archive).toBeVisible({ timeout: 30_000 });
|
||||
await archive.click();
|
||||
|
||||
await expectWorkspaceArchivedOnDaemon(seeded);
|
||||
} finally {
|
||||
await seeded.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,12 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import { openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
closeCommandCenter,
|
||||
expectCommandCenterTab,
|
||||
expectCommandCenterTabs,
|
||||
openCommandCenter,
|
||||
selectCommandCenterTab,
|
||||
} from "../support/helpers/command-center";
|
||||
import {
|
||||
delayDirectorySuggestionResponses,
|
||||
holdDirectorySuggestionResponses,
|
||||
@@ -17,6 +24,7 @@ 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 =
|
||||
@@ -67,7 +75,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 expect(panel.getByRole("button", { name: "Files" })).toBeVisible();
|
||||
await expectCommandCenterTab(panel, "Files");
|
||||
await startCommandCenterLayoutObservation(page);
|
||||
|
||||
await panel.getByTestId("command-center-input").fill(FILE_NAME);
|
||||
@@ -97,26 +105,90 @@ test("workspace file search stays geometrically stable through delayed loading a
|
||||
}
|
||||
});
|
||||
|
||||
test("dropping the files scope leaves the search row the same height", async ({ page }) => {
|
||||
test("command center tabs rotate with Tab and never move the header", async ({ page }) => {
|
||||
const seeded = await seedWorkspace({
|
||||
repoPrefix: "command-center-file-search-scope-",
|
||||
title: "Scope chip height",
|
||||
repoPrefix: "command-center-tabs-",
|
||||
title: "Tab rotation",
|
||||
});
|
||||
|
||||
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 scoped = await header.boundingBox();
|
||||
const input = panel.getByTestId("command-center-input");
|
||||
|
||||
await page.getByTestId("command-center-files-scope").click();
|
||||
await expect(page.getByTestId("command-center-files-scope")).toHaveCount(0);
|
||||
const unscoped = 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");
|
||||
});
|
||||
|
||||
expect(scoped?.height).toBe(unscoped?.height);
|
||||
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);
|
||||
});
|
||||
} finally {
|
||||
await seeded.cleanup();
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import {
|
||||
searchCommandCenter,
|
||||
warmCommandCenterRows,
|
||||
expectOnlyCommandCenterRowRendered,
|
||||
expectCommandCenterAgentWindow,
|
||||
scrollToOldestCommandCenterAgent,
|
||||
expectCommandCenterWorkspaceWindow,
|
||||
scrollToOldestCommandCenterWorkspace,
|
||||
} from "../support/helpers/command-center-performance";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
expectPrimaryCommandCenterActions,
|
||||
expectTightTwoLineResultSpacing,
|
||||
expectVisibleKeyboardNavigationNotToScroll,
|
||||
expectWorkspaceResultsToBeLimitedUntilSearch,
|
||||
expectRecentWorkspacesUntilSearch,
|
||||
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);
|
||||
// The empty query lists the most recent workspaces, so the last one seeded leads it.
|
||||
// All leads with the most recent workspaces, so the last one seeded leads it.
|
||||
await expectTightTwoLineResultSpacing(panel, "Command Center Scroll 08");
|
||||
await expectWorkspaceResultsToBeLimitedUntilSearch(panel);
|
||||
await expectRecentWorkspacesUntilSearch(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,42 +76,50 @@ test("Command Center preserves manual scrolling through live updates and resumes
|
||||
}
|
||||
});
|
||||
|
||||
test("live search updates render only the changed row and keep agents virtualized", async ({
|
||||
test("live search updates render only the changed row and keep workspaces 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 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 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 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("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 agent");
|
||||
await warmCommandCenterRows(page);
|
||||
await scrollToOldestCommandCenterAgent(panel);
|
||||
await expect(panel.getByText("Search agent 000", { exact: true })).toBeVisible();
|
||||
await expectCommandCenterAgentWindow(panel, seeded.agents.length);
|
||||
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);
|
||||
});
|
||||
} finally {
|
||||
await seeded.cleanup();
|
||||
}
|
||||
|
||||
@@ -4,7 +4,12 @@ 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 { openCommandCenter } from "../support/helpers/command-center";
|
||||
import {
|
||||
commandCenterSection,
|
||||
expectCommandCenterTab,
|
||||
openCommandCenter,
|
||||
selectCommandCenterTab,
|
||||
} 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";
|
||||
@@ -21,9 +26,7 @@ const AGENT_TITLE = "Fix checkout retries";
|
||||
test.describe("Command center workspaces", () => {
|
||||
test.describe.configure({ timeout: 180_000 });
|
||||
|
||||
test("agent and workspace results retain their icons and overlay live status", async ({
|
||||
page,
|
||||
}) => {
|
||||
test("workspace results overlay live status", async ({ page }) => {
|
||||
const workspace = await seedRunningMockAgentWorkspace({
|
||||
repoPrefix: "command-center-status-",
|
||||
title: "Review checkout retries",
|
||||
@@ -34,15 +37,13 @@ test.describe("Command center workspaces", () => {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectAgentTabActive(page, workspace.agentId);
|
||||
const panel = await openCommandCenter(page);
|
||||
const agent = panel.getByTestId(`command-center-agent-${getServerId()}:${workspace.agentId}`);
|
||||
// Recent workspaces leaves out the open one; the Workspaces tab lists every workspace.
|
||||
await selectCommandCenterTab(panel, "Workspaces");
|
||||
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();
|
||||
@@ -80,9 +81,11 @@ 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);
|
||||
@@ -92,65 +95,151 @@ 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);
|
||||
|
||||
// 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("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();
|
||||
});
|
||||
|
||||
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 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 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,
|
||||
}) => {
|
||||
@@ -229,7 +318,7 @@ test.describe("Compact sidebar inspection", () => {
|
||||
title: "Compact destination",
|
||||
});
|
||||
try {
|
||||
const agent = await createIdleAgent(seeded.client, {
|
||||
await createIdleAgent(seeded.client, {
|
||||
cwd: seeded.repoPath,
|
||||
workspaceId: seeded.workspaceId,
|
||||
title: "Compact root agent",
|
||||
@@ -246,7 +335,10 @@ 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-agent-${getServerId()}:${agent.id}`).click();
|
||||
await agentSearch
|
||||
.getByTestId(`command-center-workspace-${getServerId()}:${seeded.workspaceId}`)
|
||||
.getByTestId("command-center-workspace-agent")
|
||||
.click();
|
||||
await expect(page.getByRole("button", { name: "Open menu", exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("textbox", { name: "Message agent...", exact: true }),
|
||||
|
||||
@@ -787,9 +787,22 @@ test.describe("Composer autocomplete", () => {
|
||||
await input.press("ArrowDown");
|
||||
await input.press("ArrowDown");
|
||||
await input.press("h");
|
||||
await expect(popover.getByText("/help", { exact: true }).first()).toBeVisible();
|
||||
// On web the search reads the cursor after paint, so the input's value runs ahead of
|
||||
// the list. Wait on the list itself. The list mounts only the rows near its scroll
|
||||
// position, so one missing row proves nothing: right after the arrows wrap to the top,
|
||||
// /tdd at the bottom is unmounted while the search is still "". With the search at "",
|
||||
// the list always mounts the bottom row (/tdd) or the chosen one (/exit); only the
|
||||
// search "h" leaves both out. Check them in one query so no frame falls between them.
|
||||
await expect(
|
||||
popover.filter({
|
||||
has: page.getByText("/help", { exact: true }),
|
||||
hasNot: page.getByText(/^\/(tdd|exit)$/),
|
||||
}),
|
||||
).toBeVisible();
|
||||
await input.press("Backspace");
|
||||
await expect(input).toHaveValue("/");
|
||||
// /tdd is back only once the search is "" again.
|
||||
await expect(popover.getByText("/tdd", { exact: true }).first()).toBeVisible();
|
||||
await input.press("Enter");
|
||||
|
||||
await expect(input).toHaveValue("/tdd ");
|
||||
|
||||
@@ -148,6 +148,23 @@ 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,
|
||||
|
||||
@@ -20,6 +20,21 @@ function explorerSidebar(page: Parameters<typeof ensureExplorerSidebar>[0]) {
|
||||
return page.getByTestId("workspace-explorer-sidebar").filter({ visible: true });
|
||||
}
|
||||
|
||||
const LAYOUT_VIEWPORTS = {
|
||||
compact: { width: 390, height: 844 },
|
||||
wide: { width: 1280, height: 900 },
|
||||
};
|
||||
|
||||
// The previous layout stays on screen for a few renders after the resize. Wait for the shell to
|
||||
// switch so the next step reads the layout it resized to.
|
||||
async function resizeToLayout(
|
||||
page: Parameters<typeof ensureExplorerSidebar>[0],
|
||||
layout: keyof typeof LAYOUT_VIEWPORTS,
|
||||
) {
|
||||
await page.setViewportSize(LAYOUT_VIEWPORTS[layout]);
|
||||
await expect(page.getByTestId(`${layout}-shell`)).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectExplorerActiveTabForeground(
|
||||
page: Parameters<typeof ensureExplorerSidebar>[0],
|
||||
) {
|
||||
@@ -244,7 +259,7 @@ test("tablet prototype keeps Explorer tabs when resizing down to a phone", async
|
||||
await page.screenshot({ path: testInfo.outputPath("tablet-951.png") });
|
||||
await openExplorerAgentDraft(page);
|
||||
await page.screenshot({ path: testInfo.outputPath("tablet-agent-draft.png") });
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await resizeToLayout(page, "compact");
|
||||
await revealPhoneExplorer(page);
|
||||
await expect(
|
||||
explorerSidebar(page).getByRole("button", { name: "New tab", exact: true }),
|
||||
@@ -289,10 +304,10 @@ test("retains the Explorer host through appearance changes and folding", async (
|
||||
.poll(() => explorer.evaluate((element) => getComputedStyle(element).backgroundColor))
|
||||
.not.toBe(previousColor);
|
||||
expect(await host.evaluate((element) => element.isConnected)).toBe(true);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await resizeToLayout(page, "compact");
|
||||
await ensureExplorerSidebar(page);
|
||||
expect(await host.evaluate((element) => element.isConnected)).toBe(true);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await resizeToLayout(page, "wide");
|
||||
await expect(explorer).toBeVisible();
|
||||
expect(await host.evaluate((element) => element.isConnected)).toBe(true);
|
||||
} finally {
|
||||
@@ -327,7 +342,7 @@ test("reorders compact Explorer tabs with a pointer without changing selection",
|
||||
const workspace = await seedWorkspace({ repoPrefix: "explorer-compact-drag-" });
|
||||
try {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await resizeToLayout(page, "compact");
|
||||
await openFilesPanel(page);
|
||||
await reorderCompactExplorerTabs(page);
|
||||
await expect(
|
||||
@@ -394,9 +409,9 @@ test("updates populated code and diff appearance without losing the editor insta
|
||||
.getByTestId("file-source-editor")
|
||||
.elementHandle();
|
||||
await text.fill(`${source}\n// retained Explorer edit`);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await resizeToLayout(page, "compact");
|
||||
await ensureExplorerSidebar(page);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await resizeToLayout(page, "wide");
|
||||
expect(await explorerEditor!.evaluate((node) => node.isConnected)).toBe(true);
|
||||
await expect(text).toContainText("retained Explorer edit");
|
||||
} finally {
|
||||
@@ -461,9 +476,9 @@ test("retains populated Explorer chat and terminal attachments through appearanc
|
||||
const terminalNode = await terminal.elementHandle();
|
||||
await page.getByTestId("workspace-explorer-toggle").first().click();
|
||||
await ensureExplorerSidebar(page);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await resizeToLayout(page, "compact");
|
||||
await ensureExplorerSidebar(page);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await resizeToLayout(page, "wide");
|
||||
await cycleWorkspaceTheme(page);
|
||||
expect(await terminalNode!.evaluate((node) => node.isConnected)).toBe(true);
|
||||
expect(attaches).toHaveLength(1);
|
||||
@@ -483,7 +498,7 @@ test("compact file sheets cover Explorer and return to its retained file list",
|
||||
try {
|
||||
await writeFile(`${workspace.repoPath}/sheet-marker.txt`, "Explorer sheet marker\n");
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await resizeToLayout(page, "compact");
|
||||
const explorer = await ensureExplorerSidebar(page);
|
||||
await openFilesPanel(page);
|
||||
const host = await explorer.elementHandle();
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { test } from "../support/fixtures";
|
||||
import { gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
|
||||
|
||||
const HEADER_ICON_BUTTONS = ["workspace-header-menu-trigger", "workspace-explorer-toggle"];
|
||||
|
||||
function visible(page: Page, testId: string): Locator {
|
||||
return page.getByTestId(testId).filter({ visible: true }).first();
|
||||
}
|
||||
|
||||
function matchesFocusVisible(target: Locator): Promise<boolean> {
|
||||
return target.evaluate((el) => el.matches(":focus-visible"));
|
||||
}
|
||||
|
||||
async function expectKeyboardFocusRing(page: Page, testId: string): Promise<void> {
|
||||
const button = visible(page, testId);
|
||||
// Chromium matches :focus-visible on a programmatic focus that follows keyboard input.
|
||||
await page.keyboard.press("Shift");
|
||||
await button.focus();
|
||||
await expect(button).toBeFocused();
|
||||
expect(await matchesFocusVisible(button)).toBe(true);
|
||||
await expect(button).toHaveCSS("outline-style", "solid");
|
||||
await expect(button).toHaveCSS("outline-width", "2px");
|
||||
// Header rows clip overflow; an outset ring would lose its top and bottom edges.
|
||||
await expect(button).toHaveCSS("outline-offset", "-2px");
|
||||
}
|
||||
|
||||
async function expectNoPointerFocusRing(page: Page, testId: string): Promise<void> {
|
||||
const button = visible(page, testId);
|
||||
await button.blur();
|
||||
// Toggle twice so the layout ends where it started.
|
||||
await button.click();
|
||||
await button.click();
|
||||
await expect(button).toBeFocused();
|
||||
expect(await matchesFocusVisible(button)).toBe(false);
|
||||
await expect(button).toHaveCSS("outline-style", "none");
|
||||
}
|
||||
|
||||
test.describe("Icon button focus ring", () => {
|
||||
test("header icon buttons show the focus ring for keyboard focus only", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
const workspace = await seedWorkspace({ repoPrefix: "icon-button-focus-" });
|
||||
try {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await waitForWorkspaceTabsVisible(page);
|
||||
for (const testId of HEADER_ICON_BUTTONS) {
|
||||
await expectKeyboardFocusRing(page, testId);
|
||||
}
|
||||
await expectNoPointerFocusRing(page, "workspace-explorer-toggle");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -125,12 +125,15 @@ 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 countBefore = await newTabs.count();
|
||||
const openedCount = await newTabs.count();
|
||||
await pressNewTabShortcut(page);
|
||||
await expect(newTabs).toHaveCount(openedCount + 1);
|
||||
const countBefore = openedCount + 1;
|
||||
const draftCount = await countTabsOfKind(page, "draft");
|
||||
|
||||
await test.step("opening the plus menu leaves the current tabs intact", async () => {
|
||||
|
||||
@@ -160,6 +160,22 @@ 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,
|
||||
}) => {
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
addProjectFromSetup,
|
||||
continueSetup,
|
||||
expectSetupStep,
|
||||
expectSheetCoversSetupCard,
|
||||
finishSetup,
|
||||
goToSetupStep,
|
||||
hostGivesAgentsPaseoTools,
|
||||
@@ -24,7 +23,6 @@ import {
|
||||
recordFirstLaunch,
|
||||
setupModal,
|
||||
setupPrimaryButton,
|
||||
setupSheet,
|
||||
showSetupAgainFromSettings,
|
||||
skipSetup,
|
||||
startSetupHost,
|
||||
@@ -37,11 +35,7 @@ import {
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { enableRelayAndExpectOffer } from "../support/helpers/pair-device";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import {
|
||||
installAcpCatalogProvider,
|
||||
openAddProvider,
|
||||
openSettingsHostSection,
|
||||
} from "../support/helpers/settings";
|
||||
import { openSettingsHostSection } from "../support/helpers/settings";
|
||||
import { createTempDirectory, createTempGitRepo } from "../support/helpers/workspace";
|
||||
|
||||
// Midnight's muted foreground (#9a9db0), which the step description is drawn in.
|
||||
@@ -65,28 +59,11 @@ 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 providers");
|
||||
await expectSetupStep(page, "Your agents");
|
||||
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");
|
||||
@@ -126,33 +103,6 @@ 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");
|
||||
|
||||
@@ -195,7 +145,7 @@ test("changing the theme keeps the setup window in place on every step", async (
|
||||
|
||||
for (const title of [
|
||||
"Welcome to Paseo",
|
||||
"Your providers",
|
||||
"Your agents",
|
||||
"Add your projects",
|
||||
"Let agents use Paseo",
|
||||
"Take your agents with you",
|
||||
@@ -468,7 +418,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 providers");
|
||||
await step("Your agents");
|
||||
await primary("Continue").click();
|
||||
await step("Add your projects");
|
||||
await primary("Continue").click();
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import {
|
||||
test,
|
||||
expectStillBrowsing,
|
||||
installFromPage,
|
||||
installListingFromRow,
|
||||
openDirectory,
|
||||
openFromInstalledTab,
|
||||
openListingPage,
|
||||
uninstallFromPage,
|
||||
} from "../support/helpers/plugin-directory";
|
||||
|
||||
test("installs a listed plugin from Browse and uninstalls it from either of its pages", async ({
|
||||
page,
|
||||
directoryHost,
|
||||
}) => {
|
||||
await openDirectory(page, directoryHost);
|
||||
await installListingFromRow(page);
|
||||
await expectStillBrowsing(page);
|
||||
await openListingPage(page);
|
||||
await uninstallFromPage(page);
|
||||
await installFromPage(page);
|
||||
await openFromInstalledTab(page);
|
||||
await uninstallFromPage(page);
|
||||
});
|
||||
@@ -14,6 +14,44 @@ import { daemonWsRoutePattern } from "../support/helpers/daemon-port";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
|
||||
import {
|
||||
backToPlugins,
|
||||
clearSearch,
|
||||
closePluginLogs,
|
||||
expectGalleryMenuWithoutSourceInstall,
|
||||
expectPluginActionPending,
|
||||
expectPluginFailed,
|
||||
expectPluginHealthy,
|
||||
expectPluginOff,
|
||||
expectPluginOn,
|
||||
expectPluginRemoved,
|
||||
expectPluginsOff,
|
||||
expectPluginsOn,
|
||||
expectPluginsRoute,
|
||||
expectSourceInstallFailed,
|
||||
expectSourceInstallTurnsPluginsOn,
|
||||
expectSourceInstalled,
|
||||
expectToast,
|
||||
expectUpdateAvailable,
|
||||
installFromSource,
|
||||
openPluginLogs,
|
||||
openPluginPage,
|
||||
openPluginPageActions,
|
||||
openSourceInstall,
|
||||
pluginRow,
|
||||
reloadPluginFromPage,
|
||||
removePluginFromPage,
|
||||
searchInstalled,
|
||||
selectInstalledTab,
|
||||
selectPluginPageAction,
|
||||
submitSourceInstall,
|
||||
turnOffPluginsFromMenu,
|
||||
turnOnPluginsFromAlert,
|
||||
turnOnPluginsFromMenu,
|
||||
turnPluginOff,
|
||||
turnPluginOn,
|
||||
updatePlugin,
|
||||
} from "../support/helpers/plugin-gallery";
|
||||
import {
|
||||
expectSettingsHeader,
|
||||
openCompactSettings,
|
||||
@@ -170,22 +208,12 @@ async function openCompactPluginSettings(page: Page): Promise<void> {
|
||||
const serverId = getServerId();
|
||||
await openCompactSettings(page, buildOpenProjectRoute());
|
||||
await openHostSection(page, serverId, "plugins");
|
||||
await expect(page.getByRole("textbox", { name: "Plugin source", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: /^Installed/ })).toBeVisible();
|
||||
}
|
||||
|
||||
async function reloadPlugin(page: Page): Promise<void> {
|
||||
await selectPluginAction(page, "e2e-plugin", "Reload");
|
||||
await expect(page.getByText("Reloaded e2e-plugin", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function openPluginActions(page: Page, pluginId: string): Promise<void> {
|
||||
await page.getByRole("button", { name: `Actions for ${pluginId}`, exact: true }).click();
|
||||
await expect(page.getByRole("menuitem").first()).toBeVisible();
|
||||
}
|
||||
|
||||
async function selectPluginAction(page: Page, pluginId: string, action: string): Promise<void> {
|
||||
await openPluginActions(page, pluginId);
|
||||
await page.getByRole("menuitem", { name: action, exact: true }).click();
|
||||
async function openPluginPageFromSettings(page: Page, name: string): Promise<void> {
|
||||
await openPluginSettings(page);
|
||||
await openPluginPage(page, name);
|
||||
}
|
||||
|
||||
async function expectContributionBody(page: Page, expectedBody: string): Promise<void> {
|
||||
@@ -238,11 +266,6 @@ async function capturePluginInstallForm(
|
||||
});
|
||||
}
|
||||
|
||||
async function installPlugin(page: Page, source: string): Promise<void> {
|
||||
await page.getByLabel("Plugin source").fill(source);
|
||||
await page.getByRole("button", { name: "Install plugin" }).click();
|
||||
}
|
||||
|
||||
async function expectPluginSourceDocsOpen(page: Page): Promise<void> {
|
||||
const requestedPage = page
|
||||
.context()
|
||||
@@ -266,6 +289,17 @@ async function expectPluginSourceDocsOpen(page: Page): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function commitAll(repository: string, message: string): void {
|
||||
execFileSync("git", ["add", "-A"], { cwd: repository, stdio: "ignore" });
|
||||
execFileSync("git", ["commit", "-m", message], { cwd: repository, stdio: "ignore" });
|
||||
}
|
||||
|
||||
/** A new commit on the remote is an update for a plugin installed from that Git repository. */
|
||||
async function publishGitPluginChange(repository: string, title: string): Promise<void> {
|
||||
await writeFile(path.join(repository, "index.client.tsx"), pluginSource(title));
|
||||
commitAll(repository, title);
|
||||
}
|
||||
|
||||
async function createGitPluginRepository(root: string): Promise<string> {
|
||||
const repository = path.join(root, "repository");
|
||||
await mkdir(repository);
|
||||
@@ -359,14 +393,12 @@ async function createGatedBuildRepository(
|
||||
}
|
||||
|
||||
async function installFailedPlugin(
|
||||
page: Page,
|
||||
client: Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>,
|
||||
directory: string,
|
||||
): Promise<void> {
|
||||
await client.installPluginSource({ source: directory });
|
||||
await writeFile(path.join(directory, "index.client.tsx"), "export default broken !!!");
|
||||
await client.reloadPlugin("failed-preview-plugin");
|
||||
await expect(page.getByLabel("failed-preview-plugin failed")).toBeVisible();
|
||||
}
|
||||
|
||||
test("installs, reloads, recovers, disables, and removes a trusted local plugin", async ({
|
||||
@@ -378,12 +410,15 @@ test("installs, reloads, recovers, disables, and removes a trusted local plugin"
|
||||
await toggleRemoveAndReinstallLocalPlugin(page, directory);
|
||||
});
|
||||
|
||||
test("installs a Git source after a failed source remains editable", async ({
|
||||
test("installs a Git source after a failed source remains editable, then updates it", async ({
|
||||
page,
|
||||
pluginEnvironment,
|
||||
}, testInfo) => {
|
||||
const source = await prepareCompactGitInstall(page, pluginEnvironment);
|
||||
await retryGitInstallAndInspectRows(page, source, testInfo);
|
||||
await updateGitPlugin(page, source.repository);
|
||||
await expectCompactPluginMenuFits(page, testInfo);
|
||||
await failUpdateFromPluginPage(page, source.repository);
|
||||
});
|
||||
|
||||
for (const sourceSupport of [undefined, false]) {
|
||||
@@ -400,7 +435,7 @@ for (const viewport of [
|
||||
{ width: 1280, height: 900 },
|
||||
{ width: 390, height: 844 },
|
||||
]) {
|
||||
test(`installs an npm source and manages its row at ${viewport.width}px`, async ({
|
||||
test(`installs an npm source and manages it at ${viewport.width}px`, async ({
|
||||
page,
|
||||
pluginEnvironment,
|
||||
}, testInfo) => {
|
||||
@@ -415,18 +450,19 @@ async function openNpmPluginSettings(page: Page, width: number) {
|
||||
else await openPluginSettings(page);
|
||||
}
|
||||
|
||||
async function expectSourceHierarchy(page: Page, description: string, source: string) {
|
||||
const descriptionText = page.getByText(description, { exact: false });
|
||||
const sourceText = page.getByText(source, { exact: false });
|
||||
const descriptionSize = await descriptionText.evaluate((element) =>
|
||||
Number.parseFloat(getComputedStyle(element).fontSize),
|
||||
/** The row's description reads before where the plugin was installed from. */
|
||||
async function expectSourceHierarchy(
|
||||
page: Page,
|
||||
pluginId: string,
|
||||
description: string,
|
||||
source: string,
|
||||
) {
|
||||
const row = pluginRow(page, pluginId);
|
||||
await expect(row.getByText(description, { exact: true })).toHaveCSS(
|
||||
"color",
|
||||
"rgb(113, 113, 122)",
|
||||
);
|
||||
const sourceSize = await sourceText.evaluate((element) =>
|
||||
Number.parseFloat(getComputedStyle(element).fontSize),
|
||||
);
|
||||
expect(sourceSize).toBeLessThan(descriptionSize);
|
||||
await expect(sourceText).toHaveCSS("color", "rgb(161, 161, 170)");
|
||||
await expect(descriptionText).toHaveCSS("color", "rgb(113, 113, 122)");
|
||||
await expect(row.getByText(source, { exact: true })).toHaveCSS("color", "rgb(161, 161, 170)");
|
||||
}
|
||||
|
||||
async function installLocalPluginWithStatusExamples(
|
||||
@@ -457,36 +493,51 @@ async function installLocalPluginWithStatusExamples(
|
||||
}),
|
||||
);
|
||||
await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Plugin v1"));
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installPluginSource({ source: disabledDirectory });
|
||||
await client.disablePlugin("disabled-preview-plugin-with-a-long-name");
|
||||
await installFailedPlugin(client, failedDirectory);
|
||||
|
||||
const catalog = observePluginCatalog(page);
|
||||
await gotoAppShell(page);
|
||||
await openPluginSettings(page);
|
||||
await catalog.waitForInitialFetch();
|
||||
await expect(page.getByRole("textbox", { name: "Plugin installation ID" })).toHaveCount(0);
|
||||
await expectPluginSourceDocsOpen(page);
|
||||
await expectPluginFailed(page, "failed-preview-plugin");
|
||||
|
||||
// Plugins off on the host: the Installed tab says so and turns them back on.
|
||||
await client.patchDaemonConfig({ pluginsEnabled: false });
|
||||
await page.getByRole("switch", { name: "Enable plugins" }).click();
|
||||
await expect(page.getByText("Plugins enabled", { exact: true })).toBeVisible();
|
||||
await client.installPluginSource({ source: disabledDirectory });
|
||||
await client.disablePlugin("disabled-preview-plugin-with-a-long-name");
|
||||
await installFailedPlugin(page, client, failedDirectory);
|
||||
await page.getByLabel("Plugin source").fill(directory);
|
||||
await page.getByRole("button", { name: "Install plugin" }).click();
|
||||
await expect(page.getByText("Installed e2e-plugin", { exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel("e2e-plugin running")).toBeVisible();
|
||||
await expectPluginsOff(page);
|
||||
await turnOnPluginsFromAlert(page);
|
||||
await turnOffPluginsFromMenu(page);
|
||||
await turnOnPluginsFromMenu(page);
|
||||
|
||||
await openSourceInstall(page);
|
||||
await expectPluginSourceDocsOpen(page);
|
||||
await submitSourceInstall(page, directory);
|
||||
await expectSourceInstalled(page, "e2e-plugin");
|
||||
await expectPluginOn(page, "e2e-plugin");
|
||||
await expectPluginHealthy(page, "e2e-plugin");
|
||||
await expect(page.getByText("Exercises the complete local plugin lifecycle")).toBeVisible();
|
||||
await expect(
|
||||
page.getByText("Keeps optional previews off until this plugin is enabled"),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText("Demonstrates a plugin that needs attention")).toBeVisible();
|
||||
await expect(page.getByLabel("disabled-preview-plugin-with-a-long-name disabled")).toBeVisible();
|
||||
await expect(page.getByLabel("failed-preview-plugin failed")).toBeVisible();
|
||||
await expectPluginOff(page, "disabled-preview-plugin-with-a-long-name");
|
||||
await expectPluginFailed(page, "failed-preview-plugin");
|
||||
|
||||
await searchInstalled(page, "needs attention");
|
||||
await expect(pluginRow(page, "failed-preview-plugin")).toBeVisible();
|
||||
await expect(pluginRow(page, "e2e-plugin")).toHaveCount(0);
|
||||
await clearSearch(page);
|
||||
await expect(pluginRow(page, "e2e-plugin")).toBeVisible();
|
||||
await capturePluginInstallForm(page, testInfo, "wide");
|
||||
await openPluginActions(page, "e2e-plugin");
|
||||
|
||||
await openPluginPage(page, "e2e-plugin");
|
||||
await openPluginPageActions(page, "e2e-plugin");
|
||||
await capturePluginInstallForm(page, testInfo, "wide-menu");
|
||||
await page.getByRole("menuitem", { name: "Logs", exact: true }).click();
|
||||
await expect(page.getByRole("dialog")).toContainText("Logs: e2e-plugin");
|
||||
await page.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await page.keyboard.press("Escape");
|
||||
await openPluginLogs(page, "e2e-plugin");
|
||||
await closePluginLogs(page);
|
||||
await openContributionFromSettings(page, "Plugin v1", "Plugin v1 cleanup 0");
|
||||
|
||||
return directory;
|
||||
@@ -497,13 +548,13 @@ async function reloadAndRecoverLocalPlugin(
|
||||
client: PluginEnvironment["client"],
|
||||
directory: string,
|
||||
) {
|
||||
await openPluginSettings(page);
|
||||
await reloadPlugin(page);
|
||||
await openPluginPageFromSettings(page, "e2e-plugin");
|
||||
await reloadPluginFromPage(page, "e2e-plugin");
|
||||
await openContributionFromSettings(page, "Plugin v1", "Plugin v1 cleanup 1");
|
||||
|
||||
await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Plugin v2"));
|
||||
await openPluginSettings(page);
|
||||
await reloadPlugin(page);
|
||||
await openPluginPageFromSettings(page, "e2e-plugin");
|
||||
await reloadPluginFromPage(page, "e2e-plugin");
|
||||
await openContributionFromSettings(page, "Plugin v2", "Plugin v2 cleanup 2");
|
||||
await expect(page.getByRole("button", { name: "Plugin v1", exact: true })).not.toBeVisible();
|
||||
|
||||
@@ -511,8 +562,8 @@ async function reloadAndRecoverLocalPlugin(
|
||||
path.join(directory, "index.client.tsx"),
|
||||
pluginSource("Broken surface", "render exploded"),
|
||||
);
|
||||
await openPluginSettings(page);
|
||||
await reloadPlugin(page);
|
||||
await openPluginPageFromSettings(page, "e2e-plugin");
|
||||
await reloadPluginFromPage(page, "e2e-plugin");
|
||||
await openContributionFromSettings(page, "Broken surface", "Plugin failed: render exploded");
|
||||
await openContribution(page, "Healthy surface", "Healthy contribution");
|
||||
await openContribution(page, "Broken surface", "Plugin failed: render exploded");
|
||||
@@ -522,39 +573,39 @@ async function reloadAndRecoverLocalPlugin(
|
||||
await expect(page.getByRole("button", { name: "Broken surface", exact: true })).not.toBeVisible();
|
||||
|
||||
await writeFile(path.join(directory, "index.client.tsx"), "export default broken syntax !!!");
|
||||
await openPluginSettings(page);
|
||||
await selectPluginAction(page, "e2e-plugin", "Reload");
|
||||
await expect(page.getByTestId("plugin-management-feedback")).toContainText("Request failed");
|
||||
await expect(page.getByLabel("e2e-plugin failed")).toBeVisible();
|
||||
await openPluginPageFromSettings(page, "e2e-plugin");
|
||||
await selectPluginPageAction(page, "e2e-plugin", "Reload");
|
||||
await expectToast(page, "Request failed");
|
||||
await backToPlugins(page, "e2e-plugin");
|
||||
await expectPluginFailed(page, "e2e-plugin");
|
||||
await leavePluginSettings(page);
|
||||
await expectContributionRemoved(page, "Recovered surface");
|
||||
|
||||
await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Plugin v3"));
|
||||
await openPluginSettings(page);
|
||||
await selectPluginAction(page, "e2e-plugin", "Reload");
|
||||
await expect(page.getByLabel("e2e-plugin running")).toBeVisible();
|
||||
await openPluginPageFromSettings(page, "e2e-plugin");
|
||||
await reloadPluginFromPage(page, "e2e-plugin");
|
||||
await backToPlugins(page, "e2e-plugin");
|
||||
await expectPluginHealthy(page, "e2e-plugin");
|
||||
await openContributionFromSettings(page, "Plugin v3", "Plugin v3 cleanup 5");
|
||||
}
|
||||
|
||||
async function toggleRemoveAndReinstallLocalPlugin(page: Page, directory: string) {
|
||||
await openPluginSettings(page);
|
||||
await page.getByRole("switch", { name: "e2e-plugin: Disable", exact: true }).click();
|
||||
await expect(page.getByLabel("e2e-plugin disabled")).toBeVisible();
|
||||
await turnPluginOff(page, "e2e-plugin");
|
||||
await leavePluginSettings(page);
|
||||
await expectContributionRemoved(page, "Plugin v3");
|
||||
|
||||
await openPluginSettings(page);
|
||||
await page.getByRole("switch", { name: "e2e-plugin: Enable", exact: true }).click();
|
||||
await expect(page.getByLabel("e2e-plugin running")).toBeVisible();
|
||||
await turnPluginOn(page, "e2e-plugin");
|
||||
await openContributionFromSettings(page, "Plugin v3", "Plugin v3 cleanup 6");
|
||||
|
||||
await openPluginSettings(page);
|
||||
page.once("dialog", (dialog) => dialog.accept());
|
||||
await selectPluginAction(page, "e2e-plugin", "Remove");
|
||||
await expect(page.getByTestId("plugin-row-e2e-plugin")).toHaveCount(0);
|
||||
await openPluginPageFromSettings(page, "e2e-plugin");
|
||||
await removePluginFromPage(page, "e2e-plugin");
|
||||
await expectPluginsRoute(page);
|
||||
await expectPluginRemoved(page, "e2e-plugin");
|
||||
|
||||
await installPlugin(page, directory);
|
||||
await expect(page.getByLabel("e2e-plugin running")).toBeVisible();
|
||||
await installFromSource(page, directory, "e2e-plugin");
|
||||
await expectPluginOn(page, "e2e-plugin");
|
||||
await gotoAppShell(page);
|
||||
await openContribution(page, "Plugin v3", "Plugin v3 cleanup 7");
|
||||
}
|
||||
@@ -583,10 +634,8 @@ async function prepareCompactGitInstall(page: Page, pluginEnvironment: PluginEnv
|
||||
await client.disablePlugin("compact-disabled-plugin");
|
||||
await gotoAppShell(page);
|
||||
await openCompactPluginSettings(page);
|
||||
await expect(page.getByRole("textbox", { name: "Plugin installation ID" })).toHaveCount(0);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: false });
|
||||
await page.getByRole("switch", { name: "Enable plugins" }).click();
|
||||
await expect(page.getByText("Plugins enabled", { exact: true })).toBeVisible();
|
||||
await expectPluginsOff(page);
|
||||
|
||||
return { repository, missingSource };
|
||||
}
|
||||
@@ -598,24 +647,58 @@ async function retryGitInstallAndInspectRows(
|
||||
) {
|
||||
const { repository, missingSource } = source;
|
||||
|
||||
await installPlugin(page, missingSource);
|
||||
await expect(page.getByTestId("plugin-management-feedback")).toContainText(
|
||||
await openSourceInstall(page);
|
||||
// Plugins are off, so the confirmation says installing turns them on.
|
||||
await expectSourceInstallTurnsPluginsOn(page);
|
||||
await submitSourceInstall(page, missingSource);
|
||||
await expectSourceInstallFailed(
|
||||
page,
|
||||
missingSource,
|
||||
`Plugin directory does not exist: ${missingSource}`,
|
||||
);
|
||||
await expect(page.getByLabel("Plugin source")).toHaveValue(missingSource);
|
||||
await capturePluginInstallForm(page, testInfo, "compact-error");
|
||||
|
||||
await installPlugin(page, pathToFileURL(repository).href);
|
||||
await expect(page.getByText("Installed git-e2e-plugin", { exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel("git-e2e-plugin running")).toBeVisible();
|
||||
await submitSourceInstall(page, pathToFileURL(repository).href);
|
||||
await expectSourceInstalled(page, "git-e2e-plugin");
|
||||
await expectPluginsOn(page);
|
||||
await expectPluginOn(page, "git-e2e-plugin");
|
||||
await expect(
|
||||
page.getByText("Shows how a realistically long plugin description wraps on a compact screen"),
|
||||
).toBeVisible();
|
||||
await expect(page.getByLabel("compact-disabled-plugin disabled")).toBeVisible();
|
||||
await expect(page.getByLabel("Plugin source")).toHaveValue("");
|
||||
await expectPluginOff(page, "compact-disabled-plugin");
|
||||
await capturePluginInstallForm(page, testInfo, "compact-success");
|
||||
await openPluginActions(page, "git-e2e-plugin");
|
||||
const removeAction = page.getByRole("menuitem", { name: "Remove", exact: true });
|
||||
}
|
||||
|
||||
async function updateGitPlugin(page: Page, repository: string) {
|
||||
await publishGitPluginChange(repository, "Git plugin v2");
|
||||
// Updates are checked when Plugins opens.
|
||||
await page.reload();
|
||||
await expectUpdateAvailable(page, "git-e2e-plugin");
|
||||
await updatePlugin(page, "git-e2e-plugin");
|
||||
await expectPluginOn(page, "git-e2e-plugin");
|
||||
}
|
||||
|
||||
/** An update that fails on the plugin's page says why there, and offers Retry. */
|
||||
async function failUpdateFromPluginPage(page: Page, repository: string) {
|
||||
await publishGitPluginChange(repository, "Git plugin v3");
|
||||
await page.reload();
|
||||
const update = page.getByTestId("plugin-update").filter({ visible: true });
|
||||
await expect(update).toHaveText("Update");
|
||||
// Rewriting the commit the page checked leaves its update pointing at a commit the remote no
|
||||
// longer serves. The next check offers the rewritten commit.
|
||||
execFileSync("git", ["commit", "--amend", "-m", "Git plugin v3, amended"], {
|
||||
cwd: repository,
|
||||
stdio: "ignore",
|
||||
});
|
||||
await update.click();
|
||||
await expect(update).toHaveText("Retry");
|
||||
await expect(page.getByText(/Git command failed/)).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectCompactPluginMenuFits(page: Page, testInfo: TestInfo) {
|
||||
await openPluginPage(page, "git-e2e-plugin");
|
||||
await openPluginPageActions(page, "git-e2e-plugin");
|
||||
const removeAction = page.getByRole("menuitem", { name: "Uninstall", exact: true });
|
||||
await expect(removeAction).toBeInViewport({ ratio: 1 });
|
||||
await waitForSettledPosition(removeAction);
|
||||
await capturePluginInstallForm(page, testInfo, "compact-menu");
|
||||
@@ -648,12 +731,11 @@ async function prepareLegacyPluginHost(
|
||||
|
||||
async function verifyLegacyPluginManagement(page: Page, directory: string) {
|
||||
await expect(
|
||||
page.getByText("Update this host to install plugins", { exact: true }),
|
||||
pluginRow(page, "legacy-source-plugin").getByText(directory, { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole("textbox", { name: "Plugin source", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByText(directory, { exact: true })).toBeVisible();
|
||||
await selectPluginAction(page, "legacy-source-plugin", "Reload");
|
||||
await expect(page.getByText("Reloaded legacy-source-plugin", { exact: true })).toBeVisible();
|
||||
await expectGalleryMenuWithoutSourceInstall(page);
|
||||
await openPluginPage(page, "legacy-source-plugin");
|
||||
await reloadPluginFromPage(page, "legacy-source-plugin");
|
||||
}
|
||||
|
||||
async function prepareNpmPluginHost(
|
||||
@@ -667,23 +749,22 @@ async function prepareNpmPluginHost(
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await gotoAppShell(page);
|
||||
await openNpmPluginSettings(page, viewport.width);
|
||||
await selectInstalledTab(page);
|
||||
}
|
||||
|
||||
async function retryNpmInstallAndInspectRow(page: Page, width: number, testInfo: TestInfo) {
|
||||
await installPlugin(page, "npm:missing-plugin");
|
||||
await expect(page.getByTestId("plugin-management-feedback")).toContainText("404");
|
||||
await expect(page.getByLabel("Plugin source")).toHaveValue("npm:missing-plugin");
|
||||
await installPlugin(page, "npm:@paseo-fixture/review@^2.0.0");
|
||||
await expect(page.getByText("Installed npm-review", { exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel("npm-review running")).toBeVisible();
|
||||
await openSourceInstall(page);
|
||||
await submitSourceInstall(page, "npm:missing-plugin");
|
||||
await expectSourceInstallFailed(page, "npm:missing-plugin", "404");
|
||||
await submitSourceInstall(page, "npm:@paseo-fixture/review@^2.0.0");
|
||||
await expectSourceInstalled(page, "npm-review");
|
||||
await expectPluginOn(page, "npm-review");
|
||||
await expectSourceHierarchy(
|
||||
page,
|
||||
"npm-review",
|
||||
"Installed from the npm fixture registry",
|
||||
"npm:@paseo-fixture/review · 2.0.0",
|
||||
);
|
||||
await expect(
|
||||
page.getByText("Installed from the npm fixture registry", { exact: true }),
|
||||
).toBeVisible();
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath(`npm-plugin-${width}.png`),
|
||||
animations: "disabled",
|
||||
@@ -691,12 +772,11 @@ async function retryNpmInstallAndInspectRow(page: Page, width: number, testInfo:
|
||||
}
|
||||
|
||||
async function reloadAndRemoveNpmPlugin(page: Page) {
|
||||
await selectPluginAction(page, "npm-review", "Reload");
|
||||
await expect(page.getByText("Reloaded npm-review", { exact: true })).toBeVisible();
|
||||
page.once("dialog", (dialog) => dialog.accept());
|
||||
await selectPluginAction(page, "npm-review", "Remove");
|
||||
await expect(page.getByText("Removed npm-review", { exact: true })).toBeVisible();
|
||||
await expect(page.getByLabel("npm-review running")).toHaveCount(0);
|
||||
await openPluginPage(page, "npm-review");
|
||||
await reloadPluginFromPage(page, "npm-review");
|
||||
await removePluginFromPage(page, "npm-review");
|
||||
await expectPluginsRoute(page);
|
||||
await expectPluginRemoved(page, "npm-review");
|
||||
}
|
||||
|
||||
test("renders installed-plugin descriptions as plain text", async ({ page, pluginEnvironment }) => {
|
||||
@@ -793,19 +873,6 @@ async function holdPluginLifecycleQueue(
|
||||
};
|
||||
}
|
||||
|
||||
function pluginRowActions(page: Page, pluginId: string) {
|
||||
return page.getByRole("button", { name: `Actions for ${pluginId}`, exact: true });
|
||||
}
|
||||
|
||||
async function expectPluginRowPending(page: Page, pluginId: string): Promise<void> {
|
||||
await expect(pluginRowActions(page, pluginId)).toBeDisabled();
|
||||
}
|
||||
|
||||
async function expectPluginRowSettled(page: Page, pluginId: string): Promise<void> {
|
||||
await expect(pluginRowActions(page, pluginId)).toBeEnabled();
|
||||
await expect(page.getByLabel(`${pluginId} running`)).toBeVisible();
|
||||
}
|
||||
|
||||
async function capturePluginSurface(page: Page, testInfo: TestInfo, name: string): Promise<void> {
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath(name),
|
||||
@@ -836,39 +903,36 @@ test("keeps Reload pending past a minute while the plugin queue is busy", async
|
||||
// Observe before the app loads: its daemon socket comes up with the page.
|
||||
const reload = observePluginReload(page);
|
||||
await gotoAppShell(page);
|
||||
await openPluginSettings(page);
|
||||
// Plugins on is a precondition here, not the subject: set it through the daemon instead of the
|
||||
// switch, whose transient "Plugins enabled" confirmation this scenario must not depend on.
|
||||
// Plugins on is a precondition here, not the subject: set it through the daemon.
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installPluginSource({ source: pluginDirectory });
|
||||
await expectPluginRowSettled(page, "e2e-plugin");
|
||||
// Installed before Plugins opens, so it opens on the Installed tab.
|
||||
await openPluginSettings(page);
|
||||
await expectPluginOn(page, "e2e-plugin");
|
||||
await openPluginPage(page, "e2e-plugin");
|
||||
|
||||
const queue = await holdPluginLifecycleQueue(client, directory);
|
||||
try {
|
||||
await selectPluginAction(page, "e2e-plugin", "Reload");
|
||||
await selectPluginPageAction(page, "e2e-plugin", "Reload");
|
||||
await reload.waitForRequest();
|
||||
// Pending: the row's actions stay disabled, so a second reload cannot be submitted.
|
||||
await expectPluginRowPending(page, "e2e-plugin");
|
||||
// Pending: the plugin's controls stay disabled, so a second action cannot be submitted.
|
||||
await expectPluginActionPending(page, "e2e-plugin");
|
||||
await capturePluginSurface(page, testInfo, "plugin-reload-pending.png");
|
||||
|
||||
await waitPastFormerReloadDeadline(page, reload.requestedAt());
|
||||
|
||||
// Past the former deadline the reload is still pending, the row shows its previous state, and
|
||||
// no timeout error reached the surface.
|
||||
await expectPluginRowPending(page, "e2e-plugin");
|
||||
await expect(page.getByLabel("e2e-plugin running")).toBeVisible();
|
||||
await expect(page.getByTestId("plugin-management-feedback")).toHaveCount(0);
|
||||
// Past the former deadline the reload is still pending; a request timeout would have settled
|
||||
// it and released the switch.
|
||||
await expectPluginActionPending(page, "e2e-plugin");
|
||||
await expect(page.getByTestId("app-toast-message")).toHaveCount(0);
|
||||
await capturePluginSurface(page, testInfo, "plugin-reload-past-deadline.png");
|
||||
|
||||
await queue.release();
|
||||
// The daemon's answer only arrives once the plugin really started again; a request timeout
|
||||
// would have shown up as feedback during the wait above.
|
||||
// The daemon's answer only arrives once the plugin really started again.
|
||||
await reload.waitForResponse();
|
||||
expect(reload.requestCount()).toBe(1);
|
||||
await expect(page.getByTestId("plugin-management-feedback")).toContainText(
|
||||
"Reloaded e2e-plugin",
|
||||
);
|
||||
await expectPluginRowSettled(page, "e2e-plugin");
|
||||
await expectToast(page, "Reloaded e2e-plugin");
|
||||
await expectPluginOn(page, "e2e-plugin");
|
||||
await capturePluginSurface(page, testInfo, "plugin-reload-completed.png");
|
||||
} finally {
|
||||
await queue.settle();
|
||||
|
||||
@@ -18,11 +18,12 @@ import {
|
||||
expectSettingsUnavailable,
|
||||
openPluginsPage,
|
||||
expectActionsMenuWithoutSettings,
|
||||
expectNoSettingsCogWithoutScreens,
|
||||
expectSettingsFollowPluginSwitch,
|
||||
expectSettingsHidden,
|
||||
expectSettingsTab,
|
||||
openTabbedSettings,
|
||||
selectSettingsTab,
|
||||
openTabbedSettingsLink,
|
||||
expectSettingsTooltip,
|
||||
expectNamedPluginRow,
|
||||
} from "../support/helpers/plugin-settings";
|
||||
|
||||
@@ -52,35 +53,41 @@ test("another client's save preserves a conflicting draft", async ({ page }) =>
|
||||
await discardTitle(page);
|
||||
});
|
||||
|
||||
test("Back to plugins returns from a plugin settings screen", async ({ page }) => {
|
||||
test("Back to plugins returns from a plugin page", async ({ page }) => {
|
||||
await openDisplaySettings(page);
|
||||
await returnToPluginsPage(page);
|
||||
});
|
||||
|
||||
test("plugin settings open from the cog and show a tab per screen", async ({ page }) => {
|
||||
test("plugin pages open from their row and show a tab per settings screen", async ({ page }) => {
|
||||
await openPluginsPage(page);
|
||||
await test.step("plugin rows show the display name", async () => {
|
||||
await expectNamedPluginRow(page);
|
||||
});
|
||||
await test.step("the cog explains itself", async () => {
|
||||
await expectSettingsTooltip(page);
|
||||
await test.step("the row opens the plugin's page", async () => {
|
||||
await openTabbedSettings(page);
|
||||
});
|
||||
await test.step("the actions menu keeps only plugin actions", async () => {
|
||||
await test.step("the page's menu keeps only plugin actions", async () => {
|
||||
await expectActionsMenuWithoutSettings(page);
|
||||
});
|
||||
await test.step("tabs switch between the plugin's settings screens", async () => {
|
||||
await openTabbedSettings(page);
|
||||
await selectSettingsTab(page, "Advanced");
|
||||
await selectSettingsTab(page, "General");
|
||||
await returnToPluginsPage(page);
|
||||
});
|
||||
await test.step("a plugin without settings screens shows no cog", async () => {
|
||||
await expectNoSettingsCogWithoutScreens(page);
|
||||
await test.step("turning a plugin off removes its settings from its page", async () => {
|
||||
await expectSettingsFollowPluginSwitch(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("a settings screen link opens its tab", async ({ page }) => {
|
||||
test("a settings screen link opens its tab, unavailable while the plugin is off", async ({
|
||||
page,
|
||||
settingsPlugin,
|
||||
}) => {
|
||||
await openTabbedSettingsLink(page, "Advanced");
|
||||
await settingsPlugin.disablePlugin("settings-tabs");
|
||||
await expectSettingsUnavailable(page);
|
||||
await settingsPlugin.enablePlugin("settings-tabs");
|
||||
await expectSettingsTab(page, "Advanced");
|
||||
});
|
||||
|
||||
test.describe("compact plugin settings", () => {
|
||||
@@ -95,7 +102,7 @@ test.describe("compact plugin settings", () => {
|
||||
await hideMetadata(page);
|
||||
await returnAndReopenSettings(page);
|
||||
await settingsPlugin.disablePlugin("settings-example");
|
||||
await expectSettingsUnavailable(page);
|
||||
await expectSettingsHidden(page);
|
||||
await settingsPlugin.enablePlugin("settings-example");
|
||||
await reloadSavedDisplaySettings(page);
|
||||
});
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
import { ACP_PROVIDER_ICON_SVGS } from "../../src/assets/acp-provider-icons";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import type { Locator, TestInfo } from "@playwright/test";
|
||||
import type { TestInfo } from "@playwright/test";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import {
|
||||
findAcpCatalogProvider,
|
||||
openAddProvider,
|
||||
openAddProviderArea,
|
||||
openSettingsHost,
|
||||
openSettingsHostSection,
|
||||
} from "../support/helpers/settings";
|
||||
|
||||
async function openProviderCatalog(page: Page, viewport?: { width: number; height: number }) {
|
||||
async function openProviderCatalog(page: Page) {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, getServerId());
|
||||
await openSettingsHostSection(page, getServerId(), "providers");
|
||||
if (viewport) await page.setViewportSize(viewport);
|
||||
await openAddProvider(page);
|
||||
await openAddProviderArea(page);
|
||||
}
|
||||
|
||||
async function expectProviderArtwork(
|
||||
@@ -26,11 +25,11 @@ async function expectProviderArtwork(
|
||||
name: string,
|
||||
) {
|
||||
await findAcpCatalogProvider(page, name);
|
||||
// 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();
|
||||
// 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();
|
||||
await expect(icon).toBeVisible();
|
||||
// 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");
|
||||
// Provider artwork is 24px; the generic PackagePlus fallback is 20px.
|
||||
await expect.soft(icon).toHaveAttribute("width", "24");
|
||||
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")!);
|
||||
@@ -50,20 +49,3 @@ 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);
|
||||
});
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
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,15 +2,11 @@ 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,
|
||||
leaveProviderDetail,
|
||||
openAddProvider,
|
||||
openProviderDetail,
|
||||
openAddProviderArea,
|
||||
openSettingsHost,
|
||||
openSettingsHostSection,
|
||||
} from "../support/helpers/settings";
|
||||
@@ -66,39 +62,13 @@ 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").click();
|
||||
await page.getByTestId(`provider-remove-${CUSTOM_PROVIDER.id}`).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);
|
||||
@@ -109,39 +79,20 @@ 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");
|
||||
|
||||
// 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 expect(page.getByTestId("provider-actions-claude")).toHaveCount(0);
|
||||
await openAddProviderArea(page);
|
||||
await installAcpCatalogProvider(page, CUSTOM_PROVIDER.name);
|
||||
await expectProviderInstalledInSettings(page, CUSTOM_PROVIDER.name);
|
||||
await expectProviderSource(client, "custom");
|
||||
|
||||
await openProviderDetail(page, CUSTOM_PROVIDER.name);
|
||||
await expect(page.getByTestId("provider-remove")).toBeVisible();
|
||||
await watchForMissingNotice(page);
|
||||
gate.holdNextServerMessage(CONFIG_RESPONSE);
|
||||
await page.getByTestId(`provider-actions-${CUSTOM_PROVIDER.id}`).click();
|
||||
await expect(page.getByTestId(`provider-remove-${CUSTOM_PROVIDER.id}`)).toBeVisible();
|
||||
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", {
|
||||
@@ -149,33 +100,7 @@ test.describe("provider removal", () => {
|
||||
exact: true,
|
||||
}),
|
||||
).toHaveCount(0);
|
||||
} 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);
|
||||
await expectProviderSource(client, undefined);
|
||||
} finally {
|
||||
await removeCustomProvider(client).catch(() => undefined);
|
||||
await client.close().catch(() => undefined);
|
||||
@@ -205,9 +130,7 @@ test.describe("provider removal", () => {
|
||||
exact: true,
|
||||
});
|
||||
await expect(pluginProviderRow).toBeVisible();
|
||||
await openProviderDetail(page, PLUGIN_PROVIDER.name);
|
||||
await expect(page.getByTestId("provider-remove")).toHaveCount(0);
|
||||
await leaveProviderDetail(page);
|
||||
await expect(page.getByTestId(`provider-actions-${PLUGIN_PROVIDER.id}`)).toHaveCount(0);
|
||||
|
||||
// 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 report" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Diagnostic", exact: true })).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 report" }).click();
|
||||
await page.getByRole("button", { name: "Diagnostic", exact: true }).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("Checked just now", { exact: true })).toBeVisible({
|
||||
await expect(page.getByText("Updated just now", { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -15,9 +15,6 @@ import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import {
|
||||
expectSettingsHeader,
|
||||
expectProviderNotOnHost,
|
||||
expectProviderPageLoaded,
|
||||
gotoProviderPage,
|
||||
openSettingsHost,
|
||||
openHostSection,
|
||||
expectHostLabelDisplayed,
|
||||
@@ -265,20 +262,6 @@ 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);
|
||||
|
||||
@@ -153,21 +153,29 @@ async function holdStreamAfterFirstCompletedToolCall(page: Page, agentId: string
|
||||
type OverviewChatDisplay = "collapseToolCalls" | "collapseTurns";
|
||||
|
||||
// Expand thinking keeps reasoning out of tool call runs, so the first tool call starts alone.
|
||||
async function configureOverviewToolCalls(page: Page, chatDisplay: OverviewChatDisplay) {
|
||||
await page.addInitScript((display) => {
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
JSON.stringify({ chatDisplay: display, autoExpandReasoning: true }),
|
||||
);
|
||||
}, chatDisplay);
|
||||
async function configureOverviewToolCalls(
|
||||
page: Page,
|
||||
chatDisplay: OverviewChatDisplay,
|
||||
autoExpandReasoning: boolean,
|
||||
) {
|
||||
await page.addInitScript(
|
||||
({ display, expandReasoning }) => {
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
JSON.stringify({ chatDisplay: display, autoExpandReasoning: expandReasoning }),
|
||||
);
|
||||
},
|
||||
{ display: chatDisplay, expandReasoning: autoExpandReasoning },
|
||||
);
|
||||
}
|
||||
|
||||
async function createOverviewAgent(
|
||||
page: Page,
|
||||
title: string,
|
||||
chatDisplay: OverviewChatDisplay = "collapseToolCalls",
|
||||
autoExpandReasoning = true,
|
||||
) {
|
||||
await configureOverviewToolCalls(page, chatDisplay);
|
||||
await configureOverviewToolCalls(page, chatDisplay, autoExpandReasoning);
|
||||
return seedMockAgentWorkspace({
|
||||
repoPrefix: "tool-call-overview-sheet-",
|
||||
title,
|
||||
@@ -401,3 +409,211 @@ test("forms a closed group when the lone tool call was left closed", async ({ pa
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
const longGroupedDetail = {
|
||||
type: "unknown",
|
||||
input: Array.from({ length: 80 }, (_, i) => `Long input ${i}`),
|
||||
output: Array.from({ length: 80 }, (_, i) => `Long output ${i}`),
|
||||
};
|
||||
|
||||
function provideLongReadDetail(item: Record<string, unknown> | undefined) {
|
||||
if (item?.type === "tool_call" && item.name === "read") item.detail = longGroupedDetail;
|
||||
}
|
||||
|
||||
function provideLongReasoningDetail(item: Record<string, unknown> | undefined) {
|
||||
if (item?.type === "reasoning") {
|
||||
item.text = Array.from({ length: 80 }, (_, i) => `Long reasoning ${i}`).join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
async function provideLongToolDetails(page: Page, transformItem = provideLongReadDetail) {
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
ws.onMessage((message) => server.send(message));
|
||||
server.onMessage((message) => {
|
||||
const raw = typeof message === "string" ? message : message.toString("utf8");
|
||||
const envelope = JSON.parse(raw);
|
||||
const item = envelope.message?.payload?.event?.item;
|
||||
transformItem(item);
|
||||
if (envelope.message?.type === "fetch_agent_timeline_response") {
|
||||
for (const entry of envelope.message.payload.entries) transformItem(entry.item);
|
||||
}
|
||||
ws.send(JSON.stringify(envelope));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function toggleAndMeasureTool(badge: Locator) {
|
||||
await badge.scrollIntoViewIfNeeded();
|
||||
await badge.evaluate((node) => {
|
||||
// Inline groups own a bounded viewport; opened turns use the chat viewport.
|
||||
const container =
|
||||
node.closest('[data-testid="tool-call-group"]') ??
|
||||
node.closest('[data-testid="agent-chat-scroll"]');
|
||||
if (!container) throw new Error("Expected a tool inside a group or chat viewport");
|
||||
const frames: { top: number; height: number; containerHeight: number }[] = [];
|
||||
(node as HTMLElement & { disclosureFrames: typeof frames }).disclosureFrames = frames;
|
||||
node.querySelector("button")!.addEventListener(
|
||||
"click",
|
||||
() => {
|
||||
const measure = () => {
|
||||
const bounds = node.getBoundingClientRect();
|
||||
frames.push({
|
||||
top: bounds.top,
|
||||
height: bounds.height,
|
||||
containerHeight: container.getBoundingClientRect().height,
|
||||
});
|
||||
if (frames.length < 20) requestAnimationFrame(measure);
|
||||
};
|
||||
requestAnimationFrame(measure);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
await openToolDetails(badge);
|
||||
await expect
|
||||
.poll(() =>
|
||||
badge.evaluate(
|
||||
(node) => (node as HTMLElement & { disclosureFrames: unknown[] }).disclosureFrames.length,
|
||||
),
|
||||
)
|
||||
.toBe(20);
|
||||
return badge.evaluate(
|
||||
(node) =>
|
||||
(
|
||||
node as HTMLElement & {
|
||||
disclosureFrames: { top: number; height: number; containerHeight: number }[];
|
||||
}
|
||||
).disclosureFrames,
|
||||
);
|
||||
}
|
||||
|
||||
for (const display of ["collapseToolCalls", "collapseTurns"] as const) {
|
||||
test(`keeps multi-section tool details within the group (${display})`, async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const agent = await createOverviewAgent(page, "Bounded grouped tool details", display);
|
||||
try {
|
||||
await provideLongToolDetails(page);
|
||||
await openOverviewAgent(page, agent);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Exercise bounded grouped details.");
|
||||
await agent.client.waitForAgentUpsert(
|
||||
agent.agentId,
|
||||
(snapshot) => snapshot.status === "idle",
|
||||
30_000,
|
||||
);
|
||||
// A fresh mount of a finished conversation starts with its disclosures closed.
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
if (display === "collapseToolCalls") {
|
||||
await scrollChatAwayFromBottom(page, { deltaY: -10_000, minDistanceFromBottom: 1 });
|
||||
}
|
||||
const group = page.getByTestId("tool-call-group").first();
|
||||
if (display === "collapseTurns") {
|
||||
await expect(page.getByTestId("tool-call-badge")).toHaveCount(0);
|
||||
await openToolDetails(page.getByTestId("turn-summary").first());
|
||||
} else {
|
||||
await expect(group).toBeVisible();
|
||||
await expect(group.getByTestId("tool-call-badge")).toHaveCount(0);
|
||||
await openToolDetails(group);
|
||||
}
|
||||
const scope = display === "collapseTurns" ? page : group;
|
||||
const badge = scope.getByTestId("tool-call-badge").filter({ hasText: "Read" }).first();
|
||||
await expect(badge).toBeVisible();
|
||||
const expandedFrames = await toggleAndMeasureTool(badge);
|
||||
for (const frame of expandedFrames)
|
||||
expect(frame.height).toBeLessThanOrEqual(frame.containerHeight);
|
||||
expect(
|
||||
Math.max(...expandedFrames.map((frame) => frame.top)) -
|
||||
Math.min(...expandedFrames.map((frame) => frame.top)),
|
||||
).toBeLessThanOrEqual(1);
|
||||
await expect(badge).toContainText("Long output");
|
||||
const collapsedFrames = await toggleAndMeasureTool(badge);
|
||||
expect(
|
||||
Math.max(...collapsedFrames.map((frame) => frame.top)) -
|
||||
Math.min(...collapsedFrames.map((frame) => frame.top)),
|
||||
).toBeLessThanOrEqual(1);
|
||||
await expect(badge).not.toContainText("Long output");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("keeps tool headers reachable in an overflowing group", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const agent = await createOverviewAgent(page, "Overflowing overview tool group");
|
||||
try {
|
||||
const gate = await holdStreamAfterFirstCompletedToolCall(page, agent.agentId);
|
||||
await openOverviewAgent(page, agent);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Inspect a large tool group.");
|
||||
await gate.waitForFirstCompleted();
|
||||
gate.appendCompletedCalls(15);
|
||||
const group = page.getByTestId("tool-call-group").first();
|
||||
await openToolDetails(group);
|
||||
const badges = group.getByTestId("tool-call-badge");
|
||||
await expect(badges).toHaveCount(16);
|
||||
await expect.poll(() => group.evaluate(hasScrolledToLatest)).toBe(true);
|
||||
const first = badges.first();
|
||||
for (const action of ["expand", "collapse"]) {
|
||||
await test.step(`${action} the first tool without moving its header`, async () => {
|
||||
await first.scrollIntoViewIfNeeded();
|
||||
const headerTop = await topOf(first);
|
||||
const frames = await toggleAndMeasureTool(first);
|
||||
for (const frame of frames) expect(Math.abs(frame.top - headerTop)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
}
|
||||
await test.step("follow the next appended tool", async () => {
|
||||
gate.appendCompletedCalls(1);
|
||||
await expect(badges).toHaveCount(17);
|
||||
await expect.poll(() => group.evaluate(hasScrolledToLatest)).toBe(true);
|
||||
});
|
||||
await test.step("reopen the group at its latest tool", async () => {
|
||||
await openToolDetails(group);
|
||||
await expect(badges).toHaveCount(0);
|
||||
await openToolDetails(group);
|
||||
await expect(badges).toHaveCount(17);
|
||||
await expect.poll(() => group.evaluate(hasScrolledToLatest)).toBe(true);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps expanded reasoning within the group viewport", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const agent = await createOverviewAgent(
|
||||
page,
|
||||
"Bounded grouped reasoning",
|
||||
"collapseToolCalls",
|
||||
false,
|
||||
);
|
||||
try {
|
||||
// Seed before opening so the fixture transforms complete snapshots, not token deltas.
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Inspect grouped reasoning.");
|
||||
await agent.client.waitForAgentUpsert(
|
||||
agent.agentId,
|
||||
(snapshot) => snapshot.status === "idle",
|
||||
30_000,
|
||||
);
|
||||
await provideLongToolDetails(page, provideLongReasoningDetail);
|
||||
await openOverviewAgent(page, agent);
|
||||
await scrollChatAwayFromBottom(page, { deltaY: -10_000, minDistanceFromBottom: 1 });
|
||||
const group = page.getByTestId("tool-call-group").first();
|
||||
await openToolDetails(group);
|
||||
const thought = group.getByTestId("tool-call-badge").filter({ hasText: "Thinking" }).first();
|
||||
const frames = await toggleAndMeasureTool(thought);
|
||||
const viewportHeight = await group.evaluate((node) => {
|
||||
const scroll = Array.from(node.querySelectorAll<HTMLElement>("*")).find((child) =>
|
||||
["auto", "scroll"].includes(getComputedStyle(child).overflowY),
|
||||
);
|
||||
if (!scroll) throw new Error("Expected the group's scroll viewport");
|
||||
return scroll.getBoundingClientRect().height;
|
||||
});
|
||||
for (const frame of frames) expect(frame.height).toBeLessThanOrEqual(viewportHeight);
|
||||
await expect(thought).toContainText("Long reasoning 79");
|
||||
await openToolDetails(thought);
|
||||
await expect(thought).not.toContainText("Long reasoning 79");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ 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 {
|
||||
@@ -33,7 +34,13 @@ import {
|
||||
pinRow,
|
||||
openUsageOptions,
|
||||
closeUsageOptions,
|
||||
pickUsageHost,
|
||||
usageModalHost,
|
||||
dragUsageCardAbove,
|
||||
recordUsageCardPositionsAfterRelease,
|
||||
expectUsageCardOrder,
|
||||
expectUsageOptionsFitContent,
|
||||
setUsageCardOn,
|
||||
showUsageAs,
|
||||
refreshAllUsage,
|
||||
togglePin,
|
||||
@@ -93,10 +100,6 @@ 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`,
|
||||
@@ -108,6 +111,14 @@ 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)];
|
||||
@@ -120,15 +131,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, ["31% Weekly", "12% Weekly"]);
|
||||
await expectPinnedUsage(page, ["12% Weekly", "31% Weekly"]);
|
||||
await openUsageFromItem(page);
|
||||
}
|
||||
|
||||
async function expectUsageProviderOrder(page: Page, summary: string[]) {
|
||||
const group = page.getByTestId(`usage-host-${getServerId()}`);
|
||||
await expect(group.getByText(/^(opencode|openai) plan$/)).toHaveText([
|
||||
"opencode plan",
|
||||
"openai plan",
|
||||
"opencode plan",
|
||||
]);
|
||||
await expectPinnedUsage(page, summary);
|
||||
}
|
||||
@@ -143,7 +154,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 filter for one host", async ({
|
||||
test("opens from the sidebar on the host's reports, with no host named for one host", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
@@ -183,7 +194,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(hostFilter(page)).toHaveCount(0);
|
||||
await expect(page.getByTestId("usage-modal-host")).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();
|
||||
@@ -200,15 +211,67 @@ test.describe("usage modal", () => {
|
||||
}) => {
|
||||
const usage = await installReversedUsageRefresh(page);
|
||||
await openUsageSummaryAtWidth(page, width);
|
||||
await expectUsageProviderOrder(page, ["31% Weekly", "12% Weekly"]);
|
||||
// Reports arrive opencode first; cards and the summary stay alphabetical.
|
||||
await expectUsageProviderOrder(page, ["12% Weekly", "31% Weekly"]);
|
||||
await qaScreenshot(page, `usage-order-${width}-before-refresh`);
|
||||
|
||||
await refreshUsageAndWaitForReports(page, usage);
|
||||
await expectUsageProviderOrder(page, ["41% Weekly", "22% Weekly"]);
|
||||
await expectUsageProviderOrder(page, ["22% Weekly", "41% 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"]);
|
||||
|
||||
const stopRecording = await recordUsageCardPositionsAfterRelease(page);
|
||||
await dragUsageCardAbove(page, "beta:home", "alpha:a");
|
||||
await expectUsageCardOrder(page, ["beta:home", "alpha:a", "beta:work"]);
|
||||
await expectPinnedUsage(page, ["20% Weekly", "31% Weekly"]);
|
||||
// The cards are in their new slots from the first frame after the drop.
|
||||
const framesAfterDrop = await stopRecording();
|
||||
const settled = framesAfterDrop.at(-1);
|
||||
expect(settled).toBeDefined();
|
||||
expect(framesAfterDrop.filter((frame) => frame !== settled)).toEqual([]);
|
||||
|
||||
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();
|
||||
@@ -320,9 +383,11 @@ 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: [[weeklyReport("beta", 12)]],
|
||||
lists: [{ stream: [secondaryReports.promise, weeklyReport("beta", 12)] }],
|
||||
});
|
||||
await gotoAppShell(page);
|
||||
await addConnectedHostAndReload(page, {
|
||||
@@ -336,12 +401,15 @@ test.describe("usage modal", () => {
|
||||
await openUsageFromItem(page);
|
||||
await expect(page.getByTestId(`usage-host-${primaryServerId}`)).toBeVisible();
|
||||
|
||||
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 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 qaScreenshot(page, "usage-modal-picked-host");
|
||||
await expectPinnedUsage(page, ["12% Weekly"]);
|
||||
|
||||
@@ -360,6 +428,51 @@ 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,10 +318,11 @@ 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: no host filter, as on History.
|
||||
await expect(page.locator('[data-testid="usage-host-filter-trigger"]:visible')).toHaveCount(
|
||||
0,
|
||||
);
|
||||
// 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);
|
||||
await togglePin(screen, "Claude", "Weekly");
|
||||
await expectPinnedUsage(page, ["31% 5h", "7% 5h", "12% wk"]);
|
||||
await expect(pinRow(screen, "Claude", "Session")).toBeChecked();
|
||||
|
||||
@@ -14,6 +14,7 @@ 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,
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
resizeSidebarToMinimum,
|
||||
rowArchiveButton,
|
||||
rowKebab,
|
||||
scrollSidebarListToEnd,
|
||||
undoButton,
|
||||
workspaceRow,
|
||||
workspaceTitleWidth,
|
||||
@@ -119,6 +121,41 @@ 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,27 +5,34 @@ 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";
|
||||
|
||||
async function seedRiskyWorktree(
|
||||
client: Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>,
|
||||
worktreeDirectory: string,
|
||||
): Promise<void> {
|
||||
type DaemonClient = Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
|
||||
|
||||
async function seedRiskyWorktree(client: DaemonClient, 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,
|
||||
@@ -55,35 +62,189 @@ async function seedRiskyWorktree(
|
||||
const dirtyFile = path.join(worktreeDirectory, "DIRTY.md");
|
||||
await writeFile(dirtyFile, "# dirty\n");
|
||||
|
||||
const refreshed = await client.checkoutRefresh(worktreeDirectory);
|
||||
await refreshCheckout(client, worktreeDirectory);
|
||||
}
|
||||
|
||||
async function refreshCheckout(client: DaemonClient, directory: string): Promise<void> {
|
||||
const refreshed = await client.checkoutRefresh(directory);
|
||||
if (!refreshed.success) {
|
||||
throw new Error(`Failed to refresh checkout for ${worktreeDirectory}`);
|
||||
throw new Error(`Failed to refresh checkout for ${directory}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 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(
|
||||
// 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(
|
||||
page: Page,
|
||||
workspaceId: string,
|
||||
answer: "accept" | "dismiss",
|
||||
openArchive: () => Promise<void>,
|
||||
): Promise<Dialog> {
|
||||
let warning: Dialog | undefined;
|
||||
page.once("dialog", (dialog) => {
|
||||
warning = dialog;
|
||||
void (answer === "accept" ? dialog.accept() : dialog.dismiss());
|
||||
const warning = page.waitForEvent("dialog", { timeout: 10_000 }).then(async (dialog) => {
|
||||
await (answer === "accept" ? dialog.accept() : dialog.dismiss());
|
||||
return dialog;
|
||||
});
|
||||
await clickArchiveWorkspaceMenuItem(page, workspaceId);
|
||||
if (!warning) {
|
||||
throw new Error("Expected an archive confirmation dialog, but none was shown.");
|
||||
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;
|
||||
}
|
||||
return warning;
|
||||
}
|
||||
|
||||
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();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
let client: Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
|
||||
let client: DaemonClient;
|
||||
let tempRepo: { path: string; cleanup: () => Promise<void> };
|
||||
const createdWorktreeDirectories = new Set<string>();
|
||||
|
||||
@@ -103,36 +264,53 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
await tempRepo?.cleanup().catch(() => undefined);
|
||||
});
|
||||
|
||||
test("a risky workspace archive is gated by confirmation and removes its worktree after acceptance", async ({
|
||||
page,
|
||||
}) => {
|
||||
const serverId = getServerId();
|
||||
await openProjectViaDaemon(client, tempRepo.path);
|
||||
async function createWorktree(slug: string) {
|
||||
const project = await openProjectViaDaemon(client, tempRepo.path);
|
||||
const worktree = await createWorktreeViaDaemon(client, {
|
||||
cwd: tempRepo.path,
|
||||
slug: `archive-risk-${Date.now()}`,
|
||||
slug: `${slug}-${Date.now()}`,
|
||||
});
|
||||
createdWorktreeDirectories.add(worktree.workspaceDirectory);
|
||||
expect(existsSync(worktree.workspaceDirectory)).toBe(true);
|
||||
return { ...worktree, project };
|
||||
}
|
||||
|
||||
await seedRiskyWorktree(client, worktree.workspaceDirectory);
|
||||
|
||||
async function openSidebarRow(page: Page, workspaceId: string): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await waitForWorkspaceInSidebar(page, { serverId, workspaceId: worktree.workspaceId });
|
||||
await waitForWorkspaceInSidebar(page, { serverId: getServerId(), workspaceId });
|
||||
}
|
||||
|
||||
const firstWarning = await clickArchiveAndAnswerWarning(page, worktree.workspaceId, "dismiss");
|
||||
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 firstWarning = await answerArchiveWarning(page, "dismiss", () =>
|
||||
clickArchiveWorkspaceMenuItem(page, worktree.workspaceId),
|
||||
);
|
||||
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 expect(
|
||||
page.getByTestId(`sidebar-workspace-row-${serverId}:${worktree.workspaceId}`),
|
||||
).toBeVisible({ timeout: 10_000 });
|
||||
await expectWorktreeKept(page, worktree);
|
||||
expect(existsSync(worktree.workspaceDirectory)).toBe(true);
|
||||
|
||||
const secondWarning = await clickArchiveAndAnswerWarning(page, worktree.workspaceId, "accept");
|
||||
const secondWarning = await answerArchiveWarning(page, "accept", () =>
|
||||
clickArchiveWorkspaceMenuItem(page, worktree.workspaceId),
|
||||
);
|
||||
expect(secondWarning.message()).toContain("Uncommitted changes");
|
||||
expect(secondWarning.message()).toContain("1 unpushed commit");
|
||||
|
||||
@@ -143,4 +321,128 @@ 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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
context platform=ios timeout=60000 retries=0
|
||||
# Start in an empty, connected composer with the Claude provider selected.
|
||||
# COMMAND_ROW must name an inserting command, not an immediate client action.
|
||||
env COMMAND_ROW="/advisor, Let Claude consult a stronger model at key moments"
|
||||
env COMMAND_TEXT="/advisor "
|
||||
open sh.paseo.debug
|
||||
wait "editable=true" 60000
|
||||
fill "editable=true" "/"
|
||||
wait "label=\"${COMMAND_ROW}\"" 15000
|
||||
press "label=\"${COMMAND_ROW}\""
|
||||
# Do not type or move the caret: replacement itself must close autocomplete.
|
||||
wait absent "label=\"${COMMAND_ROW}\"" 3000
|
||||
wait "editable=true value=\"${COMMAND_TEXT}\"" 3000
|
||||
@@ -0,0 +1,28 @@
|
||||
# Inline tool detail scrolling on iPad
|
||||
|
||||
Use a task-owned iPad Pro 11-inch (M5) simulator in portrait (834×1210 points),
|
||||
with the development bundle already loaded and a connected isolated mock host.
|
||||
Set Chat display to Collapse turns. Prepare a finished turn containing a tool
|
||||
named `scroll_probe`, with unknown detail: `input` is 80 newline-separated
|
||||
`input-line-N` lines (N=0…79), and `output` is `SCROLL_REACHED_OUTPUT`.
|
||||
|
||||
Expand the turn, scroll chat to its start, and expand Scroll probe. The tool's
|
||||
header must be at y=613…644 and its 400-point body below it. The fixed pan path
|
||||
starts inside that body and stays inside it. Output starts below the cap.
|
||||
These are replay preconditions, not asserted pixel sizes. Close other expanded
|
||||
tools so the Scroll probe selector identifies this disclosure.
|
||||
|
||||
Replay `native-inline-tool-scroll.ios.yaml --maestro` on that explicit simulator
|
||||
through the existing mobile runner or agent-device. In Expo's development menu,
|
||||
turn off Tools button, then dismiss the known notification entitlement toast
|
||||
with its bottom-right close button. Their transparent accessibility windows
|
||||
otherwise mark app text covered. Another overlay must fail the visibility
|
||||
assertions. Pass `--platform ios` and the prepared session's `--state-dir` when
|
||||
replaying in that session.
|
||||
|
||||
The flow first asserts Input is visible and the output marker is not. After
|
||||
panning it requires Output and its marker to be visible, then requires closing
|
||||
the tool to hide its contents and reopening it to show Input again. Presence in
|
||||
the accessibility tree is insufficient. A negative control with the passive
|
||||
wrapper retained and only the detail's scrolling disabled must fail at Output
|
||||
visibility. The browser disclosure suite checks tab navigation.
|
||||
@@ -0,0 +1,28 @@
|
||||
appId: sh.paseo.debug
|
||||
---
|
||||
- assertVisible:
|
||||
id: workspace-tabs-scroll
|
||||
- assertVisible: Scroll probe
|
||||
- assertVisible: Input
|
||||
- assertNotVisible: SCROLL_REACHED_OUTPUT
|
||||
- repeat:
|
||||
times: 7
|
||||
commands:
|
||||
- swipe:
|
||||
start: "600,850"
|
||||
end: "600,670"
|
||||
duration: 600
|
||||
- swipe:
|
||||
start: "600,850"
|
||||
end: "600,700"
|
||||
duration: 600
|
||||
- assertVisible: Output
|
||||
- assertVisible: SCROLL_REACHED_OUTPUT
|
||||
- tapOn:
|
||||
point: "600,628"
|
||||
- assertNotVisible: Output
|
||||
- assertNotVisible: Input
|
||||
- tapOn:
|
||||
point: "600,628"
|
||||
- assertVisible: Input
|
||||
- stopApp
|
||||
@@ -111,11 +111,13 @@ try {
|
||||
"android",
|
||||
"--no-test-ime",
|
||||
);
|
||||
ad("wait", "text", "Plugin source", "5000");
|
||||
const plugins = JSON.parse(ad("snapshot", "-i", "--json"));
|
||||
const source = plugins.data.nodes.find((node) => node.type === "android.widget.EditText");
|
||||
assert(source, "The connected host must support installing plugins from source");
|
||||
ad("press", `@${source.ref}`);
|
||||
// The source field lives in the Install from source sheet, behind the page's menu.
|
||||
ad("wait", 'label="More plugin actions"', "5000");
|
||||
ad("press", 'label="More plugin actions"');
|
||||
ad("wait", 'text="Install from source"', "5000");
|
||||
ad("press", 'text="Install from source"');
|
||||
ad("wait", 'id="plugin-source-input"', "5000");
|
||||
ad("press", 'id="plugin-source-input"');
|
||||
ad("type", "qa-source");
|
||||
const pluginMeasurement = await waitForFocusedInput();
|
||||
// A FormTextInput draws its border and padding on the native input's parent.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,71 @@
|
||||
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");
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
"""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)
|
||||
@@ -1,6 +1,8 @@
|
||||
import { writeFile, rm, rename } from "node:fs/promises";
|
||||
import { mkdtemp, writeFile, rm, rename } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { copyPluginExample } from "./helpers/plugin-fixture";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { copyPluginExample, pluginRequirements } from "./helpers/plugin-fixture";
|
||||
import { connectNewWorkspaceDaemonClient } from "./helpers/new-workspace";
|
||||
import { test as base } from "./fixtures";
|
||||
import {
|
||||
@@ -14,6 +16,7 @@ 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>>;
|
||||
@@ -98,6 +101,39 @@ 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 {
|
||||
@@ -126,3 +162,15 @@ export default function contribute(server) {
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
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,7 +21,6 @@ export interface OlderTimelinePagesGate {
|
||||
getRepeatedEntryCount(): number;
|
||||
getOwnedEntryCountContaining(text: string): number;
|
||||
releasePage(pageNumber: number): void;
|
||||
waitForRequestCount(count: number): Promise<void>;
|
||||
}
|
||||
|
||||
export interface DaemonHydrationGate {
|
||||
@@ -371,15 +370,6 @@ 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));
|
||||
@@ -393,7 +383,6 @@ export async function holdAgentOlderTimelinePages(
|
||||
sessionMessage.direction === "before"
|
||||
) {
|
||||
requestCount += 1;
|
||||
resolveRequestWaiters();
|
||||
}
|
||||
server.send(message);
|
||||
});
|
||||
@@ -439,14 +428,6 @@ 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"]',
|
||||
scope: '[data-testid="command-center-files-scope"]',
|
||||
tabs: '[data-testid="command-center-tabs"]',
|
||||
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 < 60; index += 1) {
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
agents.push(
|
||||
await createMockIdleAgent(seed.client, {
|
||||
cwd: seed.repoPath,
|
||||
@@ -49,11 +49,27 @@ 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.
|
||||
await page.waitForTimeout(600);
|
||||
await page.evaluate(() => {
|
||||
globalThis.__PASEO_RENDER_PROFILE_REASONS__ = {};
|
||||
});
|
||||
// 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;
|
||||
}
|
||||
|
||||
export async function expectOnlyCommandCenterRowRendered(page: Page, resultId: string) {
|
||||
@@ -73,16 +89,17 @@ export async function expectOnlyCommandCenterRowRendered(page: Page, resultId: s
|
||||
expect(renders).toEqual({ [`CommandCenterResultRow:${resultId}`]: { render: 1 } });
|
||||
}
|
||||
|
||||
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();
|
||||
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();
|
||||
expect(count).toBeGreaterThan(0);
|
||||
expect(count).toBeLessThan(total);
|
||||
}
|
||||
|
||||
export async function scrollToOldestCommandCenterAgent(panel: Locator) {
|
||||
export async function scrollToOldestCommandCenterWorkspace(panel: Locator) {
|
||||
await panel.getByTestId("command-center-results").evaluate((element) => {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
element.dispatchEvent(new Event("scroll"));
|
||||
|
||||
@@ -22,14 +22,9 @@ export async function observeCommandCenterScroll(page: Page): Promise<void> {
|
||||
|
||||
const discoverPanel = new MutationObserver(() => {
|
||||
const panel = document.querySelector<HTMLElement>('[data-testid="command-center-panel"]');
|
||||
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;
|
||||
const viewport = panel?.querySelector<HTMLElement>('[data-testid="command-center-results"]');
|
||||
const firstResult = viewport?.querySelector<HTMLElement>('[role="button"]');
|
||||
if (!viewport || !firstResult) return;
|
||||
|
||||
discoverPanel.disconnect();
|
||||
let frame = 0;
|
||||
@@ -119,15 +114,8 @@ export async function expectVisibleKeyboardNavigationNotToScroll(
|
||||
for (let index = 0; index < 4; index += 1) await page.keyboard.press("ArrowDown");
|
||||
|
||||
const scrollSamples = await panel
|
||||
.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");
|
||||
|
||||
.getByTestId("command-center-results")
|
||||
.evaluate(async (viewport) => {
|
||||
const samples: number[] = [];
|
||||
for (let frame = 0; frame < 20; frame += 1) {
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
||||
@@ -139,7 +127,8 @@ export async function expectVisibleKeyboardNavigationNotToScroll(
|
||||
expect(Math.max(...scrollSamples)).toBe(0);
|
||||
}
|
||||
|
||||
export async function expectWorkspaceResultsToBeLimitedUntilSearch(panel: Locator): Promise<void> {
|
||||
/** All leads with three recent workspaces; a query searches every workspace. */
|
||||
export async function expectRecentWorkspacesUntilSearch(panel: Locator): Promise<void> {
|
||||
const workspaces = panel.locator(
|
||||
'[data-testid^="command-center-workspace-"]:not([data-testid="command-center-workspace-subtitle"])',
|
||||
);
|
||||
@@ -150,9 +139,11 @@ export async function expectWorkspaceResultsToBeLimitedUntilSearch(panel: Locato
|
||||
),
|
||||
).size;
|
||||
|
||||
await expect.poll(distinctWorkspaceCount).toBe(5);
|
||||
await expect(panel.getByText("Recent workspaces", { exact: true })).toBeVisible();
|
||||
await expect.poll(distinctWorkspaceCount).toBe(3);
|
||||
|
||||
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,5 +1,20 @@
|
||||
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();
|
||||
@@ -12,3 +27,46 @@ 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,6 +258,16 @@ 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 searchModels(page, id);
|
||||
await page.getByRole("textbox", { name: "Search models" }).fill(id);
|
||||
const remove = page.getByRole("button", { name: `Remove ${id}`, exact: true });
|
||||
await expect(remove).toBeInViewport({ ratio: 1 });
|
||||
await remove.click();
|
||||
@@ -33,20 +33,8 @@ export async function removeCustomModel(page: Page, id: string): Promise<void> {
|
||||
}
|
||||
|
||||
export async function expectCustomModelRetained(page: Page, id: string): Promise<void> {
|
||||
await searchModels(page, id);
|
||||
await page.getByRole("textbox", { name: "Search models" }).fill(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" }));
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ export async function listTerminalIds(daemon: IsolatedHostDaemon): Promise<strin
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
async function psField(pid: number, field: "stat" | "lstart"): Promise<string> {
|
||||
async function psField(pid: number, field: "stat" | "lstart" | "comm"): Promise<string> {
|
||||
const { stdout } = await execFileAsync("ps", ["-o", `${field}=`, "-p", String(pid)], {
|
||||
env: { ...process.env, LC_ALL: "C" },
|
||||
});
|
||||
@@ -117,17 +117,22 @@ export interface UnclosableTerminalProgram {
|
||||
export async function plantUnclosableTerminalProgram(
|
||||
daemon: IsolatedHostDaemon,
|
||||
): Promise<UnclosableTerminalProgram> {
|
||||
const parent = spawn("/bin/sh", ["-c", "sleep 0 & echo $!; exec sleep 600"], {
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
// The shell reaps any child that has exited whenever it finishes a builtin, so the program
|
||||
// reads fd 3 until we close it, which happens only once the shell has become `sleep`.
|
||||
const parent = spawn("/bin/sh", ["-c", "cat <&3 >/dev/null & echo $!; exec sleep 600 3<&-"], {
|
||||
stdio: ["ignore", "pipe", "ignore", "pipe"],
|
||||
});
|
||||
parent.unref();
|
||||
const release = () => {
|
||||
parent.stdio[3]?.destroy();
|
||||
if (parent.exitCode === null && parent.signalCode === null) parent.kill("SIGKILL");
|
||||
};
|
||||
try {
|
||||
const pid = await new Promise<number>((resolve) => {
|
||||
parent.stdout!.once("data", (chunk: Buffer) => resolve(Number(chunk.toString().trim())));
|
||||
});
|
||||
await expect.poll(() => psField(parent.pid!, "comm")).toMatch(/(^|\/)sleep$/);
|
||||
parent.stdio[3]!.destroy();
|
||||
await expect.poll(async () => (await psField(pid, "stat")).startsWith("Z")).toBe(true);
|
||||
const gone = spawn(process.execPath, ["-e", ""], { stdio: "ignore" });
|
||||
await new Promise((resolve) => gone.once("exit", resolve));
|
||||
|
||||
@@ -33,8 +33,10 @@ async function createRunningMockAgent(
|
||||
return { id: agent.id, title };
|
||||
}
|
||||
|
||||
async function openCommandCenter(page: Page): Promise<void> {
|
||||
// Agents are found through their workspace: the query names the agent, the row shows it.
|
||||
async function searchCommandCenter(page: Page, query: string): Promise<void> {
|
||||
await page.getByTestId("sidebar-search").click();
|
||||
await page.getByTestId("command-center-input").fill(query);
|
||||
}
|
||||
|
||||
export class DirectoryBootstrapScenario {
|
||||
@@ -78,8 +80,10 @@ export class DirectoryBootstrapScenario {
|
||||
const workspaceLink = this.page.getByText(workspace.projectDisplayName, { exact: true });
|
||||
await expect(workspaceLink).toHaveCount(1);
|
||||
await expect(workspaceLink).toBeVisible();
|
||||
await openCommandCenter(this.page);
|
||||
const agentLink = this.page.getByText(agent.title, { exact: true });
|
||||
await searchCommandCenter(this.page, agent.title);
|
||||
const agentLink = this.page
|
||||
.getByTestId("command-center-workspace-agent")
|
||||
.getByText(agent.title, { exact: true });
|
||||
await expect(agentLink).toHaveCount(1);
|
||||
await expect(agentLink).toBeVisible();
|
||||
await this.page.keyboard.press("Escape");
|
||||
@@ -111,8 +115,10 @@ export class DirectoryBootstrapScenario {
|
||||
const workspaceLink = this.page.getByText(workspace.projectDisplayName, { exact: true });
|
||||
await expect(workspaceLink).toHaveCount(1);
|
||||
await expect(workspaceLink).toBeVisible();
|
||||
await openCommandCenter(this.page);
|
||||
const agentLink = this.page.getByText(agent.title, { exact: true });
|
||||
await searchCommandCenter(this.page, agent.title);
|
||||
const agentLink = this.page
|
||||
.getByTestId("command-center-workspace-agent")
|
||||
.getByText(agent.title, { exact: true });
|
||||
await expect(agentLink).toHaveCount(1);
|
||||
await expect(agentLink).toBeVisible();
|
||||
await agentLink.click();
|
||||
|
||||
@@ -232,8 +232,11 @@ export async function expectNewWorkspaceControlsEnabled(page: Page): Promise<voi
|
||||
});
|
||||
}
|
||||
|
||||
export async function openNewWorkspaceProjectPickerWithShortcut(page: Page): Promise<void> {
|
||||
await page.keyboard.press("Control+P");
|
||||
export async function openNewWorkspaceProjectPickerWithShortcut(
|
||||
page: Page,
|
||||
shortcut = "Control+P",
|
||||
): Promise<void> {
|
||||
await page.keyboard.press(shortcut);
|
||||
|
||||
const searchInput = page.getByPlaceholder("Search projects");
|
||||
await expect(searchInput).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
@@ -86,17 +86,6 @@ 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,
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { expect, test as base, type Page } from "../fixtures";
|
||||
import appPackage from "../../../package.json";
|
||||
import { gotoAppShell, openSettings } from "./app";
|
||||
import { addConnectedHostAndReload } from "./hosts";
|
||||
import { pluginRequirements } from "./plugin-fixture";
|
||||
import {
|
||||
expectToast,
|
||||
openPluginPage,
|
||||
pluginPageName,
|
||||
selectInstalledTab,
|
||||
selectPluginPageAction,
|
||||
} from "./plugin-gallery";
|
||||
import { openHostSection, selectSettingsHost } from "./settings";
|
||||
import { startHostDaemon } from "./versioned-host-daemon";
|
||||
|
||||
/**
|
||||
* Settings → Plugins → Browse against a host whose registry is a local server. The one listing
|
||||
* installs from a local Git repository, so installing needs no network.
|
||||
*/
|
||||
|
||||
export const LISTING = {
|
||||
id: "acme/directory-example",
|
||||
name: "Directory example",
|
||||
description: "Adds a review checklist to every workspace",
|
||||
overview: "Directory example keeps a checklist beside your agents.",
|
||||
};
|
||||
|
||||
export const test = base.extend<{ directoryHost: { serverId: string; port: number } }>({
|
||||
directoryHost: async ({ e2eWorker }, provide) => {
|
||||
void e2eWorker;
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-plugin-directory-"));
|
||||
const registry = await startRegistry(await createListedPlugin(root));
|
||||
try {
|
||||
const host = await startHostDaemon({
|
||||
version: appPackage.version,
|
||||
pluginRegistryUrl: registry.url,
|
||||
});
|
||||
try {
|
||||
await provide({ serverId: host.serverId, port: host.port });
|
||||
} finally {
|
||||
await host.dispose();
|
||||
}
|
||||
} finally {
|
||||
await registry.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
async function createListedPlugin(root: string) {
|
||||
const repository = path.join(root, "repository");
|
||||
execFileSync("git", ["init", "-b", "main", repository], { stdio: "ignore" });
|
||||
await writeFile(
|
||||
path.join(repository, "paseo-plugin.json"),
|
||||
JSON.stringify({
|
||||
id: "directory-example",
|
||||
name: LISTING.name,
|
||||
requirements: pluginRequirements,
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(repository, "index.client.ts"),
|
||||
"export default function () { return () => {}; }",
|
||||
);
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync(
|
||||
"git",
|
||||
["-c", "user.name=Paseo Tests", "-c", "user.email=e2e@paseo.test", ...args],
|
||||
{
|
||||
cwd: repository,
|
||||
encoding: "utf8",
|
||||
},
|
||||
).trim();
|
||||
git("add", "-A");
|
||||
git("commit", "-m", "initial");
|
||||
const date = "2026-10-03T00:00:00.000Z";
|
||||
return {
|
||||
id: LISTING.id,
|
||||
name: LISTING.name,
|
||||
description: LISTING.description,
|
||||
categories: ["tools"],
|
||||
author: { github: "acme", name: "Acme" },
|
||||
repository: { url: "https://github.com/acme/directory-example" },
|
||||
artifact: {
|
||||
kind: "git",
|
||||
remote: pathToFileURL(repository).href,
|
||||
commit: git("rev-parse", "HEAD"),
|
||||
},
|
||||
media: [],
|
||||
submittedAt: date,
|
||||
reviewedAt: date,
|
||||
updatedAt: date,
|
||||
publishedAt: date,
|
||||
installs: 1200,
|
||||
};
|
||||
}
|
||||
|
||||
async function startRegistry(listing: Record<string, unknown>) {
|
||||
const documents: Record<string, unknown> = {
|
||||
"/index.json": {
|
||||
schemaVersion: 1,
|
||||
registry: { name: "Local", url: "http://127.0.0.1" },
|
||||
categories: [{ slug: "tools", label: "Tools" }],
|
||||
plugins: [listing],
|
||||
featured: [],
|
||||
generatedAt: "2026-10-03T00:00:00.000Z",
|
||||
},
|
||||
[`/plugins/${LISTING.id}.json`]: {
|
||||
...listing,
|
||||
readme: `# ${LISTING.name}\n\n${LISTING.overview}`,
|
||||
},
|
||||
};
|
||||
const server = createServer((request, response) => {
|
||||
const document = request.url ? documents[request.url] : undefined;
|
||||
if (!document) {
|
||||
response.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
response.setHeader("Content-Type", "application/json");
|
||||
response.end(JSON.stringify(document));
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing registry address");
|
||||
return {
|
||||
url: `http://127.0.0.1:${address.port}`,
|
||||
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
|
||||
};
|
||||
}
|
||||
|
||||
function listingRow(page: Page) {
|
||||
return page.getByTestId(`plugin-listing-${LISTING.id}`).filter({ visible: true });
|
||||
}
|
||||
|
||||
function browseTab(page: Page) {
|
||||
return page.getByRole("button", { name: "Browse", exact: true });
|
||||
}
|
||||
|
||||
/** A host with no plugins opens Plugins on Browse. */
|
||||
export async function openDirectory(page: Page, host: { serverId: string; port: number }) {
|
||||
await gotoAppShell(page);
|
||||
await addConnectedHostAndReload(page, { ...host, label: "Plugin directory" });
|
||||
await openSettings(page);
|
||||
await selectSettingsHost(page, host.serverId);
|
||||
await openHostSection(page, host.serverId, "plugins");
|
||||
await expect(browseTab(page)).toHaveAttribute("aria-selected", "true");
|
||||
await expect(listingRow(page)).toContainText(LISTING.description);
|
||||
}
|
||||
|
||||
/** Install asks first, naming the author and version, then the row offers Uninstall. */
|
||||
export async function installListingFromRow(page: Page) {
|
||||
await listingRow(page).getByTestId(`plugin-install-${LISTING.id}`).click();
|
||||
const sheet = page.getByTestId("plugin-install-sheet");
|
||||
await expect(sheet).toContainText("Acme");
|
||||
await sheet.getByTestId("plugin-install-confirm").click();
|
||||
await expect(listingRow(page).getByTestId(`plugin-uninstall-${LISTING.id}`)).toBeVisible({
|
||||
timeout: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** Installing the first plugin keeps the user on Browse. */
|
||||
export async function expectStillBrowsing(page: Page) {
|
||||
await expect(browseTab(page)).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByRole("button", { name: /^Installed · 1/ })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openListingPage(page: Page) {
|
||||
await listingRow(page).getByText(LISTING.name, { exact: true }).click();
|
||||
await expect(pluginPageName(page)).toHaveText(LISTING.name);
|
||||
await expect(page.getByText(LISTING.overview, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstalling keeps the plugin's page open on its listing, back on Install, whether the page was
|
||||
* opened from Browse or from the Installed tab.
|
||||
*/
|
||||
export async function uninstallFromPage(page: Page) {
|
||||
page.once("dialog", (dialog) => dialog.accept());
|
||||
await selectPluginPageAction(page, LISTING.name, "Uninstall");
|
||||
await expectToast(page, `Uninstalled ${LISTING.name}`);
|
||||
await expect(pluginPageName(page)).toHaveText(LISTING.name);
|
||||
await expect(
|
||||
page.getByTestId(`plugin-install-${LISTING.id}`).filter({ visible: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
|
||||
export async function installFromPage(page: Page) {
|
||||
await page.getByTestId(`plugin-install-${LISTING.id}`).filter({ visible: true }).click();
|
||||
await page.getByTestId("plugin-install-confirm").click();
|
||||
await expect(
|
||||
page.getByRole("button", { name: `Actions for ${LISTING.name}`, exact: true }),
|
||||
).toBeVisible({ timeout: 60_000 });
|
||||
}
|
||||
|
||||
export async function openFromInstalledTab(page: Page) {
|
||||
await page.getByRole("button", { name: "Back to plugins", exact: true }).click();
|
||||
await selectInstalledTab(page);
|
||||
await openPluginPage(page, LISTING.name, "directory-example");
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
import { expect, type Page } from "../fixtures";
|
||||
import { getServerId } from "./server-id";
|
||||
import { expectAppRoute } from "./route-assertions";
|
||||
|
||||
/**
|
||||
* Settings → Host → Plugins: the Installed and Browse tabs, the page menu, the install sheet and a
|
||||
* plugin's own page. Helpers that take a plugin name expect the manifest name, which is the plugin
|
||||
* ID when the manifest has none.
|
||||
*/
|
||||
|
||||
export function pluginsRoute(serverId = getServerId()): string {
|
||||
return buildSettingsHostSectionRoute(serverId, "plugins");
|
||||
}
|
||||
|
||||
export function pluginPageRoute(pluginId: string, serverId = getServerId()): string {
|
||||
return `${pluginsRoute(serverId)}/${encodeURIComponent(pluginId)}`;
|
||||
}
|
||||
|
||||
/** Settings keeps the Plugins page mounted beneath a plugin's page, so read visible rows only. */
|
||||
export function pluginRow(page: Page, pluginId: string) {
|
||||
return page.getByTestId(`plugin-row-${pluginId}`).filter({ visible: true });
|
||||
}
|
||||
|
||||
function pluginSwitch(page: Page, name: string, action: "Disable" | "Enable") {
|
||||
return page.getByRole("switch", { name: `${name}: ${action}`, exact: true }).filter({
|
||||
visible: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectToast(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("app-toast-message")).toContainText(message);
|
||||
}
|
||||
|
||||
// Tabs and search
|
||||
|
||||
export async function selectInstalledTab(page: Page): Promise<void> {
|
||||
const tab = page.getByRole("button", { name: /^Installed/ });
|
||||
await tab.click();
|
||||
await expect(tab).toHaveAttribute("aria-selected", "true");
|
||||
}
|
||||
|
||||
export async function searchInstalled(page: Page, query: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Search installed", exact: true }).fill(query);
|
||||
}
|
||||
|
||||
export async function clearSearch(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Clear search", exact: true }).click();
|
||||
await expect(page.getByRole("textbox", { name: "Search installed", exact: true })).toHaveValue(
|
||||
"",
|
||||
);
|
||||
}
|
||||
|
||||
// Installed rows
|
||||
|
||||
export async function expectPluginOn(page: Page, name: string): Promise<void> {
|
||||
await expect(pluginSwitch(page, name, "Disable")).toBeVisible();
|
||||
await expect(pluginSwitch(page, name, "Disable")).toBeEnabled();
|
||||
}
|
||||
|
||||
export async function expectPluginOff(page: Page, name: string): Promise<void> {
|
||||
await expect(pluginSwitch(page, name, "Enable")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function turnPluginOff(page: Page, name: string): Promise<void> {
|
||||
await pluginSwitch(page, name, "Disable").click();
|
||||
await expectPluginOff(page, name);
|
||||
}
|
||||
|
||||
export async function turnPluginOn(page: Page, name: string): Promise<void> {
|
||||
await pluginSwitch(page, name, "Enable").click();
|
||||
await expectPluginOn(page, name);
|
||||
}
|
||||
|
||||
/** The switch stays disabled while an action on the plugin runs, so a second one cannot start. */
|
||||
export async function expectPluginActionPending(page: Page, name: string): Promise<void> {
|
||||
await expect(pluginSwitch(page, name, "Disable")).toBeDisabled();
|
||||
}
|
||||
|
||||
export async function expectPluginFailed(page: Page, pluginId: string): Promise<void> {
|
||||
await expect(pluginRow(page, pluginId).getByText("failed", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectPluginHealthy(page: Page, pluginId: string): Promise<void> {
|
||||
await expect(pluginRow(page, pluginId)).toBeVisible();
|
||||
await expect(pluginRow(page, pluginId).getByText("failed", { exact: true })).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectPluginRemoved(page: Page, pluginId: string): Promise<void> {
|
||||
await expect(page.getByTestId(`plugin-row-${pluginId}`)).toHaveCount(0);
|
||||
}
|
||||
|
||||
// Plugins on the host
|
||||
|
||||
function pluginsOffAlert(page: Page) {
|
||||
return page.getByRole("alert").filter({ hasText: "Plugins are off on" });
|
||||
}
|
||||
|
||||
export async function expectPluginsOff(page: Page): Promise<void> {
|
||||
await expect(pluginsOffAlert(page)).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectPluginsOn(page: Page): Promise<void> {
|
||||
await expect(pluginsOffAlert(page)).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function turnOnPluginsFromAlert(page: Page): Promise<void> {
|
||||
await pluginsOffAlert(page).getByRole("button", { name: "Turn on", exact: true }).click();
|
||||
await expectPluginsOn(page);
|
||||
}
|
||||
|
||||
// The page menu
|
||||
|
||||
function galleryMenu(page: Page) {
|
||||
return page.getByRole("button", { name: "More plugin actions", exact: true }).filter({
|
||||
visible: true,
|
||||
});
|
||||
}
|
||||
|
||||
async function openGalleryMenu(page: Page): Promise<void> {
|
||||
await galleryMenu(page).click();
|
||||
await expect(page.getByRole("menuitem").first()).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectGalleryMenuWithoutSourceInstall(page: Page): Promise<void> {
|
||||
await openGalleryMenu(page);
|
||||
await expect(page.getByRole("menuitem", { name: "Turn off plugins", exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("menuitem", { name: "Install from source", exact: true }),
|
||||
).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
|
||||
export async function turnOffPluginsFromMenu(page: Page): Promise<void> {
|
||||
await openGalleryMenu(page);
|
||||
await page.getByRole("menuitem", { name: "Turn off plugins", exact: true }).click();
|
||||
await expectToast(page, "Plugins disabled");
|
||||
await expectPluginsOff(page);
|
||||
}
|
||||
|
||||
export async function turnOnPluginsFromMenu(page: Page): Promise<void> {
|
||||
await openGalleryMenu(page);
|
||||
await page.getByRole("menuitem", { name: "Turn on plugins", exact: true }).click();
|
||||
await expectToast(page, "Plugins enabled");
|
||||
await expectPluginsOn(page);
|
||||
}
|
||||
|
||||
// Install from source
|
||||
|
||||
function sourceField(page: Page) {
|
||||
return page.getByRole("textbox", { name: "Plugin source", exact: true });
|
||||
}
|
||||
|
||||
export async function openSourceInstall(page: Page): Promise<void> {
|
||||
await openGalleryMenu(page);
|
||||
await page.getByRole("menuitem", { name: "Install from source", exact: true }).click();
|
||||
await expect(sourceField(page)).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectSourceInstallTurnsPluginsOn(page: Page): Promise<void> {
|
||||
await expect(
|
||||
page.getByText("Plugins are not sandboxed. Installing also turns plugins on.", {
|
||||
exact: true,
|
||||
}),
|
||||
).toBeVisible();
|
||||
}
|
||||
|
||||
export async function submitSourceInstall(page: Page, source: string): Promise<void> {
|
||||
await sourceField(page).fill(source);
|
||||
await page.getByRole("button", { name: "Install", exact: true }).click();
|
||||
}
|
||||
|
||||
/** A failed install keeps the sheet open with the source, so the user can correct it. */
|
||||
export async function expectSourceInstallFailed(
|
||||
page: Page,
|
||||
source: string,
|
||||
message: string,
|
||||
): Promise<void> {
|
||||
await expect(page.getByRole("alert").filter({ hasText: message })).toBeVisible();
|
||||
await expect(sourceField(page)).toHaveValue(source);
|
||||
}
|
||||
|
||||
export async function expectSourceInstalled(page: Page, name: string): Promise<void> {
|
||||
await expectToast(page, `Installed ${name}`);
|
||||
await expect(sourceField(page)).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function installFromSource(page: Page, source: string, name: string): Promise<void> {
|
||||
await openSourceInstall(page);
|
||||
await submitSourceInstall(page, source);
|
||||
await expectSourceInstalled(page, name);
|
||||
}
|
||||
|
||||
// Updates
|
||||
|
||||
function updateRow(page: Page, pluginId: string) {
|
||||
return page.getByTestId(`plugin-update-${pluginId}`).filter({ visible: true });
|
||||
}
|
||||
|
||||
export async function updatePlugin(page: Page, pluginId: string): Promise<void> {
|
||||
await updateRow(page, pluginId).getByRole("button", { name: "Update", exact: true }).click();
|
||||
await expectToast(page, `${pluginId} updated`);
|
||||
await expect(page.getByTestId(`plugin-update-${pluginId}`)).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectUpdateAvailable(page: Page, pluginId: string): Promise<void> {
|
||||
await expect(updateRow(page, pluginId)).toBeVisible();
|
||||
}
|
||||
|
||||
// A plugin's page
|
||||
|
||||
export function pluginPageName(page: Page) {
|
||||
return page.getByTestId("plugin-page-name").filter({ visible: true });
|
||||
}
|
||||
|
||||
/** Opens the plugin's page from its row on the Installed tab. */
|
||||
export async function openPluginPage(page: Page, name: string, pluginId = name): Promise<void> {
|
||||
await pluginRow(page, pluginId).getByText(name, { exact: true }).click();
|
||||
await expect(pluginPageName(page)).toHaveText(name);
|
||||
}
|
||||
|
||||
export async function backToPlugins(page: Page, pluginId: string): Promise<void> {
|
||||
await page.getByRole("button", { name: "Back to plugins", exact: true }).click();
|
||||
await expect(pluginRow(page, pluginId)).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openPluginPageActions(page: Page, name: string): Promise<void> {
|
||||
await page
|
||||
.getByRole("button", { name: `Actions for ${name}`, exact: true })
|
||||
.filter({ visible: true })
|
||||
.click();
|
||||
await expect(page.getByRole("menuitem").first()).toBeVisible();
|
||||
}
|
||||
|
||||
export async function selectPluginPageAction(
|
||||
page: Page,
|
||||
name: string,
|
||||
action: "Reload" | "Logs" | "Uninstall",
|
||||
): Promise<void> {
|
||||
await openPluginPageActions(page, name);
|
||||
await page.getByRole("menuitem", { name: action, exact: true }).click();
|
||||
}
|
||||
|
||||
export async function reloadPluginFromPage(page: Page, name: string): Promise<void> {
|
||||
await selectPluginPageAction(page, name, "Reload");
|
||||
await expectToast(page, `Reloaded ${name}`);
|
||||
}
|
||||
|
||||
export async function openPluginLogs(page: Page, name: string): Promise<void> {
|
||||
await selectPluginPageAction(page, name, "Logs");
|
||||
await expect(page.getByRole("dialog")).toContainText(`Logs: ${name}`);
|
||||
}
|
||||
|
||||
export async function closePluginLogs(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(page.getByRole("dialog")).toHaveCount(0);
|
||||
}
|
||||
|
||||
/** Uninstall confirms first; uninstalling a plugin that is not in the directory returns to Plugins. */
|
||||
export async function removePluginFromPage(page: Page, name: string): Promise<void> {
|
||||
page.once("dialog", (dialog) => dialog.accept());
|
||||
await selectPluginPageAction(page, name, "Uninstall");
|
||||
await expectToast(page, `Uninstalled ${name}`);
|
||||
await expect(pluginPageName(page)).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectPluginsRoute(page: Page): Promise<void> {
|
||||
await expectAppRoute(page, pluginsRoute());
|
||||
}
|
||||
@@ -106,12 +106,10 @@ export async function verifyProviderSettings({
|
||||
await test.step("provider settings render the registered icon", async () => {
|
||||
await openSettings(page);
|
||||
await openSettingsHostSection(page, getServerId(), "providers");
|
||||
// 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 expectProviderIcon(
|
||||
page.getByRole("button", { name: "Direct provider example provider details", exact: true }),
|
||||
iconPaths,
|
||||
);
|
||||
await capture(page, testInfo, "provider-settings");
|
||||
await page.getByTestId("settings-back-to-workspace").click();
|
||||
});
|
||||
|
||||
@@ -9,6 +9,15 @@ import { addConnectedHostAndReload } from "./hosts";
|
||||
import { gotoAppShell, openSettings } from "./app";
|
||||
import { openHostSection, selectSettingsHost } from "./settings";
|
||||
import { pluginRequirements } from "./plugin-fixture";
|
||||
import {
|
||||
backToPlugins,
|
||||
expectPluginFailed,
|
||||
expectPluginHealthy,
|
||||
openPluginPage,
|
||||
selectPluginPageAction,
|
||||
} from "./plugin-gallery";
|
||||
|
||||
const PLUGIN_ID = "requirements-example";
|
||||
|
||||
export const test = base.extend<{
|
||||
requirementHost: { serverId: string; port: number; directory: string; client: DaemonClient };
|
||||
@@ -80,7 +89,7 @@ export const test = base.extend<{
|
||||
async function writeRequirements(directory: string, paseo: string) {
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "requirements-example", requirements: { paseo } }),
|
||||
JSON.stringify({ id: PLUGIN_ID, requirements: { paseo } }),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -93,7 +102,7 @@ export async function openRequirementHost(page: Page, host: { serverId: string;
|
||||
}
|
||||
|
||||
export async function expectAppMismatch(page: Page) {
|
||||
await expect(page.getByLabel("requirements-example failed", { exact: true })).toBeVisible();
|
||||
await expectPluginFailed(page, PLUGIN_ID);
|
||||
await expect(
|
||||
page.getByText(/Plugin "requirements-example" requires Paseo \^99.0.0. Your app is/),
|
||||
).toBeVisible();
|
||||
@@ -102,18 +111,21 @@ export async function expectAppMismatch(page: Page) {
|
||||
export async function correctRequirementAndReload(page: Page, directory: string) {
|
||||
await writeRequirements(directory, pluginRequirements.paseo);
|
||||
await reloadRequirementsPlugin(page);
|
||||
await expect(page.getByLabel("requirements-example running", { exact: true })).toBeVisible();
|
||||
await backToPlugins(page, PLUGIN_ID);
|
||||
await expectPluginHealthy(page, PLUGIN_ID);
|
||||
await expect(page.getByText(/Your app is/)).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function rejectDaemonMismatch(page: Page, directory: string) {
|
||||
await writeRequirements(directory, ">=100.0.0");
|
||||
await reloadRequirementsPlugin(page);
|
||||
await expect(page.getByLabel("requirements-example failed", { exact: true })).toBeVisible();
|
||||
await backToPlugins(page, PLUGIN_ID);
|
||||
await expectPluginFailed(page, PLUGIN_ID);
|
||||
await expect(page.getByText(/Your daemon is 99.0.0/).first()).toBeVisible();
|
||||
}
|
||||
|
||||
/** Reload lives on the plugin's page. */
|
||||
async function reloadRequirementsPlugin(page: Page) {
|
||||
await page.getByRole("button", { name: "Actions for requirements-example", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Reload", exact: true }).click();
|
||||
await openPluginPage(page, PLUGIN_ID);
|
||||
await selectPluginPageAction(page, PLUGIN_ID, "Reload");
|
||||
}
|
||||
|
||||
@@ -7,8 +7,18 @@ import { gotoAppShell, openSettings } from "./app";
|
||||
import { goBackInSettings, openCompactSettings, openHostSection } from "./settings";
|
||||
import { getServerId } from "./server-id";
|
||||
import { expectAppRoute } from "./route-assertions";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
|
||||
import {
|
||||
backToPlugins,
|
||||
openPluginPage,
|
||||
openPluginPageActions,
|
||||
pluginPageName,
|
||||
pluginPageRoute,
|
||||
pluginRow,
|
||||
pluginsRoute,
|
||||
turnPluginOff,
|
||||
turnPluginOn,
|
||||
} from "./plugin-gallery";
|
||||
|
||||
type SettingsClient = Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
|
||||
|
||||
@@ -90,68 +100,64 @@ export const test = base.extend<{ settingsPlugin: SettingsClient }>({
|
||||
export async function openDisplaySettings(page: Page) {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openPluginScreen(page);
|
||||
await openSettingsExamplePage(page);
|
||||
}
|
||||
export async function openCompactDisplaySettings(page: Page) {
|
||||
await gotoAppShell(page);
|
||||
await openCompactSettings(page, new URL(page.url()).pathname);
|
||||
await openPluginScreen(page);
|
||||
await openSettingsExamplePage(page);
|
||||
}
|
||||
async function openPluginScreen(page: Page) {
|
||||
async function openSettingsExamplePage(page: Page) {
|
||||
await openHostSection(page, getServerId(), "plugins");
|
||||
await openSettingsFromCog(page);
|
||||
await openPluginPage(page, "settings-example");
|
||||
await expectSettingsExampleScreen(page);
|
||||
}
|
||||
/** The cog on a plugin's row. Its label is "Settings"; the row tells plugins apart. */
|
||||
function settingsButton(page: Page, pluginId: string) {
|
||||
return page
|
||||
.getByTestId(`plugin-row-${pluginId}`)
|
||||
.filter({ visible: true })
|
||||
.getByRole("button", { name: "Settings", exact: true });
|
||||
}
|
||||
async function openSettingsFromCog(page: Page) {
|
||||
await settingsButton(page, "settings-example").click();
|
||||
/** A plugin's page shows its settings inline. With one screen there are no tabs. */
|
||||
async function expectSettingsExampleScreen(page: Page) {
|
||||
await expect(page.getByRole("switch", { name: "Show metadata" })).toBeVisible();
|
||||
// A plugin with one settings screen shows no tabs, and the header names only the plugin.
|
||||
await expect(page.getByTestId("plugin-settings-tabs")).toHaveCount(0);
|
||||
await expectSettingsHeader(page, "settings-example");
|
||||
await expectAppRoute(page, pluginPageRoute("settings-example"));
|
||||
}
|
||||
export async function openPluginsPage(page: Page) {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openHostSection(page, getServerId(), "plugins");
|
||||
}
|
||||
/** The page's menu holds plugin actions only; its settings screens are on the page itself. */
|
||||
export async function expectActionsMenuWithoutSettings(page: Page) {
|
||||
await page.getByRole("button", { name: "Actions for settings-example", exact: true }).click();
|
||||
await openPluginPageActions(page, TABBED_PLUGIN_NAME);
|
||||
await expect(page.getByRole("menuitem", { name: "Reload", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Display", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole("menuitem", { name: "General", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole("menuitem", { name: "Advanced", exact: true })).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
export async function expectNoSettingsCogWithoutScreens(page: Page) {
|
||||
await page.getByRole("switch", { name: "settings-example: Disable" }).click();
|
||||
await expect(page.getByRole("switch", { name: "settings-example: Enable" })).toBeVisible();
|
||||
await expect(settingsButton(page, "settings-example")).toHaveCount(0);
|
||||
await page.getByRole("switch", { name: "settings-example: Enable" }).click();
|
||||
await expect(settingsButton(page, "settings-example")).toBeVisible();
|
||||
/** Turning a plugin off unloads its settings screens, so its page no longer shows them. */
|
||||
export async function expectSettingsFollowPluginSwitch(page: Page) {
|
||||
await openPluginPage(page, "settings-example");
|
||||
await turnPluginOff(page, "settings-example");
|
||||
await expectSettingsHidden(page);
|
||||
await turnPluginOn(page, "settings-example");
|
||||
await expect(page.getByRole("switch", { name: "Show metadata" })).toBeVisible();
|
||||
}
|
||||
export async function expectSettingsTooltip(page: Page) {
|
||||
await settingsButton(page, "settings-example").hover();
|
||||
await expect(page.getByRole("tooltip")).toHaveText("Settings");
|
||||
await page.mouse.move(0, 0);
|
||||
export async function expectSettingsHidden(page: Page) {
|
||||
await expect(page.getByRole("switch", { name: "Show metadata" })).toHaveCount(0);
|
||||
}
|
||||
/** A manifest `name` titles the row and its controls; the id stays visible beneath it. */
|
||||
/** A manifest `name` titles the row and its switch, and opens the plugin's page. */
|
||||
export async function expectNamedPluginRow(page: Page) {
|
||||
const row = page.getByTestId(`plugin-row-${TABBED_PLUGIN_ID}`).filter({ visible: true });
|
||||
const row = pluginRow(page, TABBED_PLUGIN_ID);
|
||||
await expect(row.getByText(TABBED_PLUGIN_NAME, { exact: true })).toBeVisible();
|
||||
await expect(row.getByText(TABBED_PLUGIN_ID, { exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("switch", { name: `${TABBED_PLUGIN_NAME}: Disable`, exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("button", { name: `Actions for ${TABBED_PLUGIN_NAME}`, exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(row).toHaveAccessibleName(TABBED_PLUGIN_NAME);
|
||||
}
|
||||
/** The page names the plugin by its manifest name, with the ID beneath it. */
|
||||
export async function openTabbedSettings(page: Page) {
|
||||
await settingsButton(page, TABBED_PLUGIN_ID).click();
|
||||
await openPluginPage(page, TABBED_PLUGIN_NAME, TABBED_PLUGIN_ID);
|
||||
await expect(
|
||||
page.getByText(TABBED_PLUGIN_ID, { exact: true }).filter({ visible: true }),
|
||||
).toBeVisible();
|
||||
await expectAppRoute(page, pluginPageRoute(TABBED_PLUGIN_ID));
|
||||
await expectSettingsTab(page, "General");
|
||||
// The Advanced icon reads the plugin's translations; the General icon throws and is dropped.
|
||||
await expect(page.getByTestId("advanced-tab-icon")).toBeVisible();
|
||||
@@ -159,27 +165,25 @@ export async function openTabbedSettings(page: Page) {
|
||||
function settingsTab(page: Page, title: string) {
|
||||
return page.getByTestId("plugin-settings-tabs").getByRole("button", { name: title, exact: true });
|
||||
}
|
||||
/** Tabs swap the screen in place on the plugin's page, so Back still returns to Plugins. */
|
||||
export async function selectSettingsTab(page: Page, title: "General" | "Advanced") {
|
||||
await settingsTab(page, title).click();
|
||||
await expectSettingsTab(page, title);
|
||||
await expectAppRoute(
|
||||
page,
|
||||
`${pluginPageRoute(TABBED_PLUGIN_ID)}?screenId=${title.toLowerCase()}`,
|
||||
);
|
||||
}
|
||||
export async function expectSettingsTab(page: Page, title: "General" | "Advanced") {
|
||||
const other = title === "General" ? "Advanced" : "General";
|
||||
await expect(settingsTab(page, title)).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByText(`${title} settings body`, { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(`${other} settings body`, { exact: true })).toHaveCount(0);
|
||||
// The header names the plugin by its manifest name; the tab names the screen.
|
||||
await expectSettingsHeader(page, TABBED_PLUGIN_NAME);
|
||||
await expectAppRoute(
|
||||
page,
|
||||
`${buildSettingsHostSectionRoute(getServerId(), "plugins")}/${TABBED_PLUGIN_ID}/${title.toLowerCase()}`,
|
||||
);
|
||||
await expect(pluginPageName(page)).toHaveText(TABBED_PLUGIN_NAME);
|
||||
}
|
||||
export async function openTabbedSettingsLink(page: Page, title: "General" | "Advanced") {
|
||||
await gotoAppShell(page);
|
||||
await page.goto(
|
||||
`${buildSettingsHostSectionRoute(getServerId(), "plugins")}/${TABBED_PLUGIN_ID}/${title.toLowerCase()}`,
|
||||
);
|
||||
await page.goto(`${pluginPageRoute(TABBED_PLUGIN_ID)}/${title.toLowerCase()}`);
|
||||
await expectSettingsTab(page, title);
|
||||
}
|
||||
export async function groupByWorkspace(page: Page) {
|
||||
@@ -235,18 +239,13 @@ export async function discardTitle(page: Page) {
|
||||
}
|
||||
export async function returnAndReopenSettings(page: Page) {
|
||||
await goBackInSettings(page);
|
||||
await openSettingsFromCog(page);
|
||||
await expectAppRoute(page, pluginsRoute());
|
||||
await openPluginPage(page, "settings-example");
|
||||
await expectSettingsExampleScreen(page);
|
||||
}
|
||||
export async function returnToPluginsPage(page: Page) {
|
||||
await page.getByRole("button", { name: "Back to plugins", exact: true }).click();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "plugins"));
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Actions for settings-example", exact: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
async function expectSettingsHeader(page: Page, title: string) {
|
||||
// Settings keeps the Plugins page mounted beneath, so read the visible title only.
|
||||
await expect(page.getByText(title, { exact: true }).filter({ visible: true })).toHaveCount(1);
|
||||
await backToPlugins(page, "settings-example");
|
||||
await expectAppRoute(page, pluginsRoute());
|
||||
}
|
||||
export async function expectSettingsUnavailable(page: Page) {
|
||||
await expect(
|
||||
|
||||
@@ -131,6 +131,7 @@ export interface SeedDaemonClient {
|
||||
currentModeId: string | null;
|
||||
status: string;
|
||||
title?: string | null;
|
||||
metadata?: Record<string, unknown>;
|
||||
};
|
||||
}>;
|
||||
}>;
|
||||
|
||||
@@ -507,8 +507,8 @@ export async function serveJson(page: Page, url: string, body: unknown): Promise
|
||||
});
|
||||
}
|
||||
|
||||
export async function openAddProvider(page: Page): Promise<void> {
|
||||
await page.getByTestId("provider-list-add").click();
|
||||
export async function openAddProviderArea(page: Page): Promise<void> {
|
||||
await page.getByTestId("host-page-add-provider-card").scrollIntoViewIfNeeded();
|
||||
await expect(page.getByRole("textbox", { name: "Search providers" })).toBeVisible();
|
||||
}
|
||||
|
||||
@@ -520,59 +520,17 @@ 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,7 +427,11 @@ export async function holdOlderHistoryPages(
|
||||
const loader = page.getByTestId("load-older-history-spinner");
|
||||
return {
|
||||
async expectRequestedPages(count) {
|
||||
await gate.waitForRequestCount(count);
|
||||
await expect
|
||||
.poll(() => gate.getRequestCount(), {
|
||||
message: `older history requests ${count} page(s)`,
|
||||
})
|
||||
.toBeGreaterThanOrEqual(count);
|
||||
expect(gate.getRequestCount()).toBe(count);
|
||||
},
|
||||
async expectSettledWithRequestedPages(count) {
|
||||
|
||||
@@ -147,6 +147,84 @@ 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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recording where the cards are painted on every frame after the next mouse release.
|
||||
* Call the returned function to stop and read the frames, each as "id@top" for every card.
|
||||
*/
|
||||
export async function recordUsageCardPositionsAfterRelease(
|
||||
page: Page,
|
||||
): Promise<() => Promise<string[]>> {
|
||||
const recording = await usageModal(page).evaluateHandle((modal) => {
|
||||
const state = { released: false, stopped: false, frames: [] as string[] };
|
||||
const markReleased = () => {
|
||||
state.released = true;
|
||||
};
|
||||
window.addEventListener("mouseup", markReleased, { capture: true, once: true });
|
||||
const recordFrame = () => {
|
||||
if (state.stopped) return;
|
||||
if (state.released) {
|
||||
const cards = Array.from(modal.querySelectorAll('[data-testid^="usage-report-"]'));
|
||||
state.frames.push(
|
||||
cards
|
||||
.map((card) => {
|
||||
const id = card.getAttribute("data-testid")?.slice("usage-report-".length);
|
||||
return `${id}@${Math.round(card.getBoundingClientRect().top)}`;
|
||||
})
|
||||
.join(" "),
|
||||
);
|
||||
}
|
||||
requestAnimationFrame(recordFrame);
|
||||
};
|
||||
requestAnimationFrame(recordFrame);
|
||||
return state;
|
||||
});
|
||||
return () =>
|
||||
recording.evaluate((state) => {
|
||||
state.stopped = true;
|
||||
return state.frames;
|
||||
});
|
||||
}
|
||||
|
||||
/** 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");
|
||||
@@ -167,14 +245,18 @@ 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 buttons, so no row presses or highlights on hover.
|
||||
* but the header's buttons and on/off switch, 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) => node.getAttribute("role") !== "button").length);
|
||||
.evaluateAll(
|
||||
(nodes) =>
|
||||
nodes.filter((node) => !["button", "switch"].includes(node.getAttribute("role") ?? ""))
|
||||
.length,
|
||||
);
|
||||
expect(focusable).toBe(0);
|
||||
}
|
||||
|
||||
@@ -273,6 +355,19 @@ 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(
|
||||
|
||||
@@ -62,6 +62,38 @@ export async function startRestartableHostDaemon(version: string): Promise<Resta
|
||||
};
|
||||
}
|
||||
|
||||
export interface HostDaemon {
|
||||
serverId: string;
|
||||
port: number;
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
|
||||
/** A host daemon of its own, for tests that need host configuration the worker daemon lacks. */
|
||||
export async function startHostDaemon(options: {
|
||||
version: string;
|
||||
pluginRegistryUrl?: string;
|
||||
}): Promise<HostDaemon> {
|
||||
const paseoHomeRoot = await mkdtemp(path.join(tmpdir(), "paseo-e2e-host-"));
|
||||
try {
|
||||
const daemon = await startVersionedHostDaemon({
|
||||
...options,
|
||||
port: await getAvailableHostDaemonPort(),
|
||||
paseoHomeRoot,
|
||||
});
|
||||
return {
|
||||
serverId: daemon.serverId,
|
||||
port: daemon.port,
|
||||
async dispose() {
|
||||
await daemon.stop();
|
||||
await rm(paseoHomeRoot, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await rm(paseoHomeRoot, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
interface VersionedHostDaemon {
|
||||
serverId: string;
|
||||
port: number;
|
||||
@@ -73,6 +105,7 @@ interface VersionedHostDaemonOptions {
|
||||
version: string;
|
||||
port: number;
|
||||
paseoHomeRoot: string;
|
||||
pluginRegistryUrl?: string;
|
||||
}
|
||||
|
||||
// Starts the versioned test daemon on an explicit port with a caller-owned PASEO_HOME. The caller
|
||||
@@ -83,7 +116,12 @@ async function startVersionedHostDaemon(
|
||||
const child = spawnTsx(
|
||||
VERSIONED_DAEMON_ENTRYPOINT,
|
||||
[options.version, String(options.port), options.paseoHomeRoot],
|
||||
{ stdio: ["ignore", "pipe", "pipe", "ipc"] },
|
||||
{
|
||||
stdio: ["ignore", "pipe", "pipe", "ipc"],
|
||||
env: options.pluginRegistryUrl
|
||||
? { ...process.env, PASEO_PLUGIN_REGISTRY: options.pluginRegistryUrl }
|
||||
: process.env,
|
||||
},
|
||||
);
|
||||
const ready = Promise.withResolvers<{ port: number; serverId: string }>();
|
||||
let output = "";
|
||||
|
||||
@@ -162,3 +162,38 @@ 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)),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -91,10 +91,13 @@ async function selectWorkspaceTab(tab: Locator): Promise<void> {
|
||||
export async function ensureExplorerSidebar(page: Page): Promise<Locator> {
|
||||
const toggle = page.getByTestId("workspace-explorer-toggle").first();
|
||||
await expect(toggle).toBeVisible({ timeout: 30_000 });
|
||||
const explorer = explorerSidebar(page);
|
||||
if ((await explorer.count()) === 0) {
|
||||
// Decide from the toggle, which reports the open state. The sidebar's own visibility lags it:
|
||||
// a compact layout draws its closed Explorer for a frame before hiding it.
|
||||
if ((await toggle.getAttribute("aria-expanded")) !== "true") {
|
||||
await toggle.click();
|
||||
}
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "true");
|
||||
const explorer = explorerSidebar(page);
|
||||
await expect(explorer).toBeVisible({ timeout: 30_000 });
|
||||
return explorer;
|
||||
}
|
||||
|
||||
@@ -15,5 +15,6 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'com.facebook.react:react-android'
|
||||
testImplementation "junit:junit:4.13.2"
|
||||
}
|
||||
|
||||
+25
-3
@@ -1,26 +1,48 @@
|
||||
package sh.paseo.trace
|
||||
|
||||
import android.os.Trace
|
||||
import com.facebook.react.bridge.UiThreadUtil
|
||||
import com.facebook.react.bridge.ReactContext
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
|
||||
class PaseoNativeTraceModule : Module() {
|
||||
private var recorder: DiagnosticRecorder? = null
|
||||
private var touches: TouchDiagnostics? = null
|
||||
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("PaseoNativeTrace")
|
||||
|
||||
Function("startRecorder") { metadata: Map<String, String> ->
|
||||
if (recorder == null) {
|
||||
appContext.reactContext?.applicationContext?.let { recorder = DiagnosticRecorder(it, metadata) }
|
||||
(appContext.reactContext as? ReactContext)?.let { context ->
|
||||
val sink = DiagnosticRecorder(context.applicationContext, metadata)
|
||||
recorder = sink
|
||||
UiThreadUtil.runOnUiThread {
|
||||
if (recorder === sink) {
|
||||
touches = TouchDiagnostics(context, sink::record).also { it.start(appContext.currentActivity?.window) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
HeartbeatTiming.intervalMs
|
||||
}
|
||||
Function("record") { name: String, data: Map<String, String> -> recorder?.record(name, data) }
|
||||
Function("heartbeat") { recorder?.heartbeat() }
|
||||
OnActivityEntersForeground { recorder?.active(true) }
|
||||
OnActivityEntersForeground {
|
||||
recorder?.active(true)
|
||||
UiThreadUtil.runOnUiThread { touches?.activity(appContext.currentActivity?.window) }
|
||||
}
|
||||
OnActivityEntersBackground { recorder?.active(false) }
|
||||
OnDestroy { recorder?.close(); recorder = null }
|
||||
OnDestroy {
|
||||
val sink = recorder
|
||||
recorder = null
|
||||
UiThreadUtil.runOnUiThread {
|
||||
touches?.close()
|
||||
touches = null
|
||||
sink?.close()
|
||||
}
|
||||
}
|
||||
|
||||
Function("beginSection") { name: String ->
|
||||
Trace.beginSection(name.take(127))
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package sh.paseo.trace
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.os.Build
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.Window
|
||||
import android.view.WindowInsets
|
||||
import com.facebook.react.R
|
||||
import com.facebook.react.bridge.ReactContext
|
||||
import com.facebook.react.bridge.UiThreadUtil
|
||||
import com.facebook.react.interfaces.ExtraWindowEventListener
|
||||
import com.facebook.react.uimanager.ReactPointerEventsView
|
||||
import com.facebook.react.uimanager.TouchTargetHelper
|
||||
import com.facebook.react.uimanager.RootView
|
||||
|
||||
/** Temporary touch evidence. Only attached while the diagnostic recorder is running. */
|
||||
internal class TouchDiagnostics(
|
||||
private val context: ReactContext,
|
||||
private val write: (String, Map<String, String>) -> Unit,
|
||||
) : ExtraWindowEventListener {
|
||||
private val windows = mutableMapOf<Window, TouchCallback>()
|
||||
private var nextWindow = 0
|
||||
private var activityWindow: Window? = null
|
||||
|
||||
fun start(window: Window?) {
|
||||
UiThreadUtil.assertOnUiThread()
|
||||
context.addExtraWindowEventListener(this)
|
||||
activity(window)
|
||||
}
|
||||
|
||||
fun activity(window: Window?) {
|
||||
if (activityWindow === window) return
|
||||
activityWindow?.let { release(it) }
|
||||
activityWindow = window
|
||||
window?.let { observe(it) }
|
||||
}
|
||||
|
||||
override fun onExtraWindowCreate(window: Window) = observe(window)
|
||||
override fun onExtraWindowDestroy(window: Window) = release(window)
|
||||
|
||||
private fun observe(window: Window) {
|
||||
if (windows.containsKey(window)) return
|
||||
val callback = TouchCallback(window, window.callback, ++nextWindow, write)
|
||||
windows[window] = callback
|
||||
window.callback = callback
|
||||
write("touch.window.open", mapOf("window" to "$nextWindow"))
|
||||
}
|
||||
|
||||
private fun release(window: Window) {
|
||||
val callback = windows.remove(window) ?: return
|
||||
// Another observer may wrap ours. Disable it even when we cannot unwrap its owner.
|
||||
callback.active = false
|
||||
if (window.callback === callback) window.callback = callback.previous
|
||||
write("touch.window.close", mapOf("window" to "${callback.id}"))
|
||||
}
|
||||
|
||||
fun close() {
|
||||
context.removeExtraWindowEventListener(this)
|
||||
windows.keys.toList().forEach { release(it) }
|
||||
activityWindow = null
|
||||
}
|
||||
}
|
||||
|
||||
private class TouchCallback(
|
||||
private val window: Window,
|
||||
val previous: Window.Callback,
|
||||
val id: Int,
|
||||
private val write: (String, Map<String, String>) -> Unit,
|
||||
) : Window.Callback by previous {
|
||||
var active = true
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
val boundary = event.actionMasked == MotionEvent.ACTION_DOWN ||
|
||||
event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL
|
||||
if (!active || !boundary) return previous.dispatchTouchEvent(event)
|
||||
val fields = mutableMapOf(
|
||||
"window" to "$id", "gesture" to "${event.downTime}",
|
||||
"action" to "${event.actionMasked}", "eventMs" to "${event.eventTime}",
|
||||
"x" to "${event.x}", "y" to "${event.y}",
|
||||
"imeVisible" to if (Build.VERSION.SDK_INT >= 30) "${window.decorView.rootWindowInsets?.isVisible(WindowInsets.Type.ime())}" else "unsupported",
|
||||
"imeBottom" to if (Build.VERSION.SDK_INT >= 30) "${window.decorView.rootWindowInsets?.getInsets(WindowInsets.Type.ime())?.bottom}" else "unsupported",
|
||||
"focus" to describe(window.currentFocus),
|
||||
)
|
||||
// This is a hit-test prediction, not proof that the eventual responder accepted the press.
|
||||
// Use RN's own pointer-events and transformed-coordinate rules, rather than approximating them.
|
||||
val root = reactRootAt(window.decorView, event.x.toInt(), event.y.toInt())
|
||||
if (root != null) {
|
||||
try {
|
||||
val origin = IntArray(2)
|
||||
root.getLocationOnScreen(origin)
|
||||
val path = TouchTargetHelper.findTargetPathAndCoordinatesForTouch(event.rawX - origin[0], event.rawY - origin[1], root, FloatArray(2))
|
||||
path.take(10).forEachIndexed { index, target ->
|
||||
fields["hit$index"] = "${target.getViewId()}:${describe(target.getView())}"
|
||||
}
|
||||
} catch (error: RuntimeException) {
|
||||
fields["hitError"] = error.javaClass.simpleName
|
||||
}
|
||||
}
|
||||
write("touch.window.before", fields)
|
||||
val handled = previous.dispatchTouchEvent(event)
|
||||
write("touch.window.after", mapOf(
|
||||
"window" to "$id", "gesture" to "${event.downTime}",
|
||||
"action" to "${event.actionMasked}", "handled" to "$handled",
|
||||
"focus" to describe(window.currentFocus),
|
||||
))
|
||||
return handled
|
||||
}
|
||||
}
|
||||
|
||||
private fun describe(view: View?): String {
|
||||
if (view == null) return "none"
|
||||
// Deliberately omit text, accessibility labels, nativeID, and content descriptions.
|
||||
val pointer = (view as? ReactPointerEventsView)?.pointerEvents
|
||||
val testId = (view.getTag(R.id.react_test_id) as? String)?.takeIf { it in diagnosticTestIds } ?: ""
|
||||
return "${view.javaClass.simpleName}#$testId/${view.id};p=$pointer;a=${view.alpha};enabled=${view.isEnabled};frame=${view.left},${view.top},${view.width},${view.height};translation=${view.translationX},${view.translationY}"
|
||||
}
|
||||
|
||||
// Other test IDs include user-controlled entity IDs. Keep only fixed surface names.
|
||||
private val diagnosticTestIds = setOf(
|
||||
"message-input-root", "composer-fullscreen", "composer-viewport", "composer-viewport-content",
|
||||
"composer-dock-content", "composer-track-scroll", "agent-list-backdrop", "file-explorer-backdrop",
|
||||
"workspace-create-submit", "new-workspace-launch-submit", "compact-provider-list",
|
||||
)
|
||||
|
||||
// Expo's developer menu adds a full-window Compose host above the React root. It passes ordinary
|
||||
// touches through, but RN's helper cannot traverse that host. Start at the actual React surface;
|
||||
// native modal windows expose a separate RootView and receive their own observation.
|
||||
private fun reactRootAt(view: View, x: Int, y: Int): ViewGroup? {
|
||||
if (view.visibility != View.VISIBLE || view.alpha == 0f) return null
|
||||
// getGlobalVisibleRect is relative to the window root, including for offset/freeform windows.
|
||||
val bounds = Rect()
|
||||
if (!view.getGlobalVisibleRect(bounds) || !bounds.contains(x, y)) return null
|
||||
if (view is RootView && view is ViewGroup) return view
|
||||
if (view is ViewGroup) {
|
||||
for (index in view.childCount - 1 downTo 0) {
|
||||
reactRootAt(view.getChildAt(index), x, y)?.let { return it }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
+54
-1
@@ -1,10 +1,12 @@
|
||||
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;
|
||||
@@ -12,7 +14,7 @@ import com.facebook.react.views.scroll.ReactScrollView;
|
||||
import com.facebook.react.views.scroll.ReactScrollViewHelper;
|
||||
|
||||
/**
|
||||
* React Native's vertical scroll view with two corrections. Java, because the content-position
|
||||
* React Native's vertical scroll view with five corrections. Java, because the content-position
|
||||
* config type is internal to React Native's Kotlin module.
|
||||
*/
|
||||
final class PaseoScrollView extends ReactScrollView {
|
||||
@@ -27,6 +29,7 @@ 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);
|
||||
@@ -51,6 +54,56 @@ 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) {
|
||||
|
||||
@@ -23,6 +23,12 @@ 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: {
|
||||
|
||||
@@ -394,6 +394,56 @@ describe("bottom anchor controller driver", () => {
|
||||
expect(harness.scrollAttempts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("honors a submit made during a gesture when that gesture ends away", () => {
|
||||
const harness = createDriverHarness({ isNearBottom: false });
|
||||
harness.driver.beginUserScroll();
|
||||
harness.driver.requestLocalAnchor({ agentId: "agent-1", reason: "message-sent" });
|
||||
harness.scheduler.flushAll();
|
||||
expect(harness.scrollAttempts).toEqual([]);
|
||||
|
||||
harness.driver.endUserScroll({ isAtEnd: false });
|
||||
harness.scheduler.flushAll();
|
||||
|
||||
expect(harness.context.measurementState.offsetY).toBe(
|
||||
harness.context.measurementState.contentHeight -
|
||||
harness.context.measurementState.viewportHeight,
|
||||
);
|
||||
expect(harness.driver.getSnapshot()).toMatchObject({
|
||||
mode: "sticky-bottom",
|
||||
pendingRequest: null,
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["rewind", "jump-to-bottom"] as const)(
|
||||
"lets scrolling away supersede a late %s request",
|
||||
(reason) => {
|
||||
const harness = createDriverHarness({ isNearBottom: false });
|
||||
harness.driver.beginUserScroll();
|
||||
harness.driver.requestLocalAnchor({ agentId: "agent-1", reason });
|
||||
harness.driver.endUserScroll({ isAtEnd: false });
|
||||
harness.scheduler.flushAll();
|
||||
|
||||
expect(harness.scrollAttempts).toEqual([]);
|
||||
expect(harness.driver.getSnapshot()).toMatchObject({
|
||||
mode: "detached",
|
||||
pendingRequest: null,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("lets a new gesture supersede a submit requested during the previous gesture", () => {
|
||||
const harness = createDriverHarness({ isNearBottom: false });
|
||||
harness.driver.beginUserScroll();
|
||||
harness.driver.requestLocalAnchor({ agentId: "agent-1", reason: "message-sent" });
|
||||
harness.driver.endUserScroll({ isAtEnd: false });
|
||||
harness.driver.beginUserScroll();
|
||||
harness.driver.endUserScroll({ isAtEnd: false });
|
||||
harness.scheduler.flushAll();
|
||||
|
||||
expect(harness.scrollAttempts).toEqual([]);
|
||||
expect(harness.driver.getSnapshot()).toMatchObject({ mode: "detached", pendingRequest: null });
|
||||
});
|
||||
|
||||
it("resumes following when a user scroll ends at the end", () => {
|
||||
const harness = createDriverHarness({
|
||||
transportBehavior: {
|
||||
|
||||
@@ -499,11 +499,16 @@ function createBottomAnchorControllerDriver(
|
||||
cancelPendingAttempt();
|
||||
setModeInternal("detached");
|
||||
},
|
||||
// Following resumes only for a gesture that ends at the end. Resuming from short of it would
|
||||
// scroll the rows the finger just let go of, so a release above the end, or with output that
|
||||
// arrived below it during the gesture, stays detached with the pill.
|
||||
// A gesture ending short stays detached unless a newer prompt submission requested the end.
|
||||
// Passive output must not move the rows the finger just let go of.
|
||||
endUserScroll(params) {
|
||||
isUserScrollActive = false;
|
||||
// Submit arrives with the user's action; rewind and tail jumps can arrive after a fetch.
|
||||
// A newer gesture would have detached again, so only a still-sticky submit owns release.
|
||||
if (pendingRequest?.reason === "message-sent" && mode === "sticky-bottom") {
|
||||
evaluate(false, "user_scroll_end");
|
||||
return;
|
||||
}
|
||||
if (params.isAtEnd) {
|
||||
if (mode === "detached") {
|
||||
setModeInternal("sticky-bottom");
|
||||
|
||||
@@ -4,6 +4,7 @@ import { within } from "@testing-library/dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { i18n as testI18n } from "@/i18n/i18next";
|
||||
import { ToolCallDetailsContent } from "@/components/tool-call-details";
|
||||
import { ExpandableBadge } from "@/components/message";
|
||||
import { page, userEvent } from "vitest/browser";
|
||||
import { PlanCard } from "@/components/plan-card";
|
||||
@@ -202,3 +203,87 @@ describe("tool badge file action", () => {
|
||||
expect(view().queryByText("File contents")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
const longDetail = {
|
||||
type: "unknown" as const,
|
||||
input: { text: "input\n".repeat(80) },
|
||||
output: { text: "output\n".repeat(80) },
|
||||
};
|
||||
|
||||
describe("inline tool detail height", () => {
|
||||
it("caps the complete detail, including input, output and error, to its allowance", () => {
|
||||
act(() =>
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToolCallDetailsContent
|
||||
detail={longDetail}
|
||||
errorText={"error\n".repeat(80)}
|
||||
maxHeight={200}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
expect(container.getBoundingClientRect().height).toBeLessThanOrEqual(200);
|
||||
expect(container.textContent).toContain("output");
|
||||
expect(container.textContent).toContain("error");
|
||||
});
|
||||
});
|
||||
|
||||
const longShellDetail = {
|
||||
type: "shell" as const,
|
||||
command: "echo command\n".repeat(80),
|
||||
output: "output\n".repeat(80),
|
||||
};
|
||||
|
||||
const longEditDetail = {
|
||||
type: "edit" as const,
|
||||
filePath: "example.txt",
|
||||
oldString: "old line\n".repeat(80),
|
||||
newString: "new line\n".repeat(80),
|
||||
};
|
||||
|
||||
describe("capped tool scrolling", () => {
|
||||
it.each([longShellDetail, longEditDetail])(
|
||||
"gives a capped $type detail one vertical scroll owner",
|
||||
(detail) => {
|
||||
act(() =>
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToolCallDetailsContent detail={detail} maxHeight={200} />
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
const verticalScrollers = Array.from(container.querySelectorAll("*")).filter((node) =>
|
||||
["auto", "scroll"].includes(getComputedStyle(node).overflowY),
|
||||
);
|
||||
expect(verticalScrollers).toHaveLength(1);
|
||||
expect(container.getBoundingClientRect().height).toBeLessThanOrEqual(200);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
function renderCopyOutput() {
|
||||
return <button type="button">Copy output</button>;
|
||||
}
|
||||
|
||||
describe("tool detail interaction", () => {
|
||||
it("keeps detail controls in the tab order", async () => {
|
||||
function Badge() {
|
||||
const [expanded, setExpanded] = React.useState(true);
|
||||
const toggle = React.useCallback(() => setExpanded(!expanded), [expanded]);
|
||||
return (
|
||||
<ExpandableBadge
|
||||
label="Probe"
|
||||
isExpanded={expanded}
|
||||
onToggle={toggle}
|
||||
renderDetails={renderCopyOutput}
|
||||
/>
|
||||
);
|
||||
}
|
||||
act(() => root.render(<Badge />));
|
||||
const header = view().getByRole("button", { name: "Probe" });
|
||||
act(() => header.focus());
|
||||
await userEvent.keyboard("{Tab}");
|
||||
expect(document.activeElement).toBe(view().getByRole("button", { name: "Copy output" }));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,8 +49,21 @@ afterEach(() => {
|
||||
host.remove();
|
||||
});
|
||||
|
||||
function mountTimeline(historyMounted: StreamItem[]) {
|
||||
const strategy = createWebStreamStrategy({ isMobileBreakpoint: true });
|
||||
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 });
|
||||
const viewportRef = React.createRef<StreamViewportHandle>();
|
||||
const input: StreamRenderInput = {
|
||||
agentId: "agent",
|
||||
@@ -76,6 +89,7 @@ function mountTimeline(historyMounted: StreamItem[]) {
|
||||
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 } }));
|
||||
@@ -100,8 +114,20 @@ function mountTimeline(historyMounted: StreamItem[]) {
|
||||
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 () => {
|
||||
@@ -113,6 +139,53 @@ function mountTimeline(historyMounted: StreamItem[]) {
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -208,3 +281,32 @@ 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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -457,6 +457,8 @@ 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,
|
||||
@@ -605,6 +607,15 @@ 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;
|
||||
@@ -791,16 +802,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 mouseGesture = mouseScrollGestureRef.current;
|
||||
const hasUpwardInputEvidence =
|
||||
mouseGesture?.kind === "scrollbar" ||
|
||||
(mouseGesture?.kind === "autoscroll" && mouseGesture.hasUpwardEvidence) ||
|
||||
window.performance.now() < upwardInputEvidenceUntilRef.current;
|
||||
const userScrolledUp = scrolledUp && hasUpwardInputEvidence();
|
||||
|
||||
if (!followOutputRef.current && isAtBottom && scrolledDown && !isJumpSettling()) {
|
||||
setFollowOutput(true);
|
||||
} else if (followOutputRef.current && scrolledUp && hasUpwardInputEvidence) {
|
||||
} else if (followOutputRef.current && userScrolledUp) {
|
||||
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;
|
||||
@@ -811,8 +822,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
evaluateHistoryStart();
|
||||
}, [
|
||||
evaluateHistoryStart,
|
||||
hasUpwardInputEvidence,
|
||||
isJumpSettling,
|
||||
readingAnchor,
|
||||
rearmHistoryStartFromUserIntent,
|
||||
stopFollowingOutputFromUserIntent,
|
||||
updateScrollMetrics,
|
||||
]);
|
||||
|
||||
@@ -883,6 +883,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
status={call.status}
|
||||
isLastInSequence={index === group.run.calls.length - 1}
|
||||
defaultExpanded={false}
|
||||
maxDetailHeight={GROUPED_TOOL_CALL_DETAIL_MAX_HEIGHT}
|
||||
standalone={false}
|
||||
onInlineDetailsExpandedChangeByItemId={setInlineDetailsExpanded}
|
||||
/>
|
||||
@@ -1375,6 +1376,7 @@ interface ThoughtSlotProps {
|
||||
isLastInSequence: boolean;
|
||||
defaultExpanded: boolean;
|
||||
standalone?: boolean;
|
||||
maxDetailHeight?: number;
|
||||
}
|
||||
|
||||
// Reasoning text is paced the same way assistant text is; see @/hooks/use-revealed-text.
|
||||
@@ -1386,6 +1388,7 @@ function ThoughtSlot({
|
||||
isLastInSequence,
|
||||
defaultExpanded,
|
||||
standalone,
|
||||
maxDetailHeight,
|
||||
}: ThoughtSlotProps) {
|
||||
const revealedText = useRevealedText(text, status === "ready" ? "complete" : "streaming");
|
||||
return (
|
||||
@@ -1398,6 +1401,7 @@ function ThoughtSlot({
|
||||
isLastInSequence={isLastInSequence}
|
||||
defaultExpanded={defaultExpanded}
|
||||
standalone={standalone}
|
||||
maxDetailHeight={maxDetailHeight}
|
||||
forceInline={defaultExpanded}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -931,10 +931,11 @@ function RootStack() {
|
||||
<Stack.Screen name="h/[serverId]" />
|
||||
<Stack.Screen name="settings/hosts/[serverId]/index" />
|
||||
<Stack.Screen name="settings/hosts/[serverId]/[hostSection]" />
|
||||
<Stack.Screen name="settings/hosts/[serverId]/plugins/[pluginId]/index" />
|
||||
<Stack.Screen name="settings/hosts/[serverId]/plugins/[pluginId]/[screenId]" />
|
||||
<Stack.Screen name="settings/hosts/[serverId]/plugin-directory/[owner]/[slug]" />
|
||||
<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,23 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
||||
import SettingsScreen from "@/screens/settings-screen";
|
||||
|
||||
/** A plugin directory listing's page, by its `owner/slug` ID. */
|
||||
export default function PluginListingRoute() {
|
||||
const { serverId, owner, slug } = useLocalSearchParams<{
|
||||
serverId: string;
|
||||
owner: string;
|
||||
slug: string;
|
||||
}>();
|
||||
const view = useMemo(
|
||||
() => ({ kind: "pluginListing" as const, serverId, listingId: `${owner}/${slug}` }),
|
||||
[serverId, owner, slug],
|
||||
);
|
||||
return (
|
||||
<HostRouteBootstrapBoundary>
|
||||
<SettingsScreen view={view} />
|
||||
</HostRouteBootstrapBoundary>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
||||
import SettingsScreen from "@/screens/settings-screen";
|
||||
|
||||
/** An installed plugin's page. A settings tab chosen on it arrives as `screenId`. */
|
||||
export default function PluginPageRoute() {
|
||||
const { serverId, pluginId, screenId } = useLocalSearchParams<{
|
||||
serverId: string;
|
||||
pluginId: string;
|
||||
screenId?: string;
|
||||
}>();
|
||||
const view = useMemo(
|
||||
() => ({ kind: "plugin" as const, serverId, pluginId, screenId }),
|
||||
[serverId, pluginId, screenId],
|
||||
);
|
||||
return (
|
||||
<HostRouteBootstrapBoundary>
|
||||
<SettingsScreen view={view} />
|
||||
</HostRouteBootstrapBoundary>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export type { ArchivedWorkspace, ArchivedWorkspaceAgent } from "./internal/group";
|
||||
export {
|
||||
useArchivedWorkspaceSearch,
|
||||
type ArchivedWorkspaceSearch,
|
||||
} from "./internal/use-archived-workspace-search";
|
||||
@@ -0,0 +1,128 @@
|
||||
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 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
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());
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
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,6 +39,21 @@ 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;
|
||||
@@ -322,11 +337,12 @@ describe("useFileLink", () => {
|
||||
act(() => {
|
||||
result.current.setWorkspaceRoot("/Users/test/other");
|
||||
});
|
||||
deferred.resolve(resolvedSuggestions([{ path: "docs/dumm.md", kind: "file" }]));
|
||||
await resolveLookupAndDeliver(
|
||||
deferred,
|
||||
resolvedSuggestions([{ path: "docs/dumm.md", kind: "file" }]),
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getDirectorySuggestions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
expect(getDirectorySuggestions).toHaveBeenCalledTimes(1);
|
||||
expect(openedFiles).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
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,62 +2,75 @@ 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,
|
||||
): string | null {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
const activeAttachmentRef = useRef<AttachmentMetadata | null>(null);
|
||||
): AttachmentPreviewUrl {
|
||||
const [resolved, setResolved] = useState<{
|
||||
key: string;
|
||||
preview: AttachmentPreviewUrl;
|
||||
} | null>(null);
|
||||
const attachmentRef = useRef(attachment);
|
||||
attachmentRef.current = attachment;
|
||||
|
||||
const id = attachment?.id;
|
||||
const storageType = attachment?.storageType;
|
||||
const storageKey = attachment?.storageKey;
|
||||
const mimeType = attachment?.mimeType;
|
||||
const key = attachmentKey(attachment);
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
let currentUrl: string | null = null;
|
||||
const current = attachmentRef.current;
|
||||
|
||||
activeAttachmentRef.current = current ?? null;
|
||||
if (!current) {
|
||||
setUrl(null);
|
||||
if (!current || key === null) {
|
||||
return;
|
||||
}
|
||||
let disposed = false;
|
||||
let currentUrl: string | null = null;
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const resolved = await resolveAttachmentPreviewUrl(current);
|
||||
const url = await resolveAttachmentPreviewUrl(current);
|
||||
if (disposed) {
|
||||
await releaseAttachmentPreviewUrl({ attachment: current, url: resolved });
|
||||
await releaseAttachmentPreviewUrl({ attachment: current, url });
|
||||
return;
|
||||
}
|
||||
currentUrl = resolved;
|
||||
setUrl(resolved);
|
||||
currentUrl = url;
|
||||
setResolved({ key, preview: { status: "ready", url } });
|
||||
} catch (error) {
|
||||
console.error("[attachments] Failed to resolve preview URL", {
|
||||
attachmentId: current.id,
|
||||
error,
|
||||
});
|
||||
if (!disposed) {
|
||||
setUrl(null);
|
||||
setResolved({ key, preview: FAILED });
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
const activeAttachment = activeAttachmentRef.current;
|
||||
if (!currentUrl || !activeAttachment) {
|
||||
return;
|
||||
if (currentUrl) {
|
||||
void releaseAttachmentPreviewUrl({ attachment: current, url: currentUrl });
|
||||
}
|
||||
void releaseAttachmentPreviewUrl({
|
||||
attachment: activeAttachment,
|
||||
url: currentUrl,
|
||||
});
|
||||
// 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));
|
||||
};
|
||||
}, [id, storageType, storageKey, mimeType]);
|
||||
}, [key]);
|
||||
|
||||
return url;
|
||||
return resolved !== null && resolved.key === key ? resolved.preview : LOADING;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { memo, useCallback, useMemo, useState } from "react";
|
||||
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
|
||||
import { Text, View } from "react-native";
|
||||
import { ExternalLink, Gift } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
SheetHeaderIconButton,
|
||||
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,12 +28,9 @@ 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;
|
||||
@@ -54,19 +51,12 @@ export function ChangelogSheet({ visible, onClose }: ChangelogSheetProps) {
|
||||
title: t("changelog.title"),
|
||||
leading: sheetLeadingIcon,
|
||||
actions: (
|
||||
<Pressable
|
||||
<SheetHeaderIconButton
|
||||
icon={ExternalLink}
|
||||
label={t("changelog.openWebsite")}
|
||||
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],
|
||||
|
||||
@@ -24,10 +24,12 @@ import {
|
||||
useSyncExternalStore,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Check, ChevronRight, Folder, X } from "lucide-react-native";
|
||||
import { Check, ChevronRight } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { BottomSheetFlatList, type BottomSheetFlatListMethods } from "@gorhom/bottom-sheet";
|
||||
import { useAgentDescriptor, resolveAgentLabel } from "@/agent-presentation";
|
||||
import { resolveAgentLabel } from "@/agent-presentation";
|
||||
import { useArchivedWorkspaceSearch, type ArchivedWorkspace } from "@/archived-workspaces";
|
||||
import { ArchivedBadge } from "@/components/archived-badge";
|
||||
import { StatusIcon } from "@/components/status-icon";
|
||||
import { useWorkspaceStatus } from "@/workspace-status";
|
||||
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
@@ -35,12 +37,14 @@ 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,
|
||||
@@ -48,18 +52,20 @@ import {
|
||||
} from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useAggregatedAgents } from "@/hooks/use-aggregated-agents";
|
||||
import { useAggregatedAgents, type AggregatedAgent } 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 { useHosts } from "@/runtime/host-runtime";
|
||||
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 {
|
||||
useKeyboardShortcutsStore,
|
||||
type CommandCenterScope,
|
||||
} from "@/stores/keyboard-shortcuts-store";
|
||||
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
|
||||
navigateToWorkspace,
|
||||
useActiveWorkspaceSelection,
|
||||
} from "@/stores/navigation-active-workspace-store";
|
||||
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import {
|
||||
clearCommandCenterFocusRestoreElement,
|
||||
@@ -67,8 +73,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,
|
||||
@@ -76,21 +82,23 @@ import {
|
||||
type CommandCenterListMetrics,
|
||||
} from "./list-metrics";
|
||||
import { useCommandCenterContributions } from "./provider";
|
||||
import { filterAndRankWorkspaces } from "./workspace-search";
|
||||
import { createWorkspaceRanker } from "./workspace-search";
|
||||
import {
|
||||
buildContributionSections,
|
||||
filterAndRankBuiltInResults,
|
||||
joinSubtitleParts,
|
||||
PINNED_SECTION_BAND,
|
||||
projectCommandCenterRows,
|
||||
type CommandCenterAgentResult,
|
||||
type CommandCenterFileResult,
|
||||
type CommandCenterListRow,
|
||||
type CommandCenterResult,
|
||||
type CommandCenterResultSection,
|
||||
type CommandCenterSearchFields,
|
||||
type CommandCenterWorkspaceAgent,
|
||||
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";
|
||||
|
||||
@@ -100,23 +108,16 @@ 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();
|
||||
@@ -124,28 +125,73 @@ function createWorkspaceResultAction(serverId: string, workspaceId: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function createAgentResultAction(serverId: string, agentId: string) {
|
||||
return () => {
|
||||
function createAgentResultAction(serverId: string) {
|
||||
return (agentId: string) => {
|
||||
clearCommandCenterFocusRestoreElement();
|
||||
navigateToAgent({ serverId, agentId });
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 useBuiltInRows(open: boolean): {
|
||||
workspaces: CommandCenterWorkspaceResult[];
|
||||
agents: CommandCenterAgentResult[];
|
||||
} {
|
||||
const { t } = useTranslation();
|
||||
const previousRows = useRef(
|
||||
new Map<string, CommandCenterAgentResult | CommandCenterWorkspaceResult>(),
|
||||
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(),
|
||||
);
|
||||
const { agents } = useAggregatedAgents({ demand: open });
|
||||
const { projects } = useProjects({ enabled: open });
|
||||
const showHost = useHosts().length > 1;
|
||||
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.
|
||||
*/
|
||||
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;
|
||||
const iconTargets = useMemo(
|
||||
() =>
|
||||
open
|
||||
@@ -163,24 +209,26 @@ function useBuiltInRows(open: boolean): {
|
||||
);
|
||||
const iconDataByProjectViewKey = useProjectIcons({ projects: iconTargets });
|
||||
|
||||
return useMemo(() => {
|
||||
const active = useMemo(() => {
|
||||
if (!open) {
|
||||
previousRows.current.clear();
|
||||
return { workspaces: [], agents: [] };
|
||||
return [];
|
||||
}
|
||||
// Built-in IDs identify immutable navigation targets. Reuse their callbacks and unchanged
|
||||
// Workspace 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, CommandCenterAgentResult | CommandCenterWorkspaceResult>();
|
||||
const preserve = <T extends CommandCenterAgentResult | CommandCenterWorkspaceResult>(
|
||||
row: T,
|
||||
): T => {
|
||||
const nextRows = new Map<string, CommandCenterWorkspaceResult>();
|
||||
const preserve = (row: CommandCenterWorkspaceResult): CommandCenterWorkspaceResult => {
|
||||
const previous = previousRows.current.get(row.id);
|
||||
if (previous) row.run = previous.run;
|
||||
const stable = previous && equal(previous, row) ? (previous as T) : row;
|
||||
if (previous) {
|
||||
row.run = previous.run;
|
||||
row.openAgent = previous.openAgent;
|
||||
}
|
||||
const stable = previous && equal(previous, row) ? previous : row;
|
||||
nextRows.set(row.id, stable);
|
||||
return stable;
|
||||
};
|
||||
const allWorkspaces: CommandCenterWorkspaceResult[] = [];
|
||||
const agentsByWorkspace = groupWorkspaceAgents(agents);
|
||||
const rows: CommandCenterWorkspaceResult[] = [];
|
||||
for (const project of projects) {
|
||||
const workspaceProject = {
|
||||
viewKey: project.viewKey,
|
||||
@@ -190,10 +238,11 @@ function useBuiltInRows(open: boolean): {
|
||||
for (const host of project.hosts) {
|
||||
for (const workspace of host.workspaces) {
|
||||
if (workspace.archivingAt) continue;
|
||||
allWorkspaces.push(
|
||||
const key = `${host.serverId}:${workspace.id}`;
|
||||
rows.push(
|
||||
preserve({
|
||||
kind: "workspace",
|
||||
id: `workspace:${host.serverId}:${workspace.id}`,
|
||||
id: `workspace:${key}`,
|
||||
title: workspace.title ?? workspace.name,
|
||||
subtitle: joinSubtitleParts([
|
||||
showHost ? host.serverName : null,
|
||||
@@ -205,66 +254,93 @@ function useBuiltInRows(open: boolean): {
|
||||
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),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
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),
|
||||
});
|
||||
});
|
||||
previousRows.current = nextRows;
|
||||
return { workspaces: allWorkspaces, agents: agentRows };
|
||||
}, [agents, iconDataByProjectViewKey, open, projects, showHost, t]);
|
||||
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)
|
||||
: 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,
|
||||
},
|
||||
];
|
||||
});
|
||||
}, [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,
|
||||
};
|
||||
}
|
||||
|
||||
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]);
|
||||
/**
|
||||
* 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),
|
||||
);
|
||||
}
|
||||
|
||||
interface CommandCenterState {
|
||||
open: boolean;
|
||||
scope: CommandCenterScope;
|
||||
clearScope(): void;
|
||||
/** The tabs on offer, in the order Tab walks them. */
|
||||
tabs: readonly CommandCenterTab[];
|
||||
tab: CommandCenterTab;
|
||||
selectTab(tab: CommandCenterTab): void;
|
||||
query: string;
|
||||
setQuery(query: string): void;
|
||||
activeId: string | null;
|
||||
@@ -275,7 +351,7 @@ interface CommandCenterState {
|
||||
fileSearchError: string | null;
|
||||
close(): void;
|
||||
select(result: CommandCenterResult): void;
|
||||
key(key: string): boolean;
|
||||
key(event: { key: string; shiftKey?: boolean }): boolean;
|
||||
}
|
||||
|
||||
function useCommandCenterState(
|
||||
@@ -285,62 +361,95 @@ function useCommandCenterState(
|
||||
const keyboardActionDispatcher = useKeyboardActionDispatcher();
|
||||
const { t } = useTranslation();
|
||||
const open = useKeyboardShortcutsStore((state) => state.commandCenterOpen);
|
||||
const scope = useKeyboardShortcutsStore((state) => state.commandCenterScope);
|
||||
const requestedTab = useKeyboardShortcutsStore((state) => state.commandCenterTab);
|
||||
const setOpen = useKeyboardShortcutsStore((state) => state.setCommandCenterOpen);
|
||||
const setScope = useKeyboardShortcutsStore((state) => state.setCommandCenterScope);
|
||||
const setTab = useKeyboardShortcutsStore((state) => state.setCommandCenterTab);
|
||||
const snapshot = useCommandCenterContributions();
|
||||
const inputRef = useRef<EditingTextInputHandle>(null);
|
||||
const previousOpenRef = useRef(open);
|
||||
const { query, activeId } = useSyncExternalStore(interaction.subscribe, interaction.getSnapshot);
|
||||
const builtInSections = useBuiltInSections(open, query);
|
||||
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 {
|
||||
entries: fileSearchEntries,
|
||||
loading: fileSearchLoading,
|
||||
error: fileSearchError,
|
||||
openFile,
|
||||
} = useWorkspaceFileSearch({
|
||||
enabled: open && (scope === "files" || Boolean(query.trim())),
|
||||
enabled:
|
||||
open &&
|
||||
tabs.includes("files") &&
|
||||
(tab === "files" || (tab === "all" && Boolean(query.trim()))),
|
||||
query,
|
||||
});
|
||||
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 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 projection = useMemo(
|
||||
() =>
|
||||
projectCommandCenterRows(
|
||||
scope === "files"
|
||||
? fileSections
|
||||
: [...contributionSections, ...fileSections, ...builtInSections],
|
||||
listMetrics,
|
||||
),
|
||||
[builtInSections, contributionSections, fileSections, listMetrics, scope],
|
||||
() => projectCommandCenterRows(sections, listMetrics),
|
||||
[listMetrics, sections],
|
||||
);
|
||||
const loading =
|
||||
fileSearchLoading || (listsWorkspaces && (archivedSearch.pending || workspaceRows.loading));
|
||||
useLayoutEffect(() => {
|
||||
interaction.update({ open, scope, query, projection, loading: fileSearchLoading });
|
||||
}, [interaction, open, scope, query, projection, fileSearchLoading]);
|
||||
interaction.update({ open, tab, query, projection, loading });
|
||||
}, [interaction, open, tab, query, projection, loading]);
|
||||
|
||||
const close = useCallback(() => setOpen(false), [setOpen]);
|
||||
const select = useCallback(
|
||||
@@ -350,16 +459,29 @@ 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(
|
||||
(pressed: string): boolean => {
|
||||
(event: { key: string; shiftKey?: boolean }): boolean => {
|
||||
if (!open) return false;
|
||||
const pressed = event.key;
|
||||
const results = projection.selectableResults;
|
||||
if (pressed === "Escape") {
|
||||
close();
|
||||
return true;
|
||||
}
|
||||
if (pressed === "Backspace" && !query.trim() && scope) {
|
||||
setScope(null);
|
||||
if (pressed === "Tab") {
|
||||
setTab(rotateCommandCenterTab(tab, event.shiftKey ? "previous" : "next", tabs));
|
||||
return true;
|
||||
}
|
||||
if (pressed === "Backspace" && !query.trim() && tab !== "all") {
|
||||
setTab("all");
|
||||
return true;
|
||||
}
|
||||
if (pressed === "Enter") {
|
||||
@@ -377,9 +499,10 @@ function useCommandCenterState(
|
||||
projection.selectableResults,
|
||||
query,
|
||||
activeId,
|
||||
scope,
|
||||
tab,
|
||||
tabs,
|
||||
select,
|
||||
setScope,
|
||||
setTab,
|
||||
interaction,
|
||||
],
|
||||
);
|
||||
@@ -405,8 +528,9 @@ function useCommandCenterState(
|
||||
|
||||
return {
|
||||
open,
|
||||
scope,
|
||||
clearScope: () => setScope(null),
|
||||
tabs,
|
||||
tab,
|
||||
selectTab,
|
||||
query,
|
||||
setQuery: interaction.setQuery,
|
||||
activeId,
|
||||
@@ -536,55 +660,38 @@ function SubtitleWithTimestamp({
|
||||
);
|
||||
}
|
||||
|
||||
const providerIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
|
||||
function AgentResultContent({
|
||||
result,
|
||||
/**
|
||||
* 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,
|
||||
query,
|
||||
backdrop,
|
||||
}: {
|
||||
result: CommandCenterAgentResult;
|
||||
agent: CommandCenterWorkspaceAgent;
|
||||
serverId: string;
|
||||
query: string;
|
||||
backdrop: SurfaceBackdrop;
|
||||
}) {
|
||||
const agent = result.agent;
|
||||
const descriptor = useAgentDescriptor(
|
||||
{ kind: "agent", agentId: agent.id },
|
||||
{ serverId: agent.serverId },
|
||||
);
|
||||
const Icon = useMemo(
|
||||
() => withUnistyles(descriptor.icon, providerIconMapping),
|
||||
[descriptor.icon],
|
||||
);
|
||||
const ProviderIcon = useProviderIcon(agent.provider, serverId);
|
||||
const Icon = useMemo(() => withUnistyles(ProviderIcon, providerIconMapping), [ProviderIcon]);
|
||||
return (
|
||||
<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 style={styles.agentLine} testID="command-center-workspace-agent">
|
||||
<View style={styles.agentLineIcon}>
|
||||
<Icon size={12} />
|
||||
</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,
|
||||
@@ -595,24 +702,27 @@ function WorkspaceResultIcon({
|
||||
const statusBucket = useWorkspaceStatus(result.serverId, result.workspaceId);
|
||||
return (
|
||||
<StatusIcon statusBucket={statusBucket} size={16} backdrop={backdrop}>
|
||||
<View accessibilityElementsHidden importantForAccessibility="no-hide-descendants" aria-hidden>
|
||||
<WorkspaceProjectIcon project={result.project} />
|
||||
</View>
|
||||
<DecorativeProjectIcon project={result.project} />
|
||||
</StatusIcon>
|
||||
);
|
||||
}
|
||||
|
||||
/** The same project icon the sidebar's workspace rows lead with: its image, or a lettered square. */
|
||||
function WorkspaceProjectIcon({ project }: { project: CommandCenterWorkspaceResult["project"] }) {
|
||||
/**
|
||||
* 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"] }) {
|
||||
const initial = projectIconPlaceholderLabelFromDisplayName(project.name).charAt(0).toUpperCase();
|
||||
return (
|
||||
<ProjectIconView
|
||||
iconDataUri={project.iconDataUri}
|
||||
initial={initial}
|
||||
projectViewKey={project.viewKey}
|
||||
size={16}
|
||||
textStyle={styles.projectIconFallbackText}
|
||||
/>
|
||||
<View accessibilityElementsHidden importantForAccessibility="no-hide-descendants" aria-hidden>
|
||||
<ProjectIconView
|
||||
iconDataUri={project.iconDataUri}
|
||||
initial={initial}
|
||||
projectViewKey={project.viewKey}
|
||||
size={16}
|
||||
textStyle={styles.projectIconFallbackText}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -650,17 +760,18 @@ 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}>
|
||||
<WorkspaceResultIcon result={result} backdrop={backdrop} />
|
||||
{/* An archived workspace runs nothing, so it has no status to show. */}
|
||||
{result.archived ? (
|
||||
<DecorativeProjectIcon project={result.project} />
|
||||
) : (
|
||||
<WorkspaceResultIcon result={result} backdrop={backdrop} />
|
||||
)}
|
||||
</View>
|
||||
<View style={styles.textContent}>
|
||||
<QueryHighlightedText
|
||||
@@ -675,8 +786,16 @@ 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>
|
||||
);
|
||||
}
|
||||
@@ -761,9 +880,24 @@ function SectionRow({ row }: { row: Extract<CommandCenterListRow, { kind: "secti
|
||||
}
|
||||
|
||||
// Escape arrives without asking; it is registered for `agent.interrupt` anyway.
|
||||
// Backspace stays off deliberately — the palette pops its scope with it on web,
|
||||
// Backspace stays off deliberately — on web it returns a tab to All when the field is empty,
|
||||
// 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();
|
||||
@@ -875,22 +1009,42 @@ export function CommandCenter() {
|
||||
: {}),
|
||||
scrollEventThrottle: 16,
|
||||
};
|
||||
const submit = useCallback(() => state.key("Enter"), [state]);
|
||||
const submit = useCallback(() => state.key({ key: "Enter" }), [state]);
|
||||
const handleOverlayKeyDown = useCallback(
|
||||
(event: KeyboardInputEvent) => {
|
||||
if (!state.key(event.key)) return false;
|
||||
if (!state.key(event)) return false;
|
||||
event.preventDefault();
|
||||
return true;
|
||||
},
|
||||
[state],
|
||||
);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
|
||||
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown", "Tab"],
|
||||
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
|
||||
@@ -910,32 +1064,28 @@ export function CommandCenter() {
|
||||
accessible={false}
|
||||
>
|
||||
<OverlayLayerProvider layer={modalLayer}>
|
||||
<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 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>
|
||||
<View style={styles.tabBar}>{tabs}</View>
|
||||
{fileSearchError}
|
||||
<BottomSheetFlatList ref={bottomSheetListRef} {...commonListProps} />
|
||||
</OverlayLayerProvider>
|
||||
@@ -949,30 +1099,26 @@ 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, 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 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>
|
||||
<View style={styles.tabBar}>{tabs}</View>
|
||||
{fileSearchError}
|
||||
<FlatList ref={listRef} {...commonListProps} />
|
||||
</View>
|
||||
@@ -998,25 +1144,6 @@ 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,
|
||||
@@ -1043,11 +1170,12 @@ const styles = StyleSheet.create((theme) => ({
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.border,
|
||||
},
|
||||
bottomSheetHeader: {
|
||||
// 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: {
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[3],
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.border,
|
||||
paddingTop: COMMAND_CENTER_SECTION_GAP,
|
||||
},
|
||||
input: {
|
||||
fontSize: theme.fontSize.base,
|
||||
@@ -1058,25 +1186,6 @@ 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" },
|
||||
@@ -1129,6 +1238,14 @@ 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 { CommandCenterScope } from "@/stores/keyboard-shortcuts-store";
|
||||
import type { CommandCenterTab } from "./tabs";
|
||||
|
||||
function results(ids = ["a", "b", "c", "d"]) {
|
||||
return projectCommandCenterRows(
|
||||
@@ -21,17 +21,17 @@ function results(ids = ["a", "b", "c", "d"]) {
|
||||
})),
|
||||
},
|
||||
],
|
||||
{ singleLineRow: 40, twoLineRow: 60, sectionTitle: 20, sectionDivider: 10 },
|
||||
{ singleLineRow: 40, twoLineRow: 60, threeLineRow: 80, sectionTitle: 20, sectionDivider: 10 },
|
||||
);
|
||||
}
|
||||
|
||||
function setup(options: { scope?: CommandCenterScope; measured?: boolean } = {}) {
|
||||
function setup(options: { tab?: CommandCenterTab; 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,
|
||||
scope: options.scope ?? null,
|
||||
tab: options.tab ?? "all",
|
||||
query: model.getSnapshot().query,
|
||||
projection: results(ids),
|
||||
loading,
|
||||
@@ -53,6 +53,45 @@ 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);
|
||||
@@ -120,7 +159,7 @@ describe("Command Center interaction", () => {
|
||||
});
|
||||
|
||||
it("waits for scoped search results instead of revealing the previous query's rows", () => {
|
||||
const { model, offsets, publish } = setup({ scope: "files" });
|
||||
const { model, offsets, publish } = setup({ tab: "files" });
|
||||
model.scrolled(100);
|
||||
model.setQuery("new");
|
||||
publish(["a", "b"], true);
|
||||
@@ -132,7 +171,7 @@ describe("Command Center interaction", () => {
|
||||
});
|
||||
|
||||
it("manual interaction cancels a reveal awaiting search results", () => {
|
||||
const { model, offsets, publish } = setup({ scope: "files" });
|
||||
const { model, offsets, publish } = setup({ tab: "files" });
|
||||
model.setQuery("new");
|
||||
publish([], true);
|
||||
model.beginManualScroll();
|
||||
@@ -153,13 +192,29 @@ describe("Command Center interaction", () => {
|
||||
expect(offsets).toEqual([]);
|
||||
});
|
||||
|
||||
it("scope changes reset selection and request a reveal", () => {
|
||||
it("tab changes select the first result and return the list to the top", () => {
|
||||
const { model, offsets } = setup();
|
||||
model.move("next");
|
||||
model.move("next");
|
||||
model.move("next");
|
||||
model.scrolled(100);
|
||||
model.update({ open: true, scope: "files", query: "", projection: results(), loading: false });
|
||||
model.update({ open: true, tab: "files", query: "", projection: results(), loading: false });
|
||||
expect(model.getSnapshot().activeId).toBe("a");
|
||||
expect(offsets).toEqual([20, 20]);
|
||||
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" });
|
||||
});
|
||||
|
||||
it("close discards the old query, metrics, and deferred reveal", () => {
|
||||
@@ -167,7 +222,7 @@ describe("Command Center interaction", () => {
|
||||
model.setQuery("old");
|
||||
publish();
|
||||
model.move("previous");
|
||||
model.update({ open: false, scope: null, query: "old", projection: results(), loading: false });
|
||||
model.update({ open: false, tab: "all", query: "old", projection: results(), loading: false });
|
||||
model.layout(80);
|
||||
expect(model.getSnapshot()).toEqual({ query: "", activeId: null });
|
||||
expect(offsets).toEqual([]);
|
||||
|
||||
@@ -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,21 +12,28 @@ interface Snapshot {
|
||||
|
||||
interface ResultsInput {
|
||||
open: boolean;
|
||||
scope: CommandCenterScope;
|
||||
tab: CommandCenterTab;
|
||||
query: string;
|
||||
projection: CommandCenterListProjection;
|
||||
/** A source of this query's and tab's results is still loading. */
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
/** Selection persists; permission to move the viewport lasts for one user command. */
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function createCommandCenterInteraction(scrollToOffset: (offset: number) => void) {
|
||||
let snapshot: Snapshot = { query: "", activeId: null };
|
||||
const listeners = new Set<() => void>();
|
||||
let open = false;
|
||||
let scope: CommandCenterScope = null;
|
||||
let tab: CommandCenterTab = "all";
|
||||
let projection: CommandCenterListProjection | null = null;
|
||||
let loading = false;
|
||||
let revealPending = false;
|
||||
let followingFirst = true;
|
||||
let offset = 0;
|
||||
let visibleLength = 0;
|
||||
|
||||
@@ -38,8 +45,8 @@ export function createCommandCenterInteraction(scrollToOffset: (offset: number)
|
||||
|
||||
function reveal() {
|
||||
if (!open || !revealPending || !projection || visibleLength <= 0) return;
|
||||
// Scoped file search keeps its previous entries while the next query is loading.
|
||||
if (scope === "files" && loading) return;
|
||||
// The Files tab keeps its previous entries while the next query is loading.
|
||||
if (tab === "files" && loading) return;
|
||||
if (!snapshot.activeId) {
|
||||
if (!loading) revealPending = false;
|
||||
return;
|
||||
@@ -67,9 +74,10 @@ export function createCommandCenterInteraction(scrollToOffset: (offset: number)
|
||||
};
|
||||
},
|
||||
update(input: ResultsInput) {
|
||||
const resetSelection = input.open && (!open || scope !== input.scope);
|
||||
const tabChanged = open && input.open && tab !== input.tab;
|
||||
const resetSelection = input.open && (!open || tabChanged);
|
||||
open = input.open;
|
||||
scope = input.scope;
|
||||
tab = input.tab;
|
||||
if (!open) {
|
||||
projection = null;
|
||||
revealPending = false;
|
||||
@@ -80,33 +88,44 @@ 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 (scope !== "files" || !loading) {
|
||||
if (tab !== "files" || !loading) {
|
||||
publish({
|
||||
...snapshot,
|
||||
activeId: preserveActiveResultId(snapshot.activeId, projection.selectableResults),
|
||||
activeId: followingFirst
|
||||
? (projection.selectableResults[0]?.id ?? null)
|
||||
: 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 ||
|
||||
(scope === "files" && loading) ||
|
||||
(tab === "files" && loading) ||
|
||||
projection.selectableResults.length === 0
|
||||
)
|
||||
return false;
|
||||
followingFirst = false;
|
||||
publish({
|
||||
...snapshot,
|
||||
activeId: moveActiveResultId(snapshot.activeId, projection.selectableResults, direction),
|
||||
|
||||
@@ -16,6 +16,8 @@ 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;
|
||||
|
||||
@@ -26,6 +28,8 @@ 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. */
|
||||
@@ -37,6 +41,7 @@ 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,
|
||||
|
||||
@@ -3,7 +3,6 @@ import type { CommandCenterContribution } from "./contributions";
|
||||
import { COMMAND_CENTER_LIST_METRICS } from "./list-metrics";
|
||||
import {
|
||||
buildContributionSections,
|
||||
filterAndRankBuiltInResults,
|
||||
joinSubtitleParts,
|
||||
moveActiveResultId,
|
||||
PINNED_SECTION_BAND,
|
||||
@@ -11,6 +10,7 @@ import {
|
||||
projectCommandCenterRows,
|
||||
type CommandCenterWorkspaceResult,
|
||||
} from "./results";
|
||||
import { createWorkspaceRanker } from "./workspace-search";
|
||||
|
||||
function contribution(input: {
|
||||
id: string;
|
||||
@@ -118,7 +118,12 @@ function workspace(
|
||||
project: { viewKey: "project", name: "project", iconDataUri: null },
|
||||
changeRequestNumber: null,
|
||||
activityAt,
|
||||
agents: [],
|
||||
matchedAgent: null,
|
||||
archived: false,
|
||||
background: false,
|
||||
run: () => undefined,
|
||||
openAgent: () => undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -184,6 +189,40 @@ 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");
|
||||
@@ -486,25 +525,9 @@ describe("Command Center query tokenization", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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",
|
||||
]);
|
||||
});
|
||||
describe("workspace ranking", () => {
|
||||
const rank = (rows: readonly CommandCenterWorkspaceResult[], query: string) =>
|
||||
createWorkspaceRanker()(rows, query).map((row) => row.id);
|
||||
|
||||
it("puts the best match first even when it sorts last alphabetically", () => {
|
||||
const rows = [
|
||||
@@ -514,22 +537,7 @@ describe("filterAndRankBuiltInResults", () => {
|
||||
];
|
||||
|
||||
// Alphabetically this is Alpha, Label, Zebra. "lab des" only matches Label as Design.
|
||||
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",
|
||||
]);
|
||||
expect(rank(rows, "lab des")).toEqual(["c"]);
|
||||
});
|
||||
|
||||
it("orders rows in the same match tier by recency, not by where the word sits", () => {
|
||||
@@ -539,10 +547,7 @@ describe("filterAndRankBuiltInResults", () => {
|
||||
workspace("newer", "design the cli interface to expose usage data", "host", minutesAgo(5)),
|
||||
];
|
||||
|
||||
expect(filterAndRankBuiltInResults(rows, "usage", visibleOnly).map((row) => row.id)).toEqual([
|
||||
"newer",
|
||||
"older",
|
||||
]);
|
||||
expect(rank(rows, "usage")).toEqual(["newer", "older"]);
|
||||
});
|
||||
|
||||
it("keeps a better match tier above a more recent weaker match", () => {
|
||||
@@ -551,16 +556,13 @@ describe("filterAndRankBuiltInResults", () => {
|
||||
workspace("whole-word", "Usage hover card", "host", minutesAgo(600)),
|
||||
];
|
||||
|
||||
expect(filterAndRankBuiltInResults(rows, "usage", visibleOnly).map((row) => row.id)).toEqual([
|
||||
"whole-word",
|
||||
"subsequence",
|
||||
]);
|
||||
expect(rank(rows, "usage")).toEqual(["whole-word", "subsequence"]);
|
||||
});
|
||||
|
||||
it("drops a row when one token matches nothing", () => {
|
||||
const rows = [workspace("a", "Label as Design")];
|
||||
|
||||
expect(filterAndRankBuiltInResults(rows, "lab zzz", visibleOnly)).toEqual([]);
|
||||
expect(rank(rows, "lab zzz")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
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. */
|
||||
@@ -50,6 +53,13 @@ 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;
|
||||
@@ -60,18 +70,19 @@ 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;
|
||||
}
|
||||
|
||||
export interface CommandCenterAgentResult {
|
||||
kind: "agent";
|
||||
id: string;
|
||||
agent: AggregatedAgent;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
activityAt: Date | null;
|
||||
run(): void;
|
||||
/** Opens the workspace on this agent's tab. */
|
||||
openAgent(agentId: string): void;
|
||||
}
|
||||
|
||||
export interface CommandCenterFileResult {
|
||||
@@ -94,13 +105,12 @@ export interface CommandCenterContributionResult {
|
||||
|
||||
export type CommandCenterResult =
|
||||
| CommandCenterWorkspaceResult
|
||||
| CommandCenterAgentResult
|
||||
| CommandCenterFileResult
|
||||
| CommandCenterContributionResult;
|
||||
|
||||
export interface CommandCenterResultSection {
|
||||
id: string;
|
||||
/** CONTRIBUTION_SECTION_BAND or PINNED_SECTION_BAND. Compared before anything else. */
|
||||
/** LEADING, CONTRIBUTION or PINNED_SECTION_BAND. Compared before anything else. */
|
||||
band: number;
|
||||
rank: number;
|
||||
title?: string;
|
||||
@@ -162,6 +172,14 @@ 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(" · ");
|
||||
@@ -181,12 +199,18 @@ function contributionSearchFields(
|
||||
return { visible, hidden: contribution.keywords };
|
||||
}
|
||||
|
||||
/** 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;
|
||||
/** 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;
|
||||
const presentation = result.contribution.presentation;
|
||||
return presentation.kind === "action" && Boolean(presentation.subtitle);
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -211,10 +235,7 @@ function resultScore(result: CommandCenterResult): CommandCenterScore | undefine
|
||||
return result.kind === "contribution" ? result.score : undefined;
|
||||
}
|
||||
|
||||
/** 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. */
|
||||
/** A built-in row that orders by how recently it saw activity. */
|
||||
export interface CommandCenterRecentRow {
|
||||
activityAt: Date | null;
|
||||
}
|
||||
@@ -235,44 +256,20 @@ export function compareBuiltInScores(left: CommandCenterScore, right: CommandCen
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
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) continue;
|
||||
if (contribution.visibility === "query" && !hasQuery && !options.includeQueryOnly) continue;
|
||||
let score: CommandCenterScore | undefined;
|
||||
if (hasQuery) {
|
||||
// The score is the filter: null means no token found a home, so the row is out.
|
||||
@@ -351,7 +348,7 @@ export function projectCommandCenterRows(
|
||||
offset += sectionHeight;
|
||||
}
|
||||
for (const result of section.results) {
|
||||
const height = hasSubtitleLine(result) ? metrics.twoLineRow : metrics.singleLineRow;
|
||||
const height = resultHeight(result, metrics);
|
||||
offsets.push(offset);
|
||||
rowIndexByResultId.set(result.id, rows.length);
|
||||
rows.push({ kind: "result", key: result.id, result, height });
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
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",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user