Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Unify desktop UI with native-style controls and keyboard workflows (#484)

Dee50ef07cb44a6
diff --git a/desktop/AGENTS.md b/desktop/AGENTS.md
index 370493339..6d9bd3a6a 100644
--- a/desktop/AGENTS.md
+++ b/desktop/AGENTS.md
@@ -1,11 +1,17 @@
# Desktop development
-Use [CLAUDE.md](CLAUDE.md) for desktop architecture, build commands, and testing
-conventions.
-
-Before adding or changing workspace chrome, welcome controls, dialogs, pickers,
-forms, or previews, follow the [terminal workspace design system](design/terminal-workspace.md).
-For dialogs in particular,
-read and follow the [terminal dialog design system](design/terminal-dialogs.md).
-Its core rule is **fixed cells, plain text, one-line selection**. It supersedes
-older visual handoff notes for these surfaces.
+Use [CLAUDE.md](CLAUDE.md) for architecture, build commands, and testing.
+
+For all UI outside terminal panes, follow the
+[desktop design system](design/desktop-design-system.md). The user's current
+Mac-friendly direction supersedes earlier BIOS, fixed-cell, bracket-button,
+and all-monospace presentation rules.
+
+Keep terminal content and terminal interaction intact. Pane boundaries are
+covered by [terminal-workspace.md](design/terminal-workspace.md); shared dialog
+behavior and data ownership by [terminal-dialogs.md](design/terminal-dialogs.md)
+and [new-harness-entry-rules.md](design/new-harness-entry-rules.md).
+
+The full visual migration is tracked in
+[desktop-ui-migration.md](design/desktop-ui-migration.md). Preserve core UX,
+controller reuse, keyboard/IME behavior, drafts, pending receipts, and scope.
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 09603d051..1cb3d78d4 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -244,9 +244,10 @@ from `node_status` pushes — distinct from our own socket status, pending offli
### Command dock
-For workspace presentation, follow the [terminal workspace design system](design/terminal-workspace.md).
-For dialog presentation, follow the [terminal dialog design system](design/terminal-dialogs.md):
-fixed cells, plain text, one-line selection. Cmd-N and Cmd-O are the reference implementations.
+For app UI outside terminal panes, follow the [desktop design system](design/desktop-design-system.md).
+The terminal-only presentation rules are retired for desktop forms, pickers, and menus.
+Preserve [workspace boundaries](design/terminal-workspace.md) and
+[dialog behavior](design/terminal-dialogs.md). Cmd-N and New Tab share their composer.
`SwarmSearchController` owns search and selection; `SwarmSearchResults` keeps a bounded cache of
visible/recent row controls. Query-dependent match text listens separately, so typing does not
@@ -298,8 +299,13 @@ its headless debug timings do not establish native display or network latency.
`grid.AppTheme.brightness`, which `_GridTokenScope` in `main.dart` sets from `Theme.of(context)`.
Chrome widgets call `grid.AppTheme.watch(context)` at the top of `build` so `const` subtrees still
repaint on a theme flip.
-- The [workspace status bar](design/workspace-status-bar.md) places compact numbered tabs and global actions at the top,
- with focused machine/repo/branch/PR at the bottom left and the model at the bottom right. Automatic names use the strongest shared harness type,
+- The [workspace status bar](design/workspace-status-bar.md) places system-font tabs and global actions at the top,
+ with subscription usage remaining at the bottom left and focused machine/repo/branch/PR at the bottom right.
+ Tabs center their name/status group without permanent number prefixes; Command replaces
+ the status with the resolved shortcut beside the name. Tab and pane close marks are small
+ and quiet, with larger click targets. Each pane places its model control before its
+ always-visible close icon. Usage has no dot separators and colors only low/exhausted
+ percentages. Automatic names use the strongest shared harness type,
project, or machine, preferring traits that distinguish tabs and excluding dependent viewers.
The context follows a viewer's owner and uses the compact project label, never a worktree path
or marker. User-renamed tabs always retain their saved name. Customize Harness → Status
@@ -308,17 +314,13 @@ its headless debug timings do not establish native display or network latency.
- `lib/theme/app_theme.dart` (`AppColors`, `AppTheme.terminalLight/terminalDark`) is a set of
adapters over those tokens. Nothing here is `const` on purpose — freezing a colour is how light mode
silently breaks. Do not add a parallel palette.
-- **Type** is `AppType` (`lib/shared/theme/app_type.dart`): one size scale (display 28, title 20,
- heading 15, label/mono 13, monoLabel 12, caption/monoMeta 11) across two faces. The terminal's
- face leads — headings, labels, buttons, rows, fields, tabs, shortcuts and anything copied are
- mono — and the system sans is kept for prose alone (`body`, `caption`), which is what stops a
- screen reading as a wall of mono. Ordinary UI stays on the `AppType` scale and uses
- `appTextScaleOf` for geometry. The terminal grid, composer, find field, empty tab's welcome
- page, and terminal-workspace dialogs follow the selected terminal size (⌘+/⌘−). Dialogs use
- `terminalContentStyle()` and `terminalCellSizeOf(context)` for the exact font and character grid;
- see [the dialog guide](design/terminal-dialogs.md). Workspace tabs, status text, pane
- titles, and model selectors use `workspaceBarTextStyle()`: fixed 13 pt SF Mono regular
- on macOS, platform monospace elsewhere. Native menus keep the system menu font.
+- **Type** is `AppType` (`lib/shared/theme/app_type.dart`): system sans for app
+ headings, labels, fields, navigation, and prose; explicit mono for code, paths,
+ logs, and identifiers. Ordinary UI is independent of terminal zoom and respects
+ accessibility text scaling. The terminal grid, in-pane composer, and in-pane
+ find keep the selected terminal font and size. Compact pane/status bars retain
+ their established `workspaceBarTextStyle()` and user-selected status themes.
+ Native menus use the system menu font. Do not measure desktop UI in terminal cells.
- `ThemeModeStore` and `TerminalFontStore` are `ValueNotifier` singletons (they must resolve above the
provider scope and before sign-in).
@@ -338,8 +340,10 @@ its headless debug timings do not establish native display or network latency.
- **Agent-account usage is what the native Models menu reads** (`lib/usage/`,
`usage/models_menu_controller.dart`, `SwarmSubscriptionView` in `SwarmTitlebar.swift`): what the
Claude and Codex accounts on this machine — and on the remote machines that answer `usage_read` —
- have spent. Each account shows its `tightest` window, the limit that stops the work first. Opening
- the menu reads the cached snapshot and refreshes at most once a minute; nothing polls on startup.
+ have spent. Each account shows its `tightest` window, the limit that stops the work first.
+ The shared controller reads ahead at startup and every five minutes; opening a menu requests
+ a fresh reading, capped at once per minute. The footer uses these same deduplicated accounts
+ and freshness rules, displaying the remaining percentage rather than the amount spent.
**Remote machines' accounts arrive through `usage_read`** (`AppNotifier.readRemoteUsage`,
`usage/remote_usage.dart`, `usage/usage_accounts.dart`; CLI side `cli/src/lib/accountUsage.ts`).
A remote machine may be signed in to a DIFFERENT subscription, and the only honest way to read
@@ -534,8 +538,9 @@ its headless debug timings do not establish native display or network latency.
`shortcuts/shortcuts_browser.dart` shares searchable, grouped rows between the ⌘/ dialog and
Settings ▸ Keyboard shortcuts. It reads resolved bindings through `keyboardLessons()`, so remaps
appear immediately; clicking a row or pressing Enter opens keyboard practice without dispatching
- that action. Labels and keycaps use the selected terminal font and size. ⇧⌘P opens commands with
- the query `>`; ⌘P opens the unified picker. On Linux these use Ctrl+Shift+P and Ctrl+P. `shortcuts/key_cap.dart` uses the app type scale elsewhere.
+ that action. Labels and keycaps use system UI typography and accessibility text scaling,
+ independent of terminal font and zoom. The practice scratch preview retains terminal typography.
+ ⇧⌘P opens commands with the query `>`; ⌘P opens the unified picker. On Linux these use Ctrl+Shift+P and Ctrl+P.
Other workspace shortcuts are ⌘-based — Ctrl otherwise belongs to the shell/tmux, ⌥ is a
Meta prefix for the pty (⌥⏎ and ⌥⌫ only — `AltAsMetaInputHandler` in
`lib/terminal/terminal_input.dart` turns them into `ESC` + Return and `ESC` + `\x7f`, so the
diff --git a/desktop/assets/octicons/README.md b/desktop/assets/octicons/README.md
index 638e3c33d..b05c2bee4 100644
--- a/desktop/assets/octicons/README.md
+++ b/desktop/assets/octicons/README.md
@@ -1,4 +1,4 @@
-# GitHub PR icons
+# GitHub icons
Original 16px icons from [Primer Octicons](https://github.com/primer/octicons),
retrieved September 28, 2026. Used under the included MIT license.
@@ -7,6 +7,7 @@ retrieved September 28, 2026. Used under the included MIT license.
- `git-merge.svg`: Merged
- `git-pull-request-closed.svg`: Closed
- `git-pull-request-draft.svg`: Draft
+- `mark-github.svg`: GitHub repository chooser (retrieved September 29, 2026)
Source: `https://raw.githubusercontent.com/primer/octicons/main/icons/<name>-16.svg`.
Dart and AppKit load the same vectors and apply the shared state colors.
diff --git a/desktop/assets/octicons/mark-github.svg b/desktop/assets/octicons/mark-github.svg
new file mode 100644
index 000000000..0e55a8ef2
--- /dev/null
+++ b/desktop/assets/octicons/mark-github.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M6.766 11.328c-2.063-.25-3.516-1.734-3.516-3.656 0-.781.281-1.625.75-2.188-.203-.515-.172-1.609.063-2.062.625-.078 1.468.25 1.968.703.594-.187 1.219-.281 1.985-.281.765 0 1.39.094 1.953.265.484-.437 1.344-.765 1.969-.687.218.422.25 1.515.046 2.047.5.593.766 1.39.766 2.203 0 1.922-1.453 3.375-3.547 3.64.531.344.89 1.094.89 1.954v1.625c0 .468.391.734.86.547C13.781 14.359 16 11.53 16 8.03 16 3.61 12.406 0 7.984 0 3.563 0 0 3.61 0 8.031a7.88 7.88 0 0 0 5.172 7.422c.422.156.828-.125.828-.547v-1.25c-.219.094-.5.156-.75.156-1.031 0-1.64-.562-2.078-1.609-.172-.422-.36-.672-.719-.719-.187-.015-.25-.093-.25-.187 0-.188.313-.328.625-.328.453 0 .844.281 1.25.86.313.452.64.655 1.031.655s.641-.14 1-.5c.266-.265.47-.5.657-.656"/></svg>
\ No newline at end of file
diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.md
new file mode 100644
index 000000000..3168f52d8
--- /dev/null
+++ b/desktop/design/desktop-design-system.md
@@ -0,0 +1,389 @@
+# Harness desktop design system
+
+The canonical system for everything around terminal panes. This supersedes
+older BIOS, bracket-button and mixed desktop recipes. The user-approved
+direction is the authority: refine one system, then use it everywhere.
+
+## Character
+
+A calm, precise Mac workspace. Content supplies the personality: an agent's
+real mark, a session name, a useful preview. Surfaces organize; they do not
+compete. System typography, comfortable density, consistent optical alignment,
+quiet neutral controls and a deliberate blue selection are the visual language.
+No ornamental gradients, noisy borders, imitation terminal forms or gratuitous
+animation. Keep the live terminal, terminal font, status glyphs and native tabs.
+
+The Spotlight references guide search hierarchy and recognizable identity.
+They are inspiration, not a claim of Apple authorship or pixel-identical AppKit.
+
+## The design brief
+
+Harness should feel like a precise, welcoming instrument for working with agents.
+The terminal is the working surface. Starting, finding and arranging work should
+feel effortless around it. Opening a picker should lower the amount the person
+has to think about; closing it should return them to exactly where they were.
+
+Our interpretation of Jony Ive's published emphasis on "bringing order to
+complexity" is to design these relationships before their decoration. It is not
+a prediction of what he or his team would make. See the
+[research and comparison record](macos-design-research.md) for primary sources.
+
+Five decisions give this system its character:
+
+1. **One focal point per surface.** The task in Cmd-N, the query and selected
+ result in Cmd-P, the name in Rename. Configuration stays visible but quiet.
+ Only the action that completes the task has a strong filled treatment.
+2. **Depth has a job.** The workspace, one floating task surface, and an anchored
+ child picker are distinct layers. A child menu stays attached to its source;
+ its parent loses active emphasis. Opaque content protects legibility over
+ busy terminals. Decorative glass, refraction and stacks of translucent cards
+ are not part of this implementation.
+3. **Content supplies identity.** Real agent marks and clear names carry color
+ and recognition. System symbols explain actions. Text needs no extra symbol
+ unless the symbol makes the action faster to recognize.
+4. **Proportion is deliberate.** A short form has a short reading line. The
+ space around a heading relates to the fields below it. Nested corners share
+ a rhythm. Controls keep their bounds through hover, focus and press.
+5. **Continuity is part of the finish.** Typing never moves its own field.
+ Search scopes preserve the query. Menus open at the expected edge, dismiss
+ one level at a time and return focus. Drafts survive dismissal. Immediate
+ feedback takes priority over a decorative transition.
+
+The benchmark is the relationship between surfaces, not a collection of good
+looking individual dialogs. Rename and Move Pane have different content but
+must clearly belong to the same application when viewed beside Cmd-N and Cmd-P.
+
+## Bringing order to machines, agents and models
+
+The interface follows the person's task, not the internal service architecture.
+Show each decision where it changes the outcome, and disclose the next level
+from the control that owns it.
+
+| Person's decision | Visible place | Relationship to preserve |
+| --- | --- | --- |
+| What should happen? | Prompt, then the terminal's work | The task remains the focal point |
+| Where is the project? | Project selector; machine inside its search row | A folder belongs to a machine; its path is not globally interchangeable |
+| Which agent or specialized harness? | Agent selector, with its real mark | A specialized harness can run with an agent framework: “Run Blender with” |
+| Which model and effort? | Model control and its options | Available models belong to the selected agent and connection |
+| What may it do? | Visible approvals control | Preserve the explicit setting; never hide a permission change behind styling |
+| How is the work isolated? | Worktree and branch together | Fresh main default, remembered worktree choice, reviewed draft kept intact |
+| Which work am I returning to? | Session name in tabs/search, with machine/project context when useful | Session identity stays stable when its model or activity changes |
+
+The footer describes the focused work. Creation controls describe the next
+launch. Search scopes describe the result set. Do not mix those contexts or repeat
+all machine, framework and model details in every row. Reveal extra context when
+names are ambiguous; full values remain available to accessibility and tooltips.
+
+## Reference decisions
+
+| Reference | What informs this system | Harness decision |
+| --- | --- | --- |
+| Apple Spotlight, including the user's references | Query first; recognizable identities; a clear selected row; secondary details separated from results | Compact scope pills, real agent marks, quiet toolbar, optional preview |
+| Apple design system and Materials guidance | Layout and grouping establish hierarchy; curvature relates to its container; materials separate functional layers | Shared surface anatomy and concentric geometry; legible neutral panels rather than a simulated Liquid Glass effect |
+| Things' task editor | Optional detail is available without competing with the task | A prompt-led composer with calm configuration and one completion action |
+| Raycast's official design/engineering account | Native quality includes placement, focus, opening behavior and responsiveness | Check interaction continuity alongside screenshots; keep the user's requested hand cursor as a deliberate Harness choice |
+
+Capsules are a deliberate part of Harness's requested control language, not a
+claim that every Mac control should be a capsule. Apple retains rounded
+rectangles for dense controls. Here, action buttons and scope/identity selectors
+use capsules; fields, result rows and compact icon targets use related rounded
+rectangles. Consistency means the same role looks and behaves the same everywhere.
+
+## One implementation
+
+`AppType` owns typography. `AppPalette` owns semantic colors. `AppDesktop` and
+`AppControl` own geometry, focus, selection and control dimensions. `AppMenu`
+owns floating surface colors. `buildAppTheme` applies those recipes to standard
+Flutter buttons, fields, menus and dialogs. `DesktopChrome` exposes the same
+values to creation, search and desktop presenters; it is not a second palette.
+
+`DesktopDialogSurface` frames every custom dialog and chooser.
+`DesktopDialogHeader` provides the shared title/dismiss anatomy.
+`DesktopPromptSurface` keeps form actions visible beneath scrolling content.
+`DesktopPill` is the selector/scope variant of the same control family.
+`AppMenuItem` is the ordinary context-menu row. Controllers, keymaps, pending
+receipts, transport state and persistence remain independent of presentation.
+
+Do not solve a local styling problem by inventing another button or palette.
+Use a named role below. If a new role is necessary, define it here and in shared
+tokens before adopting it at call sites.
+
+## Type and language
+
+| Role | System face, size, weight | Use |
+| --- | --- | --- |
+| Display | 28, semibold | Welcome or sign-in title |
+| Page title | 20, semibold | Settings or substantial detail page |
+| Dialog / section heading | 17, semibold, 1.3 line height | Rename Tab, Move Pane |
+| Body | 13–14, regular, 1.45 line height | Explanations and result names |
+| Control | 13, regular or medium, 1.25 line height | Buttons and menu choices |
+| Metadata | 12, regular, 1.35 line height | Context, counts, explanations |
+| Search / task editor | 17 / 15, regular | Cmd-P and Cmd-N |
+
+SF system typography on Apple platforms, system fallbacks elsewhere. Monospace
+is explicit for code, copyable technical identifiers and shortcut hints; it is
+not the default for navigation or session context. Terminal zoom never resizes
+app controls. Platform text scaling does, and controls grow rather than clip.
+Buttons keep at least 6 points of padding above and below the rendered label.
+The fallback workspace tab strip and Harness Store control follow these same
+rules, including platform text scaling; compact terminal/status bars retain
+their separate sizing contract.
+
+Names before context. Buttons state the action: New Harness, Save, Cancel,
+Open Folder, New Folder, GitHub. Use short sentence-case instructions: Enter
+project name, Enter GitHub URL, Run Blender with. Standard named destinations
+retain their names, such as Harness Store and New Tab. Avoid repeated labels,
+internal state names, decorative punctuation and implementation details.
+
+## Color and state
+
+Use semantic light/dark tokens throughout. Floating surfaces share the same
+neutral material (`AppMenu.fill`); fields are one step inset, not another card.
+A hairline rim and soft shadow separate floating content from its background.
+Avoid repeatedly drawing cards inside a dialog.
+
+- Primary text is nearly white or nearly black. Metadata remains readable.
+- Blue filled capsules identify the primary action. Blue rows identify the
+ active keyboard/pointer choice; their labels and secondary text turn white.
+- A stored choice also has a checkmark. Focus and stored selection differ.
+- Ordinary controls use a faint neutral fill and one thin rim. Hover increases
+ the fill. Press increases it again. Focus has a stable 1.5-point blue boundary.
+- Quiet inline controls beneath the creation prompt stay borderless. A subtle
+ neutral fill identifies focus; Increase Contrast may add the focus boundary.
+ Returning from a chooser must not leave a bright outline around the branch.
+- Destructive actions use the shared danger fill or semantic error ink.
+- Unavailable choices explain why and preserve useful previews. Disabled
+ controls do not show a hand cursor. Color is never the only status signal.
+- Increase Contrast strengthens boundaries. Reduce Motion removes optional
+ motion. Live terminal content is never blurred or scaled for decoration.
+
+The terminal's chosen color palette remains independent from UI focus blue.
+All modal veils share one 95% token: black in dark appearance, white in light.
+Cmd-N and Cmd-P must have exactly the same backdrop darkness, including coverage
+of the native footer. Popovers have no independent full-window veil.
+
+## Icons
+
+`AppIcons` owns one monochrome outline vocabulary: the regular (400) Lucide
+family with rounded ends and joins. Use its named constants, never raw Material
+icons, alternate stroke weights or text characters for app actions. A close
+button always uses `AppIcons.close`; plus, search, back, disclosure, folder,
+branch and check retain one silhouette everywhere.
+
+Use 16-point icons beside text, 20 for standalone controls, and 24 for a feature
+illustration. Center the drawing optically inside its role's target; icon-only
+controls retain a 32-point target and a descriptive tooltip/accessibility label.
+Workspace close marks are a quiet exception: 12-point Lucide × at 45% foreground,
+with an optically matched 8-point regular SF Symbol in AppKit, inside the existing
+click target. Hover or keyboard focus restores full ink;
+Increase Contrast strengthens the resting mark. Tabs reveal the mark on hover,
+while pane headers keep it visible. Neither changes geometry on interaction.
+Use the surrounding text's semantic color. Hover changes emphasis or the shared
+control fill, never the symbol, weight or position. Disabled icons stay legible
+without suggesting an action. Agent, provider, service and product logos retain
+their recognizable artwork; welcome recents keep the original color at a small
+size so agent identity remains easy to distinguish.
+
+AppKit-owned menus and toolbar controls use regular monochrome SF Symbols with
+one shared sizing recipe, matching the system menus. Terminal text, user-chosen
+Powerline symbols, activity marks and companion artwork retain their meaning;
+they are content rather than competing app-control styles. Quantitative stars
+use `AppRatingStar`: one rounded outline with a proportional fill. Connection
+dots remain solid at their intended size; color is accompanied by status text.
+
+## Geometry
+
+| Role | Logical points |
+| --- | --- |
+| Spacing scale | 4, 8, 12, 16, 24 |
+| Dialog outer radius | 20 |
+| Popover outer radius | 16 |
+| Field / inset row / pane radius | 10 |
+| Tab upper corner / outward lower shoulder | 10 / 8 |
+| Tab top inset | 6 |
+| Tab close target inset from outer bounds | 8 |
+| Dialog content inset | 24 |
+| Group / control gap | 16 / 8 |
+| Menu inset | 6 |
+| Standard / compact control minimum height | 32 / 28 |
+| Standard field minimum height | 36 |
+| Inline icon / search identity mark | 16 / 28 |
+| Small form / destination chooser width | 460 |
+| Creation composer maximum width | 680 |
+| Search maximum width / height | 1120 / 680 |
+
+Primary and secondary action buttons and scope selectors are capsules. Text
+fields are rounded rectangles. Icon buttons have 32-point targets. Related
+corners are concentric: an inset row is less rounded than its enclosing panel.
+Widths describe content: agent 304, project 400, model 440, machine submenu 264;
+all clamp to the available window. The project search grows with enlarged text
+so its query and machine remain readable together. Never stretch a short list
+to fill a page.
+
+List anatomy is consistent: identity at left, name, optional useful secondary
+context, then a checkmark, shortcut or disclosure at right. Text baselines and
+accessory columns align. Specialized harness names need no marketing second
+line. Machine menus align to the project popover's top edge with an 8-point gap,
+then flip or constrain when the window has insufficient room.
+
+## Surface families
+
+**Task dialogs** — one heading, optional short explanation, fields, and fixed
+trailing actions. Rename, confirmation, linking and sharing use the same type,
+frame, padding and control states. Content scrolls before actions disappear.
+`DesktopPromptScrollBody` shows a quiet, draggable scroll thumb when the body
+overflows, including before the first scroll gesture. Text leaves 12 points of
+clearance for the thumb. Short content has no visible scroll furniture; nested
+editors keep their own input and scrolling behavior.
+
+**Pickers** — the same frame and header, inset result rows and a quiet footer
+with relevant keyboard hints. Move Pane uses a tab icon, destination name,
+harness count and optional number accelerator. Selection uses the same blue
+row treatment as search; no competing outlined selection card.
+
+**History** — use the shared dialog header, search field and result rows.
+The scope label is “This window”: these are the window's visited and closed
+tabs and panes. Search receives initial focus. Tab reaches Close, and Enter on
+Close dismisses the dialog without accepting a result. Results scroll and
+reveal the active row without moving the search field. History keeps its
+existing controller and does not add a preview.
+
+**Cmd-P** — a prominent search field, separate compact scope pills, recognizable
+agent marks and clean results. Harnesses is the default scope. Preserve typed
+words when changing scope. Keep result selection stable through live updates.
+Details remain in the existing optional preview. No second search index or
+management implementation. Toolbar controls are secondary to the query. Keep
+the editor and footer stationary while results update; do not resize the panel
+on every keystroke or make short lists stretch their individual rows. On wide
+windows, results take 44% and the preview 56% of the reading area. The panel
+clamps to the window; narrower layouts retain their existing preview toggle.
+Section headings use their natural text height with 8-point group spacing,
+never a full result-row height. Loading, failed refresh and settled emptiness
+are different states; keep existing results visible while refreshing.
+
+**Cmd-N / New Tab** — one shared form and controller. Agent and project above
+the “Harness anything” prompt; model, approvals and profile below; Worktree and
+branch together.
+The dialog is frameless over its veil. New Tab uses the same width on the page.
+Machine stays inside the repo search row.
+
+**Welcome and New Tab hierarchy** — creation is primary. Show at most six rows
+under “Recent harnesses”, separated from creation controls by 56 points. Use
+small original-color agent marks and one muted neutral ink for names, context,
+heading and timestamps. Use “now” for visits under one minute old. Context
+reuses `StatusLine`, honoring the selected wording, machine/project/branch
+visibility and status font, but omitting ANSI colors and segment backplates.
+It is never a second renderer with a hard-coded dot separator.
+A new user with no history sees the composer
+without an empty recents section; initial project guidance is neutral. Empty
+tabs hide the workspace footer, which returns when there is work to describe.
+Before a creation machine is available, show “Harness anything”, a short next
+step and a natural-width “Choose a machine” action. Keep that action available
+while finding machines. While saved defaults load, show “Preparing your harness…”
+in the same quiet hierarchy, then hand focus to the existing composer. Startup
+must not leave a blank page or imply that a harness has already started.
+
+Fresh forms focus the prompt and use the last explicit agent, project,
+approvals and worktree choices. Fresh branches default to main; reopening a
+draft preserves its selected branch. Enter submits except during composition.
+Escape and outside click dismiss the innermost picker first, then the dialog;
+they preserve its draft. Pending operations retain their existing close guards.
+Opening any form or preview must never start work.
+The GitHub entry starts with only “Enter GitHub URL”; a valid address reveals
+its clone action and an invalid submission reveals inline validation. Do not
+add a duplicate example line or an empty results area beneath an empty field.
+
+**Workspace tabs and pane frames** — tabs use the 13-point system control face,
+independent of the status bar and terminal font. Center the name and its adjacent
+status as one compact group, without permanent number prefixes. Navigation ink
+follows the tab-bar surface, including beside light app content. The default label
+is New Tab. A small right-hand close icon appears on hover, with its 32-point
+target inset 8 points from the outer tab bounds. This puts the cross's center
+16 points inside the curved body edge. Reserve that space before truncating
+the title so hover never crowds the name or status. Holding Command
+temporarily replaces the status with the actual remapped shortcut beside the
+name. An idle tab has no empty status slot; its name centers on its own. Hover
+never moves the name, and Command never changes tab width. Long names truncate
+and retain a full-name tooltip. Selection, dragging, middle-click close and the
+existing keyboard commands keep their meaning.
+
+The selected tab has 10-point upper corners and 8-point outward lower shoulders,
+joining the workspace along its bottom edge. It starts 6 points below the top
+of the strip. Pane frames use the related 10-point radius, with a 9-point clipped
+inner edge beneath their 1-point rim. Only their frame changes: terminal content,
+input, selection and status typography remain the terminal's own. AppKit mirrors
+these shared geometry values; Flutter uses AppDesktop directly.
+
+**Pane header** — the current model is a quiet text control immediately before
+an always-visible close icon at the right edge. Clicking the model focuses that
+pane and opens the same Models picker as Cmd-:. Selection stays bound to that
+harness; a closed or replaced pane cannot receive a stale selection. Long model
+names truncate and retain their full-name tooltip. Keep effort in the terminal,
+and keep the close target clear at narrow widths. Tab-strip close behavior is
+separate and remains hover-revealed.
+
+**Focused workspace footer** — remaining subscription usage at the left,
+with machine, project, branch and PR together at the right following the focused pane. Each
+context field keeps its existing action, including the branch/PR chooser.
+Titles stay quiet when several panes are visible; do not repeat branches in
+pane headers. Do not repeat model or effort in the footer. Context honors Customize Harness's selected
+status face, fields, colors and shell/Powerline treatment. Recent-harness
+context uses that same renderer's monochrome presentation to stay secondary.
+Use compact labels such as “Claude 0% Codex 50%”, separated by whitespace only.
+Provider names stay neutral. Color only the remaining percentage: red at 0%,
+amber above 0% through 20%, neutral above 20% or when unavailable. Use shared
+semantic ink adjusted to remain readable on the selected workspace surface;
+the number always conveys the state independently of color. These percentages are
+remaining, not used. Use the same deduplicated accounts, limiting window and
+freshness rules as Models. Separate subscriptions remain separate; unknown or
+expired values show “—”, never a fabricated zero. Hover explains reset windows
+and account identity; clicking opens Subscriptions without switching a model.
+Companion and sharing controls sit after usage without shifting the context.
+
+**Settings, Store and supporting screens** — the same type, colors and controls
+at page scale. Related settings use grouping and whitespace. Existing artwork,
+terminal previews, native toolbar/footer components and domain-specific visuals
+retain their meaning. Read-only loading/error views use the same hierarchy.
+Pane-resize guidance is app navigation: use the shared popover surface, system
+type and wrapping keyboard hints. It must not look like terminal output.
+
+## Interaction and review
+
+Every clickable element has a hand cursor, every editor a text cursor.
+Settings controls expose purpose, current value and state to accessibility;
+neighboring explanatory text alone is not an accessible label. Do not merge
+multiple actions into a single settings row. Short popovers use their measured
+content height, including enlarged text, before applying the window height cap. Standard
+editing, IME, keymap remaps, focus traversal and focus return remain intact.
+Pending selectors must be unavailable to pointer, keyboard and accessibility
+activation together. A queued selection cannot change an operation's target;
+failure or cancellation restores the original control and permits retry.
+Opening a modal isolates the workspace and native footer in the accessibility
+tree. A late reply cannot restore a dismissed form or act on a different pane.
+
+Review actual system-font renders in both appearances, narrow/short windows,
+160–200% text, long names, empty/loading/error states, changed live data and
+Increase Contrast. Exercise mouse, keyboard, nested dismissal, drafts and
+composition. Use synthetic review data, not real agent launches or permissions.
+Inspect the rebuilt app; widget tests alone do not prove native VoiceOver or
+physical IME behavior. Record evidence and limitations in the migration ledger.
+
+## Standard of finish
+
+This specification establishes a direction, not an award or a quality score.
+The work is ready for visual review only when:
+
+- Cmd-N, Cmd-P, Rename, Move Pane and an ordinary menu are reviewed together,
+ in both appearances, at normal desktop scale. None uses a competing recipe.
+- The first intended action is obvious without reading a paragraph. Secondary
+ settings are discoverable without turning the main surface into a dashboard.
+- Optical alignment, text baselines, icon weight, nested corners and empty space
+ hold up with short, long, missing and changing content.
+- Hover, focus, stored selection, unavailable and error states stay distinct;
+ small text remains readable. Enlarged text receives space instead of clipping.
+- Opening, typing, scope changes, child menus and dismissal feel continuous in
+ the running app. An attractive still image is insufficient evidence.
+
+Remaining defects and unverified platform behavior belong in the review ledger.
+Do not describe the implementation as flawless, Apple's design, or the best Mac
+design system. Let the functioning app and the user's review establish its quality.
diff --git a/desktop/design/desktop-ui-migration.md b/desktop/design/desktop-ui-migration.md
new file mode 100644
index 000000000..9c2fb6631
--- /dev/null
+++ b/desktop/design/desktop-ui-migration.md
@@ -0,0 +1,374 @@
+# Desktop UI migration and review
+
+Objective: a coherent, welcoming Mac-style application around unchanged terminal
+panes. This tracks the complete requested scope, not only the initial composer.
+The [design system](desktop-design-system.md) is normative; historical screenshots
+and tests do not override it. The user authorized PR, merge, and desktop release
+on 2026-09-30; the unmerged checkpoints below describe earlier review stages.
+
+## Surface inventory
+
+| Surface | Current evidence / work remaining |
+| --- | --- |
+| Shared type, controls, fields, menus | System typography, semantic colors, 32-point icon controls, stable focus boundaries, Increase Contrast and platform text scaling implemented; terminal scaling stays independent |
+| Welcome / New Tab | Shared 680-point composer; six muted Recent harnesses with status-format context and “now”; empty welcome omits history; machine discovery and pending defaults have distinct, actionable startup presentations |
+| Cmd-N and child choosers | Purpose icons, approval explanations, visible focus, and coding-agent-first order implemented; shared controller retained |
+| Cmd-P and resource previews | 1120×680 bounded panel, wider preview, natural-height model groups, explicit loading/error/retry states; six scopes rendered in both appearances |
+| Full History | Shared desktop header/search/results with explicit “This window” scope; initial focus, Close activation, composition, result reveal and terminal focus return tested; light/dark and narrow/enlarged renders inspected |
+| Rename and takeover | Desktop prompt anatomy implemented; safety/IME and focus-return tests pass |
+| Stop, delete, restart, fork | Desktop confirmations implemented; long errors scroll independently of fixed actions; synthetic light/dark/narrow renders inspected |
+| Sharing | Access/people/options, comments, observer sidebar, and viewer access/error states use desktop surfaces; existing sharing and authentication rules retained |
+| Add Phone | Desktop QR/device layout implemented; pairing lifecycle tests and light/dark enlarged-text renders pass |
+| Machine recovery/linking | Desktop linking/password layouts implemented; bounded selectable errors, fixed actions, and 32-point reveal controls tested/rendered |
+| Notifications | Desktop popup, two-line rows, glyphs, and empty/error states implemented; unchanged event rules tested; live empty popup inspected |
+| Branches / pull requests | Desktop lists and shared modal veil implemented; colored icons, readable status words, honest load failures, Page Up/Down tested and rendered |
+| Settings / customization | Desktop status customization, natural-height controls, error contrast, keyboard focus and passive native footer preview implemented; actual status previews preserve the selected renderer |
+| Store | Existing graphical discovery/detail/launch routes retained; ordinary labels, search and counts use system typography; desktop and narrow/enlarged previews inspected |
+| Sign-in / setup / boot | Boot/preflight/setup migrated and rendered; installer lifecycle tests pass; sign-in already graphical and scrollable |
+| Shortcuts / keyboard practice | Desktop browsing/practice layout implemented and rendered; remapping and scratch terminal retained |
+| Teams / ancillary dialogs | Swarm conversation, questions, member controls and Quick Start use desktop typography and controls; polling, answers, learning steps and storage unchanged |
+| Layout / move / pane menus | Graphical layout previews, scrollable move list, shared model menu, compact Find options and desktop resize guidance implemented; keyboard navigation and terminal Find sizing retained |
+| Daemon panels | Companion settings, pairing, proposal controls and consent use desktop controls; artwork, reveal frames, state and approval gates retained |
+| Native tabs / footer / menus | System-font curved tabs with names, hover close and Command-held hints; 10-point pane frames. Pane model control before an always-visible close icon. Remaining subscription usage at left and focused machine/project/branch/PR at right. Empty New Tabs hide the footer; modals isolate it, with a passive customization preview |
+| Linux / browser presentation | Shared light/dark, narrow and enlarged-text fixtures cover responsive behavior; physical Linux/browser platform validation is not claimed |
+
+Legacy/test-only paths (including the old NewAgentDialog entry when
+`newHarnessOpensInBox` is disabled) are excluded from the visible migration.
+The standalone MachinesManager, old machine-link dialog, and generic
+team-creation presenter have no production caller in this tree. They are not
+counted as completed user journeys. Shared controls still serve their tests.
+
+## AI review panel
+
+The user requested independent AI perspectives. These are design and engineering
+reviews, not claims of human credentials or Apple endorsement.
+
+- Mac design research: checked Apple HIG/WWDC and official excellent-app
+ references; recommends hierarchy, visible focus, consistent anatomy, semantic
+ light/dark colors, and restrained optional motion. See the research record.
+- Product/accessibility review: found value-only composer controls, missing
+ approval explanations, misleading All scope, weak focus, and ambiguous recents.
+- Frontend review: traced live paths, identified TerminalBox and bespoke
+ terminal-cell forms, and found that AppMenuItem ignored its textStyle input.
+
+Address findings in shared components where appropriate. Each surface still
+needs rendered and runtime review after its migration. A code review or one
+passing screenshot does not establish whole-app completion.
+
+## Verification ledger
+
+Baseline `7782202b`: 4,522 desktop tests passed, 12 skipped; 996 native titlebar
+checks; full form/controller executable-line coverage; local debug build opened.
+These results precede the broad redesign and must not be attributed to later edits.
+
+### Broad desktop surfaces checkpoint, 2026-09-29
+
+- Full desktop suite: **4,560 passed, 16 skipped**, with fresh line and branch
+ coverage. The complete creation controller/form line gate passed.
+- Static analysis covers `lib`, `test`, and `integration_test`. The macOS debug
+ build and **996 native titlebar checks** passed. The native drag fixture needs
+ access to the macOS pasteboard service; its sandboxed run failed the drag
+ assertion, then the authorized native run passed without code changes.
+- AI review fixes include Tab traversal past prompt wrappers, scrollable and
+ selectable long errors with actions kept visible, clear composer-control
+ purposes, honest history load failures, readable status words, and paging
+ the active PR/branch list.
+- Real-font synthetic renders cover light/dark confirmations, sharing, history,
+ notifications, setup, shortcuts, and connection forms. Connection forms were
+ checked at 720×560 with 1×/2× text and 480×360 with 1.6× text; confirmation
+ error layouts include 480×360 at 1.7×.
+- The rebuilt app was reopened. Live review checked the New Tab composer,
+ recent context, coding-agent-first chooser, search scopes/dismissal, native
+ footer coverage, and notification empty state. No real agent was launched.
+- Remaining work is explicit in the inventory above. Physical IME and VoiceOver
+ have not been verified; this checkpoint does not include a Linux build or a
+ repeat of the historical 19-journey native Flutter fixture.
+
+For each new checkpoint record changed surfaces, relevant tests, actual renders,
+native runtime checks, reviewer findings, fixes, and unresolved gaps. Test traces
+must correspond to the final source. Native keyboard injection does not prove
+physical AppKit IME or VoiceOver interaction. No live user data in saved previews.
+
+### Complete desktop presentation pass, 2026-09-29
+
+- Full desktop suite: **4,628 passed, 16 skipped**, with fresh line and branch
+ coverage. New Harness covers **3,813/3,813 executable lines** across its
+ complete controller and form. This is not a whole-app coverage claim.
+- Static analysis of `lib`, `test`, and `integration_test` is clean. The normal
+ macOS debug build succeeds. **999 native titlebar checks** pass, including
+ passive footer preview containment. The macOS Flutter integration fixture
+ passes **19 creation/search journeys**. Its test app is replaced by the normal
+ review build afterward.
+- Independent frontend and product review found and resolved a scrolling-menu
+ focus loop, Find scaling inheritance, observer-header overflow, Add project's
+ intrinsic-layout failure, small-window conversation space, stale focus styles,
+ and Quick Start's remaining terminal-style app controls. The last guide-strip
+ fill adjustment passed its **24-test** guidance/practice rerun.
+- Synthetic real-font renders were inspected for the remaining menus, Store,
+ layout/move palettes, comments, Swarm conversation, Quick Start, observer
+ header, status customization, and companion panels. Cases include both
+ appearances, 360–390-point widths, up to 200% text, Increase Contrast, and
+ Reduce Motion. Rendering fixtures preserve real approval and stale-response
+ guards while substituting data and services.
+- Live macOS review checked the creation form and coding-agent-first chooser,
+ nested dismissal, full footer coverage, search scope switching, settings,
+ status customization's visible but noninteractive footer preview, Store, and
+ Quick Start. Existing terminals and tabs restored. No agent was launched,
+ sharing changed, account authorized, or companion approval accepted for review.
+- The migrated reachable surfaces now follow the shared desktop system.
+ Terminal rendering, status artwork, core controllers, and launch/notification
+ semantics retain their existing behavior. Physical AppKit IME, VoiceOver,
+ and native Linux/browser execution remain separate validation limits; widget
+ semantics and injected-key tests do not establish those results.
+
+The experimental branch remains unmerged for the user's visual review.
+
+
+### Coherent desktop system and focused footer, 2026-09-29
+
+- The specification now defines the task/project/machine hierarchy, shared
+ surface and control tokens, interaction defaults, one 95% modal veil, and one
+ regular outline icon family. `AppIcons` replaces mixed Material/Lucide weights
+ throughout app controls; native menus use the matching regular SF recipe.
+ Agent/provider logos, terminal glyphs and companion artwork retain identity.
+- Cmd-N and Cmd-P, nested pickers, Rename, Move Pane, layout, task routing,
+ connection forms and resource editing use shared geometry and focus states.
+ API editor actions remain visible while the fields scroll. Explicit launch
+ choices persist; fresh forms default to main without overwriting drafts.
+- Welcome/New Tab shows at most six secondary recents, small monochrome agent
+ marks, a 56-point separation and “now” below one minute. Context uses the
+ actual customized status renderer with contrast correction for unbacked ink.
+ No-history welcome has no empty recents section or blank footer.
+- Model/effort is left; focused machine/project/branch/PR is right in both
+ Flutter and AppKit. Branch actions retain their existing target guards.
+ Pane headers retain their quiet titles and hover-only close control.
+- Full suite: **4,645 passed, 16 skipped**. The creation controller/form gate
+ covers **3,894/3,894 executable lines (100%)**. Subsequent icon presentation
+ refinements passed the relevant **76-test** footer/dialog/Store/sharing/pane
+ rerun; no creation logic changed after the full coverage run.
+- Static analysis is clean. **999 AppKit titlebar checks** and **19 native macOS
+ journeys** pass across four sequential batches (5, 5, 4, 5). The native fixture
+ uses fake transports and in-memory workspaces; it starts no real agent.
+- Final real-font synthetic renders were inspected for creation and its machine
+ submenu, search, welcome with/without history, rename/move/layout, focused
+ footer, pane close and customized status styles. Both appearances and narrow,
+ enlarged-text cases are covered. Screenshot fixtures now load the actual
+ regular outline font rather than substituting Ahem squares.
+- The normal macOS debug build succeeds and is open for review. Live review
+ confirmed the focused footer's left/right arrangement, branch/PR click target,
+ matching Cmd-N/Cmd-P veils covering the native footer, Escape dismissal, and
+ six quieter New Tab recents without an empty footer. Existing windows were
+ restored; no real agent was launched. The design system file is open in
+ TextEdit for review.
+- Physical IME, VoiceOver and native Linux/browser execution remain outside this
+ verification. These results do not claim those platform checks or whole-app
+ code coverage. The branch remains experimental and unmerged.
+
+
+### Review refinements and familiar tabs, 2026-09-29
+
+- Creation and New Tab share “Harness anything”. Recent harnesses use one muted
+ neutral ink, retain the chosen status wording/fields/font, and suppress colored
+ backgrounds. Quiet inline creation controls keep a neutral focus fill; normal
+ branch focus no longer leaves a bright outline.
+- GitHub entry begins as a single field. Validation grows only as needed. Long
+ chooser errors and model notices scroll within a bounded area while search and
+ a complete option remain available. A lost-machine message now opens the existing
+ machine chooser directly. Anchors scrolled out of view cannot place its popover
+ above the window; the regression was reproduced with real fonts and a long draft.
+- Cmd-P has a 1120×680 maximum, with 44/56 results/preview proportion on wide
+ windows. A synthetic answer has 591 points of reading width rather than 360.
+ Model section headings and gaps use their own natural height. Loading, retrying,
+ errors and settled emptiness are distinct without discarding available results.
+- AppKit and Flutter tabs use system type, left-aligned names and related curved
+ geometry. Permanent numbering is removed. Hover reveals close; Command reveals
+ actual remapped shortcut hints without shifting titles. Legacy automatic New
+ Swarm names become New Tab; explicitly saved custom names remain exact. Pane
+ frames adopt the shared 10-point radius and clipped 9-point inner edge.
+- Supporting refinements include purpose/value/state accessibility for settings,
+ naturally sized enlarged-text menus, 6-point vertical button padding, consistent
+ model/Find selection and checkmarks, and the Harness manager's shared surface,
+ typography and readable semantic status/error colors.
+- Independent AI reviewers exercised rendered interaction fixtures for search,
+ creation, settings, model/Find menus and the manager. Native tab review includes
+ rest, hover and Command-held states in both appearances.
+- Each pane now shows its model immediately before an always-visible close icon.
+ The model opens the shared Models picker for that exact harness. Narrow panes
+ retain the close target; stale or unavailable targets cannot switch an agent.
+ Tab-strip close still appears on hover and yields to Command-held hints.
+- The footer's left side shows remaining subscription usage, such as
+ “Claude 0% · Codex 50%”, from the same deduplicated accounts and limiting
+ windows as Models. Unknown readings show “—”; distinct accounts remain
+ distinct. Hover explains the reading; click opens Subscriptions. The right
+ side retains the focused machine/project/branch/PR and their actions.
+- Final suite: **4,702 passed, 16 skipped**. New Harness has **3,948/3,948**
+ covered executable lines and the resource picker **1,271/1,271** (both 100%).
+ App, test and integration source analysis is clean. A whole-directory analysis
+ additionally reports 12 pre-existing informational lints in vendored xterm;
+ terminal dependency code was not changed.
+- **19 native macOS journeys** pass across four sequential batches (5, 5, 5, 4),
+ using in-memory workspaces and fake transports. **1,224 AppKit checks** pass,
+ including hidden native-window layout. These do not establish physical
+ AppKit keyboard/IME behavior.
+- The normal macOS debug review build succeeds. Final actual-font renders cover
+ the pane model/close arrangement, subscription footer, muted recents and curved
+ tabs at wide and narrow sizes. Automatic reopening was blocked by the native
+ app-control connection (“Sky Computer Use native pipe startup failed”); this
+ checkpoint does not claim a live-account app review.
+
+### Quiet workspace controls and supporting-surface review, 2026-09-29
+
+- Subscription readings use whitespace rather than dot separators. Names remain
+ neutral; only percentages use red for zero and amber through 20%. Flutter and
+ AppKit receive the same colored spans. Unavailable readings remain neutral and
+ cannot appear as exhausted accounts. Contrast checks cover every workspace
+ palette in both appearances.
+- Pane close marks use the shared smaller size and 45% resting ink, strengthening
+ for hover, focus and Increase Contrast without reducing their click target.
+- Tab names and status form a centered group. Command replaces the status with
+ the resolved shortcut immediately beside the name. Empty status marks reserve
+ no visible slot. Close glyphs are optically matched across Flutter and AppKit,
+ inside separate 32-point targets. Eight tabs fit the reviewed 1280-point width
+ without truncation or horizontal scrolling.
+- Shared confirmation/form bodies now show a draggable scroll thumb whenever
+ content overflows, before the first scroll gesture. Long selectable recovery
+ messages retain their own bounded scroll area and fixed actions. Error text can
+ still be selected and copied in full without changing keyboard ownership.
+- Settings navigation exposes button/selected/enabled accessibility states.
+ Setup metadata and errors now use readable semantic ink. Export Logs retains
+ visible, scalable, keyboard-accessible actions at enlarged text. Store
+ recordings use the shared modal veil.
+- Integrated supporting-surface checks: **121 passed**. Footer/pane checks:
+ **21 passed**, including updates, unknown values, low/exhausted colors, pane
+ targeting, and narrow widths. **10 actual-font render checks** cover light/dark
+ confirmations and connection forms, including enlarged selectable errors.
+- Tab/workspace checks: **53 passed**. Native checks: **1,331 titlebar/layout**,
+ **169 keyboard bridge**, and **9 viewer**; a final windowless run passed
+ **1,090** checks after updating the colored subscription fixture. Actual-font
+ light/dark tab captures cover rest, hover, Command and enlarged text. Source
+ analysis is clean and the normal macOS debug build succeeds.
+- A fresh review instance was launched from this worktree after rebuilding;
+ process start time was verified newer than the bundle. The unavailable native
+ app-control connection still prevents claiming a live visual automation pass.
+
+Remaining review: physical VoiceOver and AppKit IME, and native Linux/browser
+use. These remain explicit gaps, not completed checks. This checkpoint remains
+unmerged.
+
+### Welcome handoff and final interaction review, 2026-09-29
+
+- The no-machine welcome now has a clear heading and natural-width action.
+ Machine discovery keeps that action available. Pending saved defaults show
+ distinct preparation copy before the existing composer receives focus. Recent
+ harnesses retain their 56-point separation in this fallback presentation.
+- Project search measures its header at enlarged text sizes; both “Search repos”
+ and the machine remain readable at 880×560 and 200% text. The ordinary width
+ stays compact. The branch/PR route now uses the shared modal veil, including
+ native footer coverage, without changing the underlying pane or terminal input.
+- Add project uses the same desktop remote-folder chooser as New Harness,
+ preserving path shortcuts and visible recovery. Errors use shared semantic
+ ink. Orchestrator guidance wraps before its Send action can leave the panel.
+- Pane-resize instructions use the desktop surface and system type; divider and
+ key behavior are unchanged. Clone repository gives its URL initial focus.
+ Synthetic composition checks protect Escape in cloning and Enter/Escape in
+ task routing; ordinary actions resume after composition. Explicit Cancel stays
+ available, and retry preserves its existing focus behavior.
+- The independent reviewers inspected actual-font light/dark renders, enlarged
+ text, startup/loading/recovery states, and input handoffs. Supporting dialogs
+ passed **48 render checks**, with **9 final clone tests/renders** after the
+ initial-focus correction. Resize guidance fits 480×360 at 200% text.
+- With source frozen, the combined affected-journey suite passes **171 tests**.
+ Static analysis of `lib`, `test`, and `integration_test` is clean; the normal
+ macOS debug build succeeds. New Harness passes its full **3,953/3,953** line
+ gate, and the resource picker passes **1,271/1,271** lines.
+- The broader run passed **4,754 tests**, skipped **16**, and reported one clone
+ focus failure because it had compiled the library before the final focus edit.
+ The final 171-test run recompiles and passes that regression. Do not describe
+ the earlier broad run as a clean run of the final source.
+- The native app-control service still returns “native pipe startup failed”.
+ Actual VoiceOver and physical AppKit IME remain unverified. Light renders test
+ shared components; the production workspace still uses its approved dark
+ appearance and this work does not add an appearance switch.
+
+### Completion audit and supporting navigation, 2026-09-30
+
+- A fresh frozen full suite at `4bbe5a255` resolves the earlier compilation
+ timing ambiguity: **4,755 passed, 16 skipped**. Its fresh coverage passes the
+ New Harness **3,953/3,953** and resource picker **1,271/1,271** line gates.
+ Those results precede the following final audit fixes.
+- Full History now uses the shared desktop surface, header, search field and
+ result treatment. “This window” names its existing scope accurately. Close
+ receives its own Enter action; search composition retains Escape. Synthetic
+ native-command tests cover selection, dismissal and terminal focus return.
+- The fallback Harness Store control uses system UI type and measured label
+ padding. The fallback tab strip respects platform text scaling; ordinary
+ navigation can grow while terminal zoom remains independent. Actual-font
+ renders cover normal and 200% text.
+- Pending device pairing prevents keyboard and queued selector changes, keeping
+ the displayed device aligned with the operation. Fake failure/cancellation
+ journeys verify accessible state and editing/retry recovery. Manage harnesses
+ now displays and announces “now” for activity under one minute, including
+ future clock skew, consistent with welcome and search.
+- The combined affected-journey suite passes **167 tests**, with **1 optional
+ render skipped**. History also passes all six final interaction/layout tests
+ with actual fonts, and its four normal/narrow light/dark renders were inspected.
+ Static analysis of `lib`, `test`, and `integration_test` is clean, and the
+ normal macOS debug review build succeeds.
+ Shared tab/pane close marks remain the small, fine, muted recipe documented in
+ the design system, with their larger click targets and interaction emphasis.
+- Native runtime verification is still pending: app control reports “Sky
+ Computer Use native pipe startup failed”. Automatic approval review timed out
+ twice before a native integration test could launch; no native test executed
+ in this checkpoint. Physical VoiceOver and AppKit IME remain unverified.
+
+### Native journey verification, 2026-09-30
+
+- The existing fixture launches successfully without the optional sleep-control
+ wrapper. The earlier automatic-review timeout no longer prevents native test
+ execution. A complete creation/search run passes **19 native journeys**;
+ the newly included History checks pass **6 native journeys** in a subsequent
+ process. Both use the macOS engine, fake transports and in-memory workspaces.
+- The first creation/search run passed 18 journeys and observed an unexpected
+ `r` in one nominally empty prompt. That journey passed in isolation, then all
+ 19 passed together with explicit checks that both the editor and controller
+ were empty before Return. No production input code changed. The unexpected
+ input's source was not established; the first run is not counted as passing.
+- History's native checks cover initial focus, bidirectional Tab traversal,
+ Close versus result activation, synthetic composition, terminal focus return,
+ and bounded light/dark layouts at normal and 200% text. This strengthens
+ engine-level evidence; it does not establish physical AppKit IME or VoiceOver.
+- Supporting documentation now agrees with the current system: centered tab
+ name/status groups, Command hints beside the name, shared plus icons,
+ whitespace-separated usage, model/close pane headers, and focused Git context
+ in the footer. Draft, project and worktree ownership rules are unchanged.
+- The independent completion review found no further concrete UI source
+ contradiction. Final live visual continuity, physical VoiceOver and AppKit IME
+ remain unverified while native app control is unavailable. These are the
+ remaining completion gaps; further styling without a demonstrated defect is
+ optional polish.
+- Scoped fixture analysis is clean and the normal `lib/main.dart` review app
+ was rebuilt after native tests. A final app-control attempt still returns
+ “Sky Computer Use native pipe startup failed”, so no live visual review is
+ claimed for this checkpoint.
+
+### Tab close and recent identities review, 2026-09-30
+
+- Tab close targets now sit 8 points inside the outer bounds, keeping the cross
+ clear of the curved edge in both AppKit and Flutter. The 32-point click target
+ is preserved; the title reserves that space before truncating and remains
+ stationary on hover. Natural tab widths gain 16 points to retain the centered
+ name/status group, so the eight-tab full-name fixture now uses a 1440-point
+ strip. Existing narrow-window scrolling behavior is retained.
+- The native tab uses an 8-point regular SF cross to match the pane's small
+ 12-point Lucide mark. Flutter tabs and pane headers already share
+ `AppIcons.closeSize`. Hover emphasis and keyboard commands are unchanged.
+- Recent harnesses retain the original agent colors at 18 points. Removed the
+ grayscale filter and additional opacity; names and context remain quiet.
+ The canonical design system records both revised rules.
+- The existing tab/welcome suites pass **20 tests**, including light/dark,
+ narrow layouts, enlarged type, draft continuity, and close/select ownership.
+ The isolated AppKit titlebar harness passes **1,090 checks** without opening
+ windows. Scoped analysis and formatting are clean. Synthetic native and
+ Flutter renders were inspected in both appearances.
+- The normal macOS debug app builds and was reopened for review. Physical
+ AppKit input and VoiceOver were not exercised in this small visual update.
diff --git a/desktop/design/friendly-desktop-experiment.md b/desktop/design/friendly-desktop-experiment.md
new file mode 100644
index 000000000..280a863e9
--- /dev/null
+++ b/desktop/design/friendly-desktop-experiment.md
@@ -0,0 +1,195 @@
+# Friendly desktop experiment
+
+Requested on 2026-09-28. Local review branch: `experiment/friendly-desktop`.
+This experiment follows the user's new direction for the UI around the terminal.
+The [desktop design system](desktop-design-system.md) now governs all UI outside
+the terminal panes, superseding fixed-cell geometry, bracket buttons, and
+all-monospace app controls. Track the full scope in the
+[migration ledger](desktop-ui-migration.md). This experiment was not included in
+Desktop 1.2.27 and must not be merged without the user's approval.
+
+- Startup and New Tab embed the same `NewHarnessForm` and
+ `NewHarnessController` used by Cmd-N. The form keeps its 680-point maximum
+ width on the full page, without a modal backdrop or Close button. Recent
+ sessions use the existing `WelcomeSessions` eligibility and visit ordering,
+ rendered as a quiet list below the composer. Both form and list scroll in
+ short windows. Typing numbers edits the message; recent rows remain clickable
+ and keyboard-focusable rather than intercepting plain digit keys.
+- Empty tabs initially focus the message. Cmd-N returns to that tab's existing
+ draft. Each empty tab keeps its own choices and message when switching tabs
+ or opening search. Launching uses that tab, with the same pending-receipt,
+ installation, validation, and duplicate-start guards as the popup. A populated
+ workspace still opens Cmd-N as a popup. No harness starts merely by visiting
+ the page.
+- On macOS the native footer yields to a modal route or creation/search backdrop,
+ including its accessibility controls, then restores when it closes.
+- Cmd-N places a centered, 680-point composer directly on a 95% dark backdrop,
+ without an outer card, border, or shadow. Light mode uses a 95% white backdrop
+ so the unframed labels remain readable. Cmd-P retains its floating frame.
+ Both use system typography and visible focus boundaries without shifting controls.
+- Agent and Repo are compact capsule selectors above the editor, with the
+ agent's existing brand mark and Close at the right. The always-visible message
+ editor says “Harness anything”; New Harness sits inside its lower-right corner,
+ works without a message, and has no visible Return symbol.
+ Model, Approvals, and Codex Profile sit below the composer on the left;
+ a checked Worktree control and a branch icon/name sit on the right. Git
+ controls stay together, moving below the other settings in narrow windows
+ or at larger text sizes. Long branch names truncate at the beginning, keeping
+ their identifying suffix and complete Unicode characters; the tooltip and
+ accessibility label retain the complete branch and worktree plan.
+- Machine selection sits inside the Repo search row: “Search repos in This Mac”.
+ Selecting the machine opens a separate menu on the right, repositioning to
+ stay onscreen in narrow windows. The folder query never filters machines.
+ Tab reaches the machine selector from search; selecting a machine returns
+ to Repo, and Escape closes only the machine menu. Open Folder, New Folder,
+ and GitHub appear above the recent folders, separated by a thin rule.
+ Recent folders are scoped to
+ that machine. Fresh launch contexts still default to local; restored drafts
+ and explicit Store machine choices retain their destination. The closed Repo
+ control includes the machine name for remote destinations.
+- Agent choices keep every coding agent above specialized harnesses. A stable,
+ curated order starts with Claude Code, Codex, Cursor, Copilot, Grok, and
+ OpenCode, followed by Antigravity, Amp, Kilo, Devin, Pi, Hermes, Command Code,
+ and Muse. Newly supported coding agents also stay in this first group.
+ Specialized harnesses follow with recent choices first, then Blender,
+ CircuitJS, Godogen, MuJoCo, RDKit, Strudel, Typst, and the remaining catalog.
+ Terminal comes last. Entries appear once; removed packages and viewers remain
+ excluded. Search still ranks matching names by relevance. The saved launch
+ choice remains the default selection without moving it above coding agents.
+- The last explicit approval choice is remembered per agent, including Full
+ access when selected. Worktree choices are remembered per machine/project.
+ Projects without a saved choice keep Worktree on; agents without a saved
+ approval mode keep Auto-approve. Drafts take precedence over these defaults.
+- Fresh and restored task drafts focus the prompt. Enter launches without an
+ extra step. Explicit agent and project selections become remembered defaults;
+ use recents still record actual launches. The task shortcut focuses
+ the editor; the former Options shortcut opens Model directly (Repo for
+ Terminal). Terminal keeps the editor read-only and outside keyboard
+ traversal while preserving a carried message.
+- In the task editor, Enter submits; Shift-Enter inserts a newline. Cmd-Enter
+ remains a remappable launch shortcut. Opening a chooser does not submit the task.
+ Escape and outside clicks dismiss the innermost chooser, then the main form,
+ preserving its draft. X directly dismisses the composer and remains available while
+ a chooser is open. Existing pending-launch checks still protect unresolved
+ creation receipts.
+ A choice or cancellation returns focus to the originating control. Tab and
+ Shift-Tab dismiss a chooser without applying a value and continue form traversal.
+- Focus stays inside the active dialog. The prompt receives initial focus;
+ Terminal focuses New Harness because it has no task. Tab from New Harness wraps
+ to Agent, then Repo, message, Model, Approvals, Profile, Worktree,
+ Branch, and Close. Shift-Tab reaches Close. Tab reaches each visible control without
+ stopping on hidden fields. Arrow keys navigate searchable option lists.
+ Existing command identities and shortcut remapping remain available.
+- Dismissing Cmd-N or switching to Cmd-P preserves its unsent draft in the same
+ machine/project/source-pane context. Another source pane gets its own defaults.
+ Cmd-N resumes that draft even after typing a search query; a fresh composer
+ uses the query when there is no draft. Explicit create-from-search and Store
+ task actions keep their requested text and existing ownership rules.
+ Restoration uses the current destination tab and never duplicates a pending
+ launch receipt.
+- New, Open, and Clone use the selected machine directly. Open Folder invokes
+ the native local folder dialog or remote folder browser in one step. Accepting
+ returns to the composer; cancelling returns to the Repo list. New and Clone
+ prompts offer Change machine. Choosers begin at a focused search field and
+ size to their contents, with no visible title, close button, or key legend.
+ A back control appears inside search only for nested prompts. Machine rows
+ keep names, the current checkmark, and unavailable status; redundant remote
+ captions are omitted. Repo paths remain available for disambiguation.
+- Configuration uses the existing creation controller and choice navigation.
+ Remote machine checks, worktree errors, launch receipts, and installation
+ recovery retain their existing behavior. Task text survives configuration
+ changes and narrow layouts.
+- Cmd-P uses a rounded, compact palette, a native-sized search editor, and
+ visible Harnesses / Machines / Projects / Models / Store / Commands filters.
+ Filters edit the existing searchable prefixes; typing prefixes still works.
+ Sessions show their context in the second line. A visible preview toggle
+ keeps session history and resource management available, with their existing
+ keyboard controls and safety checks. Tab traverses the toolbar, the scope-pill
+ group, and preview actions; Up/Down navigates results. Escape returns from
+ management controls to search before dismissing the dialog.
+- System UI typography is used for app headings, controls, fields, shortcut
+ browsing, and task text. Explicit code, paths, workspace bars, and terminal
+ content retain their appropriate monospace styles.
+- Header selectors use compact capsules; composer settings use quiet text
+ controls with a focus ring. The default action retains its keyboard commands
+ without displaying a shortcut symbol.
+ Clickable controls show a hand cursor, while editors retain a text cursor.
+ Icon-only toolbar controls and navigation links retain their roles.
+
+Review creation and search with keyboard, mouse, input composition, long text,
+light/dark palettes, narrow windows, and unavailable resources. Use synthetic
+fixtures for saved previews; never commit live account screenshots.
+
+Validation of the shared welcome composer on 2026-09-29, after `cc5c4ecf`:
+
+- The full desktop suite passed: **4,522 passed, 12 skipped**. Tests cover
+ independent tab drafts, delayed default loading during tab switches, launch
+ retries and pending receipts, recent-session navigation, search round trips,
+ keyboard focus, and coding-agent ordering. The Repo machine control now
+ handles Right Arrow before the menu anchor consumes it.
+- Fresh full-suite coverage passed the complete New Harness gate:
+ **1,882/1,882 controller lines** and **1,926/1,926 form lines**. This measures
+ executable lines, not exhaustive branch coverage.
+- App/test static analysis, the macOS debug build, and all **996 native
+ titlebar checks** passed. Native checks include hiding and restoring the
+ footer and its accessibility controls around a modal.
+- Synthetic page previews were inspected in light and dark themes at regular
+ and narrow widths with enlarged text. The rebuilt app was reopened for live
+ review of the full-page composer, recent sessions, agent ordering, and popup
+ footer coverage. No real agent was launched for validation. This iteration
+ did not rerun the older 19-journey native Flutter fixture or a Linux build.
+
+Validation of the interaction polish on 2026-09-29, after `67dc29f1`:
+
+- All 169 tests passed across the seven affected composer, dialog, edge-case,
+ entry-rule, preference, and friendly-desktop suites. The additional agent
+ picker, harness selection, install, and project-context suites also passed.
+- App/test static analysis and the macOS debug build passed. Synthetic previews
+ were inspected in dark and light themes, including enlarged text and narrow
+ windows. The final machine-menu styling also passed both theme layout tests.
+- The normal app was reopened. Live review checked the Repo/machine cascade,
+ agent ordering, and Escape returning to the composer without closing it.
+ This iteration did not rerun the full suite, native fixture, or Linux build.
+
+Validation of the frameless composer iteration on 2026-09-29, after `89aceb38`:
+
+- 177 targeted tests passed across composer layout, compact launch, dialog
+ interaction, launch edge cases, entry rules, saved preferences, project
+ context, and friendly desktop suites. This includes keyboard machine
+ selection, machine-scoped folders, nested cancellation, and draft retention.
+- App/test static analysis and the macOS debug build passed. Synthetic previews
+ were inspected in both themes, including narrow layouts and enlarged text.
+ The normal app was reopened and the composer and local Repo menu inspected.
+- This iteration did not rerun the full suite or native fixture described below.
+
+Validation of the minimal composer iteration on 2026-09-29,
+against the experiment baseline `a26237c9`:
+
+- The full desktop unit/widget suite passed: **4,500 passed, 12 skipped**.
+ The native macOS fixture passed all **19 journeys**, once each across four
+ sequential native processes. App/test analysis and formatting passed.
+ The normal macOS debug app was rebuilt after the fixture and opened for review.
+- The fresh full-suite trace covers **1,986/1,986 changed executable lines**.
+ The complete creation form/controller cover **3,627/3,627 lines**; the
+ resource-picker gate covers **1,265/1,265 lines**. These are executable-line
+ measurements, not a claim of complete branch coverage or every possible
+ interaction. No coverage exclusions or stale traces were used.
+- Independent AI developer reviews exercised creation, nested cancellation,
+ mouse/keyboard focus, preview actions, unavailable resources, narrow windows,
+ enlarged text, legacy presentation, and full-tab recovery. The final pass
+ added 26 layout/interaction journeys and a four-round mixed-input sequence.
+ It fixed competing focus restoration after folder acceptance, a stale Return
+ hint, clipped actions in short folder menus, and search text replacing an
+ interrupted draft. Synthetic renders were visually inspected in both themes
+ with real fonts and shadows.
+- A long native test process encountered background frame throttling in this
+ environment. All 19 independent journeys passed in four fresh-process shards
+ with unchanged assertions and timeouts. No Flutter lifecycle or frame
+ completion was overridden. Launch submission uses fake daemons in tests;
+ no real agent sessions were created for validation.
+
+The native fixture injects Flutter keyboard events into the macOS engine.
+Physical AppKit IME behavior and VoiceOver were not separately verified.
+Linux behavior is covered by widget tests; a Linux native build was not run.
+See [the validation record](friendly-desktop-validation.md) for commands and
+the interaction suites.
diff --git a/desktop/design/friendly-desktop-validation.md b/desktop/design/friendly-desktop-validation.md
new file mode 100644
index 000000000..99adfe3c9
--- /dev/null
+++ b/desktop/design/friendly-desktop-validation.md
@@ -0,0 +1,241 @@
+# Friendly desktop validation
+
+Validation for the desktop redesign in PR #484. The earlier checkpoints below
+are historical, not the current visual specification.
+Current behavior and later validation are recorded in
+[friendly-desktop-experiment.md](friendly-desktop-experiment.md); the broader
+redesign follows [desktop-design-system.md](desktop-design-system.md).
+
+## Release checkpoint — 2026-09-30
+
+The branch incorporates main through `dd3097b7f`, including machine profiles,
+companion artwork and shared chat, local-model management, web picker layouts,
+and background opacity behind running harnesses.
+
+| Check | Result |
+| --- | --- |
+| Full desktop unit/widget suite | 4,932 passed; 16 skipped; one stale startup expectation corrected below |
+| Startup rerun | All 4 passed after adding the new background preference to the expected load |
+| Native macOS composer/search journeys | All 25 passed |
+| Native macOS workspace journeys | 26 passed in the full run; the corrected reconnect case passed separately (27 total) |
+| AppKit titlebar, tabs, and footer checks | All 4,193 passed |
+| Companion render fixtures | All 95 passed |
+| Latest background and tab geometry checks | All 13 passed |
+| Welcome composer render fixtures | All 14 passed |
+| Dart analysis of app, tests, and native fixtures | No issues |
+
+The reconnect fixture now advertises the daemon's no-takeover capability and
+represents an established terminal whose initial control claim has been consumed.
+It checks automatic reattachment without takeover, retention of the terminal
+view and selection, and keyboard input after the new stream arrives. Setup uses
+the same isolated guest fixture as the current unit tests; it never launches a
+real daemon. Hermes first-message support is kept in sync with the CLI contract.
+
+Synthetic [dark](review/2026-09-30-welcome-dark.png) and
+[light](review/2026-09-30-welcome-light.png) screenshots were visually checked,
+including agent colors and system text. The welcome fixtures also cover narrow
+windows and 160% text size.
+
+These checks use fake agents and injected Flutter keys. They do not establish
+physical AppKit IME, VoiceOver, or interactive Linux/browser behavior. Release
+CI builds macOS Intel and Apple Silicon variants and Linux x64 and arm64.
+Coverage percentages from the historical checkpoints are not measurements of
+this merged release candidate.
+
+## Historical minimal composer iteration (after a26237c9)
+
+The form is 860 points wide, with Agent, Machine, and Repo across the top and
+the existing agent brand marks. The optional message editor says “Harness anything”
+and keeps New harness inside its lower-right corner. The initial focus still
+supports Cmd-N followed by Return. Model, Approvals, and Codex Profile are small,
+text-only controls below. Worktree on/off and Branch stay together on the right,
+moving together below the other settings in narrow windows or at larger text
+sizes. The title, Add task toggle, and Options disclosure are removed.
+
+Keyboard focus uses a subtle fill without thick outlines or layout movement.
+Cmd-N and Cmd-P share the darker backdrop and softened dialog shadow. Choosers
+start at search, size to their contents, and omit visible headings, close
+buttons, and key legends. A back control remains for nested prompts. Long names
+truncate visually while retaining complete tooltips and accessibility labels.
+
+Open Folder… invokes the selected machine's native local dialog or remote
+browser immediately. Cancelling preserves the draft and returns to the Repo
+list; choosing a folder returns focus to Repo. Its menu row has no submenu
+chevron. Legacy terminal presentation and launch validation are preserved.
+
+Cmd-N resumes an interrupted draft even after typing in Cmd-P. Search text seeds
+a new composer when no compatible draft exists; explicit new-task search
+actions and Store examples still use their requested task. Pending launch
+receipts keep their exact reviewed values.
+
+Independent AI review added 26 composer journeys in
+`test/desktop_composer_layout_test.dart`, alongside the updated launch fixtures.
+These cover the visual hierarchy, full Tab/Shift-Tab traversal, empty and
+multiline launch, live shortcut remapping, all dropdowns, outside clicks,
+Codex-only profiles, Terminal focus, folder cancellation/acceptance, long names,
+light/dark themes, narrow windows, and 160% text size. They pass with the normal
+test font and with real UI fonts. A four-round mixed mouse/keyboard journey
+changes agents and settings, reopens menus, filters lists, cancels by click and
+Escape, then switches through search and restores the complete draft.
+
+Review found and verified fixes for competing focus restoration after folder
+acceptance, a stale Return hint after focus moved into the editor, clipped
+Change Machine actions in short folder menus, and search text replacing an
+unsent message when switching back to the composer.
+
+Synthetic screenshots were visually inspected in both themes, with decoded
+agent assets and real shadows enabled. No live-account screenshots are committed.
+The native fixture uses injected Flutter keys and fake daemons, and does not
+establish physical AppKit IME or VoiceOver behavior.
+
+Final unit/widget validation on 2026-09-29, against `a26237c9`:
+
+| Check | Result |
+| --- | --- |
+| Full desktop unit/widget suite | 4,500 passed; 12 skipped |
+| Native macOS interaction fixture | 19 passed across four sequential shards |
+| App, test, and integration-test analysis | No issues |
+| Formatting | 19 changed Dart files; no changes needed |
+| Normal macOS debug build | Passed; opened for review |
+| Changed executable-line coverage | 1,986 / 1,986 (100%) |
+| Complete creation form and controller | 3,627 / 3,627 (100%) |
+| Resource picker coverage gate | 1,265 / 1,265 (100%) |
+
+All three coverage gates passed against a single fresh full-suite trace. Source
+hashes remained unchanged during the run; no stale traces or coverage exclusions
+were used. These are executable-line measurements, not exhaustive branch or
+input coverage. Unscoped analysis also reports 12 pre-existing info lints in
+unchanged `third_party/xterm` files.
+
+After the native fixture finished, the normal `lib/main.dart` app was rebuilt
+with analytics disabled and opened for review. Cmd-N opens the final composer.
+
+The single-process native fixture encountered background frame-delivery
+throttling after roughly 30 seconds. Diagnostics showed responsive Dart timers
+and native queries, with drawing reduced to about one frame every ten seconds,
+even while the display was awake. All 19 independent journeys then passed once
+each across four fresh native processes (5 + 5 + 4 + 5), with the original
+assertions, timeouts, lifecycle, and frame policy unchanged. Temporary diagnostic
+code was removed. This is a validation-environment limitation, not a claimed
+product fix.
+
+## Earlier polished checkpoint
+
+| Check | Result |
+| --- | --- |
+| Full desktop unit/widget suite | 4,424 passed; 12 skipped |
+| Native macOS interaction fixture | 12 passed |
+| Dart analysis | No issues |
+| Formatting | 62 changed Dart files checked; no changes needed |
+| Normal macOS debug build | Passed; opened for review |
+| Changed executable-line coverage | 1,809 / 1,809 (100%) |
+| Complete creation form and controller | 3,541 / 3,541 (100%) |
+| Resource picker coverage gate | 1,265 / 1,265 (100%) |
+
+Coverage combines real test traces from the final source. Modules edited after
+the broad coverage run were replaced with fresh traces; obsolete line offsets
+were not combined. No coverage exclusions were added. The measurements cover
+executable lines, not every branch or possible input.
+
+## Earlier interaction review
+
+The added suites exercise keyboard and mouse behavior through rendered widgets
+with fake application state and daemon responses:
+
+- `desktop_dialog_interaction_test.dart`: initial focus, traversal, custom
+ shortcuts, composition ownership, nested cancellation, outside clicks, draft
+ restoration, repeat submission, source-pane ownership, and dialog switching.
+- `desktop_new_harness_edge_test.dart`: creation errors, configuration changes,
+ terminal/task compatibility, and narrow layouts.
+- `desktop_search_polish_test.dart` and `desktop_final_ux_test.dart`: search
+ toolbar, scope selection, prefixes, focus, enlarged/narrow layouts, disposal,
+ and repeated reopening. Keyboard-selected scopes stay visible after resizing.
+- `desktop_search_edges_test.dart`: model availability, inventory updates,
+ failed/repeated actions, API editing, preview ownership, polling, and recovery.
+- `desktop_resource_forms_edge_test.dart`: native machine/API configuration,
+ keyboard behavior, asynchronous responses, and errors.
+- `desktop_remote_folder_picker_test.dart`: path entry, browsing, pagination,
+ keyboard shortcuts, input composition, refresh, failure, retry, and disposal.
+- `desktop_preview_compatibility_test.dart`: dated search matches, external
+ conversation warnings, legacy keyboard activation, empty-result recovery,
+ preview scrolling, Store history, and recovery from a full destination tab.
+
+Independent AI developers reviewed synthetic user journeys and rendered
+screens. Their findings led to fixes for hidden selected scopes, stale preview
+callbacks, immediate action focus, clipping, and editor movement. Native visual
+review checked the floating frames and shadows, typography, option lists,
+search results, and previews. At that checkpoint, the normal app was left on Cmd-N.
+
+## Reproduction
+
+Run from `desktop/` with the repository's Flutter/Dart toolchain:
+
+```sh
+flutter test --no-pub --coverage --reporter expanded
+flutter analyze --no-pub lib test integration_test
+node tool/check_new_harness_coverage.mjs coverage/lcov.info
+node tool/check_resource_picker_coverage.mjs coverage/lcov.info
+python3 tool/check_portability_coverage.py --base a26237c9 --lcov desktop/coverage/lcov.info
+```
+
+On macOS, run the isolated native fixture, then restore the normal review app:
+
+```sh
+caffeinate -d -i -u env FLUTTER_TEST=1 DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer flutter test -d macos --no-pub --dart-define=HARNESS_TEST=true integration_test/friendly_desktop_e2e_test.dart --reporter expanded
+DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer flutter build macos --debug --no-pub --target lib/main.dart --dart-define=HARNESS_ANALYTICS_DISABLED=true
+```
+
+If this host throttles a background native test window, add `--total-shards=4`
+and run `--shard-index=0`, `1`, `2`, and `3` in separate sequential processes.
+Run every shard and check the combined test count; do not skip slow assertions.
+
+Native tests inject Flutter keys and use fake daemons. They do not establish
+physical AppKit IME or VoiceOver behavior. Linux widget variants passed; no
+Linux native build was performed. Live-account review remained read-only, and
+live screenshots are not repository fixtures.
+
+## Earlier compact launch checkpoint
+
+Final validation on 2026-09-29, against `a26237c9`:
+
+| Check | Result |
+| --- | --- |
+| Full desktop unit/widget suite | 4,471 passed; 12 skipped |
+| Native macOS interaction fixture | 19 passed |
+| Dart analysis | No issues |
+| Formatting | 12 changed Dart files checked |
+| Normal macOS debug build | Passed; compact Cmd-N opened for review |
+| Changed executable-line coverage | 1,973 / 1,973 (100%) |
+| Complete creation form and controller | 3,645 / 3,645 (100%) |
+| Resource picker coverage gate | 1,265 / 1,265 (100%) |
+
+All three coverage gates passed using the single final full-suite trace from
+the current source. No earlier traces or coverage exclusions were needed.
+These are executable-line measurements, not exhaustive branch or input coverage.
+
+The team review identified two needs: immediate keyboard launch and discoverable
+controls. Empty-task Cmd-N now opens at 560 points wide with Start focused.
+Machine is in the header; Project and Agent remain the main fields. Approvals
+and Worktree stay directly accessible. Add task reveals the composer; Options
+reveals Branch, Model, and Profile in the same dialog. Restored tasks remain
+visible, and empty task editors can be collapsed.
+
+The last explicit approval selection is saved per agent. Worktree is saved per
+machine/project. The existing preference files are extended without changing
+their paths or replacing agent/project recents. Unsupported stored approval
+modes are ignored, storage failures retain the in-memory choice, and pending or
+restored drafts keep their reviewed values. Automatic retry recovery does not
+replace an explicit worktree preference.
+
+Independent test drives added 23 compact interaction journeys and 24 preference
+scenarios. They found and verified fixes for an invisible Tab stop, loss of
+focus after a failed launch, disabled-Start keyboard recovery, late preference
+repainting, and a draft whose resolved worktree choice was not snapshotted.
+The macOS fixture now includes seven compact journeys alongside the existing
+12 composer/search journeys; all 19 passed. The fixture uses fake app state and
+daemons, including when Return submits a launch.
+
+Synthetic visual review covered compact and expanded layouts, both themes,
+600-point windows, and 160% text size. The normal app is rebuilt after the native
+fixture, with the compact Cmd-N left open for review. Physical AppKit IME and
+VoiceOver remain outside this validation.
diff --git a/desktop/design/macos-design-research.md b/desktop/design/macos-design-research.md
new file mode 100644
index 000000000..5f7e6b1b4
--- /dev/null
+++ b/desktop/design/macos-design-research.md
@@ -0,0 +1,205 @@
+# macOS design research
+
+Sources checked **2026-09-29** for the unmerged `experiment/friendly-desktop`
+branch. This note informs the desktop design system; it is research evidence,
+not the canonical implementation specification.
+
+The aim is a friendly, coherent Mac interface around the terminal. Preserve
+terminal rendering and the established tab, pane, creation, and search
+interactions. Improve hierarchy, legibility, consistency, and feedback without
+changing the meaning or ownership of commands.
+
+Apple has not reviewed or approved OpenHarness, and no Apple award is claimed.
+Award references below describe the named reference apps only.
+
+## What Apple recommends
+
+These are paraphrases of primary sources. The numerical proposals later in this
+note are our choices, not Apple requirements.
+
+| Topic | Guidance relevant to OpenHarness | Primary source |
+| --- | --- | --- |
+| Mac workspaces | Support comfortable information density, flexible windows, keyboard operation, and access to commands through the menu bar. | [Designing for macOS](https://developer.apple.com/design/human-interface-guidelines/designing-for-macos/) |
+| Toolbars | Choose frequently useful actions deliberately and group related controls clearly. Standard components help maintain platform consistency. | [Toolbars](https://developer.apple.com/design/human-interface-guidelines/toolbars) |
+| Typography | Use the system face and semantic hierarchy. Apple's Mac text-style table lists 13-point body text with a 16-point line height. | [Typography, Japanese edition](https://developer.apple.com/jp/design/human-interface-guidelines/typography) |
+| Focus | Text and search fields generally use a focus ring; lists use a row highlight. Avoid unexpected focus changes. | [Focus and selection](https://developer.apple.com/design/human-interface-guidelines/focus-and-selection/) |
+| Color | Custom palettes need light, dark, and increased-contrast variants. Communicate meaningful state through labels or shapes as well as color. | [Color](https://developer.apple.com/design/human-interface-guidelines/color?changes=_2_2) |
+| Contrast | Check foreground/background contrast in every appearance. Apple recommends at least 4.5:1 and encourages stronger contrast for custom small text. | [Dark Mode](https://developer.apple.com/design/human-interface-guidelines/dark-mode) |
+| Sheets | Use sheets for scoped tasks related to the parent view. Back navigates within a flow; Close or Cancel dismisses it. | [Sheets](https://developer.apple.com/design/human-interface-guidelines/sheets?changes=_1_1) |
+| Menus | Group related commands, order important actions usefully, and keep submenu hierarchy shallow. Use consistent icon treatment within a group. | [Menus](https://developer.apple.com/design/human-interface-guidelines/menus?changes=_4_1_8) |
+| Motion | Use animation to explain feedback or transitions, keep it optional, and avoid distracting motion. | [Motion](https://developer.apple.com/design/human-interface-guidelines/motion?changes=l_9_3) |
+| Accessibility | Describe interface elements for VoiceOver and provide non-color indicators for meaningful distinctions. | [Accessibility](https://developer.apple.com/design/human-interface-guidelines/accessibility?changes=latest_maj_6_3&language=objc) |
+
+Two WWDC sessions help translate these principles into a component system:
+
+- [Get to know the new design system, WWDC25](https://developer.apple.com/videos/play/wwdc2025/356/)
+ describes shared component anatomy and consistent core interactions. For our
+ pickers, this suggests stable positions for checkmarks, labels, and accessories.
+- [Meet Liquid Glass, WWDC25](https://developer.apple.com/videos/play/wwdc2025/219/)
+ explains the material's functional role. In this Flutter implementation,
+ legibility over terminal output takes precedence over imitating that effect.
+
+Our interpretation: native behavior and clear content hierarchy matter more to
+this Flutter redesign than simulating every Liquid Glass effect. A visual
+refresh should preserve the existing fast input and draft-restoration behavior.
+
+## Product examples and our interpretation
+
+These observations use official product descriptions and examples, not a
+hands-on audit. They are design references, not templates to copy.
+
+| Reference | Documented pattern | Useful interpretation for OpenHarness |
+| --- | --- | --- |
+| **Things** | Its editor keeps optional details secondary, and Quick Find emphasizes immediate results. Things documents its Apple Design Awards in 2009 and 2017. [Features](https://culturedcode.com/things/features/), [award history](https://culturedcode.com/things/blog/2017/06/back-from-wwdc/) | Keep the task editor dominant, configuration calm, and search feedback immediate. For example, changing Model should preserve both the draft and the editor's visual position. |
+| **Bear** | Its official presentation emphasizes a minimal native interface and gradually revealed capabilities. Apple named Bear a 2017 Design Award winner. [Product](https://bear.app/), [Apple announcement](https://www.apple.com/newsroom/2017/06/apple-design-awards-celebrate-the-best-in-innovation-and-creativity/) | Put personality in meaningful agent marks and considered color; use typography and spacing for the rest. Avoid decorating every setting with an unrelated symbol. |
+| **Ulysses** | Its product page pairs a focused editor with substantial project organization and identifies it as an Apple Design Award winner. [Product](https://ulysses.app/) | Keep secondary power accessible through the existing menus and previews without making every option equally prominent. |
+| **Play** | Apple praises approachable access to sophisticated prototyping and an organized interface in its 2025 award description. [Apple Design Awards](https://developer.apple.com/design/awards/2025/) | Judge the redesign by whether a newcomer can understand the next action while experienced users retain efficient controls. |
+
+## Chosen starting measurements
+
+These are proposals to evaluate in rendered fixtures. They are not a claim of
+pixel-for-pixel AppKit fidelity. Values use Flutter logical pixels; verify their
+appearance at the native window scale and with enlarged text.
+
+| Role | Starting proposal | Example |
+| --- | --- | --- |
+| Control label | System sans, 13 size / 16 line height, regular or medium | Agent, Repo, Model |
+| Body and editor prose | System sans, 14 / 20 | Task text and explanations |
+| Secondary metadata | System sans, 12 / 16 | Machine or session context |
+| Section heading | System sans, 17 / 22, medium | Resource-management section |
+| Spacing | 4, 8, 12, 16, 24 scale | About 8 within a group, 16 between groups, 20–24 at panel edges |
+| Controls | 32 regular, 28 compact minimum height; grow for text | Standard selector versus inline setting |
+| Icons | Approximately 16, optically aligned to text | Menu chevron or control glyph |
+| Shapes | Start from existing 8-point controls and 16-point palette; evaluate nested corners together | Keep Agent/Repo capsules as deliberate selector variants |
+
+Paths, shortcut hints, and terminal content retain their established typography.
+Use the semantic role to choose a style rather than shrinking text until it fits.
+Long values should preserve useful context through truncation and complete
+accessible labels or tooltips.
+
+## Findings in the existing implementation
+
+- [`DesktopChrome.text`](../lib/widgets/desktop_chrome.dart) already uses the
+ system body face, but gives all roles the same `1.45` line-height multiplier.
+ Separate control, prose, metadata, and heading roles for more consistent density.
+- `DesktopPill` currently gives hover and press the same overlay. Its focus fill
+ also replaces its selected fill, so focused-selected is not a separately
+ designed state. Review this explicitly, especially for scope selectors. Keep
+ focus feedback visible without changing bounds or moving neighboring controls.
+- The declared `focusRing` token is unused by `DesktopPill`. A quiet fill can
+ remain the normal treatment; provide a stronger, distinguishable treatment for
+ increased contrast and verify text-field focus separately. Existing opacity
+ values alone do not establish an accessibility failure or a passing result.
+- Consolidate chooser row anatomy, menu insets, separators, and shadows. For
+ example, Open Folder and Clone should align their labels and accessory columns
+ even when only one opens a nested step. Do not add decorative cards around
+ each group.
+- The frameless composer backdrop and search palette are intentional experiment
+ decisions. Preserve their established behavior. Do not automatically reuse
+ their modal treatment for unrelated settings or small menus.
+- Keep new chrome tokens separate from terminal tokens. `AppControl` contains
+ historical opinions about exact macOS shapes; they are not universal Apple
+ rules. The experiment and validation documents also describe different
+ composer iterations and need reconciliation in the canonical specification.
+- Current immediate hover, selection, and keyboard feedback is a sound baseline.
+ Optional transition polish must not delay typing, focus, results, or dismissal.
+
+## Review checklist
+
+Use synthetic content and the actual system fonts. Record what was exercised;
+widget or coverage results do not establish native accessibility behavior.
+
+- [ ] **Light and dark:** inspect controls, metadata, selections, borders,
+ shadows, errors, and long values; measure rendered text contrast.
+- [ ] **High contrast:** enable Increase Contrast; verify control boundaries and
+ focus, selected, disabled, and inactive-window distinctions.
+- [ ] **Reduced motion:** enable Reduce Motion; keep all state changes
+ understandable without movement. Check Reduce Transparency if materials are used.
+- [ ] **Resize and text:** review minimum width, short windows, enlarged text,
+ long Unicode names, and live resizing without clipped or displaced actions.
+- [ ] **Keyboard and pointer:** traverse both directions, use arrows and existing
+ shortcuts, inspect hover and press feedback, and verify focus returns to the
+ originating control after chooser acceptance or cancellation.
+- [ ] **Accessibility:** use VoiceOver and Accessibility Inspector to check names,
+ roles, values, selection, disabled state, reading order, and modal containment.
+- [ ] **IME:** exercise native composition, candidate selection, paste, and
+ multiline editing; Return during composition must not accidentally launch.
+- [ ] **Continuity:** retain drafts, query, selection, and underlying terminals
+ through the existing New/Search round trips. No input should leak to terminals.
+
+The existing friendly-desktop validation explicitly leaves physical AppKit IME
+and VoiceOver unverified. Keep those limitations visible until native review has
+actually been performed.
+
+## Second research pass: relationships before tokens
+
+Rechecked primary sources after the user challenged whether the first system
+was exceptional enough. The first document established consistency; that did
+not establish exceptional visual quality. There is no defensible objective
+ranking of a "best ever" design system, nor evidence that Jony Ive would endorse
+this particular interface.
+
+### Evidence examined
+
+- **Apple, Get to know the new design system, WWDC25:** read the transcript,
+ especially shape, structure and continuity. Apple explicitly distinguishes
+ compact rounded-rectangle controls from larger capsule controls on Mac.
+ Its spatial treatment ties secondary surfaces to their source. This supports
+ a hierarchy of related shapes, rather than giving every element an identical
+ pill. [Primary source](https://developer.apple.com/videos/play/wwdc2025/356/)
+- **Apple, Materials:** materials have functional roles. Our choice is a quiet,
+ legible floating panel; no claim of implementing native Liquid Glass.
+ [Primary source](https://developer.apple.com/design/human-interface-guidelines/materials)
+- **Things:** read the official feature account and visually inspected its
+ presented editor. A plain writing area is dominant; optional date/tag details
+ occupy a secondary edge. This is a product-page visual study, not a hands-on
+ usability test. [Primary source](https://culturedcode.com/things/features/)
+- **Raycast:** read the May 2026 engineering/design account and visually inspected
+ its interface montage. Compact labels, anchored menus and restrained controls
+ share a consistent density. Its stated native-quality criteria include
+ opening behavior and preventing clipped popovers or flicker. Our hand cursor
+ remains an explicit user preference, despite Raycast choosing otherwise.
+ [Primary source](https://www.raycast.com/blog/a-technical-deep-dive-into-the-new-raycast)
+- **Jony Ive's published design principle:** Apple's 2013 announcement quotes
+ his emphasis on "bringing order to complexity". Our interpretation is to
+ simplify structure, defaults and interaction before adding effects. It is
+ not a prediction of his present-day design choices.
+ [Primary source](https://www.apple.com/newsroom/2013/06/10Apple-Unveils-iOS-7/)
+
+### Changes this research calls for
+
+The canonical specification now starts with a design brief and explicit visual
+relationships before its measurements. Review must compare actual surfaces side
+by side. The task is the focal point; controls use a limited shared family;
+identity comes from real agent marks; depth explains ownership; behavior carries
+continuity. Dense terminal output remains visually independent.
+
+The review should reject an oversized empty search panel, nested decorative
+cards, redundant icons, competing selection treatments, inconsistent typography,
+weak text contrast, unstable focus or a lost draft even if each local component
+passes its tests. Any responsive adjustment must retain stable editor geometry
+and the existing controller's query, selection and preview state.
+
+
+## Settings and supporting-surface review
+
+The next primary-source pass focused on small interaction details rather than
+adding decoration. Apple's [VoiceOver evaluation criteria](https://developer.apple.com/help/app-store-connect/manage-app-accessibility/voiceover-evaluation-criteria)
+and [accessibility design session](https://developer.apple.com/videos/play/wwdc2025/229/)
+informed purpose, value and state labels for controls. The implementation now
+exposes those separately and avoids merging multiple actions into one setting.
+Widget semantics tests establish that metadata; a native VoiceOver pass is still
+required to evaluate actual navigation and announcements.
+
+Apple's [writing guidance](https://developer.apple.com/design/human-interface-guidelines/writing)
+encouraged clearer action and recovery language. The review found that “Choose a
+machine” must lead directly to the existing chooser when a selected machine
+vanishes. The creator keeps its prompt and explicit launch choices during that
+recovery. Loading is also separated from settled emptiness in search.
+
+[Nova's documented settings](https://help.nova.app/settings/) and
+[appearance settings](https://help.nova.app/settings/theme/) were examined as
+examples of organizing configuration. Search vocabulary and returning to the last
+settings pane remain possible later improvements; they were not silently added
+as part of this presentation pass. Measured content height, clear grouping and
+consistent control labels were actionable within the current scope.
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
index e13c91ec7..941d89e27 100644
--- a/desktop/design/new-harness-entry-rules.md
+++ b/desktop/design/new-harness-entry-rules.md
@@ -1,52 +1,50 @@
# New Harness entry rules
-Presentation follows the [terminal dialog design system](terminal-dialogs.md).
-Use that guide for current visuals; this document owns entry and launch behavior.
-
-Startup and Cmd-T show the same quiet welcome page. Cmd-T creates a blank tab;
-Escape leaves that tab open. The command dock opens only after an explicit
-Cmd-N, Cmd-O, or Cmd-P action. Start Harness submits the reviewed draft;
-opening or cancelling the dock never starts a harness.
-
-The compact, centered launch form starts with `New Harness` selected.
-Agent, Project, and collapsed Options are the main rows. Options expands Model,
-Approvals, applicable Profile, Branch, and Worktree in consecutive rows. Enter launches
-using the displayed settings. The launch action follows the fields with one blank row
-and no extra shortcut hint. Enter on the selected action launches; there is no
-Shift-Enter shortcut. Carried tasks remain in the draft.
-
-Up/Down moves between fields and automatically reveals that field's chooser to
-the right, without moving the form. Right, typing, or Enter moves keyboard focus
-into the chooser. Enter accepts a value and returns focus to New Harness; a
-second Enter launches. Escape discards the search and returns to the form.
-Tab and Shift-Tab switch between the form and its chooser without applying a
-choice; Up/Down navigates the active pane, matching Cmd-P and Cmd-I.
-There is no summary pane. Agent combines coding agents and specialized
-harnesses in one list. Choosing Blender opens a compatible coding-agent list
-in the chooser. Project
-searches all machine/folder pairs, local first, with unavailable destinations
-dimmed. Choosing a pair sets both the machine and project. New Folder, Open
-Folder, and Clone Repository first ask for a machine, with local preselected,
-then show their name, path/browser, or URL prompt. Escape retraces these steps.
-Project displays `machine:full-path`; there is no separate Machine row.
-
-Use the terminal's selected font and measured cells. All controls are plain
-text, with one-row highlights. Worktree uses `[x]` / `[ ]`. Narrow windows show
-the active list on the same column with its own height. Validation messages have
-their own whole rows. The chooser starts with search, without
-a back/title row; Left or Escape returns to the form. Opening, searching, and cancelling
-never send input to an existing harness or start one.
+Presentation follows the [desktop design system](desktop-design-system.md).
+This document owns entry, drafts, and launch behavior; the
+[desktop experiment](friendly-desktop-experiment.md) records the reviewed
+composer and picker interactions. Earlier terminal-cell form styling is retired.
+
+Startup and New Tab embed the same `NewHarnessForm` and controller used by
+Cmd-N, at the same 680-point maximum width. The page has Recent harnesses below
+the composer, without a modal frame or Close button. Opening the page or dialog
+never starts a harness; New Harness submits the reviewed draft.
+
+Agent and Repo selectors sit above the message. Model, Approvals, applicable
+Profile, Worktree, and Branch remain visible below it. Fresh and restored task
+drafts focus the prompt. Terminal, which takes no task, focuses New Harness. In the message,
+Enter submits and Shift-Enter inserts a newline, respecting composition and the
+active keymap. Tab/Shift-Tab traverse the visible controls. Arrow keys navigate
+an open chooser. Accepting or cancelling returns focus to its originating control.
+
+Outside clicks and Escape close the innermost child picker first, then the main
+popup. The X directly closes the popup. Dismissal preserves its draft; unresolved
+launch receipts retain their close guards. The popup's 95% dark backdrop
+covers the native footer. The full-page entry retains its per-tab draft when
+switching tabs. Choosers use system typography, normal controls, a search field,
+natural row heights, and bounded scrolling.
+
+Agent combines direct coding agents and specialized harnesses in one searchable
+list. A specialized harness then offers compatible coding agents. Repo searches
+recent folders on the selected machine; its search row contains the machine
+picker, with local preselected for a fresh context. Open Folder, New Folder,
+and GitHub operate on that selected machine. Open invokes the native local
+folder dialog or remote browser; New and Clone offer Change machine inside
+their prompts. Escape retraces child steps. A remote machine appears in the
+closed Repo label, with the full folder path available in its tooltip.
+
+Opening, searching, and cancelling never send input to an existing harness.
| Entry | Initial values | Destination after a successful start |
| --- | --- | --- |
-| Cmd-T, then Cmd-N | Last successful agent, local machine, last project on that machine | The blank tab opened by Cmd-T |
-| Cmd-Shift-P → New Harness | Last successful agent, local machine, last project on that machine | Current tab |
-| Cmd-N or the New Harness command | Last successful agent, local machine, last project on that machine; retain explicit task and destination | Current tab unless its source requests a new tab |
+| Cmd-T, then Cmd-N | Last explicit agent, local machine, last selected project on that machine | The blank tab opened by Cmd-T |
+| Cmd-Shift-P → New Harness | Last explicit agent, local machine, last selected project on that machine | Current tab |
+| Cmd-N or the New Harness command | Last explicit agent, local machine, last selected project on that machine; retain explicit task and destination | Current tab unless its source requests a new tab |
| Explicit pane split | Focused pane's defaults | Requested split in that tab |
| Store New Harness, or a product's Open action in the pane or native Models menu | Explicit product and machine; suggested project named for that product | New tab |
| Store Resume Harness | Existing harness and its machine; choose from a menu when several match | Focus its existing tab or reopen a view of the same harness |
| Store Try this prompt | Same as Open, with the example as the editable task | New tab |
-| First empty workspace | No automatic action; show the welcome page | User chooses with Cmd-N, Cmd-O, or Cmd-S |
+| First empty workspace / New Tab | Same launch defaults, with a draft owned by that empty tab | That tab when the user submits New Harness |
The Store and orchestration tabs cannot host a terminal pane. Generic creation
from either uses a new tab. Command-bar requests keep the workspace context and
@@ -67,10 +65,11 @@ arrows navigate within the active pane and Enter activates the focused item.
## Harness and agent choices
-Agent lists recent specialized harnesses, direct coding agents, installed
-harnesses, and the rest of the machine's catalog, followed by Browse Harness
-Store. All are searchable. Codex, Claude Code, and Terminal are direct choices;
-there is no separate Coding category. A specialized harness asks which compatible
+Agent keeps every coding agent first, in the curated order documented in the
+desktop experiment. Specialized harnesses follow with recent choices, the tuned
+set, and the remaining catalog. Terminal comes last. All are searchable and
+the saved default selection does not move specialized harnesses above coding
+agents. There is no separate Coding category. A specialized harness asks which compatible
coding agent should run it, preselecting its remembered choice. The form's value
then reads `Blender · Codex`. Choosing a direct agent removes the package choice
and sends no `dsh`; it does not remove project instructions or skills.
@@ -84,13 +83,21 @@ Machine changes re-evaluate compatibility and never silently substitute at
launch. The installed package's compatibility takes precedence over a newer
catalog listing.
-The existing local state store retains separate engine and harness recents and
-the last successful engine per harness. Legacy preference keys and the app data
-directory stay in place. Fresh forms use successful launches, not canceled edits.
+The existing local state store retains separate engine and harness use recents.
+Explicit desktop agent/harness choices become defaults immediately without
+pretending a launch happened or changing use-recency order. The compatible
+agent chosen for a harness is remembered too. Explicit folder choices are saved
+after Git discovery canonicalizes linked worktrees to their repository. Legacy
+preference keys and the app data directory stay in place.
+On the desktop experiment, approvals separately remember the last explicit
+selection for each agent. Worktree remembers the last explicit toggle for each
+project on each machine, even when the form is later dismissed. Unsupported
+saved modes are ignored; drafts and pending receipts retain their reviewed
+values. Automatic retry recovery never changes these remembered preferences.
## Model selection
-Model lives under Options and uses the chosen agent’s supported routes. Show the
+Model is a compact control below the message and uses the chosen agent’s supported routes. Show the
selected model name, or its provider (OpenAI / Anthropic) when the launch model
is not reported. Its picker reuses the Models menu's subscription usage
source and the selected machine's model catalog. It shows the relevant
@@ -115,30 +122,34 @@ is needed while continuing to allow ordinary subscription launches.
## Git projects
-Git projects enable Branch and Worktree. Worktree defaults to **Yes**;
-Enter, Space, Left/Right, Page Up/Down, or a click toggles `[x]` and `[ ]`.
+Git projects enable Branch and Worktree. Worktree defaults to **Yes** when the
+project has no saved worktree preference;
+The checkbox supports pointer and keyboard activation through the form's active
+keymap. Its label and branch icon remain together as the form narrows.
An empty repository explains that a commit is required for a worktree and asks
for a choice. Folders without Git keep both rows disabled. Discovery runs on the selected machine
without fetching, switching branches, or creating a worktree. A failed
discovery offers Retry and blocks starting until the result is known.
A worktree is a temporary folder, never a project: a harness is known by the
-folder it was started in and its repository's branch. Pane headers read
-`folder › branch`, with the machine first only for another computer: the folder
-the harness started in (a subfolder as itself, a checkout's root — a
-worktree's too — as its repository), which does not follow the agent's shell,
-and the branch with the same icon everywhere. A checkout on no branch — a
-commit an agent checked out to read or test — shows no branch; the tooltip says
-`No branch: on commit 65281563`. Worktree folders are never shown; the header's
-tooltip has the full path. Cut short, the folder shortens in the
-middle before the branch does. A folder inside a linked
+folder it was started in and its repository's branch. The focused workspace
+footer shows machine, project, branch and PR together using the user's selected
+status style. Pane headers keep harness identity, the model control and close
+action; they do not repeat project or branch context. The project label is the
+folder the harness started in (a subfolder as itself, a checkout's root — a
+worktree's too — as its repository), and does not follow the agent's shell.
+Detached checkouts do not invent a branch name; full path and checkout details
+remain available through the context controls. Worktree implementation folders
+are not everyday project labels. See [workspace-status-bar.md](workspace-status-bar.md)
+for context actions and compact layout. A folder inside a linked
worktree (the focused pane's, or one typed or browsed) shows as the same folder
in the repository's main checkout, so Cmd-N from a worktree pane starts beside
it rather than inside it. Worktrees Start made are never offered as recent
projects.
-**Branch** starts on `main` (local, or `origin/main`) with Worktree on, and on the
-folder's own branch after the user turns Worktree off. Missing `main` requires
+**Branch** starts on `main` for a fresh desktop form. With Worktree on, local
+`main` or `origin/main` can supply the base. With Worktree off, it must be a local
+branch; a remote-only `main` requires an explicit local branch choice. Missing `main` requires
an explicit branch choice; a failed worktree creation never silently turns
Worktree off. Branch does not follow the pane New Harness was opened from:
New Harness is new work, and another agent's branch is one pick away. The start
@@ -178,8 +189,8 @@ A picked or created branch keeps its name. The worktree is checked out in
`~/harnesses/worktrees/<repository>/<branch>`, and ignored files listed in the
repository's `.worktreeinclude` (gitignore syntax, e.g. `.env`) are copied in.
-With **No**, **Branch** is the branch the folder itself is on; only local
-branches are selectable. A branch with a worktree of its own opens there.
+With **No**, **Branch** selects the local checkout branch, initially `main` for
+fresh desktop work. Only local branches are selectable. A branch with a worktree of its own opens there.
Typing a name no branch has offers **Create branch**:
a new branch from the folder's branch, keeping its uncommitted changes.
Switching or creating needs no harness working in the folder, and switching
@@ -202,15 +213,22 @@ worktree: the retry selects that worktree's branch with Worktree off.
- Workspace drafts belong to their original machine, focused source harness,
and project context. A different focused harness does not inherit their edits.
-- Fresh Cmd-N and Cmd-Shift-P creation use the same successful-launch defaults.
+- Fresh Cmd-N and Cmd-Shift-P creation use the same remembered explicit choices.
The current tab controls placement; a saved draft cannot redirect it to an old destination.
+- Draft identity uses the original source context, not the remembered project
+ subsequently changed by editing that draft. Reopening cannot lose the task
+ because the person's latest choice became a new default.
- Store drafts belong to the explicitly requested product and machine. Opening
Blender cannot restore Workshop's agent, task, or generated project name.
-- Escape discards ordinary Cmd-N edits. Explicit Store entries can resume their
- compatible draft, including the selected agent. Store Open still wins if the
- harness or machine was changed inside that saved draft.
-- A newly typed search task or Store example starts from that entry's defaults.
- Repeating the same request while its draft is already open keeps its edits.
+- Closing Cmd-N keeps its draft for that context. Explicit Store entries can
+ resume their compatible draft, including the selected agent. Store Open still
+ wins if the harness or machine was changed inside that saved draft.
+- Cmd-N from search resumes the same-context draft, including its task and
+ selected options. Search text seeds the task only when no compatible draft
+ resumes; browsing search must not replace an interrupted composer.
+- Explicitly choosing a new-task search result or a Store example starts the
+ requested task from that entry's defaults. Repeating the same request while
+ its draft is already open keeps its edits.
- A request awaiting confirmation is an exception: restore its exact values and
receipt. A new task must not silently turn an uncertain start into a duplicate.
An in-flight or uncertain draft cannot be replaced while it is open.
@@ -222,7 +240,8 @@ worktree: the retry selects that worktree's branch with Worktree off.
Suggested projects display the existing `<agent>-YYYY-MM-DD-HH-MM` naming
convention. Untouched suggestions follow agent changes; a user's edited name
does not. The suggestion is frozen while reviewed. Project → New Folder
-asks for a machine, then opens the name prompt; accepting a name returns to the Project field.
+opens the name prompt on the selected machine, with Change machine available;
+accepting a name returns to the Repo control.
Each machine retains its own project choice. A folder on one machine is never
silently reused on another. Generated folders use exclusive reservation and
diff --git a/desktop/design/review/2026-09-30-welcome-dark.png b/desktop/design/review/2026-09-30-welcome-dark.png
new file mode 100644
index 000000000..ffe90b84f
Binary files /dev/null and b/desktop/design/review/2026-09-30-welcome-dark.png differ
diff --git a/desktop/design/review/2026-09-30-welcome-light.png b/desktop/design/review/2026-09-30-welcome-light.png
new file mode 100644
index 000000000..cadf1b861
Binary files /dev/null and b/desktop/design/review/2026-09-30-welcome-light.png differ
diff --git a/desktop/design/terminal-dialogs.md b/desktop/design/terminal-dialogs.md
index d6fec2c99..cdad4329e 100644
--- a/desktop/design/terminal-dialogs.md
+++ b/desktop/design/terminal-dialogs.md
@@ -1,401 +1,100 @@
-# Terminal dialog design system
-
-Use the [product terminology](../../docs/terminology.md): a swarm groups harnesses;
-a harness is one running agent session.
-
-**Fixed cells. Plain text. One-line selection.**
-
-This is the dialog chapter of the [terminal workspace design system](terminal-workspace.md).
-
-Harness's terminal-workspace dialogs should feel like part of the terminal.
-This is the agreed design direction from the Cmd-N and Cmd-P review on
-2026-09-24. Apply it to new and revised workspace pickers, forms, confirmations,
-and their previews. It is the current source of truth for their presentation,
-including where older design handoffs describe different visuals.
-
-Cmd-N (`NewHarnessForm`) and Cmd-O (`SwarmSearchResults` in its terminal setup
-layout) are the implementation references. Full Settings pages and embedded
-viewers keep their own component systems.
-
-![Open Harness rendered with fixture data](images/terminal-open-harness.png)
-
-The fixture above shows the terminal grid, plain-text rows, and unselected
-opening state. Live surfaces use the user's selected terminal font and palette.
-
-## Lay out a character grid
-
-Measure the selected terminal font through `terminalCellSizeOf(context)` in
-[`terminal_text.dart`](../lib/terminal/terminal_text.dart). Its width is one
-character column; its height is one text row. Use this shared measurement in
-both layout and scrolling calculations.
-
-- Express horizontal margins, gutters, column widths, and gaps in whole cells.
-- Express vertical spacing in whole text rows. A title is one row; its context
- or description is the next row; separation is a blank row.
-- Align the input text, result titles, and context lines to the same column.
- Align form labels and values in consistent columns.
-- Keep single-line choices to one row. Truncate long labels within their
- column; preserve the full value for accessibility or inspection.
-- On narrow windows, reduce columns or change the pane arrangement. Keep the
- measured font and row spacing rather than shrinking text to fit.
-
-Do not approximate a cell as `fontSize * .6`, copy pixel padding from a
-screenshot, or let Material control minimum heights determine the grid.
-
-```dart
-final cell = terminalCellSizeOf(context);
-final gutter = cell.width * 2;
-final lineHeight = cell.height;
-```
-
-## Highlight one line
-
-The selection background spans the selected name/value line and is exactly one
-terminal row tall. Descriptions, metadata, previews, and blank spacing remain
-outside it. Only the list or field that owns keyboard navigation shows the
-active highlight. Moving selection must not shift any text or columns.
-
-Click targets may include a result's context line. Their size must not enlarge
-the visible selection. Keep semantic selection, focus, and enabled state even
-when using custom row widgets.
-
-## Use text for the controls
-
-- No provider logos, avatars, decorative emoji, image assets, or icon-font
- glyphs in dialog chrome. Write `Codex`, `Claude`, or the harness name.
-- Keep Cmd-O and Cmd-P search prefixes editable: Cmd-P opens an empty field and
- Cmd-O inserts `#`. Deleting a prefix returns to harness search.
- Do not draw a separate prompt character beside these inputs.
-- All Cmd-P results occupy one row: title
- on the left and activity age, when available, on the right. Machine, project,
- model, API connection, and Store details live in the preview. For harnesses,
- the preview puts the compact
- Standard context `machine:project (branch)` directly below the harness title,
- followed by status and harness type. Omit missing fields and preserve
- important state such as Offline.
-- Boolean controls use `[x]` and `[ ]`; Enter and Space toggle them.
-- Menu actions use concise text, such as `New Harness`, with the same row
- highlight as other choices and no surrounding brackets. Shortcut hints,
- when needed, are text beside the action, resolved from the live keymap.
-- Omit redundant heading rows such as “New Swarm” or “New Pane.” Add a label or
- explanation only when it helps someone understand a choice or state.
-- Preserve user content, including Unicode. The restriction on decorative
- graphics applies to our controls, not to the text someone supplied.
-
-For example, Cmd-P session results are consecutive single lines:
-
-```text
- Search harnesses
-
- Checkout retries 5m
- Search experience 1h
-```
-
-The highlight covers the selected row. All result types, including resource
-creation entries, use consecutive single lines. Details remain searchable and
-available to screen readers. Machine and project previews retain their name
-and harness count even when they contain just one session.
-
-Unavailable harnesses keep their place in the list. Dim their names and replace
-the activity age with a short reason such as `Offline`, `Not connected`, or
-`Link required`. They remain selectable for their saved preview, but Enter and
-click cannot open them. Availability updates in place when the machine reconnects.
-
-![An offline session remains readable in the preview](images/terminal-open-unavailable.png)
-
-![A selected session with its context in the preview](images/terminal-open-harness-preview.png)
-
-![Models use the same single-line list with details in the preview](images/terminal-open-models.png)
-
-## Inherit the real terminal's appearance
-
-Use `terminalContentStyle()` for all dialog text: input, labels, values,
-metadata, timestamps, actions, and previews. This preserves the terminal's
-font family, fallback fonts, size, line height, and zero added letter/word
-spacing. Do not substitute the general app UI type scale or hardcode a font
-and size in an individual dialog.
-
-Resolve colors through `terminalThemeFor(AppTheme.palette.value,
-terminalThemeStore.value)` from
-[`terminal_theme.dart`](../lib/terminal/terminal_theme.dart). Use its background,
-foreground, cursor, selection, and semantic colors. Derive muted text from its
-foreground; hardcoded white fails on other terminal schemes.
-
-Use the same thin frame as an active pane:
-`terminalPaneBorder(focused: true)` and `kTerminalCornerRadius` from
-[`box_chrome.dart`](../lib/widgets/box_chrome.dart). Keep the surface flat, with
-no elevated cards, pill controls, or decorative shadows inside it.
-
-Cmd-O and Cmd-P use one unfilled, borderless text line with a thin, two-pixel caret.
-Align its editable text with the result titles. Previews use the same text
-metrics and blank-row spacing; warnings are readable text in semantic colors.
-
-Cmd-P opens with no selected row. The preview area shows the type hints as plain,
-muted text: `@ machines`, `# projects`, `: models`,
-`* store`, and `> commands`.
-Each hint is also a plain-text button: clicking it inserts the prefix into the
-same editor and keeps typing focus there. Selected harnesses open with Enter.
-Machines use Enter to **Manage**: focus moves to their controls without invoking
-one. Models use five sections: **Subscriptions**, **APIs**, **Your models**,
-the downloads, and **Shared with you**. Headers are plain muted text and never
-take selection. Put **[ Add ]** within APIs. Your models puts downloaded models
-first, followed by models served on the user's machines. The downloads are
-headed with the machine they are for and its memory (`Get for this Mac · 64 GB`),
-and a machine with nothing to download has no such heading. Where a model
-shares memory with everything else (a Mac's unified memory, or system RAM with
-no GPU), only models that fit half of it with a coding agent's 64K context are
-offered, and the other half stays for everything else it runs; an NVIDIA
-card's free VRAM is the model's own, all of it. They are ordered for a
-coding agent on that machine: quants of 3 bits or more first, then the ones the
-catalog estimates at 20 tok/s or more, then bigger models first, then the
-catalog's own (popularity) order — with one version of each model before any
-second: its MTP, QAT or pruned variants, and fine-tunes sharing its MoE shape
-(`35B-A3B`) or its size and speed. Safety classifiers are never offered. The
-list shows the first five;
-the rest stay behind **[ More models (N) ]**, where Enter
-expands them in place and selects the first catalog row, and **[ Show fewer ]**
-collapses them. The catalog never offers another quantization of a model the
-machine already has. Explicit searches also include matching catalog models.
-A model row names its model alone; the quantization is in the preview, and on
-the row only when two versions of one model share a name. Ahead of its last
-word a model of yours lines up two columns, its size and its speed (measured
-while it runs, else the catalog's estimate, `~10 tok/s`); a list too narrow to
-keep the name readable drops them. Shared rows show only
-the model and sharing machine's label, separated by ` · `. An API heads its models:
-`▸`/`▾` before its name says whether they are listed, and the end of its row says
-how many (`378 models`) or `Tools` for one no harness can run on. Its models
-stay folded until Enter on its row, and explicit searches include matching ones,
-always under their own API and never interleaved with another's. Model rows are
-indented under the API's name, show only the model, and say **Use** for a
-harness on this computer. Filtering
-preserves the groups.
-
-A plain right-aligned **Use** identifies a model the current pane can use;
-**Get** identifies a model that can be downloaded. A model of yours says what
-Enter does unless something is happening to it (**Downloading**, **Starting**),
-and the one the pane is on says **● In use**. Only a live row's word is green —
-running, in use, or under way; an action is plain, a failure a warning. Get on
-a model the pane can run downloads it, starts it and moves the pane onto it in
-one step, with the hint following it (`Downloading 42%…`); closing the picker
-stops the switch, never the download. Other model rows are dimmed,
-remain selectable for inspection, and have no action badge. Enter does nothing
-on these rows; it must never silently become Manage. Show the reason in the
-preview when it helps. Subscription names include the account label; only an
-account compatible with the current harness and available on its machine can
-say Use. Include actionable labels in accessibility text.
-
-From a live harness, both Cmd-I and Cmd-P's model scope use Enter to **Use** a
-served model, installed local model, or compatible subscription. Starting
-installed weights happens once; progress stays in the picker, and the pane
-switches only when the model is served. Closing the picker cancels the pending
-switch while startup continues on its host. **Get** prepares an undownloaded
-model on its host and stays in the picker. Pin selection to the pane that
-opened it; changing focus must never switch another pane's model.
-
-Cmd-N, Cmd-P, and Cmd-I share pane navigation: **Tab/Shift-Tab switch between
-the left and right panes**, without selecting a value or running an action.
-**Up/Down move within the active pane**: fields or choices in Cmd-N, results or
-controls in Cmd-P. **Enter activates the highlighted item**. In Cmd-N, Enter
-on a field opens its choices; Enter on a choice applies it and selects New
-Harness. Tab returns to the same field without applying a choice. In Cmd-P, Enter on a usable model
-uses it, on a Get row gets it, on a machine enters management, and on a harness
-opens it. Arrow keys walk controls while the right pane owns focus; they must
-not change the resource behind them. Left/Right retain normal cursor movement
-in text fields, and move between adjacent buttons. Enter/Space activate focused
-buttons. An inline form with text fields (Cmd-P's API editor) is the one place
-Tab stays inside the pane: it walks the fields, then reaches the buttons, and
-the next Tab leaves for the list; Shift-Tab walks back and leaves from the
-first field. Escape backs out of an inline form, then returns to search while
-preserving the query and selection. Hints use the live keymap. Only the active
-pane shows a selection highlight.
-Typing selects the first match and replaces the hints with its preview. Arrows
-and pointer movement can also select a row. A pointer cannot change the resource
-while its management controls own keyboard focus. Clearing the root search returns
-to the hints; live inventory updates must not choose a row for the user. Enter
-does nothing until a row is selected. Keep the input and list in place throughout.
-Cmd-P has no New Harness row, including in machine and project harness lists.
-Cmd-N opens creation. Resource setup rows use general guidance rather than
-presumed defaults.
-Page Up/Down pages the result list; Shift-Up/Down scrolls the preview by one
-measured terminal row. These keys preserve the input's focus and query. Preview
-scrolling keeps the selected result and result-list scroll position unchanged.
-
-Cmd-Shift-P opens this same picker with editable `>` text. Commands and `?` help
-keep the same input, frame, terminal metrics, and two-pane arrangement as Cmd-P;
-changing a prefix must not replace the editor or move it. Command names occupy
-one row with their live shortcut aligned right. The preview shows the selected
-command's name, category, and shortcut, without session-text placeholders. Empty
-matches clear the preview. Omit the older title/count row and key-hint footer.
-
-![Commands in the shared terminal picker](images/terminal-search-commands.png)
-
-Open dialogs must follow live terminal font and theme changes while preserving
-the input controller, query, selection, focus, and scroll state. Wire the font,
-palette, and terminal-theme dependencies as the reference dialogs do. Settings
-come from Harness's own Terminal preferences, not Apple Terminal or iTerm.
-
-## Keep the terminal interaction
-
-Cmd-N opens a compact, centered key/value form with Agent, Project, collapsed
-Options, and `New Harness` selected. Enter launches with the displayed
-settings. Options expands Model, Approvals, applicable Profile, Branch, and Worktree
-as consecutive rows without internal blank rows. Machine is selected with Project. Keep a blank row between Agent and Project and before Options.
-Worktree uses `[x]` / `[ ]`. There is no duplicate summary pane.
-Project shows the committed machine and full path, such as
-`M2:~/code/autonomous-harness`. Browsing the chooser never changes this value
-until a choice is accepted.
-
-![Compact New Harness form](images/terminal-new-harness-compact.png)
-
-Reserve nine columns for labels and two blank columns before values. The launch
-action follows the last visible field with exactly one blank row; never pin it
-to the bottom with a flexible spacer. The form and chooser use whole character
-columns and rows. The form fits its visible rows, stays centered, and keeps its
-geometry when choices appear beside it. The chooser starts directly with its search line;
-omit a redundant back/title row such as `< Agent`.
-
-Up/Down selects a field and automatically reveals its small chooser to the
-right. Navigation still belongs to the form. Right, typing, or Enter moves
-focus into the chooser; then Up/Down moves its choices. Enter accepts a value,
-closes the chooser, and selects New Harness, ready for the next Enter to launch.
-A held Enter must not accept and launch in one keypress. Escape discards the
-search and returns to the form in one step; Left also returns when the search
-is empty. Nested project and specialized-agent steps retrace their choices.
-On narrow windows, the active chooser replaces the form on the same column with
-enough rows for its list. Returning restores the compact form. Validation messages
-get whole rows of their own so neither the explanation nor the choices are clipped.
-
-Fresh Cmd-N uses the last successfully launched agent, the last used project
-on the local machine, the local machine, branch `main`, and Worktree Yes for a
-Git project. Model shows the selected model name, or OpenAI / Anthropic when
-the subscription agent has not reported a model. Approvals starts at Auto-approve.
-Focused panes and canceled edits do not change these defaults; unresolved
-launch receipts remain recoverable. An explicit split can inherit its source.
-If a required value is unavailable or uncertain, explain it and require a
-choice. Never substitute another branch, project, agent, or profile, or turn
-Worktree off after a worktree creation failure.
-
-Agent offers Codex, Claude Code, Terminal, and specialized harnesses together.
-Keep agent choices to one line. A direct agent completes the choice. A specialized harness such as Blender
-uses `Run Blender with` as the search hint, offering compatible coding agents
-with its remembered choice selected. The Agent value then reads
-`Blender · Codex`.
-
-![Blender runner chooser](images/terminal-new-harness-runner.png)
-
-Project searches existing `machine:project` pairs across the inventory; names,
-machine names, and paths are searchable. Put local projects first before a
-search, and dim unavailable destinations with a short reason. Selecting a
-project commits both its machine and folder. New Folder, Open Folder, and Clone
-Repository first ask for a machine (local selected), then a name, path/browser,
-or repository URL. Escape retraces these steps. Searching or moving the
-highlight never creates a folder or starts a harness.
-
-Arrows navigate the active choices; Enter accepts the current choice; Escape
-goes back or dismisses according to the existing workflow. An editor still
-accepts ordinary text, including `j` and `k`. Preserve composition, paste,
-readline editing, remapped shortcuts, and mouse access.
-
-Opening, searching, previewing, and cancelling must not send input to an agent,
-start a process, or resize/recreate the underlying terminal. Return focus to the
-workspace on dismissal. Search navigation should keep typing focus in its
-editor, and a stationary pointer must not steal the keyboard highlight.
-
-Keep lists virtualized and retain cached row controls. Arrow movement updates
-the old and new highlights; it should not rebuild the editor or whole catalog.
-Calculate reveal and paging from the actual measured item extent.
-
-## Share an agent
-
-Share follows the Cmd-N form: the agent name, aligned Access and People fields,
-collapsed Options, and Copy link selected. Access opens Private/Public choices
-beside the form. Browsing choices never changes access; accepting one applies it
-and returns to Copy link. People owns an email editor and the existing invitations.
-Options reveals invitation expiry, Comments, and Stop sharing. Expiry applies
-to new email invitations, not to the public link. Keep online guidance visible.
-Up/Down move within a pane, Tab switches panes, Enter accepts, and Escape backs
-out or dismisses. Narrow windows replace the form with the active chooser.
-Opening or cancelling the form alone never changes permissions or creates a link.
-
-![Compact Share form, rendered with synthetic data](images/share-form-compact.png)
-
-![Public and private choices beside the same form](images/share-form-access.png)
-
-## Review a dialog change
-
-Check the result with the user's terminal font and colors, an alternate scheme,
-enlarged text, and a narrow window. Look for a one-line highlight, aligned
-columns, intact text, plain controls, and no layout jumps. Exercise typing,
-selection, acceptance, dismissal, scrolling, and focus restoration. Check live
-font/theme changes while the dialog is open.
-
-Reuse the relevant existing checks:
-
-- [`new_harness_grid_test.dart`](../test/new_harness_grid_test.dart): row and
- column alignment, selection ownership, and scaling.
-- [`open_picker_rendering_test.dart`](../test/open_picker_rendering_test.dart):
- pane/dialog appearance, one-line selection, no logos, and virtualized traversal.
-- [`swarm_search_render_test.dart`](../test/swarm_search_render_test.dart):
- cached rows, query updates, theme changes, and focus.
-- [`swarm_search_preview_test.dart`](../test/swarm_search_preview_test.dart):
- preview navigation and narrow layouts.
-- [`keymap_runtime_test.dart`](../test/keymap_runtime_test.dart): shortcut
- routing and focus ownership.
-- [`share_harness_test.dart`](../test/share_harness_test.dart) and
- [`share_toolbar_test.dart`](../test/share_toolbar_test.dart): sharing flows,
- cell layout, responsive draft preservation, shortcuts, and focused-agent scope.
-
-When checking a native build, restart into the rebuilt app before judging the
-result. An existing process does not pick up a new build automatically.
-
-## Manage machines and models inside Cmd-P
-
-Place compact facts and controls together at the top of the preview. This
-computer has `[ Password ] [ Rename ]`; remote machines have `[ Connect ]
-[ Rename ] [ Delete ]`, with Connect only when linking is needed. Password opens
-the password form alone. Delete retains the account-removal confirmation. Show
-connection state, harness count, and real CPU/RAM readings; refresh resource
-readings while the machine picker is visible and the app is in the foreground.
-Do not add a View harnesses, Linked machines, Refresh, or Actions button to this
-management pane. Keep the controls on one row, wrapping only when needed.
-
-Connect, Rename, Password, and Delete edit or confirm **inside the right pane**;
-never cover Cmd-P with a second dialog. Keep the search and machine list in
-place. Cancel/Escape returns to the selected machine's controls. Pending
-operations survive closing their editor, and errors stay beside the fields.
-Deletion and password clearing start with Cancel focused.
-
-With no machine name typed, order machines by the next useful action: online
-machines needing a connection, this computer, other connected machines, then
-offline machines. Sort names naturally within each group. A live status change
-may reorder rows but must preserve the selected machine's identity. Typed
-queries retain match relevance. Put **Add machine** after the machine rows.
-It explains installation on the other computer, sign-in to the same account,
-and setting its password. App and CLI open their setup instructions in the
-same right pane; copying CLI commands never executes them on this computer.
-
-Local models show their name with quantization once, host and model-file size,
-and measured tokens/sec and request count with its period when available.
-Include inventory from every connected, linked machine in the account. Resolve
-Grid hostnames through the hostname on the Harness machine record, then use
-that machine's own model IDs and capabilities for controls. Display its Harness
-name (for example, M2), and keep its Grid hostname (mac.lan) searchable. Unlinked,
-offline, unknown, and shared hosts must not inherit another machine's controls.
-Reuse existing operation progress/failure labels; omit redundant normal-state
-labels such as Available. Show quantization once beside the name when known,
-including quantization explicitly present in an imported GGUF filename. Do not
-guess it from the model family or file size.
-
-Local models have one contextual button: **[ Get ]** before download,
-**[ Use ]** when installed and startable, or **[ Stop ]** when an owned process
-can be stopped. A running model's list action remains Use; Stop requires
-activating its button. Unavailable actions are dim and cannot receive focus.
-On hosts that support a separate download, Get only saves the files. Older
-hosts prepare models through their existing combined download/start action;
-explain `Downloads and starts on <machine>.` before Get. Use starts installed
-weights when necessary, then selects the model for the original harness.
-
-API provider selection, credential editing, validation, saving, and deletion
-stay in the picker's right pane. Keep keys masked by default; do not return
-stored secrets to the editor. Errors and progress appear in place. Leaving a
-pending form must not let its eventual reply reopen it or change the selection.
+# Desktop dialog behavior
+
+Use the [desktop design system](desktop-design-system.md) for presentation.
+This file retains the interaction and data-integrity contracts from the former
+terminal-dialog specification. Fixed cells, one-line-only selection, mandatory
+monospace, bracket buttons, ASCII checkboxes, and terminal-colored modal frames
+are retired for app UI. Older screenshots are historical evidence only.
+
+## Shared ownership
+
+Reuse the existing controllers, launch paths, and draft stores. Cmd-N and the
+full-page welcome use the same form. Cmd-P scopes use the same query editor,
+result selection, and resource preview. Styling must not fork their behavior.
+The detailed creation contract is [new-harness-entry-rules.md](new-harness-entry-rules.md).
+
+Fresh creation uses saved successful choices on the local machine. Explicit
+Store/split requests and restored drafts retain their own destination and
+reviewed values. Never substitute another branch, folder, agent, or profile,
+or disable Worktree after a failure. Browsing options does not commit them.
+Searching and highlighting never creates a folder or launches a harness.
+A held Return cannot accept a choice and launch in the same keypress.
+
+The popup's main form closes through its explicit Close action. Child menus
+may dismiss on outside click or Escape and return to the same draft. New Tab
+has no Close button on its form. Successful creation uses its existing tab
+placement. Preserve pending launch receipts and duplicate-start guards.
+
+## Keyboard and focus
+
+Resolve shortcuts from the live keymap. Normal text, including j and k, stays
+text. Preserve paste, readline editing, input composition, and remapping.
+Enter/Space activate the focused control; Enter in the task submits according
+to the existing form rule. Composition confirmation is never submission.
+
+Search keeps focus in its editor while navigating results. Tab traverses
+controls and existing list/preview regions. Inline editors keep traversal in
+fields until the final action, then return to the surrounding view. Escape
+backs out of nested editing before dismissing a surface. Page navigation uses
+the rendered row extents. Focus returns to the trigger on dismissal.
+
+A stationary pointer does not steal keyboard selection. Live inventory updates
+do not pick a result or switch the resource being edited. Opening, previewing,
+or cancelling UI cannot send input to an agent or recreate a terminal.
+
+## Search and resources
+
+The empty query searches harnesses. Editable prefixes and clickable scopes
+remain: machines, projects, models, Store, and commands. Keep one editor and
+stable geometry across scopes. Cmd-N creates; Cmd-P has no duplicate New Harness
+result. Empty matches clear the preview. No row selected means Enter does nothing.
+Unavailable sessions retain their saved preview and show the actual reason;
+click/Enter cannot open them until available.
+
+Commands use their real names and current shortcuts. Results remain virtualized;
+query changes and highlights do not rebuild the whole catalog. Selection is
+identified by stable resource identity through inventory changes.
+
+Machines keep Connect/Password, Rename, and Delete in their existing management
+preview. Inline changes do not cover search with a second dialog. Cancelling
+returns to that machine's controls. Pending requests survive editor dismissal;
+late responses cannot change a replacement editor. Destructive confirmations
+start with Cancel focused. Show real resource readings and availability.
+
+Before a machine search, prioritize online machines needing connection, this
+computer, other connected machines, and offline machines. Preserve selected
+identity across reorder. Add machine remains available after the list and
+explains setup on the other computer. Copying an installation command does
+not execute it here.
+
+Model groups retain Subscriptions, APIs, Your local AI models, and Shared with
+you. API model disclosure, matching within groups, compatible subscriptions,
+and local catalogs retain their current behavior. Get downloads/prepares;
+Use starts when necessary and selects for the original harness; Stop explicitly
+stops an owned process. An unavailable row stays inspectable without activation.
+Closing the picker cancels its pending model switch, not startup on the host.
+Never transfer another machine's capabilities to an unknown/shared host.
+
+Show real sizes, quantization, throughput, and request periods only when known.
+Keys stay masked; provider credential editors never read stored secrets back
+into a field. Resource errors and progress appear beside the affected controls.
+
+## Sharing
+
+Keep the selected agent, committed access, people, invitation expiry, comments,
+and stop-sharing controls in the same flow. Browsing access options does not
+change permissions. Opening or cancelling alone does not create a link.
+Expiry applies to new invitations, not public links. Pending requests and
+errors retain their existing scope and protections against stale completion.
+
+## Verification
+
+Review dark and light appearances, narrow windows, enlarged text, long labels,
+loading/errors, missing resources, mouse and keyboard, composition, and live
+updates. Use the relevant existing creation, placement, sharing, search,
+resource, keymap, and lifecycle suites. Replace tests that enforce retired
+presentation with checks of the new visible behavior while retaining safeguards.
+
+After a native build, restart the app before judging it. Use synthetic data for
+saved screenshots. Coverage gates measure executable lines, not every possible
+interaction. Physical native IME and VoiceOver require their own verification.
diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.md
index 58598278d..05356f4c2 100644
--- a/desktop/design/terminal-workspace.md
+++ b/desktop/design/terminal-workspace.md
@@ -1,159 +1,57 @@
-# Terminal workspace design system
-
-Use the [product terminology](../../docs/terminology.md): a swarm groups harnesses;
-a harness is one running agent session.
-
-Harness should feel like a terminal workspace, from its tab bar to its welcome
-page, dialogs, and contextual controls. **Text first. Keyboard first. Fixed
-cells.** Use this document for new workspace surfaces and visual reviews.
-
-The [terminal dialog rules](terminal-dialogs.md) specify row and column geometry,
-selection, input, and preview behavior. The [workspace status bar rules](workspace-status-bar.md)
-specify tabs, pane headers, focused context, and model selection. Those documents
-are the detailed implementation references for this system.
-
-## Text is the interface
-
-Use meaningful names and familiar terminal punctuation. Menu actions such as
-`New Harness` use plain text and the same row highlight as other choices.
-Standalone actions can use brackets, such as `[ Customize Harness ]`, instead
-of rounded buttons with pictograms. A checkbox is
-`[x]` or `[ ]`. Harness search has no prefix; `#` selects projects and `>` selects
-commands as editable text. `@`, `:`, and `*` scope machines, models, and Store
-inside the same picker. The top row keeps swarms, `+`, a plain search icon, the
-notification bell, and the rounded Harness Store button. When enabled in
-Experimental settings, the illustrated daemon sits after Store at the far right;
-its hover portrait is a deliberate artwork exception to text-first chrome. The bottom row holds focused
-machine/repo/branch/PR links on the left and the model selector on the right.
-Keep descriptive tooltips and accessible names. Search and bell are deliberate
-icon exceptions; the bell shows a count only when there is something to see.
-Store restores its colorful polymath mark and a quiet filled pill. The bottom
-context has no separate background or divider.
-
-There is no broadly understood ASCII pencil. Keep `[ Customize Harness ]` after
-customization as well as before it. The same action should retain its name and
-location; a saved background must not silently replace it with an unlabeled icon.
-Over artwork, a flat backing may protect text contrast. Do not add a pill,
-bordered button well, logo, emoji, or ornamental icon to workspace controls.
-User content and embedded viewers retain their own visual language.
-
-## Keyboard is the primary path
-
-Every workspace action needs an existing command or a clear keyboard interaction.
-Cmd-S opens the Store tab, Cmd-M opens Machines (`@`), and Cmd-I opens Models (`:`).
-History remains available from its menu without a default shortcut. Cmd-Y and Cmd-U
-have no default workspace action. On macOS, Minimize remains available from the
-yellow window button and the Window menu; Cmd-M belongs to Machines inside Harness.
-Resolve shortcut hints from the live keymap. Cmd-N creates a harness, Cmd-O opens projects (`#`), Cmd-P searches harnesses, and Cmd-Shift-P opens
-commands (`>`) in the shared picker. Cmd-I opens models with `:` already entered;
-typing Shift is unnecessary. From a live harness pane, Enter uses a served or
-downloaded model for that pane, starting installed weights when necessary; Tab
-switches between the list and controls. In Cmd-N, Tab switches between fields
-and their choices. Up/Down navigates the active pane and Enter activates.
-Cmd-P's model scope uses the same behavior. Cmd-T opens a swarm, Cmd-W closes a swarm, and
-Cmd-Shift-W closes the focused pane view. Cmd-Q quits the app. Enter activates,
-Space toggles, and Escape backs out or dismisses.
-
-Closing a pane removes its view immediately, without a minimize animation.
-
-Keep mouse access useful without adding duplicate floating controls. Clickable
-text shows a hand cursor and bold text on hover, press, and keyboard focus.
-Preserve the underlying colors, including filled status segments. Reserve both
-text weights during layout so emphasis never shifts neighboring controls.
-Resting controls stay unboxed, except the optional Share action: its flat
-primary accent fill makes collaboration visible in the bottom row, before the model.
-Settings → Experimental → Share button enables it; it is off by default.
-Tooltips describe the
-action, not merely the text. Omit a tooltip that repeats the visible name;
-show the full name when truncated, or a different underlying name. A model
-selector says `Switch model · Subscription or local models`; include its full
-model name only when shortened or temporarily replaced by a switching label. Disabled controls must not advertise an available
-action or receive keyboard activation. Preserve accessibility names and focus
-restoration; terminal styling is not permission to replace real controls with
-inaccessible painted text.
-
-## Use a real character grid
-
-Measure columns and rows through `terminalCellSizeOf(context)` for dialogs and
-welcome content. Text, margins, choices, and scrolling follow those dimensions.
-Dialog selection highlights exactly one text row. Keep fixed font metrics when space
-gets tight; truncate long values or reduce the number of visible columns.
-
-Persistent tab, status, and pane bars use `workspaceBarTextStyle()` and
-`workspaceBarCellSizeOf(context)`: 13 pt SF Mono regular on macOS and the platform
-monospace stack on Linux, independent of terminal zoom. Every bar control uses
-same minimum click height: `workspaceBarControlHeight()` (28 pt). The active tab
-fills the entire bar height with the workspace background color, joining the
-content below; selection keeps regular text and adds no `*` marker. Hovering a
-tab uses bold text like other bar controls. No rounded corners, ripple, or
-separate model-label well. Dialogs and welcome
-actions use `terminalContentStyle()` and follow the terminal font preference.
-
-## Keep surfaces quiet
-
-First launch uses the same New Swarm page as every later visit: “Harness like a
-boss.” followed by five clickable shortcuts: Start a harness, Manage all your
-harnesses, Deploy a local model, Manage all your machines, and Build beyond code.
-Resolve the shortcut hints from the live keymap; unbound actions remain clickable.
-Keep this page independent of onboarding progress; no checklist or automatic dialog.
-
-![Shared first-launch and New Swarm welcome](images/workspace-welcome.png)
-
-Use terminal foreground, background, muted text, and selection colors. Workspace
-dialogs use the same thin frame as a focused pane. Avoid raised cards, shadows,
-rounded action pills, and redundant headings. Tabs use concise text labels, with
-selection conveyed by background rather than bold type.
-
-The selected harness's terminal and its viewers stay at full contrast together;
-other harnesses receive a 30% neutral-gray
-veil (`#9D9D9D`) over their header and content, lifting dark backgrounds while
-softening text. In the default Graphite palette, inactive backgrounds render as
-`#404040` (RGB 64, 64, 64). Selection follows the existing click and keyboard
-focus actions. Selecting either the terminal or its viewer keeps both clear;
-the focus ring and keyboard input still belong only to the selected pane.
-Match viewers to their owner on the same machine. Keep the current harness clear
-while a menu or the tab strip temporarily owns keyboard focus. A single or zoomed
-pane stays clear.
-Waiting-question borders paint above the veil, at full strength.
-This is a paint treatment: retain terminal state and let the first click reach
-the pane underneath.
-
-![Selected center pane at full contrast, with synthetic terminal content](images/workspace-pane-focus.png)
-
-Status layouts and terminal palettes are separate choices. **Plain** always uses
-the terminal foreground for context text. PR state icons keep their distinct
-green/purple/red/gray colors when Color is on, including in Plain. In Powerline
-layouts, that state color fills the final joined block, with contrasting icon
-and number inside. Shell layouts use the terminal's
-ANSI colors. The named Pastel Powerline, Catppuccin Powerline, Tokyo Night, and
-Gruvbox Rainbow presets carry their own status-only colors, resolved in the
-shared status formatter for both Flutter and AppKit. Color off makes any preset
-monochrome. Branch symbols and separators are drawn vectors so users can keep
-their normal monospace font. Do not invent runtime facts, Git dirtiness, exit
-status, or progress to decorate a theme.
-
-## Make context useful
-
-Show the focused pane's model, machine, compact project name, branch, and PR in the
-bottom status bar. A dependent viewer uses its owner's context. Keep internal
-worktree paths and machinery out of everyday labels.
-
-Machine opens the shared picker scoped to that machine. Project opens its harnesses across
-known checkouts and machines. With session Git context, Branch opens Branches and pull requests: checked-out and recorded branches,
-with PR history. Temporary checkout paths stay out of these labels and details.
-Older daemons keep exact-branch project search. Hide detached commit hashes from
-the bar. Multiple branches or unavailable Git data use plain context text, without a
-branch symbol. These are navigation actions; they do not check out a branch.
-The PR label opens that PR. Each field gets its own accessible link, tooltip, and
-the shared hover treatment, including in joined Agnoster segments.
-
-## Review in context
-
-Check keyboard-only operation, hover, focus, disabled state, narrow windows,
-long names, missing Git data, a dependent viewer, light and dark palettes, and
-terminal font changes. Opening or dismissing controls must not send input to an
-agent or recreate its terminal. Use synthetic data for screenshots.
-
-Start with `TerminalTextAction`, `WorkspaceBarControl`, `WorkspaceStatusLine`, and
-the Cmd-N/Cmd-O reference implementations. Native macOS controls must match the
-Flutter fallback in behavior and appearance.
+# Terminal workspace boundaries
+
+The [desktop design system](desktop-design-system.md) governs all app UI around
+the panes. It replaces this document's former fixed-cell and text-only rules
+for welcome pages, forms, dialogs, pickers, menus, and buttons. Historical
+screenshots show prior iterations and are not a presentation specification.
+
+## Preserve the terminal
+
+Terminal output, direct keyboard input, the in-pane composer, and in-pane find
+remain terminal-native. Keep the selected terminal font, palette, exact content,
+scrollback, selection, and input behavior. Real code, paths, and logs may use
+monospace elsewhere when it helps readability.
+
+Do not recreate, resize, or send input to a terminal merely because app chrome
+opens or closes. Preserve terminal ownership, pending streams, viewer-owner
+relationships, and pane state. Closing a pane removes its view immediately.
+
+## Keep the workspace structure
+
+Tabs remain compact and content-sized, adding one at a time until the row fills.
+Preserve Command-number navigation and established working/question/done/failure
+marks. Idle does not need a mark. Motion represents actual work and respects
+Reduce Motion. Keep the top global actions compact and the Store button familiar.
+
+The footer shows remaining subscription usage on the left. Its right-hand context follows the focused pane: machine, project, branch, and PR
+at the right. Each pane header shows its model immediately before an always-visible
+close icon. Clicking the model opens the shared Models picker for that harness;
+the footer does not repeat model or effort. Do not show worktree implementation
+paths in everyday labels. User-selected shell/Powerline status styles remain
+available, including PR state colors and the option to disable color.
+
+Machine opens its scope, Project opens related harnesses, Branch opens the
+existing branches/PR history, and the PR opens its URL. These are navigation,
+not checkout actions. Missing data stays honest. Dependent viewers use their
+owner's context. See [workspace-status-bar.md](workspace-status-bar.md) for
+behavior and data rules; the desktop design system controls presentation.
+
+## Focused panes
+
+The selected pane stays at full contrast. Other visible panes receive the
+approved 30% neutral-gray veil; Graphite's inactive background is RGB 64,64,64.
+A single or zoomed pane stays clear. Existing click and keyboard focus actions
+own selection. Keep the current pane clear while a menu or the tab strip has
+keyboard focus. Waiting-question borders remain visible above the veil.
+The overlay does not consume the first click or alter terminal state.
+
+## Input and review
+
+Retain existing commands and their live remapping. Menus and visible controls
+make those commands discoverable without requiring a shortcut lesson. Text
+editors retain ordinary editing and composition. Disabled actions do not activate.
+
+Review narrow windows, long names, terminal font changes, alternate terminal
+palettes, dependent viewers, missing Git data, and light/dark app appearance.
+Opening or dismissing desktop UI must return focus correctly and never type
+into an agent accidentally. Use synthetic terminal content for saved previews.
diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.md
index 59b04bd09..10afb82db 100644
--- a/desktop/design/workspace-status-bar.md
+++ b/desktop/design/workspace-status-bar.md
@@ -1,29 +1,27 @@
# Workspace status bar
-Use the [product terminology](../../docs/terminology.md): a swarm groups harnesses;
-a harness is one running agent session.
-
-A navigation row above the panes and a 37.5 pt status row below them, using compact
-monospace text and measured character cells.
-Follow the [terminal workspace design system](terminal-workspace.md).
+A navigation row above the panes and a 37.5 pt status row below them. Tabs use
+system type; status fields use the selected workspace monospace face.
+Follow the [desktop design system](desktop-design-system.md) and
+[terminal workspace boundaries](terminal-workspace.md). Historical captures below
+illustrate data and interaction rules, not the current tab geometry.
```text
-1:api ? 2:web ⠹ 3:blender ✓ + Search Bell (✿ Harness Store)
+api ? web ⠹ blender ✓ + Search Bell (✿ Harness Store)
panes
-M2 > openharness > branch-name > #439 GPT-6 Astra · Max
+Claude 0% Codex 50% M2 > openharness > branch-name > #439
```
-![Top navigation and bottom context, rendered with synthetic data](images/workspace-bottom-bar.png)
+The context follows the focused pane. The branch stays clickable in the
+footer; pane headers do not repeat it. Empty New Tabs have no footer.
The optional Experimental creature sits after Store in a fixed 44pt slot.
Tim and eggs use bundled bitmap art; hovering opens a full-size preview without
changing focus. The slot reserves no space when disabled. See [daemons](daemons.md).
-## Swarms on the left
-
-Each swarm shows its number and a compact name. A user-entered name always wins:
+Each tab shows a compact name without a permanent number prefix. A user-entered name always wins:
once renamed, keep it across pane changes, closing/reopening, and saved layout
restores. Use automatic naming only when `nameIsCustom` is false. Custom-named
tabs do not vote in the automatic-name comparison. Count independent
@@ -35,17 +33,19 @@ Ties within one trait use pane order. Focus does not affect the name.
This keeps `blender` useful beside coding tabs, uses project names when all work
is code, and uses machine names for the same project on different computers.
-Tabs with identical contents can still share a name; their numbers distinguish
-them. Preserve the full name for inspection when its visible label is truncated.
-
-Center the text with one cell of padding on each side. Size each tab to its label
-and activity mark, capped at 24 cells. Keep the remaining space after `+` empty
-for dragging the window; adding tabs fills that space one by one. Tabs never
-stretch to fill the row. Scroll overflow when needed, revealing the selected
-tab on keyboard navigation. An exceptionally narrow viewport may show a smaller
-tab, preserving activity marks before truncating names.
-There is no close button or reserved close-button space. Cmd-W closes the active
-tab; preserve remapped shortcuts, native menu access, and middle-click closing.
+Tabs with identical contents can still share a name; their positions distinguish
+them, and holding Command reveals their actual shortcut hints. Preserve the full name for inspection when its visible label is truncated.
+
+Center each name and its adjacent status as one group in compact, content-sized
+tabs, capped at 240 points. An idle name centers on its own. Use the
+shared 10-point upper corners, 8-point outward lower shoulders and 6-point top
+inset. Keep space after `+` available for dragging the window. Scroll overflow
+and reveal the selected tab on keyboard navigation. Narrow viewports can show
+smaller tabs while preserving their controls.
+The right accessory reveals × on hover. While Command is held, the actual
+shortcut replaces the status beside the name without changing the tab width.
+Hover never moves the title. Cmd-W, remapped shortcuts, native menu access,
+and middle-click closing remain available.
Preserve reorder, rename, keyboard focus, and terminal sessions. Cmd-T opens a
swarm. Cmd-O opens the shared picker with `#` for projects; Cmd-P opens it directly
on harnesses. Cmd-Shift-P opens commands (`>`). The projects list has
@@ -53,29 +53,27 @@ no New Project/Open Folder row. Projects with an open pane in any tab come first
each group is alphabetical. Pane focus and navigation history do not change that
order. Cmd-Q retains its native Quit action.
-Tabs, status fields/symbols, PRs, and model labels and pane close actions share `WorkspaceBarControl`
-in Flutter and the same native draw metrics: 28 pt minimum click height and
-bold text on hover, press, and keyboard focus, with a hand cursor. Preserve the
-underlying colors, including Agnoster segment backgrounds and joins. Reserve
-both text weights during layout so labels and ribbon shapes never shift.
-The active tab fills the entire bar height with the workspace background color,
-joining the content below. Its resting text stays regular; do not add a `*`
-marker. Keep text centered, with no ripple or rounded button well.
+Status fields, PRs, model labels and pane close actions share
+`WorkspaceBarControl`: 28-point minimum click height, a hand cursor and emphasis
+on hover, press and keyboard focus. Preserve selected status colors, backgrounds
+and joins; reserve both text weights so labels never shift. Tabs use
+`DesktopWorkspaceTab` and matching AppKit metrics, with a selected shape joining
+the workspace. See the design system for their system type and surface colors.
![Agnoster PR hover and a selected tab joining the workspace, rendered with synthetic data](images/workspace-bar-hover.png)
-Do not show a tooltip that repeats a visible tab name (the numeric prefix does
-not make it a different name). Show a different underlying name or the full
-label when it is truncated. Keep action hints on symbols and status links.
+Do not show a tooltip that repeats a visible tab name. Show a different underlying
+name or the full label when it is truncated. Keep action hints on symbols and
+status links.
-The new-tab `+` uses a plain-text control: no resting
-box, with bold text on hover or keyboard
-focus. Keep its New Swarm tooltip and shortcut hint.
+The new-tab action uses the shared plus icon, with no resting box. Hover and
+keyboard focus increase its emphasis without changing the glyph or its bounds.
+Keep its New Tab tooltip and shortcut hint.
### Harness activity
-Use hn's activity states in two existing places: after the swarm name
-(`2:web ⠹`), and after the title in a pane header (`[engine] Harness name ⠹`).
+Use hn's activity states in two existing places: after the tab name
+(`web ⠹`), and after the title in a pane header (`[engine] Session name ⠹`).
Idle has no visible mark. Viewer headers show their owner's state. Shells, unknown agents, and
utility tabs have no harness activity mark. Keep the existing engine icon.
The mark replaces the native tab's old orange attention indicator; it adds no
@@ -109,7 +107,7 @@ two ASCII pipes at 65% font size with quarter-cell negative letter spacing:
short, thin strokes centered in the same cell. Keep native and Flutter metrics
in sync. The question mark stays plain yellow. Animate only the
mark, never the label, width, terminal, or method-channel payload. Long tabs
-shorten their names and scroll; preserve room for the number and mark. SF Mono
+shorten their names and scroll; preserve room for the accessory and mark. SF Mono
does not contain Braille, so Flutter explicitly falls back to the platform's
symbol font inside that fixed cell. Native text uses CoreText fallback.
@@ -126,33 +124,47 @@ acknowledgement, fixed geometry, visibility, and animation. Set
`HARNESS_ACTIVITY_CAPTURE_DIR` when running the workspace activity test to
capture synthetic Flutter screenshots and the native tab payload.
-Tab labels, status text, pane titles, and model selectors use **13 pt SF Mono,
-regular weight at rest** on macOS. Linux uses its platform monospace stack at the same
+Tab names use the **13-point system face**. Status text, pane titles and model
+selectors use **13 pt SF Mono, regular weight at rest** on macOS. Linux uses its platform monospace stack at the same
size. Use `workspaceBarTextStyle()` and `workspaceBarCellSizeOf(context)` from
`lib/shared/theme/workspace_bar_style.dart`; the native bar receives that same
font through `barStyle`. Keep this size independent of terminal zoom and avoid
an additional UI text-scale factor. Selection uses background color, not bold.
-Terminal content and dialogs still follow the user's selected terminal font
-and size.
+Terminal content keeps the user's selected terminal font and size. Desktop dialogs
+use the shared system-type scale.
![13 pt workspace bars with synthetic pane names](images/workspace-bars-13pt.png)
## Pane controls
-The bottom bar shows the focused harness's model selector at the right, with
-machine, project, branch and PR at the left. Pane headers keep the harness title and a hover-only ASCII `x` at their
-far right. The `x` closes that pane view, keeps its harness running, and uses the
-shared bold hover treatment. Its tooltip names Close Pane and the current shortcut.
-Reserve its width so revealing it does not move the title.
+Each pane header shows its model immediately before an always-visible × at the
+right edge. Tab and pane close marks share a small regular glyph (12-point
+Lucide, optically matched 10-point SF Symbol) and quiet 45% resting ink, with
+full ink on hover/focus and the existing larger click
+targets. The close control removes that pane view while keeping its harness
+running. Its tooltip names Close Pane and the current shortcut. Long model names
+truncate without moving or covering the close target. Clicking the model focuses
+that pane and opens the same unified Models picker as Cmd-:, preserving the
+existing target and availability guards.
+
+The footer shows remaining subscription usage on the left and the focused
+harness's machine, project, branch and PR at the right. It does not repeat model
+or effort. Read the same deduplicated account rows as Models: each percentage
+uses the limiting window and expires under the same rules. Different accounts
+remain distinct. Unknown usage shows “—”; exhausted usage shows “0%”. Hover
+explains remaining percentages and reset windows; click opens Subscriptions.
+Separate accounts with whitespace, without dot separators. Provider names stay
+neutral; only percentages carry warning ink: red at zero, amber through 20%,
+neutral above 20% or when unavailable. Resolve the same readable colors for the
+Flutter and native footers against the chosen workspace background.
+No account or usage reading is invented for this footer.
For the model label, prefer
its local model ID or the daemon's observed subscription model (`selectedModel`),
such as `GPT-6 Astra`, `Fable`, or `Opus`. Keep versions when reported; never infer
a version from a family alias. Older daemons fall back to the provider name.
-Append the reported effort in the same control, for example `GPT-6 Astra · Max`.
-Model and effort come from the same validated runtime profile and follow pane
-focus together. Missing effort stays absent; never infer it from a model or
-carry subscription effort onto a local model. Effort-only updates repaint too.
+Show only the model name in the header. The terminal presents its effort setting;
+never infer effort or append subscription effort to a local model name.
Keep this label visible without requiring hover, including while disconnected;
disable switching when the pane is read-only. Use a hand cursor, bold text on hover
and keyboard focus, and a tooltip explaining subscription/local switching.
@@ -174,7 +186,7 @@ access. Keep the resize gaps available for resizing.
Settings → Experimental → Share button is off by default on desktop and web.
The choice persists locally and updates the bar immediately; when off, no button
or space is reserved. [Settings reference](images/share-experimental.png).
-When enabled, Share sits in the bottom bar before the model selector, with a
+When enabled, Share sits in the bottom bar before focused context, with a
flat accent fill, white text, and the same fixed font and control height as the
other bar actions. Reserve its width before allocating context. Web keeps
Download app as a secondary text action in the same footer.
@@ -241,14 +253,15 @@ the window bottom. The former 9.5 pt pane gutter is part of the status row,
rather than extra padding only above it. Native and Flutter reserve 37.5 pt and
keep the same pane height, with equal space above and below the footer content.
-Show `machine project`, then `(branch)` and PR when known at the left. Put the
-focused model at the far right. The status row has one-cell outer gutters and no background fill or divider;
-its controls sit directly on the workspace surface. Both sides follow
-the focused pane; changing placement preserves each field's existing action.
-The optional companion and Share control sit before the model. At narrow widths,
+Show `machine project`, then `(branch)` and PR when known at the right. Put the
+remaining subscription usage at the far left. The status row has one-cell outer gutters and no background fill or divider;
+its controls sit directly on the workspace surface. The right side follows the
+focused pane; usage at the left covers all subscriptions independently of focus.
+Each context field preserves its existing action.
+The optional companion and Share control sit between these groups. At narrow widths,
truncate labels inside their allocated space rather than overlap controls.
-The model is a separate plain text control so switching themes preserves its
-click target. A focus change closes its picker; stale native actions and delayed
+The model control in each pane header keeps its click target when themes change.
+A focus change invalidates its selection target; stale callbacks and delayed
model selections cannot retarget a different harness.
Use the shared `AgentProject.label` rule: at a Git root, prefer the remote repo's
name, falling back to the local repo name; in a repo subfolder, use that folder's
@@ -403,8 +416,8 @@ References: [Zsh prompt parameters](https://zsh.sourceforge.io/Doc/Release/Param
[Agnoster](https://github.com/agnoster/agnoster-zsh-theme), and
[Powerlevel10k](https://github.com/romkatv/powerlevel10k).
-Pane headers keep task identity and the hover-only close action. The top bar
-contains swarms, New Swarm, a plain search icon, the bell, and the Harness Store button.
+Pane headers keep task identity, model selection and an always-visible close action. The top bar
+contains tabs, New Tab, a plain search icon, the bell, and the Harness Store button.
Search opens the existing unified picker; Store opens the existing Store tab.
The Store restores its earlier rounded pill, colorful polymath mark, and quiet
tinted fill. Its label is `Harness Store`, without brackets. Keep the full name
@@ -424,7 +437,7 @@ narrow windows. Native menus and commands remain available.
Only while daemons are on (the account's `GET /api/zoo` answered 200, or a
person enabled Settings → Experimental → Focus-bar creature), the daemon sits
-in the footer before the optional Share control and focused model. Off, or before that is known, nothing is
+at the left of the footer before the optional Share control. Off, or before that is known, nothing is
reserved for it and the bar is exactly the one described above; when it turns
on, the slot waits for a quiet moment (no button held, the pointer off the
footer) so controls never move under a click. On:
@@ -442,7 +455,7 @@ enters or leaves, so neither the creature nor its neighbors move.
Its name and progress belong in the tooltip and panel, never beside the
sprite. Clicking a ready egg hatches it; otherwise a click boops the daemon and
opens its panel. When something needs you or failed, its one line replaces the
-left context and PR in the terminal's yellow for 5.2 s, like tmux's message
+right context and PR in the terminal's yellow for 5.2 s, like tmux's message
line. The model stays available; a reply to a click is dim. Mood and frame updates repaint only the slot.
The contract is [daemons/README.md](../../daemons/README.md); the desktop's
choices are in [Daemons on the desktop](daemons.md).
diff --git a/desktop/integration_test/friendly_desktop_e2e_test.dart b/desktop/integration_test/friendly_desktop_e2e_test.dart
new file mode 100644
index 000000000..d4e1be3c1
--- /dev/null
+++ b/desktop/integration_test/friendly_desktop_e2e_test.dart
@@ -0,0 +1,48 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:integration_test/integration_test.dart';
+import 'package:window_manager/window_manager.dart';
+
+import '../test/desktop_dialog_interaction_test.dart' as interactions;
+import '../test/desktop_compact_launch_test.dart' as compact;
+import '../test/desktop_history_dialog_test.dart' as history;
+
+/// Exercise creation, search and History in the macOS engine/window.
+///
+/// Run serially with other native fixtures:
+/// FLUTTER_TEST=1 flutter test -d macos --no-pub \
+/// integration_test/friendly_desktop_e2e_test.dart
+/// If this host throttles background native frames, run all four shards in
+/// separate sequential processes with --total-shards=4 --shard-index=0..3.
+///
+/// The imported fixture mounts the real workspace overlays around in-memory
+/// transports, fake terminal sessions, and a memory-only keymap. It never boots
+/// the CLI or sends a request to a real machine. Keyboard events and IME values
+/// are injected, so this suite does not establish physical AppKit candidate
+/// window behavior. Rebuild lib/main.dart afterward for the normal review app.
+/// Exhaustive project, async launch, and method-channel scenarios remain in the
+/// full widget suite. Each native smoke journey has a 45-second time limit.
+void main() {
+ if (!kUnderTest) {
+ throw StateError('Friendly desktop fixtures require FLUTTER_TEST=1');
+ }
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized().framePolicy =
+ LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;
+ setUpAll(() async {
+ await windowManager.ensureInitialized();
+ await windowManager.setSize(const Size(1280, 800));
+ // Keep this isolated fixture visible while other Harness windows run.
+ // macOS can suspend frame delivery for a fully occluded test window.
+ await windowManager.setAlwaysOnTop(true);
+ });
+ tearDownAll(() => windowManager.setAlwaysOnTop(false));
+ setUp(() async {
+ // Foreground this isolated fixture rather than another running build.
+ await windowManager.show();
+ await windowManager.focus();
+ });
+ interactions.main(nativeSmoke: true);
+ compact.main(nativeSmoke: true);
+ history.main();
+}
diff --git a/desktop/integration_test/native_workspace_e2e_test.dart b/desktop/integration_test/native_workspace_e2e_test.dart
index 96df67565..de689212a 100644
--- a/desktop/integration_test/native_workspace_e2e_test.dart
+++ b/desktop/integration_test/native_workspace_e2e_test.dart
@@ -36,6 +36,7 @@ import 'package:harness/settings/settings_screen.dart';
import 'package:harness/settings/settings_section.dart';
import 'package:harness/settings/sections/shortcuts_section.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:harness/shared/widgets/app_select_field.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/new_harness.dart';
@@ -54,9 +55,11 @@ import 'package:harness/ws/ws_conn.dart';
import '../test/keymap_host_test.dart' show key;
import '../test/support/mixed_agents.dart';
+import '../test/support/guest_app.dart';
import '../test/support/password_cli.dart';
import '../test/support/machine_api.dart';
import '../test/support/rename_connection.dart';
+import '../test/support/resource_picker.dart';
import '../test/support/stop_connection.dart';
import '../test/support/fork_connection.dart';
import '../test/support/restart_connection.dart';
@@ -79,6 +82,28 @@ import '../test/usage_jsonl_scanners_test.dart'
import '../test/signout_recovery_test.dart'
show SignOutFixture, signOutApp, signOutHost;
+Future<void> openMachineEditor(
+ WidgetTester tester,
+ String machineId,
+ String action,
+) async {
+ if (resourceScope('@').evaluate().isEmpty) {
+ await key(tester, LogicalKeyboardKey.keyM, cmd: true);
+ await tester.pumpAndSettle();
+ }
+ await selectResource(tester, 'machine:$machineId');
+ await tester.tap(find.byKey(ValueKey('resource-action:picker.$action')));
+ await tester.pumpAndSettle();
+}
+
+Future<void> closeMachinePicker(WidgetTester tester) async {
+ for (var step = 0; resourceField.evaluate().isNotEmpty && step < 4; step++) {
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ }
+ expect(resourceField, findsNothing);
+}
+
class _CreationConnection extends WsConn {
_CreationConnection({this.products = const []})
: super(
@@ -235,6 +260,17 @@ class _WorkspaceLinks implements PeerLinkClient {
/// Run with FLUTTER_TEST=1. This fixture never bootstraps the real CLI, loads a
/// Harness home, or creates real agents; it mounts the real native workspace
/// around in-memory sessions and simulates creation and machine-link requests.
+Future<void> waitForWorkspace(
+ WidgetTester tester,
+ bool Function() ready, {
+ required String reason,
+}) async {
+ for (var i = 0; i < 100 && !ready(); i++) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ expect(ready(), isTrue, reason: reason);
+}
+
void main() {
if (!kUnderTest) {
throw StateError('Native workspace fixtures require FLUTTER_TEST=1');
@@ -260,7 +296,7 @@ void main() {
(tester) async {
final provisioner = SetupProvisioner();
final app =
- AppNotifier(
+ GuestTestApp(
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
@@ -296,8 +332,8 @@ void main() {
theme: grid.buildAppTheme(brightness: Brightness.dark),
home: ListenableBuilder(
listenable: app,
- builder: (_, _) => app.status == AppStatus.unauthenticated
- ? const Scaffold(body: Text('Sign-in reached'))
+ builder: (_, _) => app.status == AppStatus.authenticated
+ ? const Scaffold(body: Text('Guest workspace reached'))
: EnvironmentSetupScreen(notifier: app),
),
),
@@ -357,8 +393,13 @@ void main() {
),
);
await tester.pump(const Duration(milliseconds: 100));
- expect(app.status, AppStatus.unauthenticated);
- expect(find.text('Sign-in reached'), findsOneWidget);
+ await waitForWorkspace(
+ tester,
+ () => app.status == AppStatus.authenticated,
+ reason: 'Setup completes its async startup before opening the guest workspace',
+ );
+ expect(app.signedIn, isFalse);
+ expect(find.text('Guest workspace reached'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
},
@@ -382,6 +423,8 @@ void main() {
agentId: 'a0',
agentName: 'Fixture',
engineId: 'codex',
+ // An established stream has already consumed its initial claim.
+ takeover: false,
send: connection.sendTerminalFrame,
sendBinary: (frame) async {
if (frame.kind == TerminalBinaryKind.input) input.add(frame);
@@ -442,11 +485,19 @@ void main() {
'protocolVersion': 3,
'backend': 'tmux',
'available': true,
+ 'features': {'noTakeover': true},
});
await tester.pump(const Duration(milliseconds: 100));
+ await waitForWorkspace(
+ tester,
+ () => connection.frames.any((frame) => frame.type == 'terminal_open'),
+ reason:
+ 'Reconnect opens the visible terminal after discovery completes',
+ );
final open = connection.frames
.lastWhere((frame) => frame.type == 'terminal_open')
.payload;
+ expect(open['takeover'], isFalse);
await session.handleFrame('terminal_ready', {
'requestId': open['requestId'],
'agentId': 'a0',
@@ -979,17 +1030,18 @@ void main() {
await startHarness(tester);
await settle();
expect(connection.installs, ['autonomous/circuit']);
- expect(
- inPane('Installing Autonomous Circuit on This Mac'),
- findsOneWidget,
- );
+ expect(inPane('Setting up Autonomous Circuit'), findsOneWidget);
+ expect(inPane('On This Mac'), findsOneWidget);
await say({
'id': 'autonomous/circuit',
'phase': 'setup',
'line': 'npm ci',
});
await settle();
- expect(inPane('✓'), findsOneWidget);
+ expect(
+ find.descendant(of: pane, matching: find.byIcon(AppIcons.circleCheck)),
+ findsOneWidget,
+ );
expect(inPane('npm ci'), findsWidgets);
await say({
'id': 'autonomous/circuit',
@@ -1003,13 +1055,23 @@ void main() {
'detail': 'setup exited 1',
});
await settle();
- expect(inPane('✗'), findsOneWidget);
+ expect(
+ inPane('Autonomous Circuit could not be installed'),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: pane, matching: find.byIcon(AppIcons.circleAlert)),
+ findsWidgets,
+ );
expect(connection.creates, isEmpty);
await key(tester, LogicalKeyboardKey.enter);
await settle();
expect(connection.installs, hasLength(2));
- expect(inPane('✗'), findsNothing);
+ expect(
+ find.descendant(of: pane, matching: find.byIcon(AppIcons.circleAlert)),
+ findsNothing,
+ );
await say({'id': 'autonomous/circuit', 'phase': 'done'});
connection.reply!.complete({'ok': true});
await settle();
@@ -1023,7 +1085,7 @@ void main() {
);
testWidgets(
- 'native first workspace stays quiet until New Harness is requested',
+ 'native first workspace offers the shared composer without starting work',
(tester) async {
final connection = _CreationConnection();
final app = _FirstCreationApp(connection);
@@ -1044,8 +1106,16 @@ void main() {
);
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 200));
- expect(find.byType(NewHarnessForm), findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(find.byType(WorkspaceWelcome), findsOneWidget);
+ expect(connection.creates, isEmpty);
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('new-harness-task')))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
await tester.pump(const Duration(milliseconds: 200));
final box = tester
@@ -1053,17 +1123,23 @@ void main() {
.controller;
expect(box.engine, 'codex');
expect(box.needsProject, isTrue);
- await startHarness(tester);
+ expect(
+ tester
+ .widget<FilledButton>(
+ find.byKey(const ValueKey('new-harness-field-start')),
+ )
+ .onPressed,
+ isNull,
+ );
expect(connection.creates, isEmpty);
expect(box.requiredChoice?.message, 'Choose a project.');
+ await openLaunchRow(tester, 'project');
await tester.tap(
find.byKey(
ValueKey('new-harness-option-${NewHarnessController.newProjectId}'),
),
);
await tester.pump();
- expect(box.field, NewHarnessField.machine);
- await key(tester, LogicalKeyboardKey.enter);
expect(box.field, NewHarnessField.projectName);
await typeHarnessQuery(tester, 'first-project');
await key(tester, LogicalKeyboardKey.enter);
@@ -1090,7 +1166,7 @@ void main() {
);
testWidgets(
- 'native JEV navigation returns to the original pane and hands off to New Swarm',
+ 'native JEV navigation returns to the original pane and hands off to New Tab',
(tester) async {
final app = createApp();
final input = <TerminalBinaryFrame>[];
@@ -1218,11 +1294,11 @@ void main() {
await command('Keyboard practice');
expect(learning.finished, isTrue);
final filter = find.byKey(const ValueKey('practice-filter'));
- await tester.enterText(filter, 'New Swarm');
+ await tester.enterText(filter, 'New Tab');
await tester.pump();
await key(tester, LogicalKeyboardKey.enter);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
- expect(find.text('[x] New Swarm'), findsOneWidget);
+ expect(find.byKey(const ValueKey('practice-completed')), findsOneWidget);
await key(tester, LogicalKeyboardKey.keyW, cmd: true);
expect(app.swarms, [original]);
expect(original.panes, panes);
@@ -1399,7 +1475,7 @@ void main() {
await tester.pump(const Duration(milliseconds: 80));
final sharedTab = app.activeSwarm;
expect(sharedTab, isNot(same(source)));
- expect(sharedTab.name, 'Fix login redirect');
+ expect(sharedTab.name, 'openharness');
expect(sharedTab.panes.single.session, same(claude));
expect(source.panes, [firstPane, secondPane]);
await key(tester, LogicalKeyboardKey.keyW, cmd: true);
@@ -1451,7 +1527,7 @@ void main() {
);
for (final (label, shortcut) in [
- ('New Swarm', LogicalKeyboardKey.keyT),
+ ('New Tab', LogicalKeyboardKey.keyT),
('Open Harness', LogicalKeyboardKey.keyP),
]) {
testWidgets('native created $label gets terminal input without a click', (
@@ -1478,10 +1554,18 @@ void main() {
),
);
await tester.pump(const Duration(milliseconds: 200));
+ final expectedTask = shortcut == LogicalKeyboardKey.keyT
+ ? 'Keep the task from my new tab'
+ : 'Check retargeted keyboard input';
if (shortcut == LogicalKeyboardKey.keyT) {
await key(tester, shortcut, cmd: true);
+ await tester.pumpAndSettle();
expect(find.byType(WorkspaceWelcome), findsOneWidget);
expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
+ await tester.enterText(
+ find.byKey(const ValueKey('new-harness-task')),
+ expectedTask,
+ );
}
await key(tester, LogicalKeyboardKey.keyP, cmd: true);
final search = find.byKey(const ValueKey('swarm-search-input'));
@@ -1500,11 +1584,12 @@ void main() {
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
.task,
- 'Check retargeted keyboard input',
+ expectedTask,
);
await startHarness(tester);
await tester.pump(const Duration(milliseconds: 200));
await tester.pump();
+ expect(connection.creates.single['prompt'], expectedTask);
expect(find.byType(NewHarnessForm), findsNothing);
expect(app.activeSwarm, same(destination));
expect(
@@ -1672,7 +1757,7 @@ void main() {
}
testWidgets(
- 'native creation resets canceled edits and launches the reviewed choices',
+ 'native creation preserves canceled edits and launches the reviewed choices',
(tester) async {
final connection = _CreationConnection();
final app = createApp(connectionForTest: (_) => connection);
@@ -1744,30 +1829,19 @@ void main() {
);
await openLaunchRow(tester, 'project');
- await typeHarnessQuery(tester, 'does-not-match-any-existing-project');
- for (
- var step = 0;
- prompt().selected?.id != NewHarnessController.existingProjectId &&
- step < 8;
- step++
- ) {
- await key(tester, LogicalKeyboardKey.arrowDown);
- }
- expect(prompt().selected?.id, NewHarnessController.existingProjectId);
- await key(tester, LogicalKeyboardKey.enter);
- expect(prompt().field, NewHarnessField.machine);
- await key(tester, LogicalKeyboardKey.enter);
- expect(prompt().field, NewHarnessField.project);
- expect(
- prompt().options.any(
- (option) => option.id == NewHarnessController.browseId,
- ),
- isTrue,
+ await tester.tap(find.byKey(const ValueKey('new-harness-repo-machine')));
+ await tester.pumpAndSettle();
+ final localMachine = find.byKey(
+ const ValueKey('new-harness-machine-option-m'),
);
+ expect(localMachine, findsOneWidget);
+ expect(prompt().field, NewHarnessField.projectMenu);
await key(tester, LogicalKeyboardKey.escape);
- expect(prompt().field, NewHarnessField.machine);
- await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(localMachine, findsNothing);
expect(prompt().field, NewHarnessField.projectMenu);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(prompt().field, NewHarnessField.launch);
await openLaunchRow(tester, 'approvals');
await typeHarnessQuery(tester, 'Plan first');
@@ -1785,21 +1859,13 @@ void main() {
);
expect(connection.creates, isEmpty);
- // A canceled draft does not become the next Cmd-N's defaults.
+ // Dismissing a draft preserves the reviewed choices and prompt.
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- await tester.pump(const Duration(milliseconds: 80));
- expect(prompt().engine, 'codex');
- expect(prompt().modeLabel, 'Auto-approve');
- expect(prompt().task, '');
- expect(prompt().project.folder, '/work/openharness');
- await openLaunchRow(tester, 'agent');
- await typeHarnessQuery(tester, 'claude');
- await key(tester, LogicalKeyboardKey.enter);
- await openLaunchRow(tester, 'approvals');
- await typeHarnessQuery(tester, 'Plan first');
- await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
expect(prompt().engine, 'claude');
expect(prompt().mode, 'plan');
+ expect(prompt().task, task);
+ expect(prompt().project.folder, '/work/openharness');
await startHarness(tester);
await tester.pump(const Duration(milliseconds: 200));
expect(find.byType(NewHarnessForm), findsNothing);
@@ -1807,7 +1873,7 @@ void main() {
expect(source.panes.length, 2);
expect(source.panes.first, same(original));
expect(app.focusedPane!.agentId, 'made');
- expect(connection.creates.single['prompt'], isNull);
+ expect(connection.creates.single['prompt'], task);
expect(connection.creates.single, containsPair('engine', 'claude'));
expect(connection.creates.single, containsPair('permissionMode', 'plan'));
expect(
@@ -1865,12 +1931,12 @@ void main() {
),
);
await tester.pump(const Duration(milliseconds: 200));
- final field = find.byKey(const ValueKey('connect-password-studio-input'));
+ final field = find.byKey(const ValueKey('remote-password-connect-field'));
await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ await openMachineEditor(tester, 'studio', 'resource_connect');
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
await tester.enterText(field, 'fixture password');
- await tester.testTextInput.receiveAction(TextInputAction.done);
+ await key(tester, LogicalKeyboardKey.enter);
await tester.pump();
expect(links.requests, ['studio']);
expect(tester.widget<TextField>(field).readOnly, isTrue);
@@ -1885,7 +1951,7 @@ void main() {
expect(links.requests, ['studio', 'studio']);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
+ await closeMachinePicker(tester);
expect(app.focusedPane, same(pane));
expect(input, isEmpty);
await key(tester, LogicalKeyboardKey.arrowLeft);
@@ -1893,6 +1959,7 @@ void main() {
input.clear();
await key(tester, LogicalKeyboardKey.keyM, cmd: true);
await tester.pumpAndSettle();
+ await openMachineEditor(tester, 'studio', 'resource_connect');
expect(tester.widget<TextField>(field).readOnly, isTrue);
expect(tester.widget<TextField>(field).controller!.text, isEmpty);
await key(tester, LogicalKeyboardKey.enter);
@@ -1905,8 +1972,7 @@ void main() {
expect(field, findsNothing);
expect(pane.session, same(session));
expect(input, isEmpty);
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
+ await closeMachinePicker(tester);
await key(tester, LogicalKeyboardKey.arrowRight);
await tester.pump(const Duration(milliseconds: 20));
expect(input.single.bytes, [27, 91, 67]);
@@ -1948,32 +2014,33 @@ void main() {
await tester.pumpAndSettle();
await key(tester, LogicalKeyboardKey.keyM, cmd: true);
await tester.pumpAndSettle();
- await tester.tap(find.text('Set password'));
- await tester.pumpAndSettle();
- final password = find.byKey(const ValueKey('make-available-password'));
+ await openMachineEditor(tester, 'm', 'resource_settings');
+ final password = find.byKey(const ValueKey('remote-password-field'));
expect(tester.widget<TextField>(password).focusNode!.hasFocus, isTrue);
await tester.enterText(password, 'fixture password');
- await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.enterText(
+ find.byKey(const ValueKey('remote-password-confirm-field')),
+ 'fixture password',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(cli.passwords, ['fixture password']);
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.keyM, cmd: true);
- await tester.pumpAndSettle();
- expect(find.text('Saving password…'), findsOneWidget);
+ await closeMachinePicker(tester);
+ await openMachineEditor(tester, 'm', 'resource_settings');
+ expect(find.text('Saving…'), findsOneWidget);
expect(cli.passwords, hasLength(1));
cli.setReply!.complete(cli.setResult);
await tester.pumpAndSettle();
- expect(find.text('Change password'), findsOneWidget);
- await tester.tap(find.text('Change password'));
+ expect(find.text('Password saved.'), findsOneWidget);
+ await openMachineEditor(tester, 'm', 'resource_settings');
+ expect(find.text('Password is set.'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('machine-form:Change')));
await tester.pumpAndSettle();
expect(tester.widget<TextField>(password).focusNode!.hasFocus, isTrue);
expect(tester.widget<TextField>(password).controller!.text, isEmpty);
- await tester.tap(find.text('Cancel'));
- await tester.pumpAndSettle();
- expect(find.text('Change password'), findsOneWidget);
- await key(tester, LogicalKeyboardKey.escape);
+ await tester.tap(find.byKey(const ValueKey('machine-form:Cancel')));
await tester.pumpAndSettle();
+ await closeMachinePicker(tester);
expect(app.focusedPane, same(pane));
expect(pane.session, same(session));
expect(input, isEmpty);
@@ -2013,52 +2080,46 @@ void main() {
await tester.pumpAndSettle();
await key(tester, LogicalKeyboardKey.keyM, cmd: true);
await tester.pumpAndSettle();
- Future<void> action(String label) async {
- final options = find.byTooltip(
- 'Options for ${app.stateOf('studio')!.machine.displayName}',
- );
- await tester.ensureVisible(options);
- await tester.tap(options);
- await tester.pumpAndSettle();
- await tester.tap(find.text(label));
- await tester.pumpAndSettle();
- }
+ Future<void> action(String label) => openMachineEditor(
+ tester,
+ 'studio',
+ label == 'Rename' ? 'resource_rename' : 'resource_remove',
+ );
await action('Rename');
final rename = find.byKey(const Key('machine-rename-input'));
expect(tester.widget<TextField>(rename).focusNode!.hasFocus, isTrue);
- tester.testTextInput.enterText('Office builder');
- await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.enterText(rename, 'Office builder');
+ await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(api.renames, [('studio', 'Office builder')]);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
+ expect(resourceScope('@'), findsOneWidget);
await action('Rename');
expect(tester.widget<TextField>(rename).readOnly, isTrue);
expect(api.renames, hasLength(1));
api.renameReply!.complete('Office builder');
await tester.pumpAndSettle();
- expect(find.text('Office builder'), findsOneWidget);
+ expect(find.text('Office builder'), findsWidgets);
await action('Remove from account…');
await key(tester, LogicalKeyboardKey.enter); // Cancel is the default.
await tester.pumpAndSettle();
expect(api.deletes, isEmpty);
await action('Remove from account…');
- await tester.tap(find.byKey(const Key('machine-delete-confirm')));
+ await tester.tap(find.byKey(const ValueKey('machine-form:Delete')));
await tester.pumpAndSettle();
expect(api.deletes, ['studio']);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
await action('Remove from account…');
- expect(find.text('Deleting machine…'), findsOneWidget);
+ expect(find.text('Deleting…'), findsOneWidget);
expect(api.deletes, hasLength(1));
api.deleteReply!.complete();
await tester.pumpAndSettle();
expect(app.stateOf('studio'), isNull);
- expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
+ expect(resourceScope('@'), findsOneWidget);
+ await closeMachinePicker(tester);
expect(app.focusedPane, same(pane));
expect(pane.session, same(session));
expect(input, isEmpty);
@@ -2293,7 +2354,7 @@ void main() {
const WsRequestTimeout('agent_fork'),
);
await tester.pumpAndSettle();
- expect(find.text('enter check status'), findsOneWidget);
+ expect(find.text('Check status'), findsOneWidget);
await key(tester, LogicalKeyboardKey.enter);
expect(connection.checks, [
{'creationId': id},
@@ -2372,7 +2433,7 @@ void main() {
await tester.pumpAndSettle();
expect(
find.text(
- 'Started a new conversation. The previous session could not be resumed.',
+ 'Started a new conversation. The previous conversation could not be resumed.',
),
findsOneWidget,
);
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dart
index b4177fa3f..ef847a975 100644
--- a/desktop/lib/app_shell.dart
+++ b/desktop/lib/app_shell.dart
@@ -123,20 +123,22 @@ class HarnessApp extends StatelessWidget {
),
// The design system's own `buildAppTheme` — see the note where a second,
// hand-written `ThemeData` used to shadow it, in `lib/theme/app_theme.dart`.
- // One theme, no `darkTheme`/`themeMode` to resolve between: the chosen
- // palette says whether it is light or dark.
+ // The chosen palette owns the appearance; platform text scaling remains
+ // available to app controls.
theme: grid.buildAppTheme(brightness: prefs.palette.brightness),
- // The chosen point size is already applied to every style and terminal
- // cell. A second UI scale would make the chrome disagree with the grid.
- builder: (context, child) => MediaQuery.withNoTextScaling(
- child: _GridTokenScope(
- child: keymap == null
- ? child ?? const SizedBox.shrink()
- : KeymapProvider(
- keymap: keymap!,
- child: child ?? const SizedBox.shrink(),
- ),
- ),
+ highContrastTheme: grid.buildAppTheme(
+ brightness: prefs.palette.brightness,
+ highContrast: true,
+ ),
+ // Desktop forms respect the platform's text size. Fixed-grid terminal
+ // surfaces own their no-scaling boundary alongside terminal zoom.
+ builder: (context, child) => _GridTokenScope(
+ child: keymap == null
+ ? child ?? const SizedBox.shrink()
+ : KeymapProvider(
+ keymap: keymap!,
+ child: child ?? const SizedBox.shrink(),
+ ),
),
home: StatsLifecycle(
child: RootShell(authenticatedScreen: authenticatedScreen),
diff --git a/desktop/lib/core/agent_preference.dart b/desktop/lib/core/agent_preference.dart
index 963a1ad59..598fe7dc9 100644
--- a/desktop/lib/core/agent_preference.dart
+++ b/desktop/lib/core/agent_preference.dart
@@ -1,8 +1,9 @@
import 'dart:convert';
import 'local_key_value_store.dart';
+import 'permission_modes.dart';
-/// Remembers an agent choice, independently of a machine, profile or permission.
+/// Remembers agent choices and each agent's last explicit approval mode.
class AgentPreference {
AgentPreference(this.storage);
final LocalKeyValueStore? storage;
@@ -19,6 +20,8 @@ class AgentPreference {
bool advancedOpen = false;
List<String> recentHarnesses = const [];
final _enginesByHarness = <String, String>{};
+ final _permissionsByEngine = <String, String>{};
+ String? permissionModeFor(String engine) => _permissionsByEngine[engine];
String? engineFor(String? harnessId) =>
_enginesByHarness[harnessId ?? 'coding'];
@@ -26,6 +29,20 @@ class AgentPreference {
/// Harness lists before anything is typed.
List<String> recent = const [];
+ List<String>? _recentChoices;
+
+ /// Actual launch choices, interleaving coding agents and specialized
+ /// harnesses. A harness's backend is not a second launch by the user.
+ /// Older preferences recorded the two lists separately; preserve their last
+ /// known choice first when migrating that history.
+ List<String> get recentChoices =>
+ _recentChoices ??
+ <String>{
+ ?harness ?? value,
+ ...recentHarnesses,
+ ...recent,
+ }.take(recentCapacity).toList(growable: false);
+
Future<void>? _loading;
Future<void> _writes = Future.value();
int _revision = 0;
@@ -90,7 +107,23 @@ class AgentPreference {
: null;
recent = ids(data['agents'], false);
recentHarnesses = ids(data['harnesses'], true);
+ if (data['choices'] case final List choices) {
+ _recentChoices = choices
+ .whereType<String>()
+ .where((id) => id.isNotEmpty)
+ .toSet()
+ .take(recentCapacity)
+ .toList(growable: false);
+ }
advancedOpen = data['advancedOpen'] == true;
+ if (data['permissionsByEngine'] case final Map permissions) {
+ for (final engine in kEnginePermissionModes.keys) {
+ final mode = permissions[engine];
+ if (permissionModesOf(engine).any((item) => item.id == mode)) {
+ _permissionsByEngine[engine] = mode as String;
+ }
+ }
+ }
if (data['enginesByHarness'] case final Map choices) {
for (final entry in choices.entries) {
if (entry.key is String &&
@@ -116,6 +149,17 @@ class AgentPreference {
return _save();
}
+ /// Explicit composer selections become the next form's defaults without
+ /// recording an agent launch or changing the recent-use order.
+ Future<void> selectLaunch(String engine, {String? harnessId}) async {
+ await load();
+ _revision++;
+ value = engine;
+ harness = harnessId;
+ _enginesByHarness[harnessId ?? 'coding'] = engine;
+ await _save();
+ }
+
/// [agent] was just used to create a harness: it moves to the front of
/// [recent].
Future<void> remember(String agent, {String? harnessId}) async {
@@ -125,6 +169,11 @@ class AgentPreference {
harnessId = agent;
agent = value ?? '';
}
+ final choice = harnessId ?? agent;
+ _recentChoices = <String>{
+ if (choice.isNotEmpty) choice,
+ ...recentChoices,
+ }.take(recentCapacity).toList(growable: false);
harness = harnessId;
if (agent.isNotEmpty) {
value = agent;
@@ -150,14 +199,24 @@ class AgentPreference {
await _save();
}
+ Future<void> selectPermissionMode(String engine, String mode) async {
+ if (!permissionModesOf(engine).any((item) => item.id == mode)) return;
+ await load();
+ _permissionsByEngine[engine] = mode;
+ _revision++;
+ await _save();
+ }
+
Future<void> _save() {
final snapshot = jsonEncode({
'engine': value,
'harness': harness,
'agents': recent,
'harnesses': recentHarnesses,
+ 'choices': recentChoices,
'enginesByHarness': _enginesByHarness,
'advancedOpen': advancedOpen,
+ 'permissionsByEngine': _permissionsByEngine,
});
return _writes = _writes.then((_) async {
try {
diff --git a/desktop/lib/core/first_task.dart b/desktop/lib/core/first_task.dart
index 1b4706f9b..08d094941 100644
--- a/desktop/lib/core/first_task.dart
+++ b/desktop/lib/core/first_task.dart
@@ -5,7 +5,7 @@
/// the CLI's `FIRST_PROMPT_ARGS` (cli/src/lib/engineLaunch.ts). A machine refuses
/// a first message for any other engine (`PROMPT_UNSUPPORTED`).
/// test/first_task_test.dart holds the two lists to the same answer.
-const kFirstTaskEngines = {'claude', 'codex', 'opencode'};
+const kFirstTaskEngines = {'claude', 'codex', 'opencode', 'hermes'};
/// Whether a harness on [engine] — its base engine, for a Store harness — can
/// start on a first task.
diff --git a/desktop/lib/core/project_history.dart b/desktop/lib/core/project_history.dart
index f8ec6adeb..3892b8c40 100644
--- a/desktop/lib/core/project_history.dart
+++ b/desktop/lib/core/project_history.dart
@@ -9,6 +9,7 @@ class ProjectHistory {
static const _key = 'new_agent_projects_v1';
final _recent = <String, List<String>>{};
final _selected = <String, String?>{};
+ final _worktrees = <String, Map<String, bool>>{};
Future<void>? _loading;
Future<void> _saving = Future.value();
int _revision = 0;
@@ -17,6 +18,7 @@ class ProjectHistory {
List.unmodifiable(_recent[machine] ?? []);
bool hasSelection(String machine) => _selected.containsKey(machine);
String? selected(String machine) => _selected[machine];
+ bool? worktreeFor(String machine, String path) => _worktrees[machine]?[path];
Future<void> load() => _loading ??= _load();
Future<void> _load() async {
@@ -38,10 +40,20 @@ class ProjectHistory {
.toSet()
.toList();
}
- if (value['selected'] == null ||
- value['selected'] is String && _valid(value['selected'])) {
+ if (value.containsKey('selected') &&
+ (value['selected'] == null ||
+ value['selected'] is String && _valid(value['selected']))) {
_selected[entry.key] = value['selected'];
}
+ if (value['worktrees'] case final Map choices) {
+ _worktrees[entry.key] = {
+ for (final choice in choices.entries.take(40))
+ if (choice.key is String &&
+ _valid(choice.key) &&
+ choice.value is bool)
+ choice.key as String: choice.value as bool,
+ };
+ }
}
} catch (_) {
// A missing preference never blocks creation.
@@ -64,9 +76,37 @@ class ProjectHistory {
...?_recent[machine]?.where((item) => item != path),
].take(40).toList();
}
+ await _save();
+ }
+
+ /// A worktree preference belongs to this folder on this machine. It does
+ /// not change the selected project or add a worktree folder to recents.
+ Future<void> selectWorktree(String machine, String path, bool enabled) async {
+ if (!_valid(path)) return;
+ await load();
+ _revision++;
+ _worktrees[machine] = {
+ path: enabled,
+ for (final entry
+ in (_worktrees[machine] ?? {}).entries
+ .where((entry) => entry.key != path)
+ .take(39))
+ entry.key: entry.value,
+ };
+ await _save();
+ }
+
+ Future<void> _save() async {
final snapshot = jsonEncode({
- for (final id in _selected.keys.toList().reversed.take(64))
- id: {'selected': _selected[id], 'recent': _recent[id] ?? []},
+ for (final id in {
+ ..._worktrees.keys,
+ ..._selected.keys,
+ }.toList().reversed.take(64))
+ id: {
+ if (_selected.containsKey(id)) 'selected': _selected[id],
+ 'recent': _recent[id] ?? [],
+ if (_worktrees.containsKey(id)) 'worktrees': _worktrees[id],
+ },
});
_saving = _saving.then((_) async {
try {
diff --git a/desktop/lib/models/api_connections_panel.dart b/desktop/lib/models/api_connections_panel.dart
index 07226e41a..abe435dff 100644
--- a/desktop/lib/models/api_connections_panel.dart
+++ b/desktop/lib/models/api_connections_panel.dart
@@ -1,6 +1,6 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';
import '../shared/theme/app_theme.dart';
@@ -165,7 +165,7 @@ class _ApiConnectionsPanelState extends State<ApiConnectionsPanel> {
connection.provider == 'anthropic')
ModelMark(model: connection.provider)
else
- const Icon(LucideIcons.plug, size: 20),
+ const Icon(AppIcons.plug, size: 20),
const SizedBox(width: 12),
Expanded(
child: Column(
@@ -211,16 +211,13 @@ class _ApiConnectionsPanelState extends State<ApiConnectionsPanel> {
IconButton(
tooltip: 'Keep ${connection.name}',
onPressed: () => setState(() => _removing = null),
- icon: const Icon(LucideIcons.x, size: 16),
+ icon: const Icon(AppIcons.close, size: 16),
),
] else ...[
IconButton(
tooltip: '${saved ? 'Edit' : 'Add'} ${connection.name}',
onPressed: enabled ? () => _edit(connection) : null,
- icon: Icon(
- saved ? LucideIcons.pencil : LucideIcons.plus,
- size: 18,
- ),
+ icon: Icon(saved ? AppIcons.pencil : AppIcons.plus, size: 18),
),
if (saved)
IconButton(
@@ -228,7 +225,7 @@ class _ApiConnectionsPanelState extends State<ApiConnectionsPanel> {
onPressed: enabled
? () => setState(() => _removing = connection.id)
: null,
- icon: const Icon(LucideIcons.trash2, size: 16),
+ icon: const Icon(AppIcons.trash2, size: 16),
),
],
],
@@ -365,7 +362,7 @@ class _ApiEditorState extends State<_ApiEditor> {
IconButton(
onPressed: widget.onClose,
tooltip: widget.backLabel,
- icon: const Icon(LucideIcons.arrowLeft, size: 18),
+ icon: const Icon(AppIcons.arrowLeft, size: 18),
),
const SizedBox(width: 4),
Expanded(
@@ -411,7 +408,7 @@ class _ApiEditorState extends State<_ApiEditor> {
alignment: Alignment.centerLeft,
child: TextButton.icon(
onPressed: () => _openKeyPage(keyUrl),
- icon: const Icon(LucideIcons.arrowUpRight, size: 14),
+ icon: const Icon(AppIcons.arrowUpRight, size: 14),
label: const Text('Get API key'),
),
),
@@ -420,9 +417,7 @@ class _ApiEditorState extends State<_ApiEditor> {
child: TextButton.icon(
onPressed: () => setState(() => _advanced = !_advanced),
icon: Icon(
- _advanced
- ? LucideIcons.chevronUp
- : LucideIcons.chevronDown,
+ _advanced ? AppIcons.chevronUp : AppIcons.chevronDown,
size: 14,
),
label: const Text('Advanced'),
@@ -513,11 +508,10 @@ class _ApiEditorState extends State<_ApiEditor> {
decoration: InputDecoration(
labelText: label,
hintText: hint,
- labelStyle: AppType.monoMeta(color: AppPalette.textSecondary),
- hintStyle: AppType.monoMeta(color: AppPalette.textFaint),
+ labelStyle: AppType.caption(color: AppPalette.textSecondary),
+ hintStyle: AppType.body(color: AppPalette.textFaint),
filled: true,
fillColor: AppPalette.windowBg,
- border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
suffixIcon: secret
? Row(
mainAxisSize: MainAxisSize.min,
@@ -525,13 +519,13 @@ class _ApiEditorState extends State<_ApiEditor> {
IconButton(
tooltip: 'Paste API key',
onPressed: widget.controller.saving ? null : _pasteKey,
- icon: const Icon(LucideIcons.clipboardPaste, size: 16),
+ icon: const Icon(AppIcons.clipboardPaste, size: 16),
),
IconButton(
tooltip: _visible ? 'Hide API key' : 'Show API key',
onPressed: () => setState(() => _visible = !_visible),
icon: Icon(
- _visible ? LucideIcons.eyeOff : LucideIcons.eye,
+ _visible ? AppIcons.eyeOff : AppIcons.eye,
size: 16,
),
),
diff --git a/desktop/lib/models/models_panel.dart b/desktop/lib/models/models_panel.dart
index 68148df4a..6939a44f3 100644
--- a/desktop/lib/models/models_panel.dart
+++ b/desktop/lib/models/models_panel.dart
@@ -1,8 +1,8 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../core/models.dart';
import '../shared/theme/app_theme.dart';
@@ -160,7 +160,7 @@ class _ModelsPanelState extends State<ModelsPanel> with SectionWakes {
IconButton(
onPressed: widget.onClose,
tooltip: 'Close Models',
- icon: const Icon(LucideIcons.x, size: 16),
+ icon: const Icon(AppIcons.close, size: 16),
),
],
),
@@ -196,7 +196,7 @@ class _ModelsPanelState extends State<ModelsPanel> with SectionWakes {
color: AppPalette.textFaint,
),
prefixIcon: Icon(
- LucideIcons.search,
+ AppIcons.search,
size: 15,
color: AppPalette.textFaint,
),
@@ -207,7 +207,7 @@ class _ModelsPanelState extends State<ModelsPanel> with SectionWakes {
? null
: IconButton(
tooltip: 'Clear search',
- icon: const Icon(LucideIcons.x, size: 14),
+ icon: const Icon(AppIcons.close, size: 14),
onPressed: () {
setState(_search.clear);
_searchFocus.requestFocus();
@@ -221,13 +221,18 @@ class _ModelsPanelState extends State<ModelsPanel> with SectionWakes {
horizontal: 12,
),
border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(8),
+ borderRadius: BorderRadius.circular(
+ AppDesktop.fieldRadius,
+ ),
borderSide: BorderSide.none,
),
focusedBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(8),
+ borderRadius: BorderRadius.circular(
+ AppDesktop.fieldRadius,
+ ),
borderSide: BorderSide(
- color: AppPalette.accent.withValues(alpha: .8),
+ color: AppDesktop.focus,
+ width: AppDesktop.focusWidth,
),
),
),
@@ -514,10 +519,10 @@ class _ModelsPanelState extends State<ModelsPanel> with SectionWakes {
? 'Start'
: 'Download and start';
final icon = model.canStop
- ? LucideIcons.pause
+ ? AppIcons.pause
: model.downloaded
- ? LucideIcons.play
- : LucideIcons.download;
+ ? AppIcons.play
+ : AppIcons.download;
final tooltip = active
? status
: model.canStop
@@ -788,7 +793,7 @@ class LocalModelInvitation extends StatelessWidget {
tooltip: 'Dismiss',
onPressed: () =>
unawaited(controller.dismissIntroduction()),
- icon: const Icon(Icons.close, size: 17),
+ icon: const Icon(AppIcons.close, size: 17),
),
],
),
diff --git a/desktop/lib/orchestrator/orchestrator_launcher.dart b/desktop/lib/orchestrator/orchestrator_launcher.dart
index 13ddf7353..e178db88d 100644
--- a/desktop/lib/orchestrator/orchestrator_launcher.dart
+++ b/desktop/lib/orchestrator/orchestrator_launcher.dart
@@ -2,10 +2,10 @@ import 'dart:async';
import '../shared/widgets/labeled_field.dart';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
@@ -152,12 +152,12 @@ class _OrchestratorLauncherState extends State<OrchestratorLauncher> {
grid.AppTheme.watch(context);
return Dialog(
backgroundColor: grid.AppPalette.panelBg,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
insetPadding: const EdgeInsets.all(24),
child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 740, maxHeight: 740),
+ constraints: const BoxConstraints(maxWidth: 680, maxHeight: 740),
child: SingleChildScrollView(
- padding: const EdgeInsets.all(28),
+ padding: const EdgeInsets.all(24),
child: CallbackShortcuts(
bindings: {
const SingleActivator(
@@ -173,14 +173,14 @@ class _OrchestratorLauncherState extends State<OrchestratorLauncher> {
Row(
children: [
Icon(
- LucideIcons.sparkles,
+ AppIcons.sparkles,
size: 18,
color: grid.AppPalette.swarmAccent,
),
const SizedBox(width: 10),
const Expanded(child: Text('Orchestrator')),
AppIconButton(
- icon: LucideIcons.x,
+ icon: AppIcons.close,
tooltip: 'Close',
onPressed: () => Navigator.of(context).pop(),
),
@@ -206,7 +206,7 @@ class _OrchestratorLauncherState extends State<OrchestratorLauncher> {
minLines: 5,
maxLines: 9,
maxLength: 24000,
- style: grid.AppType.mono(height: 1.45),
+ style: grid.AppType.body(height: 1.45),
onChanged: (_) => setState(() {}),
decoration: const InputDecoration(
border: InputBorder.none,
@@ -254,16 +254,14 @@ class _OrchestratorLauncherState extends State<OrchestratorLauncher> {
? null
: _start,
icon: Icon(
- _starting
- ? LucideIcons.ellipsis
- : LucideIcons.arrowUpRight,
+ _starting ? AppIcons.ellipsis : AppIcons.arrowUpRight,
size: 16,
),
label: Text(
_starting
? 'Starting…'
: _attempt == null
- ? 'Start creating ${kIsWeb ? 'Alt+↵' : '⌘↵'}'
+ ? 'Start creating'
: 'Check launch',
),
),
@@ -322,7 +320,7 @@ class _OrchestratorLauncherState extends State<OrchestratorLauncher> {
overflow: TextOverflow.ellipsis,
),
subtitle: Text(project['state'] as String? ?? ''),
- trailing: const Icon(LucideIcons.arrowUpRight, size: 14),
+ trailing: const Icon(AppIcons.arrowUpRight, size: 14),
onTap: _machine == null
? null
: () {
diff --git a/desktop/lib/orchestrator/orchestrator_workspace.dart b/desktop/lib/orchestrator/orchestrator_workspace.dart
index 4f41d8582..671c9d426 100644
--- a/desktop/lib/orchestrator/orchestrator_workspace.dart
+++ b/desktop/lib/orchestrator/orchestrator_workspace.dart
@@ -1,8 +1,8 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
@@ -121,7 +121,7 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {
Row(
children: [
Icon(
- LucideIcons.sparkles,
+ AppIcons.sparkles,
size: 17,
color: grid.AppPalette.swarmAccent,
),
@@ -145,7 +145,7 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {
child: const Text('Stop'),
),
AppIconButton(
- icon: LucideIcons.plus,
+ icon: AppIcons.plus,
tooltip: 'New project',
onPressed: () =>
showOrchestratorLauncher(context, widget.notifier),
@@ -212,7 +212,7 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {
mainAxisSize: MainAxisSize.min,
children: [
Icon(
- LucideIcons.layers,
+ AppIcons.layers,
color: grid.AppPalette.textSecondary,
size: 28,
),
@@ -318,9 +318,7 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {
mainAxisSize: MainAxisSize.min,
children: [
Icon(
- task.state == 'succeeded'
- ? LucideIcons.check
- : LucideIcons.layers,
+ task.state == 'succeeded' ? AppIcons.check : AppIcons.layers,
size: 24,
color: grid.AppPalette.textSecondary,
),
@@ -385,7 +383,7 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {
].contains(task.state) &&
model.state == 'active')
AppIconButton(
- icon: LucideIcons.rotateCcw,
+ icon: AppIcons.rotateCcw,
tooltip: 'Retry task',
onPressed: model.operating
? null
@@ -393,7 +391,7 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {
),
if (task.agentId != null)
AppIconButton(
- icon: LucideIcons.terminal,
+ icon: AppIcons.terminal,
tooltip: 'Inspect ${task.title}',
onPressed: () => _inspect(task.agentId!),
),
@@ -434,7 +432,7 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {
const Expanded(child: Text('Director')),
if (model.directorId != null)
AppIconButton(
- icon: LucideIcons.terminal,
+ icon: AppIcons.terminal,
tooltip: 'Inspect director',
onPressed: () => _inspect(model.directorId!),
),
@@ -560,15 +558,17 @@ class _OrchestratorWorkspaceState extends State<OrchestratorWorkspace> {
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
- Text(
- 'Shift ↵ for a new line',
- style: grid.AppType.monoMeta(
- color: grid.AppPalette.textSecondary,
+ Flexible(
+ child: Text(
+ 'Shift ↵ for a new line',
+ style: grid.AppType.monoMeta(
+ color: grid.AppPalette.textSecondary,
+ ),
),
),
const SizedBox(width: 10),
AppIconButton(
- icon: LucideIcons.arrowUp,
+ icon: AppIcons.arrowUp,
tooltip: 'Send to director',
onPressed: !model.canChat || model.sending
? null
diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dart
index e8a1880ac..9dabdb102 100644
--- a/desktop/lib/screens/login_screen.dart
+++ b/desktop/lib/screens/login_screen.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
@@ -118,7 +119,7 @@ class LoginScreen extends StatelessWidget {
iconSize: 18,
visualDensity: VisualDensity.compact,
color: grid.AppPalette.textSecondary,
- icon: const Icon(Icons.close),
+ icon: const Icon(AppIcons.close),
onPressed: onClose,
),
),
@@ -379,7 +380,7 @@ class _ActionState extends State<_Action> {
autofocus: true,
onPressed: signingOutFailed ? notifier.logout : notifier.login,
icon: Icon(
- signingOutFailed ? Icons.logout : Icons.login,
+ signingOutFailed ? AppIcons.logOut : AppIcons.logIn,
size: grid.AppControl.iconSize,
),
label: Text(signingOutFailed ? 'Retry sign out' : 'Sign in'),
@@ -451,7 +452,7 @@ class _ActionState extends State<_Action> {
onPressed: notifier.openingLoginBrowser
? null
: notifier.openLoginBrowser,
- icon: const Icon(Icons.open_in_new, size: 16),
+ icon: const Icon(AppIcons.externalLink, size: 16),
label: Text(
notifier.openingLoginBrowser
? 'Opening browser…'
@@ -461,7 +462,7 @@ class _ActionState extends State<_Action> {
TextButton.icon(
onPressed: _copying ? null : _copyLink,
icon: Icon(
- _copiedUrl == url ? Icons.check : Icons.content_copy,
+ _copiedUrl == url ? AppIcons.check : AppIcons.copy,
size: 16,
),
label: Semantics(
@@ -525,7 +526,7 @@ class _ErrorTile extends StatelessWidget {
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Icon(Icons.error_outline, size: 16, color: danger),
+ Icon(AppIcons.circleAlert, size: 16, color: danger),
const SizedBox(width: 8),
Expanded(
child: Text(
@@ -574,7 +575,7 @@ class _Seal extends StatelessWidget {
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
- Icon(Icons.lock_outline, size: 13, color: grid.AppPalette.teal),
+ Icon(AppIcons.lock, size: 13, color: grid.AppPalette.teal),
const SizedBox(width: 8),
Text(
'End-to-end encrypted',
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index db3057b7c..b44159632 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -3,6 +3,7 @@ import 'dart:async';
import 'dart:convert';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/foundation.dart'
show ValueListenable, kIsWeb, listEquals;
@@ -10,7 +11,6 @@ import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:xterm/xterm.dart' show TerminalTheme;
import '../core/runtime_platform.dart';
@@ -73,12 +73,12 @@ import '../widgets/harness_activity_mark.dart';
import '../widgets/workspace_status_line.dart';
import '../widgets/workspace_pull_request_label.dart';
import '../widgets/workspace_bar_control.dart';
-import '../widgets/workspace_tab_close.dart';
import '../widgets/session_work_dialog.dart';
import '../widgets/web_download_button.dart';
import '../widgets/workspace_share_button.dart';
import '../widgets/workspace_store_button.dart';
import '../widgets/grid_model_picker.dart';
+import '../widgets/workspace_subscription_usage.dart';
import '../store/store_mark.dart';
import '../store/store_screen.dart';
import '../widgets/harness_start_page.dart';
@@ -94,6 +94,9 @@ import '../widgets/restart_agent_action.dart';
import '../widgets/new_agent_dialog.dart';
import '../widgets/box_chrome.dart';
import '../widgets/new_harness_form.dart';
+import '../widgets/desktop_chrome.dart';
+import '../widgets/desktop_search_panel.dart';
+import '../widgets/desktop_workspace_tab.dart';
import '../widgets/open_harness_intent.dart';
import '../widgets/pane_grid.dart';
import '../widgets/remote_folder_picker.dart';
@@ -101,7 +104,6 @@ import '../widgets/shortcuts_sheet.dart';
import '../widgets/harness_customize_pane.dart';
import '../shared/widgets/app_dialog.dart';
import '../widgets/swarm_dialogs.dart';
-import '../widgets/swarm_search_input.dart';
import '../widgets/swarm_command_picker.dart';
import '../widgets/swarm_switcher.dart';
import '../widgets/swarm_resource_preview.dart';
@@ -137,6 +139,7 @@ import '../widgets/daemon_slot.dart';
import '../widgets/workspace_quick_start.dart';
import '../widgets/workspace_start_guide.dart';
import '../widgets/workspace_welcome.dart';
+import '../widgets/workspace_machine_prompt.dart';
import '../shortcuts/keyboard_practice.dart';
import '../widgets/agent_alert_banners.dart';
import '../settings/experimental_features.dart';
@@ -196,8 +199,8 @@ enum _NewHarnessSource { workspace, product }
/// Drafts belong to the entry's source, before the person edits its defaults.
/// Product requests also name an agent explicitly: two Store pages must never
-/// resume one another's drafts. Placement remains separate, so Cmd-T and Cmd-O
-/// can resume the same workspace draft in the newly requested destination.
+/// resume one another's drafts. Empty tabs also own their draft individually;
+/// search and Cmd-N return to that tab's reviewed choices.
typedef _NewHarnessContext = ({
_NewHarnessSource source,
String machineId,
@@ -205,27 +208,9 @@ typedef _NewHarnessContext = ({
String? sourceAgentId,
String? folder,
String? projectName,
+ String? welcomeTabId,
});
-/// The command box's title line, a step quieter than the rows under it. The
-/// box is drawn on the terminal's ground, so its muted ink comes from there.
-TextStyle get _boxCaption => grid.AppType.monoLabel(
- color: terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- ).muted,
- fontWeight: FontWeight.w400,
-);
-
-/// The veil a workspace dialog drops over the panes behind it. Near-black on a
-/// dark palette; on a light one a near-black sheet would be the loudest thing
-/// on screen, so it is the workspace's own grey, which still sits a step below
-/// the dialog's lighter ground.
-Color get _workspaceVeil => grid.AppTheme.pick(
- grid.AppPalette.swarmField,
- Colors.black,
-).withValues(alpha: .94);
-
class _SwarmScreenState extends State<SwarmScreen> {
/// The title bar's seam: the `harness/swarm_tabs` channel on macOS — and
/// in anything forced onto the native-tabs path, so a test can still mock
@@ -262,7 +247,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
skipTraversal: true,
);
late int _tabStripRequest;
- final _focusedModelController = GridModelPickerController();
OverlayEntry? _modelsOverlay;
VoidCallback? _unregisterModels;
OverlayEntry? _harnessesOverlay;
@@ -396,25 +380,33 @@ class _SwarmScreenState extends State<SwarmScreen> {
final _searchCatalog = SwarmSearchCatalog();
final _searchText = TextEditingController();
final _searchFocus = FocusNode(debugLabel: 'Search harnesses');
+ final _searchDialogScope = FocusScopeNode(
+ debugLabel: 'Search dialog',
+ traversalEdgeBehavior: TraversalEdgeBehavior.closedLoop,
+ );
// Prefix edits switch between command and resource layouts. Keep the same
// editor mounted so its text-input connection and composition survive.
late GlobalKey _searchInputKey;
final _tabScroll = ScrollController();
+ final _tabShortcutHints = ValueNotifier(false);
({String activeId, List<String> order, double viewport, List<double> widths})?
_tabGeometry;
bool _tabRevealScheduled = false;
SwarmSearchController? _search;
OverlayEntry? _searchOverlay;
DeviceFinder? _searchDevice;
- final _resourcePreviewKey = GlobalKey();
+ var _resourcePreviewKey = GlobalKey();
/// New Harness, open in the box. Never open beside the search: they are two
/// modes of one surface, and opening either closes the other.
NewHarnessController? _newHarness;
+ bool _newHarnessEmbedded = false;
+ bool _welcomeEntryScheduled = false;
DeviceFormPort? _newHarnessDevicePort, _deviceFormPort;
String? _deviceFormId, _deviceFormMachine;
String _deviceFormSurface = 'new';
OverlayEntry? _newHarnessOverlay;
+ var _newHarnessFormKey = GlobalKey<NewHarnessFormState>();
/// Escape keeps unfinished work with the machine/project/agent it started
/// from. Switching context must not carry a task into the wrong project or
@@ -436,6 +428,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
bool _pickingFolder = false;
bool _newHarnessHidden = false;
bool _routeIsCurrent = true;
+ bool _footerPreviewCurrent = false;
String? _linkDialogMachineId;
bool _browserMachineSetupHandled = false;
String? _nativeState;
@@ -463,19 +456,85 @@ class _SwarmScreenState extends State<SwarmScreen> {
Widget _startGuide() => WorkspaceWelcome(
key: ValueKey('welcome:${app.activeSwarmId}'),
onCommand: _runShortcut,
+ composerBuilder: newHarnessOpensInBox
+ ? (recent) => _newHarnessEmbedded && _newHarness != null
+ ? _newHarnessContent(footer: recent)
+ : Center(
+ child: SizedBox(
+ width: 680,
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ WorkspaceMachinePrompt(
+ loading: app.machinesLoading,
+ preparing: app.localMachineState != null,
+ onChoose: () => unawaited(_openMachines()),
+ ),
+ if (recent != null) ...[
+ const SizedBox(height: 56),
+ recent,
+ ],
+ ],
+ ),
+ ),
+ ),
+ )
+ : null,
// What to pick up, opened into this tab the way Cmd-P opens it: a harness
// as itself, a conversation Harness did not start as a harness resuming it.
app: app,
projects: _projects.projects,
- onOpen: (row) => unawaited(
- _activateSearch(
- SwarmSearchSelection(row),
- app.activeSwarmId,
- placement: HarnessPlacement.currentTab,
- ),
- ),
+ onOpen: (row) {
+ if (_newHarness?.requestDismiss() == false) return;
+ _closeNewHarness(restoreFocus: false);
+ unawaited(
+ _activateSearch(
+ SwarmSearchSelection(row),
+ app.activeSwarmId,
+ placement: HarnessPlacement.currentTab,
+ ),
+ );
+ },
);
+ bool get _canShowWelcomeComposer =>
+ newHarnessOpensInBox &&
+ mounted &&
+ _shortcutsEnabled &&
+ app.panes.isEmpty &&
+ !app.activeSwarm.isStore &&
+ !app.activeSwarm.isOrchestrator &&
+ _newHarness == null &&
+ _search == null &&
+ !_commandBarOpen &&
+ !_pickingFolder &&
+ app.localMachineState != null;
+
+ void _scheduleWelcomeComposer() {
+ if (_welcomeEntryScheduled || !_canShowWelcomeComposer) return;
+ _welcomeEntryScheduled = true;
+ final tab = app.activeSwarmId;
+ WidgetsBinding.instance.addPostFrameCallback((_) async {
+ try {
+ if (!_canShowWelcomeComposer || app.activeSwarmId != tab) return;
+ await _newAgent(
+ stillCurrent: () =>
+ _canShowWelcomeComposer && app.activeSwarmId == tab,
+ );
+ } finally {
+ _welcomeEntryScheduled = false;
+ // Switching tabs while defaults load must schedule the new page too.
+ if (mounted && app.activeSwarmId != tab) _scheduleWelcomeComposer();
+ }
+ });
+ // Also reached after a search overlay's final frame, when there would
+ // otherwise be no next frame to mount the restored page draft.
+ WidgetsBinding.instance.scheduleFrame();
+ }
+
void _showKeyboardShortcuts() {
if (_newHarness?.requestDismiss() == false) return;
_closeNewHarness(restoreFocus: false);
@@ -511,7 +570,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.announceWindowForeground();
},
onHide: app.announceWindowForeground,
- onInactive: app.announceWindowForeground,
+ onInactive: () {
+ _tabShortcutHints.value = false;
+ app.announceWindowForeground();
+ },
// Whether the app is in front of anyone decides whether the model surfaces refresh at all
// (`AppNotifier.foreground`): a minimised or background window asks no daemon anything.
onStateChange: app.appLifecycleChanged,
@@ -598,6 +660,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_spokenTasks = app.spokenTasks.listen(_openSpokenTask);
// The app's shared controller, so this menu and every pane's model picker show one reading.
_modelsMenu = widget.modelsMenu ?? app.modelsMenu;
+ _modelsMenu!.addListener(_subscriptionUsageChanged);
app.modelManager.addListener(_modelManagerChanged);
_modelsRequests = app.modelsRequests.listen((_) {
if (mounted && !_modelsVisible) {
@@ -720,6 +783,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_onboarding.removeListener(_onboardingChanged);
if (widget.onboarding == null) _onboarding.dispose();
app.modelManager.removeListener(_modelManagerChanged);
+ _modelsMenu?.removeListener(_subscriptionUsageChanged);
app.modelManager.setPanelVisible(false);
_modelsRequests?.cancel();
_keymap.removeListener(_keymapChanged);
@@ -745,15 +809,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
_searchDevice?.close();
_search?.dispose();
_pickerModels?.dispose();
- _focusedModelController.dispose();
_previewControls.dispose();
_newHarnessOverlay?.remove();
_newHarnessOverlay?.dispose();
_newHarness?.dispose();
_navigation.dispose();
_searchFocus.dispose();
+ _searchDialogScope.dispose();
_searchText.dispose();
_tabScroll.dispose();
+ _tabShortcutHints.dispose();
_canvasFocus.dispose();
_shellFocus.dispose();
_startSearchFocus.dispose();
@@ -856,7 +921,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_pickerModalDepth > 0 ||
_commandBarOpen ||
(finding
- ? _newHarness != null ||
+ ? (_newHarness != null && !_newHarnessEmbedded) ||
_modelsOverlay != null ||
_harnessesOverlay != null
: _search != null ||
@@ -930,7 +995,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
final target = _search!.targetId;
final split = _search!.split;
final placement = _search!.placement;
- final task = _search!.createTask;
+ final fallbackTask = _search!.createTask;
final selected = _search!.selected;
final machineId =
_search!.scopedMachineId ??
@@ -942,7 +1007,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
swarmId: target,
split: split,
placement: placement,
- task: task,
+ fallbackTask: fallbackTask,
),
);
return;
@@ -986,6 +1051,22 @@ class _SwarmScreenState extends State<SwarmScreen> {
(_lastWorkspace?.$2 == true && app.panes.isNotEmpty))) {
_closeSearch(restoreFocus: false);
}
+ if (_newHarnessEmbedded && _newHarness?.swarmId != app.activeSwarmId) {
+ _closeNewHarness(restoreFocus: false);
+ }
+ // A successful creation removes its form through onCreated. Opening a
+ // recent session or restoring a pane can replace the page independently.
+ if (_newHarnessEmbedded && app.panes.isNotEmpty) {
+ final box = _newHarness;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted &&
+ _newHarnessEmbedded &&
+ identical(_newHarness, box) &&
+ app.panes.isNotEmpty) {
+ _closeNewHarness(restoreFocus: false);
+ }
+ });
+ }
final workspace = (app.activeSwarmId, app.panes.isEmpty);
if (_lastWorkspace == workspace) return;
if (_commandBarOpen && _lastWorkspace != null) {
@@ -1012,39 +1093,60 @@ class _SwarmScreenState extends State<SwarmScreen> {
_closeNewHarness(restoreFocus: false);
String? next;
await _dialog(() async {
- next = await showDialog<String>(
+ next = await showAppDialog<String>(
context: context,
builder: (context) => Dialog(
- backgroundColor: grid.AppPalette.swarmWelcome,
+ backgroundColor: Colors.transparent,
+ elevation: 0,
insetPadding: const EdgeInsets.all(24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 1200, maxHeight: 800),
- child: Column(
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(20, 8, 8, 0),
- child: Row(
- children: [
- Text('Quick Start', style: grid.AppType.heading()),
- const Spacer(),
- TextButton(
- onPressed: () => Navigator.pop(context, 'tour'),
- child: const Text('Try the keyboard tour'),
- ),
- IconButton(
- tooltip: 'Close',
- onPressed: () => Navigator.pop(context),
- icon: const Icon(Icons.close, size: 18),
- ),
- ],
+ child: DesktopDialogSurface(
+ child: Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 16, 16, 0),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final compact =
+ constraints.maxWidth <
+ MediaQuery.textScalerOf(context).scale(470);
+ final tour = TextButton(
+ onPressed: () => Navigator.pop(context, 'tour'),
+ child: const Text('Try the keyboard tour'),
+ );
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Quick Start',
+ style: DesktopChrome.heading(),
+ ),
+ ),
+ if (!compact) tour,
+ IconButton(
+ tooltip: 'Close',
+ onPressed: () => Navigator.pop(context),
+ icon: const Icon(AppIcons.close, size: 18),
+ ),
+ ],
+ ),
+ if (compact) tour,
+ ],
+ );
+ },
+ ),
),
- ),
- Expanded(
- child: WorkspaceStartGuide(
- onShortcuts: () => Navigator.pop(context, 'shortcuts'),
+ Expanded(
+ child: WorkspaceStartGuide(
+ onShortcuts: () => Navigator.pop(context, 'shortcuts'),
+ ),
),
- ),
- ],
+ ],
+ ),
),
),
),
@@ -1335,6 +1437,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
}
+ WorkspaceSubscriptionUsage get _subscriptionUsage =>
+ WorkspaceSubscriptionUsage.fromRows(_modelsMenu?.rows ?? const []);
+
+ void _subscriptionUsageChanged() {
+ if (!mounted) return;
+ if (_native) _syncNative();
+ setState(() {});
+ }
+
void _toolbarNoticesChanged() {
if (!mounted) return;
_modelsOverlay?.markNeedsBuild();
@@ -1527,7 +1638,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
final agent = focused.agent;
if (agent == null) return;
final machineId = focused.pane.machineId;
- await showDialog<void>(
+ await showAppDialog<void>(
context: context,
builder: (_) => SessionWorkDialog(
agent: agent,
@@ -1619,28 +1730,25 @@ class _SwarmScreenState extends State<SwarmScreen> {
'foreground': terminalTheme.foreground.toARGB32(),
'selection': terminalTheme.selection.toARGB32(),
},
- 'focusedModel': focused == null || !modelPickerSupports(focused.engine)
- ? null
- : {
- 'text': focused.modelLabel,
- 'segments': [
- {
- 'text': focused.modelLabel,
- 'foreground': terminalTheme.foreground.toARGB32(),
- },
- ],
- 'detail': [
- _canSwitchFocusedModel(focused)
- ? 'Switch model · Subscription or local models'
- : null,
- focused.agent?.gridModel == null
- ? null
- : focused.agent?.gridWebSearch?.sentence,
- ].whereType<String>().join('\n'),
- 'interactive': _canSwitchFocusedModel(focused),
- 'paneId': focused.pane.id,
- 'agentId': focused.agentId,
- },
+ 'subscriptionUsage': {
+ 'text': _subscriptionUsage.text,
+ 'label': _subscriptionUsage.detail,
+ 'detail': _subscriptionUsage.detail,
+ 'segments': _subscriptionUsage
+ .paintSegments(
+ foreground: terminalTheme.foreground,
+ surface: grid.AppPalette.swarmField,
+ )
+ .map((part) => part.toJson())
+ .toList(),
+ 'interactive': _shortcutsEnabled,
+ },
+ 'footerCovered':
+ !_showWorkspaceFooter ||
+ (!_routeIsCurrent && !_footerPreviewCurrent) ||
+ (_newHarnessOverlay != null && !_newHarnessHidden) ||
+ _searchOverlay != null,
+ 'footerPassive': _footerPreviewCurrent && !_routeIsCurrent,
'focusedContext': focused == null
? null
: {
@@ -1767,8 +1875,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
{
'id': swarm.id,
'name': swarm.name,
- 'label':
- '${app.profileSwarms.indexOf(swarm) + 1}:${names[swarm.id]}',
+ 'label': names[swarm.id],
+ 'shortcutHint': _keymap.hint(
+ 'swarm.select_${app.profileSwarms.indexOf(swarm) + 1}',
+ ),
'kind': swarm.kind,
'agentCount': _tabAgents(swarm).length,
'engine': swarm.isStore ? 'store' : _tabEngine(swarm),
@@ -1936,19 +2046,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
}
- if (call.method == 'focusedModel') {
- if (args['paneId'] is int) {
- final expectedPane = args['paneId'];
- final expectedAgent = args['agentId'];
- await WidgetsBinding.instance.endOfFrame;
- final focused = WorkspacePaneContext.focused(app);
- if (focused != null &&
- focused.pane.id == expectedPane &&
- focused.agentId == expectedAgent &&
- _canSwitchFocusedModel(focused)) {
- _focusedModelController.open();
- }
- }
+ if (call.method == 'subscriptions') {
+ if (_shortcutsEnabled) _toggleModels(initialTab: ModelsTab.subscriptions);
return;
}
if (call.method == 'focusedContext') {
@@ -2449,7 +2548,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
- Future<void> _customize() => _dialog(() => showHarnessCustomizePane(context));
+ void _footerPreviewChanged(bool current) {
+ if (!mounted || _footerPreviewCurrent == current) return;
+ _footerPreviewCurrent = current;
+ if (_native) _syncNative();
+ }
+
+ Future<void> _showCustomizePane() => showHarnessCustomizePane(
+ context,
+ bottomInset: _native
+ ? workspaceBarControlHeight(context) + kWorkspaceInset
+ : 0,
+ onCurrentChanged: _footerPreviewChanged,
+ );
+
+ Future<void> _customize() => _dialog(_showCustomizePane);
Future<void> _settings([SettingsSection? section]) => _dialog(
() => showSettingsScreen(
@@ -2457,6 +2570,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app,
initialSection: section,
experimentalFeatures: _experimentalFeatures,
+ onCustomize: _showCustomizePane,
source: 'swarm',
compactBelow: widget.chrome?.compactBelow ?? 0,
),
@@ -2533,10 +2647,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? engine,
String? projectName,
String? task,
+ String? fallbackTask,
HarnessPlacement? placement,
_NewHarnessSource source = _NewHarnessSource.workspace,
bool Function()? stillCurrent,
}) async {
+ if (_newHarnessEmbedded &&
+ _newHarness != null &&
+ source == _NewHarnessSource.workspace &&
+ split == null &&
+ engine == null &&
+ machineId == null &&
+ task == null) {
+ _newHarnessFormKey.currentState?.focusComposer();
+ return;
+ }
final search = source == _NewHarnessSource.workspace ? _search : null;
// A pane never lands in the store tab: New Harness from there goes to
// the empty starter tab (or a fresh one), the way New Tab does.
@@ -2547,17 +2672,17 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
final target = swarmId ?? search?.targetId ?? app.activeSwarmId;
final requestedSplit = split ?? search?.split;
- // ⌘N from inside the search keeps what was typed: it is what the create
- // row would have started the harness on.
- if (newHarnessOpensInBox) task ??= search?.createTask;
+ // Search text seeds a fresh composer, but switching back with ⌘N must not
+ // replace a draft. Explicit create rows and Store examples pass task.
+ if (newHarnessOpensInBox) fallbackTask ??= search?.createTask;
if (app.activeSwarmId != target) return;
// A fresh launcher uses saved choices on this computer. Only an explicit
// split inherits its source pane; changing focus never changes Cmd-N's
// defaults.
- final focused =
- source == _NewHarnessSource.workspace && requestedSplit != null
+ final draftSource = source == _NewHarnessSource.workspace
? app.focusedPane ?? _newTabSources[target]
: null;
+ final focused = requestedSplit != null ? draftSource : null;
final machine = focused == null ? null : app.stateOf(focused.machineId);
final agent = machine?.agents
.where((agent) => agent.id == focused?.agentId)
@@ -2601,11 +2726,22 @@ class _SwarmScreenState extends State<SwarmScreen> {
split: requestedSplit,
engine: engine,
placement: placement,
- task: task,
+ task: task ?? fallbackTask,
);
return;
}
final inherited = agent?.engine;
+ final embedded =
+ source == _NewHarnessSource.workspace &&
+ requestedSplit == null &&
+ app.panes.isEmpty &&
+ !app.activeSwarm.isStore &&
+ !app.activeSwarm.isOrchestrator;
+ final welcomeOrigin = embedded
+ ? _newHarnessDrafts.keys
+ .where((key) => key.welcomeTabId == target)
+ .lastOrNull
+ : null;
_openNewHarness(
machineId: id,
// ⌘⇧T is how a shell is made; New Harness from a shell means an agent.
@@ -2618,14 +2754,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
initialFolder == null &&
source == _NewHarnessSource.product,
task: task,
- draftContext: (
- source: source,
- machineId: id,
- requestedEngine: engine,
- sourceAgentId: focused?.agentId,
- folder: initialFolder,
- projectName: projectName,
- ),
+ fallbackTask: fallbackTask,
+ embedded: embedded,
+ draftContext:
+ welcomeOrigin ??
+ (
+ source: source,
+ machineId: id,
+ requestedEngine: engine,
+ sourceAgentId: draftSource?.agentId,
+ // Remembered defaults may change while this draft is dismissed.
+ // Only an explicitly requested folder defines its ownership.
+ folder: folder ?? paneProject?.cwd,
+ projectName: projectName,
+ welcomeTabId: embedded ? target : null,
+ ),
swarmId: target,
split: requestedSplit,
placement: placement,
@@ -2682,6 +2825,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
swarmId: swarmId,
split: split,
placement: returnedPlacement ?? placement,
+ embedded: draftContext?.welcomeTabId != null && app.panes.isEmpty,
);
return;
}
@@ -2700,11 +2844,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? projectName,
bool autoProject = false,
String? task,
+ String? fallbackTask,
NewHarnessDraft? draft,
_NewHarnessContext? draftContext,
required String swarmId,
PaneSplitRequest? split,
HarnessPlacement? placement,
+ bool embedded = false,
}) {
// A dialog's pop future can complete before didChangeDependencies refreshes
// the cached route flag. Its live route already owns the next prompt.
@@ -2723,6 +2869,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
sourceAgentId: app.focusedPane?.agentId,
folder: folder,
projectName: projectName,
+ welcomeTabId: embedded ? swarmId : null,
);
bool matchesSelection(NewHarnessDraft candidate) =>
origin.requestedEngine == null ||
@@ -2755,22 +2902,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
if (_search != null) _closeSearch(restoreFocus: false);
_closeCommandBar(restoreFocus: false);
- _searchReturnFocus ??= FocusManager.instance.primaryFocus;
+ if (!embedded) _searchReturnFocus ??= FocusManager.instance.primaryFocus;
if (_native) _preparePaneFocus();
- _canvasFocus.descendantsAreFocusable = false;
+ _newHarnessEmbedded = embedded;
+ _canvasFocus.descendantsAreFocusable = embedded;
_newHarnessContext = origin;
- // Consume once. Explicit text from search starts a fresh task with the
- // inherited defaults; an empty search resumes this context's whole draft.
+ // Consume once. ⌘N resumes this context's whole draft, even after typing
+ // in search. Only an explicit new-task action replaces ordinary edits.
final savedDraft = _newHarnessDrafts[origin];
// A lost reply always restores its exact receipt. Otherwise explicit
- // product/machine choices and freshly typed tasks win over old defaults.
+ // product/machine choices and explicit task requests win over old defaults.
final resumed =
draft ??
(savedDraft != null &&
(savedDraft.attempt?.awaitingConfirmation == true ||
- (origin.source != _NewHarnessSource.workspace &&
- task == null &&
- matchesSelection(savedDraft)))
+ (task == null && matchesSelection(savedDraft)))
? savedDraft
: null);
if (resumed != null) _newHarnessDrafts.remove(origin);
@@ -2781,7 +2927,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
harnessId: harnessId,
folder: folder,
projectName: projectName,
- task: task,
+ task: task ?? (resumed == null ? fallbackTask : null),
draft: resumed,
autoProject: autoProject,
offersStore: true,
@@ -2789,42 +2935,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
split: split,
placement: placement,
);
- final content = NewHarnessForm(
- controller: box,
- devicePort: _newHarnessDevicePort = DeviceFormPort(),
- onCreated: () {
- _closeNewHarness(restoreFocus: false, keepDraft: false);
- unawaited(_focusCreatedPane());
- },
- onClose: () {
- final target = box.swarmId ?? app.activeSwarmId;
- _closeNewHarness();
- app.cancelSwarmDraft(target);
- },
- onBrowse: () => _browseForNewHarness(box),
- onStore: _openStore,
- onLinkProfile: () => unawaited(_linkProfileForNewHarness(box)),
- onNeedsForm: () {
- if (box.busy || box.checking) {
- box.warn('Check the pending creation before changing forms.');
- return;
- }
- final draft = box.draft;
- _closeNewHarness(restoreFocus: false, keepDraft: false);
- unawaited(
- _newAgentForm(
- machineId: draft.machineId,
- initialDraft: draft,
- draftContext: origin,
- returnToPrompt: true,
- swarmId: swarmId,
- split: split,
- placement: box.effectivePlacement,
- returnedPlacement: box.placement,
- ),
- );
- },
- );
+ _newHarnessFormKey = GlobalKey<NewHarnessFormState>();
+ _newHarnessDevicePort = DeviceFormPort();
+ if (embedded) {
+ setState(() {});
+ return;
+ }
+ final content = _newHarnessContent();
_newHarnessOverlay = OverlayEntry(
// Hidden, not removed, while a dialog ROUTE is up — see
// [_withNewHarnessHidden]. The form keeps its State and its draft.
@@ -2839,28 +2956,18 @@ class _SwarmScreenState extends State<SwarmScreen> {
return Stack(
children: [
Positioned.fill(
- child: BlockSemantics(
- child: GestureDetector(
- key: const ValueKey('new-harness-dismiss'),
- behavior: HitTestBehavior.opaque,
- onTap: () {
- if (box.requestDismiss()) {
- final target = box.swarmId ?? app.activeSwarmId;
- _closeNewHarness();
- app.cancelSwarmDraft(target);
- }
- },
- // Keep the workspace quiet behind the focused pane.
- child: ColoredBox(color: _workspaceVeil),
- ),
+ child: DesktopDialogBackdrop(
+ key: const ValueKey('new-harness-dismiss'),
+ onDismiss: () => _newHarnessFormKey.currentState
+ ?.dismissFromOutside(),
),
),
Positioned.fill(
top: _native ? 0 : _tabBarHeight,
child: Padding(
- padding: EdgeInsets.symmetric(
- horizontal: terminalCellSizeOf(context).width * 2,
- vertical: terminalCellSizeOf(context).height,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 20,
+ vertical: 24,
),
child: content,
),
@@ -2874,6 +2981,52 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
);
Overlay.of(context).insert(_newHarnessOverlay!);
+ if (_native) _syncNative();
+ }
+
+ Widget _newHarnessContent({Widget? footer}) {
+ final box = _newHarness!;
+ final origin = _newHarnessContext!;
+ return NewHarnessForm(
+ key: _newHarnessFormKey,
+ controller: box,
+ desktop: true,
+ embedded: _newHarnessEmbedded,
+ footer: footer,
+ devicePort: _newHarnessDevicePort,
+ onCreated: () {
+ _closeNewHarness(restoreFocus: false, keepDraft: false);
+ unawaited(_focusCreatedPane());
+ },
+ onClose: () {
+ final target = box.swarmId ?? app.activeSwarmId;
+ _closeNewHarness();
+ app.cancelSwarmDraft(target);
+ },
+ onBrowse: () => _browseForNewHarness(box),
+ onStore: _openStore,
+ onLinkProfile: () => unawaited(_linkProfileForNewHarness(box)),
+ onNeedsForm: () {
+ if (box.busy || box.checking) {
+ box.warn('Check the pending creation before changing forms.');
+ return;
+ }
+ final draft = box.draft;
+ _closeNewHarness(restoreFocus: false, keepDraft: false);
+ unawaited(
+ _newAgentForm(
+ machineId: draft.machineId,
+ initialDraft: draft,
+ draftContext: origin,
+ returnToPrompt: true,
+ swarmId: box.swarmId ?? app.activeSwarmId,
+ split: box.split,
+ placement: box.effectivePlacement,
+ returnedPlacement: box.placement,
+ ),
+ );
+ },
+ );
}
Future<void> _focusCreatedPane() async {
@@ -2915,6 +3068,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (entry == null) return show();
_newHarnessHidden = true;
entry.markNeedsBuild();
+ if (_native) _syncNative();
try {
return await show();
} finally {
@@ -2922,6 +3076,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
// The box may have been closed under the dialog; the flag is reset
// either way so the next one does not open invisible.
_newHarnessOverlay?.markNeedsBuild();
+ if (_native && mounted) _syncNative();
}
}
@@ -2946,7 +3101,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
notifier: app,
machineId: machineId,
initialPath: box.project.folder,
- terminal: true,
+ desktop: true,
),
);
} finally {
@@ -2984,6 +3139,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
notifier: app,
machineId: machineId,
initialPath: initialPath,
+ desktop: true,
),
);
} finally {
@@ -3028,7 +3184,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
_newHarnessOverlay?.remove();
_newHarnessOverlay?.dispose();
_newHarnessOverlay = null;
+ if (_native && mounted) _syncNative();
_newHarness = null;
+ final wasEmbedded = _newHarnessEmbedded;
+ _newHarnessEmbedded = false;
+ if (wasEmbedded && mounted) setState(() {});
_newHarnessDevicePort?.detach();
_newHarnessDevicePort = null;
if (keepDraft && _newHarnessContext != null) {
@@ -3473,6 +3633,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
bool _noteKey(KeyEvent event) {
+ // Paint hints only; the existing keymap still owns every shortcut.
+ _tabShortcutHints.value = HardwareKeyboard.instance.isMetaPressed;
// Off, this is not here at all: every key goes where it went before.
if (event is! KeyDownEvent || _zoo.daemons == DaemonsSwitch.off) {
return false;
@@ -4071,8 +4233,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
math.max(0.0, MediaQuery.sizeOf(context).width - 32),
);
return Positioned(
- top: (_native ? 0.0 : _tabBarHeight) + 8,
- right: 12,
+ top: kIsWeb ? _tabBarHeight + 8 : null,
+ bottom: kIsWeb ? null : _statusBarHeight + 8,
+ right: kIsWeb ? 12 : null,
+ left: kIsWeb ? null : 16,
child: IgnorePointer(
child: ListenableBuilder(
listenable: _face,
@@ -4307,6 +4471,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_daemonOverlay = OverlayEntry(
builder: (context) => _anchoredBesideSlot(
onBarrierTap: _closeDaemon,
+ width: 480,
child: DaemonPanel(
key: ValueKey(_zoo.scope),
face: _face,
@@ -4347,6 +4512,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
required Widget child,
required VoidCallback onBarrierTap,
int cells = 46,
+ double? width,
}) => LayoutBuilder(
builder: (context, constraints) {
final top = _native ? 0.0 : _tabBarHeight;
@@ -4366,7 +4532,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
right: 10,
width: (constraints.maxWidth - 20).clamp(
0,
- terminalCellSizeOf(context).width * cells,
+ width ?? terminalCellSizeOf(context).width * cells,
),
child: ConstrainedBox(
constraints: BoxConstraints(
@@ -4603,6 +4769,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
void _togglePaneModels() => _toggleModels();
+ void _openPaneModels(int paneId, String machineId, String agentId) {
+ if (!_shortcutsEnabled) return;
+ final pane = app.panes.where((pane) => pane.id == paneId).firstOrNull;
+ if (pane == null ||
+ pane.machineId != machineId ||
+ pane.agentId != agentId) {
+ return;
+ }
+ app.focusPane(pane.id);
+ final focused = WorkspacePaneContext.focused(app);
+ if (focused != null && _canSwitchFocusedModel(focused)) {
+ _togglePaneModels();
+ }
+ }
+
void _bindModelSelection() {
final focused = WorkspacePaneContext.focused(app);
if (focused == null ||
@@ -4689,57 +4870,38 @@ class _SwarmScreenState extends State<SwarmScreen> {
20)
.clamp(0, 620),
),
- child: DecoratedBox(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(14),
- boxShadow: [
- BoxShadow(
- color: Colors.black.withValues(alpha: .35),
- blurRadius: 36,
- offset: const Offset(0, 12),
- ),
- ],
- border: Border.all(
- color: grid.AppPalette.textPrimary.withValues(alpha: .12),
- ),
- ),
- child: Padding(
- padding: const EdgeInsets.all(1),
- child: KeymapProvider(
- keymap: _keymap,
- child: HarnessSessionManager(
- app: app,
- introduction:
- _onboarding.next == OnboardingStep.harnesses
- ? OnboardingCard(
- title: 'Run your first harness',
- description: 'Give an agent a task. Watch it get to work.',
- action: 'New harness',
- onAction: () {
- _closeHarnessControls(restoreFocus: false);
- _runShortcut('agent.new');
- },
- onDismiss: () => _onboarding.dismiss(
- OnboardingStep.harnesses,
- ),
- )
- : null,
- recent: _navigation.recent,
- onClose: _closeHarnessControls,
- onOpen: (row) async {
- final destination = swarmDestinations(app)
- .where((item) => item.id == row.id)
- .firstOrNull;
- if (destination == null) return false;
- final opened = await activateSwarmDestination(
- app,
- destination,
- destinationSwarmId: app.activeSwarmId,
- );
- return opened;
- },
- ),
- ),
+ child: KeymapProvider(
+ keymap: _keymap,
+ child: HarnessSessionManager(
+ app: app,
+ introduction: _onboarding.next == OnboardingStep.harnesses
+ ? OnboardingCard(
+ title: 'Run your first harness',
+ description:
+ 'Give an agent a task. Watch it get to work.',
+ action: 'New harness',
+ onAction: () {
+ _closeHarnessControls(restoreFocus: false);
+ _runShortcut('agent.new');
+ },
+ onDismiss: () =>
+ _onboarding.dismiss(OnboardingStep.harnesses),
+ )
+ : null,
+ recent: _navigation.recent,
+ onClose: _closeHarnessControls,
+ onOpen: (row) async {
+ final destination = swarmDestinations(app)
+ .where((item) => item.id == row.id)
+ .firstOrNull;
+ if (destination == null) return false;
+ final opened = await activateSwarmDestination(
+ app,
+ destination,
+ destinationSwarmId: app.activeSwarmId,
+ );
+ return opened;
+ },
),
),
),
@@ -4818,6 +4980,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
// boundary to keep its programmatic focus request out of the picker.
_canvasFocus.descendantsAreFocusable = false;
_searchInputKey = GlobalKey();
+ _resourcePreviewKey = GlobalKey();
_search = SwarmSearchController(
app,
_navigation.recent,
@@ -5075,6 +5238,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
final target = _search?.targetId;
_closeSearch();
if (target != null) app.cancelSwarmDraft(target);
+ unawaited(_ensureEmptyEntry());
}
Future<void> _ensureEmptyEntry() async {
@@ -5082,6 +5246,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
await WidgetsBinding.instance.endOfFrame;
if (mounted && _shortcutsEnabled && app.panes.isEmpty) {
_restoreEmptyFocus();
+ _scheduleWelcomeComposer();
}
}
@@ -5287,163 +5452,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
- // Search keeps keyboard focus while commands target the selected result.
- Widget ordered(double order, Widget child) =>
- FocusTraversalOrder(order: NumericFocusOrder(order), child: child);
- final chrome = widget.chrome;
- final bar = chrome?.pickerBar?.call(
- context,
- WorkspacePicker(
- search: search,
- focus: _focusSearch,
- close: _dismissSearch,
- ),
- );
- Widget withBar(Widget input) => bar == null
- ? input
- : Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [bar, input],
- );
- final panel = Material(
- key: const ValueKey('swarm-search-results'),
- elevation: 0,
- color: terminalTheme.background,
- surfaceTintColor: Colors.transparent,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(kTerminalCornerRadius),
- side: terminalPaneBorder(focused: true),
- ),
- clipBehavior: Clip.antiAlias,
- child: DefaultTextStyle.merge(
- style: terminalContentStyle(color: terminalTheme.foreground),
- child: FocusTraversalGroup(
- policy: OrderedTraversalPolicy(),
- // Fills its frame, as fzf does: the list takes every row the box
- // has rather than hugging its contents and leaving the rest dark.
- child: search.setupLayout
- ? SwarmSearchResults(
- search: search,
- onChoose: _chooseSearch,
- onRefocus: _focusSearch,
- terminal: true,
- bios: true,
- previewBuilder: preview,
- header: withBar(
- Semantics(
- label: search.hint,
- child: ReadlineKeys(
- controller: _searchText,
- onChanged: search.setQuery,
- child: SwarmSearchInput(
- key: _searchInputKey,
- inputKey: const ValueKey('swarm-search-input'),
- controller: _searchText,
- focusNode: _searchFocus,
- search: search,
- onClose: _dismissSearch,
- onChanged: search.setQuery,
- onOpen: _focusSearch,
- terminal: true,
- bios: true,
- cursorWidth: 2,
- hintText: search.hint,
- ),
- ),
- ),
- ),
- )
- : Column(
- children: [
- ?bar,
- if (search.title != search.placement?.title)
- Padding(
- padding: const EdgeInsets.fromLTRB(14, 9, 14, 2),
- child: Row(
- children: [
- Text(search.title, style: _boxCaption),
- if (search.placement ==
- HarnessPlacement.currentTab ||
- search.split != null)
- Expanded(
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 8,
- ),
- child: Text(
- '· ${search.targetName}',
- key: const ValueKey('swarm-search-target'),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: _boxCaption,
- ),
- ),
- )
- else
- const Spacer(),
- SwarmSearchCount(search: search, terminal: true),
- ],
- ),
- ),
- ordered(
- 1,
- Semantics(
- label: search.hint,
- child: ReadlineKeys(
- controller: _searchText,
- onChanged: search.setQuery,
- child: SwarmSearchInput(
- key: _searchInputKey,
- inputKey: const ValueKey('swarm-search-input'),
- controller: _searchText,
- focusNode: _searchFocus,
- search: search,
- onClose: _dismissSearch,
- onChanged: search.setQuery,
- onOpen: _focusSearch,
- height: 38,
-
- terminal: true,
- hintText: search.hint,
- ),
- ),
- ),
- ),
- Expanded(
- child: ordered(
- 2,
- SwarmSearchResults(
- search: search,
- onChoose: _chooseSearch,
- onRefocus: _focusSearch,
- fitRows: true,
- terminal: true,
- previewBuilder: preview,
- ),
- ),
- ),
- ordered(
- 3,
- SwarmSearchHints(
- search: search,
- onSubmit: () {
- final choice = search.submit();
- if (choice != null) unawaited(_chooseSearch(choice));
- },
- onAddHere: () {
- final choice = search.addHere();
- if (choice != null) unawaited(_chooseSearch(choice));
- },
- onClose: _dismissSearch,
- onQuery: (text) {
- search.setQuery(text);
- _focusSearch();
- },
- ),
- ),
- ],
- ),
+ final panel = DesktopSearchPanel(
+ key: _searchInputKey,
+ search: search,
+ editing: _searchText,
+ focusNode: _searchFocus,
+ onChoose: _chooseSearch,
+ onClose: _dismissSearch,
+ onRefocus: _focusSearch,
+ previewBuilder: preview,
+ hostBar: widget.chrome?.pickerBar?.call(
+ context,
+ WorkspacePicker(
+ search: search,
+ focus: _focusSearch,
+ close: _dismissSearch,
),
),
);
@@ -5458,7 +5481,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
selectionColor: terminalTheme.selection,
selectionHandleColor: terminalTheme.cursor,
),
- child: KeyHints(visible: chrome?.showsKeyHints ?? true, child: panel),
+ child: KeyHints(
+ visible: widget.chrome?.showsKeyHints ?? true,
+ child: panel,
+ ),
),
);
return Offstage(
@@ -5468,6 +5494,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: LayoutBuilder(
builder: (context, constraints) {
final contents = SwarmSearchKeys(
+ desktop: true,
search: search,
editing: _searchText,
onChoose: _chooseSearch,
@@ -5477,7 +5504,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
onCommands: _showSearchCommands,
previewControls: _previewControls,
onRefocus: _focusSearch,
- child: scoped,
+ child: FocusScope(node: _searchDialogScope, child: scoped),
);
return Stack(
children: [
@@ -5485,7 +5512,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
Positioned.fill(
child: ListenableBuilder(
listenable: search,
- builder: (context, _) => search.hasPreview
+ builder: (context, _) =>
+ search.hasPreview && !search.showsTypeHints
? const SizedBox.shrink()
: Offstage(child: preview()),
),
@@ -5493,26 +5521,26 @@ class _SwarmScreenState extends State<SwarmScreen> {
// A click outside closes it. Block the dimmed workspace from
// VoiceOver while the dialog owns the keyboard.
Positioned.fill(
- child: BlockSemantics(
- child: GestureDetector(
- key: const ValueKey('swarm-search-dismiss'),
- behavior: HitTestBehavior.opaque,
- onTap: _dismissSearch,
- child: ColoredBox(color: _workspaceVeil),
- ),
+ child: DesktopDialogBackdrop(
+ key: const ValueKey('swarm-search-dismiss'),
+ onDismiss: _dismissSearch,
),
),
Positioned.fill(
top: _native ? 0.0 : _tabBarHeight,
child: Align(
alignment: const Alignment(0, -0.12),
- // Big, like fzf, and FIXED: it does not grow with the
- // results, shrink with the query, or scale with the font.
- // Only a window too small to hold it clamps it, because
- // the alternative is drawing off the screen.
+ // The palette keeps its search field in place while the
+ // result list fits its matches inside this upper bound.
child: SizedBox(
- width: math.min(1480, constraints.maxWidth - 48),
- height: math.min(760, constraints.maxHeight - 88),
+ width: math.min(
+ DesktopSearchPanel.maxWidth,
+ constraints.maxWidth - 40,
+ ),
+ height: math.min(
+ DesktopSearchPanel.maxHeight,
+ constraints.maxHeight - 72,
+ ),
child: contents,
),
),
@@ -6198,7 +6226,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _closeCommandBar,
- child: const ColoredBox(color: kDialogVeilTint),
+ child: ColoredBox(color: dialogVeilTintOf(context)),
),
),
SafeArea(
@@ -6233,6 +6261,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
builder: (context, _) {
grid.AppTheme.watch(context);
_maybeLink();
+ _scheduleWelcomeComposer();
if (app.panes.isEmpty) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => _restoreEmptyFocus(),
@@ -6269,9 +6298,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
Focus(
focusNode: _tabStripFocus,
onKeyEvent: _onTabStripKey,
- child: _native
- ? const SizedBox.shrink()
- : MediaQuery.withNoTextScaling(child: _tabStrip()),
+ child: _native ? const SizedBox.shrink() : _tabStrip(),
),
if (_learning.active)
WorkspaceQuickStart(
@@ -6325,7 +6352,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: Row(
children: [
Icon(
- Icons.info_outline,
+ AppIcons.info,
size: 16,
// Orange is ~1.8:1 on a light panel.
color: grid.AppTheme.pick(
@@ -6353,7 +6380,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
? _projects.dismissError
: app.dismissError,
tooltip: 'Dismiss',
- icon: const Icon(Icons.close, size: 16),
+ icon: const Icon(AppIcons.close, size: 16),
),
],
),
@@ -6414,6 +6441,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: PaneGrid(
notifier: app,
swarmMode: true,
+ onOpenModels: _openPaneModels,
companionViewer:
_creatureEnabled && _zoo.loaded
? _companionViewer
@@ -6546,18 +6574,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
],
),
),
- MediaQuery.withNoTextScaling(
- child: _native
- ? SizedBox(
- key: const ValueKey('workspace-status-bar'),
- height: _statusBarHeight,
- child: _focusedModelPicker(
- WorkspacePaneContext.focused(app),
- menuOnly: true,
- ),
- )
- : _statusBar(),
- ),
+ if (_showWorkspaceFooter)
+ MediaQuery.withNoTextScaling(
+ child: _native
+ ? SizedBox(
+ key: const ValueKey('workspace-status-bar'),
+ height: _statusBarHeight,
+ )
+ : _statusBar(),
+ ),
],
),
),
@@ -6655,73 +6680,18 @@ class _SwarmScreenState extends State<SwarmScreen> {
!owner!.session!.readOnly;
}
- Widget _focusedModelPicker(
- WorkspacePaneContext? focused, {
- bool menuOnly = false,
- }) {
- if (focused == null ||
- focused.agentId == null ||
- !modelPickerSupports(focused.engine)) {
- return const SizedBox.shrink();
- }
- bool current() {
- final now = WorkspacePaneContext.focused(app);
- return now != null &&
- now.pane.id == focused.pane.id &&
- now.agentId == focused.agentId &&
- now.pane.machineId == focused.pane.machineId &&
- _canSwitchFocusedModel(now);
- }
-
- return GridModelPicker(
- key: ValueKey(('focused-model', focused.pane.id, focused.agentId)),
- controller: menuOnly ? _focusedModelController : null,
- menuOnly: menuOnly,
- paneHeader: true,
- enabled: _canSwitchFocusedModel(focused),
- notifier: app,
- machineId: focused.pane.machineId,
- currentModel: focused.agent?.gridModel,
- subscriptionModel: focused.agent?.modelName,
- subscriptionEffort: focused.agent?.modelEffort,
- webSearch: focused.agent?.gridWebSearch,
- engineLabel: focused.engine,
- onOpen: () {
- if (current()) _toggleModels();
- },
- onSelected: (model) {
- if (current()) {
- unawaited(
- app.retargetAgentToGridModel(
- focused.pane.machineId,
- focused.agentId!,
- model.id,
- gridName: model.grid,
- ),
- );
- }
- },
- onUseOwnLogin: () {
- if (current()) {
- unawaited(
- app.clearAgentGrid(focused.pane.machineId, focused.agentId!),
- );
- }
- },
- onRunLocalModel: () {
- if (current()) {
- unawaited(
- app.runLocalModel(context, machineId: focused.pane.machineId),
- );
- }
- },
- );
- }
-
// Include the pane's former bottom gutter in this row, so its controls sit
// halfway between the pane edge and window bottom. Pane height is unchanged.
- double get _statusBarHeight =>
- workspaceBarControlHeight(context) + kWorkspaceInset;
+ bool get _showWorkspaceFooter =>
+ !newHarnessOpensInBox ||
+ app.panes.isNotEmpty ||
+ app.activeSwarm.isStore ||
+ app.activeSwarm.isOrchestrator ||
+ _footerPreviewCurrent;
+
+ double get _statusBarHeight => _showWorkspaceFooter
+ ? workspaceBarControlHeight(context) + kWorkspaceInset
+ : 0;
Widget _statusBar() => LayoutBuilder(
builder: (context, constraints) {
@@ -6757,13 +6727,19 @@ class _SwarmScreenState extends State<SwarmScreen> {
: 0.0;
final download = kIsWeb && !_compact(context);
final downloadWidth = download ? available * .16 : 0.0;
- final modelWidth =
+ final usage = _subscriptionUsage;
+ final usageWidth =
math.max(
0.0,
- available - shareWidth - downloadWidth - cell.width * 5,
+ available -
+ shareWidth -
+ downloadWidth -
+ (!kIsWeb && _slotShown ? 44 : 0) -
+ cell.width * 5,
) *
- .4;
+ .45;
final paneContext = Row(
+ mainAxisAlignment: MainAxisAlignment.end,
children: [
if (focused != null)
Flexible(
@@ -6808,16 +6784,48 @@ class _SwarmScreenState extends State<SwarmScreen> {
padding: EdgeInsets.symmetric(horizontal: cell.width),
child: Row(
children: [
- Expanded(
- child: _zoo.loaded
- ? DaemonVoiceLine(
- face: _face,
- brain: _brain,
- onAnswer: _shortcutsEnabled ? _answerDaemon : null,
- fallback: paneContext,
- )
- : paneContext,
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: usageWidth),
+ child: WorkspaceBarControl(
+ key: const ValueKey('workspace-subscription-usage'),
+ label: usage.detail,
+ tooltip: usage.detail,
+ onPressed: _shortcutsEnabled
+ ? () =>
+ _toggleModels(initialTab: ModelsTab.subscriptions)
+ : null,
+ builder: (context, emphasized) => Padding(
+ padding: EdgeInsets.symmetric(horizontal: cell.width),
+ child: SizedBox(
+ height: workspaceBarControlHeight(context),
+ child: Center(
+ widthFactor: 1,
+ child: Text.rich(
+ TextSpan(
+ children: [
+ for (final part in usage.paintSegments(
+ foreground: theme.foreground,
+ surface: grid.AppPalette.swarmField,
+ ))
+ TextSpan(
+ text: part.text,
+ style: TextStyle(color: part.foreground),
+ ),
+ ],
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: workspaceBarTextStyle(
+ emphasized: emphasized,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
),
+ SizedBox(width: cell.width * 2),
+ if (!kIsWeb && _slotShown) _daemonTabButton(),
if (download) ...[
SizedBox(width: cell.width),
ConstrainedBox(
@@ -6839,13 +6847,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
],
- if (focused != null && modelPickerSupports(focused.engine)) ...[
- SizedBox(width: cell.width * 2),
- ConstrainedBox(
- constraints: BoxConstraints(maxWidth: modelWidth),
- child: _focusedModelPicker(focused),
- ),
- ],
+ Expanded(
+ child: _zoo.loaded
+ ? DaemonVoiceLine(
+ face: _face,
+ brain: _brain,
+ onAnswer: _shortcutsEnabled ? _answerDaemon : null,
+ fallback: paneContext,
+ )
+ : paneContext,
+ ),
],
),
),
@@ -6870,18 +6881,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
final activities = [for (final tab in shown) tabActivity(app, tab)];
final labels = [
for (var index = 0; index < shown.length; index++)
- '${index + 1}:${names[shown[index].id]}',
+ names[shown[index].id]!,
];
final toolHeight = workspaceBarControlHeight(context);
final prefs = appearancePrefsStore.value.prompt;
final storeWidth = math.min(
WorkspaceStoreButton.widthOf(context),
- math.max(0.0, constraints.maxWidth - cell.width * 14),
+ math.max(0.0, constraints.maxWidth - cell.width * 22),
);
final leadingWidth = chrome?.leadingWidth(context) ?? 0.0;
- final closeCells = chrome?.closesTabs == true
- ? kWorkspaceTabCloseCells
- : 0;
final tabBudget = math.max(
0.0,
constraints.maxWidth -
@@ -6893,21 +6901,14 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
_tabWidths = [
for (var i = 0; i < labels.length; i++)
- math.max(
- activities[i] == null
- ? 0
- : ('${i + 1}:'.length + 4 + closeCells) * cell.width,
- math.min(
- math.min(
- labels[i].characters.length +
- 2 +
- (activities[i] == null ? 0 : 2) +
- closeCells,
- 24,
- ) *
- cell.width,
- tabBudget,
+ math.min(
+ DesktopWorkspaceTab.widthOf(
+ context,
+ labels[i],
+ shortcutHint: _keymap.hint('swarm.select_${i + 1}'),
+ hasActivity: activities[i] != null,
),
+ tabBudget,
),
];
final total = _tabWidths.fold(0.0, (sum, width) => sum + width);
@@ -6917,7 +6918,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
key: const ValueKey('workspace-tab-bar'),
color: grid.AppPalette.swarmTabBar,
child: SizedBox(
- height: math.max(_tabBarHeight, cell.height * 2),
+ height: math.max(
+ _tabBarHeight,
+ MediaQuery.textScalerOf(context).scale(13) * 1.25 + 20,
+ ),
child: Row(
children: [
SizedBox(width: cell.width),
@@ -6945,9 +6949,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
labels[index],
swarm.name,
clipped:
- workspaceBarTextSizeOf(context, labels[index]).width +
- (activity == null ? 0 : cell.width * 2) >
- _tabWidths[index] - cell.width * 2,
+ DesktopWorkspaceTab.naturalWidth(
+ context,
+ labels[index],
+ shortcutHint: _keymap.hint(
+ 'swarm.select_${index + 1}',
+ ),
+ hasActivity: activity != null,
+ ) >
+ _tabWidths[index],
);
final tabHint = [
?nameHint,
@@ -6969,127 +6979,68 @@ class _SwarmScreenState extends State<SwarmScreen> {
unawaited(app.closeSwarm(swarm.id));
}
},
- child: GestureDetector(
- onDoubleTap: () => _rename(swarm.id),
- child: Center(
- child: WorkspaceBarControl(
- label:
- '${labels[index]}: ${swarm.name}${activity == null ? '' : ', ${activity.label}'}',
- tooltip: tabHint.isEmpty ? null : tabHint,
- selectedBackground: grid.AppPalette.swarmWelcome,
- selected: selected,
- highlighted:
- selected &&
- app.tabStripFocused &&
- _tabStripFocus.hasPrimaryFocus,
- onPressed: _shortcutsEnabled
- ? () => app.selectSwarm(swarm.id)
- : null,
- builder: (context, emphasized) => SizedBox(
- height: double.infinity,
- child: Padding(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width,
- ),
- child: _withTabClose(
- closeCells > 0,
- id: swarm.id,
- visible: selected || emphasized,
- color: theme.foreground,
- child: Center(
- child: activity == null
- ? Text(
- labels[index],
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- textAlign: TextAlign.center,
- style: workspaceBarTextStyle(
- color: theme.foreground,
- emphasized: emphasized,
- ),
- )
- : Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- '${index + 1}:',
- style: workspaceBarTextStyle(
- color: theme.foreground,
- emphasized: emphasized,
- ),
- ),
- Flexible(
- child: Text(
- names[swarm.id]!,
- maxLines: 1,
- overflow:
- TextOverflow.ellipsis,
- style:
- workspaceBarTextStyle(
- color:
- theme.foreground,
- emphasized:
- emphasized,
- ),
- ),
- ),
- SizedBox(width: cell.width),
- ListenableBuilder(
- listenable: _tabScroll,
- builder: (context, _) {
- final left = _tabWidths
- .take(index)
- .fold(
- 0.0,
- (a, b) => a + b,
- );
- final offset =
- _tabScroll.hasClients
- ? _tabScroll.offset
- : 0.0;
- return ActivityMark(
- key: ValueKey(
- 'tab-activity:${swarm.id}',
- ),
- activity: activity,
- color: activityColor(
- activity,
- theme,
- color: prefs.color,
- ),
- emphasized: emphasized,
- tooltip: false,
- visible:
- left <
- offset +
- tabsWidth &&
- left + _tabWidths[index] >
- offset,
- );
- },
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- ),
+ child: DesktopWorkspaceTab(
+ id: swarm.id,
+ onRename: () => _rename(swarm.id),
+ label: labels[index],
+ selected: selected,
+ showShortcuts: _tabShortcutHints,
+ shortcutHint: _keymap.hint(
+ 'swarm.select_${index + 1}',
),
+ tooltip: tabHint.isEmpty ? null : tabHint,
+ activityLabel: activity?.label,
+ highlighted:
+ selected &&
+ app.tabStripFocused &&
+ _tabStripFocus.hasPrimaryFocus,
+ onSelect: _shortcutsEnabled
+ ? () => app.selectSwarm(swarm.id)
+ : null,
+ onClose: _shortcutsEnabled
+ ? () => unawaited(app.closeSwarm(swarm.id))
+ : null,
+ activity: activity == null || activity.mark.isEmpty
+ ? null
+ : ListenableBuilder(
+ listenable: _tabScroll,
+ builder: (context, _) {
+ final left = _tabWidths
+ .take(index)
+ .fold(0.0, (a, b) => a + b);
+ final offset = _tabScroll.hasClients
+ ? _tabScroll.offset
+ : 0.0;
+ return ActivityMark(
+ key: ValueKey('tab-activity:${swarm.id}'),
+ activity: activity,
+ color: activityColor(
+ activity,
+ theme,
+ color: prefs.color,
+ ),
+ emphasized: selected,
+ tooltip: false,
+ visible:
+ left < offset + tabsWidth &&
+ left + _tabWidths[index] > offset,
+ );
+ },
+ ),
),
),
);
},
),
),
- _statusToolSymbol(
+ _statusToolIcon(
'new-tab',
- 'New Swarm',
+ 'New Tab',
_newTab,
- '+',
+ AppIcons.plus,
Size(cell.width * 3, toolHeight),
theme,
- tooltip: 'New Swarm ${_keymap.hint('swarm.new') ?? ''}',
+ tooltip: 'New Tab ${_keymap.hint('swarm.new') ?? ''}',
),
const Spacer(),
_searchButton(theme),
@@ -7100,7 +7051,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
tooltip: 'Harness Store ${_keymap.hint('app.store') ?? ''}',
onPressed: _shortcutsEnabled ? _openStore : null,
),
- if (_slotShown) _daemonTabButton(),
+ if (kIsWeb && _slotShown) _daemonTabButton(),
SizedBox(width: cell.width),
],
),
@@ -7135,7 +7086,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
width: workspaceBarCellSizeOf(context).width * 4,
height: workspaceBarControlHeight(context),
child: Icon(
- LucideIcons.search,
+ AppIcons.search,
size: 17,
color: theme.foreground.withValues(
alpha: !_shortcutsEnabled
@@ -7156,25 +7107,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
onPressed: _shortcutsEnabled ? _showNotificationInbox : null,
);
- /// A host's narrow bar (the web on a phone): its tab switcher in place of
- /// the tab list, and no Store button, which the host's menu already offers.
- /// A tab's label, with a close mark when the host closes tabs by mouse.
- Widget _withTabClose(
- bool closes, {
- required String id,
- required bool visible,
- required Color color,
- required Widget child,
- }) => !closes
- ? child
- : WorkspaceTabCloseSlot(
- tabId: id,
- visible: visible,
- color: color,
- onClose: () => unawaited(app.closeSwarm(id)),
- child: child,
- );
-
+ /// A compact host uses a tab switcher instead of the tab list.
Widget _compactTabStrip(WorkspaceChrome chrome, TerminalTheme theme) =>
Builder(
builder: (context) {
@@ -7196,7 +7129,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
_searchButton(theme),
_notificationsButton(theme),
- if (_slotShown) _daemonTabButton(),
+ if (kIsWeb && _slotShown) _daemonTabButton(),
SizedBox(width: cell.width),
],
),
@@ -7205,11 +7138,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
},
);
- Widget _statusToolSymbol(
+ Widget _statusToolIcon(
String id,
String label,
VoidCallback onPressed,
- String symbol,
+ IconData icon,
Size size,
TerminalTheme theme, {
String? tooltip,
@@ -7222,9 +7155,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
builder: (context, emphasized) => SizedBox.fromSize(
size: size,
child: Center(
- child: Text(
- symbol,
- style: workspaceBarTextStyle(emphasized: emphasized),
+ child: Icon(
+ icon,
+ size: AppIcons.inlineSize,
+ color: theme.foreground.withValues(
+ alpha: !_shortcutsEnabled
+ ? .28
+ : emphasized
+ ? 1
+ : .75,
+ ),
),
),
),
diff --git a/desktop/lib/settings/appearance/palette_section.dart b/desktop/lib/settings/appearance/palette_section.dart
index 69ee62ed3..41be81cd6 100644
--- a/desktop/lib/settings/appearance/palette_section.dart
+++ b/desktop/lib/settings/appearance/palette_section.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../../shared/theme/app_theme.dart' as grid;
@@ -89,12 +90,14 @@ class _PaletteChoice extends StatelessWidget {
),
side: WidgetStateProperty.resolveWith(
(states) => BorderSide(
- color: selected || states.contains(WidgetState.focused)
+ color: states.contains(WidgetState.focused)
+ ? palette.foreground
+ : selected
? palette.accent
+ : MediaQuery.highContrastOf(context)
+ ? palette.foreground.withValues(alpha: .6)
: palette.foreground.withValues(alpha: .12),
- width: selected || states.contains(WidgetState.focused)
- ? 1.5
- : 1,
+ width: MediaQuery.highContrastOf(context) ? 2 : 1.5,
),
),
shape: WidgetStatePropertyAll(
@@ -117,7 +120,7 @@ class _PaletteChoice extends StatelessWidget {
SizedBox(
width: 16,
child: selected
- ? Icon(Icons.check, size: 16, color: palette.accent)
+ ? Icon(AppIcons.check, size: 16, color: palette.accent)
: null,
),
],
diff --git a/desktop/lib/settings/appearance/wallpaper_section.dart b/desktop/lib/settings/appearance/wallpaper_section.dart
index 688b56bbe..7ebc136d6 100644
--- a/desktop/lib/settings/appearance/wallpaper_section.dart
+++ b/desktop/lib/settings/appearance/wallpaper_section.dart
@@ -1,5 +1,6 @@
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
@@ -133,9 +134,22 @@ class _BackgroundCard extends StatelessWidget {
label: '$label background',
child: Material(
color: Colors.transparent,
- child: InkWell(
- onTap: onTap,
- borderRadius: BorderRadius.circular(8),
+ child: TextButton(
+ onPressed: onTap,
+ style: ButtonStyle(
+ padding: const WidgetStatePropertyAll(EdgeInsets.zero),
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ color: states.contains(WidgetState.focused)
+ ? grid.AppDesktop.focus
+ : Colors.transparent,
+ width: grid.AppDesktop.focusWidth,
+ ),
+ ),
+ shape: WidgetStatePropertyAll(
+ RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
+ ),
+ ),
child: Padding(
padding: const EdgeInsets.all(3),
child: Column(
@@ -165,7 +179,7 @@ class _BackgroundCard extends StatelessWidget {
// White vanishes on a light palette's plain field
// (1.25:1); its deep accent holds 5.1:1 or better.
child: Icon(
- Icons.check_circle,
+ AppIcons.circleCheck,
color: grid.AppTheme.pick(
grid.AppPalette.swarmAccent,
Colors.white,
diff --git a/desktop/lib/settings/sections/alerts_card.dart b/desktop/lib/settings/sections/alerts_card.dart
index 385448c2c..7f57590de 100644
--- a/desktop/lib/settings/sections/alerts_card.dart
+++ b/desktop/lib/settings/sections/alerts_card.dart
@@ -43,6 +43,7 @@ class AlertsCard extends StatelessWidget {
valueListenable: screen,
builder: (context, on, _) => SettingRow(
title: 'On-screen alerts',
+ controlSemanticLabel: 'On-screen alerts',
detail:
'Show a banner when an agent finishes, or stops to ask you '
'something. Click it to go to that harness.',
@@ -61,6 +62,7 @@ class AlertsCard extends StatelessWidget {
valueListenable: sound,
builder: (context, on, _) => SettingRow(
title: 'Alert sounds',
+ controlSemanticLabel: 'Alert sounds',
detail: 'Play a sound at the same two moments.',
control: Align(
alignment: Alignment.centerLeft,
@@ -80,6 +82,7 @@ class AlertsCard extends StatelessWidget {
listenable: Listenable.merge([system.store, system.permission]),
builder: (context, _) => SettingRow(
title: 'Desktop notifications',
+ controlSemanticLabel: 'Desktop notifications',
detail: _systemDetail(
clickOpensAgent: system.notifier.clickOpensAgent,
on: system.store.value,
diff --git a/desktop/lib/settings/sections/debug_log_tile.dart b/desktop/lib/settings/sections/debug_log_tile.dart
index 6762e6e9d..7e3a0a2f2 100644
--- a/desktop/lib/settings/sections/debug_log_tile.dart
+++ b/desktop/lib/settings/sections/debug_log_tile.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../logging/log_file.dart';
import '../../logging/log_stream.dart';
@@ -77,7 +77,7 @@ class _DebugLogTileState extends State<DebugLogTile> {
width: 18,
child: _hovered
? Icon(
- LucideIcons.chevronRight,
+ AppIcons.chevronRight,
size: 15,
color: AppPalette.textSecondary,
)
@@ -134,24 +134,24 @@ class DebugStatusIcon extends StatelessWidget {
),
),
LogStatus.ok => Icon(
- LucideIcons.circleCheck,
+ AppIcons.circleCheck,
size: 15,
color: AppPalette.online,
),
LogStatus.failed => Icon(
- LucideIcons.circleAlert,
+ AppIcons.circleAlert,
size: 15,
color: debugDangerInk(context),
),
LogStatus.warned => Icon(
- LucideIcons.triangleAlert,
+ AppIcons.triangleAlert,
size: 15,
color: AppPalette.warn,
),
// An ordinary line the app chose to write. A dot, not a tick: it did not
// succeed at anything, it happened.
LogStatus.event => Icon(
- LucideIcons.dot,
+ AppIcons.dot,
size: 15,
color: AppPalette.textFaint,
),
diff --git a/desktop/lib/settings/sections/debug_paths_card.dart b/desktop/lib/settings/sections/debug_paths_card.dart
index 6533ac7a0..6e00e312d 100644
--- a/desktop/lib/settings/sections/debug_paths_card.dart
+++ b/desktop/lib/settings/sections/debug_paths_card.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../core/harness_cli_runner.dart';
import '../../logging/log_file.dart';
@@ -72,11 +72,7 @@ class _DebugPathsCardState extends State<DebugPathsCard> {
children: [
Row(
children: [
- Icon(
- LucideIcons.terminal300,
- size: 15,
- color: AppPalette.textFaint,
- ),
+ Icon(AppIcons.terminal, size: 15, color: AppPalette.textFaint),
const SizedBox(width: 8),
Expanded(
child: Text(
@@ -85,7 +81,7 @@ class _DebugPathsCardState extends State<DebugPathsCard> {
),
),
AppIconButton(
- icon: LucideIcons.refreshCw,
+ icon: AppIcons.refreshCw,
tooltip: 'Re-check',
onPressed: _recheck,
),
diff --git a/desktop/lib/settings/sections/debug_section.dart b/desktop/lib/settings/sections/debug_section.dart
index 96c7de7c2..3a53ea2fe 100644
--- a/desktop/lib/settings/sections/debug_section.dart
+++ b/desktop/lib/settings/sections/debug_section.dart
@@ -1,6 +1,6 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../logging/log_file.dart';
import '../../logging/log_stream.dart';
@@ -124,7 +124,7 @@ class _DebugSectionState extends State<DebugSection> {
'Search messages, categories, errors',
).copyWith(
prefixIcon: Icon(
- LucideIcons.search,
+ AppIcons.search,
size: 15,
color: AppPalette.textFaint,
),
@@ -215,7 +215,7 @@ class _DebugSectionState extends State<DebugSection> {
// so the search box stays above and the user has a way back out.
if (nothingLogged) {
return const EmptyState(
- icon: LucideIcons.terminal300,
+ icon: AppIcons.terminal,
title: 'Nothing logged yet',
message:
'Use the app and every command, socket frame and request it makes '
diff --git a/desktop/lib/settings/sections/debug_toolbar.dart b/desktop/lib/settings/sections/debug_toolbar.dart
index 5305c292e..1424aaee0 100644
--- a/desktop/lib/settings/sections/debug_toolbar.dart
+++ b/desktop/lib/settings/sections/debug_toolbar.dart
@@ -1,8 +1,8 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../core/reveal_folder.dart';
import '../../widgets/export_logs_dialog.dart';
@@ -44,7 +44,7 @@ class DebugToolbar extends StatelessWidget {
onTap: total == 0 ? null : onClear,
rimmed: true,
child: DebugPillLabel(
- icon: LucideIcons.trash2,
+ icon: AppIcons.trash2,
label: 'Clear',
enabled: total != 0,
),
@@ -71,7 +71,7 @@ class _ExportLogsPill extends StatelessWidget {
onTap: () => unawaited(showExportLogsDialog(context)),
rimmed: true,
child: const DebugPillLabel(
- icon: LucideIcons.packageOpen,
+ icon: AppIcons.packageOpen,
label: 'Export logs',
enabled: true,
),
@@ -105,7 +105,7 @@ class _OpenLogsPill extends StatelessWidget {
onTap: () => unawaited(_open(context)),
rimmed: true,
child: const DebugPillLabel(
- icon: LucideIcons.folderOpen,
+ icon: AppIcons.folderOpen,
label: 'Open logs',
enabled: true,
),
diff --git a/desktop/lib/settings/sections/devices_section.dart b/desktop/lib/settings/sections/devices_section.dart
index 724c8ded9..489ce9071 100644
--- a/desktop/lib/settings/sections/devices_section.dart
+++ b/desktop/lib/settings/sections/devices_section.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
@@ -55,6 +56,8 @@ class _DevicesSectionState extends State<DevicesSection> {
List<Map<String, dynamic>> _discovered = [];
Map<String, dynamic> _status = {};
List<Map<String, dynamic>> _devices = [];
+ bool get _controlsDisabled =>
+ _busy || _loading || (kUnderTest && widget.cli == null);
@override
void initState() {
@@ -282,7 +285,7 @@ class _DevicesSectionState extends State<DevicesSection> {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- final disabled = _busy || _loading || (kUnderTest && widget.cli == null);
+ final disabled = _controlsDisabled;
Widget action(String label, VoidCallback? onPressed) => SizedBox(
width: SettingRow.controlWidth,
child: OutlinedButton(onPressed: onPressed, child: Text(label)),
@@ -333,7 +336,7 @@ class _DevicesSectionState extends State<DevicesSection> {
children: [
const Expanded(child: SelectableText('harness update')),
AppIconButton(
- icon: Icons.refresh_rounded,
+ icon: AppIcons.refreshCw,
tooltip: 'Refresh Autonomous robot status',
onPressed: disabled
? null
@@ -348,7 +351,9 @@ class _DevicesSectionState extends State<DevicesSection> {
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
_actionError ?? _error!,
- style: grid.AppType.body(color: grid.AppPalette.dangerFill),
+ style: grid.AppType.body(
+ color: Theme.of(context).colorScheme.error,
+ ),
),
),
if (!_unsupported && !_loading) ...[
@@ -412,35 +417,42 @@ class _DevicesSectionState extends State<DevicesSection> {
Row(
children: [
Expanded(
- child: IgnorePointer(
- ignoring: disabled,
- child: AppSelectField<String?>(
- key: const Key('autonomous-device-selection'),
- value: _selectedDevice,
- options: [
- const SelectOption<String?>(
- value: null,
- label: 'Select a device',
- ),
- for (final device in _discovered)
- SelectOption<String?>(
- value: device['id'] as String,
- label:
- device['name']?.toString() ??
- 'Autonomous robot',
+ child: ExcludeFocus(
+ excluding: disabled,
+ child: IgnorePointer(
+ ignoring: disabled,
+ child: AppSelectField<String?>(
+ key: const Key('autonomous-device-selection'),
+ semanticLabel: 'Autonomous robot',
+ value: _selectedDevice,
+ options: [
+ const SelectOption<String?>(
+ value: null,
+ label: 'Select a device',
),
- ],
- onChanged: (value) => setState(() {
- _selectedDevice = value;
- _code.clear();
- _actionError = null;
- }),
+ for (final device in _discovered)
+ SelectOption<String?>(
+ value: device['id'] as String,
+ label:
+ device['name']?.toString() ??
+ 'Autonomous robot',
+ ),
+ ],
+ onChanged: (value) {
+ if (_controlsDisabled) return;
+ setState(() {
+ _selectedDevice = value;
+ _code.clear();
+ _actionError = null;
+ });
+ },
+ ),
),
),
),
const SizedBox(width: 8),
AppIconButton(
- icon: Icons.refresh_rounded,
+ icon: AppIcons.refreshCw,
tooltip: 'Refresh Autonomous robot status',
onPressed: disabled
? null
diff --git a/desktop/lib/settings/sections/terminal_section.dart b/desktop/lib/settings/sections/terminal_section.dart
index dbd79a9f2..38c36d41d 100644
--- a/desktop/lib/settings/sections/terminal_section.dart
+++ b/desktop/lib/settings/sections/terminal_section.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart';
@@ -101,6 +102,7 @@ class _SchemeField extends StatelessWidget {
grid.AppTheme.watch(context);
return AppSelectField<TerminalThemeChoice>(
key: const Key('terminal-colour-scheme-dropdown'),
+ semanticLabel: 'Terminal colors',
width: SettingRow.controlWidth,
value: scheme,
options: [
@@ -132,6 +134,7 @@ class _FamilyField extends StatelessWidget {
grid.AppTheme.watch(context);
return AppSelectField<TerminalFontChoice>(
key: const Key('terminal-font-family-dropdown'),
+ semanticLabel: 'Terminal font',
width: SettingRow.controlWidth,
value: family,
// The faces this OS actually has, plus whatever is selected. The second
@@ -168,7 +171,7 @@ class _SizeStepper extends StatelessWidget {
grid.AppTheme.watch(context);
return Container(
width: SettingRow.controlWidth,
- height: grid.AppControl.height,
+ constraints: const BoxConstraints(minHeight: grid.AppControl.height),
padding: const EdgeInsets.symmetric(horizontal: 4),
decoration: BoxDecoration(
// A recessed well, the same one [AppSelectField] sits in — the two
@@ -181,7 +184,7 @@ class _SizeStepper extends StatelessWidget {
children: [
AppIconButton(
key: const Key('terminal-font-size-decrease'),
- icon: Icons.remove_rounded,
+ icon: AppIcons.minus,
size: 16,
tooltip: 'Smaller',
onPressed: size <= TerminalFontStore.minSize
@@ -195,7 +198,7 @@ class _SizeStepper extends StatelessWidget {
),
AppIconButton(
key: const Key('terminal-font-size-increase'),
- icon: Icons.add_rounded,
+ icon: AppIcons.plus,
size: 16,
tooltip: 'Larger',
onPressed: size >= TerminalFontStore.maxSize
diff --git a/desktop/lib/settings/sections/usage_header.dart b/desktop/lib/settings/sections/usage_header.dart
index 72468515f..f7b686c02 100644
--- a/desktop/lib/settings/sections/usage_header.dart
+++ b/desktop/lib/settings/sections/usage_header.dart
@@ -55,6 +55,7 @@ class UsageRangeField extends StatelessWidget {
@override
Widget build(BuildContext context) => AppSelectField<UsageRange>(
+ semanticLabel: 'Usage date range',
value: value,
width: usageControlWidth(context, 150),
options: [
diff --git a/desktop/lib/settings/sections/usage_panels.dart b/desktop/lib/settings/sections/usage_panels.dart
index 62708ac6f..70b2f90a9 100644
--- a/desktop/lib/settings/sections/usage_panels.dart
+++ b/desktop/lib/settings/sections/usage_panels.dart
@@ -6,8 +6,9 @@
/// handed — none reads a store — so the pane can be driven from a fixture.
library;
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../shared/theme/app_theme.dart';
import '../../shared/widgets/skeleton.dart';
@@ -79,17 +80,17 @@ class StatsSummaryCards extends StatelessWidget {
UsageStatCard(
label: 'Harnesses started',
value: '${summary.agentsSpawned}',
- icon: LucideIcons.bot300,
+ icon: AppIcons.bot,
),
UsageStatCard(
label: 'Time harnesses worked',
value: formatWorkedTime(summary.timeWorked),
- icon: LucideIcons.clock300,
+ icon: AppIcons.clock,
),
UsageStatCard(
label: 'Turns',
value: '${summary.turns}',
- icon: LucideIcons.messagesSquare300,
+ icon: AppIcons.messagesSquare,
),
];
return Column(
@@ -735,7 +736,7 @@ class UsageEmptyState extends StatelessWidget {
Row(
children: [
Icon(
- LucideIcons.chartNoAxesColumn300,
+ AppIcons.chartNoAxesColumn,
size: 15,
color: AppPalette.textFaint,
),
diff --git a/desktop/lib/settings/sections/usage_provider_pane.dart b/desktop/lib/settings/sections/usage_provider_pane.dart
index 390ead092..84d6b9f95 100644
--- a/desktop/lib/settings/sections/usage_provider_pane.dart
+++ b/desktop/lib/settings/sections/usage_provider_pane.dart
@@ -10,10 +10,11 @@
/// would filter on a distinction this app does not have.
library;
+
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../shared/theme/app_theme.dart';
import '../../usage/ledger/ledger_types.dart';
@@ -127,43 +128,43 @@ class _Figures extends StatelessWidget {
UsageStatCard(
label: 'Fresh input',
value: formatTokens(totals.freshInput),
- icon: LucideIcons.sparkles300,
+ icon: AppIcons.sparkles,
),
UsageStatCard(
label: 'Output',
value: formatTokens(totals.output),
- icon: LucideIcons.activity300,
+ icon: AppIcons.activity,
),
UsageStatCard(
label: 'Cache read',
value: formatTokens(totals.cacheRead),
- icon: LucideIcons.database300,
+ icon: AppIcons.database,
),
UsageStatCard(
label: 'Cache write',
value: formatTokens(totals.cacheWrite),
- icon: LucideIcons.waypoints300,
+ icon: AppIcons.waypoints,
),
UsageStatCard(
label: 'Cache reuse rate',
value: _percent(report.cacheReuseRate),
- icon: LucideIcons.gauge300,
+ icon: AppIcons.gauge,
),
UsageStatCard(
label: 'Cold turns',
value: _percent(report.zeroCacheReadShare),
- icon: LucideIcons.snowflake300,
+ icon: AppIcons.snowflake,
footnote: 'read nothing from cache',
),
UsageStatCard(
label: 'Conversations / turns',
value: '${report.sessions} / ${report.turns}',
- icon: LucideIcons.folderKanban300,
+ icon: AppIcons.folderKanban,
),
UsageStatCard(
label: 'Est. cost',
value: formatCost(report.costUsd),
- icon: LucideIcons.coins300,
+ icon: AppIcons.coins,
),
];
@@ -231,14 +232,14 @@ class _Header extends StatelessWidget {
iconSize: 15,
visualDensity: VisualDensity.compact,
tooltip: 'Rescan the local logs',
- icon: Icon(LucideIcons.refreshCw300, color: AppPalette.textSecondary),
+ icon: Icon(AppIcons.refreshCw, color: AppPalette.textSecondary),
),
IconButton(
onPressed: onDisable,
iconSize: 15,
visualDensity: VisualDensity.compact,
tooltip: 'Stop reading ${provider.label}',
- icon: Icon(LucideIcons.power300, color: AppPalette.textSecondary),
+ icon: Icon(AppIcons.power, color: AppPalette.textSecondary),
),
],
);
diff --git a/desktop/lib/settings/sections/usage_section.dart b/desktop/lib/settings/sections/usage_section.dart
index 389bddc33..61bb3ab7b 100644
--- a/desktop/lib/settings/sections/usage_section.dart
+++ b/desktop/lib/settings/sections/usage_section.dart
@@ -22,9 +22,9 @@ library;
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../core/test_run.dart';
import '../../shared/theme/app_theme.dart';
@@ -272,12 +272,12 @@ class _UsageSectionState extends State<UsageSection> {
UsageStatCard(
label: 'Total tokens',
value: formatTokens(overview.totals.total),
- icon: LucideIcons.sparkles300,
+ icon: AppIcons.sparkles,
),
UsageStatCard(
label: 'Est. cost',
value: formatCost(overview.costUsd),
- icon: LucideIcons.coins300,
+ icon: AppIcons.coins,
footnote: overview.hasUnpricedModel
? 'at least — some models unpriced'
: null,
@@ -285,14 +285,14 @@ class _UsageSectionState extends State<UsageSection> {
UsageStatCard(
label: 'Active days',
value: '${overview.activeDays}',
- icon: LucideIcons.calendarDays300,
+ icon: AppIcons.calendarDays,
),
UsageStatCard(
label: 'Cache share',
value: overview.cacheShare == null
? 'n/a'
: '${(overview.cacheShare! * 100).round()}%',
- icon: LucideIcons.database300,
+ icon: AppIcons.database,
),
];
return LayoutBuilder(
@@ -398,6 +398,7 @@ class _AnalyticsHeader extends StatelessWidget {
title: Text('Usage analytics', style: AppType.heading()),
controls: [
AppSelectField<_Lens>(
+ semanticLabel: 'Usage provider',
value: lens,
width: usageControlWidth(context, 168),
options: [
@@ -457,7 +458,7 @@ class _OverviewHeader extends StatelessWidget {
visualDensity: VisualDensity.compact,
tooltip: 'Rescan the local logs',
icon: Icon(
- LucideIcons.refreshCw300,
+ AppIcons.refreshCw,
color: onRefresh == null
? AppPalette.textFaint
: AppPalette.textSecondary,
diff --git a/desktop/lib/settings/settings_nav.dart b/desktop/lib/settings/settings_nav.dart
index de3f92945..582e93a64 100644
--- a/desktop/lib/settings/settings_nav.dart
+++ b/desktop/lib/settings/settings_nav.dart
@@ -1,6 +1,6 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/layouts/widgets/rail_section_header.dart';
import '../shared/layouts/widgets/sidebar_item.dart';
@@ -138,7 +138,7 @@ class _SettingsNavState extends State<SettingsNav> {
child: Center(
child: SidebarItem(
key: const Key('settings-back-button'),
- icon: LucideIcons.arrowLeft300,
+ icon: AppIcons.arrowLeft,
label: 'Back to app',
onTap: () => Navigator.of(context).maybePop(),
),
@@ -222,7 +222,7 @@ class _SearchField extends StatelessWidget {
decoration: InputDecoration(
hintText: 'Search settings',
prefixIcon: Icon(
- LucideIcons.search300,
+ AppIcons.search,
size: grid.kFieldIconSize,
color: grid.AppPalette.textFaint,
),
diff --git a/desktop/lib/settings/settings_screen.dart b/desktop/lib/settings/settings_screen.dart
index 508f0d135..b4f96b75f 100644
--- a/desktop/lib/settings/settings_screen.dart
+++ b/desktop/lib/settings/settings_screen.dart
@@ -26,6 +26,7 @@ Future<void> showSettingsScreen(
AppNotifier notifier, {
SettingsSection? initialSection,
ExperimentalFeaturesStore? experimentalFeatures,
+ Future<void> Function()? onCustomize,
// Which door opened Settings. No longer read since analytics was removed;
// kept so the callers need not change.
required String source,
@@ -34,7 +35,7 @@ Future<void> showSettingsScreen(
double compactBelow = 0,
}) async {
if (initialSection == SettingsSection.customize) {
- await showHarnessCustomizePane(context);
+ await (onCustomize?.call() ?? showHarnessCustomizePane(context));
return;
}
final action = await Navigator.of(context).push<SettingsSection>(
@@ -55,7 +56,7 @@ Future<void> showSettingsScreen(
// Leave the opaque Settings route before opening the panel, keeping the
// active terminals visible behind the controls and retaining caller focus.
if (action == SettingsSection.customize && context.mounted) {
- await showHarnessCustomizePane(context);
+ await (onCustomize?.call() ?? showHarnessCustomizePane(context));
}
}
diff --git a/desktop/lib/settings/settings_section.dart b/desktop/lib/settings/settings_section.dart
index ac87e7bb8..adb1ced98 100644
--- a/desktop/lib/settings/settings_section.dart
+++ b/desktop/lib/settings/settings_section.dart
@@ -1,6 +1,6 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../logging/debug_surface.dart';
@@ -11,16 +11,16 @@ import '../logging/debug_surface.dart';
/// rail, the search filter and the pane all read this list, so a section cannot
/// be listed without a screen behind it or reachable without a row.
enum SettingsSection {
- account(LucideIcons.user300, 'Account'),
- profiles(LucideIcons.monitor300, 'Profiles'),
- usage(LucideIcons.chartNoAxesColumn300, 'Usage'),
- customize(LucideIcons.palette300, 'Customize'),
- notifications(LucideIcons.bell300, 'Notifications'),
- experimental(LucideIcons.flaskConical300, 'Experimental'),
- devices(LucideIcons.zap300, 'Autonomous robots'),
- shortcuts(LucideIcons.keyboard300, 'Keyboard shortcuts'),
- debug(LucideIcons.bug300, 'Debug'),
- about(LucideIcons.info300, 'About');
+ account(AppIcons.user, 'Account'),
+ profiles(AppIcons.monitor, 'Profiles'),
+ usage(AppIcons.chartNoAxesColumn, 'Usage'),
+ customize(AppIcons.palette, 'Customize'),
+ notifications(AppIcons.bell, 'Notifications'),
+ experimental(AppIcons.flaskConical, 'Experimental'),
+ devices(AppIcons.zap, 'Autonomous robots'),
+ shortcuts(AppIcons.keyboard, 'Keyboard shortcuts'),
+ debug(AppIcons.bug, 'Debug'),
+ about(AppIcons.info, 'About');
const SettingsSection(this.icon, this.label);
diff --git a/desktop/lib/shared/layouts/widgets/rail_section_header.dart b/desktop/lib/shared/layouts/widgets/rail_section_header.dart
index 882523fbf..c4a809412 100644
--- a/desktop/lib/shared/layouts/widgets/rail_section_header.dart
+++ b/desktop/lib/shared/layouts/widgets/rail_section_header.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../theme/app_theme.dart';
@@ -70,7 +70,7 @@ class RailSectionHeader extends StatelessWidget {
constraints: const BoxConstraints.tightFor(width: 26, height: 26),
padding: EdgeInsets.zero,
color: AppPalette.textSecondary,
- icon: const Icon(LucideIcons.plus300),
+ icon: const Icon(AppIcons.plus),
onPressed: onAdd,
),
],
diff --git a/desktop/lib/shared/layouts/widgets/sidebar_item.dart b/desktop/lib/shared/layouts/widgets/sidebar_item.dart
index 0c3ac1158..28871c3a8 100644
--- a/desktop/lib/shared/layouts/widgets/sidebar_item.dart
+++ b/desktop/lib/shared/layouts/widgets/sidebar_item.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../theme/app_theme.dart';
import '../../widgets/scroll_reveal_text.dart';
@@ -176,13 +176,19 @@ class _SidebarItemState extends State<SidebarItem> {
),
);
+ final accessibleRow = Semantics(
+ button: true,
+ enabled: widget.enabled,
+ selected: widget.selected,
+ child: row,
+ );
final tooltip = widget.tooltip;
if (tooltip == null ||
tooltip.trim().isEmpty ||
tooltip.trim() == widget.label.trim()) {
- return row;
+ return accessibleRow;
}
- return Tooltip(message: tooltip, child: row);
+ return Tooltip(message: tooltip, child: accessibleRow);
}
}
@@ -605,7 +611,7 @@ class _SidebarSectionLabelState extends State<SidebarSectionLabel> {
turns: widget.collapsed ? -0.25 : 0,
duration: AppMotion.swap,
curve: AppMotion.curve,
- child: Icon(LucideIcons.chevronDown300, size: 14, color: ink),
+ child: Icon(AppIcons.chevronDown, size: 14, color: ink),
),
],
),
diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dart
new file mode 100644
index 000000000..5ed943f39
--- /dev/null
+++ b/desktop/lib/shared/theme/app_icons.dart
@@ -0,0 +1,143 @@
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+/// One outline family for app actions, navigation, and status.
+///
+/// Use these constants instead of mixing Material, Lucide weights, or text
+/// glyphs. Agent/product marks and user-selected terminal/status artwork are
+/// identities, not control icons. Size follows the surrounding control role;
+/// a small drawing never reduces its accessible hit target.
+abstract final class AppIcons {
+ static const double inlineSize = 16;
+ static const double controlSize = 20;
+ static const double featureSize = 24;
+
+ /// A quiet close mark in tabs and pane headers, inside the full click target.
+ static const double closeSize = 12;
+
+ static const activity = LucideIcons.activity400;
+ static const arrowDownToLine = LucideIcons.arrowDownToLine400;
+ static const arrowDownWideNarrow = LucideIcons.arrowDownWideNarrow400;
+ static const arrowLeft = LucideIcons.arrowLeft400;
+ static const arrowRight = LucideIcons.arrowRight400;
+ static const arrowRightToLine = LucideIcons.arrowRightToLine400;
+ static const arrowUp = LucideIcons.arrowUp400;
+ static const arrowUpRight = LucideIcons.arrowUpRight400;
+ static const bell = LucideIcons.bell400;
+ static const bellRing = LucideIcons.bellRing400;
+ static const bot = LucideIcons.bot400;
+ static const box = LucideIcons.box400;
+ static const brainCircuit = LucideIcons.brainCircuit400;
+ static const bug = LucideIcons.bug400;
+ static const calendarDays = LucideIcons.calendarDays400;
+ static const chartNoAxesColumn = LucideIcons.chartNoAxesColumn400;
+ static const check = LucideIcons.check400;
+ static const chevronDown = LucideIcons.chevronDown400;
+ static const chevronLeft = LucideIcons.chevronLeft400;
+ static const chevronRight = LucideIcons.chevronRight400;
+ static const chevronUp = LucideIcons.chevronUp400;
+ static const circle = LucideIcons.circle400;
+ static const circleAlert = LucideIcons.circleAlert400;
+ static const circleCheck = LucideIcons.circleCheck400;
+ static const circleCheckBig = LucideIcons.circleCheckBig400;
+ static const circleDashed = LucideIcons.circleDashed400;
+ static const circleDot = LucideIcons.circleDot400;
+ static const circleHelp = LucideIcons.circleHelp400;
+ static const circleMinus = LucideIcons.circleMinus400;
+ static const circlePlus = LucideIcons.circlePlus400;
+ static const circleSlash = LucideIcons.circleSlash400;
+ static const circleX = LucideIcons.circleX400;
+ static const clipboardPaste = LucideIcons.clipboardPaste400;
+ static const clock = LucideIcons.clock400;
+ static const close = LucideIcons.x400;
+ static const cloud = LucideIcons.cloud400;
+ static const cloudOff = LucideIcons.cloudOff400;
+ static const code = LucideIcons.code400;
+ static const coins = LucideIcons.coins400;
+ static const columns2 = LucideIcons.columns2400;
+ static const command = LucideIcons.command400;
+ static const copy = LucideIcons.copy400;
+ static const cornerDownLeft = LucideIcons.cornerDownLeft400;
+ static const cpu = LucideIcons.cpu400;
+ static const database = LucideIcons.database400;
+ static const dot = LucideIcons.dot400;
+ static const download = LucideIcons.download400;
+ static const ellipsis = LucideIcons.ellipsis400;
+ static const externalLink = LucideIcons.externalLink400;
+ static const eye = LucideIcons.eye400;
+ static const eyeOff = LucideIcons.eyeOff400;
+ static const fileText = LucideIcons.fileText400;
+ static const film = LucideIcons.film400;
+ static const flaskConical = LucideIcons.flaskConical400;
+ static const folder = LucideIcons.folder400;
+ static const folderKanban = LucideIcons.folderKanban400;
+ static const folderOpen = LucideIcons.folderOpen400;
+ static const folderPlus = LucideIcons.folderPlus400;
+ static const gamepad2 = LucideIcons.gamepad2400;
+ static const gauge = LucideIcons.gauge400;
+ static const gitBranch = LucideIcons.gitBranch400;
+ static const globe = LucideIcons.globe400;
+ static const hand = LucideIcons.hand400;
+ static const history = LucideIcons.history400;
+ static const hourglass = LucideIcons.hourglass400;
+ static const house = LucideIcons.house400;
+ static const info = LucideIcons.info400;
+ static const keyboard = LucideIcons.keyboard400;
+ static const laptop = LucideIcons.laptop400;
+ static const layers = LucideIcons.layers400;
+ static const layoutGrid = LucideIcons.layoutGrid400;
+ static const link2 = LucideIcons.link2400;
+ static const listFilter = LucideIcons.listFilter400;
+ static const loaderCircle = LucideIcons.loaderCircle400;
+ static const lock = LucideIcons.lock400;
+ static const logIn = LucideIcons.logIn400;
+ static const logOut = LucideIcons.logOut400;
+ static const maximize = LucideIcons.maximize400;
+ static const messageCircleQuestionMark =
+ LucideIcons.messageCircleQuestionMark400;
+ static const messagesSquare = LucideIcons.messagesSquare400;
+ static const minimize = LucideIcons.minimize400;
+ static const minus = LucideIcons.minus400;
+ static const monitor = LucideIcons.monitor400;
+ static const monitorOff = LucideIcons.monitorOff400;
+ static const music = LucideIcons.music400;
+ static const packageCheck = LucideIcons.packageCheck400;
+ static const packageOpen = LucideIcons.packageOpen400;
+ static const palette = LucideIcons.palette400;
+ static const panelsTopLeft = LucideIcons.panelsTopLeft400;
+ static const pause = LucideIcons.pause400;
+ static const pencil = LucideIcons.pencil400;
+ static const play = LucideIcons.play400;
+ static const plug = LucideIcons.plug400;
+ static const plus = LucideIcons.plus400;
+ static const power = LucideIcons.power400;
+ static const radioTower = LucideIcons.radioTower400;
+ static const refreshCw = LucideIcons.refreshCw400;
+ static const rotateCcw = LucideIcons.rotateCcw400;
+ static const search = LucideIcons.search400;
+ static const searchX = LucideIcons.searchX400;
+ static const send = LucideIcons.send400;
+ static const server = LucideIcons.server400;
+ static const shapes = LucideIcons.shapes400;
+ static const shield = LucideIcons.shield400;
+ static const shieldCheck = LucideIcons.shieldCheck400;
+ static const shieldOff = LucideIcons.shieldOff400;
+ static const slidersHorizontal = LucideIcons.slidersHorizontal400;
+ static const smartphone = LucideIcons.smartphone400;
+ static const snowflake = LucideIcons.snowflake400;
+ static const sparkles = LucideIcons.sparkles400;
+ static const square = LucideIcons.square400;
+ static const squareCheck = LucideIcons.squareCheck400;
+ static const squarePlus = LucideIcons.squarePlus400;
+ static const squareTerminal = LucideIcons.squareTerminal400;
+ static const star = LucideIcons.star400;
+ static const starHalf = LucideIcons.starHalf400;
+ static const terminal = LucideIcons.terminal400;
+ static const trash2 = LucideIcons.trash2400;
+ static const triangleAlert = LucideIcons.triangleAlert400;
+ static const unlink = LucideIcons.unlink400;
+ static const unplug = LucideIcons.unplug400;
+ static const usb = LucideIcons.usb400;
+ static const user = LucideIcons.user400;
+ static const waypoints = LucideIcons.waypoints400;
+ static const zap = LucideIcons.zap400;
+}
diff --git a/desktop/lib/shared/theme/app_theme.dart b/desktop/lib/shared/theme/app_theme.dart
index f4be5248d..b860c0b06 100644
--- a/desktop/lib/shared/theme/app_theme.dart
+++ b/desktop/lib/shared/theme/app_theme.dart
@@ -22,6 +22,17 @@ abstract final class AppTheme {
static bool get isDark => brightness.value == Brightness.dark;
+ /// A theme preview can request the opposite brightness without changing the
+ /// saved palette. Keep its surface and foreground on the same light/dark ramp.
+ static HarnessPalette paletteFor(Brightness value) =>
+ palette.value.brightness == value
+ ? palette.value
+ : value == Brightness.dark
+ ? HarnessPalette.graphite
+ : HarnessPalette.paper;
+
+ static HarnessPalette get surfacePalette => paletteFor(brightness.value);
+
/// Pick between a light and a dark value for the current brightness.
static T pick<T>(T light, T dark) => isDark ? dark : light;
@@ -155,18 +166,18 @@ class _PaletteScope extends InheritedNotifier<ValueNotifier<HarnessPalette>> {
/// hex literals, and resolves per [AppTheme.brightness].
abstract final class AppPalette {
// Approved Swarms canvas and native tab-strip palette.
- static Color get swarmField => AppTheme.palette.value.workspace;
+ static Color get swarmField => AppTheme.surfacePalette.workspace;
// Empty tabs join the selected native tab as one continuous surface.
- static Color get swarmWelcome => AppTheme.palette.value.workspace;
- static Color get swarmTabBar => AppTheme.palette.value.tabBar;
- static Color get swarmAccent => AppTheme.palette.value.accent;
+ static Color get swarmWelcome => AppTheme.surfacePalette.workspace;
+ static Color get swarmTabBar => AppTheme.surfacePalette.tabBar;
+ static Color get swarmAccent => AppTheme.surfacePalette.accent;
// Shared with the native search field for a continuous input/results surface.
- static Color get swarmSearchSurface => AppTheme.palette.value.search;
+ static Color get swarmSearchSurface => AppTheme.surfacePalette.search;
// Getters, not consts: a light palette brings its own panel and card.
static Color get agentEntrySurface =>
- AppTheme.pick(AppTheme.palette.value.panel, const Color(0xff101113));
+ AppTheme.pick(AppTheme.surfacePalette.panel, const Color(0xff101113));
static Color get agentEntryField =>
- AppTheme.pick(AppTheme.palette.value.card, const Color(0xff1d1f22));
+ AppTheme.pick(AppTheme.surfacePalette.card, const Color(0xff1d1f22));
// The command field deliberately stays light, like a browser's new-tab omnibox.
static const commandField = Color(0xFFF7F8FA);
static const commandInk = Color(0xFF202124);
@@ -185,16 +196,16 @@ abstract final class AppPalette {
// These four come from the palette in both themes: a light palette carries
// its own light surfaces (color_palette.dart), and it is the palette that
// decides the brightness in the first place.
- static Color get windowBg => AppTheme.palette.value.background;
+ static Color get windowBg => AppTheme.surfacePalette.background;
// sidebar column — a barely-there cool grey (Codex keeps the rail almost white,
// set apart by a hairline, not a tone) / charcoal panel in dark.
- static Color get panelBg => AppTheme.palette.value.panel;
+ static Color get panelBg => AppTheme.surfacePalette.panel;
// input fills, quiet cards
- static Color get cardBg => AppTheme.palette.value.card;
+ static Color get cardBg => AppTheme.surfacePalette.card;
- static Color get cardBgHover => AppTheme.palette.value.hover;
+ static Color get cardBgHover => AppTheme.surfacePalette.hover;
// A hairline separator. Light: a faint cool black; dark: a faint white — a
// black divider would vanish on charcoal.
@@ -252,7 +263,7 @@ abstract final class AppPalette {
/// row, still plainly the same indigo. [accent] can't simply take this value:
/// it is the fill under white text in ~100 places, and lightening it there
/// would drop that text to ~3.1:1 — fixing the icon by breaking the buttons.
- static Color get accentOnSurface => AppTheme.palette.value.accent;
+ static Color get accentOnSurface => AppDesktop.focus;
// avatar fill (white text on it); a touch brighter in dark for contrast.
static Color get accentMuted =>
@@ -725,7 +736,7 @@ abstract final class AppGlass {
/// use [styleFor] and the consts; everywhere else use [style] and the getters.
abstract final class AppMenu {
static const Color fillLight = Color(0xFFFFFFFF);
- static const Color fillDark = Color(0xFF2A2A2A);
+ static const Color fillDark = Color(0xFF262626);
static Color get fill => AppTheme.pick(fillLight, fillDark);
/// The panel's rim — the same hairline [AppGlass.hair] resolves to, stated as
@@ -734,10 +745,8 @@ abstract final class AppMenu {
static const Color rimDark = Color(0x1FFFFFFF);
static Color get rim => AppTheme.pick(rimLight, rimDark);
- /// A menu panel's rounding. On the §3 ladder this is the *panel* step (10),
- /// one below a content card (12) and above the rows inside it (8) — a child is
- /// never rounder than its parent.
- static const double panelRadius = 10;
+ /// Menu frame and inset rows follow the same concentric geometry.
+ static const double panelRadius = AppDesktop.menuRadius;
/// Deeper than Material's menu default (8): this panel opens over chrome that
/// already carries a lift of its own, and at 8 it reads as lying *on* that
@@ -897,20 +906,23 @@ abstract final class AppCard {
/// The app's theme for a given [brightness]. Both the light and dark themes are
/// built from this one function so the two never drift; the color tokens above
/// resolve against [AppTheme.brightness] at paint time.
-ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {
+ThemeData buildAppTheme({
+ Brightness brightness = Brightness.light,
+ bool highContrast = false,
+}) {
final isDark = brightness == Brightness.dark;
- final scheme = isDark
+ final baseScheme = isDark
? ColorScheme.dark(
primary: AppPalette.accent,
onPrimary: Colors.white,
secondary: AppPalette.accent,
- surface: AppTheme.palette.value.background,
+ surface: AppTheme.paletteFor(brightness).background,
onSurface: const Color(0xFFF5F5F5),
onSurfaceVariant: const Color(0xFFA8A8A2),
- surfaceContainerHighest: AppTheme.palette.value.card,
+ surfaceContainerHighest: AppTheme.paletteFor(brightness).card,
outline: const Color(0x14FFFFFF),
outlineVariant: const Color(0x14FFFFFF),
- error: const Color(0xFFF2544B),
+ error: const Color(0xFFFF7068),
)
: ColorScheme.light(
primary: AppPalette.accent,
@@ -918,17 +930,23 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {
secondary: AppPalette.accent,
// The light palette's own ground — matches AppPalette.windowBg, as
// the dark scheme's does.
- surface: AppTheme.palette.value.background,
- onSurface: AppTheme.palette.value.foreground,
+ surface: AppTheme.paletteFor(brightness).background,
+ onSurface: AppTheme.paletteFor(brightness).foreground,
onSurfaceVariant: const Color(0xFF62615B),
// The field fill. Not the card, which is pure white on both light
// palettes: a white field in a white dialog has no edge at all. The
// panel tone is the step the old light theme's #F3F3F2 was.
- surfaceContainerHighest: AppTheme.palette.value.panel,
+ surfaceContainerHighest: AppTheme.paletteFor(brightness).panel,
outline: const Color(0x0F000000),
outlineVariant: const Color(0x0F000000),
error: const Color(0xFFB3261E),
);
+ final scheme = highContrast
+ ? baseScheme.copyWith(
+ outline: baseScheme.onSurface.withValues(alpha: .6),
+ outlineVariant: baseScheme.onSurface.withValues(alpha: .4),
+ )
+ : baseScheme;
// The chrome fills used by menus, dialogs and toasts. A getter-backed token
// can't be a compile-time const, so these are resolved here per-brightness —
@@ -941,15 +959,19 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {
// both were `#1E1E1E`, which is [AppCard.base] — a content card's colour, one
// step *below* the block it was supposed to be.
final panelFill = isDark ? AppMenu.fillDark : AppMenu.fillLight;
- final dialogFill = AppTheme.palette.value.card;
+ final dialogFill = panelFill;
final textTheme = _appTextTheme(scheme.onSurface, scheme.onSurfaceVariant);
return ThemeData(
- filledButtonTheme: FilledButtonThemeData(style: _filledButtonStyle()),
+ filledButtonTheme: FilledButtonThemeData(
+ style: _filledButtonStyle(scheme, highContrast: highContrast),
+ ),
outlinedButtonTheme: OutlinedButtonThemeData(
- style: _outlinedButtonStyle(scheme),
+ style: _outlinedButtonStyle(scheme, highContrast: highContrast),
+ ),
+ textButtonTheme: TextButtonThemeData(
+ style: _textButtonStyle(scheme, highContrast: highContrast),
),
- textButtonTheme: TextButtonThemeData(style: _textButtonStyle()),
useMaterial3: true,
brightness: brightness,
colorScheme: scheme,
@@ -1069,6 +1091,16 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {
iconTheme: IconThemeData(color: scheme.onSurfaceVariant, size: 18),
iconButtonTheme: IconButtonThemeData(
style: ButtonStyle(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: highContrast ? 2 : 1.5,
+ color:
+ !states.contains(WidgetState.disabled) &&
+ states.contains(WidgetState.focused)
+ ? (isDark ? AppDesktop.focusDark : scheme.primary)
+ : Colors.transparent,
+ ),
+ ),
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(7)),
),
@@ -1142,9 +1174,15 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {
),
border: _fieldBorder(scheme.outline),
enabledBorder: _fieldBorder(scheme.outline),
- focusedBorder: _fieldBorder(AppPalette.accent, width: 1.5),
+ focusedBorder: _fieldBorder(
+ isDark ? AppDesktop.focusDark : scheme.primary,
+ width: highContrast ? 2 : 1.5,
+ ),
errorBorder: _fieldBorder(scheme.error),
- focusedErrorBorder: _fieldBorder(scheme.error, width: 1.5),
+ focusedErrorBorder: _fieldBorder(
+ scheme.error,
+ width: highContrast ? 2 : 1.5,
+ ),
),
// Fill, rim and elevation come from [AppMenu] so a Material popup cannot
// disagree with a MenuAnchor about what a menu looks like.
@@ -1165,6 +1203,39 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {
// point: a MenuAnchor that forgets to pass a style used to fall back to a
// rimless panel, which is the bug the hand-written style existed to fix.
menuTheme: MenuThemeData(style: AppMenu.styleFor(isDark: isDark)),
+ menuButtonTheme: MenuButtonThemeData(
+ style: ButtonStyle(
+ textStyle: WidgetStatePropertyAll(AppType.body(height: 1.25)),
+ minimumSize: const WidgetStatePropertyAll(Size(0, AppControl.height)),
+ shape: WidgetStatePropertyAll(
+ RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(AppDesktop.rowRadius),
+ ),
+ ),
+ foregroundColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? scheme.onSurface.withValues(alpha: .38)
+ : states.contains(WidgetState.hovered) ||
+ states.contains(WidgetState.focused)
+ ? AppDesktop.onSelection
+ : scheme.onSurface,
+ ),
+ backgroundColor: WidgetStateProperty.resolveWith(
+ (states) =>
+ !states.contains(WidgetState.disabled) &&
+ (states.contains(WidgetState.hovered) ||
+ states.contains(WidgetState.focused))
+ ? AppDesktop.selection
+ : Colors.transparent,
+ ),
+ overlayColor: const WidgetStatePropertyAll(Colors.transparent),
+ mouseCursor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? SystemMouseCursors.basic
+ : SystemMouseCursors.click,
+ ),
+ ),
+ ),
// An ExpansionTile defaults `backgroundColor` (expanded) and
// `collapsedBackgroundColor` to *different* values and cross-fades between
// them, so opening one flashes a tint over whatever surface it sits on. Our
@@ -1179,17 +1250,14 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {
collapsedShape: Border(),
),
dialogTheme: DialogThemeData(
- // The raised block's own fill, not a menu's and not a card's. §9.3: a
- // dialog that takes `windowBg` merges with the page, and one that takes
- // [AppCard.base] sits a step under the block it is supposed to *be* —
- // both invisible in light, both plain in dark.
+ // Standard Dialog and custom DesktopDialogSurface use one frame recipe.
backgroundColor: dialogFill,
surfaceTintColor: Colors.transparent,
- // The card radius, not a number of its own. This was 18 — the iOS
- // action-sheet curve, and the app's cards had already come down to 12 for
- // macOS without the dialogs following.
+ elevation: AppDesktop.dialogElevation,
+ shadowColor: AppDesktop.shadow,
shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(AppCard.radius),
+ borderRadius: BorderRadius.circular(AppDesktop.dialogRadius),
+ side: BorderSide(color: isDark ? AppMenu.rimDark : AppMenu.rimLight),
),
titleTextStyle: AppType.heading(color: scheme.onSurface),
contentTextStyle: AppType.body(color: scheme.onSurface),
@@ -1205,7 +1273,7 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {
// Resolved from `isDark` rather than read off the getter — see the note at
// `scrollbarTheme`.
progressIndicatorTheme: ProgressIndicatorThemeData(
- color: isDark ? const Color(0xFF6E8BFF) : const Color(0xFF2F5BEA),
+ color: isDark ? AppDesktop.focusDark : const Color(0xFF2F5BEA),
linearTrackColor: scheme.outline,
),
snackBarTheme: SnackBarThemeData(
@@ -1224,11 +1292,8 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {
/// The one set of numbers every button in the app is built from.
///
-/// macOS controls are compact, squarish and quiet: a 13pt semibold label in a
-/// ~32px capsule with a small radius — not the tall, wide, fully-round buttons
-/// Material defaults to. Before this existed each call site invented its own,
-/// which is how the app ended up with seven button heights, three shape systems
-/// and six label sizes. Change a number here, not at a call site.
+/// Shared desktop controls: 13-point system labels, 32-point capsule buttons,
+/// and softly rounded fields. Change geometry here, not in individual dialogs.
abstract final class AppControl {
/// Standard control height. macOS's regular push button sits at 32; the app's
/// own most-used value was 34, and 32 reads correctly next to a 13pt label.
@@ -1247,14 +1312,11 @@ abstract final class AppControl {
/// one.
static const double heightField = 36;
- /// Corner radius. Apple's push buttons are gently rounded, not stadium — a
- /// pill reads as a "chip" on macOS, not as a button.
- static const double radius = 8;
+ /// Text-field radius. Action buttons use the shared capsule shape.
+ static const double radius = AppDesktop.fieldRadius;
- /// A menu/popover's rounding. Tighter than a button's: macOS menus are nearly
- /// square-cornered, and rounding one like an iOS action sheet is one of the
- /// louder tells that a desktop app was drawn to phone conventions.
- static const double menuRadius = 6;
+ /// Menu/popover radius, shared with custom desktop choosers.
+ static const double menuRadius = AppDesktop.menuRadius;
/// The air between a menu panel and the control it hangs off.
///
@@ -1287,10 +1349,16 @@ abstract final class AppControl {
/// A compact glyph for an inline chip.
static const double iconSizeChip = 13;
- /// Horizontal breathing room. Apple pads a push button generously sideways and
- /// barely at all vertically — the height is what sets the touch target.
- static const EdgeInsets padding = EdgeInsets.symmetric(horizontal: 14);
- static const EdgeInsets paddingSmall = EdgeInsets.symmetric(horizontal: 10);
+ /// The minimum height keeps normal-size controls compact. Vertical padding
+ /// lets enlarged system text grow the capsule without touching its rim.
+ static const EdgeInsets padding = EdgeInsets.symmetric(
+ horizontal: 14,
+ vertical: 6,
+ );
+ static const EdgeInsets paddingSmall = EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 6,
+ );
/// A button that leads with a glyph, at the compact scale.
///
@@ -1327,11 +1395,49 @@ abstract final class AppControl {
/// [padding], grown for the current UI size — a wider label needs the
/// sidebearing to grow with it, or the text crowds the capsule's ends.
- static EdgeInsets get paddingScaled =>
- EdgeInsets.symmetric(horizontal: 14 * AppFont.uiScale);
+ static EdgeInsets get paddingScaled => padding * AppFont.uiScale;
- static EdgeInsets get paddingSmallScaled =>
- EdgeInsets.symmetric(horizontal: 10 * AppFont.uiScale);
+ static EdgeInsets get paddingSmallScaled => paddingSmall * AppFont.uiScale;
+}
+
+/// The desktop's geometry and interaction tokens. Dialogs, menu anchors, search,
+/// creation and ordinary themed controls all resolve through this one recipe.
+/// Terminal geometry and the user's terminal palette remain independent.
+abstract final class AppDesktop {
+ static const double dialogRadius = 20;
+ static const double dialogElevation = 16;
+ static const Color shadow = Color(0x3D000000);
+ static const double menuRadius = 16;
+ static const double rowRadius = 10;
+ static const double fieldRadius = 10;
+ static const double paneRadius = 10;
+ static const double tabRadius = 10;
+ static const double tabShoulder = 8;
+ static const double tabTopInset = 6;
+ static const double tabCloseInset = 8;
+ static const double panelPadding = 24;
+ static const double groupGap = 16;
+ static const double controlGap = 8;
+ static const double menuInset = 6;
+ static const double iconSize = 16;
+ static const double identitySize = 28;
+ static const double formWidth = 460;
+ static const double focusWidth = 1.5;
+
+ static Color get surface => AppMenu.fill;
+ static Color get rim => AppMenu.rim;
+ static Color get field =>
+ AppTheme.pick(const Color(0xFFF2F2F4), const Color(0xFF303030));
+ static const Color focusDark = Color(0xFF8BA9FF);
+ static Color get focus => AppTheme.pick(AppPalette.accent, focusDark);
+ static Color get selection => AppPalette.accent;
+ static const Color onSelection = Colors.white;
+ static const Color selectionDetail = Color(0xEBFFFFFF);
+
+ static const darkVeil = Color(0xF2000000);
+ static const lightVeil = Color(0xF2FFFFFF);
+ static Color veil(Brightness brightness) =>
+ brightness == Brightness.dark ? darkVeil : lightVeil;
}
/// Desktop feedback is visible on the next frame. Keep these shared names so
@@ -1422,16 +1528,16 @@ OutlineInputBorder _fieldBorder(Color color, {double width = 1}) =>
/// **not** inherit `fontFamily` from the text theme, so a button must receive
/// the UI font explicitly.
TextStyle get _buttonTextStyle =>
- AppType.label(fontWeight: AppControl.fontWeight);
+ AppType.body(fontWeight: AppControl.fontWeight, height: 1.25);
-/// A text field's own text: [AppType.mono] — what the user types is set the
-/// way a terminal sets it, at the scale of the button beside it.
+/// Ordinary form fields use the system UI face. Code, paths, credentials,
+/// and terminal editors opt into their explicit monospace styles.
/// `InputDecorationTheme` has no `style` slot (it themes the *decoration*, not
/// the editable text), so a field must be handed this explicitly:
/// `TextField(style: kFieldTextStyle, ...)`.
TextStyle get kFieldTextStyle => _fieldTextStyle(AppPalette.textPrimary);
-TextStyle _fieldTextStyle(Color color) => AppType.mono(color: color);
+TextStyle _fieldTextStyle(Color color) => AppType.body(color: color);
/// A field's leading glyph — the magnifier on a search box, and its kind.
///
@@ -1442,9 +1548,7 @@ TextStyle _fieldTextStyle(Color color) => AppType.mono(color: color);
/// the `Icon` itself still has to be handed this size at the call site.
const double kFieldIconSize = 18;
-RoundedRectangleBorder get _buttonShape => RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(AppControl.radius),
-);
+StadiumBorder get _buttonShape => const StadiumBorder();
/// The primary action: a solid accent capsule.
/// A filled button that destroys something.
@@ -1463,7 +1567,14 @@ ButtonStyle dangerButtonStyle() => FilledButton.styleFrom(
foregroundColor: Colors.white,
);
-ButtonStyle _filledButtonStyle() => FilledButton.styleFrom(
+ButtonStyle _filledButtonStyle(
+ ColorScheme scheme, {
+ bool highContrast = false,
+}) => FilledButton.styleFrom(
+ backgroundColor: scheme.primary,
+ foregroundColor: scheme.onPrimary,
+ disabledBackgroundColor: scheme.onSurface.withValues(alpha: .08),
+ disabledForegroundColor: scheme.onSurface.withValues(alpha: .38),
animationDuration: Duration.zero,
minimumSize: Size(0, AppControl.heightScaled),
padding: AppControl.paddingScaled,
@@ -1473,6 +1584,7 @@ ButtonStyle _filledButtonStyle() => FilledButton.styleFrom(
// that leaves a 32px button floating in a 48px box and wrecks every row it
// sits in.
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ enabledMouseCursor: SystemMouseCursors.click,
visualDensity: VisualDensity.standard,
// Its own wash, not [AppSurface.hoverFill]: this button already carries the
// accent as a FILL, so the hover has to read against that rather than against
@@ -1480,30 +1592,41 @@ ButtonStyle _filledButtonStyle() => FilledButton.styleFrom(
// second colour. See [_textButtonStyle] for why any of these are needed at
// all — `NoSplash` took the ripple away and left nothing behind it.
overlayColor: const Color(0x1FFFFFFF),
-);
+).copyWith(side: _controlRim(scheme, filled: true, highContrast: highContrast));
/// The secondary action: a hairline rim, no fill — Apple's "bordered" button.
-ButtonStyle _outlinedButtonStyle(ColorScheme scheme) =>
- OutlinedButton.styleFrom(
- animationDuration: Duration.zero,
- minimumSize: Size(0, AppControl.heightScaled),
- padding: AppControl.paddingScaled,
- shape: _buttonShape,
- textStyle: _buttonTextStyle,
- side: BorderSide(color: scheme.outline),
- foregroundColor: scheme.onSurface,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- visualDensity: VisualDensity.standard,
- );
-
-/// The tertiary action: text only, for the quiet way out of a dialog.
-ButtonStyle _textButtonStyle() => TextButton.styleFrom(
+ButtonStyle _outlinedButtonStyle(
+ ColorScheme scheme, {
+ bool highContrast = false,
+}) => OutlinedButton.styleFrom(
+ animationDuration: Duration.zero,
+ minimumSize: Size(0, AppControl.heightScaled),
+ padding: AppControl.paddingScaled,
+ shape: _buttonShape,
+ textStyle: _buttonTextStyle,
+ side: BorderSide(color: scheme.onSurface.withValues(alpha: .14)),
+ backgroundColor: scheme.onSurface.withValues(alpha: .04),
+ foregroundColor: scheme.onSurface,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ enabledMouseCursor: SystemMouseCursors.click,
+ visualDensity: VisualDensity.standard,
+).copyWith(side: _controlRim(scheme, highContrast: highContrast));
+
+/// A quiet capsule for secondary dialog and workspace actions.
+ButtonStyle _textButtonStyle(
+ ColorScheme scheme, {
+ bool highContrast = false,
+}) => TextButton.styleFrom(
+ foregroundColor: scheme.onSurface,
+ backgroundColor: scheme.onSurface.withValues(alpha: .055),
+ side: BorderSide(color: scheme.onSurface.withValues(alpha: .10)),
animationDuration: Duration.zero,
minimumSize: Size(0, AppControl.heightScaled),
padding: AppControl.paddingSmallScaled,
shape: _buttonShape,
textStyle: _buttonTextStyle,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ enabledMouseCursor: SystemMouseCursors.click,
visualDensity: VisualDensity.standard,
// ⚠️ Without this a text button has NO hover state at all.
//
@@ -1518,12 +1641,40 @@ ButtonStyle _textButtonStyle() => TextButton.styleFrom(
// [AppSurface.hoverFill] is the same wash the rows and menu items already
// use, so a button now answers the pointer the way everything around it does.
overlayColor: AppSurface.hoverFill,
-);
+).copyWith(side: _controlRim(scheme, highContrast: highContrast));
+
+/// Keep a real focus boundary without changing the control's layout. A filled
+/// primary uses its contrasting label color; neutral controls use the accent.
+WidgetStateProperty<BorderSide> _controlRim(
+ ColorScheme scheme, {
+ bool filled = false,
+ bool highContrast = false,
+}) => WidgetStateProperty.resolveWith((states) {
+ final disabled = states.contains(WidgetState.disabled);
+ final focused = states.contains(WidgetState.focused) && !disabled;
+ return BorderSide(
+ width: highContrast ? 2 : 1.5,
+ color: focused
+ ? filled
+ ? scheme.onPrimary
+ : scheme.brightness == Brightness.dark
+ ? AppDesktop.focusDark
+ : scheme.primary
+ : filled
+ ? Colors.transparent
+ : scheme.onSurface.withValues(
+ alpha: disabled
+ ? .06
+ : highContrast
+ ? .6
+ : .09,
+ ),
+ );
+});
TextTheme _appTextTheme(Color primary, Color secondary) {
- // Material's fifteen roles folded onto [AppType]'s steps: headings and
- // labels in mono, body in sans. A heading keeps semibold; a role that names a
- // control drops to medium.
+ // App controls share the system type hierarchy. Monospace is requested
+ // explicitly by terminal content, code, and identifiers.
final display = AppType.display(color: primary);
final title = AppType.title(color: primary);
final heading = AppType.heading(color: primary);
@@ -1544,6 +1695,6 @@ TextTheme _appTextTheme(Color primary, Color secondary) {
bodySmall: body.copyWith(color: secondary),
labelLarge: label,
labelMedium: label,
- labelSmall: AppType.monoMeta(color: primary, fontWeight: AppFont.medium),
+ labelSmall: AppType.caption(color: primary, fontWeight: AppFont.medium),
);
}
diff --git a/desktop/lib/shared/theme/app_type.dart b/desktop/lib/shared/theme/app_type.dart
index 5ccc23f7c..cd9232f44 100644
--- a/desktop/lib/shared/theme/app_type.dart
+++ b/desktop/lib/shared/theme/app_type.dart
@@ -5,36 +5,22 @@ import '../../terminal/terminal_font_store.dart';
/// The app's type scale: which face, size and weight a piece of text gets.
///
-/// Harness is a terminal app, drawn for people who have lived in one, so the
-/// terminal's face leads. Two faces, split by one rule:
-///
-/// * **Mono** — the face chosen in Settings ▸ Terminal — for everything that
-/// names, labels or is typed: headings, titles, buttons, rows, navigation,
-/// fields, tabs, pane headers, shortcuts, counts, and the strings the user
-/// copies (a path, a branch, an id, a log line). Read like a CLI's `--help`:
-/// the command in mono, its description beside it.
-/// * **Sans** — the system UI face — only for prose: a description, an
-/// explanation, a dialog's sentence, a caption. A paragraph of mono at 13pt is
-/// what made an all-mono build read as a wall, so prose is where the second
-/// face earns its place.
-///
-/// Sizes are fixed. The terminal's own size setting (⌘+ / ⌘−) moves the
-/// terminal grid, its composer, its find field and the empty tab's welcome
-/// page, which stands where a terminal will — [terminalTextStyle] — and
-/// nothing here. An earlier build set every text in the app in the terminal
-/// face at the terminal size, which left a heading and its body copy one size
-/// apart only by weight.
+/// System typography belongs to app navigation, forms, headings, and prose.
+/// Monospace is explicit: terminal content, code, paths, and identifiers.
+/// Changing the terminal font must not change desktop controls. The terminal
+/// grid, its composer, and in-pane find keep their own selected font and size.
+/// These base sizes also respect the platform's accessibility text scaling.
///
/// ```
-/// display mono 28 semibold one per screen: a page title, sign-in
-/// title mono 20 semibold a settings pane, a hero card, a figure
-/// heading mono 15 semibold a section, a dialog title, a card title
-/// label mono 13 medium buttons, rows, sidebar items, links
-/// mono mono 13 regular field text, typed commands, paths
-/// monoLabel mono 12 medium tabs, pane headers, command-box rows
-/// monoMeta mono 11 regular shortcuts, counts, eyebrows, timestamps
+/// display sans 28 semibold one per screen: a page title, sign-in
+/// title sans 20 semibold a settings pane, a hero card, a figure
+/// heading sans 17 semibold a section, a dialog title, a card title
+/// label sans 13 medium buttons, rows, sidebar items, links
+/// mono mono 13 regular commands, source text, paths
+/// monoLabel mono 12 medium terminal labels, compact code
+/// monoMeta mono 11 regular shortcut keys, identifiers, code metadata
/// body sans 13 regular prose: descriptions, explanations
-/// caption sans 11 regular tooltips, footnotes
+/// caption sans 12 regular tooltips, footnotes
/// ```
///
/// Every style takes the same optional arguments as `terminalTextStyle`, so a
@@ -42,9 +28,9 @@ import '../../terminal/terminal_font_store.dart';
abstract final class AppType {
static const double displaySize = 28;
static const double titleSize = 20;
- static const double headingSize = 15;
+ static const double headingSize = 17;
static const double bodySize = 13;
- static const double captionSize = 11;
+ static const double captionSize = 12;
static const double monoSize = 13;
static const double monoLabelSize = 12;
static const double monoMetaSize = 11;
@@ -87,7 +73,7 @@ abstract final class AppType {
double? height,
double? letterSpacing,
List<FontFeature>? fontFeatures,
- }) => _mono(
+ }) => _sans(
displaySize,
fontWeight ?? FontWeight.w600,
color,
@@ -104,7 +90,7 @@ abstract final class AppType {
double? height,
double? letterSpacing,
List<FontFeature>? fontFeatures,
- }) => _mono(
+ }) => _sans(
titleSize,
fontWeight ?? FontWeight.w600,
color,
@@ -121,7 +107,7 @@ abstract final class AppType {
double? height,
double? letterSpacing,
List<FontFeature>? fontFeatures,
- }) => _mono(
+ }) => _sans(
headingSize,
fontWeight ?? FontWeight.w600,
color,
@@ -155,7 +141,7 @@ abstract final class AppType {
double? height,
double? letterSpacing,
List<FontFeature>? fontFeatures,
- }) => _mono(
+ }) => _sans(
bodySize,
fontWeight ?? FontWeight.w500,
color,
diff --git a/desktop/lib/shared/theme/pull_request_icon.dart b/desktop/lib/shared/theme/pull_request_icon.dart
index df4b92f32..8edafb170 100644
--- a/desktop/lib/shared/theme/pull_request_icon.dart
+++ b/desktop/lib/shared/theme/pull_request_icon.dart
@@ -1,3 +1,5 @@
+import 'dart:ui' show Brightness;
+
import 'package:flutter/painting.dart';
import 'package:xterm/xterm.dart';
@@ -11,13 +13,20 @@ String pullRequestIconAsset(String state) =>
_ => 'git-pull-request',
}}.svg';
+/// Desktop surfaces can supply [brightness] without a terminal theme. Existing
+/// terminal callers keep their theme's brightness and monochrome foreground.
Color pullRequestIconColor(
String state,
- TerminalTheme theme, {
+ TerminalTheme? theme, {
bool color = true,
+ Brightness? brightness,
}) {
- if (!color) return theme.foreground;
- final light = theme.background.computeLuminance() > .5;
+ assert(theme != null || brightness != null);
+ assert(color || theme != null);
+ if (!color) return theme!.foreground;
+ final light = brightness != null
+ ? brightness == Brightness.light
+ : theme!.background.computeLuminance() > .5;
return switch (state) {
'Open' => Color(light ? 0xff1a7f37 : 0xff3fb950),
'Merged' => Color(light ? 0xff8250df : 0xffbc8cff),
diff --git a/desktop/lib/shared/theme/status_line_style.dart b/desktop/lib/shared/theme/status_line_style.dart
index b4807679d..08bdc3953 100644
--- a/desktop/lib/shared/theme/status_line_style.dart
+++ b/desktop/lib/shared/theme/status_line_style.dart
@@ -376,6 +376,7 @@ List<StatusLinePaintSegment> statusLinePaintSegments(
TerminalTheme theme, {
bool color = true,
int segmentOffset = 0,
+ Color? surfaceBackground,
}) {
color = color && parts.style != StatusLineStyle.standard;
Color resolve(StatusLineTone tone) =>
@@ -398,8 +399,11 @@ List<StatusLinePaintSegment> statusLinePaintSegments(
StatusLineTone.orange => theme.yellow,
};
Color ink(StatusLineSegment part) {
- if (!color) return theme.foreground;
- final foreground = resolve(part.foreground);
+ final foreground = color ? resolve(part.foreground) : theme.foreground;
+ if (part.background == null && surfaceBackground != null) {
+ return statusLineInkOnSurface(foreground, surfaceBackground);
+ }
+ if (!color) return foreground;
if (part.background == null || !_presetColors.containsKey(parts.style)) {
return foreground;
}
@@ -441,6 +445,33 @@ List<StatusLinePaintSegment> statusLinePaintSegments(
];
}
+/// A terminal status style can also sit on a light desktop surface. Keep its
+/// colors when readable and adjust only the ink that would disappear there.
+/// Callers without a surface keep the exact terminal/native status palette.
+Color statusLineInkOnSurface(Color ink, Color surface) {
+ final ground = surface.computeLuminance();
+ double contrast(Color color) {
+ final light = Color.alphaBlend(color, surface).computeLuminance();
+ return light > ground
+ ? (light + .05) / (ground + .05)
+ : (ground + .05) / (light + .05);
+ }
+
+ if (contrast(ink) >= 4.5) return ink;
+ const black = Color(0xFF000000), white = Color(0xFFFFFFFF);
+ final target = contrast(black) > contrast(white) ? black : white;
+ var low = 0.0, high = 1.0;
+ for (var i = 0; i < 20; i++) {
+ final mid = (low + high) / 2;
+ if (contrast(Color.lerp(ink, target, mid)!) < 4.5) {
+ low = mid;
+ } else {
+ high = mid;
+ }
+ }
+ return Color.lerp(ink, target, high)!;
+}
+
/// The four named Starship presets include a status-only palette, as their
/// upstream TOML presets do. Other styles follow the user's terminal ANSI
/// colors. These tokens are resolved here for both Flutter and AppKit, and
diff --git a/desktop/lib/shared/widgets/app_choice_picker.dart b/desktop/lib/shared/widgets/app_choice_picker.dart
index 2d1b2f76c..3d278c6d3 100644
--- a/desktop/lib/shared/widgets/app_choice_picker.dart
+++ b/desktop/lib/shared/widgets/app_choice_picker.dart
@@ -1,5 +1,6 @@
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
@@ -235,7 +236,7 @@ class _AppChoicePickerState<T> extends State<AppChoicePicker<T>> {
width: moreWidth,
height: controlHeight,
trigger: Icon(
- Icons.more_horiz,
+ AppIcons.ellipsis,
size: 20,
color: AppPalette.textSecondary,
),
@@ -314,7 +315,7 @@ class _AppChoicePickerState<T> extends State<AppChoicePicker<T>> {
: extra == null
? widget.moreLeading
: extra.leading?.call(),
- trailing: const Icon(Icons.keyboard_arrow_down, size: 18),
+ trailing: const Icon(AppIcons.chevronDown, size: 18),
),
),
),
@@ -407,7 +408,9 @@ class _AppChoicePickerState<T> extends State<AppChoicePicker<T>> {
SizedBox(
width: 16,
child: selected
- ? const ExcludeSemantics(child: Icon(Icons.check, size: 16))
+ ? const ExcludeSemantics(
+ child: Icon(AppIcons.check, size: 16),
+ )
: null,
),
],
diff --git a/desktop/lib/shared/widgets/app_dialog.dart b/desktop/lib/shared/widgets/app_dialog.dart
index 70a30cd24..91c591af8 100644
--- a/desktop/lib/shared/widgets/app_dialog.dart
+++ b/desktop/lib/shared/widgets/app_dialog.dart
@@ -1,5 +1,5 @@
-/// Shared instant dialogs. An opaque-enough tint separates terminal text from
-/// the dialog without filtering live terminal pixels on every frame.
+/// Shared desktop dialogs keep the surrounding workspace recognizable without
+/// filtering live terminal pixels on every frame.
library;
import 'dart:ui' show ImageFilter;
@@ -7,12 +7,16 @@ import 'dart:ui' show ImageFilter;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import '../theme/app_theme.dart';
+
/// Dialogs do not blur the live workspace by default.
const double kDialogVeilBlur = 0;
-/// Shared dark backdrop for dialogs and centered pickers. Terminal output
-/// stays in the background while the active surface has the user's attention.
-const Color kDialogVeilTint = Color(0xE6000000);
+/// Every modal uses the same 95% veil, including Cmd-N and Cmd-P.
+const Color kDialogVeilTint = AppDesktop.darkVeil;
+
+Color dialogVeilTintOf(BuildContext context) =>
+ AppDesktop.veil(Theme.of(context).brightness);
/// The app's dialog barrier: a flat tint and the active surface.
///
@@ -31,9 +35,10 @@ Future<T?> showAppDialog<T>({
required WidgetBuilder builder,
bool barrierDismissible = true,
String barrierLabel = 'Dismiss',
- Color veilTint = kDialogVeilTint,
+ Color? veilTint,
double veilBlur = kDialogVeilBlur,
Duration transitionDuration = Duration.zero,
+ ValueChanged<bool>? onCurrentChanged,
}) => showGeneralDialog<T>(
context: context,
// The route's own barrier draws nothing: the veil below is the barrier.
@@ -46,11 +51,14 @@ Future<T?> showAppDialog<T>({
transitionDuration: MediaQuery.disableAnimationsOf(context)
? Duration.zero
: transitionDuration,
- pageBuilder: (context, _, _) => _AppDialogVeil(
- tint: veilTint,
- blur: veilBlur,
- dismissible: barrierDismissible,
- child: Builder(builder: builder),
+ pageBuilder: (context, _, _) => _DialogVisibility(
+ onCurrentChanged: onCurrentChanged,
+ child: _AppDialogVeil(
+ tint: veilTint,
+ blur: veilBlur,
+ dismissible: barrierDismissible,
+ child: Builder(builder: builder),
+ ),
),
transitionBuilder: (context, anim, _, child) =>
transitionDuration == Duration.zero ||
@@ -59,6 +67,43 @@ Future<T?> showAppDialog<T>({
: FadeTransition(opacity: anim, child: child),
);
+/// Lets an explicit preview route preserve passive native chrome. A nested
+/// route hides that preview again; this never grants input to the workspace.
+class _DialogVisibility extends StatefulWidget {
+ const _DialogVisibility({required this.child, this.onCurrentChanged});
+ final Widget child;
+ final ValueChanged<bool>? onCurrentChanged;
+
+ @override
+ State<_DialogVisibility> createState() => _DialogVisibilityState();
+}
+
+class _DialogVisibilityState extends State<_DialogVisibility> {
+ bool? _current;
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final current = ModalRoute.isCurrentOf(context) ?? false;
+ if (current == _current) return;
+ _current = current;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && current == _current) {
+ widget.onCurrentChanged?.call(current);
+ }
+ });
+ }
+
+ @override
+ void dispose() {
+ widget.onCurrentChanged?.call(false);
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => widget.child;
+}
+
/// The veil, and the dialog standing on it.
class _AppDialogVeil extends StatelessWidget {
const _AppDialogVeil({
@@ -68,7 +113,7 @@ class _AppDialogVeil extends StatelessWidget {
required this.child,
});
- final Color tint;
+ final Color? tint;
final double blur;
final bool dismissible;
final Widget child;
@@ -86,10 +131,10 @@ class _AppDialogVeil extends StatelessWidget {
behavior: HitTestBehavior.opaque,
onTap: dismissible ? () => Navigator.of(context).maybePop() : null,
child: blur == 0
- ? ColoredBox(color: tint)
+ ? ColoredBox(color: tint ?? dialogVeilTintOf(context))
: BackdropFilter(
filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
- child: ColoredBox(color: tint),
+ child: ColoredBox(color: tint ?? dialogVeilTintOf(context)),
),
),
),
diff --git a/desktop/lib/shared/widgets/app_icon_button.dart b/desktop/lib/shared/widgets/app_icon_button.dart
index ec65e76c8..d92072b9a 100644
--- a/desktop/lib/shared/widgets/app_icon_button.dart
+++ b/desktop/lib/shared/widgets/app_icon_button.dart
@@ -1,5 +1,4 @@
import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
import '../theme/app_theme.dart';
@@ -86,13 +85,12 @@ class AppIconButton extends StatefulWidget {
/// 4.5:1 on the hover fill, while still reading unmistakably red.
static const Color _dangerDark = Color(0xFFFF8A80);
- /// The button's box. Kept a touch larger than the glyph so the hover fill
- /// reads as a pill around it rather than a tight halo.
- static const double _box = 24;
+ /// A normal desktop target, independent of terminal cell size.
+ static const double _box = 32;
/// 7 — the app's radius for a small inline button (`ghost_button.dart`,
/// `chat_header.dart`), and never rounder than the 8 of a control it sits in.
- static const double _radius = 7;
+ static const double _radius = AppDesktop.fieldRadius;
@override
State<AppIconButton> createState() => _AppIconButtonState();
@@ -100,9 +98,6 @@ class AppIconButton extends StatefulWidget {
class _AppIconButtonState extends State<AppIconButton>
with SingleTickerProviderStateMixin {
- bool _hovered = false;
- bool _focused = false;
-
/// One turn. Slow enough to read as deliberate rather than as a busy
/// indicator thrashing, fast enough that a reload finishing inside a single
/// revolution still looks like it moved.
@@ -149,8 +144,11 @@ class _AppIconButtonState extends State<AppIconButton>
// Spinning does not grey the glyph out, but it does stop the press: the
// work the last one asked for is still running.
final enabled = widget.onPressed != null && !widget.spinning;
- final pressable = widget.onPressed != null;
- final resting = widget.color ?? AppPalette.textSecondary;
+ final highContrast = MediaQuery.highContrastOf(context);
+ final reduceMotion = MediaQuery.disableAnimationsOf(context);
+ final resting =
+ widget.color ??
+ (highContrast ? AppPalette.textPrimary : AppPalette.textSecondary);
// Only the glyph changes. The fill stays the same neutral lift every other
// button gets, so a destructive button reads as *the same affordance* the
// rest of the app uses — just saying, in its ink, what it would do.
@@ -162,64 +160,74 @@ class _AppIconButtonState extends State<AppIconButton>
? danger
: (widget.hoverColor ?? AppPalette.textPrimary);
- final emphasized = enabled && (_hovered || _focused);
- final button = MouseRegion(
- cursor: enabled ? SystemMouseCursors.click : MouseCursor.defer,
- onEnter: (_) => setState(() => _hovered = true),
- onExit: (_) => setState(() => _hovered = false),
- child: FocusableActionDetector(
- enabled: enabled,
- onFocusChange: (value) => setState(() => _focused = value),
- shortcuts: const {
- SingleActivator(LogicalKeyboardKey.enter): ActivateIntent(),
- SingleActivator(LogicalKeyboardKey.space): ActivateIntent(),
- },
- actions: {
- ActivateIntent: CallbackAction<ActivateIntent>(
- onInvoke: (_) {
- if (enabled) widget.onPressed?.call();
- return null;
- },
+ return Semantics(
+ value: widget.spinning ? 'Working' : null,
+ child: IconButton(
+ tooltip: widget.tooltip,
+ onPressed: enabled ? widget.onPressed : null,
+ iconSize: widget.size,
+ style: ButtonStyle(
+ animationDuration: reduceMotion ? Duration.zero : AppMotion.hover,
+ minimumSize: const WidgetStatePropertyAll(
+ Size.square(AppIconButton._box),
),
- },
- child: GestureDetector(
- onTap: enabled ? widget.onPressed : null,
- child: AnimatedContainer(
- duration: AppMotion.hover,
- curve: AppMotion.curve,
- width: AppIconButton._box,
- height: AppIconButton._box,
- alignment: Alignment.center,
- decoration: BoxDecoration(
- color: emphasized
- ? (widget.hoverFill ?? AppSurface.hoverFill)
- : Colors.transparent,
+ padding: const WidgetStatePropertyAll(EdgeInsets.all(6)),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ visualDensity: VisualDensity.standard,
+ mouseCursor: WidgetStatePropertyAll(
+ enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,
+ ),
+ shape: WidgetStatePropertyAll(
+ RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppIconButton._radius),
),
- child: RepaintBoundary(
- child: RotationTransition(
- turns: _spin ?? const AlwaysStoppedAnimation(0),
- child: Icon(
- widget.icon,
- size: widget.size,
- color: pressable
- ? (emphasized ? active : resting)
- : AppPalette.textFaint,
- ),
- ),
+ ),
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: highContrast ? 2 : 1.5,
+ color: enabled && states.contains(WidgetState.focused)
+ ? AppPalette.accentOnSurface
+ : highContrast && enabled
+ ? AppPalette.textSecondary
+ : Colors.transparent,
),
),
+ foregroundColor: WidgetStateProperty.resolveWith((states) {
+ if (widget.spinning && widget.onPressed != null) return resting;
+ if (states.contains(WidgetState.disabled)) {
+ return AppPalette.textFaint;
+ }
+ return states.contains(WidgetState.hovered) ||
+ states.contains(WidgetState.pressed) ||
+ states.contains(WidgetState.focused)
+ ? active
+ : resting;
+ }),
+ backgroundColor: const WidgetStatePropertyAll(Colors.transparent),
+ overlayColor: WidgetStateProperty.resolveWith((states) {
+ if (states.contains(WidgetState.disabled)) {
+ return Colors.transparent;
+ }
+ if (states.contains(WidgetState.pressed)) {
+ return Color.alphaBlend(
+ AppPalette.textPrimary.withValues(alpha: .08),
+ widget.hoverFill ?? AppSurface.hoverFill,
+ );
+ }
+ if (states.contains(WidgetState.hovered) ||
+ states.contains(WidgetState.focused)) {
+ return widget.hoverFill ?? AppSurface.hoverFill;
+ }
+ return Colors.transparent;
+ }),
+ ),
+ icon: RepaintBoundary(
+ child: RotationTransition(
+ turns: _spin ?? const AlwaysStoppedAnimation(0),
+ child: Icon(widget.icon, size: widget.size),
+ ),
),
),
);
-
- final tooltip = widget.tooltip;
- return Semantics(
- button: true,
- enabled: enabled,
- child: tooltip == null
- ? button
- : Tooltip(message: tooltip, child: button),
- );
}
}
diff --git a/desktop/lib/shared/widgets/app_menu.dart b/desktop/lib/shared/widgets/app_menu.dart
index e7797add2..08789a9e3 100644
--- a/desktop/lib/shared/widgets/app_menu.dart
+++ b/desktop/lib/shared/widgets/app_menu.dart
@@ -1,13 +1,12 @@
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../theme/app_theme.dart';
-/// A row names a choice, so it is set in [AppType.mono] like every other
-/// label; its detail line is prose, in [AppType.caption]. Compact and roomy variants only change padding and icon
-/// spacing.
+/// Menu choices use the system UI face; technical values can supply their own
+/// style. Compact and roomy variants change padding and icon spacing.
@immutable
class AppMenuRowMetrics {
const AppMenuRowMetrics({required this.iconSize, required this.padding});
@@ -65,14 +64,8 @@ double get kMenuRowExtent => AppMenuRowMetrics.compact.extent;
/// hand-written `appMenuStyle()` this file used to export was the second of four
/// disagreeing recipes — see that class.
///
-/// Hand-rolled rather than a [MenuItemButton] because the app has no
-/// `menuButtonTheme`, so a bare one takes Material's M3 defaults and lands
-/// wrong on four counts at once: radius 0, 14pt text, a grey 8% hover, and a
-/// ripple every other menu here has turned off.
-///
-/// Stateful for its own hover: the glyph has to climb to [AppPalette.textPrimary]
-/// under the pointer. An icon that stays dim while the cursor sits on it reads
-/// as decoration, and nothing above this row tracks hover per-row to do it.
+/// Adds subject marks, qualifiers and detail lines to the same selection
+/// treatment supplied by the app's ordinary MenuItemButton theme.
class AppMenuItem extends StatefulWidget {
const AppMenuItem({
super.key,
@@ -124,10 +117,8 @@ class AppMenuItem extends StatefulWidget {
/// asks [AppMenuRowMetrics.detailExtent] rather than [AppMenuRowMetrics.extent].
final String? detail;
- /// A mark that belongs to the ROW's subject rather than to its action — an
- /// engine's logo, say. It gets a slot of its own AFTER the tick's, so the tick
- /// still has somewhere to go and a picked row's label does not shift sideways
- /// from an unpicked one's.
+ /// A subject's mark, such as its agent logo. Replaces [icon] in the fixed
+ /// leading slot. The trailing check never displaces this identity.
final Widget? leading;
/// Which of the two row sizes this is. Defaults to a context menu's; a picker
@@ -138,14 +129,14 @@ class AppMenuItem extends StatefulWidget {
/// This row is the current choice.
///
/// Marked THREE ways, never by one: an accent wash, a heavier label, and a
- /// tick in the leading slot. Colour alone fails anyone who cannot separate
+ /// tick in the trailing slot. Colour alone fails anyone who cannot separate
/// these two greys, and a tick alone is easy to miss in a long list.
final bool selected;
final VoidCallback onPressed;
- /// Tints the row red and gives it a red hover wash — for the row that
- /// destroys something.
+ /// Red at rest for a destructive action. Active rows retain the common
+ /// white-on-blue selection so pointer and keyboard feedback remain legible.
final bool danger;
@override
@@ -154,48 +145,45 @@ class AppMenuItem extends StatefulWidget {
class _AppMenuItemState extends State<AppMenuItem> {
bool _hovered = false;
+ bool _focused = false;
@override
Widget build(BuildContext context) {
// Lives in the MenuAnchor's overlay, so it watches for itself.
AppTheme.watch(context);
final error = Theme.of(context).colorScheme.error;
- // A danger row is already red at rest, so it deepens rather than climbs.
- final tint = widget.danger
+ final active = _hovered || _focused;
+ final tint = active
+ ? AppDesktop.onSelection
+ : widget.danger
? error
- : (_hovered || widget.selected
- ? AppPalette.textPrimary
- : AppPalette.textSecondary);
- // The tick takes the leading slot when this row is the choice; otherwise the
- // row's own glyph does, and a row with neither keeps the slot EMPTY.
- //
- // ⚠️ Empty means an empty box, not `Icons.check_box_outline_blank`. That
- // glyph draws a real outlined square — which turns a pick-one menu into what
- // reads as a checkbox list, and puts a border somewhere §1 does not allow
- // one. It shipped that way once; this comment is why it will not again.
- final glyph = widget.selected ? LucideIcons.check300 : widget.icon;
+ : AppPalette.textSecondary;
+ // Keep the identity column even when a row has no mark.
+ final glyph = widget.icon;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
child: Material(
color: Colors.transparent,
- borderRadius: BorderRadius.circular(8),
+ borderRadius: BorderRadius.circular(AppDesktop.rowRadius),
child: InkWell(
focusNode: widget.focusNode,
onTap: widget.onPressed,
onHover: (hovered) => setState(() => _hovered = hovered),
- borderRadius: BorderRadius.circular(8),
- hoverColor: widget.danger
- ? error.withValues(alpha: 0.09)
- : AppSurface.hoverFill,
- focusColor: AppSurface.hoverFill,
+ onFocusChange: (focused) => setState(() => _focused = focused),
+ mouseCursor: SystemMouseCursors.click,
+ borderRadius: BorderRadius.circular(AppDesktop.rowRadius),
+ hoverColor: Colors.transparent,
+ focusColor: Colors.transparent,
splashFactory: NoSplash.splashFactory,
child: Ink(
decoration: BoxDecoration(
- color: widget.selected
+ color: active
+ ? AppDesktop.selection
+ : widget.selected
? AppSurface.accentWash
: Colors.transparent,
- borderRadius: BorderRadius.circular(8),
+ borderRadius: BorderRadius.circular(AppDesktop.rowRadius),
),
padding: widget.metrics.padding,
child: Row(
@@ -205,18 +193,17 @@ class _AppMenuItemState extends State<AppMenuItem> {
// ticked row would sit a few pixels off an unticked one.
SizedBox(
width: widget.metrics.iconSize,
- child: glyph == null
- ? null
- : Icon(glyph, size: widget.metrics.iconSize, color: tint),
+ child:
+ widget.leading ??
+ (glyph == null
+ ? null
+ : Icon(
+ glyph,
+ size: widget.metrics.iconSize,
+ color: tint,
+ )),
),
const SizedBox(width: 9),
- if (widget.leading != null) ...[
- SizedBox(
- width: widget.metrics.iconSize,
- child: Center(child: widget.leading),
- ),
- const SizedBox(width: 9),
- ],
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -226,8 +213,12 @@ class _AppMenuItemState extends State<AppMenuItem> {
widget.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: AppType.mono(
- color: widget.danger ? error : AppPalette.textPrimary,
+ style: (widget.textStyle ?? AppType.body()).copyWith(
+ color: active
+ ? AppDesktop.onSelection
+ : widget.danger
+ ? error
+ : AppPalette.textPrimary,
height: 1.2,
fontWeight: widget.selected
? AppFont.medium
@@ -241,7 +232,9 @@ class _AppMenuItemState extends State<AppMenuItem> {
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppType.caption(
- color: AppPalette.textSecondary,
+ color: active
+ ? AppDesktop.selectionDetail
+ : AppPalette.textSecondary,
height: 1.25,
),
),
@@ -256,8 +249,10 @@ class _AppMenuItemState extends State<AppMenuItem> {
widget.note!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: AppType.mono(
- color: AppPalette.textFaint,
+ style: AppType.body(
+ color: active
+ ? AppDesktop.selectionDetail
+ : AppPalette.textSecondary,
height: 1.2,
),
),
@@ -267,6 +262,14 @@ class _AppMenuItemState extends State<AppMenuItem> {
const SizedBox(width: 8),
widget.trailing!,
],
+ if (widget.selected) ...[
+ const SizedBox(width: 12),
+ Icon(
+ AppIcons.check,
+ size: widget.metrics.iconSize,
+ color: tint,
+ ),
+ ],
],
),
),
diff --git a/desktop/lib/shared/widgets/app_rating_star.dart b/desktop/lib/shared/widgets/app_rating_star.dart
new file mode 100644
index 000000000..ad2211da6
--- /dev/null
+++ b/desktop/lib/shared/widgets/app_rating_star.dart
@@ -0,0 +1,71 @@
+import 'dart:math' as math;
+
+import 'package:flutter/widgets.dart';
+
+/// A quantitative mark: the same rounded star outline at every value, with a
+/// clipped fill so full, fractional and empty ratings also differ without color.
+class AppRatingStar extends StatelessWidget {
+ const AppRatingStar({
+ super.key,
+ required this.fraction,
+ required this.color,
+ required this.outlineColor,
+ this.size = 16,
+ });
+
+ final double fraction;
+ final Color color;
+ final Color outlineColor;
+ final double size;
+
+ @override
+ Widget build(BuildContext context) => CustomPaint(
+ size: Size.square(size),
+ painter: _StarPainter(fraction.clamp(0, 1), color, outlineColor),
+ );
+}
+
+class _StarPainter extends CustomPainter {
+ const _StarPainter(this.fraction, this.color, this.outlineColor);
+ final double fraction;
+ final Color color;
+ final Color outlineColor;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ canvas.save();
+ canvas.scale(size.width / 24, size.height / 24);
+ final path = Path();
+ for (var point = 0; point < 10; point++) {
+ final angle = -math.pi / 2 + point * math.pi / 5;
+ final radius = point.isEven ? 10.5 : 4.8;
+ final x = 12 + radius * math.cos(angle);
+ final y = 12 + radius * math.sin(angle);
+ if (point == 0) {
+ path.moveTo(x, y);
+ } else {
+ path.lineTo(x, y);
+ }
+ }
+ path.close();
+ canvas.save();
+ canvas.clipRect(Rect.fromLTWH(0, 0, 24 * fraction, 24));
+ canvas.drawPath(path, Paint()..color = color);
+ canvas.restore();
+ canvas.drawPath(
+ path,
+ Paint()
+ ..color = outlineColor
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = 1.8
+ ..strokeJoin = StrokeJoin.round,
+ );
+ canvas.restore();
+ }
+
+ @override
+ bool shouldRepaint(_StarPainter oldDelegate) =>
+ fraction != oldDelegate.fraction ||
+ color != oldDelegate.color ||
+ outlineColor != oldDelegate.outlineColor;
+}
diff --git a/desktop/lib/shared/widgets/app_select_field.dart b/desktop/lib/shared/widgets/app_select_field.dart
index 3224a22b8..69879becd 100644
--- a/desktop/lib/shared/widgets/app_select_field.dart
+++ b/desktop/lib/shared/widgets/app_select_field.dart
@@ -1,5 +1,6 @@
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -85,6 +86,7 @@ class AppSelectField<T> extends StatefulWidget {
this.filterThreshold = 8,
this.textStyle,
this.radius,
+ this.semanticLabel,
});
final T value;
@@ -119,6 +121,11 @@ class AppSelectField<T> extends StatefulWidget {
final double? radius;
final String? emptyLabel;
+ /// The control's purpose, separate from its current option's label and note.
+ /// For example, "Terminal font" with a value of "SF Mono". Omit this for
+ /// existing custom triggers that already provide their own accessible name.
+ final String? semanticLabel;
+
/// Whether a long list may put a search field at the head of its menu.
///
/// Only past [filterThreshold], because the field is furniture: a list short
@@ -403,46 +410,13 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
return KeyEventResult.ignored;
}
- /// How tall this panel may draw.
- ///
- /// ⚠️ NOT [AppControl.menuMaxHeight]. That token's 240 is for a menu that
- /// opens UPWARD and places itself by summing the height it is about to take;
- /// this one hangs below its field, so it is free to be as tall as its own
- /// list. Left at 240, a seven-item picker overflowed by five pixels and grew
- /// a scrollbar to show them — furniture that says "there is more here" when
- /// there is not.
- ///
- /// The ceiling is still real: past it a long list scrolls instead of running
- /// off the window.
- double get _panelHeight => math.min(
- // A row with a detail line is TALLER, and the difference has to be counted
- // per row rather than assumed for all of them: a list where only some
- // options carry a sentence would otherwise be measured wrong in whichever
- // direction the guess went, and a panel that disagrees with its layout by a
- // few pixels wears a scrollbar it does not need.
- _shownOptions.fold<double>(
- 0,
- (total, option) =>
- total +
- (option.detail == null
- ? AppMenuRowMetrics.roomy.extent
- : AppMenuRowMetrics.roomy.detailExtent),
- ) +
- AppMenu.panelPadding.vertical +
- ((widget.options.isEmpty && widget.emptyLabel != null) || _noMatches
- ? AppMenuRowMetrics.roomy.extent
- : 0) +
- (_filtering ? _filterExtent : 0),
- _maxPanelHeight,
- );
-
+ /// Let MenuAnchor measure the rows, including scaled text, detail lines,
+ /// custom marks and the search field. An estimate from unscaled row metrics
+ /// can hide a final option even when all choices fit in the window.
+ /// This is only a ceiling: shorter lists keep their natural height; longer
+ /// lists scroll, and MenuAnchor also constrains them to the available window.
static const double _maxPanelHeight = 380;
- /// The search field's own band: a field at the app's own height, plus the
- /// gap that separates it from the first row. Read from the scaled token, so
- /// a larger UI size grows the panel with the field inside it.
- double get _filterExtent => AppControl.heightFieldScaled + 10;
-
/// A floor under the panel's width, on top of the field's own.
///
/// A field can be narrow — the font picker's is 188 — while its list holds
@@ -477,7 +451,7 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
decoration: InputDecoration(
hintText: 'Search',
prefixIcon: Icon(
- Icons.search,
+ AppIcons.search,
size: kFieldIconSize,
color: AppPalette.textFaint,
),
@@ -535,7 +509,7 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
// with a mysterious margin down one side. Sizing the row makes the panel
// follow it, and the hover pill then spans the width a person is aiming
// at.
- style: AppMenu.style(maxHeight: _panelHeight),
+ style: AppMenu.style(maxHeight: _maxPanelHeight),
menuChildren: [
if (_filtering) _filterField(_rowWidth(panelWidth)),
if (widget.options.isEmpty && widget.emptyLabel != null)
@@ -605,95 +579,128 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
const SingleActivator(LogicalKeyboardKey.arrowDown): _open,
const SingleActivator(LogicalKeyboardKey.arrowUp): _open,
},
- child: InkWell(
- focusNode: _fieldFocus,
- onFocusChange: (value) => setState(() => _focused = value),
- onTap: () => controller.isOpen ? controller.close() : _open(),
- splashFactory: NoSplash.splashFactory,
- hoverColor: Colors.transparent,
- focusColor: Colors.transparent,
- borderRadius: BorderRadius.circular(
- widget.radius ?? AppControl.radius,
- ),
- child: SizedBox(
- width: widget.width,
- height: widget.height,
- child: AnimatedContainer(
- duration: AppMotion.hover,
- curve: AppMotion.curve,
- padding: widget.padding,
- decoration: BoxDecoration(
- color: _hovered || _focused || controller.isOpen
- ? widget.fillColor == null
- ? AppSurface.recessHover
- : Color.alphaBlend(
- AppTheme.palette.value.foreground.withValues(
- alpha: .05,
- ),
- widget.fillColor!,
- )
- : widget.fillColor ?? AppSurface.recess,
- borderRadius: BorderRadius.circular(
- widget.radius ?? AppControl.radius,
- ),
- border: Border.all(
- color:
- widget.selected == true ||
- (_focused && widget.selected == null)
- ? AppPalette.accentOnSurface
- : Colors.transparent,
- ),
- ),
- child:
- widget.trigger ??
- Row(
- children: [
- Expanded(
- child: Row(
- children: [
- if (current?.leading != null) ...[
- current!.leading!(),
- const SizedBox(width: 8),
- ],
- Flexible(
- child: Text(
- current?.label ?? '—',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style:
- widget.textStyle ??
- AppType.label(
- fontWeight: AppControl.fontWeight,
- color: AppPalette.textPrimary,
- ),
- ),
- ),
- if (current?.note != null) ...[
- const SizedBox(width: 8),
- Flexible(
- child: Text(
- current!.note!,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.mono(
- color: AppPalette.textFaint,
+ child: Semantics(
+ container: widget.semanticLabel != null,
+ button: true,
+ expanded: controller.isOpen,
+ selected: widget.selected,
+ label: widget.semanticLabel,
+ value: widget.semanticLabel == null
+ ? null
+ : [
+ current?.label ?? widget.emptyLabel ?? 'No selection',
+ ?current?.note,
+ ].join(', '),
+ child: InkWell(
+ focusNode: _fieldFocus,
+ onFocusChange: (value) => setState(() => _focused = value),
+ onTap: () => controller.isOpen ? controller.close() : _open(),
+ splashFactory: NoSplash.splashFactory,
+ hoverColor: Colors.transparent,
+ focusColor: Colors.transparent,
+ borderRadius: BorderRadius.circular(
+ widget.radius ?? AppControl.radius,
+ ),
+ child: ExcludeSemantics(
+ // The purpose and full value above replace only the visual
+ // trigger's text. The surrounding InkWell retains its actions.
+ excluding: widget.semanticLabel != null,
+ child: SizedBox(
+ width: widget.width,
+ height: widget.trigger == null
+ ? math.max(
+ widget.height,
+ MediaQuery.textScalerOf(context).scale(
+ widget.textStyle?.fontSize ??
+ AppType.bodySize,
+ ) *
+ 1.4 +
+ 12,
+ )
+ : widget.height,
+ child: AnimatedContainer(
+ duration: MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : AppMotion.hover,
+ curve: AppMotion.curve,
+ padding: widget.padding,
+ decoration: BoxDecoration(
+ color: _hovered || _focused || controller.isOpen
+ ? widget.fillColor == null
+ ? AppSurface.recessHover
+ : Color.alphaBlend(
+ AppPalette.textPrimary.withValues(
+ alpha: .05,
+ ),
+ widget.fillColor!,
+ )
+ : widget.fillColor ?? AppSurface.recess,
+ borderRadius: BorderRadius.circular(
+ widget.radius ?? AppControl.radius,
+ ),
+ border: Border.all(
+ width: MediaQuery.highContrastOf(context) ? 2 : 1.5,
+ color: _focused
+ ? AppDesktop.focus
+ : widget.selected == true
+ ? AppPalette.accentOnSurface
+ : MediaQuery.highContrastOf(context)
+ ? AppPalette.textSecondary
+ : Colors.transparent,
+ ),
+ ),
+ child:
+ widget.trigger ??
+ Row(
+ children: [
+ Expanded(
+ child: Row(
+ children: [
+ if (current?.leading != null) ...[
+ current!.leading!(),
+ const SizedBox(width: 8),
+ ],
+ Flexible(
+ child: Text(
+ current?.label ?? '—',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style:
+ widget.textStyle ??
+ AppType.label(
+ fontWeight: AppControl.fontWeight,
+ color: AppPalette.textPrimary,
+ ),
),
),
- ),
- ],
- ],
- ),
- ),
- const SizedBox(width: 6),
- Icon(
- Icons.expand_more_rounded,
- size: AppControl.iconSize,
- color: _hovered || controller.isOpen
- ? AppPalette.textPrimary
- : AppPalette.textSecondary,
+ if (current?.note != null) ...[
+ const SizedBox(width: 8),
+ Flexible(
+ child: Text(
+ current!.note!,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.body(
+ color: AppPalette.textFaint,
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(width: 6),
+ Icon(
+ AppIcons.chevronDown,
+ size: AppControl.iconSize,
+ color: _hovered || controller.isOpen
+ ? AppPalette.textPrimary
+ : AppPalette.textSecondary,
+ ),
+ ],
),
- ],
- ),
+ ),
+ ),
),
),
),
diff --git a/desktop/lib/shared/widgets/command_row.dart b/desktop/lib/shared/widgets/command_row.dart
index 53f08c5ca..6eb9ba9c5 100644
--- a/desktop/lib/shared/widgets/command_row.dart
+++ b/desktop/lib/shared/widgets/command_row.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -43,7 +44,7 @@ class CommandRow extends StatelessWidget {
),
),
Icon(
- copied ? Icons.check : Icons.copy,
+ copied ? AppIcons.check : AppIcons.copy,
size: 16,
color: copied ? AppColors.success : AppColors.mutedStrong,
),
diff --git a/desktop/lib/shared/widgets/empty_state.dart b/desktop/lib/shared/widgets/empty_state.dart
index eba6e2839..cb88bc841 100644
--- a/desktop/lib/shared/widgets/empty_state.dart
+++ b/desktop/lib/shared/widgets/empty_state.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
@@ -39,7 +40,7 @@ class EmptyState extends StatelessWidget {
/// Nothing matched the current search or filter. Deliberately actionless.
const EmptyState.noMatches({super.key, this.message, this.compact = true})
- : icon = Icons.search_off_rounded,
+ : icon = AppIcons.searchX,
title = 'No matches',
action = null;
diff --git a/desktop/lib/shared/widgets/setting_row.dart b/desktop/lib/shared/widgets/setting_row.dart
index 17112b87d..e05375a74 100644
--- a/desktop/lib/shared/widgets/setting_row.dart
+++ b/desktop/lib/shared/widgets/setting_row.dart
@@ -16,6 +16,7 @@ class SettingRow extends StatelessWidget {
required this.title,
this.detail,
required this.control,
+ this.controlSemanticLabel,
this.footer,
this.alignTop = false,
});
@@ -24,6 +25,12 @@ class SettingRow extends StatelessWidget {
final String? detail;
final Widget control;
+ /// Purpose of a single otherwise unlabeled control, such as a switch.
+ ///
+ /// Opt in only when [control] has one action. Rows containing several fields
+ /// or buttons keep their separate labels and actions instead of merging them.
+ final String? controlSemanticLabel;
+
/// Guidance or feedback that belongs inside this setting's block.
final Widget? footer;
@@ -51,6 +58,9 @@ class SettingRow extends StatelessWidget {
],
],
);
+ final labeledControl = controlSemanticLabel == null
+ ? control
+ : Semantics(label: controlSemanticLabel, child: control);
return Container(
// A raised block: fill plus a soft lift, no rim. The same recipe the rest
@@ -76,7 +86,11 @@ class SettingRow extends StatelessWidget {
MediaQuery.textScalerOf(context).scale(_stackBelow)
? Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [text, const SizedBox(height: 10), control],
+ children: [
+ text,
+ const SizedBox(height: 10),
+ labeledControl,
+ ],
)
: Row(
crossAxisAlignment: alignTop
@@ -85,7 +99,7 @@ class SettingRow extends StatelessWidget {
children: [
Expanded(child: text),
const SizedBox(width: 20),
- control,
+ labeledControl,
],
),
),
diff --git a/desktop/lib/sharing/harness_comments.dart b/desktop/lib/sharing/harness_comments.dart
index 90d435f2f..e382220f2 100644
--- a/desktop/lib/sharing/harness_comments.dart
+++ b/desktop/lib/sharing/harness_comments.dart
@@ -3,8 +3,8 @@ import 'dart:math';
import 'package:flutter/material.dart';
-import '../terminal/terminal_text.dart';
-import '../widgets/terminal_text_action.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
import '../ws/ws_conn.dart';
typedef CommentAction = Future<Map<String, dynamic>> Function(
@@ -19,10 +19,14 @@ class HarnessComments extends StatefulWidget {
required this.manage,
this.updates,
this.onSignIn,
+ this.headerAction,
+ this.padding = const EdgeInsets.all(16),
});
final CommentAction manage;
final Listenable? updates;
final VoidCallback? onSignIn;
+ final Widget? headerAction;
+ final EdgeInsetsGeometry padding;
@override
State<HarnessComments> createState() => _HarnessCommentsState();
}
@@ -155,110 +159,233 @@ class _HarnessCommentsState extends State<HarnessComments> {
@override
Widget build(BuildContext context) {
- final cell = terminalCellSizeOf(context);
- final style = terminalContentStyle(
- color: DefaultTextStyle.of(context).style.color,
- );
- return DefaultTextStyle(
- style: style,
+ grid.AppTheme.watch(context);
+ return DesktopChrome(
child: Padding(
- padding: EdgeInsets.all(cell.width * 2),
+ padding: widget.padding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Text(
- 'Comments${_comments.isEmpty ? '' : ' (${_comments.length})'}',
- ),
- SizedBox(height: cell.height),
- Expanded(
- child: _loading
- ? const Text('Loading comments…')
- : _comments.isEmpty
- ? const Text('Start the conversation.')
- : ListView.separated(
- itemCount: _comments.length,
- separatorBuilder: (_, _) => SizedBox(height: cell.height),
- itemBuilder: (context, index) {
- final c = _comments[index];
- final date = DateTime.tryParse('${c['createdAt']}')
- ?.toLocal();
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Row(
- children: [
- Expanded(
- child: Text(
- '${c['authorName']}',
- overflow: TextOverflow.ellipsis,
- style: style.copyWith(
- fontWeight: FontWeight.bold,
- ),
- ),
- ),
- if (date != null)
- Text(
- '${date.month}/${date.day} ${date.hour}:${date.minute.toString().padLeft(2, '0')}',
- ),
- if (c['canDelete'] == true)
- TerminalTextAction(
- label: 'Remove',
- onPressed: _busy
- ? null
- : () => _act('comment_remove', {
- 'id': c['id'],
- }),
- ),
- ],
- ),
- SelectionArea(
- child: Text('${c['text']}', style: style),
- ),
- ],
- );
- },
+ Row(
+ children: [
+ Expanded(
+ child: Text.rich(
+ TextSpan(
+ text: 'Comments',
+ children: [
+ if (_comments.isNotEmpty)
+ TextSpan(
+ text: ' (${_comments.length})',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
),
- ),
- if (_error != null)
- Semantics(liveRegion: true, child: Text(_error!)),
- SizedBox(height: cell.height),
- if (_canComment) ...[
- TextField(
- key: const Key('comment-input'),
- controller: _text,
- readOnly: _busy,
- style: style,
- minLines: 1,
- maxLines: 3,
- maxLength: 4000,
- decoration: InputDecoration(
- hintText: 'Leave a comment…',
- hintStyle: style,
- border: InputBorder.none,
- filled: false,
- contentPadding: EdgeInsets.zero,
- counterText: '',
+ key: const ValueKey('comments-heading'),
+ style: DesktopChrome.heading(),
+ ),
),
- onChanged: (_) => setState(() {}),
- ),
- Align(
- alignment: Alignment.centerRight,
- child: TerminalTextAction(
- label: _busy ? 'Saving…' : 'Comment',
- onPressed: _busy || _text.text.trim().isEmpty ? null : _post,
+ if (widget.headerAction case final action?) ...[
+ const SizedBox(width: DesktopChrome.controlGap),
+ action,
+ ],
+ ],
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Expanded(
+ child: LayoutBuilder(
+ builder: (context, constraints) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(child: _discussion()),
+ if (_error != null ||
+ _canComment ||
+ widget.onSignIn != null)
+ ConstrainedBox(
+ // Keep history visible while allowing a long failure or
+ // an enlarged composer to scroll inside a short pane.
+ constraints: BoxConstraints(
+ maxHeight: constraints.maxHeight * .65,
+ ),
+ child: SingleChildScrollView(
+ primary: false,
+ child: _composer(
+ maxLines:
+ constraints.maxHeight <
+ MediaQuery.textScalerOf(context).scale(240)
+ ? 2
+ : 3,
+ ),
+ ),
+ ),
+ ],
),
),
- ] else if (widget.onSignIn != null)
- Align(
- alignment: Alignment.centerLeft,
- child: TerminalTextAction(
- label: 'Sign in to comment',
- onPressed: widget.onSignIn,
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _discussion() {
+ if (_loading || _comments.isEmpty) {
+ return SingleChildScrollView(
+ primary: false,
+ child: Text(
+ _loading
+ ? 'Loading comments…'
+ : _error != null
+ ? 'Comments are unavailable.'
+ : 'Start the conversation.',
+ style: DesktopChrome.text(size: 13, color: DesktopChrome.muted),
+ ),
+ );
+ }
+ return ListView.separated(
+ key: const ValueKey('comments-list'),
+ primary: false,
+ itemCount: _comments.length,
+ separatorBuilder: (_, _) => Padding(
+ padding: const EdgeInsets.symmetric(vertical: 12),
+ child: Divider(height: 1, color: DesktopChrome.rim),
+ ),
+ itemBuilder: (context, index) {
+ final comment = _comments[index];
+ final author = '${comment['authorName']}';
+ final date = DateTime.tryParse('${comment['createdAt']}')?.toLocal();
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Tooltip(
+ message: author,
+ child: Text(
+ author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ if (date != null) ...[
+ const SizedBox(height: 4),
+ Text(
+ '${date.month}/${date.day} ${date.hour}:${date.minute.toString().padLeft(2, '0')}',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ],
+ ),
),
+ if (comment['canDelete'] == true) ...[
+ const SizedBox(width: DesktopChrome.controlGap),
+ DesktopPill(
+ label: 'Remove',
+ tooltip: 'Remove comment by $author',
+ quiet: true,
+ compact: true,
+ onPressed: _busy
+ ? null
+ : () => _act('comment_remove', {'id': comment['id']}),
+ ),
+ ],
+ ],
+ ),
+ const SizedBox(height: DesktopChrome.controlGap),
+ SelectionArea(
+ child: Text(
+ '${comment['text']}',
+ style: DesktopChrome.text(size: 13),
),
+ ),
],
+ );
+ },
+ );
+ }
+
+ Widget _composer({required int maxLines}) {
+ final border = OutlineInputBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ );
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 12),
+ child: Divider(height: 1, color: DesktopChrome.rim),
),
- ),
+ if (_error != null) ...[
+ Semantics(
+ liveRegion: true,
+ child: SelectableText(
+ _error!,
+ style: DesktopChrome.text(
+ size: 13,
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
+ const SizedBox(height: DesktopChrome.controlGap),
+ ],
+ if (_canComment) ...[
+ TextField(
+ key: const Key('comment-input'),
+ controller: _text,
+ readOnly: _busy,
+ style: DesktopChrome.text(size: 13),
+ cursorColor: DesktopChrome.accent,
+ minLines: 1,
+ maxLines: maxLines,
+ maxLength: 4000,
+ decoration: InputDecoration(
+ hintText: 'Leave a comment…',
+ hintStyle: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ border: border,
+ enabledBorder: border,
+ focusedBorder: border.copyWith(
+ borderSide: BorderSide(
+ color: DesktopChrome.focusRing,
+ width: 1.5,
+ ),
+ ),
+ filled: true,
+ fillColor: DesktopChrome.field,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 10,
+ ),
+ counterText: '',
+ ),
+ onChanged: (_) => setState(() {}),
+ ),
+ const SizedBox(height: DesktopChrome.controlGap),
+ Align(
+ alignment: Alignment.centerRight,
+ child: FilledButton(
+ key: const ValueKey('comment-post'),
+ onPressed: _busy || _text.text.trim().isEmpty ? null : _post,
+ child: Text(_busy ? 'Saving…' : 'Comment'),
+ ),
+ ),
+ ] else if (widget.onSignIn != null)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: DesktopPill(
+ label: 'Sign in to comment',
+ onPressed: widget.onSignIn,
+ ),
+ ),
+ ],
);
}
}
diff --git a/desktop/lib/sharing/share_harness_dialog.dart b/desktop/lib/sharing/share_harness_dialog.dart
index 871214088..d54b21b3f 100644
--- a/desktop/lib/sharing/share_harness_dialog.dart
+++ b/desktop/lib/sharing/share_harness_dialog.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
@@ -10,12 +11,8 @@ import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
import '../shortcuts/keymap_commands.dart';
import '../shortcuts/keymap_keyboard.dart';
-import '../terminal/terminal_text.dart';
-import '../terminal/terminal_theme.dart';
-import '../terminal/terminal_theme_store.dart';
-import '../widgets/box_chrome.dart';
import '../widgets/terminal_prompt.dart';
-import '../widgets/terminal_text_action.dart';
+import '../widgets/desktop_chrome.dart';
import 'harness_comments.dart';
import '../state/app_state.dart';
import '../ws/ws_conn.dart';
@@ -66,7 +63,6 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {
_ShareRow _row = _ShareRow.copy;
bool _options = false, _picking = false, _hideChoices = false;
int _choice = 0;
- double _column = 8, _line = 20;
final _emails = TextEditingController();
List<Map<String, dynamic>> _shares = [];
@@ -307,7 +303,7 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {
_shares.isEmpty
? 'Only you'
: '${_shares.length} ${_shares.length == 1 ? 'person' : 'people'}',
- _ShareRow.options => _options ? '[-]' : '[+]',
+ _ShareRow.options => _options ? 'Hide' : 'Show',
_ShareRow.expiry => '$_days days',
_ShareRow.comments => 'Open discussion',
_ => null,
@@ -537,31 +533,10 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- TerminalFontScope.watch(context);
- return ListenableBuilder(
- listenable: Listenable.merge([terminalFontStore, terminalThemeStore]),
- builder: (context, _) {
- final cell = terminalCellSizeOf(context);
- _column = cell.width;
- _line = cell.height;
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
- final style = terminalContentStyle(color: theme.foreground);
- final muted = theme.muted;
- Widget surface(Key key, Widget child) => Material(
- key: key,
- color: theme.background,
- elevation: 0,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(kTerminalCornerRadius),
- side: terminalPaneBorder(focused: true),
- ),
- clipBehavior: Clip.antiAlias,
- child: DefaultTextStyle(style: style, child: child),
- );
- return KeymapRegion(
+ return DesktopChrome(
+ child: DefaultTextStyle(
+ style: DesktopChrome.text(size: 13),
+ child: KeymapRegion(
contextKind: KeymapContext.picker,
composing: () => _composing,
actions: _keyActions,
@@ -570,97 +545,44 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {
autofocus: true,
onKeyEvent: _key,
child: Padding(
- padding: EdgeInsets.symmetric(
- horizontal: _column * 2,
- vertical: _line,
- ),
+ padding: const EdgeInsets.all(20),
child: LayoutBuilder(
builder: (context, constraints) {
- final columns = math.max(
- 1,
- (constraints.maxWidth / _column).floor(),
- );
- final formColumns = math.min(56, columns);
- final left = (columns - formColumns) ~/ 2;
- final available = columns - left - formColumns - 1;
- final beside = available >= 28;
+ final formWidth = math.min(480.0, constraints.maxWidth);
+ final left = (constraints.maxWidth - formWidth) / 2;
+ final available =
+ constraints.maxWidth - left - formWidth - 16;
+ final beside = available >= 280;
final showChoices = _hasChoices && !_hideChoices;
final replaceForm = _picking && !beside;
- final formWidth = formColumns * _column;
- final rows = _rows;
- var formRows = 5 + rows.length + 3;
- if (rows.contains(_ShareRow.people)) formRows++;
- // Copy follows the fields with one blank row; notices get their own rows.
- for (final message in _messages) {
- final painter =
- TextPainter(
- text: TextSpan(text: message, style: style),
- textDirection: TextDirection.ltr,
- textScaler: MediaQuery.textScalerOf(context),
- )..layout(
- maxWidth: math.max(_column, formWidth - _column * 4),
- );
- formRows += 1 + (painter.height / _line).ceil();
- painter.dispose();
- }
- final formHeight = math.min(
- constraints.maxHeight,
- formRows * _line,
- );
- final sideHeight = math.min(
- constraints.maxHeight,
- ((_row == _ShareRow.access
- ? 12
- : _row == _ShareRow.expiry
- ? 11
- : _row == _ShareRow.people
- ? math.min(20, 12 + _shares.length * 4)
- : 20) +
- (replaceForm ? 2 : 0)) *
- _line,
- );
- final top = math.max(
- 0.0,
- ((constraints.maxHeight - formHeight) / (2 * _line))
- .floor() *
- _line,
- );
- final sideTop = math.min(
- top,
- constraints.maxHeight - sideHeight,
- );
+ // Opening a chooser leaves the form in place. Narrow windows
+ // show that same chooser in the form's frame instead.
return Stack(
children: [
- Positioned(
- left: left * _column,
- top: replaceForm ? sideTop : top,
- width: formWidth,
- height: replaceForm ? sideHeight : formHeight,
- child: surface(
- const ValueKey('share-form-surface'),
- replaceForm
- ? _sidePane(
- theme.foreground,
- muted,
- theme.selection,
- narrow: true,
- )
- : _formPane(
- theme.foreground,
- muted,
- theme.selection,
- ),
+ Align(
+ alignment: Alignment.center,
+ child: SizedBox(
+ width: formWidth,
+ child: DesktopDialogSurface(
+ key: const ValueKey('share-form-surface'),
+ child: replaceForm
+ ? _sidePane(narrow: true)
+ : _formPane(),
+ ),
),
),
if (showChoices && beside)
Positioned(
- left: (left + formColumns + 1) * _column,
- top: sideTop,
- width: math.min(40, available) * _column,
- height: sideHeight,
- child: surface(
- const ValueKey('share-choices-surface'),
- _sidePane(theme.foreground, muted, theme.selection),
+ left: left + formWidth + 16,
+ top: 0,
+ bottom: 0,
+ width: math.min(360.0, available),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: DesktopDialogSurface(
+ key: const ValueKey('share-choices-surface'),
+ child: _sidePane(),
+ ),
),
),
],
@@ -669,8 +591,8 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {
),
),
),
- );
- },
+ ),
+ ),
);
}
@@ -685,153 +607,237 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {
if (_manualCopy && _link?['url'] is String) _link!['url'] as String,
];
+ /// These controls use the form's existing row/choice keyboard selection.
+ /// Excluding their own focus keeps Tab switching panes and preserves the
+ /// email editor's IME ownership; pointer and accessibility activation remain.
Widget _plainRow({
required String label,
String? value,
required bool selected,
required bool enabled,
- required Color foreground,
- required Color muted,
- required Color selection,
required VoidCallback onTap,
+ bool primary = false,
+ bool destructive = false,
+ bool? checked,
+ IconData? icon,
+ IconData? disclosure,
Key? key,
Key? rowKey,
- }) => Semantics(
- key: key,
- label: value == null ? label : '$label, $value',
- button: true,
- selected: selected,
- enabled: enabled,
- onTap: enabled ? onTap : null,
- excludeSemantics: true,
- child: MouseRegion(
- cursor: enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: enabled ? onTap : null,
- child: Container(
- key: rowKey,
- height: _line,
- color: selected && enabled ? selection : Colors.transparent,
- padding: EdgeInsets.symmetric(horizontal: _column),
- alignment: Alignment.centerLeft,
- child: value == null
- ? Text(
- label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: terminalContentStyle(
- color: enabled ? foreground : muted,
- ),
+ }) {
+ final foreground = !enabled
+ ? DesktopChrome.muted
+ : primary
+ ? Theme.of(context).colorScheme.onPrimary
+ : destructive
+ ? Theme.of(context).colorScheme.error
+ : DesktopChrome.foreground;
+ final content = Row(
+ children: [
+ if (checked != null || icon != null) ...[
+ SizedBox(
+ width: 18,
+ child: checked == false
+ ? null
+ : Icon(checked == true ? AppIcons.check : icon, size: 18),
+ ),
+ const SizedBox(width: DesktopChrome.controlGap),
+ ],
+ Expanded(
+ child: Text(label, style: DesktopChrome.control(color: foreground)),
+ ),
+ if (value != null) ...[
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ value,
+ textAlign: TextAlign.end,
+ style: DesktopChrome.control(color: DesktopChrome.muted),
+ ),
+ ),
+ ],
+ if (disclosure != null) ...[
+ const SizedBox(width: DesktopChrome.controlGap),
+ Icon(disclosure, size: 18, color: DesktopChrome.muted),
+ ],
+ ],
+ );
+ final style = ButtonStyle(
+ minimumSize: const WidgetStatePropertyAll(Size(0, 36)),
+ padding: const WidgetStatePropertyAll(
+ EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ ),
+ shape: WidgetStatePropertyAll(
+ RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ ),
+ ),
+ foregroundColor: WidgetStatePropertyAll(foreground),
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ color: selected && enabled
+ ? primary
+ ? Colors.white.withValues(alpha: .85)
+ : DesktopChrome.focusRing
+ : DesktopChrome.rim,
+ width: selected && enabled ? 2 : 1,
+ ),
+ ),
+ backgroundColor: primary
+ ? null
+ : WidgetStateProperty.resolveWith((states) {
+ if (selected && enabled) return DesktopChrome.selection;
+ if (enabled && states.contains(WidgetState.hovered)) {
+ return grid.AppGlass.rowHoverFill;
+ }
+ return DesktopChrome.field;
+ }),
+ );
+ return Semantics(
+ key: key,
+ label: value == null ? label : '$label, $value',
+ button: true,
+ selected: selected,
+ checked: checked,
+ enabled: enabled,
+ onTap: enabled ? onTap : null,
+ excludeSemantics: true,
+ child: KeyedSubtree(
+ key: rowKey,
+ child: ExcludeFocus(
+ child: primary
+ ? FilledButton(
+ onPressed: enabled ? onTap : null,
+ style: style,
+ child: content,
)
- : Row(
- children: [
- SizedBox(
- width: _column * 11,
- child: Text(
- label,
- style: terminalContentStyle(color: muted),
- ),
- ),
- Expanded(
- child: Text(
- value,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: terminalContentStyle(
- color: enabled ? foreground : muted,
- ),
- ),
- ),
- ],
+ : TextButton(
+ onPressed: enabled ? onTap : null,
+ style: style,
+ child: content,
),
),
),
- ),
+ );
+ }
+
+ Widget _formRow(_ShareRow row) => _plainRow(
+ key: ValueKey('share-field-${row.name}'),
+ rowKey: _rowKeys[row],
+ label: _label(row),
+ value: _value(row),
+ selected: _row == row && !_picking,
+ enabled: _enabled(row),
+ primary: row == _ShareRow.copy,
+ destructive: row == _ShareRow.stop,
+ icon: row == _ShareRow.copy ? AppIcons.link2 : null,
+ disclosure: switch (row) {
+ _ShareRow.options => _options ? AppIcons.chevronUp : AppIcons.chevronDown,
+ _ShareRow.access ||
+ _ShareRow.people ||
+ _ShareRow.expiry ||
+ _ShareRow.comments => AppIcons.chevronRight,
+ _ => null,
+ },
+ onTap: () {
+ _select(row);
+ _activate();
+ },
);
- Widget _formPane(Color foreground, Color muted, Color selection) =>
- SingleChildScrollView(
- controller: _formScroll,
- padding: EdgeInsets.symmetric(horizontal: _column, vertical: _line),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: EdgeInsets.symmetric(horizontal: _column),
- child: Text(
- 'Share ${widget.name}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: terminalContentStyle(color: foreground)
- .copyWith(fontWeight: FontWeight.bold),
+ Widget _formPane() => Padding(
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: Scrollbar(
+ controller: _formScroll,
+ thumbVisibility: true,
+ child: SingleChildScrollView(
+ controller: _formScroll,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text('Share harness', style: DesktopChrome.heading()),
+ const SizedBox(height: 8),
+ Text(
+ widget.name,
+ style: DesktopChrome.text(size: 14, medium: true),
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ for (final row in _rows)
+ if (row != _ShareRow.copy && row != _ShareRow.retry) ...[
+ if (row == _ShareRow.options) const SizedBox(height: 8),
+ _formRow(row),
+ const SizedBox(height: DesktopChrome.controlGap),
+ ],
+ if (!_picking) ..._messageWidgets(),
+ ],
),
),
- SizedBox(height: _line),
- for (final row in _rows) ...[
- if (row == _ShareRow.people ||
- row == _ShareRow.options ||
- row == _ShareRow.copy)
- SizedBox(height: _line),
- _plainRow(
- key: ValueKey('share-field-${row.name}'),
- rowKey: _rowKeys[row],
- label: _label(row),
- value: _value(row),
- selected: _row == row && !_picking,
- enabled: _enabled(row),
- foreground: foreground,
- muted: muted,
- selection: selection,
- onTap: () {
- _select(row);
- _activate();
- },
- ),
- ],
- if (!_picking) ..._messageWidgets(foreground),
- SizedBox(height: _line),
- Padding(
- padding: EdgeInsets.symmetric(horizontal: _column),
+ ),
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ _formRow(_ShareRow.copy),
+ if (_rows.contains(_ShareRow.retry)) ...[
+ const SizedBox(height: DesktopChrome.controlGap),
+ _formRow(_ShareRow.retry),
+ ],
+ const SizedBox(height: DesktopChrome.groupGap),
+ Row(
+ children: [
+ Expanded(
child: Text(
'Keep your machine online.',
- style: terminalContentStyle(color: muted),
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ const SizedBox(width: 8),
+ ExcludeFocus(
+ child: TextButton(
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('Close'),
),
),
],
),
- );
+ ],
+ ),
+ );
- List<Widget> _messageWidgets(Color foreground) => [
+ List<Widget> _messageWidgets() => [
for (final message in _messages) ...[
- SizedBox(height: _line),
- Padding(
- padding: EdgeInsets.symmetric(horizontal: _column),
- child: Semantics(
- liveRegion: true,
- child: _manualCopy && message == _link?['url']
- ? SelectableText(
- message,
- style: terminalContentStyle(color: foreground),
- )
- : Text(message, style: terminalContentStyle(color: foreground)),
- ),
+ const SizedBox(height: 12),
+ Semantics(
+ liveRegion: true,
+ child: _manualCopy && message == _link?['url']
+ ? SelectableText(message, style: grid.AppType.monoMeta())
+ : Text(
+ message,
+ style: DesktopChrome.text(
+ size: 13,
+ color: message == _error || message == _link?['error']
+ ? Theme.of(context).colorScheme.error
+ : _link?['pending'] == true
+ ? grid.AppPalette.warn
+ : DesktopChrome.muted,
+ ),
+ ),
),
],
];
- Widget _sidePane(
- Color foreground,
- Color muted,
- Color selection, {
- bool narrow = false,
- }) {
+ Widget _sidePane({bool narrow = false}) {
Widget choice(
String label,
int index,
VoidCallback activate, {
bool enabled = true,
String? value,
+ bool primary = false,
+ bool destructive = false,
+ bool? checked,
}) => _plainRow(
key: ValueKey('share-choice-$index'),
rowKey: _choiceKeys.putIfAbsent(index, GlobalKey.new),
@@ -839,9 +845,9 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {
value: value,
selected: _picking && _choice == index,
enabled: enabled && !_disabled,
- foreground: foreground,
- muted: muted,
- selection: selection,
+ primary: primary,
+ destructive: destructive,
+ checked: checked,
onTap: () {
setState(() {
_picking = true;
@@ -850,131 +856,198 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {
activate();
},
);
- Widget note(String text) => Padding(
- padding: EdgeInsets.symmetric(horizontal: _column),
- child: Text(text, style: terminalContentStyle(color: muted)),
+ Widget note(String text, {Color? color}) => Text(
+ text,
+ style: DesktopChrome.text(size: 13, color: color ?? DesktopChrome.muted),
+ );
+ final title = switch (_row) {
+ _ShareRow.access => 'Link access',
+ _ShareRow.people => 'People',
+ _ShareRow.expiry => 'Invitation expiry',
+ _ShareRow.comments => 'Comments',
+ _ => 'Sharing options',
+ };
+ final backControl = TextButton.icon(
+ key: narrow ? const ValueKey('share-back') : null,
+ onPressed: _backToForm,
+ icon: const Icon(AppIcons.arrowLeft, size: 16),
+ label: const Text('Back'),
);
+ final back = _row == _ShareRow.comments && _picking
+ ? backControl
+ : ExcludeFocus(child: backControl);
if (_row == _ShareRow.comments && _picking) {
return TerminalPromptKeys(
focusNode: _commentsFocus,
cancel: _backToForm,
- child: Padding(
- padding: EdgeInsets.all(_column * 2),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Align(
- alignment: Alignment.centerLeft,
- child: TerminalTextAction(
- label: 'Back',
- onPressed: _backToForm,
- ),
- ),
- SizedBox(height: _line),
- Expanded(
- child: HarnessComments(
- key: _commentsKey,
- manage: widget.manage,
- ),
- ),
- ],
+ child: SizedBox(
+ height: 560,
+ child: HarnessComments(
+ key: _commentsKey,
+ manage: widget.manage,
+ headerAction: back,
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
),
),
);
}
- return SingleChildScrollView(
- controller: _sideScroll,
- padding: EdgeInsets.symmetric(horizontal: _column, vertical: _line),
+ final fieldBorder = OutlineInputBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ );
+ return Padding(
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
child: Column(
+ mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- if (narrow) ...[
- _plainRow(
- key: const ValueKey('share-back'),
- label: '< Back',
- selected: false,
- enabled: true,
- foreground: foreground,
- muted: muted,
- selection: selection,
- onTap: _backToForm,
- ),
- SizedBox(height: _line),
- ],
- if (_row == _ShareRow.access) ...[
- choice('Private', 0, () => unawaited(_chooseVisibility(0))),
- note('Only invited emails can view and comment.'),
- SizedBox(height: _line),
- choice('Public', 1, () => unawaited(_chooseVisibility(1))),
- note('Anyone with the link can view. Sign in to comment.'),
- SizedBox(height: _line),
- note('Viewers cannot control your harness.'),
- ],
- if (_row == _ShareRow.expiry) ...[
- for (var i = 0; i < 3; i++)
- choice('${const [7, 30, 90][i]} days', i, () {
- setState(() => _days = const [7, 30, 90][i]);
- _backToForm(selectCopy: true);
- }),
- SizedBox(height: _line),
- note(
- 'Applies to new invitations. Your link stays active until you stop sharing.',
- ),
- ],
- if (_row == _ShareRow.people) ...[
- Padding(
- padding: EdgeInsets.symmetric(horizontal: _column),
- child: TextField(
- key: _choiceKeys.putIfAbsent(0, GlobalKey.new),
- controller: _emails,
- focusNode: _emailFocus,
- enabled: !_disabled,
- keyboardType: TextInputType.emailAddress,
- style: terminalContentStyle(color: foreground),
- cursorWidth: 2,
- decoration: InputDecoration(
- hintText: 'Add emails',
- hintStyle: terminalContentStyle(color: muted),
- isDense: true,
- filled: false,
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- contentPadding: EdgeInsets.zero,
+ Row(
+ children: [
+ Expanded(child: Text(title, style: DesktopChrome.heading())),
+ back,
+ ],
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Flexible(
+ child: Scrollbar(
+ controller: _sideScroll,
+ thumbVisibility: true,
+ child: SingleChildScrollView(
+ controller: _sideScroll,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (_row == _ShareRow.access) ...[
+ choice(
+ 'Private',
+ 0,
+ () => unawaited(_chooseVisibility(0)),
+ checked: !_isPublic,
+ ),
+ const SizedBox(height: 8),
+ note('Only invited emails can view and comment.'),
+ const SizedBox(height: DesktopChrome.groupGap),
+ choice(
+ 'Public',
+ 1,
+ () => unawaited(_chooseVisibility(1)),
+ checked: _isPublic,
+ ),
+ const SizedBox(height: 8),
+ note(
+ 'Anyone with the link can view. Sign in to comment.',
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ note('Viewers cannot control your agent.'),
+ ],
+ if (_row == _ShareRow.expiry) ...[
+ for (var i = 0; i < 3; i++) ...[
+ choice('${const [7, 30, 90][i]} days', i, () {
+ setState(() => _days = const [7, 30, 90][i]);
+ _backToForm(selectCopy: true);
+ }, checked: _days == const [7, 30, 90][i]),
+ const SizedBox(height: DesktopChrome.controlGap),
+ ],
+ const SizedBox(height: 8),
+ note(
+ 'Applies to new invitations. Your link stays active until you stop sharing.',
+ ),
+ ],
+ if (_row == _ShareRow.people) ...[
+ Text(
+ 'Email addresses',
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: DesktopChrome.controlGap),
+ TextField(
+ key: _choiceKeys.putIfAbsent(0, GlobalKey.new),
+ controller: _emails,
+ focusNode: _emailFocus,
+ enabled: !_disabled,
+ keyboardType: TextInputType.emailAddress,
+ style: DesktopChrome.text(size: 14),
+ cursorColor: DesktopChrome.accent,
+ decoration: InputDecoration(
+ hintText: 'Add emails',
+ hintStyle: DesktopChrome.text(
+ size: 14,
+ color: DesktopChrome.muted,
+ ),
+ isDense: true,
+ filled: true,
+ fillColor: DesktopChrome.field,
+ border: fieldBorder,
+ enabledBorder: fieldBorder,
+ focusedBorder: fieldBorder.copyWith(
+ borderSide: BorderSide(
+ color: DesktopChrome.focusRing,
+ width: 2,
+ ),
+ ),
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 10,
+ ),
+ ),
+ onTap: () => setState(() {
+ _picking = true;
+ _choice = 0;
+ }),
+ onChanged: (_) => setState(() {}),
+ onSubmitted: (_) {
+ if (!_composing && !_disabled) unawaited(_invite());
+ },
+ ),
+ const SizedBox(height: DesktopChrome.controlGap),
+ choice(
+ 'Add people',
+ 1,
+ () => unawaited(_invite()),
+ enabled: _emails.text.trim().isNotEmpty,
+ primary: true,
+ ),
+ const SizedBox(height: 8),
+ note(
+ 'Invited for $_days days. Copy and send them the link.',
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ if (_shares.isEmpty) note('No invited people yet.'),
+ for (final (index, share) in _shares.indexed) ...[
+ Text(
+ '${share['email']}',
+ style: DesktopChrome.text(size: 13, medium: true),
+ ),
+ const SizedBox(height: 4),
+ note(
+ _recipientStatus(share),
+ color: share['error'] != null
+ ? Theme.of(context).colorScheme.error
+ : share['pending'] == true ||
+ share['expired'] == true
+ ? grid.AppPalette.warn
+ : DesktopChrome.muted,
+ ),
+ const SizedBox(height: 8),
+ choice(
+ 'Remove ${share['email']}',
+ index + 2,
+ () => unawaited(_remove(share['id'] as String)),
+ destructive: true,
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ ],
+ note(
+ 'Viewers can comment; they cannot control your agent.',
+ ),
+ ],
+ if (_row == _ShareRow.comments)
+ note('Open Comments to join the discussion.'),
+ if (_picking) ..._messageWidgets(),
+ ],
),
- onTap: () => setState(() {
- _picking = true;
- _choice = 0;
- }),
- onChanged: (_) => setState(() {}),
- onSubmitted: (_) {
- if (!_composing && !_disabled) unawaited(_invite());
- },
),
),
- choice(
- 'Add people',
- 1,
- () => unawaited(_invite()),
- enabled: _emails.text.trim().isNotEmpty,
- ),
- note('Invited for $_days days. Copy and send them the link.'),
- SizedBox(height: _line),
- if (_shares.isEmpty) note('No invited people yet.'),
- for (final (index, share) in _shares.indexed) ...[
- note('${share['email']}'),
- note(_recipientStatus(share)),
- choice(
- 'Remove ${share['email']}',
- index + 2,
- () => unawaited(_remove(share['id'] as String)),
- ),
- SizedBox(height: _line),
- ],
- note('Viewers can comment; they cannot control your harness.'),
- ],
- if (_row == _ShareRow.comments) note('Enter to open the discussion.'),
- if (_picking) ..._messageWidgets(foreground),
+ ),
],
),
);
diff --git a/desktop/lib/sharing/shared_agent_page.dart b/desktop/lib/sharing/shared_agent_page.dart
index 32e0dc51c..c81ea481a 100644
--- a/desktop/lib/sharing/shared_agent_page.dart
+++ b/desktop/lib/sharing/shared_agent_page.dart
@@ -5,10 +5,10 @@ import 'package:flutter/material.dart';
import 'package:url_launcher/link.dart';
import '../core/models.dart';
+import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
import '../state/terminal_pane.dart';
-import '../terminal/terminal_text.dart';
-import '../widgets/terminal_text_action.dart';
+import '../widgets/desktop_chrome.dart';
import '../widgets/web_download_button.dart';
import 'shared_agent_location.dart';
import 'shared_harness_panel.dart';
@@ -142,23 +142,34 @@ class _SharedAgentPageState extends State<SharedAgentPage> {
@override
Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
final data = _data;
return Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
body: SafeArea(
child: Column(
children: [
Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
- child: Row(
- children: [
- Link(
- uri: Uri.parse('/'),
- builder: (context, follow) =>
- TerminalTextAction(label: 'Harness', onPressed: follow),
- ),
- const Spacer(),
- const WebDownloadButton(),
- ],
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+ child: SizedBox(
+ width: double.infinity,
+ child: Wrap(
+ spacing: 16,
+ runSpacing: 8,
+ alignment: WrapAlignment.spaceBetween,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ Link(
+ uri: Uri.parse('/'),
+ builder: (context, follow) => DesktopPill(
+ label: 'Harness',
+ quiet: true,
+ onPressed: follow,
+ ),
+ ),
+ const WebDownloadButton(),
+ ],
+ ),
),
),
Expanded(
@@ -192,44 +203,75 @@ class _SharedAgentPageState extends State<SharedAgentPage> {
: () => unawaited(widget.app.login()),
)
: Center(
- child: Padding(
+ child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- _loading
- ? 'Opening shared harness…'
- : _error ?? 'Shared harness',
- style: terminalContentStyle(),
- textAlign: TextAlign.center,
- ),
- if (widget.app.lastError != null)
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 440),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
Text(
- widget.app.lastError!,
+ _loading
+ ? 'Opening shared harness…'
+ : 'Shared harness',
+ style: DesktopChrome.heading(),
textAlign: TextAlign.center,
),
- const SizedBox(height: 20),
- if (_signInRequired)
- TerminalTextAction(
- label: widget.app.signingIn
- ? 'Signing in…'
- : 'Sign in',
- onPressed: widget.app.signingIn
- ? null
- : () => unawaited(widget.app.login()),
- ),
- if (!_loading && !_signInRequired)
- TerminalTextAction(
- label: 'Retry',
- onPressed: _load,
- ),
- if (!_loading && _signedIn && _data == null)
- TerminalTextAction(
- label: 'Switch account',
- onPressed: () => unawaited(widget.app.logout()),
+ if (!_loading) ...[
+ const SizedBox(height: 12),
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ _error ?? 'Shared harness',
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ textAlign: TextAlign.center,
+ ),
+ ),
+ ],
+ if (widget.app.lastError != null) ...[
+ const SizedBox(height: 12),
+ Text(
+ widget.app.lastError!,
+ style: DesktopChrome.text(
+ size: 13,
+ color: Theme.of(context).colorScheme.error,
+ ),
+ textAlign: TextAlign.center,
+ ),
+ ],
+ const SizedBox(height: 20),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ alignment: WrapAlignment.center,
+ children: [
+ if (_signInRequired)
+ DesktopPill(
+ label: widget.app.signingIn
+ ? 'Signing in…'
+ : 'Sign in',
+ onPressed: widget.app.signingIn
+ ? null
+ : () => unawaited(widget.app.login()),
+ ),
+ if (!_loading && !_signInRequired)
+ DesktopPill(
+ label: 'Retry',
+ onPressed: _load,
+ ),
+ if (!_loading && _signedIn && _data == null)
+ DesktopPill(
+ label: 'Switch account',
+ onPressed: () =>
+ unawaited(widget.app.logout()),
+ ),
+ ],
),
- ],
+ ],
+ ),
),
),
),
diff --git a/desktop/lib/sharing/shared_harness_bar.dart b/desktop/lib/sharing/shared_harness_bar.dart
index 1c8229ce9..16be9b49c 100644
--- a/desktop/lib/sharing/shared_harness_bar.dart
+++ b/desktop/lib/sharing/shared_harness_bar.dart
@@ -1,9 +1,9 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../shared/theme/workspace_bar_style.dart';
-import '../widgets/terminal_text_action.dart';
-import '../widgets/workspace_bar_control.dart';
+import '../shared/widgets/app_icon_button.dart';
+import '../widgets/desktop_chrome.dart';
/// What a reader of a shared harness is looking at, most urgent first.
enum SharedPaneStatus {
@@ -41,8 +41,8 @@ enum SharedPaneStatus {
}
/// The one bar above a shared harness: name, state and read-only label on the
-/// left, the reader's actions on the right. Workspace bar type and height, so a
-/// shared pane reads like any other pane header.
+/// left, the reader's actions on the right. Actions wrap when the pane or text
+/// size needs more room, without changing how the output below is sized.
class SharedHarnessBar extends StatelessWidget {
const SharedHarnessBar({
super.key,
@@ -71,31 +71,56 @@ class SharedHarnessBar extends StatelessWidget {
/// Below this width the actions move to a second row instead of squeezing
/// the name to nothing.
- static const narrowWidth = 640.0;
+ static const narrowWidth = 800.0;
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- final cell = workspaceBarCellSizeOf(context);
- final height = workspaceBarControlHeight(context);
- Widget row(List<Widget> children) => SizedBox(
- height: height,
- child: Row(children: children),
- );
return Container(
- padding: EdgeInsets.symmetric(horizontal: cell.width),
- color: grid.AppSurface.recess,
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ decoration: BoxDecoration(
+ color: grid.AppSurface.recess,
+ border: Border(bottom: BorderSide(color: DesktopChrome.rim)),
+ ),
child: LayoutBuilder(
builder: (context, constraints) {
- final identity = _identity(cell);
- final actions = _actions(cell);
- if (constraints.maxWidth >= narrowWidth) {
- return row([Expanded(child: Row(children: identity)), ...actions]);
+ final close = AppIconButton(
+ icon: AppIcons.close,
+ tooltip: 'Close shared harness',
+ onPressed: onClose,
+ );
+ final actions = Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: _actions(),
+ );
+ if (constraints.maxWidth >=
+ narrowWidth * grid.appTextScaleOf(context)) {
+ return Row(
+ children: [
+ Expanded(child: _identity()),
+ const SizedBox(width: 16),
+ actions,
+ const SizedBox(width: 8),
+ close,
+ ],
+ );
}
return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
children: [
- row(identity),
- row([const Spacer(), ...actions]),
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(child: _identity()),
+ const SizedBox(width: 8),
+ close,
+ ],
+ ),
+ const SizedBox(height: 8),
+ actions,
],
);
},
@@ -103,102 +128,88 @@ class SharedHarnessBar extends StatelessWidget {
);
}
- List<Widget> _identity(Size cell) {
- final muted = workspaceBarTextStyle(color: grid.AppPalette.textSecondary);
- return [
- Flexible(
+ Widget _identity() => Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Tooltip(
+ message: name,
child: Text(
name,
- maxLines: 1,
+ maxLines: 2,
overflow: TextOverflow.ellipsis,
- style: workspaceBarTextStyle(
- color: grid.AppPalette.textPrimary,
- emphasized: true,
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ if (detail case final detail?) ...[
+ const SizedBox(height: 4),
+ Tooltip(
+ message: detail,
+ child: Text(
+ detail,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
),
),
+ ],
+ const SizedBox(height: 4),
+ Wrap(
+ spacing: 12,
+ runSpacing: 4,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ ExcludeSemantics(
+ child: Container(
+ width: 6,
+ height: 6,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: status.color,
+ ),
+ ),
+ ),
+ const SizedBox(width: 6),
+ Text(status.label, style: DesktopChrome.metadata()),
+ ],
+ ),
+ Text('View only', style: DesktopChrome.metadata()),
+ ],
),
- if (detail case final detail?)
- Text(' · $detail', maxLines: 1, style: muted),
- SizedBox(width: cell.width * 2),
- Text('●', style: workspaceBarTextStyle(color: status.color)),
- SizedBox(width: cell.width),
- Text(status.label, style: muted),
- Text(' · ', style: muted),
- Text('View only', style: muted),
- ];
- }
+ ],
+ );
- List<Widget> _actions(Size cell) {
+ List<Widget> _actions() {
final viewer = viewerSelected;
return [
if (viewer != null && onSelectViewer != null) ...[
- _ViewTab(
+ DesktopPill(
label: 'Terminal',
selected: !viewer,
+ compact: true,
onPressed: () => onSelectViewer!(false),
),
- _ViewTab(
+ DesktopPill(
label: 'Viewer',
selected: viewer,
+ compact: true,
onPressed: () => onSelectViewer!(true),
),
- SizedBox(width: cell.width),
],
if (onRetry case final retry?)
- TerminalTextAction(label: 'Retry', onPressed: retry),
- TerminalTextAction(
+ DesktopPill(label: 'Retry', onPressed: retry, compact: true),
+ DesktopPill(
label: commentsSelected ? 'Watch' : 'Comments',
onPressed: onToggleComments,
- ),
- Tooltip(
- message: 'Close shared harness',
- child: TerminalTextAction(label: 'Close', onPressed: onClose),
+ compact: true,
),
];
}
}
-/// A Terminal/Viewer choice drawn like a workspace tab: the selection is a
-/// fill, hover and focus are bold text.
-class _ViewTab extends StatelessWidget {
- const _ViewTab({
- required this.label,
- required this.selected,
- required this.onPressed,
- });
-
- final String label;
- final bool selected;
- final VoidCallback onPressed;
-
- @override
- Widget build(BuildContext context) {
- final cell = workspaceBarCellSizeOf(context);
- final size = workspaceBarTextSizeOf(context, label);
- return WorkspaceBarControl(
- label: label,
- selected: selected,
- selectedBackground: grid.AppPalette.windowBg,
- onPressed: onPressed,
- builder: (context, emphasized) => SizedBox(
- width: size.width + cell.width * 2,
- height: workspaceBarControlHeight(context),
- child: Center(
- child: Text(
- label,
- style: workspaceBarTextStyle(
- color: selected
- ? grid.AppPalette.textPrimary
- : grid.AppPalette.textSecondary,
- emphasized: emphasized,
- ),
- ),
- ),
- ),
- );
- }
-}
-
/// One quiet line under the bar: why the terminal is empty or has ended.
class SharedHarnessNotice extends StatelessWidget {
const SharedHarnessNotice(this.message, {super.key});
@@ -208,20 +219,13 @@ class SharedHarnessNotice extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- final cell = workspaceBarCellSizeOf(context);
return Container(
width: double.infinity,
- padding: EdgeInsets.symmetric(
- horizontal: cell.width,
- vertical: cell.height / 2,
- ),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: grid.AppPalette.divider)),
),
- child: Text(
- message,
- style: workspaceBarTextStyle(color: grid.AppPalette.textSecondary),
- ),
+ child: Text(message, style: DesktopChrome.metadata()),
);
}
}
diff --git a/desktop/lib/sharing/shared_harness_panel.dart b/desktop/lib/sharing/shared_harness_panel.dart
index 4e00a1ead..d45227d83 100644
--- a/desktop/lib/sharing/shared_harness_panel.dart
+++ b/desktop/lib/sharing/shared_harness_panel.dart
@@ -314,10 +314,7 @@ class _SharedHarnessPanelState extends State<SharedHarnessPanel> {
builder: (context, size) {
final commentsBeside = size.maxWidth >= _commentsBesideWidth;
final commentsWidth = commentsBeside
- ? (terminalCellSizeOf(context).width * 44).clamp(
- 280.0,
- size.maxWidth * .45,
- )
+ ? 360.0.clamp(280.0, size.maxWidth * .45)
: size.maxWidth;
final besideComments = _commentsSelected && commentsBeside;
final outputWidth =
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index ff38372c2..7c156331a 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -446,7 +446,7 @@ const kSwarmShortcuts = [
AppShortcut(
action: ShortcutAction.newSwarm,
activator: SingleActivator(LogicalKeyboardKey.keyT, meta: true),
- label: 'New Swarm',
+ label: 'New Tab',
group: ShortcutGroup.navigate,
),
// ⌘⇧T is New Terminal, as it is in a terminal app. "Reopen last closed
@@ -489,7 +489,7 @@ const kSwarmShortcuts = [
AppShortcut(
action: ShortcutAction.closeSwarm,
activator: SingleActivator(LogicalKeyboardKey.keyW, meta: true),
- label: 'Close Swarm',
+ label: 'Close Tab',
group: ShortcutGroup.navigate,
),
AppShortcut(
@@ -499,7 +499,7 @@ const kSwarmShortcuts = [
meta: true,
shift: true,
),
- label: 'Rename Swarm',
+ label: 'Rename Tab',
group: ShortcutGroup.navigate,
),
AppShortcut(
diff --git a/desktop/lib/shortcuts/key_cap.dart b/desktop/lib/shortcuts/key_cap.dart
index 81485622d..ee88e25d9 100644
--- a/desktop/lib/shortcuts/key_cap.dart
+++ b/desktop/lib/shortcuts/key_cap.dart
@@ -1,5 +1,6 @@
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -57,7 +58,9 @@ class KeyCap extends StatelessWidget {
? Semantics(
label: label == '⇥' ? 'Tab' : 'Return',
child: Icon(
- label == '⇥' ? Icons.keyboard_tab : Icons.keyboard_return,
+ label == '⇥'
+ ? AppIcons.arrowRightToLine
+ : AppIcons.cornerDownLeft,
size: iconSize,
color: grid.AppPalette.textPrimary,
),
diff --git a/desktop/lib/shortcuts/keyboard_practice.dart b/desktop/lib/shortcuts/keyboard_practice.dart
index 42e6b7d2d..b0394df80 100644
--- a/desktop/lib/shortcuts/keyboard_practice.dart
+++ b/desktop/lib/shortcuts/keyboard_practice.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -11,6 +12,7 @@ import '../core/test_run.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/app_type.dart';
import '../widgets/box_chrome.dart';
+import '../widgets/desktop_chrome.dart';
import '../widgets/terminal_prompt.dart';
import 'app_keymap.dart';
import 'app_shortcuts.dart';
@@ -36,28 +38,28 @@ class KeyboardLesson {
.map((binding) => boxKeyLabel(describeKeyBinding(binding)))
.join(' / ');
String get result => switch (command) {
- 'swarm.new' => '[work] [new swarm]\nFind a harness, or create one',
- 'agent.open' || 'agent.add' =>
- '[harness 1] │ [harness 2]\nBoth harnesses share this swarm.',
- 'agent.new' => 'agent Claude Code\nmachine dev\nproject ~/work/payments\ntask (optional)\nCreate is selected. Up/Down + Enter edits an argument. Permissions and profiles are inside Agent.',
- 'pane.zoom' => '[harness 2 — full workspace]\nPress the same key to restore the other panes.',
+ 'swarm.new' => '[work] [new tab]\nFind a harness, or create one',
+ 'agent.open' ||
+ 'agent.add' => '[agent 1] │ [agent 2]\nBoth agents share this tab.',
+ 'agent.new' => 'Codex · This Mac · payments\nHarness anything (optional)\nNew harness is selected. Return starts with these settings; Tab reaches each control. Model, approvals, and Codex profile are below the message.',
+ 'pane.zoom' => '[agent 2 — full workspace]\nPress the same key to restore the other panes.',
'pane.close' =>
'[harness 1]\nThe second view closes. Its harness keeps running.',
'swarm.close' =>
'[previous swarm]\nThe view closes. Its harnesses keep running.',
- 'navigation.commands' => '>rename\nRename Harness\nRename Swarm',
+ 'navigation.commands' => '>rename\nRename Harness\nRename Tab',
'terminal.find' => 'find > timeout\n1/3 matches in this terminal’s output',
'picker.complete' => 'project ~/work/payments\nTab completes the current argument; Enter accepts it.',
'picker.complete_back' =>
'project ~/work/\nShift-Tab walks path candidates backward.',
'picker.cancel' => '> ready\nEscape steps back from a nested chooser, then returns to the terminal.',
'creation.agent' => 'agent Claude Code\nFilter the agents, then Enter to choose. Escape returns to the launch menu.',
- 'creation.project' => 'project on This Mac\nresearch website payments\nNew project / Open folder / Clone GitHub repository\nType to filter projects. Up/Down selects; Enter chooses; Escape goes back.',
+ 'creation.project' => 'repo on This Mac\nresearch website payments\nNew project / Open folder / Clone GitHub repository\nType to filter repos. Up/Down selects; Enter chooses; Escape goes back.',
'creation.project_new' => 'name payments processing\nCreate payments-processing\nThis Mac:~/harnesses/payments-processing',
- 'creation.project_existing' => 'folder ~/work/payments\nEnter a folder path, or press Enter to browse on the selected machine.',
- 'creation.project_repository' => 'repo https://github.com/openai/codex\nChoose the repository, then launch to clone it and start the harness.',
+ 'creation.project_existing' => 'Open folder\nChoose a folder on the selected machine. Cancelling returns to the Repo list.',
+ 'creation.project_repository' => 'repo https://github.com/openai/codex\nChoose the repository, then launch to clone it and start the agent.',
'creation.project_machine' => 'machine Office\nChoose where the project lives. Folders are scoped to that machine.',
- 'creation.project_browse' => 'Browse folders\nChoose a folder on the selected machine; cancelling returns to the folder prompt.',
+ 'creation.project_browse' => 'Browse folders\nChoose a folder on the selected machine; cancelling returns to the previous chooser.',
'creation.project_recent_1' ||
'creation.project_recent_2' ||
'creation.project_recent_3' ||
@@ -66,11 +68,11 @@ class KeyboardLesson {
'creation.project_recent_6' ||
'creation.project_recent_7' ||
'creation.project_recent_8' ||
- 'creation.project_recent_9' => 'Recent project selected\nThe launch summary now uses this folder on the selected machine.',
- 'creation.task' => 'task fix the tests\nEnter starts the harness with this first task. Escape keeps the draft.',
- 'creation.options' => 'options\nChange permissions or the Codex profile.',
- 'picker.more_options' =>
- 'more options\nPermissions · Codex profile · repository',
+ 'creation.project_recent_9' => 'Repo selected\nThe composer now uses this folder on the selected machine.',
+ 'creation.task' => 'Harness anything\nEnter starts the harness. Shift-Enter adds a line; Escape keeps the draft.',
+ 'creation.options' =>
+ 'Model\nChoose a model for this harness. For Terminal, choose a repo.',
+ 'picker.more_options' => 'New harness\nOpen the composer from search. In the composer, choose a model; Terminal opens the Repo list.',
'picker.toggle_preview' =>
'results │ preview\nToggle again to hide the preview.',
'agent.stop' => 'Stop Harness?\n> Cancel Stop\nStopping ends the running harness; its saved conversation is kept. Closing a pane only closes a view.',
@@ -511,241 +513,376 @@ class _KeyboardPracticeState extends State<KeyboardPractice> {
super.dispose();
}
+ InputDecoration _fieldDecoration(String hint, {bool search = false}) =>
+ InputDecoration(
+ hintText: hint,
+ hintStyle: DesktopChrome.control(color: DesktopChrome.muted),
+ prefixIcon: search
+ ? Icon(AppIcons.search, size: 18, color: DesktopChrome.muted)
+ : null,
+ filled: true,
+ fillColor: DesktopChrome.field,
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 10,
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ borderSide: BorderSide(
+ color: MediaQuery.highContrastOf(context)
+ ? DesktopChrome.muted
+ : DesktopChrome.rim,
+ width: 1.5,
+ ),
+ ),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ borderSide: BorderSide(color: DesktopChrome.accent, width: 1.5),
+ ),
+ );
+
@override
Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
TerminalFontScope.watch(context);
final lesson = _lesson;
final rows = filtered;
- final body = TerminalBox(
- child: Padding(
- padding: const EdgeInsets.all(18),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Wrap(
- alignment: WrapAlignment.spaceBetween,
- spacing: 16,
- runSpacing: 6,
- children: [
- Text('keyboard practice', style: boxMonoStyle()),
+ final completedCount = lessons.where((l) => _done.contains(l.id)).length;
+ final lessonCount = lessons.length;
+ final body = DesktopChrome(
+ child: DesktopDialogSurface(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ LayoutBuilder(
+ builder: (context, constraints) => Wrap(
+ alignment: WrapAlignment.spaceBetween,
+ spacing: 16,
+ runSpacing: 4,
+ children: [
+ Semantics(
+ header: true,
+ child: Text(
+ 'Keyboard practice',
+ style: DesktopChrome.heading(),
+ ),
+ ),
+ Semantics(
+ label:
+ '$completedCount of $lessonCount shortcuts practiced',
+ excludeSemantics: true,
+ child: Text(
+ constraints.maxWidth < 560 * appTextScaleOf(context)
+ ? '$completedCount of $lessonCount'
+ : '$completedCount/$lessonCount practiced',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (lesson == null) ...[
+ const SizedBox(height: 8),
Text(
- '${lessons.where((l) => _done.contains(l.id)).length}/${lessons.length} practiced',
- style: boxMonoStyle(color: kBoxFaint),
+ 'Try shortcuts in a scratch workspace. Your agents stay as they are.',
+ style: DesktopChrome.metadata(),
),
],
- ),
- const SizedBox(height: 8),
- Text(
- 'Practice only · your running harnesses stay untouched',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- const SizedBox(height: 18),
- if (lesson == null) ...[
- Row(
- children: [
- Text('practice > ', style: boxMonoStyle()),
- Expanded(
- child: TextField(
- key: const ValueKey('practice-filter'),
- controller: _filter,
- focusNode: _filterFocus,
- autofocus: true,
- style: boxMonoStyle(),
- decoration: const InputDecoration(
- hintText: 'Find a shortcut or a group',
- border: InputBorder.none,
- isDense: true,
- ),
- onChanged: (_) => setState(() => _cursor = 0),
- ),
+ const SizedBox(height: 16),
+ if (lesson == null) ...[
+ TextField(
+ key: const ValueKey('practice-filter'),
+ controller: _filter,
+ focusNode: _filterFocus,
+ autofocus: true,
+ style: DesktopChrome.control(),
+ decoration: _fieldDecoration(
+ 'Find a shortcut or a group',
+ search: true,
),
- ],
- ),
- const SizedBox(height: 10),
- Flexible(
- child: rows.isEmpty
- ? Text('No matching shortcuts.', style: boxMonoStyle())
- : ListView.builder(
- controller: _scroll,
- shrinkWrap: true,
- itemExtent: 54.0 * appTextScaleOf(context),
- itemCount: rows.length,
- itemBuilder: (context, i) {
- final row = rows[i];
- return InkWell(
- key: ValueKey(
- 'practice-${row.context.name}-${row.command}',
+ onChanged: (_) => setState(() => _cursor = 0),
+ ),
+ const SizedBox(height: 12),
+ Flexible(
+ child: rows.isEmpty
+ ? Padding(
+ padding: const EdgeInsets.symmetric(vertical: 16),
+ child: Text(
+ 'No matching shortcuts.',
+ style: DesktopChrome.text(
+ color: DesktopChrome.muted,
),
- onTap: () => _open(row),
- child: ColoredBox(
- color: i == _cursor.clamp(0, rows.length - 1)
- ? boxInk(.09)
- : Colors.transparent,
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 8,
- vertical: 5,
+ ),
+ )
+ : ListView.builder(
+ controller: _scroll,
+ shrinkWrap: true,
+ itemExtent: 54.0 * appTextScaleOf(context),
+ itemCount: rows.length,
+ itemBuilder: (context, i) {
+ final row = rows[i];
+ final selected =
+ i == _cursor.clamp(0, rows.length - 1);
+ final practiced = _done.contains(row.id);
+ return MergeSemantics(
+ child: Semantics(
+ key: ValueKey(
+ 'practice-${row.context.name}-${row.command}',
),
- child: Row(
- children: [
- Text(
- _done.contains(row.id) ? '[x] ' : '[ ] ',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- Expanded(
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- mainAxisAlignment:
- MainAxisAlignment.center,
- children: [
- Text(
- row.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(),
+ button: true,
+ selected: selected,
+ label:
+ '${row.label}, ${row.bindings.isEmpty ? 'command search' : row.keys}',
+ value: practiced
+ ? 'Practiced'
+ : 'Not practiced',
+ child: TextButton(
+ onPressed: () => _open(row),
+ style:
+ TextButton.styleFrom(
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 5,
+ ),
+ backgroundColor: selected
+ ? DesktopChrome.selection
+ : Colors.transparent,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
),
- Text(
- '${row.group} · ${row.bindings.isEmpty ? 'command search' : row.keys}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(
- color: kBoxFaint,
- ),
+ ),
+ tapTargetSize:
+ MaterialTapTargetSize.shrinkWrap,
+ splashFactory: NoSplash.splashFactory,
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color:
+ states.contains(
+ WidgetState.focused,
+ )
+ ? DesktopChrome.accent
+ : Colors.transparent,
),
- ],
+ ),
+ overlayColor:
+ WidgetStateProperty.resolveWith(
+ (states) => DesktopChrome
+ .foreground
+ .withValues(
+ alpha:
+ states.contains(
+ WidgetState.pressed,
+ )
+ ? .12
+ : states.contains(
+ WidgetState.hovered,
+ )
+ ? .05
+ : 0,
+ ),
+ ),
),
+ child: ExcludeSemantics(
+ child: Row(
+ children: [
+ Icon(
+ practiced
+ ? AppIcons.circleCheck
+ : AppIcons.circle,
+ size: 18,
+ color: practiced
+ ? DesktopChrome.accent
+ : DesktopChrome.muted,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ mainAxisAlignment:
+ MainAxisAlignment.center,
+ children: [
+ Text(
+ row.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ '${row.group} · ${row.bindings.isEmpty ? 'command search' : row.keys}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 8),
+ Icon(
+ AppIcons.chevronRight,
+ size: 18,
+ color: DesktopChrome.muted,
+ ),
+ ],
),
- if (i == _cursor)
- Text(
- '<',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ],
+ ),
),
),
- ),
- );
- },
- ),
- ),
- ] else
- Flexible(
- child: Scrollbar(
- controller: _detailScroll,
- thumbVisibility: true,
- child: SingleChildScrollView(
- controller: _detailScroll,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- '${lesson.group} / ${lesson.label}',
- style: boxMonoStyle(),
- ),
- const SizedBox(height: 16),
- Text(
- _matched
- ? '[x] ${lesson.label}'
- : lesson.bindings.isEmpty
- ? 'No shortcut assigned. Find it by name in command search.'
- : 'Press ${lesson.keys}',
- style: boxMonoStyle(),
+ );
+ },
),
- if (!_matched && lesson.bindings.length > 1)
- Padding(
- padding: const EdgeInsets.only(top: 6),
+ ),
+ ] else
+ Flexible(
+ child: Scrollbar(
+ controller: _detailScroll,
+ thumbVisibility: true,
+ child: SingleChildScrollView(
+ controller: _detailScroll,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(lesson.group, style: DesktopChrome.metadata()),
+ const SizedBox(height: 4),
+ Semantics(
+ header: true,
child: Text(
- 'Try any of these bindings.',
- style: boxMonoStyle(color: kBoxFaint),
+ lesson.label,
+ style: AppType.title(
+ color: DesktopChrome.foreground,
+ ),
),
),
- if (!_matched && lesson.bindings.isEmpty)
- TextField(
- key: const ValueKey('practice-command'),
- controller: _answer,
- focusNode: _answerFocus,
- style: boxMonoStyle(),
- decoration: InputDecoration(
- prefixText: ': ',
- hintText: lesson.label,
- border: InputBorder.none,
+ const SizedBox(height: 16),
+ if (_matched)
+ Row(
+ children: [
+ Icon(
+ AppIcons.circleCheck,
+ color: DesktopChrome.accent,
+ size: 20,
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ 'Shortcut practiced',
+ key: const ValueKey('practice-completed'),
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ ],
+ )
+ else
+ Text(
+ lesson.bindings.isEmpty
+ ? 'No shortcut assigned. Find it by name in command search.'
+ : 'Press ${lesson.keys}',
+ style: DesktopChrome.text(),
+ ),
+ if (!_matched && lesson.bindings.length > 1)
+ Padding(
+ padding: const EdgeInsets.only(top: 6),
+ child: Text(
+ 'Try any of these bindings.',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ if (!_matched && lesson.bindings.isEmpty)
+ Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: TextField(
+ key: const ValueKey('practice-command'),
+ controller: _answer,
+ focusNode: _answerFocus,
+ style: DesktopChrome.control(),
+ decoration: _fieldDecoration(lesson.label),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Container(
+ padding: const EdgeInsets.all(14),
+ // This is terminal content, with its existing mono
+ // type and scratch output, inside desktop chrome.
+ decoration: BoxDecoration(
+ color: grid.AppPalette.swarmField,
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Text(
+ _matched ? lesson.result : 'scratch workspace\n\n[agent 1] │ [agent 2]\n\n> ready',
+ key: const ValueKey('practice-preview'),
+ style: boxMonoStyle(),
),
),
- const SizedBox(height: 16),
- Container(
- padding: const EdgeInsets.all(14),
- // A recessed well: black sinks a dark field, but
- // at 26% it turns a light one into a grey slab.
- color: grid.AppTheme.pick(
- boxInk(.06),
- Colors.black26,
+ const SizedBox(height: 12),
+ Text(
+ 'A scratch workspace. Your agents stay as they are.',
+ style: DesktopChrome.metadata(),
),
- child: Text(
- _matched ? lesson.result : 'scratch workspace\n\n[harness 1] │ [harness 2]\n\n> ready',
- key: const ValueKey('practice-preview'),
- style: boxMonoStyle(),
+ const SizedBox(height: 4),
+ Text(
+ 'Page Up / Page Down to scroll',
+ style: DesktopChrome.metadata(),
),
- ),
- if (_feedback != null)
- Padding(
- padding: const EdgeInsets.only(top: 12),
- child: Text(
- _feedback!,
- style: boxMonoStyle(color: kBoxFaint),
+ if (_feedback != null)
+ Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: Text(
+ _feedback!,
+ style: DesktopChrome.metadata(),
+ ),
),
- ),
- if (_matched)
- Semantics(
- liveRegion: true,
- child: Text(
- 'Shortcut practiced. Enter continues.',
- style: boxMonoStyle(color: kBoxFaint),
+ if (_matched)
+ Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: Semantics(
+ liveRegion: true,
+ child: Text(
+ 'Shortcut practiced. Enter continues.',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
),
- ),
- ],
+ ],
+ ),
),
),
),
- ),
- const SizedBox(height: 12),
- Wrap(
- spacing: 16,
- runSpacing: 4,
- crossAxisAlignment: WrapCrossAlignment.center,
- children: [
- if (lesson == null)
- Text(
- '${_hint('picker.accept')} practice ${_hint('picker.previous')}/${_hint('picker.next')} choose',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- if (lesson != null)
- TextButton(
- onPressed: _next,
- child: Text(
- _matched ? 'Enter Next' : 'Skip',
- style: boxMonoStyle(),
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 16,
+ runSpacing: 8,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ if (lesson == null)
+ Text(
+ '${_hint('picker.accept')} Practice · ${_hint('picker.previous')}/${_hint('picker.next')} Browse',
+ style: DesktopChrome.metadata(),
),
+ if (lesson != null)
+ DesktopPill(
+ onPressed: _next,
+ label: _matched ? 'Next shortcut' : 'Skip',
+ ),
+ DesktopPill(
+ key: const ValueKey('practice-back'),
+ onPressed: _back,
+ label: lesson == null ? 'Close' : 'All shortcuts',
+ tooltip: lesson == null ? _hint('picker.cancel') : 'Esc',
+ quiet: true,
),
- if (lesson != null)
- Text(
- 'pgup/pgdn read',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- TextButton(
- key: const ValueKey('practice-back'),
- onPressed: _back,
- child: Text(
- lesson == null
- ? '${_hint('picker.cancel')} Close'
- : 'esc All shortcuts',
- style: boxMonoStyle(),
- ),
- ),
- ],
- ),
- ],
+ ],
+ ),
+ ],
+ ),
),
),
);
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 8eafd415c..2be824adb 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -113,7 +113,7 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'swarm.new',
- 'New Swarm',
+ 'New Tab',
ShortcutGroup.navigate,
action: ShortcutAction.newSwarm,
nativeAction: 'new',
@@ -121,7 +121,7 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'swarm.close',
- 'Close Swarm',
+ 'Close Tab',
ShortcutGroup.navigate,
action: ShortcutAction.closeSwarm,
nativeAction: 'closeActive',
@@ -158,7 +158,7 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'swarm.rename',
- 'Rename Swarm',
+ 'Rename Tab',
ShortcutGroup.actions,
action: ShortcutAction.renameSwarm,
nativeAction: 'renameActive',
@@ -738,7 +738,7 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'picker.add_here',
- 'Add the selected harness',
+ 'Start or add the selected harness',
ShortcutGroup.actions,
extraKeys: ['cmd+enter'],
context: KeymapContext.picker,
@@ -773,10 +773,10 @@ final harnessCommands = <HarnessCommand>[
// Launch and Project use arrows/Enter. Keep stable command identities for
// explicit user bindings without reserving plain letters in these prompts.
for (final (name, key, label) in [
- ('agent', null, 'Choose an agent or harness'),
- ('project', null, 'Choose the new harness’s project'),
- ('task', null, 'Edit the new harness’s first task'),
- ('options', null, 'Edit the new harness’s advanced options'),
+ ('agent', null, 'Choose the new agent'),
+ ('project', null, 'Choose the new agent’s project'),
+ ('task', null, 'Edit the new agent’s first message'),
+ ('options', null, 'Choose the new agent’s model'),
// Project is a text filter. Keep these command identities available for
// explicit user remaps, without taking ordinary letters from the editor.
('project_new', null, 'Name a new project'),
diff --git a/desktop/lib/shortcuts/keymap_settings.dart b/desktop/lib/shortcuts/keymap_settings.dart
index 0a8102afd..c74a8ed32 100644
--- a/desktop/lib/shortcuts/keymap_settings.dart
+++ b/desktop/lib/shortcuts/keymap_settings.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -72,7 +73,7 @@ class KeymapSettings extends StatelessWidget {
if (keymap?.store != null)
TextButton.icon(
onPressed: () => openKeyboardConfig(context),
- icon: const Icon(Icons.edit_outlined, size: 16),
+ icon: const Icon(AppIcons.pencil, size: 16),
label: const Text('Edit keyboard config'),
style: TextButton.styleFrom(
foregroundColor: grid.AppPalette.textPrimary,
diff --git a/desktop/lib/shortcuts/shortcuts_browser.dart b/desktop/lib/shortcuts/shortcuts_browser.dart
index b7bb93c4f..db5a719f2 100644
--- a/desktop/lib/shortcuts/shortcuts_browser.dart
+++ b/desktop/lib/shortcuts/shortcuts_browser.dart
@@ -1,11 +1,12 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../terminal/terminal_text.dart';
+import '../widgets/desktop_chrome.dart';
import 'app_keymap.dart';
import 'key_cap.dart';
import 'keymap_commands.dart';
@@ -132,10 +133,9 @@ class _ShortcutsBrowserState extends State<ShortcutsBrowser> {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- TerminalFontScope.watch(context);
final keymap = KeymapTheme.of(context) ?? _fallback;
return ListenableBuilder(
- listenable: Listenable.merge([keymap, terminalFontStore]),
+ listenable: keymap,
builder: (context, _) {
final query = _query.text.trim().toLowerCase();
final groups = <String, List<KeyboardLesson>>{};
@@ -166,198 +166,214 @@ class _ShortcutsBrowserState extends State<ShortcutsBrowser> {
}
_visible = [for (final name in names) ...groups[name]!];
if (_cursor >= _visible.length) _cursor = _visible.length - 1;
- final scale = terminalTextScaleOf(context);
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 12, 12, 12),
- child: Row(
- children: [
- if (widget.onClose != null)
- IconButton(
- onPressed: widget.onClose,
- tooltip: 'Close keyboard shortcuts',
- icon: Icon(Icons.arrow_back, size: 20 * scale),
- )
- else
- Padding(
- padding: const EdgeInsets.only(right: 12),
- child: Icon(
- Icons.search,
- size: 20 * scale,
- color: grid.AppPalette.textSecondary,
- ),
+ final scale = grid.appTextScaleOf(context);
+ return DesktopChrome(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 20, 24, 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Semantics(
+ header: true,
+ child: Text(
+ 'Keyboard shortcuts',
+ style: DesktopChrome.heading(),
+ ),
+ ),
+ ),
+ if (keymap.store != null)
+ IconButton(
+ tooltip: 'Edit keyboard shortcuts',
+ icon: const Icon(
+ AppIcons.slidersHorizontal,
+ size: 20,
+ ),
+ onPressed: () => openKeyboardConfig(context),
+ ),
+ if (widget.onClose != null)
+ IconButton(
+ onPressed: widget.onClose,
+ tooltip: 'Close keyboard shortcuts',
+ icon: const Icon(AppIcons.close, size: 20),
+ ),
+ ],
),
- Expanded(
- child: TextField(
+ const SizedBox(height: 12),
+ TextField(
key: const ValueKey('shortcuts-search'),
controller: _query,
focusNode: _input,
autofocus: widget.autofocus,
- style: terminalTextStyle(
- color: grid.AppPalette.textPrimary,
- ),
+ style: DesktopChrome.control(),
onChanged: _filterChanged,
decoration: InputDecoration(
- hintText: 'Search keyboard shortcuts…',
- hintStyle: terminalTextStyle(
- color: grid.AppPalette.textFaint,
+ hintText: 'Search actions or keys',
+ hintStyle: DesktopChrome.control(
+ color: DesktopChrome.muted,
+ ),
+ prefixIcon: Icon(
+ AppIcons.search,
+ size: 18 * scale,
+ color: DesktopChrome.muted,
+ ),
+ suffixIcon: _query.text.isEmpty
+ ? null
+ : IconButton(
+ tooltip: 'Clear search',
+ icon: const Icon(AppIcons.close, size: 18),
+ onPressed: () {
+ _query.clear();
+ _filterChanged('');
+ _input.requestFocus();
+ },
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ borderSide: BorderSide(
+ color: MediaQuery.highContrastOf(context)
+ ? DesktopChrome.muted
+ : DesktopChrome.rim,
+ width: 1.5,
+ ),
+ ),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ borderSide: BorderSide(
+ color: DesktopChrome.accent,
+ width: 1.5,
+ ),
),
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- filled: false,
+ fillColor: DesktopChrome.field,
+ filled: true,
isDense: true,
contentPadding: const EdgeInsets.symmetric(
- vertical: 12,
+ horizontal: 12,
+ vertical: 10,
),
),
),
- ),
- if (_query.text.isNotEmpty)
- IconButton(
- tooltip: 'Clear search',
- icon: Icon(Icons.close, size: 18 * scale),
- onPressed: () {
- _query.clear();
- _filterChanged('');
- _input.requestFocus();
- },
- ),
- if (keymap.store != null)
- IconButton(
- tooltip: 'Edit keyboard shortcuts',
- icon: Icon(Icons.tune, size: 20 * scale),
- onPressed: () => openKeyboardConfig(context),
- ),
- ],
- ),
- ),
- Divider(height: 1, color: grid.AppGlass.hair),
- if (keymap.error != null)
- Padding(
- padding: const EdgeInsets.all(16),
- child: Text(
- keymap.error!,
- style: terminalTextStyle(
- color: grid.AppPalette.textSecondary,
- ),
+ ],
),
),
- Expanded(
- child: _visible.isEmpty
- ? Center(
- child: Padding(
- padding: const EdgeInsets.all(24),
- child: Text(
- 'No shortcuts found. Try an action or a key.',
- style: terminalTextStyle(
- color: grid.AppPalette.textSecondary,
+ Divider(height: 1, color: grid.AppGlass.hair),
+ if (keymap.error != null)
+ Padding(
+ padding: const EdgeInsets.all(16),
+ child: Text(keymap.error!, style: DesktopChrome.metadata()),
+ ),
+ Expanded(
+ child: _visible.isEmpty
+ ? Center(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Text(
+ 'No shortcuts found. Try an action or a key.',
+ style: DesktopChrome.text(
+ color: DesktopChrome.muted,
+ ),
),
),
- ),
- )
- : LayoutBuilder(
- builder: (context, constraints) {
- final columns =
- constraints.maxWidth >= 760 * math.max(1, scale)
- ? 2
- : 1;
- return Scrollbar(
- controller: _scroll,
- child: ListView(
+ )
+ : LayoutBuilder(
+ builder: (context, constraints) {
+ final columns =
+ constraints.maxWidth >= 760 * math.max(1, scale)
+ ? 2
+ : 1;
+ return Scrollbar(
controller: _scroll,
- padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
- children: [
- for (final name in names) ...[
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 12,
- 20,
- 12,
- 10,
- ),
- child: Text(
- name == 'Essentials' ? 'General' : name,
- style: terminalTextStyle(
- color: grid.AppPalette.textSecondary,
- ),
- ),
- ),
- for (
- var row = 0;
- row < groups[name]!.length;
- row += columns
- )
+ child: ListView(
+ controller: _scroll,
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
+ children: [
+ for (final name in names) ...[
Padding(
- padding: EdgeInsets.only(
- bottom:
- row + columns < groups[name]!.length
- ? 4
- : 0,
+ padding: const EdgeInsets.fromLTRB(
+ 12,
+ 20,
+ 12,
+ 10,
),
- child: Row(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- for (
- var column = 0;
- column < columns;
- column++
- ) ...[
- if (column > 0)
- const SizedBox(width: 20),
- if (row + column >=
- groups[name]!.length)
- const Expanded(child: SizedBox())
- else
- Expanded(
- child: _lessonRow(
- groups[name]![row + column],
+ child: Text(
+ name == 'Essentials' ? 'General' : name,
+ style: DesktopChrome.control(
+ medium: true,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ),
+ for (
+ var row = 0;
+ row < groups[name]!.length;
+ row += columns
+ )
+ Padding(
+ padding: EdgeInsets.only(
+ bottom:
+ row + columns < groups[name]!.length
+ ? 4
+ : 0,
+ ),
+ child: Row(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ children: [
+ for (
+ var column = 0;
+ column < columns;
+ column++
+ ) ...[
+ if (column > 0)
+ const SizedBox(width: 20),
+ if (row + column >=
+ groups[name]!.length)
+ const Expanded(child: SizedBox())
+ else
+ Expanded(
+ child: _lessonRow(
+ groups[name]![row + column],
+ ),
),
- ),
+ ],
],
- ],
+ ),
),
- ),
+ ],
],
- ],
- ),
- );
- },
- ),
- ),
- Divider(height: 1, color: grid.AppGlass.hair),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
- child: Wrap(
- spacing: 24,
- runSpacing: 8,
- children: [
- Text(
- '↑↓ select',
- style: terminalTextStyle(
- color: grid.AppPalette.textSecondary,
- ),
- ),
- Text(
- '↵ practice',
- style: terminalTextStyle(
- color: grid.AppPalette.textSecondary,
- ),
- ),
- if (widget.onClose != null)
- Text(
- 'esc close',
- style: terminalTextStyle(
- color: grid.AppPalette.textSecondary,
+ ),
+ );
+ },
),
- ),
- ],
),
- ),
- ],
+ Divider(height: 1, color: grid.AppGlass.hair),
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 24,
+ vertical: 12,
+ ),
+ child: Wrap(
+ spacing: 24,
+ runSpacing: 8,
+ children: [
+ Text('↑↓ Browse', style: DesktopChrome.metadata()),
+ Text('Return Practice', style: DesktopChrome.metadata()),
+ if (widget.onClose != null)
+ Text('Esc Close', style: DesktopChrome.metadata()),
+ ],
+ ),
+ ),
+ ],
+ ),
);
},
);
@@ -383,30 +399,61 @@ class _ShortcutBrowserRow extends StatelessWidget {
? describeKeyStrokeKeys(binding.keys.single)
: [describeKeyBinding(binding)],
];
- return Semantics(
- button: true,
- selected: selected,
- label: '${lesson.label}, ${lesson.keys}. Practice shortcut',
- child: Material(
- animationDuration: Duration.zero,
- color: selected ? grid.AppSurface.selectedFill : Colors.transparent,
- borderRadius: BorderRadius.circular(6),
- child: InkWell(
- onTap: onTap,
- borderRadius: BorderRadius.circular(6),
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ return MergeSemantics(
+ child: Semantics(
+ button: true,
+ selected: selected,
+ label: '${lesson.label}, ${lesson.keys}. Practice shortcut',
+ child: TextButton(
+ onPressed: onTap,
+ style:
+ TextButton.styleFrom(
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 10,
+ ),
+ backgroundColor: selected
+ ? DesktopChrome.selection
+ : Colors.transparent,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ ),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ splashFactory: NoSplash.splashFactory,
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? DesktopChrome.accent
+ : Colors.transparent,
+ ),
+ ),
+ overlayColor: WidgetStateProperty.resolveWith(
+ (states) => DesktopChrome.foreground.withValues(
+ alpha: states.contains(WidgetState.pressed)
+ ? .12
+ : states.contains(WidgetState.hovered)
+ ? .05
+ : 0,
+ ),
+ ),
+ ),
+ child: ExcludeSemantics(
child: LayoutBuilder(
builder: (context, constraints) {
final keys = KeyChordView(
chords: chords,
- textStyle: terminalTextStyle(),
+ textStyle: DesktopChrome.control(),
);
final label = Text(
lesson.label,
- style: terminalTextStyle(color: grid.AppPalette.textPrimary),
+ style: DesktopChrome.control(),
);
- if (constraints.maxWidth < 330 * terminalTextScaleOf(context)) {
+ if (constraints.maxWidth < 330 * grid.appTextScaleOf(context)) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [label, const SizedBox(height: 8), keys],
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 75a3710b2..e1891dc20 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2729,7 +2729,10 @@ class AppNotifier extends ChangeNotifier {
final machineId = localMachineState?.machine.machineId;
final connection = machineId == null ? null : _pool?[machineId];
if (connection == null) return;
- final pending = connection.sendTerminalFrame('dial_settings', {'id': id, ...patch});
+ final pending = connection.sendTerminalFrame('dial_settings', {
+ 'id': id,
+ ...patch,
+ });
unawaited(pending.catchError((_) => false));
}
@@ -7593,8 +7596,11 @@ class AppNotifier extends ChangeNotifier {
systemNotifications.withdraw(machineId, agentId);
agentAlerts.dismiss(
AgentAlert(
- machineId: machineId, agentId: agentId,
- title: '', kind: AlertKind.done, at: DateTime.now(),
+ machineId: machineId,
+ agentId: agentId,
+ title: '',
+ kind: AlertKind.done,
+ at: DateTime.now(),
),
);
_announceAgentSeen(machineId, agentId, readToken);
@@ -7602,7 +7608,11 @@ class AppNotifier extends ChangeNotifier {
/// Reading is not answering. A device receipt clears only the exact message
/// it displayed; the pending question and all pane/focus state remain intact.
- void readAgentNotification(String machineId, String agentId, {String? readToken}) {
+ void readAgentNotification(
+ String machineId,
+ String agentId, {
+ String? readToken,
+ }) {
if (readToken != null &&
agentUnread.readTokenFor(machineId, agentId) != readToken) {
return;
@@ -7614,7 +7624,9 @@ class AppNotifier extends ChangeNotifier {
..remove(key)
..[key] = question.requestId;
while (_readQuestionNotifications.length > AgentUnread.capacity) {
- _readQuestionNotifications.remove(_readQuestionNotifications.keys.first);
+ _readQuestionNotifications.remove(
+ _readQuestionNotifications.keys.first,
+ );
}
}
_forgetUnread(machineId, agentId);
@@ -7649,7 +7661,8 @@ class AppNotifier extends ChangeNotifier {
unawaited(
_conn(machineId)
.sendTerminalFrame('agent_seen', {
- 'agentId': agentId, 'readToken': ?readToken,
+ 'agentId': agentId,
+ 'readToken': ?readToken,
})
.catchError((_) => false),
);
@@ -10043,7 +10056,7 @@ class AppNotifier extends ChangeNotifier {
'Fork created. Its original swarm closed; use New Pane to open it.';
} else if (target.panes.length >= maxPanes && !keepFocus) {
notice =
- 'Fork created. Its original swarm is full; use New Swarm to open it.';
+ 'Fork created. Its original swarm is full; use New Tab to open it.';
} else {
if (target.panes.length >= maxPanes) {
newSwarm(name: fork.name);
@@ -13105,8 +13118,10 @@ class AppNotifier extends ChangeNotifier {
final readId = payload['agentId'];
final readMachine = payload['machineId'];
final readToken = payload['readToken'];
- if (readId is String && readMachine is String &&
- readToken is String && readToken.isNotEmpty) {
+ if (readId is String &&
+ readMachine is String &&
+ readToken is String &&
+ readToken.isNotEmpty) {
readAgentNotification(readMachine, readId, readToken: readToken);
}
break;
@@ -13223,7 +13238,9 @@ class AppNotifier extends ChangeNotifier {
final goneId = _eventAgentId(machine, event, payload);
if (goneId != null) {
agentUnread.forget(machineId, goneId);
- _readQuestionNotifications.remove(AgentUnread.keyFor(machineId, goneId));
+ _readQuestionNotifications.remove(
+ AgentUnread.keyFor(machineId, goneId),
+ );
}
final agentId = _eventAgentId(machine, event, payload);
if (agentId != null) {
@@ -13270,7 +13287,9 @@ class AppNotifier extends ChangeNotifier {
// reconnect and when attaching to a turn that was already mid-dialog, and a window
// that beeped at those would sound an alarm every time the network hiccuped.
if (!repeat && !questionNotificationRead(machineId, agentId)) {
- _readQuestionNotifications.remove(AgentUnread.keyFor(machineId, agentId));
+ _readQuestionNotifications.remove(
+ AgentUnread.keyFor(machineId, agentId),
+ );
_raiseAlert(machine, agentId, AlertKind.needsYou);
}
}
@@ -13286,7 +13305,9 @@ class AppNotifier extends ChangeNotifier {
final open = machine.blockedAgents[agentId];
if (open != null && open.requestId == requestId) {
machine.blockedAgents.remove(agentId);
- _readQuestionNotifications.remove(AgentUnread.keyFor(machineId, agentId));
+ _readQuestionNotifications.remove(
+ AgentUnread.keyFor(machineId, agentId),
+ );
// An old question close cannot erase a newer completed result.
if (agentUnread.kindFor(machineId, agentId) == AlertKind.needsYou) {
_forgetUnread(machineId, agentId);
diff --git a/desktop/lib/state/harness_placement.dart b/desktop/lib/state/harness_placement.dart
index 5772428e6..71cf121a3 100644
--- a/desktop/lib/state/harness_placement.dart
+++ b/desktop/lib/state/harness_placement.dart
@@ -4,7 +4,7 @@ enum HarnessPlacement {
currentTab,
newTab;
- String get title => this == newTab ? 'New Swarm' : 'New Pane';
+ String get title => this == newTab ? 'New Tab' : 'New Pane';
String get action =>
this == newTab ? 'Open in new swarm' : 'Add to this swarm';
String get createAction =>
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 997ceb471..65ceaa022 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -434,6 +434,7 @@ class NewHarnessController extends ChangeNotifier {
: harnessId != null && engine != null && !isHarnessId(engine)
? engine
: _initialEngine(isHarnessId(engine) ? null : engine);
+ _restorePermissionMode();
_model = isTerminal ? null : draft?.model;
_modelUsage = modelUsage;
_ownsModelUsage = modelUsage == null;
@@ -457,6 +458,7 @@ class NewHarnessController extends ChangeNotifier {
_project = draft.project;
this.task = draft.task;
_mode = draft.permissionMode;
+ _chosenModes[_engine] = _mode;
_profile = draft.profile;
_profileChosen = draft.profileChosen;
_attempt = draft.attempt;
@@ -495,12 +497,13 @@ class NewHarnessController extends ChangeNotifier {
} else if (!_selectionTouched && draft == null && isHarnessId(engine)) {
_engine = _initialEngine(null);
}
+ _restorePermissionMode();
_refresh();
}),
);
unawaited(
app.projectHistory.load().then((_) {
- if (!_disposed && !listEquals(_seen, _signature())) _refresh();
+ if (!_disposed && !locked) _refresh();
}),
);
// What the machine has is asked when the box opens, as the form does: an
@@ -522,6 +525,7 @@ class NewHarnessController extends ChangeNotifier {
return;
}
_engine = _initialEngine(null);
+ _restorePermissionMode();
_refresh();
}),
);
@@ -635,16 +639,30 @@ class NewHarnessController extends ChangeNotifier {
bool get isGitProject => _gitProject.isGit && !isTerminal;
bool get canUseWorktree => isGitProject && !checkingGit;
bool get worktree =>
- isGitProject && (_worktree ?? worktreeByDefault(_gitProject));
+ isGitProject &&
+ (_worktree ??
+ app.projectHistory.worktreeFor(_machineId, _project.folder ?? '') ??
+ worktreeByDefault(_gitProject));
+
+ /// Fresh desktop work starts on main, with or without a worktree. A retry
+ /// must instead keep the branch of the folder its first attempt prepared.
+ bool get _defaultsToMain =>
+ _desktopChoices && _attempt?.preparedFolder == null;
+ String? get branchRef {
+ if (_branchRef != null) return _branchRef;
+ if (_defaultsToMain) {
+ final main = defaultBranchRef(_gitProject, worktree: true);
+ return !worktree && main?.startsWith('refs/remotes/') == true
+ ? null
+ : main;
+ }
+ return defaultBranchRef(_gitProject, worktree: worktree);
+ }
- /// With Worktree on, what a new branch starts from; off, the branch the
- /// folder is on. Unchosen, the default for the mode.
- String? get branchRef =>
- _branchRef ?? defaultBranchRef(_gitProject, worktree: worktree);
String? get gitError => _gitProject.error;
String get branchLabel =>
_refName(branchRef) ??
- (worktree ? 'main · unavailable' : 'Detached HEAD');
+ (worktree || _defaultsToMain ? 'main · unavailable' : 'Detached HEAD');
String? _refName(String? ref) =>
_gitProject.branches
.where((branch) => branch.ref == ref)
@@ -706,6 +724,11 @@ class NewHarnessController extends ChangeNotifier {
void toggleWorktree() {
if (locked || !canUseWorktree) return;
_worktree = !worktree;
+ if (_project.folder case final folder?) {
+ unawaited(
+ app.projectHistory.selectWorktree(_machineId, folder, _worktree!),
+ );
+ }
error = null;
_refresh();
}
@@ -824,7 +847,10 @@ class NewHarnessController extends ChangeNotifier {
// With Worktree off its branch stays chosen and Start reopens that
// worktree; otherwise new work starts from the repository's own branch.
if (info.mainFolder case final main? when _project.folder == key.$2) {
- if (_worktree == false && _branchRef == null && info.branch != null) {
+ if (!_defaultsToMain &&
+ _worktree == false &&
+ _branchRef == null &&
+ info.branch != null) {
_branchRef = 'refs/heads/${info.branch}';
}
_project = NewHarnessProject.folder(main);
@@ -1010,7 +1036,7 @@ class NewHarnessController extends ChangeNotifier {
project: _project,
task: task,
permissionMode: _mode,
- worktree: _worktree,
+ worktree: isGitProject ? worktree : _worktree,
branchRef: _branchRef,
branchName: _branchName,
placeholder: isGitProject ? placeholder : _placeholder,
@@ -1033,7 +1059,7 @@ class NewHarnessController extends ChangeNotifier {
_project.folder!,
_gitProject,
worktree: worktree,
- branchRef: _branchRef,
+ branchRef: branchRef,
branchName: _branchName,
placeholder: placeholder,
)
@@ -1052,8 +1078,26 @@ class NewHarnessController extends ChangeNotifier {
/// starts it with nothing sent. Kept while the other answers are changed.
String task = '';
+ /// The desktop composer edits the first message independently of whichever
+ /// configuration chooser is open. It never repurposes that chooser's query.
+ void setTask(String value) {
+ if (locked || task == value) return;
+ task = value;
+ error = taskTooLong
+ ? 'A first message can be $kFirstTaskMaxLength characters; '
+ 'this is ${value.trim().length}.'
+ : null;
+ notifyListeners();
+ }
+
/// The permission mode picked, by id; an engine without it uses its default.
String _mode = kDefaultPermissionMode;
+ final _chosenModes = <String, String>{};
+ String _permissionFor(String engine) =>
+ _chosenModes[engine] ??
+ app.agentPreference.permissionModeFor(_baseOf(engine)) ??
+ kDefaultPermissionMode;
+ void _restorePermissionMode() => _mode = _permissionFor(_engine);
/// The engine a choice launches: a store harness runs ON one of them.
String _baseOf(String engine) => isHarnessId(engine)
@@ -1071,8 +1115,9 @@ class NewHarnessController extends ChangeNotifier {
_settingsEngine == _engine ? _profile : null;
List<PermissionMode> get _settingsModes =>
permissionModesOf(_baseOf(_settingsEngine));
- String get _settingsMode => _settingsModes.any((mode) => mode.id == _mode)
- ? _mode
+ String get _settingsMode =>
+ _settingsModes.any((mode) => mode.id == _permissionFor(_settingsEngine))
+ ? _permissionFor(_settingsEngine)
: kDefaultPermissionMode;
bool get takesTask => takesFirstTask(_base);
bool get taskTooLong => task.trim().length > kFirstTaskMaxLength;
@@ -1097,7 +1142,7 @@ class NewHarnessController extends ChangeNotifier {
List<NewHarnessOption> agentSettingsFor(String engine) {
final modes = permissionModesOf(_baseOf(engine));
final mode =
- modes.where((mode) => mode.id == _mode).firstOrNull ??
+ modes.where((mode) => mode.id == _permissionFor(engine)).firstOrNull ??
modes.where((mode) => mode.id == kDefaultPermissionMode).firstOrNull;
return [
if (mode != null)
@@ -1231,7 +1276,10 @@ class NewHarnessController extends ChangeNotifier {
message: 'This project is unavailable. Choose a project.',
);
}
- if (!checkingGit && isGitProject && worktree && branchRef == null) {
+ if (!checkingGit &&
+ isGitProject &&
+ (worktree || _defaultsToMain && _gitProject.branches.isNotEmpty) &&
+ branchRef == null) {
return (
field: _gitProject.branches.isEmpty
? NewHarnessField.projectMenu
@@ -1619,13 +1667,24 @@ class NewHarnessController extends ChangeNotifier {
detail: machineLabel,
);
+ bool _desktopChoices = false;
+
+ /// Desktop menus scope folders to the selected machine and keep coding
+ /// agents ahead of recent and featured specialized harnesses.
+ void useDesktopChoices(bool desktop) {
+ if (_desktopChoices == desktop) return;
+ _desktopChoices = desktop;
+ _refresh(resetCursor: true);
+ }
+
List<NewHarnessOption> _projectMenu() => [
- const NewHarnessOption(
- id: repositoryId,
- synthetic: true,
- title: 'Clone Repository',
- detail: 'Paste a GitHub repository URL',
- ),
+ if (!_desktopChoices)
+ const NewHarnessOption(
+ id: repositoryId,
+ synthetic: true,
+ title: 'Clone Repository',
+ detail: 'Paste a GitHub repository URL',
+ ),
const NewHarnessOption(
id: existingProjectId,
synthetic: true,
@@ -1638,6 +1697,13 @@ class NewHarnessController extends ChangeNotifier {
title: 'New Folder',
detail: 'Name a new folder',
),
+ if (_desktopChoices)
+ const NewHarnessOption(
+ id: repositoryId,
+ synthetic: true,
+ title: 'GitHub',
+ detail: 'Clone a GitHub repository',
+ ),
..._ranked(_recentProjects()),
];
@@ -1729,6 +1795,25 @@ class NewHarnessController extends ChangeNotifier {
query = field == NewHarnessField.task ? task : '';
error = null;
_refresh(resetCursor: true);
+ _rememberProjectSelection();
+ }
+
+ void _rememberProjectSelection() {
+ if (!_desktopChoices || _project.folder == null) return;
+ final machine = _machineId;
+ final revision = _gitRevision;
+ // Git discovery normalizes a chosen worktree back to its repository.
+ // Do not persist the temporary checkout or an obsolete async selection.
+ unawaited(() async {
+ await _gitFuture;
+ if (_disposed || machine != _machineId || revision != _gitRevision) {
+ return;
+ }
+ final folder = _project.folder;
+ if (folder != null && gitError != 'PROJECT_UNAVAILABLE') {
+ await app.projectHistory.select(machine, folder);
+ }
+ }());
}
/// ⌘↵: make it now — WITH the row under the highlight. Creating with the
@@ -1808,9 +1893,15 @@ class NewHarnessController extends ChangeNotifier {
case NewHarnessField.projectRepository:
if (option.machineId case final id?) _selectMachine(id);
_project = option.project ?? _project;
+ if (_desktopChoices) {
+ _syncGitProject();
+ _rememberProjectSelection();
+ }
case NewHarnessField.mode:
_selectEngine(_settingsEngine);
_mode = option.id;
+ _chosenModes[_engine] = _mode;
+ unawaited(app.agentPreference.selectPermissionMode(_base, _mode));
case NewHarnessField.profile:
_selectEngine(_settingsEngine);
_profile = option.profile;
@@ -1819,6 +1910,12 @@ class NewHarnessController extends ChangeNotifier {
case NewHarnessField.launch:
break;
}
+ if (_desktopChoices &&
+ (field == NewHarnessField.harness || field == NewHarnessField.agent)) {
+ unawaited(
+ app.agentPreference.selectLaunch(_engine, harnessId: _harnessId),
+ );
+ }
}
void _selectEngine(String engine) {
@@ -1831,6 +1928,7 @@ class NewHarnessController extends ChangeNotifier {
_resetProfiles();
}
_engine = engine;
+ if (changed) _restorePermissionMode();
if (isTerminal) _model = null;
if (changed &&
_harnessId == null &&
@@ -2283,6 +2381,8 @@ class NewHarnessController extends ChangeNotifier {
null,
...app.agentPreference.recentHarnesses,
null,
+ ...app.agentPreference.recentChoices,
+ null,
// An install narrates through pushes that change no catalog row.
if (installRun case final run?) ...[
run.phase,
@@ -2383,12 +2483,15 @@ class NewHarnessController extends ChangeNotifier {
: options.indexWhere(
(option) => !option.synthetic && option.title == _cycle!.name,
);
+ final firstProject = options.indexWhere((option) => !option.synthetic);
cursor = cycling >= 0
? cycling
: kept >= 0
? kept
: field == NewHarnessField.projectMenu
- ? (options.length > 3 ? 3 : 1)
+ ? (firstProject >= 0
+ ? firstProject
+ : options.indexWhere((option) => option.id == existingProjectId))
: query.isEmpty && now >= 0
? now
: field == NewHarnessField.profile
@@ -2613,6 +2716,49 @@ class NewHarnessController extends ChangeNotifier {
if (machine?.dsh[id]?.installed == false) 'installs first',
].whereType<String>().where((part) => part.isNotEmpty).join(' · '),
);
+ if (_desktopChoices) {
+ final engines = {for (final engine in allEngines) engine.id};
+ return _ranked([
+ for (final id in <String>{
+ for (final id in [
+ // Keep coding agents together in a stable, familiar-first order.
+ // Recency can reorder specialized harnesses, never this group.
+ 'claude',
+ 'codex',
+ 'cursor',
+ 'copilot',
+ 'grok',
+ 'opencode',
+ 'agy',
+ 'amp',
+ 'kilo',
+ 'devin',
+ 'pi',
+ 'hermes',
+ 'commandcode',
+ 'muse',
+ ...engines,
+ ...app.agentPreference.recentChoices.where(isHarnessId),
+ 'autonomous/blender',
+ 'autonomous/circuitjs',
+ 'autonomous/godogen',
+ 'autonomous/mujoco',
+ 'autonomous/rdkit',
+ 'autonomous/strudel',
+ 'autonomous/typst',
+ ...harnesses,
+ kTerminalEngine,
+ ])
+ if (isHarnessId(id)
+ ? _offered(id)
+ : engines.contains(id) || id == kTerminalEngine)
+ isHarnessId(id) ? operationId(id) : id,
+ })
+ isHarnessId(id)
+ ? row(id)
+ : NewHarnessOption(id: id, title: labelOf(id), engine: id),
+ ]);
+ }
return _ranked([
for (final id in recents) row(id),
for (final id in <String>{
@@ -2648,7 +2794,11 @@ class NewHarnessController extends ChangeNotifier {
// local one is the choice most launches want, and an unusable machine in
// the middle of the usable ones made the list read as a jumble. Within
// each group the inventory's own order holds.
- List<NewHarnessOption> _machineOptions() => _ranked([
+ List<NewHarnessOption> _machineOptions() => _ranked(machineChoices);
+
+ /// Unfiltered choices for the Repo menu's separate machine picker. The
+ /// folder search must never filter the machine inventory.
+ List<NewHarnessOption> get machineChoices => [
for (final machine in [
...app.machineStates.values.where((m) => m.isLocalMachine),
...app.machineStates.values.where(
@@ -2679,7 +2829,7 @@ class NewHarnessController extends ChangeNotifier {
'computer yet. Link it from the Machines menu.'
: '${machine.machine.displayName} is offline.',
),
- ]);
+ ];
/// Whether what is typed in the project field is a path being completed.
bool get isPathQuery => field == NewHarnessField.project && _isPath(query);
@@ -2754,6 +2904,7 @@ class NewHarnessController extends ChangeNotifier {
...app.machineStates.values.where((m) => !m.isLocalMachine),
].where((m) => !m.machine.isShared)) {
final id = machine.machine.machineId;
+ if (_desktopChoices && id != _machineId) continue;
final folders = _recentProjectFolders(id).toList();
final names = <String, int>{};
for (final folder in folders) {
@@ -3055,18 +3206,20 @@ class NewHarnessController extends ChangeNotifier {
/// A second explicit dismissal acknowledges an unresolved creation.
bool requestDismiss() {
if (linkingProfile) {
- warn('Linking the profile. Escape closes once it is done.');
+ warn('Linking the profile. You can close once it is done.');
return false;
}
if (busy) {
- warn('Still working on it. Escape closes once it is done.');
+ warn('Still working on it. You can close once it is done.');
return false;
}
if (checking && !_warnedAboutClosing) {
_warnedAboutClosing = true;
warn(
- 'The harness may already exist. Return checks on it; Escape again '
- 'closes without knowing.',
+ _desktopChoices
+ ? 'The harness may already exist. Check status to find it, or click Close again to leave this form.'
+ : 'The harness may already exist. Return checks on it; Escape again '
+ 'closes without knowing.',
);
return false;
}
diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dart
index 69a9e2ef6..dab4b15a7 100644
--- a/desktop/lib/state/swarm.dart
+++ b/desktop/lib/state/swarm.dart
@@ -44,7 +44,7 @@ class Swarm {
static const storeName = 'Harness Store';
static const companionsName = 'Companions';
- static const defaultName = 'New Swarm';
+ static const defaultName = 'New Tab';
// 'New Harness' was the default until 2026-09-15, 'New Agent' for a day
// after, and 'Untitled Tab' until 2026-09-24; a layout saved then still
// carries one, and it must read as the same fresh swarm. Explicit custom
@@ -52,6 +52,7 @@ class Swarm {
static String normalizeName(String name) =>
const {
'New swarm',
+ 'New Swarm',
'New tab',
'New Tab',
'New Harness',
diff --git a/desktop/lib/state/welcome_sessions.dart b/desktop/lib/state/welcome_sessions.dart
index 0f2dc0f89..e9e6cb2ae 100644
--- a/desktop/lib/state/welcome_sessions.dart
+++ b/desktop/lib/state/welcome_sessions.dart
@@ -19,7 +19,7 @@ class WelcomeSessions extends ChangeNotifier {
WelcomeSessions(
this.app, {
this.projects = const [],
- this.limit = 9,
+ this.limit = 6,
this.window = const Duration(days: 30),
DateTime Function()? now,
}) : _now = now ?? DateTime.now;
diff --git a/desktop/lib/state/workspace_status.dart b/desktop/lib/state/workspace_status.dart
index 6ccc2d5a8..7d0535777 100644
--- a/desktop/lib/state/workspace_status.dart
+++ b/desktop/lib/state/workspace_status.dart
@@ -108,7 +108,7 @@ Map<String, String> workspaceTabNames(AppNotifier app) {
: tab.isOrchestrator
? 'orchestrator'
: candidates[tab.id]!.isEmpty
- ? 'new'
+ ? Swarm.defaultName
: candidates[tab.id]!.reduce((a, b) {
if (b.count != a.count) return b.count > a.count ? b : a;
return repetitions(b) < repetitions(a) ? b : a;
diff --git a/desktop/lib/store/store_category.dart b/desktop/lib/store/store_category.dart
index bc6d798ed..bce1e8ecf 100644
--- a/desktop/lib/store/store_category.dart
+++ b/desktop/lib/store/store_category.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/terminal/terminal_text.dart';
import '../core/dsh_catalog.dart';
@@ -205,7 +205,7 @@ class _StoreCategoryState extends State<StoreCategory> {
ActionChip(
key: ValueKey('store-related:$category'),
avatar: Icon(
- LucideIcons.arrowUpRight300,
+ AppIcons.arrowUpRight,
size: 14,
color: grid.AppPalette.textSecondary,
),
@@ -265,9 +265,8 @@ class _DisciplineHero extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
- 'GET STARTED',
- style: grid.AppType.monoMeta(
- letterSpacing: 1.2,
+ 'Get started',
+ style: grid.AppType.caption(
fontWeight: grid.AppFont.medium,
color: grid.AppPalette.accentOnSurface,
),
@@ -303,7 +302,7 @@ class _DisciplineHero extends StatelessWidget {
),
),
Icon(
- LucideIcons.arrowRight300,
+ AppIcons.arrowRight,
size: 16,
color: grid.AppPalette.textSecondary,
),
diff --git a/desktop/lib/store/store_demo_dialog.dart b/desktop/lib/store/store_demo_dialog.dart
index 3326baf4a..e2037a8ad 100644
--- a/desktop/lib/store/store_demo_dialog.dart
+++ b/desktop/lib/store/store_demo_dialog.dart
@@ -1,13 +1,14 @@
import 'dart:convert';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
import '../core/dsh_catalog.dart';
import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
import '../terminal/terminal_text.dart';
Future<void> showStoreDemo(
@@ -16,7 +17,7 @@ Future<void> showStoreDemo(
required StoreExample example,
}) async {
if (example.video == null) return;
- await showDialog<void>(
+ await showAppDialog<void>(
context: context,
builder: (_) => StoreDemoDialog(
name: entry.name,
@@ -199,7 +200,7 @@ class _StoreDemoDialogState extends State<StoreDemoDialog>
key: const ValueKey('store-demo-close'),
tooltip: 'Close recording',
onPressed: () => Navigator.of(context).pop(),
- icon: const Icon(LucideIcons.x300),
+ icon: const Icon(AppIcons.close),
),
],
),
@@ -215,7 +216,7 @@ class _StoreDemoDialogState extends State<StoreDemoDialog>
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
- LucideIcons.film300,
+ AppIcons.film,
size: 36,
color: Colors.white70,
),
@@ -268,7 +269,7 @@ class _StoreDemoDialogState extends State<StoreDemoDialog>
TextButton.icon(
key: const ValueKey('store-demo-browser'),
onPressed: _openingBrowser ? null : _openBrowser,
- icon: const Icon(LucideIcons.externalLink300, size: 16),
+ icon: const Icon(AppIcons.externalLink, size: 16),
label: const Text('Open in browser'),
),
],
diff --git a/desktop/lib/store/store_discover.dart b/desktop/lib/store/store_discover.dart
index 9236b1174..10a28bbc4 100644
--- a/desktop/lib/store/store_discover.dart
+++ b/desktop/lib/store/store_discover.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/terminal/terminal_text.dart';
import '../core/dsh_catalog.dart';
@@ -300,9 +300,8 @@ class _FeaturedStory extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
- category.toUpperCase(),
- style: grid.AppType.monoMeta(
- letterSpacing: 1.1,
+ category,
+ style: grid.AppType.caption(
fontWeight: grid.AppFont.medium,
color: grid.AppPalette.accentOnSurface,
),
@@ -333,7 +332,7 @@ class _FeaturedStory extends StatelessWidget {
),
),
Icon(
- LucideIcons.arrowRight300,
+ AppIcons.arrowRight,
size: 15,
color: grid.AppPalette.textSecondary,
),
@@ -403,7 +402,7 @@ class _DisciplineLink extends StatelessWidget {
),
const SizedBox(width: 8),
Icon(
- LucideIcons.chevronRight300,
+ AppIcons.chevronRight,
size: 16,
color: grid.AppPalette.textSecondary,
),
diff --git a/desktop/lib/store/store_explore_widgets.dart b/desktop/lib/store/store_explore_widgets.dart
index 3c7f6997a..ff4bd3ca1 100644
--- a/desktop/lib/store/store_explore_widgets.dart
+++ b/desktop/lib/store/store_explore_widgets.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';
import '../core/dsh_catalog.dart';
@@ -220,7 +220,7 @@ class _CoverCredit extends StatelessWidget {
button: true,
child: const Padding(
padding: EdgeInsets.all(9),
- child: Icon(LucideIcons.info300, size: 14, color: Colors.white),
+ child: Icon(AppIcons.info, size: 14, color: Colors.white),
),
),
),
diff --git a/desktop/lib/store/store_harness_actions.dart b/desktop/lib/store/store_harness_actions.dart
index 0d78f62e8..15725a92c 100644
--- a/desktop/lib/store/store_harness_actions.dart
+++ b/desktop/lib/store/store_harness_actions.dart
@@ -1,9 +1,9 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../core/models.dart';
import '../core/harness_catalog.dart';
@@ -257,14 +257,14 @@ class _StoreHarnessActionsState extends State<StoreHarnessActions> {
),
focusNode: i == 0 ? _firstChoiceFocus : null,
metrics: AppMenuRowMetrics.roomy,
- icon: LucideIcons.history300,
+ icon: AppIcons.history,
label: targets[i].title,
detail: targets[i].detail,
trailing: targets[i].machine.nodeOnline == false
? Tooltip(
message: 'Machine offline',
child: Icon(
- LucideIcons.cloudOff300,
+ AppIcons.cloudOff,
size: 14,
color: grid.AppPalette.textFaint,
),
@@ -325,7 +325,7 @@ class _StoreHarnessActionsState extends State<StoreHarnessActions> {
if (multiple) ...[
const SizedBox(width: 6),
Icon(
- LucideIcons.chevronDown300,
+ AppIcons.chevronDown,
key: ValueKey(
'store-resume-chevron:${widget.harnessId}',
),
diff --git a/desktop/lib/store/store_listing.dart b/desktop/lib/store/store_listing.dart
index e5c7a8b15..291fa06f6 100644
--- a/desktop/lib/store/store_listing.dart
+++ b/desktop/lib/store/store_listing.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -127,7 +128,7 @@ class _ProductRow extends StatelessWidget {
width: 18,
child: Text(
'$rank',
- style: grid.AppType.monoLabel(
+ style: grid.AppType.label(
color: grid.AppPalette.textSecondary,
),
),
@@ -183,14 +184,14 @@ class _ProductRow extends StatelessWidget {
: Row(
children: [
Icon(
- Icons.star_rounded,
+ AppIcons.star,
size: 12,
color: grid.AppPalette.textSecondary,
),
const SizedBox(width: 3),
Text(
'${rating.average.toStringAsFixed(1)} · ${rating.count}',
- style: grid.AppType.monoMeta(
+ style: grid.AppType.caption(
color: grid.AppPalette.textSecondary,
),
),
diff --git a/desktop/lib/store/store_screen.dart b/desktop/lib/store/store_screen.dart
index 66c40af8b..7c0764348 100644
--- a/desktop/lib/store/store_screen.dart
+++ b/desktop/lib/store/store_screen.dart
@@ -1,9 +1,13 @@
+import 'dart:math' as math;
import 'dart:async';
import '../shared/widgets/labeled_field.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+
+import '../shared/widgets/app_rating_star.dart';
+
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -620,14 +624,14 @@ class _StoreNav extends StatelessWidget {
children: [
SidebarItem(
key: const ValueKey('store-shelf-discover'),
- icon: LucideIcons.sparkles300,
+ icon: AppIcons.sparkles,
label: 'Discover',
selected: !hasProduct && shelf is _Discover,
onTap: () => onSelect(const _Discover()),
),
SidebarItem(
key: const ValueKey('store-shelf-all'),
- icon: LucideIcons.layoutGrid300,
+ icon: AppIcons.layoutGrid,
label: 'All harnesses',
selected: !hasProduct && shelf is _All,
onTap: () => onSelect(const _All()),
@@ -635,7 +639,7 @@ class _StoreNav extends StatelessWidget {
if (sessionCount > 0 || shelf is _Sessions)
SidebarItem(
key: const ValueKey('store-shelf-sessions'),
- icon: LucideIcons.play300,
+ icon: AppIcons.play,
label: 'Featured',
tooltip: '$sessionCount recorded runs',
selected: !hasProduct && shelf is _Sessions,
@@ -645,9 +649,8 @@ class _StoreNav extends StatelessWidget {
Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
child: Text(
- 'DISCIPLINES',
- style: grid.AppType.monoMeta(
- letterSpacing: 1.4,
+ 'Disciplines',
+ style: grid.AppType.caption(
fontWeight: grid.AppFont.medium,
color: grid.AppPalette.textFaint,
),
@@ -668,7 +671,7 @@ class _StoreNav extends StatelessWidget {
alignment: Alignment.centerRight,
child: Text(
'${counts[name]}',
- style: grid.AppType.monoMeta(
+ style: grid.AppType.caption(
color: grid.AppPalette.textFaint,
),
),
@@ -684,7 +687,7 @@ class _StoreNav extends StatelessWidget {
alignment: Alignment.centerLeft,
child: AppIconButton(
key: const ValueKey('store-viewers-button'),
- icon: LucideIcons.panelsTopLeft300,
+ icon: AppIcons.panelsTopLeft,
size: 17,
color: shelf is _Viewers
? grid.AppPalette.textPrimary
@@ -701,18 +704,18 @@ class _StoreNav extends StatelessWidget {
}
IconData _categoryIcon(String category) => switch (category) {
- 'Design' => LucideIcons.box300,
- 'Engineering' => LucideIcons.cpu300,
- 'Media' => LucideIcons.film300,
- 'Music' => LucideIcons.music300,
- 'Productivity' => LucideIcons.fileText300,
- 'Science & Data' => LucideIcons.flaskConical300,
- 'Simulation' => LucideIcons.bot300,
- 'Research' => LucideIcons.search300,
- 'Local AI' => LucideIcons.brainCircuit300,
- 'Coding' => LucideIcons.terminal300,
- 'Games' => LucideIcons.gamepad2300,
- _ => LucideIcons.shapes300,
+ 'Design' => AppIcons.box,
+ 'Engineering' => AppIcons.cpu,
+ 'Media' => AppIcons.film,
+ 'Music' => AppIcons.music,
+ 'Productivity' => AppIcons.fileText,
+ 'Science & Data' => AppIcons.flaskConical,
+ 'Simulation' => AppIcons.bot,
+ 'Research' => AppIcons.search,
+ 'Local AI' => AppIcons.brainCircuit,
+ 'Coding' => AppIcons.terminal,
+ 'Games' => AppIcons.gamepad2,
+ _ => AppIcons.shapes,
};
// Search and the complete index stay compact; disciplines and collections
@@ -846,16 +849,29 @@ class _Stars extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
for (var i = 1; i <= 5; i++)
- GestureDetector(
- onTap: onPick == null ? null : () => onPick!(i),
- child: Icon(
- value >= i
- ? Icons.star_rounded
- : value >= i - 0.5
- ? Icons.star_half_rounded
- : Icons.star_outline_rounded,
- size: size,
- color: value >= i - 0.5 ? _amber : grid.AppPalette.textFaint,
+ MouseRegion(
+ cursor: onPick == null
+ ? SystemMouseCursors.basic
+ : SystemMouseCursors.click,
+ child: GestureDetector(
+ onTap: onPick == null ? null : () => onPick!(i),
+ child: Semantics(
+ label: '$i ${i == 1 ? 'star' : 'stars'}',
+ button: onPick != null,
+ child: SizedBox.square(
+ dimension: onPick == null ? size : math.max(32, size),
+ child: Center(
+ child: AppRatingStar(
+ fraction: (value - i + 1).clamp(0, 1),
+ size: size,
+ color: _amber,
+ outlineColor: value >= i - 0.5
+ ? _amber
+ : grid.AppPalette.textFaint,
+ ),
+ ),
+ ),
+ ),
),
),
],
@@ -1673,7 +1689,7 @@ class _QuietLinkState extends State<_QuietLink> {
widget.child ?? Text(widget.label!),
if (url != null) ...[
const SizedBox(width: 3),
- Icon(LucideIcons.arrowUpRight300, size: 13, color: color),
+ Icon(AppIcons.arrowUpRight, size: 13, color: color),
],
],
),
@@ -1736,7 +1752,7 @@ class _RatingSummary extends StatelessWidget {
child: Text(
'$stars',
textAlign: TextAlign.right,
- style: grid.AppType.monoMeta(
+ style: grid.AppType.caption(
color: grid.AppPalette.textFaint,
),
),
diff --git a/desktop/lib/store/store_search.dart b/desktop/lib/store/store_search.dart
index 6a01eade8..5ebe838fc 100644
--- a/desktop/lib/store/store_search.dart
+++ b/desktop/lib/store/store_search.dart
@@ -1,8 +1,8 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -157,7 +157,7 @@ class _History extends StatelessWidget {
children: [
AppIconButton(
key: const ValueKey('store-back'),
- icon: LucideIcons.chevronLeft300,
+ icon: AppIcons.chevronLeft,
tooltip: back == null ? 'Back' : 'Back $back',
onPressed: onBack,
size: 17,
@@ -170,7 +170,7 @@ class _History extends StatelessWidget {
),
AppIconButton(
key: const ValueKey('store-nav-forward'),
- icon: LucideIcons.chevronRight300,
+ icon: AppIcons.chevronRight,
tooltip: forward == null ? 'Forward' : 'Forward $forward',
onPressed: onForward,
size: 17,
@@ -238,7 +238,7 @@ class _Field extends StatelessWidget {
child: Row(
children: [
Icon(
- LucideIcons.search300,
+ AppIcons.search,
size: 15,
color: grid.AppPalette.textSecondary,
),
@@ -252,14 +252,14 @@ class _Field extends StatelessWidget {
onChanged: onChanged,
textInputAction: TextInputAction.search,
textAlignVertical: TextAlignVertical.center,
- style: grid.AppType.mono(
+ style: grid.AppType.body(
color: grid.AppPalette.textPrimary,
),
// Bare: the outline around it is this field's border,
// so none of the theme's own may draw inside it.
decoration: InputDecoration(
hintText: 'Search harnesses',
- hintStyle: grid.AppType.mono(
+ hintStyle: grid.AppType.body(
color: grid.AppPalette.textSecondary,
),
isCollapsed: true,
@@ -279,7 +279,7 @@ class _Field extends StatelessWidget {
),
if (controller.text.isNotEmpty)
AppIconButton(
- icon: LucideIcons.x300,
+ icon: AppIcons.close,
tooltip: 'Clear search',
onPressed: onClear,
)
@@ -338,7 +338,7 @@ class _CreateHarness extends StatelessWidget {
),
child: labelled
? const Text('Create Harness')
- : const Icon(LucideIcons.plus300, size: 16),
+ : const Icon(AppIcons.plus, size: 16),
),
);
}
diff --git a/desktop/lib/store/store_sessions.dart b/desktop/lib/store/store_sessions.dart
index e0fd7ad5a..46f32e7da 100644
--- a/desktop/lib/store/store_sessions.dart
+++ b/desktop/lib/store/store_sessions.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../terminal/terminal_text.dart';
@@ -160,14 +160,14 @@ class _SessionCard extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
- LucideIcons.play300,
+ AppIcons.play,
size: 15,
color: Colors.white,
),
const SizedBox(width: 8),
Text(
'Watch run',
- style: grid.AppType.monoLabel(
+ style: grid.AppType.label(
color: Colors.white,
),
),
@@ -220,7 +220,7 @@ class _SessionCard extends StatelessWidget {
child: Text(
entry.category ?? storeCategoryFor(entry),
textAlign: TextAlign.end,
- style: grid.AppType.monoMeta(
+ style: grid.AppType.caption(
color: grid.AppPalette.textFaint,
),
),
@@ -262,7 +262,7 @@ class _SessionCard extends StatelessWidget {
foregroundColor: grid.AppPalette.accentOnSurface,
),
iconAlignment: IconAlignment.end,
- icon: const Icon(LucideIcons.arrowRight300, size: 15),
+ icon: const Icon(AppIcons.arrowRight, size: 15),
label: const Text('Explore harness'),
),
],
diff --git a/desktop/lib/store/store_showcase.dart b/desktop/lib/store/store_showcase.dart
index d575c65f2..5c7eaf912 100644
--- a/desktop/lib/store/store_showcase.dart
+++ b/desktop/lib/store/store_showcase.dart
@@ -1,6 +1,6 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/terminal/terminal_text.dart';
import '../core/dsh_catalog.dart';
@@ -101,8 +101,7 @@ class _ExampleBlockState extends State<_ExampleBlock> {
children: [
Text(
'${(i + 1).toString().padLeft(2, '0')} / ${widget.count.toString().padLeft(2, '0')}',
- style: grid.AppType.monoMeta(
- letterSpacing: 2,
+ style: grid.AppType.caption(
color: grid.AppPalette.accentOnSurface,
),
),
@@ -130,7 +129,7 @@ class _ExampleBlockState extends State<_ExampleBlock> {
onPressed: widget.onTry == null
? null
: () => widget.onTry!(example.prompt),
- icon: const Icon(LucideIcons.sparkles300, size: 17),
+ icon: const Icon(AppIcons.sparkles, size: 17),
label: const Text('Try this prompt'),
style: FilledButton.styleFrom(
backgroundColor: grid.AppPalette.accent,
@@ -151,7 +150,7 @@ class _ExampleBlockState extends State<_ExampleBlock> {
entry: widget.entry,
example: example,
),
- icon: const Icon(LucideIcons.play300, size: 17),
+ icon: const Icon(AppIcons.play, size: 17),
label: const Text('Watch recorded run'),
style: OutlinedButton.styleFrom(
minimumSize: const Size(0, 46),
@@ -161,7 +160,7 @@ class _ExampleBlockState extends State<_ExampleBlock> {
),
AppIconButton(
key: ValueKey('store-copy-prompt:$i'),
- icon: LucideIcons.copy300,
+ icon: AppIcons.copy,
tooltip: 'Copy prompt',
onPressed: () async {
await Clipboard.setData(
diff --git a/desktop/lib/store/store_viewers.dart b/desktop/lib/store/store_viewers.dart
index bfa2977bf..1e999a05e 100644
--- a/desktop/lib/store/store_viewers.dart
+++ b/desktop/lib/store/store_viewers.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../core/dsh_catalog.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -74,7 +74,7 @@ class StoreViewers extends StatelessWidget {
Row(
children: [
Icon(
- LucideIcons.panelsTopLeft300,
+ AppIcons.panelsTopLeft,
size: 20,
color: grid.AppPalette.textSecondary,
),
diff --git a/desktop/lib/teams/team_workspace.dart b/desktop/lib/teams/team_workspace.dart
index eb84f247c..e031a8820 100644
--- a/desktop/lib/teams/team_workspace.dart
+++ b/desktop/lib/teams/team_workspace.dart
@@ -1,17 +1,14 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
import '../state/harness_sessions.dart';
-import '../terminal/terminal_text.dart';
-import '../terminal/terminal_theme.dart';
-import '../terminal/terminal_theme_store.dart';
-import '../widgets/box_chrome.dart';
+import '../widgets/desktop_chrome.dart';
import '../widgets/terminal_prompt.dart';
-import '../widgets/terminal_text_action.dart';
import 'team_controller.dart';
class TeamCandidate {
@@ -120,7 +117,7 @@ Future<void> showTeamWorkspace(BuildContext context, AppNotifier app) async {
);
}
-/// Terminal-native team roster, conversations, and question composer. No terminal is
+/// Team roster, conversations, and question composer. No terminal is
/// attached or written by mounting, searching, selecting, or closing this surface.
class TeamWorkspace extends StatefulWidget {
const TeamWorkspace({
@@ -149,12 +146,15 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
late final _description = TextEditingController(text: model.newDescription);
late final _question = TextEditingController(text: model.draft);
final _questionFocus = FocusNode(debugLabel: 'Team question');
+ final _compactScroll = ScrollController();
+ final _exchangeScroll = ScrollController();
+ final _conversationScroll = ScrollController();
+ final _rosterScroll = ScrollController();
+ ScrollController? _activeScroll;
bool _creating = false;
String? _selectedMember;
- late Size cell;
- late Color foreground, muted, selection;
- TextStyle get style => terminalContentStyle(color: foreground);
- TextStyle get faint => terminalContentStyle(color: muted);
+ TextStyle get style => DesktopChrome.text(size: 13);
+ TextStyle get faint => DesktopChrome.metadata();
@override
void initState() {
super.initState();
@@ -184,54 +184,80 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
_description.dispose();
_question.dispose();
_questionFocus.dispose();
+ _compactScroll.dispose();
+ _exchangeScroll.dispose();
+ _conversationScroll.dispose();
+ _rosterScroll.dispose();
super.dispose();
}
+ void _page(int direction) {
+ final focusedContext = FocusManager.instance.primaryFocus?.context;
+ final focusedScroll = focusedContext == null
+ ? null
+ : Scrollable.maybeOf(focusedContext, axis: Axis.vertical)?.position;
+ final scroll = _activeScroll?.hasClients == true
+ ? _activeScroll
+ : _compactScroll.hasClients
+ ? _compactScroll
+ : _conversationScroll.hasClients
+ ? _conversationScroll
+ : null;
+ final position = focusedScroll ?? scroll?.position;
+ if (position == null) return;
+ position.jumpTo(
+ (position.pixels + direction * position.viewportDimension * .9).clamp(
+ 0,
+ position.maxScrollExtent,
+ ),
+ );
+ }
+
+ Widget _scrollRegion(ScrollController controller, Widget child) => Focus(
+ skipTraversal: true,
+ onFocusChange: (focused) {
+ if (focused) _activeScroll = controller;
+ },
+ child: child,
+ );
+
Widget _line(
String label,
VoidCallback? action, {
String? trailing,
+ String? detail,
+ bool? checked,
bool selected = false,
Key? key,
String? semantics,
- }) {
- return Semantics(
- selected: selected,
- label: semantics,
- child: SizedBox(
- height: cell.height,
- child: TextButton(
- key: key,
- onPressed: action,
- style:
- TextButton.styleFrom(
- foregroundColor: foreground,
- disabledForegroundColor: muted,
- backgroundColor: selected ? selection : Colors.transparent,
- minimumSize: Size.zero,
- padding: EdgeInsets.symmetric(horizontal: cell.width),
- shape: const RoundedRectangleBorder(),
- textStyle: style,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- splashFactory: NoSplash.splashFactory,
- ).copyWith(
- overlayColor: WidgetStatePropertyAll(
- selection.withValues(alpha: .45),
- ),
- ),
- child: Row(
- children: [
- Expanded(
- child: Text(
- label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- if (trailing != null) Text(' $trailing', style: faint),
- ],
- ),
- ),
+ }) => _TeamRow(
+ key: key,
+ label: label,
+ detail: detail,
+ trailing: trailing,
+ selected: selected,
+ checked: checked,
+ semanticLabel: semantics,
+ onPressed: action,
+ );
+
+ InputDecoration _fieldDecoration(String label) {
+ final border = OutlineInputBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ borderSide: BorderSide(color: DesktopChrome.rim, width: 1.5),
+ );
+ return InputDecoration(
+ labelText: label,
+ labelStyle: faint,
+ hintStyle: faint,
+ filled: true,
+ fillColor: DesktopChrome.field,
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
+ border: border,
+ enabledBorder: border,
+ focusedBorder: border.copyWith(
+ borderSide: BorderSide(color: DesktopChrome.focusRing, width: 1.5),
),
);
}
@@ -253,27 +279,13 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
maxLines: lines == 1 ? 1 : lines + 3,
style: style,
cursorWidth: 2,
- decoration: InputDecoration(
- labelText: label,
- labelStyle: faint,
- hintStyle: faint,
- filled: false,
- isDense: true,
- contentPadding: EdgeInsets.symmetric(vertical: cell.height / 2),
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- ),
+ decoration: _fieldDecoration(label),
onChanged: changed,
);
Widget _action(String label, VoidCallback? callback, {Key? key}) =>
- TerminalTextAction(
- key: key,
- label: label,
- onPressed: callback,
- padding: EdgeInsets.zero,
- );
- Widget _gap([double rows = 1]) => SizedBox(height: cell.height * rows);
+ DesktopPill(key: key, label: label, onPressed: callback);
+ Widget _gap([double groups = 1]) =>
+ SizedBox(height: DesktopChrome.groupGap * groups);
String _memberName(String? id) {
final member = model.members.where((m) => m['id'] == id).firstOrNull;
final runtime = member?['runtime'] as Map?;
@@ -393,13 +405,10 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
children: [
for (var i = 0; i < 4; i++)
Padding(
- padding: EdgeInsets.only(bottom: cell.height),
+ padding: const EdgeInsets.only(bottom: 16),
child: ColoredBox(
- color: muted.withValues(alpha: .12),
- child: SizedBox(
- width: cell.width * (24 - i * 3),
- height: cell.height,
- ),
+ color: DesktopChrome.muted.withValues(alpha: .12),
+ child: SizedBox(width: 192 - i * 24, height: 16),
),
),
],
@@ -427,6 +436,7 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
setState(() {});
},
),
+ _gap(),
_field(
_description,
'What are you building together?',
@@ -440,6 +450,7 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
key: const Key('team-search'),
changed: (_) => setState(() {}),
),
+ _gap(.5),
Text(
'${model.newMembers.length} selected · Connect introduces the team to these harnesses.',
style: faint,
@@ -453,22 +464,20 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
Text('No matching harnesses.', style: faint),
for (final candidate in candidates) ...[
_line(
- '${model.newMembers.containsKey(candidate.key) ? '[x]' : '[ ]'} ${candidate.name}',
+ candidate.name,
model.pendingCreate || !candidate.available
? null
: () => _toggle(candidate),
trailing:
'${candidate.engine} · ${candidate.available ? candidate.machineName : candidate.status}',
key: ValueKey('team-candidate-${candidate.agentId}'),
+ checked: model.newMembers.containsKey(candidate.key),
semantics:
'${candidate.name}, ${candidate.engine}, ${candidate.status}',
),
if (model.newMembers[candidate.key] case final member?)
Padding(
- padding: EdgeInsets.only(
- left: cell.width * 4,
- bottom: cell.height,
- ),
+ padding: const EdgeInsets.fromLTRB(36, 8, 0, 16),
child: LayoutBuilder(
builder: (context, constraints) {
final name = TextFormField(
@@ -476,12 +485,7 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
initialValue: member['name'] as String,
readOnly: model.pendingCreate,
style: style,
- decoration: InputDecoration(
- labelText: 'Team name',
- labelStyle: faint,
- isDense: true,
- border: InputBorder.none,
- ),
+ decoration: _fieldDecoration('Team name'),
onChanged: (v) => member['name'] = v,
);
final role = TextFormField(
@@ -489,20 +493,15 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
initialValue: member['role'] as String,
readOnly: model.pendingCreate,
style: style,
- decoration: InputDecoration(
- labelText: 'Knows about',
- labelStyle: faint,
- isDense: true,
- border: InputBorder.none,
- ),
+ decoration: _fieldDecoration('Knows about'),
onChanged: (v) => member['role'] = v,
);
- return constraints.maxWidth < cell.width * 50
- ? Column(children: [name, role])
+ return constraints.maxWidth < 440
+ ? Column(children: [name, _gap(), role])
: Row(
children: [
- SizedBox(width: cell.width * 22, child: name),
- SizedBox(width: cell.width * 2),
+ SizedBox(width: 176, child: name),
+ const SizedBox(width: 16),
Expanded(child: role),
],
);
@@ -515,8 +514,8 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
),
_gap(),
Wrap(
- spacing: cell.width * 3,
- runSpacing: cell.height,
+ spacing: 8,
+ runSpacing: 8,
children: [
_action(
model.pendingCreate ? 'Check connection' : 'Connect teammates',
@@ -542,85 +541,80 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
final selected = model.members
.where((m) => m['id'] == _selectedMember)
.firstOrNull;
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- model.isChannel ? 'Harnesses in this swarm' : 'Teammates',
- style: faint,
- ),
- _gap(),
- Flexible(
- child: ListView(
- shrinkWrap: true,
- children: [
- for (final member in model.members)
- _line(
- model.isChannel
- ? _memberName(member['id'] as String?)
- : '@${member['name']}',
- () =>
- setState(() => _selectedMember = member['id'] as String),
- selected: _selectedMember == member['id'],
- trailing: member['enabled'] == false
- ? 'Removed'
- : (member['runtime'] as Map?)?['engine'] as String? ??
- 'Offline',
- key: ValueKey('team-member-${member['id']}'),
- ),
- ],
- ),
- ),
- if (selected != null) ...[
- _gap(),
- Text(selected['role'] as String? ?? '', style: faint),
- _gap(),
+ return _scrollRegion(
+ _rosterScroll,
+ ListView(
+ controller: _rosterScroll,
+ children: [
Text(
- selected['enabled'] == false
- ? 'Removed from team'
- : (selected['runtime'] as Map?)?['available'] == true
- ? 'Available'
- : 'Offline · questions wait here',
- style: faint,
+ model.isChannel ? 'Agents in this swarm' : 'Teammates',
+ style: DesktopChrome.control(medium: true),
),
- _gap(),
- _action(
- 'Open harness',
- () => widget.onOpen(
- selected['machineId'] as String,
- selected['agentId'] as String,
+ _gap(.5),
+ for (final member in model.members)
+ _line(
+ model.isChannel
+ ? _memberName(member['id'] as String?)
+ : '@${member['name']}',
+ () => setState(() => _selectedMember = member['id'] as String),
+ selected: _selectedMember == member['id'],
+ trailing: member['enabled'] == false
+ ? 'Removed'
+ : (member['runtime'] as Map?)?['engine'] as String? ??
+ 'Offline',
+ key: ValueKey('team-member-${member['id']}'),
),
- ),
- if (!model.isChannel) _gap(.5),
- if (!model.isChannel)
+ if (selected != null) ...[
+ _gap(),
+ Text(selected['role'] as String? ?? '', style: faint),
+ _gap(),
+ Text(
+ selected['enabled'] == false
+ ? 'Removed from team'
+ : (selected['runtime'] as Map?)?['available'] == true
+ ? 'Available'
+ : 'Offline · questions wait here',
+ style: faint,
+ ),
+ _gap(),
_action(
- 'Edit teammate',
- model.operating ? null : () => _editMember(selected),
+ 'Open session',
+ () => widget.onOpen(
+ selected['machineId'] as String,
+ selected['agentId'] as String,
+ ),
),
- ],
- _gap(2),
- if (!model.isChannel)
- Align(
- alignment: Alignment.centerLeft,
- child: _action(
- 'Ask teammate',
- model.active
- ? () {
- setState(() {
- model.selectedExchange = null;
- if (selected?['enabled'] != false &&
- selected?['id'] != model.from &&
- selected != null) {
- model.to = selected['id'] as String;
- }
- });
- _questionFocus.requestFocus();
- }
- : null,
- key: const Key('team-new-question'),
+ if (!model.isChannel) _gap(.5),
+ if (!model.isChannel)
+ _action(
+ 'Edit teammate',
+ model.operating ? null : () => _editMember(selected),
+ ),
+ ],
+ _gap(2),
+ if (!model.isChannel)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: _action(
+ 'Ask teammate',
+ model.active
+ ? () {
+ setState(() {
+ model.selectedExchange = null;
+ if (selected?['enabled'] != false &&
+ selected?['id'] != model.from &&
+ selected != null) {
+ model.to = selected['id'] as String;
+ }
+ });
+ _questionFocus.requestFocus();
+ }
+ : null,
+ key: const Key('team-new-question'),
+ ),
),
- ),
- ],
+ ],
+ ),
);
}
@@ -693,21 +687,24 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
cancel: () => Navigator.pop(context),
child: _TeamSurface(
width: 620,
- child: Padding(
- padding: EdgeInsets.all(cell.width * 2),
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
adding ? 'Connect teammate' : 'Edit teammate',
- style: faint,
+ style: DesktopChrome.heading(),
),
+ _gap(),
_field(name, 'Team name'),
+ _gap(),
_field(role, 'Knows about'),
_gap(),
Wrap(
- spacing: cell.width * 3,
+ spacing: 8,
+ runSpacing: 8,
children: [
_action(
adding ? 'Connect' : 'Save',
@@ -770,8 +767,8 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
Text('Ask a teammate', style: style),
_gap(),
Wrap(
- spacing: cell.width * 3,
- runSpacing: cell.height,
+ spacing: 8,
+ runSpacing: 8,
children: [
_action(
'From @${_memberName(model.from)}',
@@ -820,7 +817,10 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
],
),
);
- Widget _conversation(Map<String, dynamic> exchange) {
+ Widget _conversation(
+ Map<String, dynamic> exchange, {
+ bool scrollable = true,
+ }) {
final answer = (exchange['answer'] as Map?)?.cast<String, dynamic>();
final from =
model.members.where((m) => m['id'] == exchange['from']).firstOrNull ??
@@ -834,215 +834,368 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
final toName =
(exchange['toPeer'] as Map?)?['name'] ??
_memberName(exchange['to'] as String?);
- return SingleChildScrollView(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- model.isChannel
- ? '$fromName → $toName'
- : '@${from?['name']} → @${to?['name']}',
- style: style,
- ),
+ final content = Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ model.isChannel
+ ? '$fromName → $toName'
+ : '@${from?['name']} → @${to?['name']}',
+ style: style,
+ ),
+ Text(
+ '${exchange['origin'] == 'owner' ? 'Requested by you' : 'Agent question'} · ${exchange['state']} · ${teamDeliveryLabel((exchange['delivery'] as Map?)?.cast<String, dynamic>())}',
+ style: faint,
+ ),
+ _gap(),
+ SelectableText(exchange['text'] as String? ?? '', style: style),
+ if ((exchange['context'] as String? ?? '').isNotEmpty) ...[
+ _gap(),
+ SelectableText(exchange['context'] as String, style: faint),
+ ],
+ _gap(),
+ if (answer != null) ...[
Text(
- '${exchange['origin'] == 'owner' ? 'Requested by you' : 'Agent question'} · ${exchange['state']} · ${teamDeliveryLabel((exchange['delivery'] as Map?)?.cast<String, dynamic>())}',
+ '${answer['late'] == true ? 'Late answer' : 'Answer'} ${answer['origin'] == 'owner' ? 'supplied by you for' : 'from'} @${to?['name']}',
style: faint,
),
- _gap(),
- SelectableText(exchange['text'] as String? ?? '', style: style),
- if ((exchange['context'] as String? ?? '').isNotEmpty) ...[
- _gap(),
- SelectableText(exchange['context'] as String, style: faint),
- ],
- _gap(),
- if (answer != null) ...[
- Text(
- '${answer['late'] == true ? 'Late answer' : 'Answer'} ${answer['origin'] == 'owner' ? 'supplied by you for' : 'from'} @${to?['name']}',
- style: faint,
+ _gap(.5),
+ SelectableText(answer['text'] as String, style: style),
+ for (final reference in answer['evidence'] as List? ?? [])
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: SelectableText(reference.toString(), style: faint),
),
- _gap(.5),
- SelectableText(answer['text'] as String, style: style),
- for (final reference in answer['evidence'] as List? ?? [])
- Padding(
- padding: EdgeInsets.only(top: cell.height / 2),
- child: SelectableText(reference.toString(), style: faint),
- ),
- _gap(),
- Text(
- answer['late'] == true
- ? 'Retained for reference. No automatic continuation.'
- : 'Return to @${from?['name']}: ${teamDeliveryLabel((exchange['continuation'] as Map?)?.cast<String, dynamic>())}',
- style: faint,
- ),
- ] else
- Text(
- exchange['state'] == 'pending'
- ? 'Waiting for a correlated answer. Delivery alone does not mean the question is answered.'
- : 'This question is ${exchange['state']}.',
- style: faint,
- ),
- if ((exchange['delivery'] as Map?)?['reason']
- case final String reason) ...[
- _gap(.5),
- Text(reason, style: faint),
- ],
_gap(),
- Wrap(
- spacing: cell.width * 3,
- runSpacing: cell.height,
- children: [
- if (from != null)
- _action(
- 'Open @${from['name']}',
- () => widget.onOpen(
- from['machineId'] as String,
- from['agentId'] as String,
- ),
- ),
- if (to != null)
- _action(
- 'Open @${to['name']}',
- () => widget.onOpen(
- to['machineId'] as String,
- to['agentId'] as String,
- ),
- ),
- if (exchange['state'] == 'pending')
- _action(
- 'Cancel question',
- model.operating
- ? null
- : () => unawaited(
- model.act('cancel', {
- 'questionId':
- exchange['questionId'] ?? exchange['id'],
- if (exchange['teamId'] != null)
- 'teamId': exchange['teamId'],
- }),
- ),
- ),
- ],
+ Text(
+ answer['late'] == true
+ ? 'Retained for reference. No automatic continuation.'
+ : 'Return to @${from?['name']}: ${teamDeliveryLabel((exchange['continuation'] as Map?)?.cast<String, dynamic>())}',
+ style: faint,
),
+ ] else
+ Text(
+ exchange['state'] == 'pending'
+ ? 'Waiting for a correlated answer. Delivery alone does not mean the question is answered.'
+ : 'This question is ${exchange['state']}.',
+ style: faint,
+ ),
+ if ((exchange['delivery'] as Map?)?['reason']
+ case final String reason) ...[
+ _gap(.5),
+ Text(reason, style: faint),
],
- ),
+ _gap(),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ if (from != null)
+ _action(
+ 'Open @${from['name']}',
+ () => widget.onOpen(
+ from['machineId'] as String,
+ from['agentId'] as String,
+ ),
+ ),
+ if (to != null)
+ _action(
+ 'Open @${to['name']}',
+ () => widget.onOpen(
+ to['machineId'] as String,
+ to['agentId'] as String,
+ ),
+ ),
+ if (exchange['state'] == 'pending')
+ _action(
+ 'Cancel question',
+ model.operating
+ ? null
+ : () => unawaited(
+ model.act('cancel', {
+ 'questionId':
+ exchange['questionId'] ?? exchange['id'],
+ if (exchange['teamId'] != null)
+ 'teamId': exchange['teamId'],
+ }),
+ ),
+ ),
+ ],
+ ),
+ ],
);
+ return scrollable
+ ? _scrollRegion(
+ _conversationScroll,
+ SingleChildScrollView(
+ controller: _conversationScroll,
+ child: content,
+ ),
+ )
+ : content;
}
- Widget _exchanges() {
+ Widget _selectedConversation({bool scrollable = true}) {
final selected = model.exchanges
.where((e) => e['id'] == model.selectedExchange)
.firstOrNull;
- return Column(
+ if (selected != null) {
+ return _conversation(selected, scrollable: scrollable);
+ }
+ if (!model.isChannel) return _composer();
+ final content = Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Agents consult relevant peers in this swarm and continue their work.',
+ style: style,
+ ),
+ _gap(),
+ Text(
+ 'This tab is your swarm. Add another agent pane to include it.',
+ style: faint,
+ ),
+ for (final instruction in teamRows(
+ model.team?['consultations'],
+ ).reversed.take(5)) ...[
+ _gap(),
+ Text(
+ 'Consult requested for ${_memberName(instruction['memberId'] as String?)} · ${teamDeliveryLabel((instruction['receipt'] as Map?)?.cast<String, dynamic>())}',
+ style: faint,
+ ),
+ ],
+ ],
+ );
+ return scrollable
+ ? _scrollRegion(
+ _conversationScroll,
+ SingleChildScrollView(
+ controller: _conversationScroll,
+ child: content,
+ ),
+ )
+ : content;
+ }
+
+ Widget _exchangeList() => _scrollRegion(
+ _exchangeScroll,
+ ListView(
+ key: const ValueKey('team-exchanges'),
+ controller: _exchangeScroll,
+ shrinkWrap: true,
+ children: [
+ for (final exchange in model.exchanges)
+ _line(
+ '${(exchange['fromPeer'] as Map?)?['name'] ?? _memberName(exchange['from'] as String?)} → ${(exchange['toPeer'] as Map?)?['name'] ?? _memberName(exchange['to'] as String?)}',
+ () => setState(
+ () => model.selectedExchange = exchange['id'] as String,
+ ),
+ detail: exchange['text'] as String? ?? '',
+ selected: model.selectedExchange == exchange['id'],
+ trailing: exchange['state'] as String,
+ key: ValueKey('team-exchange-${exchange['id']}'),
+ ),
+ ],
+ ),
+ );
+
+ Widget _exchanges() => LayoutBuilder(
+ builder: (context, constraints) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Text('Exchanges', style: faint),
+ Text('Exchanges', style: DesktopChrome.control(medium: true)),
+ _gap(.5),
+ if (model.exchanges.isEmpty)
+ Text('Questions and answers will appear here.', style: faint)
+ else
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: math.min(224, constraints.maxHeight * .38),
+ ),
+ child: _exchangeList(),
+ ),
_gap(),
- SizedBox(
- height:
- cell.height * math.min(6, math.max(2, model.exchanges.length)),
- child: model.exchanges.isEmpty
- ? Text('Questions and answers will appear here.', style: faint)
- : ListView(
- children: [
- for (final exchange in model.exchanges)
- _line(
- '${(exchange['fromPeer'] as Map?)?['name'] ?? _memberName(exchange['from'] as String?)} → ${(exchange['toPeer'] as Map?)?['name'] ?? _memberName(exchange['to'] as String?)} ${exchange['text']}',
- () => setState(
- () =>
- model.selectedExchange = exchange['id'] as String,
- ),
- selected: model.selectedExchange == exchange['id'],
- trailing: exchange['state'] as String,
- key: ValueKey('team-exchange-${exchange['id']}'),
+ Expanded(child: _selectedConversation()),
+ ],
+ ),
+ );
+
+ Widget _summary() => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (model.selectedId != null && !_creating) ...[
+ Text(
+ '${model.isChannel ? 'Swarm conversation · ' : ''}${model.members.where((m) => m['enabled'] != false).length} agents · ${model.isChannel ? 'This tab only · ' : ''}${model.team?['state'] ?? 'Connecting'}',
+ style: faint,
+ ),
+ _gap(.5),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ if (!model.isChannel)
+ _action(
+ 'All teams',
+ model.operating ? null : () => unawaited(model.select(null)),
+ ),
+ if (model.team?['state'] != 'archived')
+ _action(
+ model.active ? 'Pause collaboration' : 'Resume collaboration',
+ model.operating || model.team == null
+ ? null
+ : () => unawaited(
+ model.act(model.active ? 'pause' : 'resume'),
),
- ],
- ),
+ ),
+ if (!model.isChannel && model.team?['state'] != 'archived')
+ _action(
+ model.pendingAdd ? 'Check teammate' : 'Add teammate',
+ model.operating ? null : _addMember,
+ ),
+ if (!model.isChannel)
+ _action(
+ 'New question',
+ model.active
+ ? () => setState(() {
+ model.selectedExchange = null;
+ _questionFocus.requestFocus();
+ })
+ : null,
+ key: const Key('team-compose'),
+ ),
+ if (!model.isChannel && model.team?['state'] == 'paused')
+ _action(
+ 'Archive paused team',
+ model.operating ? null : () => unawaited(model.act('archive')),
+ ),
+ ],
),
_gap(),
- Expanded(
- child: selected == null
- ? model.isChannel
- ? SingleChildScrollView(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- 'Agents consult relevant peers in this swarm and continue their work.',
- style: style,
- ),
- _gap(),
- Text(
- 'Add a harness to this swarm to include its agent.',
- style: faint,
- ),
- for (final instruction in teamRows(
- model.team?['consultations'],
- ).reversed.take(5)) ...[
- _gap(),
- Text(
- 'Consult requested for ${_memberName(instruction['memberId'] as String?)} · ${teamDeliveryLabel((instruction['receipt'] as Map?)?.cast<String, dynamic>())}',
- style: faint,
- ),
- ],
- ],
- ),
- )
- : _composer()
- : _conversation(selected),
+ ],
+ if (model.error case final message?) ...[
+ Semantics(
+ liveRegion: true,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxHeight: 160),
+ child: SingleChildScrollView(
+ child: SelectableText(
+ message,
+ style: DesktopChrome.text(
+ size: 13,
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
+ ),
),
+ _gap(),
],
- );
- }
+ ],
+ );
Widget _detail() {
if (model.team == null) {
- return model.loading
- ? _loadingRows()
- : Align(
- alignment: Alignment.topLeft,
- child: _action(
+ return SingleChildScrollView(
+ controller: _compactScroll,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _summary(),
+ if (model.loading)
+ _loadingRows()
+ else
+ _action(
model.isChannel ? 'Retry reading swarm' : 'Retry reading team',
() => unawaited(model.refresh()),
),
- );
+ ],
+ ),
+ );
}
return LayoutBuilder(
builder: (context, constraints) {
- if (constraints.maxWidth < cell.width * 90) {
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- SizedBox(
- height: cell.height * 2,
- child: ListView(
- scrollDirection: Axis.horizontal,
- children: [
- for (final m in model.members)
- Padding(
- padding: EdgeInsets.only(right: cell.width * 2),
- child: _action(
- '${m['name']}',
- () => model.isChannel
- ? widget.onOpen(
- m['machineId'] as String,
- m['agentId'] as String,
- )
- : _editMember(m),
- ),
+ final scale = grid.appTextScaleOf(context);
+ if (constraints.maxWidth < 760 * scale ||
+ constraints.maxHeight < 420 * scale) {
+ return _scrollRegion(
+ _compactScroll,
+ SingleChildScrollView(
+ key: const ValueKey('team-compact-content'),
+ controller: _compactScroll,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _summary(),
+ Text(
+ model.isChannel ? 'Agents in this swarm' : 'Teammates',
+ style: DesktopChrome.control(medium: true),
+ ),
+ _gap(.5),
+ SizedBox(
+ height: math.max(
+ 36,
+ MediaQuery.textScalerOf(context).scale(19) + 16,
+ ),
+ child: ListView(
+ scrollDirection: Axis.horizontal,
+ children: [
+ for (final member in model.members)
+ Padding(
+ padding: const EdgeInsets.only(right: 8),
+ child: _action(
+ model.isChannel
+ ? _memberName(member['id'] as String?)
+ : '${member['name']}',
+ () => model.isChannel
+ ? widget.onOpen(
+ member['machineId'] as String,
+ member['agentId'] as String,
+ )
+ : _editMember(member),
+ ),
+ ),
+ ],
+ ),
+ ),
+ _gap(),
+ Text('Exchanges', style: DesktopChrome.control(medium: true)),
+ _gap(.5),
+ if (model.exchanges.isEmpty)
+ Text(
+ 'Questions and answers will appear here.',
+ style: faint,
+ )
+ else
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: math.min(224, constraints.maxHeight * .45),
),
- ],
- ),
+ child: _exchangeList(),
+ ),
+ _gap(),
+ _selectedConversation(scrollable: false),
+ ],
),
- Expanded(child: _exchanges()),
- ],
+ ),
);
}
- return Row(
+ return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- SizedBox(width: cell.width * 28, child: _roster()),
- SizedBox(width: cell.width * 3),
- Expanded(child: _exchanges()),
+ _summary(),
+ Expanded(
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SizedBox(width: 240, child: _roster()),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: VerticalDivider(width: 1, color: DesktopChrome.rim),
+ ),
+ Expanded(child: _exchanges()),
+ ],
+ ),
+ ),
],
);
},
@@ -1051,154 +1204,83 @@ class _TeamWorkspaceState extends State<TeamWorkspace> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
grid.AppTheme.watch(context);
- return ListenableBuilder(
- listenable: Listenable.merge([terminalFontStore, terminalThemeStore]),
- builder: (context, _) {
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
- cell = terminalCellSizeOf(context);
- foreground = theme.foreground;
- // Read off the scheme's own ground, not the app palette's: Tango stays
- // dark under a light palette. Near-black at .6 on a light ground is
- // 3.9:1, so a light scheme takes .7 (≥5.4:1); a dark one keeps .6.
- muted = foreground.withValues(
- alpha: theme.background.computeLuminance() > .5 ? .7 : .6,
- );
- selection = theme.selection;
- final title = _creating
- ? 'Connect a team'
- : model.team?['name'] as String? ??
- (model.isChannel ? 'Swarm conversation' : 'Team');
- return TerminalPromptKeys(
- cancel: widget.onClose,
- refresh: () => unawaited(model.refresh()),
- submit: model.isChannel ? null : () => unawaited(model.ask()),
- child: _TeamSurface(
- width: 1140,
- child: SizedBox(
- height: math.min(
- cell.height * 35,
- MediaQuery.sizeOf(context).height * .82,
- ),
- child: Padding(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
+ final short =
+ MediaQuery.sizeOf(context).height < 520 * grid.appTextScaleOf(context);
+ final title = _creating
+ ? 'Connect a team'
+ : model.team?['name'] as String? ??
+ (model.isChannel ? 'Swarm conversation' : 'Team');
+ final hint =
+ '${terminalPromptHint(context, 'picker.complete', 'Tab')} move · ${terminalPromptHint(context, 'picker.cancel', 'Esc')} close · conversations stay with the ${model.isChannel ? 'swarm' : 'team'}';
+ return TerminalPromptKeys(
+ cancel: widget.onClose,
+ refresh: () => unawaited(model.refresh()),
+ submit: model.isChannel ? null : () => unawaited(model.ask()),
+ pageDown: () => _page(1),
+ pageUp: () => _page(-1),
+ child: _TeamSurface(
+ width: 1140,
+ child: SizedBox(
+ height: 680,
+ child: Padding(
+ padding: EdgeInsets.all(short ? 16 : 24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
children: [
- Row(
- children: [
- Expanded(
- child: Text(
- title,
- style: style,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- _action('Close', widget.onClose),
- ],
- ),
- _gap(),
- if (model.selectedId != null && !_creating) ...[
- Wrap(
- spacing: cell.width * 3,
- runSpacing: cell.height / 2,
- children: [
- if (!model.isChannel)
- _action(
- 'All teams',
- model.operating
- ? null
- : () => unawaited(model.select(null)),
- ),
- Text(
- '${model.isChannel ? 'Swarm conversation · ' : ''}${model.members.where((m) => m['enabled'] != false).length} harnesses · ${model.isChannel ? 'This swarm only · ' : ''}${model.team?['state'] ?? 'Connecting'}',
- style: faint,
- ),
- if (model.team?['state'] != 'archived')
- _action(
- model.active
- ? 'Pause collaboration'
- : 'Resume collaboration',
- model.operating || model.team == null
- ? null
- : () => unawaited(
- model.act(
- model.active ? 'pause' : 'resume',
- ),
- ),
- ),
- if (!model.isChannel &&
- model.team?['state'] != 'archived')
- _action(
- model.pendingAdd
- ? 'Check teammate'
- : 'Add teammate',
- model.operating ? null : _addMember,
- ),
- if (!model.isChannel)
- _action(
- 'New question',
- model.active
- ? () => setState(() {
- model.selectedExchange = null;
- _questionFocus.requestFocus();
- })
- : null,
- key: const Key('team-compose'),
- ),
- if (!model.isChannel &&
- model.team?['state'] == 'paused')
- _action(
- 'Archive paused team',
- model.operating
- ? null
- : () => unawaited(model.act('archive')),
- ),
- ],
- ),
- _gap(),
- ],
- if (model.error case final message?) ...[
- Semantics(
- liveRegion: true,
+ Expanded(
+ child: Tooltip(
+ message: title,
child: Text(
- message,
- style: style,
- maxLines: 3,
+ title,
+ style: DesktopChrome.heading(),
+ maxLines: short ? 1 : 2,
overflow: TextOverflow.ellipsis,
),
),
- _gap(),
- ],
- Expanded(
- child: _creating
- ? _create()
- : model.selectedId == null && !model.isChannel
- ? _home()
- : _detail(),
),
- _gap(),
- Text(
- '${terminalPromptHint(context, 'picker.complete', 'Tab')} move · ${terminalPromptHint(context, 'picker.cancel', 'Esc')} close · conversations stay with the ${model.isChannel ? 'swarm' : 'team'}',
+ const SizedBox(width: 8),
+ IconButton(
+ key: const ValueKey('team-close'),
+ tooltip: 'Close conversation',
+ onPressed: widget.onClose,
+ icon: const Icon(AppIcons.close, size: 18),
+ ),
+ ],
+ ),
+ _gap(short ? .5 : 1),
+ Expanded(
+ child:
+ _creating ||
+ (model.selectedId == null && !model.isChannel)
+ ? Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _summary(),
+ Expanded(child: _creating ? _create() : _home()),
+ ],
+ )
+ : _detail(),
+ ),
+ if (!short) ...[
+ _gap(),
+ Tooltip(
+ message: hint,
+ child: Text(
+ hint,
style: faint,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
- ],
- ),
- ),
+ ),
+ ],
+ ],
),
),
- );
- },
+ ),
+ ),
);
}
}
@@ -1208,28 +1290,144 @@ class _TeamSurface extends StatelessWidget {
final Widget child;
final double width;
@override
- Widget build(BuildContext context) => Dialog(
- elevation: 0,
- insetPadding: const EdgeInsets.all(20),
- backgroundColor: Colors.transparent,
- child: SizedBox(
- width: width,
- child: Material(
- color: terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- ).background,
- shape: RoundedRectangleBorder(
- side: terminalPaneBorder(focused: true),
- borderRadius: BorderRadius.circular(kTerminalCornerRadius),
- ),
- clipBehavior: Clip.antiAlias,
- child: child,
+ Widget build(BuildContext context) => DesktopChrome(
+ child: Dialog(
+ elevation: 0,
+ insetPadding: const EdgeInsets.all(16),
+ backgroundColor: Colors.transparent,
+ child: SizedBox(
+ width: width,
+ child: DesktopDialogSurface(child: child),
),
),
);
}
+class _TeamRow extends StatelessWidget {
+ const _TeamRow({
+ super.key,
+ required this.label,
+ required this.onPressed,
+ this.detail,
+ this.trailing,
+ this.selected = false,
+ this.checked,
+ this.semanticLabel,
+ });
+ final String label;
+ final String? detail, trailing, semanticLabel;
+ final VoidCallback? onPressed;
+ final bool selected;
+ final bool? checked;
+
+ @override
+ Widget build(BuildContext context) {
+ final highContrast = MediaQuery.highContrastOf(context);
+ return Semantics(
+ selected: selected,
+ checked: checked,
+ label: semanticLabel,
+ child: TextButton(
+ onPressed: onPressed,
+ style:
+ TextButton.styleFrom(
+ foregroundColor: DesktopChrome.foreground,
+ disabledForegroundColor: DesktopChrome.muted,
+ backgroundColor: selected
+ ? DesktopChrome.selection
+ : Colors.transparent,
+ minimumSize: const Size(0, 32),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ textStyle: DesktopChrome.control(),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ ),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ splashFactory: NoSplash.splashFactory,
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? (highContrast
+ ? DesktopChrome.accent
+ : DesktopChrome.focusRing)
+ : Colors.transparent,
+ ),
+ ),
+ overlayColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? Colors.transparent
+ : states.contains(WidgetState.pressed)
+ ? DesktopChrome.foreground.withValues(alpha: .12)
+ : states.contains(WidgetState.hovered)
+ ? DesktopChrome.foreground.withValues(alpha: .06)
+ : Colors.transparent,
+ ),
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (checked != null) ...[
+ ExcludeSemantics(
+ child: ExcludeFocus(
+ child: IgnorePointer(
+ child: SizedBox(
+ width: 20,
+ height: 20,
+ child: Checkbox(
+ value: checked,
+ onChanged: onPressed == null ? null : (_) {},
+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ visualDensity: VisualDensity.compact,
+ ),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ ],
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Tooltip(
+ message: label,
+ child: Text(
+ label,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ if (detail != null && detail!.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(
+ detail!,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
+ if (trailing != null && trailing!.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(trailing!, style: DesktopChrome.metadata()),
+ ],
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
class _TeamChoice extends StatefulWidget {
const _TeamChoice({required this.title, required this.choices});
final String title;
@@ -1241,95 +1439,81 @@ class _TeamChoice extends StatefulWidget {
class _TeamChoiceState extends State<_TeamChoice> {
int _index = 0;
final _scroll = ScrollController();
+ final _rows = <String, GlobalKey>{};
@override
void dispose() {
_scroll.dispose();
super.dispose();
}
- @override
- Widget build(BuildContext context) {
- final cell = terminalCellSizeOf(context), style = terminalContentStyle();
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
+ void _move(int delta) {
+ setState(
+ () => _index = (_index + delta).clamp(
+ 0,
+ math.max(0, widget.choices.length - 1),
+ ),
);
- void move(int delta) {
- setState(
- () => _index = (_index + delta).clamp(
- 0,
- math.max(0, widget.choices.length - 1),
- ),
- );
- if (_scroll.hasClients) {
- final top = _index * cell.height;
- final bottom = top + cell.height;
- final offset = top < _scroll.offset
- ? top
- : bottom > _scroll.offset + _scroll.position.viewportDimension
- ? bottom - _scroll.position.viewportDimension
- : _scroll.offset;
- _scroll.jumpTo(offset.clamp(0, _scroll.position.maxScrollExtent));
- }
- }
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || widget.choices.isEmpty) return;
+ final row = _rows[widget.choices[_index].id]?.currentContext;
+ if (row != null) Scrollable.ensureVisible(row);
+ });
+ }
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
return TerminalPromptKeys(
cancel: () => Navigator.pop(context),
- previous: () => move(-1),
- next: () => move(1),
+ previous: () => _move(-1),
+ next: () => _move(1),
accept: () {
if (widget.choices.isNotEmpty) {
Navigator.pop(context, widget.choices[_index].id);
}
},
child: _TeamSurface(
- width: 660,
+ width: 480,
child: Padding(
- padding: EdgeInsets.all(cell.width * 2),
+ padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Text(
- widget.title,
- style: style.copyWith(color: theme.foreground),
+ Row(
+ children: [
+ Expanded(
+ child: Text(widget.title, style: DesktopChrome.heading()),
+ ),
+ const SizedBox(width: 8),
+ IconButton(
+ tooltip: 'Close chooser',
+ onPressed: () => Navigator.pop(context),
+ icon: const Icon(AppIcons.close, size: 18),
+ ),
+ ],
),
- SizedBox(height: cell.height),
+ const SizedBox(height: 16),
Flexible(
- child: ListView(
+ child: SingleChildScrollView(
controller: _scroll,
- shrinkWrap: true,
- children: [
- for (var i = 0; i < widget.choices.length; i++)
- SizedBox(
- height: cell.height,
- child: TextButton(
- style: TextButton.styleFrom(
- textStyle: style,
- foregroundColor: theme.foreground,
- backgroundColor: i == _index
- ? theme.selection
- : Colors.transparent,
- minimumSize: Size.zero,
- padding: EdgeInsets.symmetric(
- horizontal: cell.width,
- ),
- shape: const RoundedRectangleBorder(),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (var i = 0; i < widget.choices.length; i++)
+ _TeamRow(
+ key: _rows.putIfAbsent(
+ widget.choices[i].id,
+ GlobalKey.new,
),
+ label: widget.choices[i].label,
+ detail: widget.choices[i].detail,
+ selected: i == _index,
onPressed: () =>
Navigator.pop(context, widget.choices[i].id),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- '${widget.choices[i].label} ${widget.choices[i].detail}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
),
- ),
- ],
+ ],
+ ),
),
),
],
diff --git a/desktop/lib/web/picker/web_picker_bar.dart b/desktop/lib/web/picker/web_picker_bar.dart
index 0706f63d8..d792156fc 100644
--- a/desktop/lib/web/picker/web_picker_bar.dart
+++ b/desktop/lib/web/picker/web_picker_bar.dart
@@ -22,13 +22,8 @@ class WebPickerBar extends StatelessWidget {
listenable: search,
builder: (context, _) => Padding(
key: const ValueKey('web-picker-bar'),
- // Four cells in, like the input and the result titles under it.
- padding: EdgeInsets.fromLTRB(
- cell.width * 4,
- cell.height * .5,
- cell.width,
- 0,
- ),
+ // Align the host scopes with the shared search editor text.
+ padding: EdgeInsets.fromLTRB(57, cell.height * .5, cell.width, 0),
child: Row(
children: [
if (search.canGoBack) ...[
diff --git a/desktop/lib/web/tabs/web_tab_switcher.dart b/desktop/lib/web/tabs/web_tab_switcher.dart
index b060f8a58..4b20ab88e 100644
--- a/desktop/lib/web/tabs/web_tab_switcher.dart
+++ b/desktop/lib/web/tabs/web_tab_switcher.dart
@@ -101,8 +101,8 @@ class WebTabSwitcher extends StatelessWidget {
TerminalTheme theme,
) => WorkspaceBarControl(
key: const ValueKey('web-new-tab-button'),
- label: 'New Swarm',
- tooltip: 'New Swarm',
+ label: 'New Tab',
+ tooltip: 'New Tab',
foreground: theme.foreground,
onPressed: enabled && commands.canRun('swarm.new')
? () => commands.run('swarm.new')
diff --git a/desktop/lib/widgets/add_phone_dialog.dart b/desktop/lib/widgets/add_phone_dialog.dart
index e3ada0840..c33e1487e 100644
--- a/desktop/lib/widgets/add_phone_dialog.dart
+++ b/desktop/lib/widgets/add_phone_dialog.dart
@@ -6,19 +6,15 @@ import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:qr/qr.dart';
-import 'package:xterm/xterm.dart' show TerminalTheme;
import '../api/api_client.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
import '../ws/ws_conn.dart' show WsRequestFailure, WsRequestTimeout;
-import '../terminal/terminal_text.dart';
-import '../terminal/terminal_theme.dart';
-import '../terminal/terminal_theme_store.dart';
-import 'box_chrome.dart';
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
import 'terminal_prompt.dart';
-import 'terminal_text_action.dart';
/// Harness ▸ Add Phone… — a QR the phone scans to sign in to this account AND
/// pair with this computer, end to end encrypted, with no password typed.
@@ -554,78 +550,37 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
void _close() => Navigator.of(context).maybePop();
- TerminalTheme get _theme =>
- terminalThemeFor(grid.AppTheme.palette.value, terminalThemeStore.value);
- Color get _faint => _theme.muted;
- TextStyle _ink([Color? color]) =>
- terminalContentStyle(color: color ?? _theme.foreground);
+ Color get _faint => DesktopChrome.muted;
+ TextStyle _ink([Color? color]) => DesktopChrome.text(color: color);
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
- // Live font and colour changes reach an open dialog too — see the dialog
- // guide, design/terminal-dialogs.md.
- return ListenableBuilder(
- listenable: Listenable.merge([
- terminalFontStore,
- terminalThemeStore,
- grid.AppTheme.palette,
- ]),
- builder: (context, _) => _dialog(context),
- );
+ grid.AppTheme.watch(context);
+ return _dialog(context);
}
Widget _dialog(BuildContext context) {
- // The grid: margins in whole character columns, spacing in whole rows.
- final cell = terminalCellSizeOf(context);
- final margin = cell.width * 2;
- final row = cell.height;
- // The window is the QR and one line: 240 points — a phone camera reads that
- // from across a desk — in a whole number of rows, so the line under it stays
- // on the grid, and the window just wider than the code.
- final qrSide = (240 / row).ceil() * row;
- final width = math.min(
- qrSide + margin * 4,
- MediaQuery.sizeOf(context).width - 32,
- );
return TerminalPromptKeys(
cancel: _close,
- child: Dialog(
- insetPadding: const EdgeInsets.all(16),
- elevation: 0,
- backgroundColor: Colors.transparent,
- child: SizedBox(
- width: width,
- child: Material(
- elevation: 0,
- color: _theme.background,
- surfaceTintColor: Colors.transparent,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(kTerminalCornerRadius),
- side: terminalPaneBorder(focused: true),
- ),
- clipBehavior: Clip.antiAlias,
- child: DefaultTextStyle.merge(
- style: _ink(),
- child: SingleChildScrollView(
- padding: EdgeInsets.fromLTRB(margin, row, margin, row),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- 'Add your phone',
- textAlign: TextAlign.center,
- style: _ink(),
- ),
- SizedBox(height: row),
- ..._body(qrSide, row),
- ],
+ child: DesktopPromptSurface(
+ width: 440,
+ body: LayoutBuilder(
+ builder: (context, constraints) => DesktopPromptScrollBody(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Semantics(
+ header: true,
+ child: Text('Add your phone', style: DesktopChrome.heading()),
),
- ),
+ const SizedBox(height: 24),
+ ..._body(math.min(240, constraints.maxWidth), 16),
+ ],
),
),
),
+ actions: [TextButton(onPressed: _close, child: const Text('Done'))],
),
);
}
@@ -641,12 +596,12 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
Text('Connect a computer to add your phone.', style: _ink()),
if (widget.onConnectMachine case final connect?) ...[
SizedBox(height: row),
- TerminalTextAction(
- label: 'Connect a machine',
+ TextButton(
onPressed: () {
Navigator.of(context).pop();
connect();
},
+ child: const Text('Connect a machine'),
),
],
];
@@ -662,7 +617,16 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
}
// A moment's wait for the sign-in code, in the QR's own space: a QR that
// changed right after it appeared would be one scanned without it.
- if (!_signInAsked) return [SizedBox(height: qrSide + row * 2)];
+ if (!_signInAsked) {
+ return [
+ SizedBox(
+ height: qrSide + row * 2,
+ child: Center(
+ child: Text('Preparing your code…', style: _ink(_faint)),
+ ),
+ ),
+ ];
+ }
final link = phonePairLink(
email: target.email,
machineId: target.machineId,
@@ -705,17 +669,17 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
Text(
'Paired with this ${_thisComputer()}',
key: const ValueKey('add-phone-devices'),
- style: _ink(_faint),
+ style: DesktopChrome.metadata(),
),
+ const SizedBox(height: 8),
for (final device in shown) _deviceRow(device),
if (more > 0)
Align(
alignment: Alignment.centerLeft,
- child: TerminalTextAction(
+ child: TextButton(
key: const ValueKey('add-phone-more-devices'),
- label: '+ $more more',
- padding: EdgeInsets.zero,
onPressed: () => setState(() => _allDevices = true),
+ child: Text('Show $more more'),
),
),
];
@@ -723,37 +687,49 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
Widget _deviceRow(PairedDevice device) {
final removing = _removing.contains(device.fingerprint);
- return Row(
+ return Padding(
key: ValueKey('add-phone-device-${device.fingerprint}'),
- children: [
- Expanded(
- child: Text(
- device.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: _ink(),
+ padding: const EdgeInsets.symmetric(vertical: 4),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ device.name,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ device.online ? 'Online' : _pairedAgo(device.pairedAt),
+ style: DesktopChrome.metadata(
+ color: device.online ? grid.AppPalette.online : _faint,
+ ),
+ ),
+ ],
+ ),
),
- ),
- Text(
- device.online ? 'online' : _pairedAgo(device.pairedAt),
- style: _ink(device.online ? _theme.green : _faint),
- ),
- TerminalTextAction(
- label: removing ? 'removing…' : 'remove',
- onPressed: removing || widget.removeDevice == null
- ? null
- : () => unawaited(_remove(device)),
- ),
- ],
+ const SizedBox(width: 8),
+ TextButton(
+ onPressed: removing || widget.removeDevice == null
+ ? null
+ : () => unawaited(_remove(device)),
+ child: Text(removing ? 'Removing…' : 'Remove'),
+ ),
+ ],
+ ),
);
}
Widget _status() {
final connected = _connected;
final (text, color) = connected != null
- ? ('✓ Connected $connected', _theme.green)
+ ? ('✓ Connected $connected', grid.AppPalette.online)
: _message != null
- ? (_message!, _theme.red)
+ ? (_message!, Theme.of(context).colorScheme.error)
: ('Scan with Harness on your iPhone', _faint);
return Semantics(
liveRegion: true,
diff --git a/desktop/lib/widgets/agent_action_icons.dart b/desktop/lib/widgets/agent_action_icons.dart
index f70cd7f2b..33498f503 100644
--- a/desktop/lib/widgets/agent_action_icons.dart
+++ b/desktop/lib/widgets/agent_action_icons.dart
@@ -1,8 +1,8 @@
-import 'package:lucide_icons_flutter/lucide_icons.dart';
+import '../shared/theme/app_icons.dart';
/// Agent actions use + to create and ↗ to open. Search fields keep their lens.
/// The native menu/titlebar match these with `plus` and `arrow.up.right`.
abstract final class AgentActionIcons {
- static const create = LucideIcons.plus300;
- static const open = LucideIcons.arrowUpRight300;
+ static const create = AppIcons.plus;
+ static const open = AppIcons.arrowUpRight;
}
diff --git a/desktop/lib/widgets/agent_alert_banners.dart b/desktop/lib/widgets/agent_alert_banners.dart
index f5e3a1b54..95bd4e6ec 100644
--- a/desktop/lib/widgets/agent_alert_banners.dart
+++ b/desktop/lib/widgets/agent_alert_banners.dart
@@ -1,5 +1,7 @@
library;
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../notify/agent_alerts.dart';
@@ -132,7 +134,7 @@ class _Banner extends StatelessWidget {
// navigation.
IconButton(
key: const Key('agent-alert-dismiss'),
- icon: const Icon(Icons.close, size: 14),
+ icon: const Icon(AppIcons.close, size: 14),
color: AppColors.mutedStrong,
splashRadius: 14,
visualDensity: VisualDensity.compact,
diff --git a/desktop/lib/widgets/agent_drag.dart b/desktop/lib/widgets/agent_drag.dart
index 9d898a8fc..3b34c2dd4 100644
--- a/desktop/lib/widgets/agent_drag.dart
+++ b/desktop/lib/widgets/agent_drag.dart
@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
+import '../shared/theme/app_icons.dart';
+
import '../shared/theme/app_theme.dart' as grid;
import '../shortcuts/app_keymap.dart';
import '../shared/theme/workspace_bar_style.dart';
@@ -75,33 +77,6 @@ final agentDrag = ValueNotifier<AgentDragRef?>(null);
/// a pane drag offers the other tiles to trade places with.
final paneDragging = ValueNotifier<PaneDragRef?>(null);
-/// Hover the whole header to reveal its close action without moving its title.
-class PaneHeaderHoverRegion extends StatefulWidget {
- const PaneHeaderHoverRegion({super.key, required this.child});
- final Widget child;
-
- @override
- State<PaneHeaderHoverRegion> createState() => _PaneHeaderHoverRegionState();
-}
-
-class _PaneHeaderHoverRegionState extends State<PaneHeaderHoverRegion> {
- bool _hovered = false;
- @override
- Widget build(BuildContext context) => MouseRegion(
- onEnter: (_) => setState(() => _hovered = true),
- onExit: (_) => setState(() => _hovered = false),
- child: _PaneHeaderHover(hovered: _hovered, child: widget.child),
- );
-}
-
-class _PaneHeaderHover extends InheritedWidget {
- const _PaneHeaderHover({required this.hovered, required super.child});
- final bool hovered;
- @override
- bool updateShouldNotify(_PaneHeaderHover oldWidget) =>
- hovered != oldWidget.hovered;
-}
-
class PaneCloseButton extends StatelessWidget {
const PaneCloseButton({super.key, required this.onPressed});
@@ -115,30 +90,27 @@ class PaneCloseButton extends StatelessWidget {
terminalThemeStore.value,
);
final hint = KeymapTheme.of(context)?.hint('pane.close');
- return Visibility(
- visible:
- context
- .dependOnInheritedWidgetOfExactType<_PaneHeaderHover>()
- ?.hovered ??
- true,
- maintainState: true,
- maintainAnimation: true,
- maintainSize: true,
- child: WorkspaceBarControl(
- label: 'Close Pane',
- tooltip: [
- 'Close Pane',
- if (hint != null && hint.isNotEmpty) hint,
- ].join(' · '),
- foreground: theme.foreground,
- onPressed: onPressed,
- builder: (context, emphasized) => SizedBox(
- width: workspaceBarCellSizeOf(context).width * 3,
- height: workspaceBarControlHeight(context),
- child: Center(
- child: Text(
- 'x',
- style: workspaceBarTextStyle(emphasized: emphasized),
+ return WorkspaceBarControl(
+ label: 'Close Pane',
+ tooltip: [
+ 'Close Pane',
+ if (hint != null && hint.isNotEmpty) hint,
+ ].join(' · '),
+ foreground: theme.foreground,
+ onPressed: onPressed,
+ builder: (context, emphasized) => SizedBox(
+ width: workspaceBarCellSizeOf(context).width * 3,
+ height: workspaceBarControlHeight(context),
+ child: Center(
+ child: Icon(
+ AppIcons.close,
+ size: AppIcons.closeSize,
+ color: theme.foreground.withValues(
+ alpha: emphasized
+ ? 1
+ : MediaQuery.highContrastOf(context)
+ ? .7
+ : .45,
),
),
),
diff --git a/desktop/lib/widgets/agent_picker.dart b/desktop/lib/widgets/agent_picker.dart
index 98a183ad6..4732022c2 100644
--- a/desktop/lib/widgets/agent_picker.dart
+++ b/desktop/lib/widgets/agent_picker.dart
@@ -1,5 +1,6 @@
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -433,7 +434,7 @@ class _AgentPickerState extends State<AgentPicker> {
),
)
: Icon(
- Icons.search,
+ AppIcons.search,
size: _fontSize + 4,
color: boxText(.60),
),
@@ -442,7 +443,7 @@ class _AgentPickerState extends State<AgentPicker> {
Padding(
padding: const EdgeInsets.only(left: 12, right: 22),
child: Icon(
- Icons.keyboard_arrow_down,
+ AppIcons.chevronDown,
size: 22,
color: boxText(.60),
),
@@ -872,7 +873,7 @@ class _AgentPickerState extends State<AgentPicker> {
),
)
: current
- ? Icon(Icons.check, size: 16, color: boxText(.60))
+ ? Icon(AppIcons.check, size: 16, color: boxText(.60))
: null,
onTap: () => _choose(choice),
),
diff --git a/desktop/lib/widgets/api_picker_form.dart b/desktop/lib/widgets/api_picker_form.dart
index edab3f786..ea24cea0c 100644
--- a/desktop/lib/widgets/api_picker_form.dart
+++ b/desktop/lib/widgets/api_picker_form.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
@@ -12,6 +13,7 @@ import '../terminal/terminal_text.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
import 'box_chrome.dart' show ReadlineKeys;
+import 'desktop_chrome.dart';
import 'terminal_text_action.dart';
/// API setup uses the same preview, keymap, and controller as the model list.
@@ -45,6 +47,7 @@ class ApiPickerFormState extends State<ApiPickerForm> {
ApiConnection? _editing;
bool _advanced = false, _visible = false;
String? _error;
+ bool _desktop = false;
/// The field [_error] is about, drawn under it; null for an error about the whole form.
String? _errorField;
@@ -73,6 +76,12 @@ class ApiPickerFormState extends State<ApiPickerForm> {
focus();
}
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _desktop = DesktopChrome.of(context);
+ }
+
void _setConnection(ApiConnection connection) {
final preset = controller.presets
.where((row) => row.provider == connection.provider)
@@ -195,11 +204,26 @@ class ApiPickerFormState extends State<ApiPickerForm> {
List<FocusNode> get _nodes => [
for (final id in _visibleFields) _inputs[id]!,
- for (final action in _actions)
+ for (final action in [
+ for (final action in _actions)
+ if (!_fixedAction(action.id)) action,
+ ..._fixedActions,
+ ])
if (action.run != null && _buttons[action.id] != null)
_buttons[action.id]!,
];
+ bool _fixedAction(String id) =>
+ _desktop &&
+ _editing != null &&
+ const {'save', 'delete', 'cancel'}.contains(id);
+
+ List<({String id, String label, VoidCallback? run})> get _fixedActions => [
+ for (final id in ['cancel', 'save', 'delete'])
+ for (final action in _actions)
+ if (_fixedAction(action.id) && action.id == id) action,
+ ];
+
FocusNode get _focusTarget =>
(widget.removing ? _buttons['cancel'] : _nodes.firstOrNull) ?? _scope;
@@ -233,6 +257,23 @@ class ApiPickerFormState extends State<ApiPickerForm> {
/// other pane; Shift-Tab walks back, leaving from the first field. With no fields (the provider
/// choices), Tab leaves at once — the picker's usual pane switch.
void _tab(bool forward) {
+ if (_composing) return;
+ if (DesktopChrome.of(context)) {
+ final nodes = _nodes;
+ final current = nodes.indexWhere((node) => node.hasFocus);
+ final next = current + (forward ? 1 : -1);
+ if (next >= 0 && next < nodes.length) {
+ nodes[next].requestFocus();
+ if (nodes[next].context case final context?) {
+ Scrollable.ensureVisible(context);
+ }
+ } else if (widget.onSwitchPane != null) {
+ widget.onSwitchPane!();
+ } else {
+ _move(forward);
+ }
+ return;
+ }
final fields = [for (final id in _visibleFields) _inputs[id]!];
final at = fields.indexWhere((node) => node.hasFocus);
final onButtons = _buttons.values.any((node) => node.hasFocus);
@@ -419,19 +460,112 @@ class ApiPickerFormState extends State<ApiPickerForm> {
);
}
+ Widget _actionButton(({String id, String label, VoidCallback? run}) action) {
+ final node = _buttons.putIfAbsent(
+ action.id,
+ () => FocusNode(debugLabel: action.label),
+ );
+ if (!DesktopChrome.of(context)) {
+ return TerminalTextAction(
+ key: ValueKey('api-form:${action.id}'),
+ label: action.label,
+ padding: EdgeInsets.zero,
+ focusNode: node,
+ onPressed: action.run,
+ );
+ }
+ if (action.id == 'save' || action.id == 'delete') {
+ return FilledButton(
+ key: ValueKey('api-form:${action.id}'),
+ focusNode: node,
+ onPressed: action.run,
+ style: action.id == 'delete'
+ ? FilledButton.styleFrom(
+ backgroundColor: Theme.of(context).colorScheme.error,
+ foregroundColor: Theme.of(context).colorScheme.onError,
+ )
+ : null,
+ child: Text(action.label),
+ );
+ }
+ if (action.id.startsWith('provider:')) {
+ return TextButton(
+ key: ValueKey('api-form:${action.id}'),
+ focusNode: node,
+ onPressed: action.run,
+ style:
+ TextButton.styleFrom(
+ foregroundColor: DesktopChrome.foreground,
+ backgroundColor: DesktopChrome.field,
+ textStyle: DesktopChrome.text(size: 13),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),
+ ),
+ splashFactory: NoSplash.splashFactory,
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ color: states.contains(WidgetState.focused)
+ ? DesktopChrome.focusRing
+ : DesktopChrome.rim,
+ width: grid.AppDesktop.focusWidth,
+ ),
+ ),
+ ),
+ child: Row(
+ children: [
+ Icon(AppIcons.cloud, size: 16, color: DesktopChrome.muted),
+ const SizedBox(width: 10),
+ Expanded(child: Text(action.label)),
+ Icon(AppIcons.chevronRight, size: 17, color: DesktopChrome.muted),
+ ],
+ ),
+ );
+ }
+ return DesktopPill(
+ key: ValueKey('api-form:${action.id}'),
+ label: action.id == 'visibility'
+ ? _visible
+ ? 'Hide key'
+ : 'Show key'
+ : action.id == 'options'
+ ? _advanced
+ ? 'Hide options'
+ : 'More options'
+ : action.label,
+ selected: action.id == 'options' ? _advanced : null,
+ compact: true,
+ focusNode: node,
+ foregroundColor: action.id == 'delete'
+ ? Theme.of(context).colorScheme.error
+ : null,
+ onPressed: action.run,
+ );
+ }
+
@override
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
grid.AppTheme.watch(context);
- final cell = terminalCellSizeOf(context);
+ final desktop = DesktopChrome.of(context);
+ final cell = desktop ? const Size(9, 14) : terminalCellSizeOf(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
- final style = terminalContentStyle(color: theme.foreground);
- final muted = terminalContentStyle(
- color: theme.muted,
- );
+ final style = desktop
+ ? DesktopChrome.text(size: 13)
+ : terminalContentStyle(color: theme.foreground);
+ final muted = desktop
+ ? DesktopChrome.text(size: 12, color: DesktopChrome.muted)
+ : terminalContentStyle(color: theme.muted);
+ final errorStyle = desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: Theme.of(context).colorScheme.error,
+ )
+ : terminalContentStyle(color: theme.yellow);
return ListenableBuilder(
listenable: controller,
builder: (context, _) => _keys(
@@ -464,8 +598,8 @@ class ApiPickerFormState extends State<ApiPickerForm> {
Text(
widget.removing
? 'Delete ${_editing?.name ?? 'API'}?'
- : _editing?.name ?? 'Add API',
- style: style,
+ : _editing?.name ?? 'Add API connection',
+ style: desktop ? DesktopChrome.heading() : style,
),
if (controller.app.viewer != null)
Text('Saved on ${controller.hostLabel}', style: muted),
@@ -498,6 +632,7 @@ class ApiPickerFormState extends State<ApiPickerForm> {
'prefix' => 'Key prefix',
_ => 'Name',
}, style: muted),
+ if (desktop) const SizedBox(height: 6),
ReadlineKeys(
controller: _fields[id]!,
enabled: !controller.saving,
@@ -516,18 +651,56 @@ class ApiPickerFormState extends State<ApiPickerForm> {
autocorrect: false,
enableSuggestions: false,
style: style,
- cursorColor: theme.foreground,
+ cursorColor: desktop
+ ? DesktopChrome.accent
+ : theme.foreground,
cursorWidth: 2,
- decoration: const InputDecoration(
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- filled: false,
- isDense: true,
- isCollapsed: true,
- constraints: BoxConstraints(),
- contentPadding: EdgeInsets.zero,
- ),
+ decoration: desktop
+ ? InputDecoration(
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(
+ color: DesktopChrome.rim,
+ ),
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(
+ color: DesktopChrome.rim,
+ ),
+ ),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(
+ color: DesktopChrome.focusRing,
+ width: grid.AppDesktop.focusWidth,
+ ),
+ ),
+ filled: true,
+ fillColor: DesktopChrome.field,
+ isDense: true,
+ contentPadding:
+ const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 10,
+ ),
+ )
+ : const InputDecoration(
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ filled: false,
+ isDense: true,
+ isCollapsed: true,
+ constraints: BoxConstraints(),
+ contentPadding: EdgeInsets.zero,
+ ),
onEditingComplete: () {},
onChanged: (_) {
if (_error != null) {
@@ -542,9 +715,7 @@ class ApiPickerFormState extends State<ApiPickerForm> {
Text(
_error!,
key: ValueKey('api-form-error:$id'),
- style: terminalContentStyle(
- color: theme.yellow,
- ),
+ style: errorStyle,
),
],
),
@@ -559,10 +730,7 @@ class ApiPickerFormState extends State<ApiPickerForm> {
if ((_errorField == null ? _error : null) ??
controller.error
case final error?) ...[
- Text(
- error,
- style: terminalContentStyle(color: theme.yellow),
- ),
+ Text(error, style: errorStyle),
SizedBox(height: cell.height),
],
if (controller.saving) ...[
@@ -570,32 +738,53 @@ class ApiPickerFormState extends State<ApiPickerForm> {
SizedBox(height: cell.height),
],
_keys(
- Wrap(
- direction: _editing == null
- ? Axis.vertical
- : Axis.horizontal,
- spacing: cell.width * 2,
- runSpacing: cell.height,
- children: [
- for (final action in _actions)
- TerminalTextAction(
- key: ValueKey('api-form:${action.id}'),
- label: action.label,
- padding: EdgeInsets.zero,
- focusNode: _buttons.putIfAbsent(
- action.id,
- () => FocusNode(debugLabel: action.label),
- ),
- onPressed: action.run,
+ desktop && _editing == null
+ ? Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final action in _actions)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: _actionButton(action),
+ ),
+ ],
+ )
+ : Wrap(
+ direction: _editing == null
+ ? Axis.vertical
+ : Axis.horizontal,
+ spacing: desktop ? 8 : cell.width * 2,
+ runSpacing: desktop ? 8 : cell.height,
+ children: [
+ for (final action in _actions)
+ if (!_fixedAction(action.id))
+ _actionButton(action),
+ ],
),
- ],
- ),
buttons: true,
),
],
),
),
),
+ if (_fixedActions.isNotEmpty) ...[
+ Divider(height: 1, color: DesktopChrome.rim),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
+ child: _keys(
+ Wrap(
+ alignment: WrapAlignment.end,
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ for (final action in _fixedActions)
+ _actionButton(action),
+ ],
+ ),
+ buttons: true,
+ ),
+ ),
+ ],
Padding(
padding: EdgeInsets.symmetric(
horizontal: cell.width * 2,
@@ -610,7 +799,9 @@ class ApiPickerFormState extends State<ApiPickerForm> {
),
(
'picker.complete',
- widget.onSwitchPane == null || _visibleFields.isNotEmpty
+ desktop ||
+ widget.onSwitchPane == null ||
+ _visibleFields.isNotEmpty
? 'next'
: 'pane',
),
@@ -624,7 +815,7 @@ class ApiPickerFormState extends State<ApiPickerForm> {
case final hint?)
'${hint.replaceAll('⇥', 'Tab').replaceAll('↵', 'Enter')} $label',
].join(' · '),
- style: muted,
+ style: desktop ? DesktopChrome.metadata() : muted,
),
),
],
diff --git a/desktop/lib/widgets/bootstrapping_screen.dart b/desktop/lib/widgets/bootstrapping_screen.dart
index 014f2bdd9..7fa7e3712 100644
--- a/desktop/lib/widgets/bootstrapping_screen.dart
+++ b/desktop/lib/widgets/bootstrapping_screen.dart
@@ -1,26 +1,19 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
-import 'box_chrome.dart';
-import 'terminal_progress.dart';
+import 'desktop_chrome.dart';
/// The bridge between opening Harness and reaching the workspace.
///
-/// Printed as a session, not as a screen: a prompt line, then each thing the
-/// app does as its own line, the way `harness start` would say it in a shell.
-/// The lines behind the current one stay on screen and dim, because that is
-/// what a terminal does with what it has already said — and it is the whole
-/// difference between "something is happening" and a spinner (owner,
-/// 2026-09-23). Everything is the terminal's face at the terminal's size.
-///
-/// Bootstrap cannot count what it is doing, so the bar carries a travelling
-/// block and prints no figure rather than inventing one.
+/// Current and recent messages come from bootstrap itself. Startup has no
+/// measurable total, so its activity indicator never invents a percentage.
class BootstrappingScreen extends StatefulWidget {
const BootstrappingScreen({super.key, this.statusMessage});
final String? statusMessage;
- static const double _boxWidth = 470;
+ static const double _contentWidth = 470;
static const String _fallbackStatus = 'Opening Harness…';
@override
@@ -28,92 +21,116 @@ class BootstrappingScreen extends StatefulWidget {
}
class _BootstrappingScreenState extends State<BootstrappingScreen> {
- /// Every status this screen has shown, oldest first. Bounded because a
- /// bootstrap that keeps talking must not grow the box past the window.
- final List<String> _printed = [];
+ /// Every status this screen has shown, oldest first. Keep recent context
+ /// without letting a chatty bootstrap turn into an unbounded history.
+ final List<String> _history = [];
static const _keep = 4;
@override
void initState() {
super.initState();
- _print(widget.statusMessage ?? BootstrappingScreen._fallbackStatus);
+ _rememberStatus(
+ widget.statusMessage ?? BootstrappingScreen._fallbackStatus,
+ );
}
@override
void didUpdateWidget(BootstrappingScreen old) {
super.didUpdateWidget(old);
- _print(widget.statusMessage ?? BootstrappingScreen._fallbackStatus);
+ _rememberStatus(
+ widget.statusMessage ?? BootstrappingScreen._fallbackStatus,
+ );
}
- void _print(String line) {
- if (_printed.isNotEmpty && _printed.last == line) return;
- _printed.add(line);
- if (_printed.length > _keep) _printed.removeAt(0);
+ void _rememberStatus(String message) {
+ if (_history.isNotEmpty && _history.last == message) return;
+ _history.add(message);
+ if (_history.length > _keep) _history.removeAt(0);
}
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
final status = widget.statusMessage ?? BootstrappingScreen._fallbackStatus;
- final earlier = _printed.length > 1
- ? _printed.sublist(0, _printed.length - 1)
+ final earlier = _history.length > 1
+ ? _history.sublist(0, _history.length - 1)
: const <String>[];
+ final indicatorSize = MediaQuery.textScalerOf(context).scale(20);
- return Scaffold(
- backgroundColor: grid.AppPalette.swarmField,
- body: Center(
- child: SingleChildScrollView(
- padding: const EdgeInsets.all(24),
- child: ConstrainedBox(
- constraints: const BoxConstraints(
- maxWidth: BootstrappingScreen._boxWidth,
- ),
- child: TerminalBox(
- child: Padding(
- padding: const EdgeInsets.fromLTRB(16, 14, 16, 14),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- '$kBootPrompt harness start',
- style: boxMonoStyle(weight: FontWeight.w600),
+ return DesktopChrome(
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Center(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: BootstrappingScreen._contentWidth,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Semantics(
+ header: true,
+ child: Text(
+ 'Opening your workspace',
+ style: grid.AppType.title(
+ color: DesktopChrome.foreground,
+ height: 1.3,
+ ),
),
- const SizedBox(height: 8),
- for (final line in earlier) ...[
- Text(line, style: boxMonoStyle(color: kBoxFaint)),
- const SizedBox(height: 1),
- ],
- const SizedBox(height: 1),
- const TerminalProgressLine(),
- const SizedBox(height: 8),
- Semantics(
- key: const Key('boot-status'),
- container: true,
- liveRegion: true,
- label: 'Harness startup status',
- value: status,
- child: ExcludeSemantics(
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Flexible(
- child: Text(
- status,
- key: ValueKey(status),
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(),
- ),
+ ),
+ const SizedBox(height: DesktopChrome.panelPadding),
+ Semantics(
+ key: const Key('boot-status'),
+ container: true,
+ liveRegion: true,
+ label: 'Harness startup status',
+ value: status,
+ child: ExcludeSemantics(
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox.square(
+ dimension: indicatorSize,
+ child: MediaQuery.disableAnimationsOf(context)
+ ? Icon(
+ AppIcons.hourglass,
+ size: indicatorSize,
+ color: DesktopChrome.muted,
+ )
+ : CircularProgressIndicator(
+ strokeWidth: 2,
+ color: DesktopChrome.accent,
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ status,
+ key: ValueKey(status),
+ style: DesktopChrome.text(),
),
- const SizedBox(width: 6),
- const TerminalCursor(),
- ],
- ),
+ ),
+ ],
),
),
+ ),
+ if (earlier.isNotEmpty) ...[
+ const SizedBox(height: DesktopChrome.panelPadding),
+ Divider(height: 1, color: DesktopChrome.rim),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ 'Recent activity',
+ style: DesktopChrome.control(medium: true),
+ ),
+ for (final line in earlier) ...[
+ const SizedBox(height: DesktopChrome.controlGap),
+ Text(line, style: DesktopChrome.metadata()),
+ ],
],
- ),
+ ],
),
),
),
diff --git a/desktop/lib/widgets/box_chrome.dart b/desktop/lib/widgets/box_chrome.dart
index c5eda78c0..a310528b0 100644
--- a/desktop/lib/widgets/box_chrome.dart
+++ b/desktop/lib/widgets/box_chrome.dart
@@ -7,7 +7,7 @@ import '../terminal/terminal_text.dart';
const double kTerminalCornerRadius = 3;
-/// One rim for workspace panes and the dialogs that take their keyboard focus.
+/// A stable rim for the terminal pane, independent of the desktop dialog frame.
BorderSide terminalPaneBorder({bool focused = false}) => BorderSide(
color: focused ? grid.AppPalette.accentOnSurface : grid.AppPalette.divider,
width: 1,
@@ -37,36 +37,48 @@ class PaneOpacity extends InheritedWidget {
bool updateShouldNotify(PaneOpacity old) => old.opacity != opacity;
}
-/// The selected tab joins the workspace with the same small radius used at
-/// its top corners. The bottom curves turn outward, like a browser tab.
-class TerminalTabBorder extends ShapeBorder {
- const TerminalTabBorder({this.radius = kTerminalCornerRadius});
+/// A desktop tab joins its workspace through two outward lower shoulders.
+/// AppKit mirrors these geometry tokens in SwarmTitlebar.swift.
+class DesktopTabBorder extends ShapeBorder {
+ const DesktopTabBorder({
+ this.radius = grid.AppDesktop.tabRadius,
+ this.shoulder = grid.AppDesktop.tabShoulder,
+ this.side = BorderSide.none,
+ });
final double radius;
+ final double shoulder;
+ final BorderSide side;
@override
EdgeInsetsGeometry get dimensions => EdgeInsets.zero;
@override
- ShapeBorder scale(double t) => TerminalTabBorder(radius: radius * t);
+ ShapeBorder scale(double t) => DesktopTabBorder(
+ radius: radius * t,
+ shoulder: shoulder * t,
+ side: side.scale(t),
+ );
@override
Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
- final r = radius.clamp(0.0, rect.shortestSide / 4);
+ final r = radius.clamp(0.0, rect.shortestSide / 2);
+ final s = shoulder.clamp(0.0, rect.shortestSide / 2);
final c = r * .5522847498;
- final left = rect.left + r, right = rect.right - r;
+ final sc = s * .5522847498;
+ final left = rect.left + s, right = rect.right - s;
final top = rect.top, bottom = rect.bottom;
return Path()
..moveTo(rect.left, bottom)
- ..cubicTo(rect.left + c, bottom, left, bottom - r + c, left, bottom - r)
+ ..cubicTo(rect.left + sc, bottom, left, bottom - s + sc, left, bottom - s)
..lineTo(left, top + r)
..cubicTo(left, top + r - c, left + r - c, top, left + r, top)
..lineTo(right - r, top)
..cubicTo(right - r + c, top, right, top + r - c, right, top + r)
- ..lineTo(right, bottom - r)
+ ..lineTo(right, bottom - s)
..cubicTo(
right,
- bottom - r + c,
- rect.right - c,
+ bottom - s + sc,
+ rect.right - sc,
bottom,
rect.right,
bottom,
@@ -79,7 +91,13 @@ class TerminalTabBorder extends ShapeBorder {
getOuterPath(rect, textDirection: textDirection);
@override
- void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {}
+ void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {
+ if (side.style == BorderStyle.none) return;
+ canvas.drawPath(
+ getOuterPath(rect.deflate(side.width / 2), textDirection: textDirection),
+ side.toPaint(),
+ );
+ }
}
/// Box ink at [alpha] for rims, hairlines and washes: white on a dark palette,
@@ -327,9 +345,7 @@ class BoxHintStrip extends StatelessWidget {
alignment: Alignment.centerLeft,
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
- border: Border(
- top: BorderSide(color: boxInk(.08)),
- ),
+ border: Border(top: BorderSide(color: boxInk(.08))),
),
child: Column(
mainAxisSize: MainAxisSize.min,
diff --git a/desktop/lib/widgets/clone_repository_dialog.dart b/desktop/lib/widgets/clone_repository_dialog.dart
index 9c3fb2ffc..dcd92d761 100644
--- a/desktop/lib/widgets/clone_repository_dialog.dart
+++ b/desktop/lib/widgets/clone_repository_dialog.dart
@@ -1,5 +1,7 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import '../core/desktop_window.dart';
@@ -30,18 +32,32 @@ class CloneRepositoryDialog extends StatefulWidget {
class _CloneRepositoryDialogState extends State<CloneRepositoryDialog> {
final _url = TextEditingController();
+ final _inputFocus = FocusNode(debugLabel: 'Clone repository URL');
final _actionFocus = FocusNode(debugLabel: 'Clone repository');
final _errorAnchor = GlobalKey(debugLabel: 'Clone error');
String? _parent, _error;
RepositoryClone? _clone;
bool _picking = false, _closing = false;
bool get _busy => _clone != null;
+ bool get _composing =>
+ _url.value.composing.isValid && !_url.value.composing.isCollapsed;
GitHubRepository? get _repository => GitHubRepository.parse(_url.text);
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent == true) {
+ _inputFocus.requestFocus();
+ }
+ });
+ }
+
@override
void dispose() {
_clone?.cancel();
_url.dispose();
+ _inputFocus.dispose();
_actionFocus.dispose();
super.dispose();
}
@@ -148,7 +164,7 @@ class _CloneRepositoryDialogState extends State<CloneRepositoryDialog> {
// respect PopScope, so an accidental click cannot stop a clone.
DismissIntent: CallbackAction<DismissIntent>(
onInvoke: (_) {
- _cancel();
+ if (!_composing) _cancel();
return null;
},
),
@@ -163,19 +179,28 @@ class _CloneRepositoryDialogState extends State<CloneRepositoryDialog> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const FieldLabel('GitHub repository'),
- TextField(
- key: const ValueKey('clone-repository-url'),
- controller: _url,
- autofocus: true,
- readOnly: _busy,
- style: grid.AppType.mono(
- color: grid.AppPalette.textPrimary,
- ),
- decoration: const InputDecoration(
- hintText: 'https://github.com/owner/repository',
+ Focus(
+ skipTraversal: true,
+ onKeyEvent: (_, event) =>
+ event.logicalKey == LogicalKeyboardKey.escape &&
+ _composing
+ ? KeyEventResult.skipRemainingHandlers
+ : KeyEventResult.ignored,
+ child: TextField(
+ key: const ValueKey('clone-repository-url'),
+ controller: _url,
+ focusNode: _inputFocus,
+ autofocus: true,
+ readOnly: _busy,
+ style: grid.AppType.mono(
+ color: grid.AppPalette.textPrimary,
+ ),
+ decoration: const InputDecoration(
+ hintText: 'https://github.com/owner/repository',
+ ),
+ onChanged: (_) => setState(() => _error = null),
+ onSubmitted: (_) => _submit(),
),
- onChanged: (_) => setState(() => _error = null),
- onSubmitted: (_) => _submit(),
),
const SizedBox(height: 6),
Text(
@@ -186,7 +211,7 @@ class _CloneRepositoryDialogState extends State<CloneRepositoryDialog> {
const FieldLabel('Destination on this computer'),
OutlinedButton.icon(
onPressed: _busy || _picking ? null : _chooseDestination,
- icon: const Icon(Icons.folder_open_outlined, size: 18),
+ icon: const Icon(AppIcons.folderOpen, size: 18),
label: Text(
_parent ?? 'Choose folder…',
maxLines: 2,
diff --git a/desktop/lib/widgets/codex_profile_field.dart b/desktop/lib/widgets/codex_profile_field.dart
index a0eb63417..1c2260bfa 100644
--- a/desktop/lib/widgets/codex_profile_field.dart
+++ b/desktop/lib/widgets/codex_profile_field.dart
@@ -1,9 +1,9 @@
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/terminal/terminal_text.dart';
import '../core/codex_profiles.dart';
@@ -228,7 +228,7 @@ class _CodexProfileFieldState extends State<CodexProfileField> {
SelectOption(
value: refreshValue,
label: 'Refresh profiles',
- leading: () => const Icon(LucideIcons.refreshCw, size: 14),
+ leading: () => const Icon(AppIcons.refreshCw, size: 14),
),
],
onChanged: (value) {
@@ -250,7 +250,7 @@ class _CodexProfileFieldState extends State<CodexProfileField> {
),
const SizedBox(width: 8),
Icon(
- Icons.keyboard_arrow_down,
+ AppIcons.chevronDown,
size: 16,
color: grid.AppPalette.textSecondary,
),
diff --git a/desktop/lib/widgets/daemon_consent.dart b/desktop/lib/widgets/daemon_consent.dart
index 0d6b79299..1bad14a19 100644
--- a/desktop/lib/widgets/daemon_consent.dart
+++ b/desktop/lib/widgets/daemon_consent.dart
@@ -1,8 +1,7 @@
import 'package:flutter/material.dart';
-import 'package:xterm/xterm.dart' show TerminalTheme;
-import '../terminal/terminal_text.dart';
-import 'daemon_slot.dart';
+import '../shared/theme/app_theme.dart';
+import 'desktop_chrome.dart';
/// Where the first-day consent is.
enum DaemonConsentStep {
@@ -52,16 +51,12 @@ class DaemonConsent extends StatefulWidget {
required this.onSuggest,
required this.onKeepWatch,
this.autofocus = true,
- this.ink,
});
final String name;
final DaemonConsentStep step;
final VoidCallback onWatch, onNotNow, onSuggest, onKeepWatch;
final bool autofocus;
- /// The ink it is drawn in (the reveal's stage may be black).
- final Color? ink;
-
@override
State<DaemonConsent> createState() => _DaemonConsentState();
}
@@ -98,51 +93,18 @@ class _DaemonConsentState extends State<DaemonConsent> {
Widget _button(
String key,
String label,
- VoidCallback onPressed,
- TerminalTheme theme,
- TextStyle ink,
- Size cell, {
+ VoidCallback onPressed, {
FocusNode? focusNode,
- Color? color,
- }) => TextButton(
+ }) => DesktopPill(
key: ValueKey(key),
+ label: label,
focusNode: focusNode,
onPressed: onPressed,
- style:
- TextButton.styleFrom(
- minimumSize: Size.zero,
- fixedSize: Size.fromHeight(cell.height),
- padding: EdgeInsets.zero,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- foregroundColor: ink.color,
- shape: const RoundedRectangleBorder(),
- splashFactory: NoSplash.splashFactory,
- ).copyWith(
- overlayColor: WidgetStateProperty.resolveWith(
- (states) =>
- states.any(
- {
- WidgetState.hovered,
- WidgetState.focused,
- WidgetState.pressed,
- }.contains,
- )
- ? theme.selection.withValues(alpha: .5)
- : Colors.transparent,
- ),
- ),
- child: Text(label, style: ink.copyWith(color: color ?? theme.cursor)),
);
@override
Widget build(BuildContext context) {
- final theme = currentTerminalTheme();
- final cell = terminalCellSizeOf(context);
- final fg = widget.ink ?? theme.foreground;
- final ink = terminalContentStyle(
- color: fg,
- ).copyWith(fontFeatures: daemonTextFeatures);
- final muted = ink.copyWith(color: fg.withValues(alpha: .62));
+ AppTheme.watch(context);
final name = widget.name;
if (widget.step == DaemonConsentStep.suggest) {
return Column(
@@ -150,93 +112,79 @@ class _DaemonConsentState extends State<DaemonConsent> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text('Let $name suggest answers?', style: ink),
- SizedBox(height: cell.height / 2),
+ Text('Let $name suggest answers?', style: DesktopChrome.heading()),
+ const SizedBox(height: 12),
Text(
- 'at suggest, $name proposes answers to prompts it can read with '
+ 'At suggest, $name proposes answers to prompts it can read with '
'certainty (reads, tests, builds, in-project edits), and every '
- 'one waits for your key. it never approves a push, rm -rf, sudo, '
+ 'one waits for your key. It never approves a push, rm -rf, sudo, '
'deploy, publish, drop or merge.',
- style: muted,
+ style: DesktopChrome.text(size: 13),
),
- SizedBox(height: cell.height / 2),
+ const SizedBox(height: 12),
Text(
- 'change it any time: its panel, 4:settings.',
- style: muted,
+ 'Change it any time in the daemon’s Settings tab.',
+ style: DesktopChrome.metadata(),
),
- SizedBox(height: cell.height),
+ const SizedBox(height: 20),
Wrap(
- spacing: cell.width * 2,
+ spacing: 8,
+ runSpacing: 8,
children: [
_button(
'daemon-consent-suggest-yes',
- '[ Let $name suggest ]',
+ 'Let $name suggest',
widget.onSuggest,
- theme,
- ink,
- cell,
focusNode: _yes,
- color: theme.green,
),
_button(
'daemon-consent-keep-watch',
- '[ Keep it at watch ]',
+ 'Keep it at watch',
widget.onKeepWatch,
- theme,
- ink,
- cell,
),
],
),
],
);
}
- final label = cell.width * 8;
return Column(
key: const ValueKey('daemon-consent'),
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text('What $name sees', style: ink),
- SizedBox(height: cell.height / 2),
+ Text('What $name sees', style: DesktopChrome.heading()),
+ const SizedBox(height: 16),
for (final (what, words) in daemonConsentRows(name))
Padding(
- padding: EdgeInsets.only(bottom: cell.height / 4),
- child: Row(
+ padding: const EdgeInsets.only(bottom: 16),
+ child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- SizedBox(width: label, child: Text(what, style: ink)),
- Expanded(child: Text(words, style: muted)),
+ Text(
+ '${what[0].toUpperCase()}${what.substring(1)}',
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: 4),
+ Text(words, style: DesktopChrome.text(size: 13)),
],
),
),
- SizedBox(height: cell.height / 2),
Text(
- 'nothing is watched until you say yes.',
- style: muted,
+ 'Nothing is watched until you say yes.',
+ style: DesktopChrome.metadata(),
),
- SizedBox(height: cell.height),
+ const SizedBox(height: 20),
Wrap(
- spacing: cell.width * 2,
+ spacing: 8,
+ runSpacing: 8,
children: [
_button(
'daemon-consent-watch',
- '[ Let $name watch ]',
+ 'Let $name watch',
widget.onWatch,
- theme,
- ink,
- cell,
focusNode: _yes,
- color: theme.green,
- ),
- _button(
- 'daemon-consent-not-now',
- '[ Not now ]',
- widget.onNotNow,
- theme,
- ink,
- cell,
),
+ _button('daemon-consent-not-now', 'Not now', widget.onNotNow),
],
),
],
diff --git a/desktop/lib/widgets/daemon_hatch.dart b/desktop/lib/widgets/daemon_hatch.dart
index d6490b46f..e48ac1321 100644
--- a/desktop/lib/widgets/daemon_hatch.dart
+++ b/desktop/lib/widgets/daemon_hatch.dart
@@ -16,7 +16,7 @@ import '../daemons/zoo.dart';
import '../shared/theme/app_theme.dart';
import '../terminal/terminal_text.dart';
import '../terminal/terminal_theme_store.dart';
-import 'box_chrome.dart';
+import 'desktop_chrome.dart';
import 'daemon_consent.dart';
import 'daemon_portrait.dart';
import 'daemon_illustration.dart';
@@ -803,14 +803,13 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
]),
builder: (context, _) {
final theme = currentTerminalTheme();
- final cell = terminalCellSizeOf(context);
final pitch = _pitch;
- final background = pitch ? daemonPitch : theme.background;
// On the black stage the ink is light, whatever the theme.
final fg = pitch ? const Color(0xffd0d0d0) : theme.foreground;
- final ink = terminalContentStyle(color: fg)
- .copyWith(fontFeatures: daemonTextFeatures);
- final muted = fg.withValues(alpha: .6);
+ final ink = terminalContentStyle(color: fg).copyWith(
+ fontFeatures: daemonTextFeatures,
+ fontWeight: FontWeight.normal,
+ );
return CallbackShortcuts(
bindings: {const SingleActivator(LogicalKeyboardKey.escape): _escape},
child: Focus(
@@ -822,26 +821,31 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
label: 'Hatching',
child: Material(
key: const ValueKey('daemon-hatch'),
- color: background,
+ color: DesktopChrome.surface,
shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(kTerminalCornerRadius),
- side: terminalPaneBorder(focused: true),
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.dialogRadius,
+ ),
+ side: BorderSide(
+ color: MediaQuery.highContrastOf(context)
+ ? DesktopChrome.foreground.withValues(alpha: .6)
+ : DesktopChrome.rim,
+ ),
),
clipBehavior: Clip.antiAlias,
child: SingleChildScrollView(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height,
- ),
+ padding: const EdgeInsets.all(24),
// A steady stage: the egg, the hatchling standing in it
// and the banner all fit, so the reveal never jumps before
// the card.
child: ConstrainedBox(
- constraints: BoxConstraints(minHeight: 390),
+ constraints: BoxConstraints(
+ minHeight: _stage.index < HatchStage.card.index ? 390 : 0,
+ ),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
- children: _children(theme, cell, ink, muted, pitch),
+ children: _children(theme, ink, pitch),
),
),
),
@@ -1001,14 +1005,22 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
),
);
- List<Widget> _children(
- TerminalTheme theme,
- Size cell,
- TextStyle ink,
- Color muted,
- bool pitch,
- ) {
+ /// Artwork keeps the selected terminal font and background while ordinary
+ /// controls follow the desktop appearance and accessibility text size.
+ Widget _artWell(Widget child, Color background) => ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: ColoredBox(
+ color: background,
+ child: Padding(
+ padding: const EdgeInsets.all(12),
+ child: MediaQuery.withNoTextScaling(child: child),
+ ),
+ ),
+ );
+
+ List<Widget> _children(TerminalTheme theme, TextStyle ink, bool pitch) {
final def = _def;
+ final stageGround = pitch ? daemonPitch : theme.background;
if (_stage == HatchStage.consent || _stage == HatchStage.suggest) {
final name = _owned?.name ?? def?.id ?? 'it';
return [
@@ -1016,7 +1028,6 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
alignment: Alignment.centerLeft,
child: DaemonConsent(
name: name,
- ink: ink.color,
step: _stage == HatchStage.consent
? DaemonConsentStep.watch
: DaemonConsentStep.suggest,
@@ -1042,15 +1053,16 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
Text(
'The egg did not open.',
key: const ValueKey('daemon-hatch-failed'),
- style: ink,
+ style: DesktopChrome.heading(),
),
+ const SizedBox(height: 8),
Text(
'harnessd could not be reached. It is still in your zoo.',
textAlign: TextAlign.center,
- style: ink.copyWith(color: muted),
+ style: DesktopChrome.text(size: 13),
),
- SizedBox(height: cell.height),
- _button('[ close ]', _close, theme, ink),
+ const SizedBox(height: 20),
+ _button('Close', _close),
];
}
if (def == null ||
@@ -1059,10 +1071,10 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
_stage == HatchStage.burst ||
_stage == HatchStage.tumble ||
_stage == HatchStage.open) {
- return [_eggStage(theme, ink)];
+ return [_artWell(_eggStage(theme, ink), stageGround)];
}
if (_stage == HatchStage.merged || _stage == HatchStage.grew) {
- return _merged(def, theme, cell, ink, muted);
+ return _merged(def, theme, ink);
}
final shiny = _hatch?.shiny == true;
final traits = _traits;
@@ -1076,8 +1088,7 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
final rows = bannerRows(def.id);
final carded = _stage == HatchStage.card || _stage == HatchStage.name;
final card = carded ? _card : null;
- // The shared banner face (daemons/banner.json), monospace, at a line
- // height that keeps its rows from touching.
+ // The banner and serialized card are terminal artwork, not UI labels.
final banner = ink.copyWith(height: 1.15);
final cardGround = pitch
? const Color(0xff0c0c0c)
@@ -1088,221 +1099,199 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
'${oneInText(oneIn(roster, def.id, traits))}'
: null;
return [
- if (_stage == HatchStage.pitch)
- Padding(
- padding: EdgeInsets.only(bottom: cell.height),
- child: Text(
- 'It is pitch black. You are likely to be eaten by a grue.',
- key: const ValueKey('daemon-hatch-pitch'),
- textAlign: TextAlign.center,
- style: ink.copyWith(color: const Color(0xff949494)),
- ),
- ),
- if (_stage != HatchStage.pitch && card == null) _eggStage(theme, ink),
- if (_bannerRows > 0) ...[
- SizedBox(height: cell.height / 2),
- Text(
- IllustratedArt.supports(def.id)
- ? IllustratedArt.name(def.id)
- : rows.take(_bannerRows).join('\n'),
- key: const ValueKey('daemon-hatch-banner'),
- semanticsLabel: def.id,
- style: banner,
+ _artWell(
+ Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (_stage == HatchStage.pitch)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 16),
+ child: Text(
+ 'It is pitch black. You are likely to be eaten by a grue.',
+ key: const ValueKey('daemon-hatch-pitch'),
+ textAlign: TextAlign.center,
+ style: ink.copyWith(color: const Color(0xff949494)),
+ ),
+ ),
+ if (_stage != HatchStage.pitch && card == null)
+ _eggStage(theme, ink),
+ if (_bannerRows > 0) ...[
+ const SizedBox(height: 8),
+ FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Text(
+ IllustratedArt.supports(def.id)
+ ? IllustratedArt.name(def.id)
+ : rows.take(_bannerRows).join('\n'),
+ key: const ValueKey('daemon-hatch-banner'),
+ semanticsLabel: def.id,
+ style: banner,
+ ),
+ ),
+ ],
+ if (carded) ...[
+ const SizedBox(height: 8),
+ Text(
+ rarityStamp(roster, def, shiny: shiny),
+ key: const ValueKey('daemon-hatch-stamp'),
+ style: ink.copyWith(color: rarity, letterSpacing: 1),
+ ),
+ if (flags != null) ...[
+ const SizedBox(height: 8),
+ Text(
+ flags,
+ key: const ValueKey('daemon-hatch-flags'),
+ textAlign: TextAlign.center,
+ style: ink,
+ ),
+ ],
+ if (card != null) ...[
+ const SizedBox(height: 16),
+ Container(
+ padding: const EdgeInsets.all(8),
+ decoration: BoxDecoration(
+ color: cardGround,
+ border: Border.all(color: ink.color!.withValues(alpha: .2)),
+ ),
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: DaemonCardText(
+ key: const ValueKey('daemon-hatch-card'),
+ lines: card,
+ illustration: IllustratedArt.supports(def.id)
+ ? IllustratedArt.daemon(
+ def.id,
+ version: version,
+ traits: _traits,
+ )
+ : null,
+ portraitRows:
+ art?.frames.first.rows.length ??
+ cardPortrait(roster, def, version).length,
+ style: ink.copyWith(fontSize: (ink.fontSize ?? 13) * .92),
+ colour: daemonColor(def, theme, shiny: shiny),
+ backdrop: daemonBackdrop(def),
+ mats: art?.frames.first.mats,
+ plate:
+ daemonIndividualInk(
+ roster,
+ def,
+ traits,
+ theme,
+ shiny: shiny,
+ background: cardGround,
+ ) ??
+ daemonPlateInk(
+ roster,
+ def,
+ theme,
+ shiny: shiny,
+ background: cardGround,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ],
+ ],
),
- ],
+ stageGround,
+ ),
if (carded) ...[
- SizedBox(height: cell.height / 2),
+ const SizedBox(height: 16),
Text(
- rarityStamp(roster, def, shiny: shiny),
- key: const ValueKey('daemon-hatch-stamp'),
- style: ink.copyWith(color: rarity, letterSpacing: 1),
- ),
- if (flags != null) ...[
- SizedBox(height: cell.height / 2),
- Text(
- flags,
- key: const ValueKey('daemon-hatch-flags'),
- textAlign: TextAlign.center,
- style: ink,
- ),
- ],
- SizedBox(height: cell.height / 2),
- Text(
- "fork() returned 0. it's a ${def.id}.",
+ 'Meet ${def.id}.',
key: const ValueKey('daemon-hatch-words'),
textAlign: TextAlign.center,
- style: ink.copyWith(color: muted),
+ style: DesktopChrome.heading(),
),
if (card != null) ...[
- SizedBox(height: cell.height),
- Container(
- padding: EdgeInsets.all(cell.width),
- decoration: BoxDecoration(
- color: cardGround,
- border: Border.all(color: ink.color!.withValues(alpha: .2)),
- ),
- child: FittedBox(
- fit: BoxFit.scaleDown,
- child: DaemonCardText(
- key: const ValueKey('daemon-hatch-card'),
- lines: card,
- illustration: IllustratedArt.supports(def.id)
- ? IllustratedArt.daemon(
- def.id,
- version: version,
- traits: _traits,
- )
- : null,
- portraitRows:
- art?.frames.first.rows.length ??
- cardPortrait(roster, def, version).length,
- style: ink.copyWith(fontSize: (ink.fontSize ?? 13) * .92),
- colour: daemonColor(def, theme, shiny: shiny),
- backdrop: daemonBackdrop(def),
- mats: art?.frames.first.mats,
- plate:
- daemonIndividualInk(
- roster,
- def,
- traits,
- theme,
- shiny: shiny,
- background: cardGround,
- ) ??
- daemonPlateInk(
- roster,
- def,
- theme,
- shiny: shiny,
- background: cardGround,
- ),
- ),
- ),
- ),
- SizedBox(height: cell.height / 2),
+ const SizedBox(height: 16),
if (_stage == HatchStage.name)
- ..._namePrompt(def, theme, cell, ink, muted)
- else
- Row(
+ ..._namePrompt(def)
+ else ...[
+ Wrap(
+ alignment: WrapAlignment.center,
+ spacing: 8,
+ runSpacing: 8,
children: [
_button(
- '[ copy ]',
+ 'Copy card',
_copy,
- theme,
- ink,
focusNode: _copyFocus,
key: const ValueKey('daemon-hatch-copy'),
),
- SizedBox(width: cell.width),
if (widget.needsConsent)
_button(
- '[ next ]',
+ 'Next',
_toConsent,
- theme,
- ink,
focusNode: _nextFocus,
key: const ValueKey('daemon-hatch-next'),
)
else
- _button('[ close ]', _close, theme, ink),
- SizedBox(width: cell.width * 2),
- Expanded(
- child: Text(
- _copyNote ?? 'esc closes',
- style: ink.copyWith(color: muted),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
+ _button('Close', _close),
],
),
+ const SizedBox(height: 8),
+ Text(_copyNote ?? 'Esc closes', style: DesktopChrome.metadata()),
+ ],
],
],
];
}
- /// `name > _`: what to call it. Enter names it (empty skips), Escape or
- /// `[ skip ]` goes on without a name; it can be named later in the zoo.
- List<Widget> _namePrompt(
- DaemonDef def,
- TerminalTheme theme,
- Size cell,
- TextStyle ink,
- Color muted,
- ) => [
+ /// Enter names it (empty skips); Escape or Skip continues without a name.
+ List<Widget> _namePrompt(DaemonDef def) => [
Text(
- 'what will you call it?',
+ 'What will you call it?',
key: const ValueKey('daemon-hatch-name-question'),
- style: ink,
+ style: DesktopChrome.text(size: 13),
),
+ const SizedBox(height: 8),
TextField(
key: const ValueKey('daemon-hatch-name'),
controller: _name,
focusNode: _nameFocus,
maxLength: 24,
- style: ink,
- cursorWidth: cell.width,
- cursorHeight: cell.height,
- cursorColor: theme.cursor,
+ style: DesktopChrome.text(size: 13),
+ cursorColor: DesktopChrome.accent,
decoration: InputDecoration(
- prefixText: 'name > ',
- prefixStyle: ink.copyWith(color: muted),
+ labelText: 'Name',
hintText: individualName(
def.id,
serial: _owned?.serial ?? _hatch?.serial,
),
- hintStyle: ink.copyWith(color: muted.withValues(alpha: .35)),
counterText: '',
errorText: _nameError,
- errorStyle: ink.copyWith(color: theme.red),
- isDense: true,
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- contentPadding: EdgeInsets.zero,
),
onSubmitted: (_) => _saveName(),
),
- Row(
+ const SizedBox(height: 12),
+ Wrap(
+ alignment: WrapAlignment.center,
+ spacing: 8,
+ runSpacing: 8,
children: [
_button(
- '[ name it ]',
+ 'Name it',
_saveName,
- theme,
- ink,
key: const ValueKey('daemon-hatch-name-save'),
),
- SizedBox(width: cell.width),
_button(
- '[ skip ]',
+ 'Skip',
_endNaming,
- theme,
- ink,
key: const ValueKey('daemon-hatch-name-skip'),
),
- SizedBox(width: cell.width * 2),
- Expanded(
- child: Text(
- 'enter names it · esc skips',
- style: ink.copyWith(color: muted),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
],
),
+ const SizedBox(height: 8),
+ Text('Enter names it · Esc skips', style: DesktopChrome.metadata()),
];
/// A merged duplicate (a server from before individuals): yours, at its
/// version and in its colour (shiny now, if the duplicate was), `tim ·
/// +150 xp`, then how it grew.
- List<Widget> _merged(
- DaemonDef def,
- TerminalTheme theme,
- Size cell,
- TextStyle ink,
- Color muted,
- ) {
+ List<Widget> _merged(DaemonDef def, TerminalTheme theme, TextStyle ink) {
final hatch = _hatch!;
final owned = _owned;
final grew = _stage == HatchStage.grew ? _grew : null;
@@ -1320,7 +1309,7 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
final mood = grew == null ? DaemonMood.idle : DaemonMood.done;
return [
Container(
- color: daemonBackdrop(def),
+ color: daemonBackdrop(def) ?? theme.background,
child: _portrait(
def,
version,
@@ -1347,13 +1336,13 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
: still(version, mood),
),
),
- SizedBox(height: cell.height / 2),
+ const SizedBox(height: 8),
Text(
'$name · +${hatch.xp} xp',
key: const ValueKey('daemon-hatch-merged'),
- style: ink.copyWith(color: theme.yellow, letterSpacing: 1),
+ style: DesktopChrome.heading(),
),
- SizedBox(height: cell.height / 2),
+ const SizedBox(height: 8),
Text(
[
'another ${def.id}. +${hatch.xp} xp.',
@@ -1361,14 +1350,14 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
].join(' '),
key: const ValueKey('daemon-hatch-words'),
textAlign: TextAlign.center,
- style: ink.copyWith(color: muted),
+ style: DesktopChrome.metadata(),
),
if (grew != null) ...[
- SizedBox(height: cell.height / 2),
+ const SizedBox(height: 8),
Text(
'$name grew: bond ${grew.$1} · ${grew.$2}',
key: const ValueKey('daemon-hatch-grew'),
- style: ink.copyWith(color: theme.green),
+ style: DesktopChrome.text(size: 13, medium: true),
),
// Its room is kept while the portrait morphs, so nothing moves when
// the changelog line appears.
@@ -1380,62 +1369,33 @@ class _DaemonHatchRevealState extends State<DaemonHatchReveal> {
? const ValueKey('daemon-hatch-changelog')
: null,
textAlign: TextAlign.center,
- style: ink.copyWith(color: muted),
+ style: DesktopChrome.metadata(),
),
),
],
- SizedBox(height: cell.height),
+ const SizedBox(height: 16),
if (widget.needsConsent)
_button(
- '[ next ]',
+ 'Next',
_toConsent,
- theme,
- ink,
focusNode: _nextFocus,
key: const ValueKey('daemon-hatch-next'),
)
else
- _button('[ close ]', _close, theme, ink),
+ _button('Close', _close),
];
}
Widget _button(
String label,
- VoidCallback onPressed,
- TerminalTheme theme,
- TextStyle ink, {
+ VoidCallback onPressed, {
FocusNode? focusNode,
Key? key,
- }) => TextButton(
+ }) => DesktopPill(
key: key,
+ label: label,
focusNode: focusNode,
onPressed: onPressed,
- style:
- TextButton.styleFrom(
- minimumSize: Size.zero,
- padding: EdgeInsets.zero,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- foregroundColor: ink.color,
- shape: const RoundedRectangleBorder(),
- splashFactory: NoSplash.splashFactory,
- ).copyWith(
- overlayColor: WidgetStateProperty.resolveWith(
- (states) =>
- states.any(
- {
- WidgetState.hovered,
- WidgetState.focused,
- WidgetState.pressed,
- }.contains,
- )
- ? theme.selection.withValues(alpha: .5)
- : Colors.transparent,
- ),
- ),
- child: Text(
- label,
- style: ink.copyWith(color: _pitch ? ink.color : theme.cursor),
- ),
);
}
diff --git a/desktop/lib/widgets/daemon_panel.dart b/desktop/lib/widgets/daemon_panel.dart
index 217f03232..39e22a25d 100644
--- a/desktop/lib/widgets/daemon_panel.dart
+++ b/desktop/lib/widgets/daemon_panel.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:math';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show OverflowBoxFit;
import 'package:flutter/services.dart';
@@ -21,12 +22,12 @@ import '../daemons/zoo.dart';
import '../shared/theme/app_theme.dart';
import '../terminal/terminal_text.dart';
import '../terminal/terminal_theme_store.dart';
-import 'box_chrome.dart';
import 'daemon_consent.dart';
import 'daemon_portrait.dart';
import 'daemon_illustration.dart';
import 'daemon_art_gallery.dart';
import 'daemon_slot.dart';
+import 'desktop_chrome.dart';
part 'daemon_panel_pair.dart';
@@ -125,7 +126,6 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
bool _showDetails = false;
bool _showGallery = false;
String? _nameError;
- @override
late Size _cell;
@override
@@ -294,35 +294,46 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
@override
TerminalTheme get _theme => currentTerminalTheme();
+ TextStyle _artInk([Color? color]) => terminalContentStyle(
+ color: color ?? _theme.foreground,
+ ).copyWith(fontFeatures: daemonTextFeatures, fontWeight: FontWeight.normal);
@override
TextStyle _ink([Color? color]) =>
- terminalContentStyle(color: color ?? _theme.foreground)
- .copyWith(fontFeatures: daemonTextFeatures);
+ DesktopChrome.text(color: color ?? DesktopChrome.foreground, size: 13);
@override
- Color get _muted => _theme.foreground.withValues(alpha: .58);
+ Color get _muted => DesktopChrome.muted;
+ @override
ButtonStyle get _buttonStyle =>
TextButton.styleFrom(
- minimumSize: Size.zero,
- fixedSize: Size.fromHeight(_cell.height),
- padding: EdgeInsets.zero,
+ minimumSize: const Size(0, DesktopChrome.controlHeight),
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- foregroundColor: _theme.foreground,
- shape: const RoundedRectangleBorder(),
+ foregroundColor: DesktopChrome.foreground,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ ),
splashFactory: NoSplash.splashFactory,
alignment: Alignment.centerLeft,
).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? DesktopChrome.accent
+ : Colors.transparent,
+ ),
+ ),
overlayColor: WidgetStateProperty.resolveWith(
- (states) =>
- states.any(
- {
- WidgetState.hovered,
- WidgetState.focused,
- WidgetState.pressed,
- }.contains,
- )
- ? _theme.selection.withValues(alpha: .5)
- : Colors.transparent,
+ (states) => DesktopChrome.foreground.withValues(
+ alpha: states.contains(WidgetState.disabled)
+ ? 0
+ : states.contains(WidgetState.pressed)
+ ? .12
+ : states.contains(WidgetState.hovered)
+ ? .05
+ : 0,
+ ),
),
);
@@ -331,7 +342,6 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
String key,
String label,
VoidCallback? onPressed, {
- Color? color,
String? tooltip,
}) {
final button = TextButton(
@@ -339,10 +349,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
focusNode: _node(key),
onPressed: onPressed,
style: _buttonStyle,
- child: Text(
- label,
- style: _ink(onPressed == null ? _muted : color ?? _theme.cursor),
- ),
+ child: Text(label, style: _ink(onPressed == null ? _muted : null)),
);
return tooltip == null ? button : Tooltip(message: tooltip, child: button);
}
@@ -402,24 +409,27 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
autofocus: true,
child: TextSelectionTheme(
data: TextSelectionThemeData(
- selectionColor: _theme.selection,
- cursorColor: _theme.cursor,
+ selectionColor: DesktopChrome.selection,
+ cursorColor: DesktopChrome.accent,
),
child: Material(
key: const ValueKey('daemon-panel'),
- color: _theme.background,
+ color: DesktopChrome.surface,
shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(kTerminalCornerRadius),
- side: terminalPaneBorder(focused: true),
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.dialogRadius,
+ ),
+ side: BorderSide(
+ color: MediaQuery.highContrastOf(context)
+ ? DesktopChrome.foreground.withValues(alpha: .6)
+ : DesktopChrome.rim,
+ ),
),
clipBehavior: Clip.antiAlias,
child: SingleChildScrollView(
key: _viewport,
controller: _scroll,
- padding: EdgeInsets.symmetric(
- horizontal: _cell.width * 2,
- vertical: _cell.height,
- ),
+ padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -430,7 +440,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
key: const ValueKey('daemon-preview-label'),
style: _ink(_muted),
),
- SizedBox(height: _cell.height),
+ const SizedBox(height: 16),
],
...body,
],
@@ -457,32 +467,34 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
child: Text(
title,
key: const ValueKey('daemon-panel-title'),
- style: _ink(),
+ style: DesktopChrome.heading(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
?badge,
- SizedBox(width: _cell.width),
+ const SizedBox(width: 8),
Tooltip(
message: 'Close',
- child: TextButton(
+ child: IconButton(
key: const ValueKey('daemon-close'),
onPressed: widget.onClose,
+ tooltip: 'Close daemon',
style: _buttonStyle,
- child: Text('[x]', style: _ink(_theme.cursor)),
+ icon: const Icon(AppIcons.close, size: 18),
),
),
],
);
- /// A compact window list with a one-line selection. Click or press 1–4.
+ /// Tabs retain the same click and 1–4 keyboard navigation.
Widget _tabBar() => Padding(
- padding: EdgeInsets.only(top: _cell.height / 2),
+ padding: const EdgeInsets.only(top: 8),
child: Wrap(
- spacing: _cell.width * 2,
+ spacing: 8,
+ runSpacing: 8,
children: [
- for (final (i, tab) in DaemonSettings.tabs.indexed)
+ for (final tab in DaemonSettings.tabs)
Semantics(
selected: tab == _tab,
button: true,
@@ -491,12 +503,15 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
onPressed: () => _switchTab(tab),
style: _buttonStyle.copyWith(
backgroundColor: WidgetStatePropertyAll(
- tab == _tab ? _theme.selection.withValues(alpha: .55) : null,
+ tab == _tab ? DesktopChrome.selection : null,
),
),
child: Text(
- '${i + 1} ${_speciesName(tab)}',
- style: _ink(tab == _tab ? _theme.foreground : _muted),
+ '${tab[0].toUpperCase()}${tab.substring(1)}',
+ style: DesktopChrome.control(
+ color: tab == _tab ? DesktopChrome.foreground : _muted,
+ medium: tab == _tab,
+ ),
),
),
),
@@ -545,7 +560,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
.length;
return [
_title(egg != null ? 'Your egg is ready' : 'Your first egg'),
- SizedBox(height: _cell.height),
+ const SizedBox(height: 16),
// The egg itself, filled, at its stage: it cracks as habits count.
if (shown != null && daemonPlates.hasEgg(shown.kind))
Center(
@@ -553,22 +568,25 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
width: _cell.width * 20,
child: FittedBox(
fit: BoxFit.scaleDown,
- child: DaemonEggPlate(
- roster: roster,
- kind: shown.kind,
- stage: shown.stage,
- style: _ink().copyWith(height: 1.0),
- theme: _theme,
- animate: face.motionEnabled,
- textKey: const ValueKey('daemon-panel-egg-plate'),
- semanticsLabel: egg != null
- ? 'Your egg, ready to hatch'
- : 'Your egg, ${_stageWords(shown.stage)}',
+ child: ColoredBox(
+ color: _theme.background,
+ child: DaemonEggPlate(
+ roster: roster,
+ kind: shown.kind,
+ stage: shown.stage,
+ style: _artInk().copyWith(height: 1.0),
+ theme: _theme,
+ animate: face.motionEnabled,
+ textKey: const ValueKey('daemon-panel-egg-plate'),
+ semanticsLabel: egg != null
+ ? 'Your egg, ready to hatch'
+ : 'Your egg, ${_stageWords(shown.stage)}',
+ ),
),
),
),
),
- if (shown != null) SizedBox(height: _cell.height / 2),
+ if (shown != null) const SizedBox(height: 8),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -578,7 +596,8 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
egg != null ? 'Ready' : 'Growing',
key: const ValueKey('daemon-panel-nest'),
semanticsLabel: egg != null ? 'Ready to hatch' : 'An egg',
- style: _ink(_nestInk),
+ style: _artInk(_nestInk)
+ .copyWith(backgroundColor: _theme.background),
),
),
Expanded(
@@ -596,18 +615,18 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
],
),
if (egg == null && here >= need) ...[
- SizedBox(height: _cell.height / 2),
+ const SizedBox(height: 8),
Text(
'all of it can happen on this computer.',
key: const ValueKey('daemon-panel-here'),
style: _ink(_muted),
),
],
- SizedBox(height: _cell.height),
+ const SizedBox(height: 16),
for (final habit in habits)
if (!daemonHabitsElsewhere.contains(habit.key)) _habitRow(habit, done),
Padding(
- padding: EdgeInsets.only(top: _cell.height / 2),
+ padding: const EdgeInsets.only(top: 8),
child: Text(
'with another computer or device (never needed):',
key: const ValueKey('daemon-panel-elsewhere'),
@@ -616,7 +635,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
),
for (final habit in habits)
if (daemonHabitsElsewhere.contains(habit.key)) _habitRow(habit, done),
- SizedBox(height: _cell.height),
+ const SizedBox(height: 16),
Row(
children: [
Expanded(
@@ -625,8 +644,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
style: _ink(_muted),
),
),
- if (egg != null)
- _action('hatch', '[ hatch ]', () => widget.onHatch(egg)),
+ if (egg != null) _action('hatch', 'Hatch', () => widget.onHatch(egg)),
],
),
];
@@ -645,11 +663,12 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
final row = LayoutBuilder(
builder: (context, constraints) => Row(
children: [
- Text(
- complete ? '[x]' : '[ ]',
- style: _ink(complete ? _theme.green : _muted),
+ Icon(
+ complete ? AppIcons.circleCheck : AppIcons.circle,
+ size: 18,
+ color: complete ? DesktopChrome.accent : _muted,
),
- SizedBox(width: _cell.width),
+ const SizedBox(width: 8),
Expanded(
child: Text.rich(
TextSpan(
@@ -661,24 +680,24 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
TextSpan(text: ' needed', style: _ink(_muted)),
],
),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
style: _ink(complete || elsewhere ? _muted : null),
),
),
if (hint != null &&
!complete &&
constraints.maxWidth >= _cell.width * 36) ...[
- SizedBox(width: _cell.width),
+ const SizedBox(width: 8),
Text(hint, style: _ink(_muted)),
],
],
),
);
if (complete || command == null) {
- return SizedBox(
+ return ConstrainedBox(
key: ValueKey('daemon-habit-${habit.key}'),
- height: _cell.height,
+ constraints: const BoxConstraints(
+ minHeight: DesktopChrome.controlHeight,
+ ),
child: row,
);
}
@@ -711,7 +730,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
badge: _autonomyBadge(),
),
_tabBar(),
- SizedBox(height: _cell.height),
+ const SizedBox(height: 16),
...switch (tab) {
'zoo' => _zooTab(order, viewing, def),
'lessons' => _lessonsTab(order, pairedName),
@@ -729,9 +748,9 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
return Tooltip(
message: 'It acts on its own at this level. The floor still holds.',
child: Text(
- '[${daemonAutonomyLabel(level!)}]',
+ daemonAutonomyLabel(level!),
key: const ValueKey('daemon-panel-autonomy-badge'),
- style: _ink(_theme.yellow),
+ style: _ink(),
),
);
}
@@ -741,7 +760,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
List<Widget> _lineRows(DaemonDef def, String name) {
final mood = face.mood;
final spoken = face.voice;
- final nick = face.voiceFromPair ? daemonPairNick(name) : '';
+ final nick = face.voiceFromPair ? '$name: ' : '';
final line = spoken != null
? '$nick$spoken'
: '$name: ${face.currentLine(mood)}';
@@ -755,18 +774,21 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
Text(
face.glyph,
semanticsLabel: '$name, ${DaemonFace.moodWords[mood]}',
- style: _ink(
- daemonColor(def, _theme, shiny: face.daemon?.shiny ?? false),
- ).copyWith(backgroundColor: daemonBackdrop(def)),
+ style:
+ _artInk(
+ daemonColor(def, _theme, shiny: face.daemon?.shiny ?? false),
+ ).copyWith(
+ backgroundColor: daemonBackdrop(def) ?? _theme.background,
+ ),
),
- SizedBox(width: _cell.width * 2),
+ const SizedBox(width: 16),
Expanded(
child: Semantics(
liveRegion: true,
child: Text(
line,
key: const ValueKey('daemon-panel-line'),
- style: _ink(alert ? _theme.yellow : _muted),
+ style: _ink(alert ? DesktopChrome.foreground : _muted),
),
),
),
@@ -774,7 +796,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
),
// Asleep or out of reach is not a failure: said calmly, once.
if (face.away.isNotEmpty) ...[
- SizedBox(height: _cell.height / 2),
+ const SizedBox(height: 8),
Text(
[
for (final machine in face.away)
@@ -798,9 +820,10 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
List<Widget> _nowTab(List<String> order, DaemonDef def, String name) => [
..._lineRows(def, name),
if (_eggKinds.isNotEmpty) ...[
- SizedBox(height: _cell.height / 2),
+ const SizedBox(height: 8),
Wrap(
- spacing: _cell.width * 2,
+ spacing: 8,
+ runSpacing: 8,
children: [
for (final kind in _eggKinds)
() {
@@ -904,7 +927,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
)
: null,
portraitRows: portraitRows,
- style: _ink(),
+ style: _artInk(),
colour: colour,
backdrop: backdrop,
mats: cardArt?.frames.first.mats,
@@ -951,7 +974,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
roster: roster,
def: def,
version: viewing.version,
- style: _ink().copyWith(height: 1.15),
+ style: _artInk().copyWith(height: 1.15),
theme: _theme,
mood: mood,
shiny: viewing.shiny,
@@ -986,37 +1009,30 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
focusNode: _nameFocus,
maxLength: 24,
style: _ink(),
- cursorWidth: _cell.width,
- cursorHeight: _cell.height,
- cursorColor: _theme.cursor,
+ cursorColor: DesktopChrome.accent,
decoration: InputDecoration(
- prefixText: 'name > ',
- prefixStyle: _ink(_muted),
+ labelText: 'Name',
counterText: '',
errorText: _nameError,
- errorStyle: _ink(_theme.red),
- isDense: true,
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- contentPadding: EdgeInsets.zero,
+ errorStyle: _ink(Theme.of(context).colorScheme.error),
),
onSubmitted: (_) => _rename(viewing),
),
Text('enter saves · empty clears · esc cancels', style: _ink(_muted)),
] else
Wrap(
- spacing: _cell.width * 2,
+ spacing: 8,
+ runSpacing: 8,
children: [
if (!isPair)
- _action('pair', '[ Choose companion ]', () {
+ _action('pair', 'Choose companion', () {
face.zoo.pair(viewing.uid);
setState(() => _viewing = null);
- }, tooltip: 'Put $name in your tab bar'),
- _action('rename', '[ Rename ]', () => _beginRename(viewing)),
+ }, tooltip: 'Put $name in your status line'),
+ _action('rename', 'Rename', () => _beginRename(viewing)),
_action(
'card',
- _showCard ? '[ Portrait ]' : '[ Card ]',
+ _showCard ? 'Portrait' : 'Card',
() => setState(() {
_showCard = !_showCard;
_copyNote = null;
@@ -1027,13 +1043,13 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
),
_action(
'details',
- _showDetails ? '[ Hide details ]' : '[ Details ]',
+ _showDetails ? 'Hide details' : 'Details',
() => setState(() => _showDetails = !_showDetails),
),
if (_showCard)
_action(
'copy',
- '[ copy ]',
+ 'Copy',
() => _copy(
card,
illustratedRows: IllustratedArt.supports(def.id)
@@ -1070,17 +1086,17 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
),
],
SizedBox(height: _cell.height),
- _action('gallery', '[ Browse artwork ]', () {
+ _action('gallery', 'Browse artwork', () {
setState(() => _showGallery = true);
if (_scroll.hasClients) _scroll.jumpTo(0);
}),
SizedBox(height: _cell.height / 2),
..._shelf(viewing.id),
- SizedBox(height: _cell.height / 2),
+ const SizedBox(height: 8),
...individuals,
- SizedBox(height: _cell.height / 2),
+ const SizedBox(height: 8),
...eggs,
- SizedBox(height: _cell.height / 2),
+ const SizedBox(height: 8),
..._meters(),
];
}
@@ -1110,13 +1126,13 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
for (final def in species) {
final all = zoo.ofSpecies(def.id);
out
- ..add(SizedBox(height: _cell.height / 2))
+ ..add(const SizedBox(height: 8))
..add(
Text(
'${cardNumber(roster, def).split('/').first} ${def.id}'
' x${all.length}',
key: ValueKey('daemon-species-${def.id}'),
- style: _ink(daemonColor(def, _theme)),
+ style: DesktopChrome.control(medium: true),
),
);
final log = _traitLog(def, all);
@@ -1190,7 +1206,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
style: _buttonStyle.copyWith(
fixedSize: const WidgetStatePropertyAll(null),
backgroundColor: WidgetStatePropertyAll(
- selected ? _theme.selection.withValues(alpha: .35) : null,
+ selected ? DesktopChrome.selection : null,
),
),
child: Text(
@@ -1198,7 +1214,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
'${individualName(def.id, name: d.name, serial: d.serial)} '
'${d.version}${paired ? ' · paired' : ''}'
'${rest == null ? '' : '\n$rest'}',
- style: _ink(selected ? _theme.foreground : null),
+ style: _ink(),
),
);
}
@@ -1223,15 +1239,18 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
height: _cell.height * 3.4,
child: FittedBox(
fit: BoxFit.contain,
- child: DaemonEggPlate(
- roster: roster,
- kind: kind,
- stage: stage,
- style: _ink().copyWith(height: 1.0),
- theme: _theme,
- animate: face.motionEnabled,
- textKey: key,
- semanticsLabel: '${eggName(kind)}, $label',
+ child: ColoredBox(
+ color: _theme.background,
+ child: DaemonEggPlate(
+ roster: roster,
+ kind: kind,
+ stage: stage,
+ style: _artInk().copyWith(height: 1.0),
+ theme: _theme,
+ animate: face.motionEnabled,
+ textKey: key,
+ semanticsLabel: '${eggName(kind)}, $label',
+ ),
),
),
),
@@ -1244,10 +1263,10 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
key: const ValueKey('daemon-panel-eggs'),
style: _ink(_muted),
),
- SizedBox(height: _cell.height / 4),
+ const SizedBox(height: 4),
Wrap(
- spacing: _cell.width * 2,
- runSpacing: _cell.height / 2,
+ spacing: 8,
+ runSpacing: 8,
children: [
for (final (kind, eggs) in waiting)
() {
@@ -1291,11 +1310,12 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
..add('nap');
return [
Wrap(
- spacing: _cell.width * 2,
+ spacing: 8,
+ runSpacing: 8,
children: [
_action(
'quiet',
- face.quiet ? '[ quiet: on ]' : '[ quiet: off ]',
+ face.quiet ? 'Quiet on' : 'Quiet off',
() => face.settings.quiet = !face.quiet,
tooltip: face.quiet
? 'It says nothing until you turn this off.'
@@ -1303,7 +1323,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
),
_action(
'motion',
- face.settings.motion ? '[ motion: on ]' : '[ motion: off ]',
+ face.settings.motion ? 'Motion on' : 'Motion off',
() => face.settings.motion = !face.settings.motion,
tooltip: face.settings.motion
? 'Work frames step with agent events; blinks answer you.'
@@ -1311,7 +1331,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
),
_action(
'nap',
- face.napping ? '[ wake ]' : '[ nap ]',
+ face.napping ? 'Wake' : 'Nap',
face.napping ? face.wake : face.nap,
tooltip: face.napping
? 'Wake $name'
@@ -1385,7 +1405,8 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
if (drop.releasedAt(_now)) ..._dropOrder(drop.id),
];
- static const _slotCells = 10;
+ double get _shelfWidth =>
+ max(120 * appTextScaleOf(context), _cell.width * 10);
static String _speciesName(String id) =>
id == 'gnu' ? 'GNU' : '${id[0].toUpperCase()}${id.substring(1)}';
@@ -1404,7 +1425,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
final now = _now;
return [
for (final (n, drop) in _shelfDrops.indexed) ...[
- if (n > 0) SizedBox(height: _cell.height / 2),
+ if (n > 0) const SizedBox(height: 8),
..._dropShelf(drop, viewing, announced: !drop.releasedAt(now)),
],
];
@@ -1430,9 +1451,10 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
),
style: _ink(_muted),
),
- SizedBox(height: _cell.height / 2),
+ const SizedBox(height: 8),
Wrap(
- runSpacing: _cell.height / 2,
+ spacing: 8,
+ runSpacing: 8,
children: [
for (final d in order) announced ? _teaser(d) : _slot(d, viewing),
],
@@ -1443,9 +1465,9 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
/// A daemon of a drop announced but not out: its 0.1 sprite as `#`, faint
/// (a secret stays `[ ! ]`).
Widget _teaser(DaemonDef d) {
- final faint = _theme.foreground.withValues(alpha: .35);
+ final faint = _muted;
return SizedBox(
- width: _cell.width * _slotCells,
+ width: _shelfWidth,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
@@ -1474,7 +1496,8 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
),
key: ValueKey('daemon-zoo-${d.id}'),
semanticsLabel: d.secret ? 'A secret' : 'Not out yet',
- style: _ink(faint),
+ style: _artInk(faint)
+ .copyWith(backgroundColor: _theme.background),
),
Text('', style: _ink()),
],
@@ -1485,9 +1508,9 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
Widget _slot(DaemonDef d, String viewing) {
final owned = zoo.daemons.where((z) => z.id == d.id).toList();
final number = cardNumber(roster, d).split('/').first;
- final faint = _theme.foreground.withValues(alpha: .35);
+ final faint = _muted;
Widget cell(List<Widget> rows) => SizedBox(
- width: _cell.width * _slotCells,
+ width: _shelfWidth,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
@@ -1503,7 +1526,8 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
d.secret ? '[ ! ]' : '[ ? ]',
key: ValueKey('daemon-zoo-${d.id}'),
semanticsLabel: d.secret ? 'A secret' : 'Not yet hatched',
- style: _ink(faint),
+ style: _artInk(_theme.foreground.withValues(alpha: .35))
+ .copyWith(backgroundColor: _theme.background),
),
Text('', style: _ink()),
]),
@@ -1529,26 +1553,21 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
'${count > 1 ? ' · x$count' : ''}'
'${first.uid == zoo.pair ? ' · paired' : ''}',
child: SizedBox(
- width: _cell.width * _slotCells,
- child: GestureDetector(
- excludeFromSemantics: true,
- behavior: HitTestBehavior.opaque,
- onTap: () => setState(() => _viewing = first.uid),
+ width: _shelfWidth,
+ child: TextButton(
+ key: ValueKey('daemon-zoo-${d.id}'),
+ focusNode: _node('zoo:${d.id}'),
+ onPressed: () => setState(() => _viewing = first.uid),
+ style: _buttonStyle.copyWith(
+ backgroundColor: WidgetStatePropertyAll(
+ selected ? DesktopChrome.selection : null,
+ ),
+ ),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
- TextButton(
- key: ValueKey('daemon-zoo-${d.id}'),
- focusNode: _node('zoo:${d.id}'),
- onPressed: () => setState(() => _viewing = first.uid),
- style: _buttonStyle.copyWith(
- backgroundColor: WidgetStatePropertyAll(
- selected ? _theme.selection.withValues(alpha: .35) : null,
- ),
- ),
- child: Text('$number ${_speciesName(d.id)}', style: _ink()),
- ),
+ Text('$number ${_speciesName(d.id)}', style: _ink()),
SizedBox(
height: _cell.height * 2,
child: Align(
@@ -1568,7 +1587,7 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
'${first.shiny ? '*' : ''}$sprite',
semanticsLabel:
'${d.id} ${_growthStage(first.version)}',
- style: _ink(
+ style: _artInk(
daemonColor(d, _theme, shiny: first.shiny),
).copyWith(backgroundColor: backdrop),
),
@@ -1592,30 +1611,47 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
final progress = zoo.progress;
final into = progress.turns % earn.turnEvery;
final today = progress.days[localDayOf(DateTime.now())] ?? 0;
- String bar(int value, int of) {
- const width = 20;
- final filled = of <= 0 ? 0 : (value * width / of).floor().clamp(0, width);
- return '[${'#' * filled}${'-' * (width - filled)}]';
- }
-
- String row(String label, int value, int of) =>
- '${label.padRight(10)}${bar(value, of)} '
- '${'$value/$of'.padLeft(5)}';
+ Widget meter(String label, int value, int of) => Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text('$label · $value/$of', style: _ink(_muted)),
+ const SizedBox(height: 8),
+ LinearProgressIndicator(
+ value: of <= 0 ? 0 : (value / of).clamp(0.0, 1.0),
+ minHeight: 4,
+ borderRadius: BorderRadius.circular(2),
+ color: DesktopChrome.accent,
+ backgroundColor: DesktopChrome.rim,
+ semanticsLabel: '$label, $value of $of',
+ ),
+ ],
+ ),
+ );
// The setup egg: habits toward it, until it has come.
final setup = zoo.firstEgg ? face.zoo.setupProgress : null;
return [
- Text(
- [
- row('today', today.clamp(0, earn.dailyCap), earn.dailyCap),
- if (setup != null) row('setup egg', setup.$1, setup.$2),
- if (today >= earn.dailyCap)
- "today's turns are counted. more tomorrow.",
- ].join('\n'),
+ Semantics(
key: const ValueKey('daemon-panel-progress'),
- semanticsLabel:
+ label:
'${earn.turnEvery - into} counted turns to the next egg. '
'$today of ${earn.dailyCap} turns counted today.',
- style: _ink(_muted),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ meter('Today', today.clamp(0, earn.dailyCap), earn.dailyCap),
+ if (setup != null) meter('Setup egg', setup.$1, setup.$2),
+ if (today >= earn.dailyCap)
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Text(
+ "Today's turns are counted. More tomorrow.",
+ style: _ink(_muted),
+ ),
+ ),
+ ],
+ ),
),
];
}
@@ -1632,9 +1668,8 @@ class _DaemonPanelState extends State<DaemonPanel> with _PairSections {
final eggs = zoo.eggs.where((e) => e.kind == kind).toList();
return _action(
'egg:$kind',
- '${eggName(kind)} ×${eggs.length}',
+ 'Hatch ${eggName(kind)} · ${eggs.length} waiting',
() => widget.onHatch(eggs.first),
- color: _theme.foreground,
tooltip: 'Open a ${eggName(kind)} (${eggs.length} waiting)',
);
}
diff --git a/desktop/lib/widgets/daemon_panel_pair.dart b/desktop/lib/widgets/daemon_panel_pair.dart
index 2e62d7217..8651e322a 100644
--- a/desktop/lib/widgets/daemon_panel_pair.dart
+++ b/desktop/lib/widgets/daemon_panel_pair.dart
@@ -5,10 +5,7 @@ part of 'daemon_panel.dart';
/// waiting answer.
const daemonAutonomyWords = <String, (String, String)>{
'watch': ('watch', 'reads and tells you. it answers nothing.'),
- 'suggest': (
- 'suggest',
- 'recommends. every action waits for your key.',
- ),
+ 'suggest': ('suggest', 'recommends. every action waits for your key.'),
'act-on-key': (
'act on key',
'your key approves one waiting answer at a time; '
@@ -41,16 +38,15 @@ const daemonRulesPath = '~/.config/harness/pair.jsonc';
/// until the brain says it has armed (a moment later).
mixin _PairSections on State<DaemonPanel> {
// The panel's own drawing, shared.
- Size get _cell;
TerminalTheme get _theme;
Color get _muted;
TextStyle _ink([Color? color]);
+ ButtonStyle get _buttonStyle;
FocusNode _node(String key);
Widget _action(
String key,
String label,
VoidCallback? onPressed, {
- Color? color,
String? tooltip,
});
DaemonFace get face;
@@ -154,14 +150,27 @@ mixin _PairSections on State<DaemonPanel> {
/// Whether a key on [id] counts yet (no brain: nothing to wait for).
bool _armed(String id) => _brain?.armed(id) ?? true;
+ TextStyle get _detailStyle => AppType.mono(color: _muted, height: 1.4);
+ double get _detailRowHeight =>
+ MediaQuery.textScalerOf(context).scale(13) * 1.4;
+ int get _detailRows =>
+ (MediaQuery.sizeOf(context).height * .22 / _detailRowHeight)
+ .floor()
+ .clamp(2, 10);
+
// ── rows ───────────────────────────────────────────────────────────────────
Widget _header(String title, {Widget? trailing, Key? key}) => Padding(
key: key,
- padding: EdgeInsets.only(top: _cell.height),
+ padding: const EdgeInsets.only(top: 24),
child: Row(
children: [
- Expanded(child: Text(title, style: _ink(_muted))),
+ Expanded(
+ child: Text(
+ title,
+ style: AppType.heading(color: DesktopChrome.foreground),
+ ),
+ ),
?trailing,
],
),
@@ -187,11 +196,9 @@ mixin _PairSections on State<DaemonPanel> {
List<String> listing = const [],
}) {
final split = splitDaemonKeys(line, actions);
- final ink = color ?? _theme.foreground;
final armed = shownId == null || _armed(shownId);
- TextStyle style([bool emphasized = false]) => _ink(ink).copyWith(
- fontWeight: emphasized ? FontWeight.w600 : null,
- );
+ TextStyle style([bool emphasized = false]) =>
+ _ink().copyWith(fontWeight: emphasized ? FontWeight.w600 : null);
void press(String k) {
final action = actions.where((a) => a.key == k).firstOrNull;
if (action == null) return;
@@ -227,37 +234,84 @@ mixin _PairSections on State<DaemonPanel> {
builder: (context) {
final focused = Focus.of(context).hasFocus;
return Container(
- color: focused ? _theme.selection.withValues(alpha: .5) : null,
- child: Row(
+ padding: const EdgeInsets.all(10),
+ decoration: BoxDecoration(
+ color: focused ? DesktopChrome.selection : DesktopChrome.field,
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ border: Border.all(
+ width: 1.5,
+ color: focused ? DesktopChrome.accent : Colors.transparent,
+ ),
+ ),
+ child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- if (split.keys.isNotEmpty)
- DaemonKeys(
- keys: split.keys,
- actions: actions,
- style: style,
- live: live,
- armed: armed,
- height: _cell.height,
- idPrefix: 'daemon-key-$key',
- onAnswer: press,
- ),
- Expanded(
- child: Text.rich(
- TextSpan(
- children: [
- if (fromPair && name != null)
- TextSpan(
- text: daemonPairNick(name),
- style: style(true),
- ),
- TextSpan(text: split.rest),
- ],
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (color != null) ...[
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: Icon(
+ color == _theme.red
+ ? AppIcons.circleAlert
+ : color == _theme.yellow
+ ? AppIcons.ellipsis
+ : AppIcons.info,
+ size: 16,
+ color: color == _theme.red
+ ? Theme.of(context).colorScheme.error
+ : color == _theme.yellow
+ ? DesktopChrome.accent
+ : _muted,
+ ),
+ ),
+ const SizedBox(width: 8),
+ ],
+ Expanded(
+ child: Text.rich(
+ TextSpan(
+ children: [
+ if (fromPair && name != null)
+ TextSpan(text: '$name: ', style: style(true)),
+ TextSpan(text: split.rest),
+ ],
+ ),
+ // Whole: harnessd bounds a line (140 characters).
+ style: _ink(),
+ ),
),
- // Whole: harnessd bounds a line (140 characters).
- style: _ink(ink),
- ),
+ ],
),
+ if (split.keys.isNotEmpty) ...[
+ const SizedBox(height: 8),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ for (final shortcut in split.keys)
+ if (actions.where((a) => a.key == shortcut).firstOrNull
+ case final action?)
+ TextButton(
+ key: ValueKey(
+ 'daemon-key-$key-$shortcut${shortcut != 'g' && live && !armed ? '-arming' : ''}',
+ ),
+ onPressed: shortcut == 'g' || (live && armed)
+ ? () => press(shortcut)
+ : null,
+ style: _buttonStyle,
+ child: Text(
+ '${action.label} (${shortcut.toUpperCase()})',
+ style: DesktopChrome.control(
+ color: shortcut == 'g' || (live && armed)
+ ? DesktopChrome.foreground
+ : _muted,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ],
],
),
);
@@ -267,28 +321,28 @@ mixin _PairSections on State<DaemonPanel> {
final extra = [
if (harness != null)
Padding(
- padding: EdgeInsets.only(left: _cell.width * 2),
+ padding: const EdgeInsets.only(left: 16),
child: Text(
harness,
key: ValueKey('daemon-harness-$key'),
- style: _ink(_muted),
+ style: AppType.monoMeta(color: _muted),
),
),
for (final item in listing)
Padding(
- padding: EdgeInsets.only(left: _cell.width * 2),
+ padding: const EdgeInsets.only(left: 16),
child: Text('- $item', style: _ink()),
),
if (detail != null && detail.isNotEmpty)
Padding(
- padding: EdgeInsets.only(left: _cell.width * 2),
+ padding: const EdgeInsets.only(left: 16),
child: DaemonDetailBox(
key: ValueKey('daemon-detail-$key'),
text: detail,
- style: _ink(_muted),
- rowHeight: _cell.height,
- maxRows: 10,
- background: Color.lerp(_theme.background, _theme.foreground, .05),
+ style: _detailStyle,
+ rowHeight: _detailRowHeight,
+ maxRows: _detailRows,
+ background: DesktopChrome.field,
),
),
];
@@ -316,7 +370,7 @@ mixin _PairSections on State<DaemonPanel> {
final key = 'confirm:${confirm.id}';
order.add(key);
return Padding(
- padding: EdgeInsets.only(top: _cell.height / 2),
+ padding: const EdgeInsets.only(top: 8),
child: _keyRow(
key,
line: confirm.line,
@@ -458,11 +512,7 @@ mixin _PairSections on State<DaemonPanel> {
/// own, and the lessons it taught, newest first. A lesson reverts with one
/// `harness pair lessons revert`; an answer typed into a harness cannot be
/// taken back, and it says so.
- List<Widget> _didSection(
- List<String> order,
- DaemonBrain brain,
- String name,
- ) {
+ List<Widget> _didSection(List<String> order, DaemonBrain brain, String name) {
final acted = brain.state!.acted;
final lessons = _lessons;
final taught = [
@@ -492,18 +542,24 @@ mixin _PairSections on State<DaemonPanel> {
for (final a in acted.take(5))
Text(
'${who(a.by)}: ${a.name} '
- '${a.text.isNotEmpty ? a.text : a.action.isNotEmpty ? a.action : 'acted'}'
+ '${a.text.isNotEmpty
+ ? a.text
+ : a.action.isNotEmpty
+ ? a.action
+ : 'acted'}'
'${ago(a.at)}',
- key: ValueKey('daemon-did-${a.machineId}-${a.agentId}-${a.at?.millisecondsSinceEpoch}'),
+ key: ValueKey(
+ 'daemon-did-${a.machineId}-${a.agentId}-${a.at?.millisecondsSinceEpoch}',
+ ),
style: _ink(_muted),
),
if (acted.isNotEmpty)
Padding(
- padding: EdgeInsets.only(left: _cell.width * 2),
+ padding: const EdgeInsets.only(left: 16),
child: Text(
'an answer typed into a harness cannot be taken back.',
key: const ValueKey('daemon-did-no-revert'),
- style: _ink(_muted.withValues(alpha: .45)),
+ style: _ink(_muted),
),
),
for (final lesson in taught.take(5))
@@ -522,7 +578,7 @@ mixin _PairSections on State<DaemonPanel> {
),
_action(
'did-revert:${lesson.id}',
- '[ revert ]',
+ 'Revert',
lessons!.busy
? null
: () => unawaited(lessons.revert(lesson.id)),
@@ -576,7 +632,7 @@ mixin _PairSections on State<DaemonPanel> {
),
for (final entry in talk.skip(max(0, talk.length - 4)))
Text(
- entry.you ? 'you > ${entry.text}' : '<$name> ${entry.text}',
+ entry.you ? 'You: ${entry.text}' : '$name: ${entry.text}',
style: _ink(entry.you ? _muted : null),
maxLines: 3,
overflow: TextOverflow.ellipsis,
@@ -587,15 +643,13 @@ mixin _PairSections on State<DaemonPanel> {
key: const ValueKey('daemon-talk-status'),
style: _ink(
brain.talkPhase == DaemonTalkPhase.failed && wait == null
- ? _theme.red
+ ? Theme.of(context).colorScheme.error
: _muted,
),
),
Row(
- crossAxisAlignment: CrossAxisAlignment.baseline,
- textBaseline: TextBaseline.alphabetic,
+ crossAxisAlignment: CrossAxisAlignment.center,
children: [
- Text('> ', style: _ink(_muted)),
Expanded(
child: TextField(
key: const ValueKey('daemon-talk-input'),
@@ -605,9 +659,7 @@ mixin _PairSections on State<DaemonPanel> {
maxLines: 1,
maxLength: 2000,
style: _ink(),
- cursorWidth: _cell.width,
- cursorHeight: _cell.height,
- cursorColor: _theme.cursor,
+ cursorColor: DesktopChrome.accent,
textInputAction: TextInputAction.send,
decoration: InputDecoration(
hintText: wait == null
@@ -615,13 +667,6 @@ mixin _PairSections on State<DaemonPanel> {
: 'wait ${(wait.inMilliseconds / 1000).ceil()}s',
hintStyle: _ink(_muted.withValues(alpha: .4)),
counterText: '',
- isDense: true,
- filled: false,
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- disabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- contentPadding: EdgeInsets.zero,
),
onSubmitted: (_) {
_send();
@@ -629,6 +674,17 @@ mixin _PairSections on State<DaemonPanel> {
},
),
),
+ const SizedBox(width: 8),
+ DesktopPill(
+ key: const ValueKey('daemon-talk-send'),
+ label: 'Send',
+ onPressed: wait == null
+ ? () {
+ _send();
+ _talkFocus.requestFocus();
+ }
+ : null,
+ ),
],
),
// Every talk is a turn of the person's own engine: said, as harnessd
@@ -638,12 +694,12 @@ mixin _PairSections on State<DaemonPanel> {
'each talk is a turn of $name\'s harness on your engine: '
'it spends your model usage.',
key: const ValueKey('daemon-talk-cost'),
- style: _ink(_muted.withValues(alpha: .45)),
+ style: _ink(_muted),
),
if (canOpen)
_action(
'conversation',
- '[ open the conversation ]',
+ 'Open conversation',
widget.onOpenConversation,
tooltip: "$name's own harness, with everything it said",
),
@@ -688,19 +744,19 @@ mixin _PairSections on State<DaemonPanel> {
if (liveIds.contains(lesson.id)) continue;
rows.add(
Padding(
- padding: EdgeInsets.only(top: _cell.height / 2),
+ padding: const EdgeInsets.only(top: 8),
child: Text(
'${lesson.pending ? 'pending' : 'learned'} ${lesson.title}'
'${lesson.approved == null ? '' : ' · ${lesson.approved}'}',
key: ValueKey('daemon-lesson-${lesson.id}'),
- style: _ink(lesson.pending ? _theme.yellow : null),
+ style: _ink(),
),
),
);
if (lesson.description.isNotEmpty) {
rows.add(
Padding(
- padding: EdgeInsets.only(left: _cell.width * 2),
+ padding: const EdgeInsets.only(left: 16),
child: Text(lesson.description, style: _ink(_muted)),
),
);
@@ -708,14 +764,14 @@ mixin _PairSections on State<DaemonPanel> {
if (lessons.shownId == lesson.id && lessons.shownText != null) {
rows.add(
Padding(
- padding: EdgeInsets.only(left: _cell.width * 2),
+ padding: const EdgeInsets.only(left: 16),
child: DaemonDetailBox(
key: ValueKey('daemon-lesson-text-${lesson.id}'),
text: lessons.shownText!,
- style: _ink(_muted),
- rowHeight: _cell.height,
- maxRows: 14,
- background: Color.lerp(_theme.background, _theme.foreground, .04),
+ style: _detailStyle,
+ rowHeight: _detailRowHeight,
+ maxRows: _detailRows,
+ background: DesktopChrome.field,
),
),
);
@@ -725,7 +781,7 @@ mixin _PairSections on State<DaemonPanel> {
final buttons = <Widget>[
_action(
'lesson-show:$id',
- lessons.shownId == id ? '[ hide ]' : '[ show ]',
+ lessons.shownId == id ? 'Hide' : 'Show',
lessons.busy ? null : () => unawaited(lessons.show(id)),
),
];
@@ -734,7 +790,7 @@ mixin _PairSections on State<DaemonPanel> {
buttons.add(
_action(
'lesson-skip:$id',
- '[ skip ]',
+ 'Skip',
lessons.busy ? null : () => unawaited(lessons.skip(id)),
tooltip: 'Never proposed again',
),
@@ -744,7 +800,7 @@ mixin _PairSections on State<DaemonPanel> {
buttons.add(
_action(
'lesson-revert:$id',
- '[ revert ]',
+ 'Revert',
lessons.busy ? null : () => unawaited(lessons.revert(id)),
tooltip: 'One git revert: every agent forgets it',
),
@@ -752,8 +808,8 @@ mixin _PairSections on State<DaemonPanel> {
}
rows.add(
Padding(
- padding: EdgeInsets.only(left: _cell.width * 2),
- child: Wrap(spacing: _cell.width * 2, children: buttons),
+ padding: const EdgeInsets.only(left: 16),
+ child: Wrap(spacing: 8, runSpacing: 8, children: buttons),
),
);
// Teaching is the person's alone: the lesson's own line, or a
@@ -761,12 +817,12 @@ mixin _PairSections on State<DaemonPanel> {
if (lesson.pending) {
rows.add(
Padding(
- padding: EdgeInsets.only(left: _cell.width * 2),
+ padding: const EdgeInsets.only(left: 16),
child: Text(
'to teach it: its [y] when $name proposes it, or '
'`${DaemonLessons.approveCommand(id)}` in a terminal.',
key: ValueKey('daemon-lesson-how-$id'),
- style: _ink(_muted.withValues(alpha: .45)),
+ style: _ink(_muted),
),
),
);
@@ -781,7 +837,7 @@ mixin _PairSections on State<DaemonPanel> {
...rows,
if (lessons.message != null)
Padding(
- padding: EdgeInsets.only(top: _cell.height / 2),
+ padding: const EdgeInsets.only(top: 8),
child: Text(
lessons.message!,
key: const ValueKey('daemon-lessons-message'),
@@ -815,25 +871,45 @@ mixin _PairSections on State<DaemonPanel> {
)) ...[
() {
order.add('autonomy:$id');
- final mark = acting == id
- ? '(*)'
- : asked == id
- ? '(~)'
- : '( )';
- return _action(
- 'autonomy:$id',
- '$mark $label${asked == id && acting != id ? ' waits for your yes' : ''}',
- watching ? () => zooController.autonomy(id) : null,
- color: acting == id
- ? _theme.cursor
- : asked == id
- ? _theme.yellow
- : _theme.foreground,
- tooltip: words,
+ final selected = acting == id;
+ final waiting = asked == id && !selected;
+ return Semantics(
+ selected: selected,
+ inMutuallyExclusiveGroup: true,
+ child: TextButton(
+ key: ValueKey('daemon-autonomy:$id'),
+ focusNode: _node('autonomy:$id'),
+ onPressed: watching ? () => zooController.autonomy(id) : null,
+ style: _buttonStyle.copyWith(
+ backgroundColor: WidgetStatePropertyAll(
+ selected ? DesktopChrome.selection : null,
+ ),
+ ),
+ child: Row(
+ children: [
+ Icon(
+ selected
+ ? AppIcons.circleDot
+ : waiting
+ ? AppIcons.clock
+ : AppIcons.circle,
+ size: 18,
+ color: selected ? DesktopChrome.accent : _muted,
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ '$label${waiting ? ' · waits for your yes' : ''}',
+ style: _ink(watching ? null : _muted),
+ ),
+ ),
+ ],
+ ),
+ ),
);
}(),
Padding(
- padding: EdgeInsets.only(left: _cell.width * 4),
+ padding: const EdgeInsets.only(left: 24),
child: Text(words, style: _ink(_muted)),
),
for (final confirm in confirms)
@@ -846,7 +922,7 @@ mixin _PairSections on State<DaemonPanel> {
!daemonAutonomyWords.containsKey(confirm.level))
_confirmRow(order, confirm),
Padding(
- padding: EdgeInsets.only(top: _cell.height / 2),
+ padding: const EdgeInsets.only(top: 8),
child: Text(
'the floor, at every level: $daemonFloorLine',
key: const ValueKey('daemon-panel-floor'),
@@ -858,7 +934,7 @@ mixin _PairSections on State<DaemonPanel> {
order.add('rules');
return _action(
'rules',
- '[ rules: $daemonRulesPath ]',
+ 'Open rules file',
widget.onOpenRules,
tooltip: 'What act within rules may answer, per harness',
);
@@ -881,7 +957,7 @@ mixin _PairSections on State<DaemonPanel> {
final step = _consentStep;
final controller = face.zoo;
Widget screen(DaemonConsentStep step) => Padding(
- padding: EdgeInsets.only(top: _cell.height / 2),
+ padding: const EdgeInsets.only(top: 8),
child: DaemonConsent(
name: name,
step: step,
@@ -927,7 +1003,7 @@ mixin _PairSections on State<DaemonPanel> {
),
_action(
'consent',
- '[ review what $name sees ]',
+ 'Review what $name sees',
() => setState(() => _consentStep = DaemonConsentStep.watch),
),
];
@@ -952,9 +1028,7 @@ mixin _PairSections on State<DaemonPanel> {
),
_action(
'consent',
- consent?.watching == true
- ? '[ stop watching ]'
- : '[ review what $name sees ]',
+ consent?.watching == true ? 'Stop watching' : 'Review what $name sees',
consent?.watching == true
? () => controller.consent(watching: false)
: () => setState(() => _consentStep = DaemonConsentStep.watch),
diff --git a/desktop/lib/widgets/delete_agent_dialog.dart b/desktop/lib/widgets/delete_agent_dialog.dart
index 80bf1cf4a..803bb6220 100644
--- a/desktop/lib/widgets/delete_agent_dialog.dart
+++ b/desktop/lib/widgets/delete_agent_dialog.dart
@@ -4,8 +4,10 @@ import 'package:flutter/material.dart';
import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
-import '../terminal/terminal_text.dart';
-import 'box_chrome.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
+import 'box_chrome.dart' show BoxAnnouncer;
import 'engine_identity.dart';
import 'terminal_prompt.dart';
@@ -135,110 +137,90 @@ class _StopAgentPromptState extends State<_StopAgentPrompt> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
- return ListenableBuilder(
- listenable: terminalFontStore,
- builder: (context, _) => TerminalPromptKeys(
- focusNode: _promptFocus,
- cancel: _close,
- pageDown: () => _page(1),
- pageUp: () => _page(-1),
- child: TerminalPrompt(
+ grid.AppTheme.watch(context);
+ final danger = Theme.of(context).colorScheme.error;
+ final closeLabel = _stopping ? 'Close' : 'Cancel';
+ return TerminalPromptKeys(
+ focusNode: _promptFocus,
+ cancel: _close,
+ pageDown: () => _page(1),
+ pageUp: () => _page(-1),
+ child: DesktopPromptSurface(
+ body: DesktopPromptScrollBody(
+ controller: _body,
child: Column(
- mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Flexible(
- child: SingleChildScrollView(
- controller: _body,
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- widget.terminal ? 'Stop Terminal' : 'Stop Harness',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- const SizedBox(height: 12),
- Text(
- widget.name,
- style: boxMonoStyle(weight: FontWeight.w600),
- ),
- if (widget.notifier
- .stateOf(widget.machineId)
- ?.machine
- .displayName
- case final machine?) ...[
- const SizedBox(height: 4),
- Text(machine, style: boxMonoStyle(color: kBoxFaint)),
- ],
- const SizedBox(height: 10),
- Text(
- widget.terminal
- ? 'End this shell and anything running in it? Files are kept.'
- : 'Stop this harness? Project files and saved conversation history are kept.',
- style: boxMonoStyle(color: boxText(.70)),
- ),
- const SizedBox(height: 8),
- Text(
- 'Its panes close across swarms. Close Pane keeps it running.',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- if (_stopping) ...[
- const SizedBox(height: 12),
- Text(
- 'Stopping continues if you close this prompt.',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ],
- ],
- ),
- ),
+ Text(
+ widget.terminal ? 'Stop Terminal' : 'Stop Harness',
+ style: DesktopChrome.heading(),
+ ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ widget.name,
+ style: DesktopChrome.text(size: 14, medium: true),
+ ),
+ if (widget.notifier.stateOf(widget.machineId)?.machine.displayName
+ case final machine?) ...[
+ const SizedBox(height: 4),
+ Text(machine, style: DesktopChrome.metadata()),
+ ],
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ widget.terminal
+ ? 'End this shell and anything running in it? Files are kept.'
+ : 'Stop this harness? Project files and saved conversation history are kept.',
+ style: DesktopChrome.text(size: 13),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'Its panes close across tabs. Close Pane keeps it running.',
+ style: DesktopChrome.text(size: 13, color: DesktopChrome.muted),
),
- if (!_stopping)
- Padding(
- padding: const EdgeInsets.fromLTRB(14, 0, 14, 10),
- child: Wrap(
- spacing: 12,
- children: [
- terminalPromptButton(
- 'Cancel',
- _close,
- focusNode: _cancel,
- ),
- terminalPromptButton(
- 'Stop',
- _stop,
- danger: true,
- key: const Key('agent-stop-confirm'),
- ),
- ],
+ if (_stopping) ...[
+ const SizedBox(height: 12),
+ Text(
+ 'Stopping continues if you close this dialog.',
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
),
),
- BoxHintStrip(
- message: _error ?? (_stopping ? 'Stopping…' : null),
- isError: _error != null,
- hints: [
- if (!_stopping)
- BoxHint(
- terminalPromptHint(context, 'picker.accept', 'enter'),
- 'select',
- ),
- if (!_stopping)
- BoxHint(
- terminalPromptHint(context, 'picker.complete', 'tab'),
- 'controls',
- ),
- BoxHint(
- terminalPromptHint(context, 'picker.cancel', 'esc'),
- 'close',
- onTap: _close,
- ),
- ],
- ),
+ ],
],
),
),
+ footer: _error != null || _stopping
+ ? Semantics(
+ liveRegion: true,
+ child: DesktopPromptMessage(
+ _error ?? 'Stopping…',
+ color: _error == null ? DesktopChrome.muted : danger,
+ ),
+ )
+ : null,
+ actions: [
+ Tooltip(
+ message:
+ '$closeLabel · ${terminalPromptHint(context, 'picker.cancel', 'esc')}',
+ child: TextButton(
+ focusNode: _stopping ? null : _cancel,
+ onPressed: _close,
+ child: Text(closeLabel),
+ ),
+ ),
+ if (!_stopping)
+ Tooltip(
+ message:
+ 'Stop · ${terminalPromptHint(context, 'picker.accept', 'enter')}',
+ child: FilledButton(
+ key: const Key('agent-stop-confirm'),
+ onPressed: _stop,
+ style: grid.dangerButtonStyle(),
+ child: const Text('Stop'),
+ ),
+ ),
+ ],
),
);
}
diff --git a/desktop/lib/widgets/desktop_chrome.dart b/desktop/lib/widgets/desktop_chrome.dart
new file mode 100644
index 000000000..9d68b8407
--- /dev/null
+++ b/desktop/lib/widgets/desktop_chrome.dart
@@ -0,0 +1,383 @@
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+
+/// Desktop presentation around the terminal. The same controllers and keyboard
+/// actions own creation, search, and resource management on every platform.
+class DesktopChrome extends InheritedWidget {
+ const DesktopChrome({super.key, required super.child});
+
+ static bool of(BuildContext context) =>
+ context.dependOnInheritedWidgetOfExactType<DesktopChrome>() != null;
+
+ static Color get foreground => grid.AppPalette.textPrimary;
+ static Color get muted => grid.AppPalette.textSecondary;
+ static Color get surface => grid.AppDesktop.surface;
+ static Color get rim => grid.AppDesktop.rim;
+ static Color get field => grid.AppDesktop.field;
+ static Color get accent => grid.AppPalette.accentOnSurface;
+ static Color get selection => accent.withValues(alpha: .14);
+ static Color get activeSelection => grid.AppDesktop.selection;
+ static Color get onSelection => grid.AppDesktop.onSelection;
+ static Color get selectionDetail => grid.AppDesktop.selectionDetail;
+ static Color get focusRing => grid.AppDesktop.focus;
+ static const dialogRadius = grid.AppDesktop.dialogRadius;
+ static const menuRadius = grid.AppDesktop.menuRadius;
+ static const rowRadius = grid.AppDesktop.rowRadius;
+ static const controlRadius = grid.AppDesktop.fieldRadius;
+ static const panelPadding = grid.AppDesktop.panelPadding;
+ static const groupGap = grid.AppDesktop.groupGap;
+ static const controlGap = grid.AppDesktop.controlGap;
+ static const controlHeight = grid.AppControl.height;
+ static const compactControlHeight = grid.AppControl.heightSmall;
+ static TextStyle text({
+ Color? color,
+ double size = 14,
+ bool medium = false,
+ double height = 1.45,
+ }) => grid.AppType.body(
+ color: color ?? foreground,
+ fontWeight: medium ? FontWeight.w500 : FontWeight.w400,
+ height: height,
+ ).copyWith(fontSize: size);
+
+ static TextStyle control({Color? color, bool medium = false}) =>
+ text(color: color, size: 13, medium: medium, height: 1.25);
+ static TextStyle metadata({Color? color}) =>
+ text(color: color ?? muted, size: 12, height: 1.35);
+ static TextStyle heading({Color? color}) =>
+ grid.AppType.heading(color: color ?? foreground, height: 1.3);
+
+ static OutlinedBorder shape({double radius = dialogRadius}) =>
+ RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(radius),
+ side: BorderSide(color: rim),
+ );
+
+ @override
+ bool updateShouldNotify(DesktopChrome oldWidget) => false;
+}
+
+/// Shared by creation, search, and their child choosers. A visible frame keeps
+/// the modal distinct from the workspace without turning it into another page.
+class DesktopDialogSurface extends StatelessWidget {
+ const DesktopDialogSurface({
+ super.key,
+ required this.child,
+ this.radius = DesktopChrome.dialogRadius,
+ this.elevation = grid.AppDesktop.dialogElevation,
+ });
+
+ final Widget child;
+ final double radius;
+ final double elevation;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Material(
+ color: DesktopChrome.surface,
+ surfaceTintColor: Colors.transparent,
+ elevation: elevation,
+ shadowColor: grid.AppDesktop.shadow,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(radius),
+ side: BorderSide(
+ color: MediaQuery.highContrastOf(context)
+ ? DesktopChrome.foreground.withValues(alpha: .6)
+ : DesktopChrome.rim,
+ ),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: child,
+ );
+ }
+}
+
+class DesktopDialogBackdrop extends StatelessWidget {
+ const DesktopDialogBackdrop({super.key, required this.onDismiss});
+
+ final VoidCallback onDismiss;
+
+ @override
+ Widget build(BuildContext context) => BlockSemantics(
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onDismiss,
+ child: ColoredBox(
+ color: grid.AppDesktop.veil(Theme.of(context).brightness),
+ ),
+ ),
+ );
+}
+
+/// The Store's quiet capsule treatment, with normal focus and disabled states.
+class DesktopPill extends StatelessWidget {
+ const DesktopPill({
+ super.key,
+ required this.label,
+ required this.onPressed,
+ this.icon,
+ this.leading,
+ this.menu = false,
+ this.selected,
+ this.tooltip,
+ this.monospace = false,
+ this.semanticLabel,
+ this.semanticHint,
+ this.focusNode,
+ this.foregroundColor,
+ this.compact = false,
+ this.quiet = false,
+ this.capsule = true,
+ this.textSize = 13,
+ this.truncateFromStart = false,
+ this.menuIcon = AppIcons.chevronDown,
+ this.highlightFocus = false,
+ });
+
+ final String label;
+ final VoidCallback? onPressed;
+ final IconData? icon;
+ final Widget? leading;
+ final bool menu, monospace;
+ final bool? selected;
+ final String? tooltip;
+ final String? semanticLabel;
+ final String? semanticHint;
+ final FocusNode? focusNode;
+ final Color? foregroundColor;
+ final bool compact;
+ final bool quiet, capsule;
+ final double textSize;
+ final bool truncateFromStart;
+ final IconData menuIcon;
+ final bool highlightFocus;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final ink = foregroundColor ?? DesktopChrome.foreground;
+ final highContrast = MediaQuery.highContrastOf(context);
+ final button = TextButton(
+ focusNode: focusNode,
+ onPressed: onPressed,
+ style:
+ TextButton.styleFrom(
+ foregroundColor: ink,
+ disabledForegroundColor: ink.withValues(alpha: .38),
+ enabledMouseCursor: SystemMouseCursors.click,
+ disabledMouseCursor: SystemMouseCursors.basic,
+ backgroundColor: quiet
+ ? Colors.transparent
+ : ink.withValues(alpha: selected == true ? .13 : .055),
+ minimumSize: Size(
+ 0,
+ compact
+ ? DesktopChrome.compactControlHeight
+ : capsule
+ ? DesktopChrome.controlHeight
+ : 34,
+ ),
+ padding: EdgeInsets.symmetric(
+ horizontal: quiet
+ ? 6
+ : compact
+ ? 9
+ : 11,
+ vertical: compact || capsule ? 4 : 7,
+ ),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ capsule ? 20 : DesktopChrome.controlRadius,
+ ),
+ ),
+ textStyle: DesktopChrome.text(size: textSize, height: 1.25),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ splashFactory: NoSplash.splashFactory,
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ // Reserve the same rim in every state; focus never moves text.
+ width: grid.AppDesktop.focusWidth,
+ color:
+ states.contains(WidgetState.disabled) ||
+ (quiet && !highContrast)
+ ? Colors.transparent
+ : states.contains(WidgetState.focused) || highlightFocus
+ ? (highContrast
+ ? DesktopChrome.accent
+ : DesktopChrome.focusRing)
+ : quiet
+ ? Colors.transparent
+ : highContrast
+ ? ink.withValues(alpha: .45)
+ : ink.withValues(alpha: .09),
+ ),
+ ),
+ backgroundColor: WidgetStateProperty.resolveWith(
+ (states) => selected == true
+ ? ink.withValues(alpha: .13)
+ : states.contains(WidgetState.focused) &&
+ !states.contains(WidgetState.disabled)
+ ? ink.withValues(alpha: .10)
+ : quiet
+ ? Colors.transparent
+ : ink.withValues(alpha: selected == true ? .13 : .055),
+ ),
+ overlayColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? Colors.transparent
+ : states.contains(WidgetState.pressed)
+ ? ink.withValues(alpha: .12)
+ : states.contains(WidgetState.hovered)
+ ? ink.withValues(alpha: highContrast ? .10 : .05)
+ : Colors.transparent,
+ ),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (leading != null || icon != null) ...[
+ leading ?? Icon(icon, size: 16),
+ const SizedBox(width: 7),
+ ],
+ Flexible(
+ child: truncateFromStart
+ ? DesktopSuffixText(
+ label,
+ style: monospace ? grid.AppType.mono() : null,
+ semanticsLabel: semanticLabel,
+ )
+ : Text(
+ label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: monospace ? grid.AppType.mono() : null,
+ semanticsLabel: semanticLabel,
+ ),
+ ),
+ if (menu) ...[const SizedBox(width: 7), Icon(menuIcon, size: 16)],
+ ],
+ ),
+ );
+ final control = Semantics(
+ selected: selected,
+ hint: semanticHint,
+ child: button,
+ );
+ return tooltip == null
+ ? control
+ : Tooltip(message: tooltip!, child: control);
+ }
+}
+
+/// The same heading and dismiss control for every list or task dialog.
+/// A form can omit Close when its Cancel action already provides dismissal.
+class DesktopDialogHeader extends StatelessWidget {
+ const DesktopDialogHeader({
+ super.key,
+ required this.title,
+ this.detail,
+ this.onClose,
+ this.padding = const EdgeInsets.fromLTRB(24, 24, 16, 16),
+ });
+
+ final String title;
+ final String? detail;
+ final VoidCallback? onClose;
+ final EdgeInsets padding;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: padding,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Semantics(
+ header: true,
+ child: Text(title, style: DesktopChrome.heading()),
+ ),
+ if (detail != null) ...[
+ const SizedBox(height: 4),
+ Text(detail!, style: DesktopChrome.metadata()),
+ ],
+ ],
+ ),
+ ),
+ if (onClose != null) ...[
+ const SizedBox(width: 12),
+ IconButton(
+ tooltip: 'Close',
+ onPressed: onClose,
+ icon: const Icon(AppIcons.close, size: 16),
+ constraints: const BoxConstraints.tightFor(width: 32, height: 32),
+ padding: const EdgeInsets.all(8),
+ visualDensity: VisualDensity.standard,
+ ),
+ ],
+ ],
+ ),
+ );
+}
+
+/// Keep the identifying end of a branch name without reversing its text
+/// direction. Full labels remain available to accessibility and tooltips.
+class DesktopSuffixText extends StatelessWidget {
+ const DesktopSuffixText(
+ this.text, {
+ super.key,
+ this.style,
+ this.semanticsLabel,
+ });
+
+ final String text;
+ final TextStyle? style;
+ final String? semanticsLabel;
+
+ @override
+ Widget build(BuildContext context) => LayoutBuilder(
+ builder: (context, constraints) {
+ final painter = TextPainter(
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ maxLines: 1,
+ );
+ final resolved = DefaultTextStyle.of(context).style.merge(style);
+ bool fits(String value) {
+ painter.text = TextSpan(text: value, style: resolved);
+ painter.layout();
+ return painter.width <= constraints.maxWidth;
+ }
+
+ var visible = text;
+ if (!fits(text)) {
+ final characters = text.characters.toList(growable: false);
+ var low = 0, high = characters.length;
+ while (low < high) {
+ final count = (low + high + 1) ~/ 2;
+ if (fits('…${characters.skip(characters.length - count).join()}')) {
+ low = count;
+ } else {
+ high = count - 1;
+ }
+ }
+ visible = '…${characters.skip(characters.length - low).join()}';
+ }
+ painter.dispose();
+ return Text(
+ visible,
+ style: style,
+ maxLines: 1,
+ overflow: TextOverflow.clip,
+ semanticsLabel: semanticsLabel ?? text,
+ );
+ },
+ );
+}
diff --git a/desktop/lib/widgets/desktop_prompt_surface.dart b/desktop/lib/widgets/desktop_prompt_surface.dart
new file mode 100644
index 000000000..a3e34adf3
--- /dev/null
+++ b/desktop/lib/widgets/desktop_prompt_surface.dart
@@ -0,0 +1,135 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+
+/// Shared anatomy for compact desktop forms and confirmations. Callers retain
+/// their scrolling, focus, keyboard handling, and operation state.
+class DesktopPromptSurface extends StatelessWidget {
+ const DesktopPromptSurface({
+ super.key,
+ required this.body,
+ required this.actions,
+ this.footer,
+ this.width = grid.AppDesktop.formWidth,
+ });
+
+ /// Normally [DesktopPromptScrollBody]. Forms may retain their own controller.
+ final Widget body;
+ final List<Widget> actions;
+
+ /// A short status or recovery message that remains beside the actions.
+ final Widget? footer;
+ final double width;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return DesktopChrome(
+ child: Dialog(
+ insetPadding: const EdgeInsets.all(20),
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ child: SizedBox(
+ width: width,
+ child: DesktopDialogSurface(
+ child: Padding(
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(child: body),
+ if (footer case final footer?) ...[
+ const SizedBox(height: DesktopChrome.groupGap),
+ footer,
+ ],
+ const SizedBox(height: DesktopChrome.groupGap),
+ Wrap(
+ alignment: WrapAlignment.end,
+ spacing: DesktopChrome.controlGap,
+ runSpacing: DesktopChrome.controlGap,
+ children: actions,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// Long explanations and enlarged fields disclose their scroll position before
+/// the first gesture. One controller owns the body and its draggable thumb;
+/// nested editors retain their own scrolling and keyboard behavior.
+class DesktopPromptScrollBody extends StatefulWidget {
+ const DesktopPromptScrollBody({
+ super.key,
+ required this.child,
+ this.controller,
+ });
+
+ final Widget child;
+ final ScrollController? controller;
+
+ @override
+ State<DesktopPromptScrollBody> createState() =>
+ _DesktopPromptScrollBodyState();
+}
+
+class _DesktopPromptScrollBodyState extends State<DesktopPromptScrollBody> {
+ final _controller = ScrollController();
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final controller = widget.controller ?? _controller;
+ return ScrollConfiguration(
+ behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
+ child: Scrollbar(
+ controller: controller,
+ thumbVisibility: true,
+ child: SingleChildScrollView(
+ controller: controller,
+ padding: const EdgeInsetsDirectional.only(end: 12),
+ child: widget.child,
+ ),
+ ),
+ );
+ }
+}
+
+/// Keeps status and recovery details readable without displacing the actions.
+/// Longer messages scroll and remain selectable in full; selection does not
+/// introduce a Tab stop. Callers retain announcement and operation ownership.
+class DesktopPromptMessage extends StatelessWidget {
+ const DesktopPromptMessage(this.message, {super.key, this.color});
+
+ final String message;
+ final Color? color;
+
+ @override
+ Widget build(BuildContext context) {
+ final style = DesktopChrome.text(size: 13, color: color);
+ final measure = TextPainter(
+ text: TextSpan(text: 'M\nM\nM', style: style),
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ )..layout();
+ final maxHeight = measure.height;
+ measure.dispose();
+ return ConstrainedBox(
+ constraints: BoxConstraints(maxHeight: maxHeight),
+ child: DesktopPromptScrollBody(
+ child: SelectableText(message, style: style),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/desktop_search_panel.dart b/desktop/lib/widgets/desktop_search_panel.dart
new file mode 100644
index 000000000..dfb1b57be
--- /dev/null
+++ b/desktop/lib/widgets/desktop_search_panel.dart
@@ -0,0 +1,462 @@
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import '../state/swarm_navigation.dart';
+import '../state/swarm_search.dart';
+import 'desktop_chrome.dart';
+import 'box_chrome.dart' show ReadlineKeys;
+import 'swarm_switcher.dart';
+import 'swarm_search_input.dart';
+import 'key_hints.dart';
+
+/// A desktop command palette over the existing search and activation pipeline.
+/// Category buttons edit the same query as keyboard prefixes; no second index.
+class DesktopSearchPanel extends StatelessWidget {
+ const DesktopSearchPanel({
+ super.key,
+ required this.search,
+ required this.editing,
+ required this.focusNode,
+ required this.onChoose,
+ required this.onClose,
+ required this.onRefocus,
+ required this.previewBuilder,
+ this.hostBar,
+ });
+
+ final SwarmSearchController search;
+ final TextEditingController editing;
+ final FocusNode focusNode;
+ final ValueChanged<SwarmSearchSelection> onChoose;
+ final VoidCallback onClose, onRefocus;
+ final Widget Function() previewBuilder;
+ final Widget? hostBar;
+
+ static const maxWidth = 1120.0;
+ static const maxHeight = 680.0;
+
+ static const categories = [
+ ('Harnesses', ''),
+ ('Machines', '@'),
+ ('Projects', '#'),
+ ('Models', ':'),
+ ('Store', '*'),
+ ('Commands', '>'),
+ ];
+
+ String get _prefix => search.isProjectMode
+ ? '#'
+ : search.isMachineMode
+ ? '@'
+ : search.isModelMode
+ ? ':'
+ : search.isStoreMode
+ ? '*'
+ : search.isCommandMode
+ ? '>'
+ : '';
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return DesktopChrome(
+ child: Align(
+ alignment: Alignment.topCenter,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: maxWidth,
+ maxHeight: maxHeight,
+ ),
+ child: DesktopDialogSurface(
+ key: const ValueKey('swarm-search-results'),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ ?hostBar,
+ if (search.split != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
+ child: Text(
+ search.title,
+ style: DesktopChrome.text(size: 13, medium: true),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 12, 16, 8),
+ child: Row(
+ children: [
+ Icon(
+ AppIcons.search,
+ size: 21,
+ color: DesktopChrome.muted,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: ReadlineKeys(
+ controller: editing,
+ onChanged: search.setQuery,
+ child: SwarmSearchInput(
+ inputKey: const ValueKey('swarm-search-input'),
+ controller: editing,
+ focusNode: focusNode,
+ search: search,
+ onClose: onClose,
+ onChanged: search.setQuery,
+ onOpen: onRefocus,
+ hintText: search.hint,
+ ),
+ ),
+ ),
+ ValueListenableBuilder<TextEditingValue>(
+ valueListenable: editing,
+ builder: (context, value, _) => value.text.isEmpty
+ ? const SizedBox(width: 32, height: 32)
+ : _toolbarButton(
+ context,
+ key: const ValueKey('search-clear-query'),
+ tooltip: 'Clear search',
+ onPressed: () {
+ editing.clear();
+ search.setQuery('');
+ onRefocus();
+ },
+ icon: Icon(
+ AppIcons.circleX,
+ size: 16,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ),
+ ListenableBuilder(
+ listenable: search,
+ builder: (context, _) => _toolbarButton(
+ context,
+ key: const ValueKey('search-toggle-preview'),
+ tooltip: search.previewVisible
+ ? 'Hide preview'
+ : 'Show preview',
+ isSelected: search.previewVisible,
+ onPressed: search.supportsPreview
+ ? () {
+ search.togglePreview();
+ onRefocus();
+ }
+ : null,
+ icon: const Icon(AppIcons.columns2, size: 18),
+ ),
+ ),
+ if (hostBar == null)
+ _toolbarButton(
+ context,
+ key: const ValueKey('search-close'),
+ tooltip: 'Close search',
+ onPressed: onClose,
+ icon: const Icon(AppIcons.close, size: 18),
+ ),
+ ],
+ ),
+ ),
+ if (hostBar == null)
+ ListenableBuilder(
+ listenable: search,
+ builder: (context, _) => SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ padding: const EdgeInsets.fromLTRB(20, 2, 20, 14),
+ child: _SearchScopes(
+ selected: _prefix,
+ onRefocus: onRefocus,
+ onChanged: (prefix) {
+ final words = search.wordsQuery;
+ search.setQuery(
+ prefix.isEmpty
+ ? words
+ : '$prefix $words'.trimRight(),
+ );
+ },
+ ),
+ ),
+ ),
+ Flexible(
+ child: ListenableBuilder(
+ listenable: search,
+ builder: (context, _) => SwarmSearchResults(
+ search: search,
+ onChoose: onChoose,
+ onRefocus: onRefocus,
+ // Keep the dialog, editor, and footer stationary while a
+ // query gains a preview or changes to an empty result.
+ fitRows: false,
+ // The scope control already explains the empty search.
+ // Give results the full width until there is a preview.
+ showPreview: !search.showsTypeHints,
+ sideBySideMinWidth: 800,
+ previewBuilder: previewBuilder,
+ ),
+ ),
+ ),
+ if (KeyHints.visibleOf(context)) ...[
+ Divider(height: 1, color: DesktopChrome.rim),
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 18,
+ vertical: 11,
+ ),
+ child: ListenableBuilder(
+ listenable: search,
+ builder: (context, _) => Wrap(
+ spacing: 20,
+ runSpacing: 8,
+ children: [
+ _hint(context, 'picker.next', 'Browse'),
+ _hint(
+ context,
+ 'picker.accept',
+ search.selected == null
+ ? 'Open'
+ : search.actionLabel(search.selected!),
+ ),
+ _hint(context, 'picker.cancel', 'Close'),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _toolbarButton(
+ BuildContext context, {
+ required Key key,
+ required String tooltip,
+ required VoidCallback? onPressed,
+ required Widget icon,
+ bool? isSelected,
+ }) {
+ final parent = KeymapRegion.of(context);
+ void activate() => onPressed?.call();
+ final button = SizedBox.square(
+ dimension: 32,
+ child: IconButton(
+ key: key,
+ tooltip: tooltip,
+ onPressed: onPressed,
+ isSelected: isSelected,
+ constraints: const BoxConstraints.tightFor(width: 32, height: 32),
+ padding: const EdgeInsets.all(7),
+ visualDensity: VisualDensity.standard,
+ mouseCursor: onPressed == null
+ ? SystemMouseCursors.basic
+ : SystemMouseCursors.click,
+ icon: icon,
+ ),
+ );
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: parent?.composing,
+ actions: {
+ ...?parent?.actions,
+ 'picker.accept': activate,
+ 'picker.complete': () =>
+ FocusManager.instance.primaryFocus?.nextFocus(),
+ 'picker.complete_back': () =>
+ FocusManager.instance.primaryFocus?.previousFocus(),
+ },
+ child: KeymapTheme.of(context) == null
+ ? CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.enter): activate,
+ const SingleActivator(LogicalKeyboardKey.numpadEnter): activate,
+ },
+ child: button,
+ )
+ : Shortcuts(
+ shortcuts: const {
+ SingleActivator(LogicalKeyboardKey.enter): DoNothingIntent(),
+ SingleActivator(LogicalKeyboardKey.numpadEnter):
+ DoNothingIntent(),
+ },
+ child: button,
+ ),
+ );
+ }
+
+ Widget _hint(BuildContext context, String command, String label) {
+ final key = effectiveCommandHint(
+ context,
+ command,
+ contextKind: KeymapContext.picker,
+ );
+ if (key == null) return const SizedBox.shrink();
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(key, style: grid.AppType.monoMeta(color: DesktopChrome.muted)),
+ const SizedBox(width: 7),
+ Text(
+ label,
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ ),
+ ],
+ );
+ }
+}
+
+/// Arrow navigation stays inside the scope group, with one tab stop.
+/// Pointer selection returns directly to typing; Return does the same for keys.
+class _SearchScopes extends StatefulWidget {
+ const _SearchScopes({
+ required this.selected,
+ required this.onChanged,
+ required this.onRefocus,
+ });
+
+ final String selected;
+ final ValueChanged<String> onChanged;
+ final VoidCallback onRefocus;
+
+ @override
+ State<_SearchScopes> createState() => _SearchScopesState();
+}
+
+class _SearchScopesState extends State<_SearchScopes> {
+ var _focused = false;
+ final _focus = FocusNode(debugLabel: 'Search scopes');
+ var _revealScheduled = false;
+ BuildContext? _selectedContext;
+
+ @override
+ void dispose() {
+ _focus.dispose();
+ super.dispose();
+ }
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ // A resize or larger system text can put the active scope outside the
+ // horizontal viewport even when its selection did not change.
+ MediaQuery.sizeOf(context);
+ MediaQuery.textScalerOf(context);
+ _revealSelection();
+ }
+
+ @override
+ void didUpdateWidget(covariant _SearchScopes oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.selected != widget.selected) _revealSelection();
+ }
+
+ void _revealSelection() {
+ if (_revealScheduled) return;
+ _revealScheduled = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _revealScheduled = false;
+ if (!mounted) return;
+ final selected = _selectedContext;
+ if (selected != null && selected.mounted) {
+ Scrollable.ensureVisible(selected, alignment: .5);
+ }
+ });
+ }
+
+ void _move(int delta) {
+ final scopes = DesktopSearchPanel.categories;
+ final index = scopes.indexWhere((scope) => scope.$2 == widget.selected);
+ widget.onChanged(scopes[(index + delta) % scopes.length].$2);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final parent = KeymapRegion.of(context);
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: parent?.composing,
+ actions: {
+ ...?parent?.actions,
+ 'picker.accept': widget.onRefocus,
+ 'picker.next': () => _move(1),
+ 'picker.previous': () => _move(-1),
+ 'picker.control_next': () => _move(1),
+ 'picker.control_previous': () => _move(-1),
+ 'picker.complete': () =>
+ FocusManager.instance.primaryFocus?.nextFocus(),
+ 'picker.complete_back': () =>
+ FocusManager.instance.primaryFocus?.previousFocus(),
+ },
+ child: Focus(
+ key: const ValueKey('search-scopes'),
+ focusNode: _focus,
+ onFocusChange: (focused) => setState(() => _focused = focused),
+ onKeyEvent: (_, event) {
+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
+ return KeyEventResult.ignored;
+ }
+ final key = event.logicalKey;
+ if (key == LogicalKeyboardKey.arrowLeft ||
+ key == LogicalKeyboardKey.arrowRight ||
+ parent == null &&
+ (key == LogicalKeyboardKey.arrowUp ||
+ key == LogicalKeyboardKey.arrowDown)) {
+ _move(
+ key == LogicalKeyboardKey.arrowLeft ||
+ key == LogicalKeyboardKey.arrowUp
+ ? -1
+ : 1,
+ );
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.space ||
+ parent == null &&
+ (key == LogicalKeyboardKey.enter ||
+ key == LogicalKeyboardKey.numpadEnter)) {
+ widget.onRefocus();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: ExcludeFocus(
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ spacing: 6,
+ children: [
+ for (final (label, prefix) in DesktopSearchPanel.categories)
+ Builder(
+ builder: (segmentContext) {
+ final selected = widget.selected == prefix;
+ if (selected) _selectedContext = segmentContext;
+ return DesktopPill(
+ key: ValueKey('search-category-$label'),
+ label: label,
+ capsule: true,
+ selected: selected,
+ highlightFocus: selected && _focused,
+ foregroundColor: selected
+ ? DesktopChrome.foreground
+ : DesktopChrome.muted,
+ tooltip: prefix.isEmpty
+ ? 'Search harnesses'
+ : 'Type $prefix to search ${label.toLowerCase()}',
+ onPressed: () {
+ widget.onChanged(prefix);
+ widget.onRefocus();
+ },
+ );
+ },
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/desktop_workspace_tab.dart b/desktop/lib/widgets/desktop_workspace_tab.dart
new file mode 100644
index 000000000..0bcf9908a
--- /dev/null
+++ b/desktop/lib/widgets/desktop_workspace_tab.dart
@@ -0,0 +1,345 @@
+import 'dart:math' as math;
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/semantics.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import 'box_chrome.dart';
+import 'desktop_chrome.dart';
+
+/// The Flutter counterpart of the AppKit tab: a centered name/status group
+/// and a trailing hover close action. Command replaces status with its hint.
+class DesktopWorkspaceTab extends StatefulWidget {
+ const DesktopWorkspaceTab({
+ super.key,
+ required this.id,
+ required this.label,
+ required this.selected,
+ required this.showShortcuts,
+ required this.onSelect,
+ required this.onClose,
+ this.shortcutHint,
+ this.tooltip,
+ this.activity,
+ this.activityLabel,
+ this.highlighted = false,
+ this.onRename,
+ });
+
+ final String id, label;
+ final bool selected, highlighted;
+ final ValueListenable<bool> showShortcuts;
+ final VoidCallback? onSelect, onClose;
+ final VoidCallback? onRename;
+ final String? shortcutHint, tooltip, activityLabel;
+ final Widget? activity;
+
+ static double _measure(BuildContext context, String text, TextStyle style) {
+ final painter = TextPainter(
+ text: TextSpan(text: text, style: style),
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ maxLines: 1,
+ )..layout();
+ final width = painter.width;
+ painter.dispose();
+ return width;
+ }
+
+ // Reserve the full close target inside the tab's curved body on both sides,
+ // keeping the name centered and clear of the hover action.
+ static const _contentInset = 32.0 + grid.AppDesktop.tabCloseInset;
+ static const _indicatorGap = 6.0;
+
+ static TextStyle _hintStyle({Color? color}) =>
+ DesktopChrome.metadata(color: color).copyWith(
+ fontFamilyFallback: [...grid.AppType.sansFallback, 'Apple Symbols'],
+ );
+
+ static double indicatorWidth(
+ BuildContext context,
+ String? hint, {
+ required bool hasActivity,
+ }) => math
+ .max(
+ hasActivity ? 16.0 : 0.0,
+ hint == null || hint.isEmpty
+ ? 0.0
+ : _measure(context, hint, _hintStyle()),
+ )
+ .clamp(0.0, 72.0);
+
+ static double labelWidth(BuildContext context, String label) =>
+ _measure(context, label, DesktopChrome.control());
+
+ static double naturalWidth(
+ BuildContext context,
+ String label, {
+ String? shortcutHint,
+ bool hasActivity = false,
+ }) {
+ final indicator = indicatorWidth(
+ context,
+ shortcutHint,
+ hasActivity: hasActivity,
+ );
+ return labelWidth(context, label) +
+ _contentInset * 2 +
+ (indicator == 0 ? 0 : indicator + _indicatorGap);
+ }
+
+ static double widthOf(
+ BuildContext context,
+ String label, {
+ String? shortcutHint,
+ bool hasActivity = false,
+ }) => naturalWidth(
+ context,
+ label,
+ shortcutHint: shortcutHint,
+ hasActivity: hasActivity,
+ ).clamp(112, 256);
+
+ @override
+ State<DesktopWorkspaceTab> createState() => _DesktopWorkspaceTabState();
+}
+
+class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
+ bool _hovered = false, _focused = false;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final enabled = widget.onSelect != null;
+ final quietCloseOpacity = MediaQuery.highContrastOf(context) ? .7 : .45;
+ final focusVisible = _focused || widget.highlighted;
+ // Workspace palettes can stay dark beside light app surfaces. Match the
+ // native tab bar's ink to its own surface, independent of terminal colors.
+ final foreground = grid.AppTheme.surfacePalette.foreground;
+ final muted = foreground.withValues(alpha: .65);
+ final fill = widget.selected
+ ? grid.AppPalette.swarmWelcome
+ : _hovered
+ ? foreground.withValues(alpha: .06)
+ : Colors.transparent;
+ final ink = enabled
+ ? widget.selected || _hovered || focusVisible
+ ? foreground
+ : muted
+ : foreground.withValues(alpha: .38);
+ Widget tab = Padding(
+ padding: const EdgeInsets.only(top: grid.AppDesktop.tabTopInset),
+ child: DecoratedBox(
+ decoration: ShapeDecoration(
+ color: fill,
+ shape: DesktopTabBorder(
+ side: focusVisible
+ ? BorderSide(color: DesktopChrome.focusRing)
+ : BorderSide.none,
+ ),
+ ),
+ child: Semantics(
+ container: true,
+ explicitChildNodes: true,
+ selected: widget.selected,
+ child: LayoutBuilder(
+ builder: (context, constraints) => ValueListenableBuilder(
+ valueListenable: widget.showShortcuts,
+ builder: (context, showHints, _) {
+ final showHint =
+ enabled &&
+ showHints &&
+ (widget.shortcutHint?.isNotEmpty ?? false);
+ final indicator = DesktopWorkspaceTab.indicatorWidth(
+ context,
+ widget.shortcutHint,
+ hasActivity: widget.activity != null,
+ );
+ final indicatorSpace = widget.activity != null || showHint
+ ? indicator + DesktopWorkspaceTab._indicatorGap
+ : 0.0;
+ final labelWidth = math.min(
+ DesktopWorkspaceTab.labelWidth(context, widget.label),
+ math.max(
+ 0.0,
+ constraints.maxWidth -
+ DesktopWorkspaceTab._contentInset * 2 -
+ indicatorSpace,
+ ),
+ );
+ final groupLeft =
+ (constraints.maxWidth - labelWidth - indicatorSpace) / 2;
+ return Stack(
+ children: [
+ Positioned.fill(
+ child: Semantics(
+ button: true,
+ enabled: enabled,
+ label: [widget.label, ?widget.activityLabel].join(', '),
+ onTap: widget.onSelect,
+ customSemanticsActions: {
+ if (widget.onClose != null)
+ const CustomSemanticsAction(label: 'Close tab'):
+ widget.onClose!,
+ },
+ child: FocusableActionDetector(
+ enabled: enabled,
+ onShowFocusHighlight: (value) =>
+ setState(() => _focused = value),
+ actions: {
+ ActivateIntent: CallbackAction<ActivateIntent>(
+ onInvoke: (_) {
+ widget.onSelect?.call();
+ return null;
+ },
+ ),
+ },
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: widget.onSelect,
+ onDoubleTap: widget.onRename,
+ child: ExcludeSemantics(
+ child: Stack(
+ children: [
+ Positioned(
+ left: groupLeft,
+ width: labelWidth,
+ top: 0,
+ bottom: 0,
+ child: Center(
+ child: Text(
+ widget.label,
+ key: ValueKey('tab-label:${widget.id}'),
+ textAlign: TextAlign.center,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(
+ color: ink,
+ ),
+ ),
+ ),
+ ),
+ if (indicatorSpace > 0)
+ Positioned(
+ left:
+ groupLeft +
+ labelWidth +
+ DesktopWorkspaceTab._indicatorGap,
+ width: indicator,
+ top: 0,
+ bottom: 0,
+ child: Center(
+ child: showHint
+ ? Text(
+ widget.shortcutHint!,
+ key: ValueKey(
+ 'tab-shortcut:${widget.id}',
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style:
+ DesktopWorkspaceTab._hintStyle(
+ color: ink,
+ ),
+ )
+ : widget.activity,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ Positioned(
+ right: grid.AppDesktop.tabCloseInset,
+ width: 32,
+ top: 0,
+ bottom: 0,
+ child: Center(
+ child: IgnorePointer(
+ ignoring: !_hovered || !enabled,
+ child: ExcludeFocus(
+ excluding: !_hovered || !enabled,
+ child: ExcludeSemantics(
+ excluding: !_hovered || !enabled,
+ child: Opacity(
+ opacity: _hovered && enabled ? 1 : 0,
+ child: IconButton(
+ key: ValueKey('tab-close:${widget.id}'),
+ tooltip: 'Close tab',
+ onPressed: widget.onClose,
+ padding: EdgeInsets.zero,
+ constraints: const BoxConstraints.tightFor(
+ width: 32,
+ height: 32,
+ ),
+ style:
+ IconButton.styleFrom(
+ foregroundColor: ink,
+ backgroundColor: Colors.transparent,
+ overlayColor: Colors.transparent,
+ side: BorderSide.none,
+ tapTargetSize:
+ MaterialTapTargetSize.shrinkWrap,
+ ).copyWith(
+ animationDuration: Duration.zero,
+ foregroundColor:
+ WidgetStateProperty.resolveWith(
+ (states) => foreground.withValues(
+ alpha:
+ states.any(
+ (state) =>
+ state ==
+ WidgetState
+ .hovered ||
+ state ==
+ WidgetState
+ .focused ||
+ state ==
+ WidgetState
+ .pressed,
+ )
+ ? 1
+ : quietCloseOpacity,
+ ),
+ ),
+ ),
+ icon: const Icon(
+ AppIcons.close,
+ size: AppIcons.closeSize,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+ if (widget.tooltip case final tooltip? when tooltip.isNotEmpty) {
+ tab = Tooltip(message: tooltip, excludeFromSemantics: true, child: tab);
+ }
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ excludeFromSemantics: true,
+ onTap: widget.onSelect,
+ child: MouseRegion(
+ cursor: enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,
+ onEnter: (_) => setState(() => _hovered = true),
+ onExit: (_) => setState(() => _hovered = false),
+ child: tab,
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/dsh_install_panel.dart b/desktop/lib/widgets/dsh_install_panel.dart
index 79b59d37d..06dbca1d8 100644
--- a/desktop/lib/widgets/dsh_install_panel.dart
+++ b/desktop/lib/widgets/dsh_install_panel.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -422,7 +423,7 @@ class _StepRow extends StatelessWidget {
// Black reads on the bright dark-mode green; the deep light-mode
// green needs white.
child: Icon(
- Icons.check,
+ AppIcons.check,
size: 12,
color: grid.AppTheme.pick(Colors.white, Colors.black),
),
@@ -433,7 +434,7 @@ class _StepRow extends StatelessWidget {
shape: BoxShape.circle,
),
child: const Icon(
- Icons.priority_high,
+ AppIcons.circleAlert,
size: 12,
color: Colors.white,
),
diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dart
index 2396fdbaf..a6f885ab8 100644
--- a/desktop/lib/widgets/engine_identity.dart
+++ b/desktop/lib/widgets/engine_identity.dart
@@ -1,7 +1,7 @@
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/terminal/terminal_text.dart';
import '../core/harness_catalog.dart';
@@ -967,7 +967,7 @@ class EngineMark extends StatelessWidget {
)
: identity.id == kTerminalEngine
? Icon(
- LucideIcons.terminal,
+ AppIcons.terminal,
key: const ValueKey('engine-icon-terminal'),
size: size,
// The shell's pale steel is 1.8:1 on a light workspace; there it
diff --git a/desktop/lib/widgets/environment_preflight_screen.dart b/desktop/lib/widgets/environment_preflight_screen.dart
index fe64a808b..84bfbbb91 100644
--- a/desktop/lib/widgets/environment_preflight_screen.dart
+++ b/desktop/lib/widgets/environment_preflight_screen.dart
@@ -1,21 +1,14 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../bootstrap/environment_provisioner.dart';
import '../shared/theme/app_theme.dart' as grid;
-import 'box_chrome.dart';
-import 'terminal_progress.dart';
+import 'desktop_chrome.dart';
/// The read-only gate shown before either sign-in or environment setup.
///
-/// Printed as a session, not as a screen: a prompt line, one line per thing
-/// checked with its answer in the same column, a bar counting what is done, and
-/// a cursor waiting at the end. Everything is the terminal's face at the
-/// terminal's size — one cell size, the way a terminal has one (owner,
-/// 2026-09-23). A person who has lived in a terminal has read this exact shape
-/// ten thousand times, which is the welcome.
-///
-/// The figure is honest because it is counted: each dependency the provisioner
-/// probed is a line, and the bar is how many of them have answered.
+/// Every row reflects a dependency the provisioner actually probes. Progress
+/// counts checks that have answered, including those that need attention.
///
/// This is deliberately not part of the environment setup wizard: a computer
/// that is already ready should never look as though it has entered an
@@ -27,12 +20,11 @@ class EnvironmentPreflightScreen extends StatelessWidget {
final EnvironmentReadiness readiness;
- /// What each dependency is called in the print-out. The enum names the thing
- /// the app runs; these name it the way the person would say it.
+ /// Readable names for the dependencies the app actually checks.
static const _labels = {
- EnvironmentStep.tmux: 'tmux',
- EnvironmentStep.harness: 'harness cli',
- EnvironmentStep.clipboard: 'clipboard helper',
+ EnvironmentStep.tmux: 'Terminal tools',
+ EnvironmentStep.harness: 'Harness CLI',
+ EnvironmentStep.clipboard: 'Clipboard helper',
};
@override
@@ -44,68 +36,131 @@ class EnvironmentPreflightScreen extends StatelessWidget {
.toList();
final settled = steps.where((entry) => _settled(entry.value)).length;
final value = steps.isEmpty ? (ready ? 1.0 : null) : settled / steps.length;
+ final progress = steps.isEmpty
+ ? 'Waiting for checks…'
+ : '$settled of ${steps.length} checks finished';
+ final status = ready
+ ? 'All checks passed. Opening your workspace…'
+ : "This check doesn't install anything.";
+ final iconSize = MediaQuery.textScalerOf(context).scale(18);
+ final progressTrack = MediaQuery.highContrastOf(context)
+ ? DesktopChrome.muted
+ : DesktopChrome.rim;
- return Scaffold(
- backgroundColor: grid.AppPalette.swarmField,
- body: Center(
- child: SingleChildScrollView(
- padding: const EdgeInsets.all(24),
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 470),
- child: TerminalBox(
- child: Padding(
- padding: const EdgeInsets.fromLTRB(16, 14, 16, 14),
- child: Semantics(
- key: const Key('environment-status'),
- container: true,
- liveRegion: true,
- label: 'Harness setup status',
- value: ready ? 'Environment ready' : 'Checking this computer',
- child: ExcludeSemantics(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- '$kBootPrompt harness doctor',
- style: boxMonoStyle(weight: FontWeight.w600),
- ),
- const SizedBox(height: 8),
- for (final entry in steps) ...[
- TerminalCheckLine(
- label: _labels[entry.key]!,
- status: _status(entry.value),
- ink: _ink(entry.value),
- ),
- const SizedBox(height: 1),
- ],
- const SizedBox(height: 9),
- TerminalProgressLine(
- value: ready ? 1 : value,
- color: ready ? grid.AppPalette.online : null,
- ),
- const SizedBox(height: 8),
- Row(
+ return DesktopChrome(
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Center(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 470),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Semantics(
+ header: true,
+ child: Text(
+ ready
+ ? 'Your computer is ready'
+ : 'Checking this computer',
+ style: grid.AppType.title(
+ color: DesktopChrome.foreground,
+ height: 1.3,
+ ),
+ ),
+ ),
+ const SizedBox(height: DesktopChrome.panelPadding),
+ for (final entry in steps)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: MergeSemantics(
+ child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
+ ExcludeSemantics(
+ child: Icon(
+ _icon(entry.value),
+ size: iconSize,
+ color: _ink(entry.value),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ _labels[entry.key]!,
+ style: DesktopChrome.control(),
+ ),
+ ),
+ const SizedBox(width: 12),
Flexible(
+ fit: FlexFit.tight,
child: Text(
- ready
- ? 'all checks passed · opening your workspace'
- : 'read-only: nothing is installed by this check',
- style: boxMonoStyle(
- color: ready ? null : kBoxFaint,
- ),
+ _status(entry.value),
+ textAlign: TextAlign.end,
+ style: DesktopChrome.metadata(),
),
),
- const SizedBox(width: 6),
- const TerminalCursor(),
],
),
- ],
+ ),
+ ),
+ const SizedBox(height: DesktopChrome.panelPadding),
+ Semantics(
+ key: const Key('environment-status'),
+ container: true,
+ liveRegion: true,
+ label: 'Harness setup status',
+ value: ready
+ ? 'Environment ready'
+ : 'Checking this computer. $progress',
+ child: ExcludeSemantics(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (value != null)
+ LinearProgressIndicator(
+ value: ready ? 1 : value,
+ minHeight: 4,
+ borderRadius: BorderRadius.circular(2),
+ color: ready
+ ? grid.AppPalette.online
+ : DesktopChrome.accent,
+ backgroundColor: progressTrack,
+ stopIndicatorRadius: 0,
+ )
+ else if (MediaQuery.disableAnimationsOf(context))
+ Icon(
+ AppIcons.hourglass,
+ size: 20,
+ color: DesktopChrome.muted,
+ )
+ else
+ LinearProgressIndicator(
+ minHeight: 4,
+ borderRadius: BorderRadius.circular(2),
+ color: DesktopChrome.accent,
+ backgroundColor: progressTrack,
+ ),
+ const SizedBox(height: DesktopChrome.controlGap),
+ Text(progress, style: DesktopChrome.metadata()),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ status,
+ style: DesktopChrome.text(
+ color: ready
+ ? DesktopChrome.foreground
+ : DesktopChrome.muted,
+ size: 13,
+ ),
+ ),
+ ],
+ ),
),
),
- ),
+ ],
),
),
),
@@ -120,22 +175,31 @@ class EnvironmentPreflightScreen extends StatelessWidget {
_ => true,
};
- /// The word in the right-hand column, in a terminal's vocabulary.
static String _status(EnvironmentStepStatus status) => switch (status) {
- EnvironmentStepStatus.ready => 'ok',
- EnvironmentStepStatus.notApplicable => 'n/a',
- EnvironmentStepStatus.failed => 'fail',
- EnvironmentStepStatus.unavailable => 'missing',
- EnvironmentStepStatus.needsTerminal => 'needs a terminal',
- EnvironmentStepStatus.running => '..',
- EnvironmentStepStatus.pending => '--',
+ EnvironmentStepStatus.ready => 'Ready',
+ EnvironmentStepStatus.notApplicable => 'Not needed',
+ EnvironmentStepStatus.failed => 'Check failed',
+ EnvironmentStepStatus.unavailable => 'Unavailable',
+ EnvironmentStepStatus.needsTerminal => 'Needs Terminal',
+ EnvironmentStepStatus.running => 'Checking…',
+ EnvironmentStepStatus.pending => 'Waiting',
+ };
+
+ static IconData _icon(EnvironmentStepStatus status) => switch (status) {
+ EnvironmentStepStatus.ready => AppIcons.circleCheck,
+ EnvironmentStepStatus.notApplicable => AppIcons.circleMinus,
+ EnvironmentStepStatus.failed ||
+ EnvironmentStepStatus.unavailable => AppIcons.circleAlert,
+ EnvironmentStepStatus.needsTerminal => AppIcons.externalLink,
+ EnvironmentStepStatus.running => AppIcons.ellipsis,
+ EnvironmentStepStatus.pending => AppIcons.clock,
};
- static Color? _ink(EnvironmentStepStatus status) => switch (status) {
+ static Color _ink(EnvironmentStepStatus status) => switch (status) {
EnvironmentStepStatus.ready => grid.AppPalette.online,
EnvironmentStepStatus.failed ||
EnvironmentStepStatus.unavailable => grid.AppPalette.dangerFill,
EnvironmentStepStatus.needsTerminal => grid.AppPalette.warn,
- _ => null,
+ _ => DesktopChrome.muted,
};
}
diff --git a/desktop/lib/widgets/environment_setup_screen.dart b/desktop/lib/widgets/environment_setup_screen.dart
index b3cf43502..9015e1fae 100644
--- a/desktop/lib/widgets/environment_setup_screen.dart
+++ b/desktop/lib/widgets/environment_setup_screen.dart
@@ -1,9 +1,9 @@
import 'dart:async';
import 'dart:io';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:harness/terminal/terminal_text.dart';
import '../bootstrap/environment_provisioner.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -112,7 +112,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
padding: EdgeInsets.all(compact ? 16 : 24),
child: Center(
child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 760),
+ constraints: const BoxConstraints(maxWidth: 640),
child: Material(
color: AppColors.sidebar,
clipBehavior: Clip.antiAlias,
@@ -159,20 +159,16 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
- eyebrow.toUpperCase(),
- style: grid.AppType.monoMeta(
+ eyebrow,
+ style: grid.AppType.caption(
color: AppColors.accent,
fontWeight: FontWeight.w600,
- letterSpacing: 1.2,
),
),
const SizedBox(height: 6),
- // Terminal type here too: setup is the first thing a new install shows,
- // and it should read like the app it is about to open (owner,
- // 2026-09-23). Weight and colour carry the hierarchy instead of size.
Text(
title,
- style: terminalTextStyle(
+ style: grid.AppType.title(
fontWeight: FontWeight.w600,
color: AppColors.text,
),
@@ -180,7 +176,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
const SizedBox(height: 6),
Text(
lead,
- style: terminalTextStyle(color: AppColors.textSoft, height: 1.55),
+ style: grid.AppType.body(color: AppColors.textSoft, height: 1.55),
),
const SizedBox(height: 16),
],
@@ -242,7 +238,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
if (mode == EnvironmentSetupMode.automatic) ...[
if (needsTerminal) ...[
_notice(
- Icons.terminal,
+ AppIcons.terminal,
'Admin prompts stay in Terminal',
'Complete any installation prompts there, then return to Harness.',
),
@@ -269,7 +265,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
),
if (state.phase == EnvironmentSetupPhase.waitingForTerminal)
_notice(
- Icons.lock_outline,
+ AppIcons.lock,
'Harness cannot see your password',
'Finish the prompts in Terminal, then return here. Harness checks progress automatically.',
),
@@ -379,7 +375,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
Widget _planList(List<EnvironmentPlanItem> items) {
if (items.isEmpty) {
return _notice(
- Icons.check_circle_outline,
+ AppIcons.circleCheck,
'Nothing left to install',
'Every dependency is ready. Continue to final verification.',
);
@@ -413,7 +409,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.end,
- style: grid.AppType.body(color: AppColors.muted),
+ style: grid.AppType.body(color: AppColors.textSoft),
),
),
),
@@ -426,7 +422,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
children: [
if (items.isEmpty)
_notice(
- Icons.check_circle_outline,
+ AppIcons.circleCheck,
'Nothing left to install',
'Every dependency is ready. Continue to final verification.',
),
@@ -440,7 +436,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
children: [
Text(
'${index + 1} · ${items[index].title}',
- style: terminalTextStyle(
+ style: grid.AppType.heading(
fontWeight: FontWeight.w600,
color: AppColors.text,
),
@@ -480,7 +476,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
Expanded(
child: Text(
'Setup details',
- style: terminalTextStyle(
+ style: grid.AppType.label(
fontWeight: FontWeight.w600,
color: AppColors.text,
),
@@ -488,7 +484,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
),
TextButton.icon(
onPressed: () => _copy(diagnostics),
- icon: const Icon(Icons.copy, size: 14),
+ icon: const Icon(AppIcons.copy, size: 14),
label: Text(
_copied == diagnostics ? 'Copied' : 'Copy diagnostics',
),
@@ -570,7 +566,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
: missingCount == 0
? 'Verify and continue'
: 'Install $missingCount ${missingCount == 1 ? 'tool' : 'tools'}';
- icon = manual ? Icons.refresh : Icons.download_outlined;
+ icon = manual ? AppIcons.refreshCw : AppIcons.download;
action = manual
? widget.notifier.retryEnvironmentSetup
: widget.notifier.startEnvironmentSetup;
@@ -584,7 +580,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
action = widget.notifier.continueAfterEnvironmentSetup;
case EnvironmentSetupPhase.waitingForTerminal:
label = 'Recheck now';
- icon = Icons.refresh;
+ icon = AppIcons.refreshCw;
action = () => widget.notifier.recheckEnvironmentStep(
state.steps[EnvironmentStep.clipboard] ==
EnvironmentStepStatus.needsTerminal
@@ -634,7 +630,9 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
child: Text(
_copyError ?? 'Next: sign in and start a harness.',
style: grid.AppType.body(
- color: _copyError == null ? AppColors.textSoft : AppColors.danger,
+ color: _copyError == null
+ ? AppColors.textSoft
+ : Theme.of(context).colorScheme.error,
),
),
);
@@ -694,7 +692,7 @@ class _CheckSectionLabel extends StatelessWidget {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
return Container(
width: double.infinity,
padding: const EdgeInsets.fromLTRB(16, 11, 16, 8),
@@ -703,11 +701,10 @@ class _CheckSectionLabel extends StatelessWidget {
border: Border(bottom: BorderSide(color: AppColors.border)),
),
child: Text(
- label.toUpperCase(),
- style: grid.AppType.monoMeta(
+ label,
+ style: grid.AppType.label(
color: AppColors.textSoft,
fontWeight: FontWeight.w600,
- letterSpacing: 1.1,
),
),
);
@@ -731,11 +728,11 @@ class _CheckRow extends StatelessWidget {
grid.AppTheme.watch(context);
final color = switch (status) {
EnvironmentStepStatus.ready => AppColors.success,
- EnvironmentStepStatus.failed => AppColors.danger,
+ EnvironmentStepStatus.failed => Theme.of(context).colorScheme.error,
EnvironmentStepStatus.needsTerminal => AppColors.warning,
EnvironmentStepStatus.running => AppColors.accent,
- EnvironmentStepStatus.notApplicable => AppColors.muted,
- _ => AppColors.muted,
+ EnvironmentStepStatus.notApplicable => AppColors.textSoft,
+ _ => AppColors.textSoft,
};
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
@@ -753,12 +750,12 @@ class _CheckRow extends StatelessWidget {
else
Icon(
status == EnvironmentStepStatus.ready
- ? Icons.check_circle
+ ? AppIcons.circleCheck
: status == EnvironmentStepStatus.failed
- ? Icons.cancel_outlined
+ ? AppIcons.circleX
: status == EnvironmentStepStatus.notApplicable
- ? Icons.remove_circle_outline
- : Icons.circle_outlined,
+ ? AppIcons.circleMinus
+ : AppIcons.circle,
size: 17,
color: color,
),
@@ -769,7 +766,10 @@ class _CheckRow extends StatelessWidget {
children: [
Text(label, style: grid.AppType.label()),
const SizedBox(height: 3),
- Text(detail, style: grid.AppType.body(color: AppColors.muted)),
+ Text(
+ detail,
+ style: grid.AppType.body(color: AppColors.textSoft),
+ ),
],
),
),
diff --git a/desktop/lib/widgets/export_logs_dialog.dart b/desktop/lib/widgets/export_logs_dialog.dart
index 916d9f3c1..5bcdcd540 100644
--- a/desktop/lib/widgets/export_logs_dialog.dart
+++ b/desktop/lib/widgets/export_logs_dialog.dart
@@ -1,14 +1,15 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../core/harness_cli_runner.dart';
import '../core/reveal_folder.dart';
import '../logging/log_export.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
-import '../shared/widgets/toolbar_pill.dart';
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
/// Help ▸ Export Logs… — the one thing a bug report needs, from a menu every
/// build has.
@@ -83,95 +84,58 @@ class _ExportLogsDialogState extends State<_ExportLogsDialog> {
: 'Saved to ${result.path}\n'
'Send this file with your report. It holds no credentials.';
- return Dialog(
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 372),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(18, 18, 18, 14),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Container(
- width: 34,
- height: 34,
- decoration: BoxDecoration(
- color: mark.withValues(alpha: 0.13),
- borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),
- ),
- alignment: Alignment.center,
- child: busy
- ? SizedBox(
- width: 17,
- height: 17,
- child: CircularProgressIndicator(
- strokeWidth: 2,
- color: mark,
- ),
- )
- : Icon(
- failed
- ? LucideIcons.circleAlert300
- : LucideIcons.packageCheck300,
- size: 18,
- color: mark,
- ),
- ),
- const SizedBox(height: 12),
- Text(
- title,
- style: grid.AppType.heading(color: grid.AppPalette.textPrimary),
+ return DesktopPromptSurface(
+ body: DesktopPromptScrollBody(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Container(
+ width: 34,
+ height: 34,
+ decoration: BoxDecoration(
+ color: mark.withValues(alpha: 0.13),
+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),
),
- const SizedBox(height: 5),
- SelectableText(
- body,
- style: grid.AppType.body(
- color: grid.AppPalette.textSecondary,
- height: 1.5,
- ),
- ),
- if (!busy) ...[
- const SizedBox(height: 15),
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- if (result.path != null) ...[
- ToolbarPill(
- onTap: () => unawaited(revealFile(result.path!)),
- rimmed: true,
- child: _Label('Show in Finder'),
+ alignment: Alignment.center,
+ child: busy
+ ? SizedBox(
+ width: 17,
+ height: 17,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: mark,
),
- const SizedBox(width: 8),
- ],
- ToolbarPill(
- onTap: () => Navigator.of(context).pop(),
- tinted: true,
- child: _Label('Close', tinted: true),
+ )
+ : Icon(
+ failed ? AppIcons.circleAlert : AppIcons.packageCheck,
+ size: 18,
+ color: mark,
),
- ],
- ),
- ],
- ],
- ),
+ ),
+ const SizedBox(height: 12),
+ Text(title, style: DesktopChrome.heading()),
+ const SizedBox(height: 8),
+ SelectableText(
+ body,
+ style: DesktopChrome.text(color: DesktopChrome.muted),
+ ),
+ ],
),
),
- );
- }
-}
-
-class _Label extends StatelessWidget {
- const _Label(this.text, {this.tinted = false});
-
- final String text;
- final bool tinted;
-
- @override
- Widget build(BuildContext context) {
- return Text(
- text,
- style: grid.AppType.label(
- color: ToolbarPill.tint(tinted: tinted, enabled: true),
- ),
+ actions: [
+ if (!busy && result.path != null)
+ TextButton(
+ onPressed: () => unawaited(revealFile(result.path!)),
+ child: const Text('Show in Finder'),
+ ),
+ if (!busy)
+ FilledButton(
+ autofocus: true,
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('Close'),
+ ),
+ ],
);
}
}
diff --git a/desktop/lib/widgets/flash_firmware_dialog.dart b/desktop/lib/widgets/flash_firmware_dialog.dart
index f44d8bba2..be63b86b0 100644
--- a/desktop/lib/widgets/flash_firmware_dialog.dart
+++ b/desktop/lib/widgets/flash_firmware_dialog.dart
@@ -1,8 +1,8 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../flash/flasher.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -191,13 +191,13 @@ class _FlashDialogState extends State<_FlashDialog> {
'Checking the USB ports on this Mac.',
),
_Phase.ready => (
- LucideIcons.zap300,
+ AppIcons.zap,
grid.AppPalette.accentOnSurface,
'Flash firmware to the dial',
'Writes the latest circle release over USB.',
),
_Phase.noBoard => (
- LucideIcons.usb300,
+ AppIcons.usb,
grid.AppPalette.warn,
'No dial found',
_problem ??
@@ -213,7 +213,7 @@ class _FlashDialogState extends State<_FlashDialog> {
'Don’t unplug the dial.',
),
_Phase.done => (
- LucideIcons.circleCheck300,
+ AppIcons.circleCheck,
grid.AppPalette.online,
_version == null
? 'The dial is flashed'
@@ -221,7 +221,7 @@ class _FlashDialogState extends State<_FlashDialog> {
'Harness is running again. Your machines are back.',
),
_Phase.failed => (
- LucideIcons.triangleAlert300,
+ AppIcons.triangleAlert,
grid.AppPalette.dangerFill,
'Flash failed',
_problem ?? 'Nothing else was changed. Harness has been started again.',
@@ -380,11 +380,7 @@ class _FlashDialogState extends State<_FlashDialog> {
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Icon(
- LucideIcons.triangleAlert300,
- size: 14,
- color: grid.AppPalette.warn,
- ),
+ Icon(AppIcons.triangleAlert, size: 14, color: grid.AppPalette.warn),
const SizedBox(width: 9),
Expanded(
child: RichText(
@@ -450,7 +446,7 @@ class _FlashDialogState extends State<_FlashDialog> {
child: Row(
children: [
Icon(
- LucideIcons.squareTerminal300,
+ AppIcons.squareTerminal,
size: 13,
color: grid.AppPalette.textFaint,
),
@@ -640,11 +636,7 @@ class _StepRow extends StatelessWidget {
grid.AppTheme.watch(context);
final (Widget mark, Color ink) = switch (state) {
_StepState.done => (
- Icon(
- LucideIcons.circleCheck300,
- size: 14,
- color: grid.AppPalette.online,
- ),
+ Icon(AppIcons.circleCheck, size: 14, color: grid.AppPalette.online),
grid.AppPalette.textSecondary,
),
_StepState.running => (
@@ -660,7 +652,7 @@ class _StepRow extends StatelessWidget {
),
_StepState.failed => (
Icon(
- LucideIcons.triangleAlert300,
+ AppIcons.triangleAlert,
size: 14,
color: grid.AppPalette.dangerFill,
),
diff --git a/desktop/lib/widgets/fork_agent_dialog.dart b/desktop/lib/widgets/fork_agent_dialog.dart
index 2cad6fbb4..4fa107346 100644
--- a/desktop/lib/widgets/fork_agent_dialog.dart
+++ b/desktop/lib/widgets/fork_agent_dialog.dart
@@ -6,8 +6,10 @@ import 'package:flutter/services.dart';
import '../core/agent_names.dart';
import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
-import '../terminal/terminal_text.dart';
-import 'box_chrome.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
+import 'box_chrome.dart' show BoxAnnouncer, ReadlineKeys;
import 'terminal_prompt.dart';
export '../core/agent_names.dart' show forkNameFor;
@@ -261,188 +263,207 @@ class _ForkAgentPromptState extends State<_ForkAgentPrompt> {
TextEditingController controller,
FocusNode focus, {
bool task = false,
- }) => Semantics(
- label: task ? 'Fork first task, optional' : 'Fork name',
- child: ReadlineKeys(
- controller: controller,
- enabled: !_locked,
- onChanged: _changed,
- child: TextField(
- key: ValueKey(task ? 'fork-task' : 'fork-name'),
- controller: controller,
- focusNode: focus,
- readOnly: _locked,
- style: boxMonoStyle(),
- textAlignVertical: TextAlignVertical.center,
- minLines: 1,
- maxLines: task ? 6 : 1,
- textInputAction: task ? TextInputAction.done : TextInputAction.next,
- decoration: InputDecoration(
- hintText: task ? 'first task (optional)' : 'name',
- hintStyle: boxMonoStyle(color: kBoxFaint),
- isDense: true,
- filled: false,
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- contentPadding: EdgeInsets.zero,
- prefixIcon: Padding(
- padding: const EdgeInsets.only(right: 10),
- child: Center(
- widthFactor: 1,
- heightFactor: 1,
- child: Text(
- '$label >',
- style: boxMonoStyle(color: boxText(.70)),
+ }) {
+ final border = OutlineInputBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ );
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(label, style: DesktopChrome.control(medium: true)),
+ const SizedBox(height: DesktopChrome.controlGap),
+ Semantics(
+ label: task ? 'Fork first task, optional' : 'Fork name',
+ child: ReadlineKeys(
+ controller: controller,
+ enabled: !_locked,
+ onChanged: _changed,
+ child: TextField(
+ key: ValueKey(task ? 'fork-task' : 'fork-name'),
+ controller: controller,
+ focusNode: focus,
+ readOnly: _locked,
+ style: DesktopChrome.text(size: 14),
+ cursorColor: DesktopChrome.accent,
+ textAlignVertical: TextAlignVertical.center,
+ minLines: task ? 3 : 1,
+ maxLines: task ? 6 : 1,
+ textInputAction: task
+ ? TextInputAction.done
+ : TextInputAction.next,
+ decoration: InputDecoration(
+ hintText: task
+ ? 'What should the fork work on?'
+ : 'Harness name',
+ hintStyle: DesktopChrome.text(
+ size: 14,
+ color: DesktopChrome.muted,
+ ),
+ isDense: true,
+ filled: true,
+ fillColor: DesktopChrome.field,
+ border: border,
+ enabledBorder: border,
+ focusedBorder: border.copyWith(
+ borderSide: BorderSide(
+ color: DesktopChrome.focusRing,
+ width: grid.AppDesktop.focusWidth,
+ ),
+ ),
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 10,
+ ),
),
+ onChanged: _changed,
+ onEditingComplete: () {},
+ onSubmitted: (_) {
+ if (task) {
+ _submit();
+ } else {
+ _taskFocus.requestFocus();
+ }
+ },
),
),
- prefixIconConstraints: const BoxConstraints(minHeight: 38),
),
- onChanged: _changed,
- onEditingComplete: () {},
- onSubmitted: (_) {
- if (task) {
- _submit();
- } else {
- _taskFocus.requestFocus();
- }
- },
- ),
- ),
- );
+ ],
+ );
+ }
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
- return ListenableBuilder(
- listenable: terminalFontStore,
- builder: (context, _) => TerminalPromptKeys(
- composing: () => _composing,
- inputFocus: _nameFocus.hasFocus ? _nameFocus : _taskFocus,
- cancel: _close,
- accept: _accept,
- submit: _submit,
- next: () => _vertical(1),
- previous: () => _vertical(-1),
- pageDown: () => _page(1),
- pageUp: () => _page(-1),
- child: CallbackShortcuts(
- bindings: {
- const SingleActivator(LogicalKeyboardKey.enter, alt: true):
- _newline,
- if (KeymapTheme.of(context) == null)
- const SingleActivator(LogicalKeyboardKey.enter, meta: true):
- _submit,
- },
- child: TerminalPrompt(
- width: 760,
+ grid.AppTheme.watch(context);
+ final uncertain = _attempt.awaitingConfirmation;
+ final status = _busy
+ ? 'Waiting for fork…'
+ : uncertain
+ ? 'Fork may already exist.'
+ : null;
+ final actionLabel = uncertain ? 'Check status' : 'Fork';
+ final closeLabel = _locked ? 'Close' : 'Cancel';
+ final cwd = _attempt.source?.project?.cwd;
+ return TerminalPromptKeys(
+ composing: () => _composing,
+ inputFocus: _nameFocus.hasFocus ? _nameFocus : _taskFocus,
+ cancel: _close,
+ accept: _accept,
+ submit: _submit,
+ next: () => _vertical(1),
+ previous: () => _vertical(-1),
+ pageDown: () => _page(1),
+ pageUp: () => _page(-1),
+ child: CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.enter, alt: true): _newline,
+ if (KeymapTheme.of(context) == null)
+ const SingleActivator(LogicalKeyboardKey.enter, meta: true):
+ _submit,
+ },
+ child: DesktopPromptSurface(
+ width: 520,
+ body: DesktopPromptScrollBody(
+ controller: _body,
child: Column(
- mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Flexible(
- child: SingleChildScrollView(
- controller: _body,
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- 'Fork Harness',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- const SizedBox(height: 10),
- Text(
- 'from ${_attempt.source?.name ?? widget.sourceName}',
- style: boxMonoStyle(),
- ),
- if (widget.notifier
- .stateOf(widget.machineId)
- ?.machine
- .displayName
- case final machine?)
- Text(
- [
- machine,
- if (_attempt.source?.project?.cwd case final cwd?
- when cwd.isNotEmpty)
- cwd,
- ].join(' '),
- style: boxMonoStyle(color: kBoxFaint),
- ),
- const SizedBox(height: 6),
- Text(
- widget.engine == 'opencode'
- ? 'Starts from a handoff summary, in the same project folder.'
- : 'Continues the conversation in the same project folder.',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- const SizedBox(height: 8),
- _input('name', _name, _nameFocus),
- _input('task', _task, _taskFocus, task: true),
- if (_error case final error?) ...[
- const SizedBox(height: 8),
- Text(
- error,
- style: boxMonoStyle(color: boxErrorText),
- ),
- ],
- if (_busy)
- Text(
- 'Forking continues if you close this prompt.',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ],
- ),
+ Text('Fork Harness', style: DesktopChrome.heading()),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ 'From ${_attempt.source?.name ?? widget.sourceName}',
+ style: DesktopChrome.text(size: 14, medium: true),
+ ),
+ if (widget.notifier
+ .stateOf(widget.machineId)
+ ?.machine
+ .displayName
+ case final machine?) ...[
+ const SizedBox(height: 4),
+ Text(machine, style: DesktopChrome.metadata()),
+ ],
+ if (cwd != null && cwd.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(
+ cwd,
+ style: grid.AppType.monoMeta(color: DesktopChrome.muted),
+ ),
+ ],
+ const SizedBox(height: 8),
+ Text(
+ widget.engine == 'opencode'
+ ? 'Starts from a handoff summary, in the same project folder.'
+ : 'Continues the conversation in the same project folder.',
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
),
),
- if (_attempt.awaitingConfirmation && !_busy)
- Padding(
- padding: const EdgeInsets.fromLTRB(14, 0, 14, 8),
- child: Align(
- alignment: Alignment.centerLeft,
- child: terminalPromptButton(
- 'Start another fork',
- _startAnother,
- key: const Key('fork-start-another'),
- ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ _input('Name', _name, _nameFocus),
+ const SizedBox(height: DesktopChrome.groupGap),
+ _input('First task (optional)', _task, _taskFocus, task: true),
+ if (_error case final error?) ...[
+ const SizedBox(height: 12),
+ Semantics(
+ liveRegion: true,
+ child: DesktopPromptMessage(
+ error,
+ color: uncertain
+ ? grid.AppPalette.warn
+ : Theme.of(context).colorScheme.error,
),
),
- BoxHintStrip(
- message: _busy
- ? 'Waiting for fork…'
- : (_attempt.awaitingConfirmation
- ? 'Fork may already exist.'
- : null),
- isError: !_busy && _attempt.awaitingConfirmation,
- hints: [
- if (!_busy)
- BoxHint(
- terminalPromptHint(context, 'picker.accept', 'enter'),
- _attempt.awaitingConfirmation
- ? 'check status'
- : (_nameFocus.hasFocus ? 'edit task' : 'fork'),
- onTap: _nameFocus.hasFocus
- ? _taskFocus.requestFocus
- : _submit,
- ),
- if (!_locked)
- BoxHint(
- terminalPromptHint(context, 'picker.complete', 'tab'),
- 'fields',
- ),
- if (!_locked) const BoxHint('alt-enter', 'newline'),
- BoxHint(
- terminalPromptHint(context, 'picker.cancel', 'esc'),
- 'close',
- onTap: _close,
+ ],
+ if (uncertain && !_busy) ...[
+ const SizedBox(height: 12),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: OutlinedButton(
+ key: const Key('fork-start-another'),
+ onPressed: _startAnother,
+ child: const Text('Start another fork'),
),
- ],
- ),
+ ),
+ ],
+ if (_busy) ...[
+ const SizedBox(height: 12),
+ Text(
+ 'Forking continues if you close this dialog.',
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
],
),
),
+ footer: status == null
+ ? null
+ : Semantics(
+ liveRegion: true,
+ child: DesktopPromptMessage(
+ status,
+ color: _busy ? DesktopChrome.muted : grid.AppPalette.warn,
+ ),
+ ),
+ actions: [
+ Tooltip(
+ message:
+ '$closeLabel · ${terminalPromptHint(context, 'picker.cancel', 'esc')}',
+ child: TextButton(onPressed: _close, child: Text(closeLabel)),
+ ),
+ Tooltip(
+ message:
+ '$actionLabel · ${terminalPromptHint(context, 'picker.add_here', 'cmd-enter')}',
+ child: FilledButton(
+ key: const Key('fork-confirm'),
+ onPressed: _busy ? null : _submit,
+ child: Text(actionLabel),
+ ),
+ ),
+ ],
),
),
);
diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dart
index 03acc75b4..cb67fa5c7 100644
--- a/desktop/lib/widgets/grid_model_picker.dart
+++ b/desktop/lib/widgets/grid_model_picker.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../shared/theme/workspace_bar_style.dart';
@@ -660,7 +661,7 @@ class _GridModelPickerState extends State<GridModelPicker> {
)
else if (!widget.paneHeader)
Icon(
- Icons.arrow_drop_down,
+ AppIcons.chevronDown,
size: 14,
color: AppColors.mutedStrong,
),
@@ -750,6 +751,7 @@ class _ModelPickerPanelState extends State<_ModelPickerPanel>
@override
Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
final canRunLocally = widget.answer.canRunLocally(widget.engineLabel);
final sections = widget.sections;
final total = sections.fold<int>(0, (n, s) => n + _matching(s).length);
diff --git a/desktop/lib/widgets/harness_command_bar.dart b/desktop/lib/widgets/harness_command_bar.dart
index 3e5ff1849..999990f3d 100644
--- a/desktop/lib/widgets/harness_command_bar.dart
+++ b/desktop/lib/widgets/harness_command_bar.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -171,7 +172,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
PopupMenuButton<String>(
tooltip: 'Create or explore',
icon: const Icon(
- Icons.add,
+ AppIcons.plus,
color: grid.AppPalette.commandInk,
size: 24,
),
@@ -230,7 +231,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
onPressed: controller.dismiss,
tooltip: 'Cancel command',
icon: const Icon(
- Icons.close,
+ AppIcons.close,
color: grid.AppPalette.commandMuted,
size: 19,
),
@@ -265,8 +266,8 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
children: [
Icon(
_findOnly
- ? Icons.search
- : Icons.auto_awesome_outlined,
+ ? AppIcons.search
+ : AppIcons.sparkles,
size: 17,
color: grid.AppPalette.commandInk,
),
@@ -295,7 +296,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
),
)
: const Icon(
- Icons.arrow_upward_rounded,
+ AppIcons.arrowUp,
size: 22,
color: grid.AppPalette.commandInk,
),
@@ -324,7 +325,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
mainAxisSize: MainAxisSize.min,
children: [
Icon(
- Icons.auto_awesome,
+ AppIcons.sparkles,
size: 12,
color: grid.AppPalette.textFaint,
),
@@ -347,10 +348,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
icon: Badge(
isLabelVisible: controller.watchMatches > 0,
label: Text('${controller.watchMatches}'),
- child: const Icon(
- Icons.notifications_active_outlined,
- size: 14,
- ),
+ child: const Icon(AppIcons.bellRing, size: 14),
),
label: Text(
'${controller.watches.length} ${controller.watches.length == 1 ? 'watch' : 'watches'}',
@@ -400,8 +398,8 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
Icon(
controller.phase == CommandPhase.done &&
controller.error == null
- ? Icons.check_circle_outline
- : Icons.auto_awesome_outlined,
+ ? AppIcons.circleCheck
+ : AppIcons.sparkles,
size: 15,
color: grid.AppPalette.swarmAccent,
),
@@ -431,7 +429,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
? null
: controller.dismiss,
tooltip: 'Dismiss results',
- icon: const Icon(Icons.close, size: 15),
+ icon: const Icon(AppIcons.close, size: 15),
),
],
),
@@ -461,7 +459,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
unawaited(controller.startWatch());
setState(() => _showWatches = true);
},
- icon: const Icon(Icons.notifications_none, size: 16),
+ icon: const Icon(AppIcons.bell, size: 16),
label: const Text('Watch for this'),
),
),
@@ -626,7 +624,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
Row(
children: [
Icon(
- Icons.notifications_none,
+ AppIcons.bell,
size: 17,
color: grid.AppPalette.swarmAccent,
),
@@ -642,7 +640,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
IconButton(
onPressed: () => controller.stopWatch(watch),
tooltip: 'Stop watch',
- icon: const Icon(Icons.close, size: 16),
+ icon: const Icon(AppIcons.close, size: 16),
),
],
),
@@ -663,7 +661,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
for (final match in watch.matches)
TextButton.icon(
onPressed: () => unawaited(controller.choose(match)),
- icon: const Icon(Icons.arrow_forward, size: 14),
+ icon: const Icon(AppIcons.arrowRight, size: 14),
label: Text(match.title, overflow: TextOverflow.ellipsis),
),
],
@@ -675,10 +673,10 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
}
IconData _icon(CommandKind kind) => switch (kind) {
- CommandKind.open => Icons.terminal_rounded,
- CommandKind.command => Icons.bolt_outlined,
- CommandKind.send => Icons.send_outlined,
- CommandKind.create => Icons.add_circle_outline,
- CommandKind.search => Icons.manage_search,
- CommandKind.watch => Icons.notifications_active_outlined,
+ CommandKind.open => AppIcons.terminal,
+ CommandKind.command => AppIcons.zap,
+ CommandKind.send => AppIcons.send,
+ CommandKind.create => AppIcons.circlePlus,
+ CommandKind.search => AppIcons.listFilter,
+ CommandKind.watch => AppIcons.bellRing,
};
diff --git a/desktop/lib/widgets/harness_customize_pane.dart b/desktop/lib/widgets/harness_customize_pane.dart
index 04785a356..c9c0c7056 100644
--- a/desktop/lib/widgets/harness_customize_pane.dart
+++ b/desktop/lib/widgets/harness_customize_pane.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -7,28 +8,36 @@ import '../settings/sections/terminal_section.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/appearance_prefs_store.dart';
import '../shared/widgets/app_dialog.dart';
+import 'desktop_chrome.dart';
import 'prompt_customize.dart';
/// Opens customization over the workspace so appearance changes remain visible
/// on the terminals. All global entry points use this same right-side panel.
-Future<void> showHarnessCustomizePane(BuildContext context) =>
- showAppDialog<void>(
- context: context,
- veilTint: Colors.transparent,
- veilBlur: 0,
- transitionDuration: Duration.zero,
- builder: (context) => Align(
- alignment: Alignment.centerRight,
- child: SizedBox(
- width: (440 * grid.appTextScaleOf(context)).clamp(
- 0,
- MediaQuery.sizeOf(context).width,
- ),
- height: double.infinity,
- child: HarnessCustomizePane(onClose: () => Navigator.pop(context)),
+Future<void> showHarnessCustomizePane(
+ BuildContext context, {
+ ValueChanged<bool>? onCurrentChanged,
+ double bottomInset = 0,
+}) => showAppDialog<void>(
+ context: context,
+ onCurrentChanged: onCurrentChanged,
+ veilTint: Colors.transparent,
+ veilBlur: 0,
+ transitionDuration: Duration.zero,
+ builder: (context) => Padding(
+ padding: EdgeInsets.only(bottom: bottomInset),
+ child: Align(
+ alignment: Alignment.centerRight,
+ child: SizedBox(
+ width: (440 * grid.appTextScaleOf(context)).clamp(
+ 0,
+ MediaQuery.sizeOf(context).width,
),
+ height: double.infinity,
+ child: HarnessCustomizePane(onClose: () => Navigator.pop(context)),
),
- );
+ ),
+ ),
+);
/// Customization tabs share the app's existing preference stores.
class HarnessCustomizePane extends StatelessWidget {
@@ -39,10 +48,18 @@ class HarnessCustomizePane extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
+ final tabHeight = (MediaQuery.textScalerOf(context).scale(13) * 1.25 + 20)
+ .clamp(44.0, double.infinity);
return Material(
key: const ValueKey('harness-customize-pane'),
color: grid.AppPalette.panelBg,
- shape: Border(left: BorderSide(color: grid.AppPalette.divider)),
+ shape: Border(
+ left: BorderSide(
+ color: MediaQuery.highContrastOf(context)
+ ? DesktopChrome.foreground.withValues(alpha: .45)
+ : DesktopChrome.rim,
+ ),
+ ),
child: FocusScope(
child: CallbackShortcuts(
bindings: {const SingleActivator(LogicalKeyboardKey.escape): onClose},
@@ -52,15 +69,13 @@ class HarnessCustomizePane extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
- padding: const EdgeInsets.fromLTRB(20, 12, 8, 8),
+ padding: const EdgeInsets.fromLTRB(24, 16, 16, 12),
child: Row(
children: [
Expanded(
child: Text(
'Customize Harness',
- style: grid.AppType.heading(
- color: grid.AppPalette.textPrimary,
- ),
+ style: DesktopChrome.heading(),
),
),
IconButton(
@@ -68,7 +83,21 @@ class HarnessCustomizePane extends StatelessWidget {
autofocus: true,
tooltip: 'Close customization',
onPressed: onClose,
- icon: const Icon(Icons.close, size: 20),
+ style:
+ IconButton.styleFrom(
+ minimumSize: const Size(32, 32),
+ padding: const EdgeInsets.all(6),
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? DesktopChrome.accent
+ : Colors.transparent,
+ ),
+ ),
+ ),
+ icon: const Icon(AppIcons.close, size: 20),
),
],
),
@@ -76,22 +105,44 @@ class HarnessCustomizePane extends StatelessWidget {
TabBar(
isScrollable: true,
tabAlignment: TabAlignment.start,
- labelColor: grid.AppPalette.swarmAccent,
- unselectedLabelColor: grid.AppPalette.textSecondary,
- indicatorColor: grid.AppPalette.swarmAccent,
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ labelPadding: const EdgeInsets.symmetric(horizontal: 4),
+ labelColor: DesktopChrome.foreground,
+ unselectedLabelColor: DesktopChrome.muted,
+ indicatorColor: DesktopChrome.accent,
dividerColor: grid.AppPalette.divider,
- labelStyle: grid.AppType.label(),
- tabs: const [
- Tab(key: ValueKey('customize-prompt'), text: 'Status'),
+ labelStyle: DesktopChrome.control(medium: true),
+ unselectedLabelStyle: DesktopChrome.control(),
+ overlayColor: WidgetStateProperty.resolveWith(
+ (states) => DesktopChrome.foreground.withValues(
+ alpha: states.contains(WidgetState.pressed)
+ ? .12
+ : states.contains(WidgetState.hovered)
+ ? .05
+ : 0,
+ ),
+ ),
+ tabs: [
+ Tab(
+ key: const ValueKey('customize-prompt'),
+ height: tabHeight,
+ child: const _CustomizeTabLabel('Status'),
+ ),
Tab(
- key: ValueKey('customize-appearance'),
- text: 'Appearance',
+ key: const ValueKey('customize-appearance'),
+ height: tabHeight,
+ child: const _CustomizeTabLabel('Appearance'),
),
Tab(
- key: ValueKey('customize-wallpaper'),
- text: 'Background',
+ key: const ValueKey('customize-wallpaper'),
+ height: tabHeight,
+ child: const _CustomizeTabLabel('Wallpaper'),
+ ),
+ Tab(
+ key: const ValueKey('customize-terminal'),
+ height: tabHeight,
+ child: const _CustomizeTabLabel('Terminal'),
),
- Tab(key: ValueKey('customize-terminal'), text: 'Terminal'),
],
),
Expanded(
@@ -115,3 +166,25 @@ class HarnessCustomizePane extends StatelessWidget {
);
}
}
+
+class _CustomizeTabLabel extends StatelessWidget {
+ const _CustomizeTabLabel(this.label);
+ final String label;
+
+ @override
+ Widget build(BuildContext context) => DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ border: Border.all(
+ width: 1.5,
+ color: Focus.of(context).hasFocus
+ ? DesktopChrome.accent
+ : Colors.transparent,
+ ),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
+ child: Text(label),
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/harness_join_guide_screen.dart b/desktop/lib/widgets/harness_join_guide_screen.dart
index 23dd746ee..0e90120f6 100644
--- a/desktop/lib/widgets/harness_join_guide_screen.dart
+++ b/desktop/lib/widgets/harness_join_guide_screen.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -58,7 +59,7 @@ class _HarnessJoinGuideScreenState extends State<HarnessJoinGuideScreen> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Icon(Icons.link_off, color: AppColors.warning, size: 28),
+ Icon(AppIcons.unlink, color: AppColors.warning, size: 28),
const SizedBox(height: 14),
Text(
'Harness is offline',
diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dart
index c60069ecc..3ff8afd45 100644
--- a/desktop/lib/widgets/harness_session_manager.dart
+++ b/desktop/lib/widgets/harness_session_manager.dart
@@ -1,9 +1,9 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart';
import '../shared/widgets/app_menu.dart';
@@ -12,6 +12,7 @@ import '../state/harness_sessions.dart';
import '../state/swarm_navigation.dart';
import '../core/models.dart';
import '../usage/ledger/usage_overview.dart' show formatTokens;
+import 'desktop_chrome.dart';
import 'engine_identity.dart';
import '../notify/alert_sounds.dart';
@@ -195,15 +196,17 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
final rowHeight =
math.max(
62.0,
- scale.scale(AppType.bodySize) * 1.4 +
- scale.scale(AppType.monoMetaSize) * 1.4 +
+ (scale.scale(AppType.bodySize) * 1.3).ceilToDouble() +
+ (scale.scale(AppType.captionSize) * 1.35).ceilToDouble() +
26,
) +
- (showingQuestions ? scale.scale(AppType.monoMetaSize) * 1.4 + 6 : 0);
+ (showingQuestions
+ ? (scale.scale(AppType.captionSize) * 1.35).ceilToDouble() + 6
+ : 0);
double heightFor(HarnessSession row) =>
rowHeight +
(row.agent.hasMonitorStats
- ? scale.scale(AppType.monoMetaSize) * 1.4 + 6
+ ? (scale.scale(AppType.captionSize) * 1.35).ceilToDouble() + 6
: 0);
return FocusScope(
child: CallbackShortcuts(
@@ -267,38 +270,28 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
}
return KeyEventResult.handled;
},
- child: Material(
+ child: DesktopDialogSurface(
key: const ValueKey('session-manager'),
- color: AppPalette.panelBg,
- borderRadius: BorderRadius.circular(14),
- clipBehavior: Clip.antiAlias,
+ radius: AppDesktop.menuRadius,
+ elevation: AppMenu.elevation,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(20, 10, 12, 8),
- child: Row(
- children: [
- Expanded(
- child: Text('Harnesses', style: AppType.heading()),
- ),
- IconButton(
- tooltip: 'Close Harnesses',
- onPressed: widget.onClose,
- icon: const Icon(LucideIcons.x, size: 16),
- ),
- ],
- ),
+ DesktopDialogHeader(
+ title: 'Harnesses',
+ onClose: widget.onClose,
),
if (widget.introduction != null) widget.introduction!,
Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppDesktop.panelPadding,
+ ),
child: TextField(
key: const ValueKey('session-search'),
controller: _search,
focusNode: _searchFocus,
autofocus: true,
- style: AppType.monoLabel(),
+ style: AppType.body(height: 1.25).copyWith(fontSize: 17),
onChanged: (_) => setState(() => _selected = null),
onSubmitted: (_) {
if (selected != null) unawaited(_open(selected));
@@ -306,18 +299,21 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
decoration: InputDecoration(
hintText:
'Search harnesses, machines, projects, branches',
- hintStyle: AppType.monoLabel(color: AppPalette.textFaint),
+ hintStyle: AppType.body(
+ color: AppPalette.textSecondary,
+ height: 1.25,
+ ).copyWith(fontSize: 17),
prefixIcon: Icon(
- LucideIcons.search,
- size: 15,
- color: AppPalette.textFaint,
+ AppIcons.search,
+ size: 20,
+ color: AppPalette.textSecondary,
),
prefixIconConstraints: const BoxConstraints(minWidth: 36),
suffixIcon: _search.text.isEmpty
? null
: IconButton(
tooltip: 'Clear search',
- icon: const Icon(LucideIcons.x, size: 14),
+ icon: const Icon(AppIcons.close, size: 16),
onPressed: () {
_search.clear();
setState(() => _selected = null);
@@ -326,26 +322,31 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
),
isDense: true,
filled: true,
- fillColor: AppPalette.windowBg,
+ fillColor: AppDesktop.field,
contentPadding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 12,
),
border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(8),
+ borderRadius: BorderRadius.circular(
+ AppDesktop.fieldRadius,
+ ),
borderSide: BorderSide.none,
),
focusedBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(8),
+ borderRadius: BorderRadius.circular(
+ AppDesktop.fieldRadius,
+ ),
borderSide: BorderSide(
- color: AppPalette.accent.withValues(alpha: .8),
+ color: AppDesktop.focus,
+ width: AppDesktop.focusWidth,
),
),
),
),
),
Padding(
- padding: const EdgeInsets.fromLTRB(16, 10, 12, 8),
+ padding: const EdgeInsets.fromLTRB(24, 12, 24, 16),
child: Row(
children: [
Expanded(
@@ -356,55 +357,35 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
for (final filter in SessionFilter.values)
Padding(
padding: const EdgeInsets.only(right: 4),
- child: Semantics(
- selected: _filter == filter,
- child: TextButton(
- key: ValueKey(
- 'session-filter:${filter.name}',
- ),
- onPressed: () => setState(() {
- _filter = filter;
- _selected = null;
- }),
- style: TextButton.styleFrom(
- backgroundColor: _filter == filter
- ? AppPalette.textPrimary.withValues(
- alpha: .08,
- )
- : Colors.transparent,
- foregroundColor: _filter == filter
- ? AppPalette.textPrimary
- : AppPalette.textSecondary,
- minimumSize: const Size(0, 30),
- padding: const EdgeInsets.symmetric(
- horizontal: 10,
- ),
- textStyle: AppType.monoMeta(),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(
- 6,
- ),
- ),
- ),
- child: Text(switch (filter) {
- SessionFilter.all =>
- 'All ${all.length}',
- SessionFilter.needsInput =>
- 'Needs input $needsInput',
- SessionFilter.running =>
- 'Running $running',
- SessionFilter.paused =>
- 'Paused $paused',
- }),
+ child: DesktopPill(
+ key: ValueKey(
+ 'session-filter:${filter.name}',
),
+ compact: true,
+ selected: _filter == filter,
+ onPressed: () => setState(() {
+ _filter = filter;
+ _selected = null;
+ }),
+ label: switch (filter) {
+ SessionFilter.all => 'All ${all.length}',
+ SessionFilter.needsInput =>
+ 'Needs input $needsInput',
+ SessionFilter.running =>
+ 'Running $running',
+ SessionFilter.paused => 'Paused $paused',
+ },
),
),
],
),
),
),
+ const SizedBox(width: AppDesktop.controlGap),
MenuAnchor(
controller: _sortMenu,
+ onOpen: () => setState(() {}),
+ onClose: () => setState(() {}),
menuChildren: [
for (final sort in SessionSort.values)
AppMenuItem(
@@ -419,39 +400,24 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
},
),
],
- builder: (context, controller, child) => Tooltip(
- message: 'Sort harnesses',
- child: TextButton.icon(
- onPressed: () => controller.isOpen
- ? controller.close()
- : controller.open(),
- style: TextButton.styleFrom(
- foregroundColor: AppPalette.textSecondary,
- minimumSize: const Size(0, 30),
- padding: const EdgeInsets.symmetric(
- horizontal: 8,
- ),
- textStyle: AppType.monoMeta(),
- ),
- icon: const Icon(
- LucideIcons.arrowDownWideNarrow,
- size: 13,
- ),
- label: Text(
- _sort == SessionSort.recent
- ? 'Recent'
- : _sort.label,
- ),
- ),
+ builder: (context, controller, child) => DesktopPill(
+ tooltip: 'Sort harnesses',
+ semanticLabel: 'Sort harnesses',
+ semanticHint: 'Current order: ${_sort.label}',
+ compact: true,
+ onPressed: () => controller.isOpen
+ ? controller.close()
+ : controller.open(),
+ icon: AppIcons.arrowDownWideNarrow,
+ label: _sort == SessionSort.recent
+ ? 'Recent'
+ : _sort.label,
),
),
],
),
),
- Divider(
- height: 1,
- color: AppPalette.textPrimary.withValues(alpha: .08),
- ),
+ Divider(height: 1, color: AppPalette.divider),
Flexible(
child: rows.isEmpty
? Padding(
@@ -463,7 +429,7 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
mainAxisSize: MainAxisSize.min,
children: [
Icon(
- LucideIcons.layers,
+ AppIcons.layers,
size: 25,
color: AppPalette.textFaint,
),
@@ -535,7 +501,16 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {
row.agent.id,
),
selected:
- _selected != null && selected?.id == row.id,
+ !_sortMenu.isOpen &&
+ _selected != null &&
+ selected?.id == row.id,
+ onSelect: () {
+ if (_selected == row.id) return;
+ setState(() {
+ _selected = row.id;
+ _selectedIndex = index;
+ });
+ },
busy: busy,
pendingLabel: _opening == row.id
? 'Opening…'
@@ -575,6 +550,7 @@ class _SessionRow extends StatelessWidget {
required this.busy,
required this.pendingLabel,
required this.onOpen,
+ required this.onSelect,
required this.onToggle,
required this.onAnswer,
this.error,
@@ -589,11 +565,37 @@ class _SessionRow extends StatelessWidget {
/// sits with the thing it is about rather than in a column of its own.
final AlertKind? unread;
- final VoidCallback onOpen, onToggle, onAnswer;
+ final VoidCallback onOpen, onSelect, onToggle, onAnswer;
final String? error;
@override
Widget build(BuildContext context) {
+ final primary = selected ? AppDesktop.onSelection : AppPalette.textPrimary;
+ final secondary = selected
+ ? AppDesktop.selectionDetail
+ : AppPalette.textSecondary;
+ final errorInk = Theme.of(context).colorScheme.error;
+ Color statusInk(Color color) => selected ? AppDesktop.onSelection : color;
+ ButtonStyle actionStyle(Color color) =>
+ IconButton.styleFrom(
+ foregroundColor: color,
+ disabledForegroundColor: secondary.withValues(alpha: .6),
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: MediaQuery.highContrastOf(context)
+ ? 2
+ : AppDesktop.focusWidth,
+ color:
+ states.contains(WidgetState.focused) &&
+ !states.contains(WidgetState.disabled)
+ ? selected
+ ? AppDesktop.onSelection
+ : AppDesktop.focus
+ : Colors.transparent,
+ ),
+ ),
+ );
// Login or permission review may be required before a native resume hook.
final canOpen =
row.canOpen &&
@@ -606,354 +608,378 @@ class _SessionRow extends StatelessWidget {
final status => status,
};
// The time the panel sorts by (Recently used), so the ages read in order.
- final activity = row.lastUsedAt == null
+ final lastUsedAt = row.lastUsedAt;
+ final age = lastUsedAt == null
+ ? null
+ : now.difference(lastUsedAt).inMinutes < 1
+ ? 'now'
+ : harnessActivityAge(lastUsedAt, now);
+ final activity = age == null
? 'Last use unknown'
- : 'Last used ${harnessActivityAge(row.lastUsedAt, now)} ago';
- Widget detail(IconData icon, String text, Color color, {String? tooltip}) =>
- Tooltip(
- message: tooltip ?? text,
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(icon, size: 11, color: color),
- const SizedBox(width: 5),
- Flexible(
- child: Text(
- text,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.monoMeta(color: color, height: 1.3),
- ),
- ),
- ],
+ : age == 'now'
+ ? 'Last used now'
+ : 'Last used $age ago';
+ Widget detail(IconData icon, String text, {String? tooltip}) => Tooltip(
+ message: tooltip ?? text,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(icon, size: 16, color: secondary),
+ const SizedBox(width: 5),
+ Flexible(
+ child: Text(
+ text,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.caption(color: secondary, height: 1.35),
+ ),
),
- );
- final details = [
- detail(
- LucideIcons.monitor,
- row.machine.machine.displayName,
- AppPalette.textSecondary,
+ ],
),
+ );
+ final details = [
+ detail(AppIcons.monitor, row.machine.machine.displayName),
if (row.project case final project?) ...[
- detail(
- LucideIcons.folder,
- project.label,
- const Color(0xff79bbaf),
- tooltip: project.cwd,
- ),
+ detail(AppIcons.folder, project.label, tooltip: project.cwd),
if (project.shownBranch case final branch?)
- detail(LucideIcons.gitBranch, branch, const Color(0xff8dbb79)),
+ detail(AppIcons.gitBranch, branch),
],
];
return Padding(
padding: const EdgeInsets.symmetric(vertical: 1),
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: selected
- ? AppPalette.textPrimary.withValues(alpha: .06)
- : Colors.transparent,
- borderRadius: BorderRadius.circular(8),
- ),
- child: Column(
- children: [
- SizedBox(
- height: height,
- child: Row(
- children: [
- Expanded(
- child: Semantics(
- key: ValueKey('session-open:${row.id}'),
- selected: selected,
- container: true,
- button: true,
- enabled: canOpen,
- label:
- '${row.agent.isStopped ? 'Resume and open' : 'Open'} ${row.agent.displayName}',
- value: [
- row.machine.machine.displayName,
- row.project?.label,
- row.project?.shownBranch,
- row.question?.prompt,
- activity,
- if (row.agent.tokensUsed case final count?)
- '$count tokens used',
- if (row.agent.outputStats case final stats?) ...[
- if (stats.hasEdits)
- '${stats.linesAdded} lines added, ${stats.linesRemoved} lines removed in recorded edits',
- if (stats.pullRequestsCreated case final count?)
- '$count pull requests created',
- ],
- busy ? pendingLabel : row.status,
- ].whereType<String>().join(', '),
- onTap: canOpen ? onOpen : null,
- excludeSemantics: true,
- child: InkWell(
+ child: Focus(
+ canRequestFocus: false,
+ skipTraversal: true,
+ onFocusChange: (focused) {
+ if (focused) onSelect();
+ },
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: selected ? AppDesktop.selection : Colors.transparent,
+ borderRadius: BorderRadius.circular(AppDesktop.rowRadius),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SizedBox(
+ height: height,
+ child: Row(
+ children: [
+ Expanded(
+ child: Semantics(
+ key: ValueKey('session-open:${row.id}'),
+ selected: selected,
+ container: true,
+ button: true,
+ enabled: canOpen,
+ label:
+ '${row.agent.isStopped ? 'Resume and open' : 'Open'} ${row.agent.displayName}',
+ value: [
+ row.machine.machine.displayName,
+ row.project?.label,
+ row.project?.shownBranch,
+ row.question?.prompt,
+ activity,
+ if (row.agent.tokensUsed case final count?)
+ '$count tokens used',
+ if (row.agent.outputStats case final stats?) ...[
+ if (stats.hasEdits)
+ '${stats.linesAdded} lines added, ${stats.linesRemoved} lines removed in recorded edits',
+ if (stats.pullRequestsCreated case final count?)
+ '$count pull requests created',
+ ],
+ busy ? pendingLabel : row.status,
+ ].whereType<String>().join(', '),
onTap: canOpen ? onOpen : null,
- borderRadius: BorderRadius.circular(8),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(12, 10, 6, 10),
- child: Row(
- children: [
- EngineMark(
- engine: row.agent.identityEngine,
- size: 22,
- ),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Flexible(
- child: Tooltip(
- message: row.agent.displayName,
- child: Text(
- row.agent.displayName,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.label(height: 1.3),
- ),
- ),
- ),
- if (row.lastUsedAt != null)
- Padding(
- padding: const EdgeInsets.only(
- left: 8,
- ),
+ excludeSemantics: true,
+ child: InkWell(
+ onTap: canOpen ? onOpen : null,
+ onHover: (hovered) {
+ if (hovered && canOpen) onSelect();
+ },
+ borderRadius: BorderRadius.circular(
+ AppDesktop.rowRadius,
+ ),
+ hoverColor: Colors.transparent,
+ focusColor: Colors.transparent,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(12, 10, 6, 10),
+ child: Row(
+ children: [
+ EngineMark(
+ engine: row.agent.identityEngine,
+ size: AppDesktop.identitySize,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Flexible(
child: Tooltip(
- message:
- 'Last used ${row.lastUsedAt!.toLocal()}',
+ message: row.agent.displayName,
child: Text(
- '· ${harnessActivityAge(row.lastUsedAt, now)}',
- key: ValueKey(
- 'session-age:${row.id}',
- ),
- style: AppType.monoMeta(
- color:
- AppPalette.textSecondary,
+ row.agent.displayName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.label(
+ color: primary,
+ height: 1.3,
),
),
),
),
- if (attention != null && !busy)
- Padding(
- padding: const EdgeInsets.only(
- left: 12,
+ if (row.lastUsedAt != null)
+ Padding(
+ padding: const EdgeInsets.only(
+ left: 8,
+ ),
+ child: Tooltip(
+ message:
+ 'Last used ${row.lastUsedAt!.toLocal()}',
+ child: Text(
+ '· $age',
+ key: ValueKey(
+ 'session-age:${row.id}',
+ ),
+ style: AppType.caption(
+ color: secondary,
+ ),
+ ),
+ ),
),
- child: Text(
- attention,
- style: AppType.monoMeta(
- color: AppPalette.textSecondary,
+ if (attention != null && !busy)
+ Padding(
+ padding: const EdgeInsets.only(
+ left: 12,
+ ),
+ child: Text(
+ attention,
+ style: AppType.caption(
+ color: secondary,
+ ),
),
),
- ),
- ],
- ),
- const SizedBox(height: 6),
- LayoutBuilder(
- builder: (context, constraints) {
- // Cap leading labels without reserving
- // columns: the branch gets all space
- // left over by short machine/project names.
- final leadingWidth = math.max(
- 0.0,
- (constraints.maxWidth -
- 12 * (details.length - 1)) /
- details.length,
- );
- return Row(
- children: [
- for (
- var i = 0;
- i < details.length;
- i++
- ) ...[
- if (i > 0)
- const SizedBox(width: 12),
- if (i == details.length - 1)
- Expanded(child: details[i])
- else
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: leadingWidth,
+ ],
+ ),
+ const SizedBox(height: 6),
+ LayoutBuilder(
+ builder: (context, constraints) {
+ // Cap leading labels without reserving
+ // columns: the branch gets all space
+ // left over by short machine/project names.
+ final leadingWidth = math.max(
+ 0.0,
+ (constraints.maxWidth -
+ 12 * (details.length - 1)) /
+ details.length,
+ );
+ return Row(
+ children: [
+ for (
+ var i = 0;
+ i < details.length;
+ i++
+ ) ...[
+ if (i > 0)
+ const SizedBox(width: 12),
+ if (i == details.length - 1)
+ Expanded(child: details[i])
+ else
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: leadingWidth,
+ ),
+ child: details[i],
),
- child: details[i],
- ),
+ ],
],
- ],
- );
- },
- ),
- if (row.agent.hasMonitorStats) ...[
- const SizedBox(height: 6),
- _MonitorStats(
- agent: row.agent,
- id: row.id,
+ );
+ },
),
- ],
- if (showQuestion)
- if (row.question
- case final question?) ...[
+ if (row.agent.hasMonitorStats) ...[
const SizedBox(height: 6),
- Tooltip(
- message: question.prompt,
- child: Text(
- question.prompt.replaceAll(
- RegExp(r'\s+'),
- ' ',
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.monoMeta(
- color: _UnreadMark.waitingTint,
- height: 1.3,
- ),
- ),
+ _MonitorStats(
+ agent: row.agent,
+ id: row.id,
+ selected: selected,
),
],
- ],
+ if (showQuestion)
+ if (row.question
+ case final question?) ...[
+ const SizedBox(height: 6),
+ Tooltip(
+ message: question.prompt,
+ child: Text(
+ question.prompt.replaceAll(
+ RegExp(r'\s+'),
+ ' ',
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.caption(
+ color: statusInk(
+ AppPalette.warn,
+ ),
+ height: 1.35,
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
),
- ),
- ],
+ ],
+ ),
),
),
),
),
- ),
- const SizedBox(width: 8),
- if (row.needsInput)
- IconButton(
- key: ValueKey('session-answer:${row.id}'),
- tooltip: 'Needs input: ${row.question!.prompt}',
- onPressed: canOpen ? onAnswer : null,
- color: const Color(0xffd9ad70),
- icon: Icon(
- LucideIcons.messageCircleQuestionMark,
- size: 17,
- semanticLabel:
- 'Needs input for ${row.agent.displayName}',
- ),
- )
- // The SAME SLOT, never both: a row is either waiting on a
- // person or it is not, and the amber question already says
- // the first case. This says the other one — work that is done
- // and has not been looked at — in the one place the eye is
- // already checking for a row's state.
- else if (unread == AlertKind.done || unread == AlertKind.failed)
- IconButton(
- key: ValueKey('session-unread-${unread!.name}:${row.id}'),
- tooltip: unread == AlertKind.failed ? 'Failed' : 'Finished',
- onPressed: canOpen ? onOpen : null,
- color: unread == AlertKind.failed
- ? AppPalette.dangerFill
- : _UnreadMark.doneTint,
- icon: Icon(
- unread == AlertKind.failed
- ? LucideIcons.circleX
- : LucideIcons.circleCheckBig,
- size: 17,
- semanticLabel:
- '${unread == AlertKind.failed ? 'Failed' : 'Finished'}, not yet seen: ${row.agent.displayName}',
+ const SizedBox(width: 8),
+ if (row.needsInput)
+ IconButton(
+ key: ValueKey('session-answer:${row.id}'),
+ tooltip: 'Needs input: ${row.question!.prompt}',
+ onPressed: canOpen ? onAnswer : null,
+ style: actionStyle(statusInk(AppPalette.warn)),
+ constraints: const BoxConstraints.tightFor(
+ width: 32,
+ height: 32,
+ ),
+ padding: const EdgeInsets.all(6),
+ icon: Icon(
+ AppIcons.messageCircleQuestionMark,
+ size: 20,
+ semanticLabel:
+ 'Needs input for ${row.agent.displayName}',
+ ),
+ )
+ // The SAME SLOT, never both: a row is either waiting on a
+ // person or it is not, and the amber question already says
+ // the first case. This says the other one — work that is done
+ // and has not been looked at — in the one place the eye is
+ // already checking for a row's state.
+ else if (unread == AlertKind.done ||
+ unread == AlertKind.failed)
+ IconButton(
+ key: ValueKey(
+ 'session-unread-${unread!.name}:${row.id}',
+ ),
+ tooltip: unread == AlertKind.failed
+ ? 'Failed'
+ : 'Finished',
+ onPressed: canOpen ? onOpen : null,
+ style: actionStyle(
+ statusInk(
+ unread == AlertKind.failed
+ ? errorInk
+ : AppPalette.online,
+ ),
+ ),
+ constraints: const BoxConstraints.tightFor(
+ width: 32,
+ height: 32,
+ ),
+ padding: const EdgeInsets.all(6),
+ icon: Icon(
+ unread == AlertKind.failed
+ ? AppIcons.circleX
+ : AppIcons.circleCheckBig,
+ size: 20,
+ semanticLabel:
+ '${unread == AlertKind.failed ? 'Failed' : 'Finished'}, not yet seen: ${row.agent.displayName}',
+ ),
),
- ),
- Tooltip(
- // Every harness pauses; what differs is how much comes
- // back, and the button says which before it is pressed —
- // a shell loses what was running in it, and an engine with
- // no way to reopen its conversation returns to a new one.
- message: busy
- ? pendingLabel
- : row.controlUnavailable ?? _toggleLabel(row),
- child: SizedBox(
- width: 40,
- height: 40,
- child: busy
- ? Semantics(
- liveRegion: true,
- label: '$pendingLabel ${row.agent.displayName}',
- child: Center(
- child: SizedBox(
- width: 15,
- height: 15,
- child: CircularProgressIndicator(
- strokeWidth: 1.5,
- color: AppPalette.textSecondary,
+ Tooltip(
+ // Every harness pauses; what differs is how much comes
+ // back, and the button says which before it is pressed —
+ // a shell loses what was running in it, and an engine with
+ // no way to reopen its conversation returns to a new one.
+ message: busy
+ ? pendingLabel
+ : row.controlUnavailable ?? _toggleLabel(row),
+ child: SizedBox(
+ width: 32,
+ height: 32,
+ child: busy
+ ? Semantics(
+ liveRegion: true,
+ label: '$pendingLabel ${row.agent.displayName}',
+ child: Center(
+ child: SizedBox(
+ width: 15,
+ height: 15,
+ child: CircularProgressIndicator(
+ strokeWidth: 1.5,
+ color: secondary,
+ ),
),
),
+ )
+ : IconButton(
+ key: ValueKey('session-toggle:${row.id}'),
+ onPressed: row.canControl ? onToggle : null,
+ icon: Icon(
+ row.agent.isStopped
+ ? AppIcons.play
+ : AppIcons.pause,
+ size: 20,
+ semanticLabel:
+ '${row.agent.isStopped ? 'Resume' : 'Pause'} ${row.agent.displayName}',
+ ),
+ padding: const EdgeInsets.all(6),
+ style: actionStyle(primary),
),
- )
- : IconButton(
- key: ValueKey('session-toggle:${row.id}'),
- onPressed: row.canControl ? onToggle : null,
- icon: Icon(
- row.agent.isStopped
- ? LucideIcons.play
- : LucideIcons.pause,
- size: 17,
- semanticLabel:
- '${row.agent.isStopped ? 'Resume' : 'Pause'} ${row.agent.displayName}',
- ),
- style: IconButton.styleFrom(
- foregroundColor: AppPalette.textPrimary,
- disabledForegroundColor: AppPalette.textFaint
- .withValues(alpha: .4),
- ),
- ),
+ ),
),
- ),
- const SizedBox(width: 6),
- ],
+ const SizedBox(width: 6),
+ ],
+ ),
),
- ),
- if (error != null)
- Padding(
- padding: const EdgeInsets.fromLTRB(46, 0, 12, 12),
- child: Semantics(
- liveRegion: true,
- child: Text(
- error!,
- style: AppType.body(color: const Color(0xffe4a19b)),
+ if (error != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppDesktop.identitySize + 24,
+ 0,
+ 12,
+ 12,
+ ),
+ child: Semantics(
+ liveRegion: true,
+ child: Text(
+ error!,
+ style: AppType.body(color: statusInk(errorInk)),
+ ),
),
),
- ),
- ],
+ ],
+ ),
),
),
);
}
}
-/// The two tints an unread harness is drawn in.
-///
-/// Named here rather than written at each use, so this and the "needs input"
-/// button beside it cannot drift into two different yellows.
-///
-/// There is no widget any more. A left-hand pip was tried and removed: the row
-/// already had a place for its state — the amber question button on the right —
-/// so a second marker beside the name said the same thing twice for a question,
-/// while putting "finished" somewhere the eye was not looking. Both live in
-/// that one slot now, and never both at once.
-abstract final class _UnreadMark {
- /// Waiting on a person. The amber the question button has always used.
- static const waitingTint = Color(0xffd9ad70);
-
- /// Finished. Green because it is the one colour nobody reads as "act now",
- /// which is exactly the difference being drawn.
- static const doneTint = Color(0xff6fbf8b);
-}
-
class _MonitorStats extends StatelessWidget {
- const _MonitorStats({required this.agent, required this.id});
+ const _MonitorStats({
+ required this.agent,
+ required this.id,
+ required this.selected,
+ });
final Agent agent;
final String id;
+ final bool selected;
@override
Widget build(BuildContext context) {
- final style = AppType.monoMeta(
- color: AppPalette.textSecondary,
- height: 1.3,
+ final style = AppType.caption(
+ color: selected ? AppDesktop.selectionDetail : AppPalette.textSecondary,
+ height: 1.35,
);
String measured(DateTime? time) =>
time == null ? '' : '\nUpdated ${time.toLocal()}';
@@ -982,12 +1008,20 @@ class _MonitorStats extends StatelessWidget {
children: [
TextSpan(
text: '+${formatTokens(stats.linesAdded!)}',
- style: const TextStyle(color: Color(0xff8dbb79)),
+ style: TextStyle(
+ color: selected
+ ? AppDesktop.onSelection
+ : AppPalette.online,
+ ),
),
const TextSpan(text: ' '),
TextSpan(
text: '−${formatTokens(stats.linesRemoved!)}',
- style: const TextStyle(color: Color(0xffd28f87)),
+ style: TextStyle(
+ color: selected
+ ? AppDesktop.onSelection
+ : Theme.of(context).colorScheme.error,
+ ),
),
],
),
diff --git a/desktop/lib/widgets/harness_start_page.dart b/desktop/lib/widgets/harness_start_page.dart
index ad740797b..315d2569a 100644
--- a/desktop/lib/widgets/harness_start_page.dart
+++ b/desktop/lib/widgets/harness_start_page.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
@@ -465,8 +466,8 @@ class _HarnessStartPageState extends State<HarnessStartPage> {
'harness-start-new-tab',
),
onPressed: widget.onNewTab ?? _open,
- icon: const Icon(Icons.add, size: 18),
- label: const Text('New Swarm'),
+ icon: const Icon(AppIcons.plus, size: 18),
+ label: const Text('New Tab'),
),
OutlinedButton.icon(
key: const ValueKey(
@@ -474,7 +475,7 @@ class _HarnessStartPageState extends State<HarnessStartPage> {
),
onPressed: widget.onNewPane ?? _open,
icon: const Icon(
- Icons.add_box_outlined,
+ AppIcons.squarePlus,
size: 18,
),
label: const Text('New Pane'),
diff --git a/desktop/lib/widgets/layout_palette.dart b/desktop/lib/widgets/layout_palette.dart
index f84aa2676..724cb7061 100644
--- a/desktop/lib/widgets/layout_palette.dart
+++ b/desktop/lib/widgets/layout_palette.dart
@@ -1,6 +1,6 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:harness/terminal/terminal_text.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
@@ -9,6 +9,7 @@ import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
import '../state/pane_preset.dart';
import '../theme/app_theme.dart';
+import 'desktop_chrome.dart';
/// ⇧⌘L — pick the shape of the grid.
///
@@ -229,11 +230,9 @@ class _LayoutPaletteState extends State<_LayoutPalette> {
},
},
child: Dialog(
- backgroundColor: grid.AppGlass.surfaceFill,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(13),
- side: BorderSide(color: grid.AppGlass.hair),
- ),
+ backgroundColor: DesktopChrome.surface,
+ insetPadding: const EdgeInsets.all(24),
+ shape: DesktopChrome.shape(),
child: Focus(
focusNode: _keys,
autofocus: true,
@@ -302,22 +301,18 @@ class _LayoutPaletteState extends State<_LayoutPalette> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(18, 16, 18, 12),
- child: Text(
- choices.isEmpty ? 'Layout' : 'Layout · $count panes',
- style: grid.AppType.monoLabel(
- color: grid.AppPalette.textSecondary,
- ),
- ),
+ DesktopDialogHeader(
+ title: choices.isEmpty
+ ? 'Layout'
+ : 'Layout · $count panes',
+ onClose: () => Navigator.of(context).pop(),
),
if (choices.isEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(18, 0, 18, 20),
child: Text(
- 'One tile has no layout to choose. Open another and the '
- 'shapes appear here.',
- style: grid.AppType.monoLabel(
+ 'Add another pane to choose a layout.',
+ style: grid.AppType.body(
fontWeight: FontWeight.w400,
color: grid.AppPalette.textFaint,
height: 1.45,
@@ -363,7 +358,7 @@ class _LayoutPaletteState extends State<_LayoutPalette> {
child: Text(
'Arrows to move · Enter or 1–${choices.length} to apply.\n'
'Changing layout resets pane sizes.',
- style: grid.AppType.monoMeta(
+ style: grid.AppType.caption(
color: grid.AppPalette.textSecondary,
height: 1.4,
),
@@ -446,56 +441,65 @@ class _ShapeButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
- return GestureDetector(
- onTap: onTap,
- child: Container(
- padding: const EdgeInsets.fromLTRB(10, 10, 10, 8),
- decoration: BoxDecoration(
- color: selected
+ return ExcludeFocus(
+ child: TextButton(
+ key: ValueKey('layout-choice-$index'),
+ onPressed: onTap,
+ style: TextButton.styleFrom(
+ padding: const EdgeInsets.fromLTRB(10, 10, 10, 8),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(10),
+ ),
+ backgroundColor: selected
? grid.AppSurface.accentWash
- : grid.AppSurface.hoverFill,
- borderRadius: BorderRadius.circular(10),
- border: Border.all(
- color: selected ? AppColors.accent : grid.AppGlass.hair,
+ : grid.AppSurface.recess,
+ side: BorderSide(
+ width: 2,
+ color: cursor
+ ? DesktopChrome.accent
+ : selected
+ ? DesktopChrome.accent.withValues(alpha: .45)
+ : MediaQuery.highContrastOf(context)
+ ? DesktopChrome.muted
+ : DesktopChrome.rim,
),
),
- // Paint focus over the fixed border so moving the highlight does not
- // change the diagram's bounds or the height of the wrapped row.
- foregroundDecoration: cursor
- ? BoxDecoration(
- borderRadius: BorderRadius.circular(10),
- border: Border.all(color: AppColors.accent, width: 2),
- )
- : null,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- SizedBox(
- width: _Strip.diagram,
- height: _Strip.diagram * 3 / 4,
- child: CustomPaint(painter: _ShapePainter(preset, count)),
- ),
- const SizedBox(height: 8),
- Text(
- preset.label,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: grid.AppType.monoLabel(
- fontWeight: FontWeight.w400,
- color: selected
- ? grid.AppPalette.textPrimary
- : grid.AppPalette.textSecondary,
+ child: Semantics(
+ selected: selected,
+ label: '${preset.label}${selected ? ', current layout' : ''}',
+ excludeSemantics: true,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ SizedBox(
+ width: _Strip.diagram,
+ height: _Strip.diagram * 3 / 4,
+ child: CustomPaint(painter: _ShapePainter(preset, count)),
),
- ),
- const SizedBox(height: 2),
- Text(
- '$index',
- style: grid.AppType.monoMeta(
- color: grid.AppPalette.textSecondary,
+ const SizedBox(height: 8),
+ Text(
+ preset.label,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(
+ color: selected
+ ? DesktopChrome.foreground
+ : DesktopChrome.muted,
+ ),
),
- ),
- ],
+ const SizedBox(height: 4),
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (selected) ...[
+ Icon(AppIcons.check, size: 14, color: DesktopChrome.accent),
+ const SizedBox(width: 4),
+ ],
+ Text('$index', style: DesktopChrome.metadata()),
+ ],
+ ),
+ ],
+ ),
),
),
);
diff --git a/desktop/lib/widgets/link_another_machine_dialog.dart b/desktop/lib/widgets/link_another_machine_dialog.dart
index 21f734486..8222af28c 100644
--- a/desktop/lib/widgets/link_another_machine_dialog.dart
+++ b/desktop/lib/widgets/link_another_machine_dialog.dart
@@ -770,7 +770,7 @@ class _LinkAnotherMachineDialogState extends State<_LinkAnotherMachineDialog> {
Padding(
padding: const EdgeInsets.all(8),
child: Text(
- 'Already linked. Open its harnesses from New Swarm or New Pane.',
+ 'Already linked. Open its harnesses from New Tab or New Pane.',
style: boxMonoStyle(
color: kBoxFaint,
),
diff --git a/desktop/lib/widgets/link_machine_dialog.dart b/desktop/lib/widgets/link_machine_dialog.dart
index 9c771908e..ca96920c1 100644
--- a/desktop/lib/widgets/link_machine_dialog.dart
+++ b/desktop/lib/widgets/link_machine_dialog.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -9,7 +10,10 @@ import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
import '../shortcuts/keymap_commands.dart' show describeKeyBinding;
import '../state/app_state.dart';
-import '../terminal/terminal_text.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
+
import 'box_chrome.dart';
/// This computer's incoming password and, separately, its outgoing links.
@@ -23,7 +27,6 @@ Future<void> showLinkMachineDialog(
context: context,
transitionDuration: Duration.zero,
veilBlur: 0,
- veilTint: Colors.transparent,
builder: (_) {
final dialog = _LinkMachineDialog(
notifier: notifier,
@@ -456,82 +459,108 @@ class _LinkMachineDialogState extends State<_LinkMachineDialog> {
Key? key,
bool first = false,
bool danger = false,
- }) => TextButton(
- key: key,
- focusNode: first ? _actionFocus : null,
- onPressed: action,
- style: TextButton.styleFrom(
- foregroundColor: danger ? boxErrorText : boxText(.70),
- textStyle: boxMonoStyle(),
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
- minimumSize: const Size(0, 30),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- ),
- child: Text(label),
- );
+ bool primary = false,
+ }) {
+ if (primary || danger) {
+ return FilledButton(
+ key: key,
+ focusNode: first ? _actionFocus : null,
+ onPressed: action,
+ style: danger ? grid.dangerButtonStyle() : null,
+ child: Text(label),
+ );
+ }
+ return TextButton(
+ key: key,
+ focusNode: first ? _actionFocus : null,
+ onPressed: action,
+ child: Text(label),
+ );
+ }
Widget _field({required bool confirm}) {
final controller = confirm ? _confirm : _password;
- return ReadlineKeys(
- controller: controller,
- enabled: !_busy,
- onChanged: _edited,
- child: TextField(
- key: Key(
- confirm ? 'remote-password-confirm-field' : 'remote-password-field',
- ),
- controller: controller,
- focusNode: confirm ? _confirmFocus : _passwordFocus,
- readOnly: _busy,
- obscureText: _obscure,
- enableSuggestions: false,
- autocorrect: false,
- style: boxMonoStyle(),
- textAlignVertical: TextAlignVertical.center,
- textInputAction: confirm ? TextInputAction.done : TextInputAction.next,
- decoration: InputDecoration(
- hintText: confirm ? 'Repeat password' : 'New remote password',
- hintStyle: boxMonoStyle(color: kBoxFaint),
- isDense: true,
- filled: false,
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- prefixIcon: Padding(
- padding: const EdgeInsets.only(right: 10),
- child: Center(
- widthFactor: 1,
- heightFactor: 1,
- child: Text(
- confirm ? ' again >' : 'password >',
- style: boxMonoStyle(color: boxText(.70)),
- ),
- ),
- ),
- prefixIconConstraints: const BoxConstraints(minHeight: 38),
- suffixIconConstraints: const BoxConstraints(
- minWidth: 28,
- minHeight: 28,
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ confirm ? 'Confirm password' : 'Remote password',
+ style: DesktopChrome.control(medium: true),
),
- suffixIcon: confirm
- ? null
- : IconButton(
- tooltip: _obscure ? 'Show password' : 'Hide password',
- icon: Icon(
- _obscure
- ? Icons.visibility_outlined
- : Icons.visibility_off_outlined,
- size: 16,
+ const SizedBox(height: 6),
+ Tooltip(
+ message:
+ '${confirm ? 'Set password' : 'Confirm password'} · ${_hint('picker.accept', 'enter')}',
+ child: ReadlineKeys(
+ controller: controller,
+ enabled: !_busy,
+ onChanged: _edited,
+ child: TextField(
+ key: Key(
+ confirm
+ ? 'remote-password-confirm-field'
+ : 'remote-password-field',
+ ),
+ controller: controller,
+ focusNode: confirm ? _confirmFocus : _passwordFocus,
+ readOnly: _busy,
+ obscureText: _obscure,
+ enableSuggestions: false,
+ autocorrect: false,
+ style: DesktopChrome.text(),
+ textAlignVertical: TextAlignVertical.center,
+ textInputAction: confirm
+ ? TextInputAction.done
+ : TextInputAction.next,
+ decoration: InputDecoration(
+ hintText: confirm ? 'Repeat password' : 'New remote password',
+ hintStyle: DesktopChrome.text(color: DesktopChrome.muted),
+ suffixIconConstraints: const BoxConstraints(
+ minWidth: 40,
+ minHeight: 36,
),
- onPressed: _busy
+ suffixIcon: confirm
? null
- : () => setState(() => _obscure = !_obscure),
+ : Center(
+ widthFactor: 1,
+ heightFactor: 1,
+ child: IconButton(
+ tooltip: _obscure
+ ? 'Show password'
+ : 'Hide password',
+ icon: Icon(
+ _obscure ? AppIcons.eye : AppIcons.eyeOff,
+ size: 16,
+ ),
+ constraints: const BoxConstraints.tightFor(
+ width: 32,
+ height: 32,
+ ),
+ style: ButtonStyle(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? DesktopChrome.accent
+ : Colors.transparent,
+ ),
+ ),
+ ),
+ onPressed: _busy
+ ? null
+ : () => setState(() => _obscure = !_obscure),
+ ),
+ ),
),
- contentPadding: EdgeInsets.zero,
- ),
- onEditingComplete: () {},
- onSubmitted: (_) => confirm ? _submit() : _nextField(),
- onChanged: _edited,
+ onEditingComplete: () {},
+ onSubmitted: (_) => confirm ? _submit() : _nextField(),
+ onChanged: _edited,
+ ),
+ ),
+ ),
+ ],
),
);
}
@@ -539,7 +568,7 @@ class _LinkMachineDialogState extends State<_LinkMachineDialog> {
List<Widget> _passwordBody() {
if (_loading) {
return [
- Text('Reading password status…', style: boxMonoStyle(color: kBoxFaint)),
+ Text('Reading password status…', style: DesktopChrome.metadata()),
];
}
if (_status == null) {
@@ -548,7 +577,7 @@ class _LinkMachineDialogState extends State<_LinkMachineDialog> {
_busy
? 'This operation continues if you close the prompt.'
: 'Password status is unavailable.',
- style: boxMonoStyle(color: kBoxFaint),
+ style: DesktopChrome.metadata(),
),
if (!_busy)
Align(
@@ -565,49 +594,35 @@ class _LinkMachineDialogState extends State<_LinkMachineDialog> {
if (_editing) ...[
Text(
'Use this password on the other machine to link to this computer.',
- style: boxMonoStyle(color: boxText(.70)),
+ style: DesktopChrome.text(color: DesktopChrome.muted),
),
const SizedBox(height: 12),
_field(confirm: false),
_field(confirm: true),
- const SizedBox(height: 8),
- Wrap(
- spacing: 10,
- children: [
- _button(
- _status!.hasPassword ? 'Change password' : 'Set password',
- _busy ? null : _submit,
- key: const Key('remote-password-set-button'),
- ),
- if (_status!.hasPassword) _button('Cancel', _busy ? null : _back),
- ],
- ),
] else ...[
- Text(
- 'Remote password is set',
- style: boxMonoStyle(weight: FontWeight.w600),
- ),
+ Text('Remote password is set', style: DesktopChrome.text(medium: true)),
const SizedBox(height: 8),
Text(
'On the other machine: Link machine → select this computer → enter its password.',
- style: boxMonoStyle(color: boxText(.70)),
+ style: DesktopChrome.text(color: DesktopChrome.muted),
),
if (_status!.fingerprint case final fingerprint?) ...[
const SizedBox(height: 12),
- Text('fingerprint', style: boxMonoStyle(color: kBoxFaint)),
+ Text('Fingerprint', style: DesktopChrome.metadata()),
SelectableText(
fingerprint,
- style: boxMonoStyle(color: boxText(.70)),
+ style: grid.AppType.mono(color: DesktopChrome.muted),
),
],
if (_status!.setAt case final date?)
Text(
- 'set ${date.toLocal().toIso8601String().substring(0, 16).replaceFirst('T', ' ')}',
- style: boxMonoStyle(color: kBoxFaint),
+ 'Set ${date.toLocal().toIso8601String().substring(0, 16).replaceFirst('T', ' ')}',
+ style: DesktopChrome.metadata(),
),
const SizedBox(height: 10),
Wrap(
- spacing: 10,
+ spacing: 8,
+ runSpacing: 8,
children: [
_button(
'Change password',
@@ -627,7 +642,7 @@ class _LinkMachineDialogState extends State<_LinkMachineDialog> {
const SizedBox(height: 8),
Text(
'This operation continues if you close the prompt.',
- style: boxMonoStyle(color: kBoxFaint),
+ style: DesktopChrome.metadata(),
),
],
if (!widget.passwordOnly) ...[
@@ -647,7 +662,7 @@ class _LinkMachineDialogState extends State<_LinkMachineDialog> {
List<Widget> _linksBody() => [
Text(
'Machines this computer can connect to.',
- style: boxMonoStyle(color: boxText(.70)),
+ style: DesktopChrome.text(color: DesktopChrome.muted),
),
const SizedBox(height: 8),
Align(
@@ -655,24 +670,21 @@ class _LinkMachineDialogState extends State<_LinkMachineDialog> {
child: _button('Refresh links', _refresh, first: true),
),
if (app.linkedMachinesLoading && app.linkedMachines.isEmpty)
- Text('Loading linked machines…', style: boxMonoStyle(color: kBoxFaint))
+ Text('Loading linked machines…', style: DesktopChrome.metadata())
else if (app.linkedMachines.isEmpty && app.linkedMachinesError == null)
- Text('No machines linked yet.', style: boxMonoStyle(color: kBoxFaint)),
+ Text('No machines linked yet.', style: DesktopChrome.metadata()),
for (final machine in app.linkedMachines)
Padding(
padding: const EdgeInsets.only(top: 12, bottom: 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text(_name(machine), style: boxMonoStyle()),
+ Text(_name(machine), style: DesktopChrome.text()),
SelectableText(
machine.fingerprint,
- style: boxMonoStyle(color: kBoxFaint),
- ),
- Text(
- 'linked ${machine.linkedAt}',
- style: boxMonoStyle(color: kBoxFaint),
+ style: grid.AppType.mono(color: DesktopChrome.muted),
),
+ Text('Linked ${machine.linkedAt}', style: DesktopChrome.metadata()),
_button(
app.unlinkingMachine(machine.machineId)
? 'Unlinking…'
@@ -694,143 +706,121 @@ class _LinkMachineDialogState extends State<_LinkMachineDialog> {
clear
? 'Prevent new links using this password? Existing links and sessions stay connected.'
: 'Remove this computer’s saved link to ${_name(_unlinkTarget!)}? A new connection will need that machine’s password.',
- style: boxMonoStyle(color: boxText(.70)),
+ style: DesktopChrome.text(color: DesktopChrome.muted),
),
- const SizedBox(height: 14),
- Wrap(
- spacing: 12,
- children: [
- _button('Cancel', _busy ? null : _back, first: true),
- _button(
- clear ? 'Clear password' : 'Unlink',
- _busy
- ? null
- : clear
- ? _clear
- : () => unawaited(_unlink()),
- danger: true,
- key: Key(
- clear
- ? 'remote-password-clear-confirm-button'
- : 'remote-password-unlink-confirm-button',
- ),
+ ];
+ }
+
+ List<Widget> _dialogActions() {
+ if (_busy) {
+ return [TextButton(onPressed: _back, child: const Text('Close'))];
+ }
+ if (_page == _Page.clear || _page == _Page.unlink) {
+ final clear = _page == _Page.clear;
+ return [
+ _button('Cancel', _back, first: true),
+ _button(
+ clear ? 'Clear password' : 'Unlink',
+ clear ? _clear : () => unawaited(_unlink()),
+ danger: true,
+ key: Key(
+ clear
+ ? 'remote-password-clear-confirm-button'
+ : 'remote-password-unlink-confirm-button',
),
- ],
+ ),
+ ];
+ }
+ if (_page == _Page.password && _editing && _status != null) {
+ return [
+ _button(_status!.hasPassword ? 'Cancel' : 'Close', _back),
+ _button(
+ _status!.hasPassword ? 'Change password' : 'Set password',
+ _submit,
+ key: const Key('remote-password-set-button'),
+ primary: true,
+ ),
+ ];
+ }
+ final close = _page == _Page.password;
+ return [
+ Tooltip(
+ message:
+ '${close ? 'Close' : 'Back'} · ${_hint('picker.cancel', 'esc')}',
+ child: TextButton(
+ onPressed: _back,
+ child: Text(close ? 'Close' : 'Back'),
+ ),
),
];
}
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
return ListenableBuilder(
- listenable: Listenable.merge([
- app,
- terminalFontStore,
- _passwordFocus,
- _confirmFocus,
- ]),
- builder: (context, _) => Dialog(
- alignment: Alignment.topCenter,
- insetPadding: const EdgeInsets.fromLTRB(16, 56, 16, 18),
- elevation: 0,
- backgroundColor: Colors.transparent,
- child: _keys(
+ listenable: Listenable.merge([app, _passwordFocus, _confirmFocus]),
+ builder: (context, _) {
+ final message = _busy
+ ? (_page == _Page.unlink
+ ? 'Unlinking machine…'
+ : _clearing
+ ? 'Clearing password…'
+ : 'Setting password…')
+ : _message ??
+ (_page == _Page.links ? app.linkedMachinesError : null);
+ final isError =
+ !_busy &&
+ (_error || _page == _Page.links && app.linkedMachinesError != null);
+ return _keys(
Focus(
+ skipTraversal: true,
autofocus: true,
onKeyEvent: _key,
- child: SizedBox(
- width: 660,
- child: TerminalBox(
+ child: DesktopPromptSurface(
+ width: 480,
+ body: DesktopPromptScrollBody(
child: Column(
- mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Flexible(
- child: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(switch (_page) {
- _Page.password => 'This computer’s password',
- _Page.clear => 'Clear remote password',
- _Page.links => 'Links from this computer',
- _Page.unlink => 'Unlink machine',
- }, style: boxMonoStyle(color: kBoxFaint)),
- const SizedBox(height: 14),
- ...switch (_page) {
- _Page.password => _passwordBody(),
- _Page.links => _linksBody(),
- _Page.clear ||
- _Page.unlink => _confirmationBody(),
- },
- ],
- ),
- ),
- ),
- BoxHintStrip(
- message: _busy
- ? (_page == _Page.unlink
- ? 'Unlinking machine…'
- : _clearing
- ? 'Clearing password…'
- : 'Setting password…')
- : _message ??
- (_page == _Page.links
- ? app.linkedMachinesLoading
- ? 'Loading linked machines…'
- : app.linkedMachinesError
- : null),
- isError:
- !_busy &&
- (_error ||
- _page == _Page.links &&
- app.linkedMachinesError != null),
- hints: [
- if (!_busy && !_loading)
- BoxHint(
- _hint('picker.accept', 'enter'),
- _page == _Page.password &&
- _editing &&
- _passwordFocus.hasFocus
- ? 'confirm password'
- : _page == _Page.password &&
- _editing &&
- _confirmFocus.hasFocus
- ? 'set password'
- : 'select',
- ),
- if (!_busy && !_loading)
- BoxHint(_hint('picker.complete', 'tab'), 'controls'),
- if (!_busy &&
- !_loading &&
- (_page == _Page.links ||
- _page == _Page.password && !_editing))
- BoxHint(
- _hint('picker.refresh', _mac ? 'cmd-r' : 'ctrl-r'),
- 'refresh',
- onTap: _refresh,
- ),
- BoxHint(
- _hint('picker.cancel', 'esc'),
- _busy ||
- _page == _Page.password &&
- (!_editing ||
- _status?.hasPassword != true)
- ? 'close'
- : 'back',
- onTap: _back,
- ),
- ],
+ Semantics(
+ header: true,
+ child: Text(switch (_page) {
+ _Page.password => 'This computer’s password',
+ _Page.clear => 'Clear remote password',
+ _Page.links => 'Links from this computer',
+ _Page.unlink => 'Unlink machine',
+ }, style: DesktopChrome.heading()),
),
+ const SizedBox(height: 16),
+ ...switch (_page) {
+ _Page.password => _passwordBody(),
+ _Page.links => _linksBody(),
+ _Page.clear || _Page.unlink => _confirmationBody(),
+ },
],
),
),
+ footer: message == null
+ ? null
+ : Semantics(
+ liveRegion: true,
+ child: SelectableText(
+ message,
+ minLines: 1,
+ maxLines: 3,
+ style: DesktopChrome.control(
+ color: isError
+ ? Theme.of(context).colorScheme.error
+ : DesktopChrome.muted,
+ ),
+ ),
+ ),
+ actions: _dialogActions(),
),
),
- ),
- ),
+ );
+ },
);
}
}
diff --git a/desktop/lib/widgets/link_machine_screen.dart b/desktop/lib/widgets/link_machine_screen.dart
index d4854f4bc..f39acd3e5 100644
--- a/desktop/lib/widgets/link_machine_screen.dart
+++ b/desktop/lib/widgets/link_machine_screen.dart
@@ -1,11 +1,14 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
-import '../terminal/terminal_text.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+
import 'box_chrome.dart';
/// Opens [LinkMachineScreen] as a modal popup for [machineId], closing itself automatically once
@@ -31,12 +34,10 @@ Future<void> showLinkMachineScreenDialog(
context: context,
transitionDuration: Duration.zero,
veilBlur: 0,
- veilTint: Colors.transparent,
builder: (context) => Dialog(
- alignment: Alignment.topCenter,
backgroundColor: Colors.transparent,
elevation: 0,
- insetPadding: const EdgeInsets.fromLTRB(16, 56, 16, 18),
+ insetPadding: const EdgeInsets.all(20),
child: ListenableBuilder(
listenable: notifier,
builder: (context, _) {
@@ -211,162 +212,193 @@ class _LinkMachineScreenState extends State<LinkMachineScreen> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
return ListenableBuilder(
- listenable: Listenable.merge([widget.notifier, terminalFontStore]),
+ listenable: widget.notifier,
builder: (context, _) {
final machineName = widget.machineState.machine.displayName;
- return Focus(
- onKeyEvent: _key,
- child: SizedBox(
- width: 620,
- child: TerminalBox(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Flexible(
- child: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- 'Link this machine',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- const SizedBox(height: 12),
- Text(
- machineName,
- style: boxMonoStyle(weight: FontWeight.w600),
- ),
- const SizedBox(height: 4),
- Text(
- 'Enter the remote password set on this machine.',
- style: boxMonoStyle(color: boxText(.70)),
- ),
- const SizedBox(height: 14),
- ReadlineKeys(
- controller: _passwordController,
- enabled: !_submitting,
- onChanged: _edited,
- child: TextField(
- key: const Key('remote-password-connect-field'),
- controller: _passwordController,
- focusNode: _passwordFocus,
- autofocus: true,
- readOnly: _submitting,
- obscureText: _obscure,
- enableSuggestions: false,
- autocorrect: false,
- textInputAction: TextInputAction.done,
- textAlignVertical: TextAlignVertical.center,
- style: boxMonoStyle(),
- decoration: InputDecoration(
- hintText: 'Remote password for $machineName',
- hintStyle: boxMonoStyle(color: kBoxFaint),
- isDense: true,
- filled: false,
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- prefixIcon: Padding(
- padding: const EdgeInsets.only(right: 10),
- child: Center(
- widthFactor: 1,
- heightFactor: 1,
- child: Text(
- 'password >',
- style: boxMonoStyle(
- color: boxText(.70),
+ return DesktopChrome(
+ child: Focus(
+ skipTraversal: true,
+ onKeyEvent: _key,
+ child: SizedBox(
+ width: 480,
+ child: DesktopDialogSurface(
+ child: Padding(
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Semantics(
+ header: true,
+ child: Text(
+ 'Link this machine',
+ style: DesktopChrome.heading(),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ machineName,
+ style: DesktopChrome.text(medium: true),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'Enter the remote password set on this machine.',
+ style: DesktopChrome.text(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ const SizedBox(height: 16),
+ ReadlineKeys(
+ controller: _passwordController,
+ enabled: !_submitting,
+ onChanged: _edited,
+ child: TextField(
+ key: const Key(
+ 'remote-password-connect-field',
+ ),
+ controller: _passwordController,
+ focusNode: _passwordFocus,
+ autofocus: true,
+ readOnly: _submitting,
+ obscureText: _obscure,
+ enableSuggestions: false,
+ autocorrect: false,
+ textInputAction: TextInputAction.done,
+ textAlignVertical: TextAlignVertical.center,
+ style: DesktopChrome.text(),
+ decoration: InputDecoration(
+ hintText:
+ 'Remote password for $machineName',
+ hintStyle: DesktopChrome.text(
+ color: DesktopChrome.muted,
+ ),
+ suffixIconConstraints: const BoxConstraints(
+ minWidth: 40,
+ minHeight: 36,
+ ),
+ suffixIcon: Center(
+ widthFactor: 1,
+ heightFactor: 1,
+ child: IconButton(
+ tooltip: _obscure
+ ? 'Show password'
+ : 'Hide password',
+ icon: Icon(
+ _obscure
+ ? AppIcons.eye
+ : AppIcons.eyeOff,
+ size: 16,
+ ),
+ constraints:
+ const BoxConstraints.tightFor(
+ width: 32,
+ height: 32,
+ ),
+ style: ButtonStyle(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color:
+ states.contains(
+ WidgetState.focused,
+ )
+ ? DesktopChrome.accent
+ : Colors.transparent,
+ ),
+ ),
+ ),
+ onPressed: _submitting
+ ? null
+ : () => setState(
+ () => _obscure = !_obscure,
+ ),
),
),
),
+ // Native Done keeps Escape available while connecting.
+ onEditingComplete: () {},
+ onSubmitted: (_) => _submit(),
+ onChanged: _edited,
),
- prefixIconConstraints: const BoxConstraints(
- minHeight: 36,
- ),
- suffixIconConstraints: const BoxConstraints(
- minWidth: 28,
- minHeight: 28,
- ),
- suffixIcon: IconButton(
- tooltip: _obscure
- ? 'Show password'
- : 'Hide password',
- icon: Icon(
- _obscure
- ? Icons.visibility_outlined
- : Icons.visibility_off_outlined,
- size: 16,
+ ),
+ const SizedBox(height: 12),
+ Text(
+ _submitting
+ ? 'Connecting continues if you close this prompt.'
+ : 'Your previous harness will reconnect automatically after linking.',
+ style: DesktopChrome.metadata(),
+ ),
+ const SizedBox(height: 8),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton(
+ key: const Key(
+ 'link-troubleshooting-details',
+ ),
+ onPressed: () => setState(
+ () => _showTroubleshootingDetails =
+ !_showTroubleshootingDetails,
+ ),
+ child: Text(
+ _showTroubleshootingDetails
+ ? 'Hide details'
+ : 'Troubleshooting details',
),
- onPressed: _submitting
- ? null
- : () => setState(
- () => _obscure = !_obscure,
- ),
),
- contentPadding: EdgeInsets.zero,
),
- // Native Done must keep the prompt's key scope alive
- // while connecting, so Escape still closes it.
- onEditingComplete: () {},
- onSubmitted: (_) => _submit(),
- onChanged: _edited,
+ if (_showTroubleshootingDetails)
+ SelectableText(
+ 'Machine ID: $_machineId',
+ style: grid.AppType.mono(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ if (_error != null || _submitting) ...[
+ const SizedBox(height: 16),
+ Semantics(
+ liveRegion: true,
+ child: SelectableText(
+ _error ?? _progress,
+ minLines: 1,
+ maxLines: 3,
+ style: DesktopChrome.control(
+ color: _error != null
+ ? Theme.of(context).colorScheme.error
+ : DesktopChrome.muted,
),
),
- const SizedBox(height: 8),
- Text(
- _submitting
- ? 'Connecting continues if you close this prompt.'
- : 'Your previous harness will reconnect automatically after linking.',
- style: boxMonoStyle(color: kBoxFaint),
+ ),
+ ],
+ const SizedBox(height: 16),
+ Wrap(
+ alignment: WrapAlignment.end,
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ TextButton(
+ onPressed: _close,
+ child: const Text('Close'),
),
- const SizedBox(height: 8),
- Align(
- alignment: Alignment.centerLeft,
- child: TextButton(
- key: const Key('link-troubleshooting-details'),
- style: TextButton.styleFrom(
- textStyle: boxMonoStyle(),
- foregroundColor: boxText(.70),
- padding: const EdgeInsets.symmetric(
- horizontal: 4,
- ),
- minimumSize: const Size(0, 28),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- ),
- onPressed: () => setState(
- () => _showTroubleshootingDetails =
- !_showTroubleshootingDetails,
- ),
- child: Text(
- _showTroubleshootingDetails
- ? 'Hide details'
- : 'Troubleshooting details',
- ),
- ),
+ FilledButton(
+ onPressed: _submitting ? null : _submit,
+ child: const Text('Link machine'),
),
- if (_showTroubleshootingDetails)
- SelectableText(
- 'Machine ID: $_machineId',
- style: boxMonoStyle(color: kBoxFaint),
- ),
],
),
- ),
- ),
- BoxHintStrip(
- message: _error ?? (_submitting ? _progress : null),
- isError: _error != null,
- hints: [
- if (!_submitting)
- BoxHint('enter', 'link machine', onTap: _submit),
- BoxHint('tab', 'controls'),
- BoxHint('esc', 'close', onTap: _close),
],
),
- ],
+ ),
),
),
),
diff --git a/desktop/lib/widgets/machine_actions.dart b/desktop/lib/widgets/machine_actions.dart
index 1a6ccfffd..cdc12b533 100644
--- a/desktop/lib/widgets/machine_actions.dart
+++ b/desktop/lib/widgets/machine_actions.dart
@@ -4,8 +4,10 @@ import 'package:flutter/material.dart';
import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
-import '../terminal/terminal_text.dart';
-import 'box_chrome.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
+import 'box_chrome.dart' show BoxAnnouncer;
import 'terminal_prompt.dart';
/// Account deletion, shared by the manager and native/legacy machine menus.
@@ -101,88 +103,72 @@ class _DeleteMachinePromptState extends State<_DeleteMachinePrompt> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
- return ListenableBuilder(
- listenable: terminalFontStore,
- builder: (context, _) => TerminalPromptKeys(
- focusNode: _promptFocus,
- cancel: _close,
- child: TerminalPrompt(
+ grid.AppTheme.watch(context);
+ final danger = Theme.of(context).colorScheme.error;
+ final closeLabel = _deleting ? 'Close' : 'Cancel';
+ return TerminalPromptKeys(
+ focusNode: _promptFocus,
+ cancel: _close,
+ child: DesktopPromptSurface(
+ body: DesktopPromptScrollBody(
child: Column(
- mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Flexible(
- child: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- 'Delete machine',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- const SizedBox(height: 12),
- Text(
- widget.displayName,
- style: boxMonoStyle(weight: FontWeight.w600),
- ),
- const SizedBox(height: 8),
- Text(
- 'Delete this machine from your account and close its panes in this window?',
- style: boxMonoStyle(color: boxText(.70)),
- ),
- const SizedBox(height: 12),
- if (!_deleting)
- Wrap(
- spacing: 12,
- children: [
- terminalPromptButton(
- 'Cancel',
- _close,
- focusNode: _cancel,
- ),
- terminalPromptButton(
- 'Delete',
- _delete,
- danger: true,
- key: const Key('machine-delete-confirm'),
- ),
- ],
- )
- else
- Text(
- 'Deletion continues if you close this prompt.',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ],
- ),
- ),
+ Text('Delete machine', style: DesktopChrome.heading()),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ widget.displayName,
+ style: DesktopChrome.text(size: 14, medium: true),
),
- BoxHintStrip(
- message: _error ?? (_deleting ? 'Deleting machine…' : null),
- isError: _error != null,
- hints: [
- if (!_deleting)
- BoxHint(
- terminalPromptHint(context, 'picker.accept', 'enter'),
- 'select',
- ),
- if (!_deleting)
- BoxHint(
- terminalPromptHint(context, 'picker.complete', 'tab'),
- 'controls',
- ),
- BoxHint(
- terminalPromptHint(context, 'picker.cancel', 'esc'),
- 'close',
- onTap: _close,
- ),
- ],
+ const SizedBox(height: 8),
+ Text(
+ 'Delete this machine from your account and close its panes in this window?',
+ style: DesktopChrome.text(size: 13),
),
+ if (_deleting) ...[
+ const SizedBox(height: 12),
+ Text(
+ 'Deletion continues if you close this dialog.',
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
],
),
),
+ footer: _error != null || _deleting
+ ? Semantics(
+ liveRegion: true,
+ child: DesktopPromptMessage(
+ _error ?? 'Deleting machine…',
+ color: _error == null ? DesktopChrome.muted : danger,
+ ),
+ )
+ : null,
+ actions: [
+ Tooltip(
+ message:
+ '$closeLabel · ${terminalPromptHint(context, 'picker.cancel', 'esc')}',
+ child: TextButton(
+ focusNode: _deleting ? null : _cancel,
+ onPressed: _close,
+ child: Text(closeLabel),
+ ),
+ ),
+ if (!_deleting)
+ Tooltip(
+ message:
+ 'Delete · ${terminalPromptHint(context, 'picker.accept', 'enter')}',
+ child: FilledButton(
+ key: const Key('machine-delete-confirm'),
+ onPressed: _delete,
+ style: grid.dangerButtonStyle(),
+ child: const Text('Delete'),
+ ),
+ ),
+ ],
),
);
}
diff --git a/desktop/lib/widgets/machine_picker_form.dart b/desktop/lib/widgets/machine_picker_form.dart
index 84b2ee4ed..d7fa206ad 100644
--- a/desktop/lib/widgets/machine_picker_form.dart
+++ b/desktop/lib/widgets/machine_picker_form.dart
@@ -13,6 +13,7 @@ import '../terminal/terminal_text.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
import 'box_chrome.dart' show ReadlineKeys;
+import 'desktop_chrome.dart';
import 'link_another_machine_dialog.dart'
show
kHarnessDownloadUrl,
@@ -195,6 +196,21 @@ class MachinePickerFormState extends State<MachinePickerForm> {
void _tab(bool forward) {
if (_composing) return;
+ if (DesktopChrome.of(context)) {
+ final nodes = _nodes;
+ final current = nodes.indexWhere((node) => node.hasFocus);
+ final next = current + (forward ? 1 : -1);
+ if (next >= 0 && next < nodes.length) {
+ final node = nodes[next];
+ node.requestFocus();
+ if (node.context case final context?) Scrollable.ensureVisible(context);
+ } else if (widget.onSwitchPane != null) {
+ widget.onSwitchPane!();
+ } else {
+ _move(forward);
+ }
+ return;
+ }
widget.onSwitchPane != null ? widget.onSwitchPane!() : _move(forward);
}
@@ -518,20 +534,90 @@ class MachinePickerFormState extends State<MachinePickerForm> {
FocusNode focus,
String key,
) {
+ final desktop = DesktopChrome.of(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
final cell = terminalCellSizeOf(context);
+ if (desktop) {
+ final fieldLabel = switch (label) {
+ 'name' => 'Name',
+ 'confirm' => 'Confirm password',
+ _ => 'Password',
+ };
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ fieldLabel,
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ ),
+ const SizedBox(height: 6),
+ ReadlineKeys(
+ controller: controller,
+ enabled: !_busy,
+ onChanged: (_) {
+ if (_message != null) setState(() => _message = null);
+ },
+ child: TextField(
+ key: ValueKey(key),
+ controller: controller,
+ focusNode: focus,
+ readOnly: _busy,
+ onTapOutside: (_) {},
+ obscureText:
+ widget.kind != MachinePickerFormKind.rename && !_showPassword,
+ enableSuggestions: false,
+ autocorrect: false,
+ style: DesktopChrome.text(size: 13),
+ cursorColor: DesktopChrome.accent,
+ decoration: InputDecoration(
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ ),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(
+ color: DesktopChrome.focusRing,
+ width: grid.AppDesktop.focusWidth,
+ ),
+ ),
+ filled: true,
+ fillColor: DesktopChrome.field,
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 10,
+ ),
+ ),
+ onEditingComplete: () {},
+ onChanged: (_) {
+ if (_message != null) setState(() => _message = null);
+ },
+ ),
+ ),
+ ],
+ );
+ }
return Row(
children: [
SizedBox(
width: cell.width * 10,
child: Text(
'$label >',
- style: terminalContentStyle(
- color: theme.muted,
- ),
+ style: terminalContentStyle(color: theme.muted),
),
),
Expanded(
@@ -578,7 +664,9 @@ class MachinePickerFormState extends State<MachinePickerForm> {
@override
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
- final cell = terminalCellSizeOf(context);
+ grid.AppTheme.watch(context);
+ final desktop = DesktopChrome.of(context);
+ final cell = desktop ? const Size(9, 14) : terminalCellSizeOf(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
@@ -586,9 +674,17 @@ class MachinePickerFormState extends State<MachinePickerForm> {
Widget line(String text, {bool selectable = false}) => selectable
? SelectableText(
text,
- style: terminalContentStyle(color: theme.foreground),
+ style: desktop
+ ? grid.AppType.mono(color: DesktopChrome.foreground)
+ .copyWith(fontSize: 12)
+ : terminalContentStyle(color: theme.foreground),
)
- : Text(text, style: terminalContentStyle(color: theme.foreground));
+ : Text(
+ text,
+ style: desktop
+ ? DesktopChrome.text(size: 13)
+ : terminalContentStyle(color: theme.foreground),
+ );
final gap = SizedBox(height: cell.height);
final name = machine?.machine.displayName ?? '';
final email = app.currentUser?.email;
@@ -600,10 +696,13 @@ class MachinePickerFormState extends State<MachinePickerForm> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- line(
+ Text(
_setup
? 'Add machine · ${widget.kind == MachinePickerFormKind.app ? 'App' : 'CLI'}'
: name,
+ style: desktop
+ ? DesktopChrome.heading()
+ : terminalContentStyle(color: theme.foreground),
),
gap,
if (_setup) ...[
@@ -680,31 +779,56 @@ class MachinePickerFormState extends State<MachinePickerForm> {
liveRegion: true,
child: Text(
_busy ? _progress : _message!,
- style: terminalContentStyle(
- color: !_busy && _error
- ? theme.yellow
- : theme.muted,
- ),
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: !_busy && _error
+ ? Theme.of(context).colorScheme.error
+ : DesktopChrome.muted,
+ )
+ : terminalContentStyle(
+ color: !_busy && _error ? theme.yellow : theme.muted,
+ ),
),
),
gap,
],
_keys(
Wrap(
- spacing: cell.width * 2,
- runSpacing: cell.height,
+ spacing: desktop ? 8 : cell.width * 2,
+ runSpacing: desktop ? 8 : cell.height,
children: [
for (final action in _actions)
- TerminalTextAction(
- key: ValueKey('machine-form:${_buttonId(action.label)}'),
- label: action.label,
- padding: EdgeInsets.zero,
- focusNode: _buttons.putIfAbsent(
- _buttonId(action.label),
- () => FocusNode(debugLabel: action.label),
+ if (desktop)
+ DesktopPill(
+ key: ValueKey('machine-form:${_buttonId(action.label)}'),
+ label: switch (action.label) {
+ 'Show' => 'Show password',
+ 'Hide' => 'Hide password',
+ _ => action.label,
+ },
+ compact: true,
+ focusNode: _buttons.putIfAbsent(
+ _buttonId(action.label),
+ () => FocusNode(debugLabel: action.label),
+ ),
+ foregroundColor:
+ action.label == 'Delete' || action.label == 'Clear'
+ ? Theme.of(context).colorScheme.error
+ : null,
+ onPressed: action.run,
+ )
+ else
+ TerminalTextAction(
+ key: ValueKey('machine-form:${_buttonId(action.label)}'),
+ label: action.label,
+ padding: EdgeInsets.zero,
+ focusNode: _buttons.putIfAbsent(
+ _buttonId(action.label),
+ () => FocusNode(debugLabel: action.label),
+ ),
+ onPressed: action.run,
),
- onPressed: action.run,
- ),
],
),
buttons: true,
@@ -746,12 +870,12 @@ class MachinePickerFormState extends State<MachinePickerForm> {
[
if (hint('picker.accept') case final enter?) '$enter select',
if (hint('picker.complete') case final tab?)
- '$tab ${widget.onSwitchPane != null ? 'pane' : 'next'}',
+ '$tab ${!desktop && widget.onSwitchPane != null ? 'pane' : 'next'}',
if (hint('picker.cancel') case final escape?) '$escape back',
].join(' · '),
- style: terminalContentStyle(
- color: theme.muted,
- ),
+ style: desktop
+ ? DesktopChrome.metadata()
+ : terminalContentStyle(color: theme.muted),
),
),
],
diff --git a/desktop/lib/widgets/machines_panel.dart b/desktop/lib/widgets/machines_panel.dart
index 33ef9523a..69e4ebdf6 100644
--- a/desktop/lib/widgets/machines_panel.dart
+++ b/desktop/lib/widgets/machines_panel.dart
@@ -1,9 +1,9 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart' show CustomSemanticsAction;
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';
import '../auth/cli_link.dart';
@@ -785,7 +785,7 @@ class _MachinesPanelState extends State<_MachinesPanel>
_MachineRow(
key: const ValueKey('add-machine'),
name: empty ? 'Add a second machine' : 'Add machine',
- icon: LucideIcons.plus,
+ icon: AppIcons.plus,
subtitle: empty
? const _MachineStatus('Run harnesses on another computer')
: null,
@@ -794,7 +794,7 @@ class _MachinesPanelState extends State<_MachinesPanel>
tooltip: _showSetup ? 'Hide setup steps' : 'Add a machine',
onPressed: toggle,
icon: Icon(
- _showSetup ? LucideIcons.chevronUp : LucideIcons.chevronRight,
+ _showSetup ? AppIcons.chevronUp : AppIcons.chevronRight,
semanticLabel: _showSetup ? 'Hide setup steps' : 'Add a machine',
size: 18,
),
@@ -877,7 +877,7 @@ class _MachinesPanelState extends State<_MachinesPanel>
tooltip: 'Close Machines',
onPressed: widget.onClose,
icon: Icon(
- LucideIcons.x,
+ AppIcons.close,
semanticLabel: 'Close Machines',
size: 18,
color: grid.AppPalette.textFaint,
@@ -979,7 +979,7 @@ class _MachineRow extends StatelessWidget {
required this.name,
this.local = false,
this.annotation,
- this.icon = LucideIcons.monitor,
+ this.icon = AppIcons.monitor,
this.subtitle,
this.action,
this.menuBuilder,
@@ -1017,7 +1017,7 @@ class _MachineRow extends StatelessWidget {
Row(
children: [
Icon(
- offline ? LucideIcons.monitorOff : icon,
+ offline ? AppIcons.monitorOff : icon,
size: 22,
semanticLabel: offline ? '$name: Offline' : null,
color: offline
@@ -1487,7 +1487,7 @@ class _MachinePasswordState extends State<_MachinePassword> {
tooltip: _obscure ? 'Show password' : 'Hide password',
onPressed: () => setState(() => _obscure = !_obscure),
icon: Icon(
- _obscure ? LucideIcons.eye : LucideIcons.eyeOff,
+ _obscure ? AppIcons.eye : AppIcons.eyeOff,
semanticLabel: _obscure
? 'Show password'
: 'Hide password',
@@ -1504,7 +1504,7 @@ class _MachinePasswordState extends State<_MachinePassword> {
isSelected: _showHelp,
onPressed: () => setState(() => _showHelp = !_showHelp),
icon: const Icon(
- LucideIcons.circleHelp,
+ AppIcons.circleHelp,
semanticLabel: 'Password help',
size: 15,
),
@@ -1704,10 +1704,10 @@ class _CopyButtonState extends State<_CopyButton> {
onPressed: _copy,
icon: Icon(
_message == 'Copied'
- ? LucideIcons.check
+ ? AppIcons.check
: _message == null
- ? LucideIcons.copy
- : LucideIcons.circleAlert,
+ ? AppIcons.copy
+ : AppIcons.circleAlert,
size: 16,
semanticLabel: _message ?? widget.label,
),
diff --git a/desktop/lib/widgets/model_picker_chrome.dart b/desktop/lib/widgets/model_picker_chrome.dart
index ad737bb92..1840ae398 100644
--- a/desktop/lib/widgets/model_picker_chrome.dart
+++ b/desktop/lib/widgets/model_picker_chrome.dart
@@ -1,21 +1,22 @@
/// The model picker's own furniture: the search field, the section headings, the rows and the
/// footer that closes the panel.
///
-/// Kept here rather than in `pane_menu.dart` because this is ONE menu's look, not the shape every
-/// pane menu shares. The find bar and the New Harness box draw their rows from `PaneMenuRow`, and
-/// a model picker that wanted an avatar, a second line and a quota meter would have dragged all of
-/// them somewhere they never asked to go.
+/// Model-specific content stays here; the surface and focusable actions share
+/// the desktop menu treatment in `pane_menu.dart`.
///
/// Everything here is presentation and nothing here decides: what a row means, whether it can be
/// chosen, and what happens when it is are all the picker's ([GridModelPicker]).
library;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/model_mark.dart';
-import '../shared/theme/app_type.dart';
+import '../shared/theme/app_theme.dart' as grid;
import '../theme/app_theme.dart';
+import 'desktop_chrome.dart';
+import 'pane_menu.dart';
import 'resting_section.dart' show kUnavailableOpacity;
/// The panel's own width. Narrower than a row list, because every row here is two lines and the
@@ -50,7 +51,7 @@ class ModelAvatar extends StatelessWidget {
alignment: Alignment.center,
decoration: BoxDecoration(
color: AppColors.surface,
- borderRadius: BorderRadius.circular(9),
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
),
child: child ?? ModelMark(model: label),
);
@@ -69,87 +70,67 @@ class ModelPickerSearch extends StatelessWidget {
final ValueChanged<String> onChanged;
@override
- Widget build(BuildContext context) => Container(
- height: 44,
- padding: const EdgeInsets.symmetric(horizontal: kModelPickerInset),
- decoration: BoxDecoration(
- color: AppColors.surface,
- borderRadius: BorderRadius.circular(10),
- border: Border.all(color: AppColors.border),
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Icon(Icons.search, size: 16, color: AppColors.mutedStrong),
- const SizedBox(width: 9),
- Expanded(
- // ⚠️ Arrow keys belong to the LIST, not to the text.
- //
- // A text field consumes up and down for cursor movement, and it is the first thing this
- // panel focuses so a person can type straight away — which left the rows unreachable
- // from the keyboard entirely: every arrow went into the field and Enter submitted
- // nothing. `Shortcuts` nearest the focused node wins over the editing shortcuts the app
- // installs at its root, so this is where that is taken back.
- child: Shortcuts(
- shortcuts: const <ShortcutActivator, Intent>{
- SingleActivator(LogicalKeyboardKey.arrowDown): NextFocusIntent(),
- SingleActivator(LogicalKeyboardKey.arrowUp):
- PreviousFocusIntent(),
- },
- // The nudge, and it is a nudge on purpose. The icon centres correctly in this row; the
- // text does not, because the decorator gives the field more height than the letters use
- // and hands the slack to the bottom. Several principled fixes were tried first — even
- // leading distribution, a pinned line height, sizing the box from its padding — and each
- // moved the number without closing the gap; the last one only made the box taller. What
- // is left is a measured offset, stated as one, rather than another theory dressed as a
- // layout rule. Half of it lands on the glyphs, which is why it is twice what the eye
- // asked for.
- child: Padding(
- padding: const EdgeInsets.only(top: 6),
- child: TextField(
- controller: controller,
- onChanged: onChanged,
- autofocus: true,
- // The LINE box centres correctly on its own; the glyphs inside it do not. The app's
- // sans face has a lopsided ascent and descent, and the default leading distribution
- // hands that asymmetry straight to the text — so the hint sat visibly high in a box a
- // widget test measures as perfectly centred, because a test measures the line box and
- // an eye sees the letters. Splitting the leading evenly is what puts them in the
- // middle of it.
- style: AppType.body(
- color: AppColors.text,
- ).copyWith(leadingDistribution: TextLeadingDistribution.even),
- textAlignVertical: TextAlignVertical.center,
- cursorColor: AppColors.text,
- decoration: InputDecoration(
- isCollapsed: true,
- // ⚠️ EVERY border state, and `filled: false`. The app's theme gives fields a 1.5px
- // accent `focusedBorder` and a fill of their own, and `border:` overrides neither —
- // so a field that autofocuses the moment the panel opens drew a second, brighter box
- // INSIDE the one around it. The box is this container's; the caret is the focus.
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- disabledBorder: InputBorder.none,
- errorBorder: InputBorder.none,
- focusedErrorBorder: InputBorder.none,
- filled: false,
- contentPadding: EdgeInsets.zero,
- hintText: 'Search models or machines',
- hintStyle: AppType.body(
- color: AppColors.muted,
- ).copyWith(leadingDistribution: TextLeadingDistribution.even),
- ),
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final highContrast = MediaQuery.highContrastOf(context);
+ final border = OutlineInputBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ borderSide: BorderSide(
+ color: highContrast
+ ? DesktopChrome.foreground.withValues(alpha: .55)
+ : DesktopChrome.rim,
+ ),
+ );
+ return ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: 40),
+ // The existing list-navigation shortcuts stay nearest the editor.
+ child: Shortcuts(
+ shortcuts: const <ShortcutActivator, Intent>{
+ SingleActivator(LogicalKeyboardKey.arrowDown): NextFocusIntent(),
+ SingleActivator(LogicalKeyboardKey.arrowUp): PreviousFocusIntent(),
+ },
+ child: TextField(
+ controller: controller,
+ onChanged: onChanged,
+ autofocus: true,
+ style: DesktopChrome.control(),
+ textAlignVertical: TextAlignVertical.center,
+ cursorColor: DesktopChrome.accent,
+ decoration: InputDecoration(
+ hintText: 'Search models or machines',
+ hintStyle: DesktopChrome.control(color: DesktopChrome.muted),
+ prefixIcon: Icon(
+ AppIcons.search,
+ size: 16,
+ color: DesktopChrome.muted,
+ ),
+ prefixIconConstraints: const BoxConstraints(
+ minWidth: 36,
+ minHeight: 36,
+ ),
+ isDense: true,
+ filled: true,
+ fillColor: DesktopChrome.field,
+ border: border,
+ enabledBorder: border,
+ focusedBorder: border.copyWith(
+ borderSide: BorderSide(
+ color: DesktopChrome.focusRing,
+ width: grid.AppDesktop.focusWidth,
),
),
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 10,
+ ),
),
),
- ],
- ),
- );
+ ),
+ );
+ }
}
-/// A section's heading: what the group is, in small caps, with how many rows are under it.
+/// A section's name and the number of visible models it contains.
///
/// The count is on the right and quiet. It answers "is the thing I want even here" before the eye
/// walks the list, which matters most in the section a search has just emptied.
@@ -163,7 +144,7 @@ class ModelPickerSectionHeader extends StatelessWidget {
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(
kModelPickerInset,
- 14,
+ 16,
kModelPickerInset,
8,
),
@@ -171,19 +152,13 @@ class ModelPickerSectionHeader extends StatelessWidget {
children: [
Expanded(
child: Text(
- label.toUpperCase(),
- style: AppType.body(color: AppColors.mutedStrong).copyWith(
- fontSize: 11,
- fontWeight: FontWeight.w700,
- letterSpacing: 0.9,
+ label,
+ style: DesktopChrome.metadata().copyWith(
+ fontWeight: FontWeight.w500,
),
),
),
- if (count != null)
- Text(
- '$count',
- style: AppType.body(color: AppColors.muted).copyWith(fontSize: 11),
- ),
+ if (count != null) Text('$count', style: DesktopChrome.metadata()),
],
),
);
@@ -236,118 +211,138 @@ class ModelPickerRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final row = Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- if (avatar != null) ...[
- dimmed
- ? Opacity(opacity: kUnavailableOpacity, child: avatar)
- : avatar!,
- const SizedBox(width: 11),
- ],
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.body(
- color: dimmed ? AppColors.muted : AppColors.text,
- ).copyWith(fontWeight: FontWeight.w600, fontSize: 13.5),
- ),
- if (subtitle.isNotEmpty) ...[
- const SizedBox(height: 2),
- Text(
- subtitle,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.mono(
- color: dimmed ? AppColors.muted : AppColors.mutedStrong,
+ grid.AppTheme.watch(context);
+ return PaneMenuAction(
+ onPressed: onTap,
+ selected: selected,
+ builder: (context, active) {
+ final row = Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ if (avatar != null) ...[
+ dimmed
+ ? Opacity(opacity: kUnavailableOpacity, child: avatar)
+ : avatar!,
+ const SizedBox(width: 11),
+ ],
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Tooltip(
+ message: title,
+ child: Text(
+ title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style:
+ DesktopChrome.control(
+ color: active
+ ? grid.AppDesktop.onSelection
+ : dimmed
+ ? DesktopChrome.muted
+ : DesktopChrome.foreground,
+ medium: true,
+ ).copyWith(
+ fontWeight: selected
+ ? FontWeight.w600
+ : FontWeight.w500,
+ ),
+ ),
),
+ if (subtitle.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(
+ subtitle,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(
+ color: active ? grid.AppDesktop.onSelection : null,
+ ),
+ ),
+ ],
+ if (hint != null) ...[
+ const SizedBox(height: 2),
+ // Two lines: "<computer> seems offline — its models come back when it does" is
+ // longer than a row is wide, and cut short it no longer says when.
+ Text(
+ hint!,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(
+ color: active ? grid.AppDesktop.onSelection : null,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ if (trailing != null) ...[
+ const SizedBox(width: 12),
+ // Capped, not flexed — see [kModelPickerTrailingMax]. The cap is also what keeps a quota
+ // column from overflowing the row at a large text size in a small window.
+ ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: kModelPickerTrailingMax,
),
- ],
- if (hint != null) ...[
- const SizedBox(height: 2),
- // Two lines: "<computer> seems offline — its models come back when it does" is
- // longer than a row is wide, and cut short it no longer says when.
- Text(
- hint!,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: AppType.body(color: AppColors.muted)
- .copyWith(fontSize: 11.5),
- ),
- ],
+ child: active
+ ? ColorFiltered(
+ colorFilter: const ColorFilter.mode(
+ grid.AppDesktop.onSelection,
+ BlendMode.srcIn,
+ ),
+ child: trailing!,
+ )
+ : trailing!,
+ ),
],
- ),
- ),
- if (trailing != null) ...[
- const SizedBox(width: 12),
- // Capped, not flexed — see [kModelPickerTrailingMax]. The cap is also what keeps a quota
- // column from overflowing the row at a large text size in a small window.
- ConstrainedBox(
- constraints: const BoxConstraints(
- maxWidth: kModelPickerTrailingMax,
- ),
- child: trailing!,
- ),
- ],
- ],
- );
- // No tick. The fill and its border are the mark, and a tick beside a quota figure crowded the
- // one thing on the row worth reading. A screen reader is told in words instead.
- return Semantics(
- selected: selected,
- child: MouseRegion(
- cursor: SystemMouseCursors.click,
- child: InkWell(
- onTap: onTap,
- mouseCursor: SystemMouseCursors.click,
- borderRadius: BorderRadius.circular(11),
- hoverColor: AppColors.rowHover,
- // Focus is a keyboard position, not a decision, and the panel focuses something the moment
- // it opens; painting it would light a row the person never pointed at.
- focusColor: Colors.transparent,
- splashColor: Colors.transparent,
- highlightColor: Colors.transparent,
- child: Container(
- padding: const EdgeInsets.symmetric(
- horizontal: kModelPickerInset,
- vertical: 9,
- ),
- decoration: BoxDecoration(
- color: selected ? AppColors.selected : null,
- borderRadius: BorderRadius.circular(11),
- border: selected
- ? Border.all(color: AppColors.accent.withValues(alpha: 0.45))
+ const SizedBox(width: 8),
+ SizedBox(
+ width: 16,
+ child: selected
+ ? Icon(
+ AppIcons.check,
+ size: 16,
+ color: active
+ ? grid.AppDesktop.onSelection
+ : DesktopChrome.foreground,
+ )
: null,
),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- row,
- if (meter != null) ...[
- const SizedBox(height: 9),
- ClipRRect(
- borderRadius: BorderRadius.circular(3),
- child: LinearProgressIndicator(
- value: meter!.clamp(0, 1),
- minHeight: 5,
- backgroundColor: AppColors.border,
- valueColor: AlwaysStoppedAnimation(
- note ?? AppColors.accent,
- ),
+ ],
+ );
+ return Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: kModelPickerInset,
+ vertical: 8,
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ row,
+ if (meter != null) ...[
+ const SizedBox(height: 8),
+ ClipRRect(
+ borderRadius: BorderRadius.circular(3),
+ child: LinearProgressIndicator(
+ value: meter!.clamp(0, 1),
+ minHeight: 5,
+ backgroundColor: active
+ ? grid.AppDesktop.onSelection.withValues(alpha: .2)
+ : AppColors.border,
+ valueColor: AlwaysStoppedAnimation(
+ active
+ ? grid.AppDesktop.onSelection
+ : note ?? AppColors.accent,
),
),
- ],
+ ),
],
- ),
+ ],
),
- ),
- ),
+ );
+ },
);
}
}
@@ -374,71 +369,43 @@ class ModelPickerFooter extends StatelessWidget {
decoration: BoxDecoration(
border: Border(top: BorderSide(color: AppColors.border)),
),
- child: Row(
- // ⚠️ Both halves Flexible and pushed apart, never Expanded + Flexible. That pair splits the
- // row down the middle and leaves the button at the START of its half, stranded short of
- // the right edge. Flexible still gives each half a fair share when a large text size means
- // they cannot both have everything they want.
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Flexible(
- child: Text(
- summary,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.body(color: AppColors.muted).copyWith(fontSize: 12),
- ),
- ),
- const SizedBox(width: 12),
- Flexible(
- child: MouseRegion(
- cursor: SystemMouseCursors.click,
- child: InkWell(
- onTap: onAction,
- mouseCursor: SystemMouseCursors.click,
- borderRadius: BorderRadius.circular(9),
- hoverColor: AppColors.rowHover,
- focusColor: Colors.transparent,
- splashColor: Colors.transparent,
- highlightColor: Colors.transparent,
- child: Container(
- padding: const EdgeInsets.symmetric(
- horizontal: 14,
- vertical: 9,
- ),
- decoration: BoxDecoration(
- color: AppColors.surface,
- borderRadius: BorderRadius.circular(9),
- border: Border.all(color: AppColors.border),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(
- Icons.grid_view_rounded,
- size: 15,
- color: AppColors.textSoft,
- ),
- const SizedBox(width: 8),
- // Flexible: at a large text size the summary and the action cannot both have
- // everything they want, and a fixed label overflowed a small window.
- Flexible(
- child: Text(
- actionLabel,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.body(
- color: AppColors.text,
- ).copyWith(fontSize: 12.5, fontWeight: FontWeight.w600),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- ],
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final count = Text(
+ summary,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ );
+ final action = DesktopPill(
+ label: actionLabel,
+ icon: AppIcons.layoutGrid,
+ onPressed: onAction,
+ tooltip: actionLabel,
+ );
+ // At larger text sizes the action needs its own line so its label stays
+ // readable. Both remain pinned while the model list scrolls above them.
+ if (constraints.maxWidth <
+ MediaQuery.textScalerOf(context).scale(300)) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ count,
+ const SizedBox(height: DesktopChrome.controlGap),
+ Align(alignment: Alignment.centerRight, child: action),
+ ],
+ );
+ }
+ // Flexible content pushed apart retains the shared left/right edges.
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Flexible(child: count),
+ const SizedBox(width: 12),
+ Flexible(child: action),
+ ],
+ );
+ },
),
);
}
diff --git a/desktop/lib/widgets/move_pane_palette.dart b/desktop/lib/widgets/move_pane_palette.dart
index bbd00d135..8237a7764 100644
--- a/desktop/lib/widgets/move_pane_palette.dart
+++ b/desktop/lib/widgets/move_pane_palette.dart
@@ -1,9 +1,11 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
+import 'desktop_chrome.dart';
/// ⇧⌘M — send the focused pane to another tab.
///
@@ -48,12 +50,12 @@ List<_Destination> _destinationsFor(AppNotifier notifier, String sourceId) => [
detail: switch (swarm.panes
.where((pane) => pane.agentId != null)
.length) {
- 0 => 'empty',
+ 0 => 'No harnesses',
1 => '1 harness',
final count => '$count harnesses',
},
),
- const _Destination(label: 'New Swarm', detail: 'a swarm of its own'),
+ const _Destination(label: 'New Tab', detail: 'Create a tab'),
];
class _MovePanePalette extends StatefulWidget {
@@ -77,6 +79,16 @@ class _MovePanePaletteState extends State<_MovePanePalette> {
/// arrow keys unheard. Same reason the layout palette keeps one.
final FocusNode _keys = FocusNode(debugLabel: 'move-pane-palette');
int _cursor = 0;
+ final _rows = <int, GlobalKey>{};
+
+ void _select(int index) {
+ setState(() => _cursor = index);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ final row = _rows[_cursor]?.currentContext;
+ if (row != null) Scrollable.ensureVisible(row);
+ });
+ }
@override
void initState() {
@@ -123,19 +135,17 @@ class _MovePanePaletteState extends State<_MovePanePalette> {
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.enter ||
- key == LogicalKeyboardKey.numpadEnter) {
+ key == LogicalKeyboardKey.numpadEnter ||
+ key == LogicalKeyboardKey.space) {
_take(destinations[_cursor.clamp(0, destinations.length - 1)]);
return KeyEventResult.handled;
}
- if (key == LogicalKeyboardKey.arrowDown || key == LogicalKeyboardKey.tab) {
- setState(() => _cursor = (_cursor + 1) % destinations.length);
+ if (key == LogicalKeyboardKey.arrowDown) {
+ _select((_cursor + 1) % destinations.length);
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.arrowUp) {
- setState(
- () =>
- _cursor = (_cursor - 1 + destinations.length) % destinations.length,
- );
+ _select((_cursor - 1 + destinations.length) % destinations.length);
return KeyEventResult.handled;
}
// ⌘1–⌘9 select a tab, so the same digits pick one here.
@@ -170,44 +180,51 @@ class _MovePanePaletteState extends State<_MovePanePalette> {
onKeyEvent: _onKey,
child: Dialog(
key: const ValueKey('move-pane-palette'),
- backgroundColor: grid.AppGlass.surfaceFill,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(13),
- side: BorderSide(color: grid.AppGlass.hair),
- ),
- child: SizedBox(
- width: 360,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- mainAxisSize: MainAxisSize.min,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 8),
- child: Text(
- 'Move pane to',
- style: grid.AppType.heading(
- color: grid.AppPalette.textPrimary,
- ),
+ insetPadding: const EdgeInsets.all(24),
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ child: DesktopDialogSurface(
+ child: SizedBox(
+ width: grid.AppDesktop.formWidth,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ DesktopDialogHeader(
+ title: 'Move Pane',
+ detail: 'Choose a destination tab.',
+ onClose: () => Navigator.of(context).pop(),
),
- ),
- for (var i = 0; i < destinations.length; i++)
- _Row(
- destination: destinations[i],
- index: i,
- selected: i == cursor,
- onTap: () => _take(destinations[i]),
- onHover: () => setState(() => _cursor = i),
+ Divider(height: 1, color: DesktopChrome.rim),
+ Flexible(
+ child: SingleChildScrollView(
+ child: Column(
+ children: [
+ for (var i = 0; i < destinations.length; i++)
+ KeyedSubtree(
+ key: _rows.putIfAbsent(i, GlobalKey.new),
+ child: _Row(
+ destination: destinations[i],
+ index: i,
+ selected: i == cursor,
+ onTap: () => _take(destinations[i]),
+ onHover: () => setState(() => _cursor = i),
+ ),
+ ),
+ ],
+ ),
+ ),
),
- Padding(
- padding: const EdgeInsets.fromLTRB(14, 8, 14, 12),
- child: Text(
- '↑↓ choose · ⏎ move · esc cancel',
- style: grid.AppType.monoMeta(
- color: grid.AppPalette.textFaint,
+ Divider(height: 1, color: DesktopChrome.rim),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 16, 24, 20),
+ child: Text(
+ '↑↓ Select · Return Move · Esc Cancel',
+ style: DesktopChrome.metadata(),
),
),
- ),
- ],
+ ],
+ ),
),
),
),
@@ -232,47 +249,72 @@ class _Row extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final ink = selected
- ? grid.AppPalette.textPrimary
- : grid.AppPalette.textSecondary;
- return MouseRegion(
- onEnter: (_) => onHover(),
- child: GestureDetector(
- onTap: onTap,
- behavior: HitTestBehavior.opaque,
- child: Container(
- key: ValueKey('move-pane-destination-$index'),
- margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 1),
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 7),
- decoration: BoxDecoration(
- color: selected ? grid.AppSurface.selectedFill : null,
- borderRadius: BorderRadius.circular(5),
- ),
- child: Row(
- children: [
- SizedBox(
- width: 18,
- child: Text(
- index < 9 ? '${index + 1}' : '',
- style: grid.AppType.monoMeta(
- color: grid.AppPalette.textFaint,
- ),
+ final ink = selected ? DesktopChrome.onSelection : DesktopChrome.foreground;
+ final muted = selected
+ ? DesktopChrome.selectionDetail
+ : DesktopChrome.muted;
+ return Semantics(
+ button: true,
+ selected: selected,
+ label: '${destination.label}, ${destination.detail}',
+ onTap: onTap,
+ child: ExcludeSemantics(
+ child: MouseRegion(
+ onEnter: (_) => onHover(),
+ cursor: SystemMouseCursors.click,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
+ child: InkWell(
+ onTap: onTap,
+ canRequestFocus: false,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ child: Container(
+ key: ValueKey('move-pane-destination-$index'),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 12,
),
- ),
- Expanded(
- child: Text(
- destination.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: grid.AppType.label(color: ink),
+ decoration: BoxDecoration(
+ color: selected ? DesktopChrome.activeSelection : null,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ ),
+ child: Row(
+ children: [
+ Icon(
+ destination.id == null
+ ? AppIcons.plus
+ : AppIcons.panelsTopLeft,
+ color: ink,
+ size: 18,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ destination.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.label(color: ink),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ destination.detail,
+ style: DesktopChrome.metadata(color: muted),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 12),
+ Text(
+ index < 9 ? '${index + 1}' : '',
+ style: grid.AppType.monoMeta(color: muted),
+ ),
+ ],
),
),
- const SizedBox(width: 8),
- Text(
- destination.detail,
- style: grid.AppType.monoMeta(color: grid.AppPalette.textFaint),
- ),
- ],
+ ),
),
),
),
diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dart
index 1856874b6..91922728b 100644
--- a/desktop/lib/widgets/new_agent_dialog.dart
+++ b/desktop/lib/widgets/new_agent_dialog.dart
@@ -1,10 +1,10 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../state/pane_arrangement.dart';
import '../core/desktop_window.dart';
@@ -1043,7 +1043,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
: () =>
Navigator.of(context)
.pop(NewAgentDialogResult.findExisting),
- icon: const Icon(LucideIcons.search, size: 16),
+ icon: const Icon(AppIcons.search, size: 16),
label: const Text('Find a harness'),
),
FilledButton(
@@ -1257,7 +1257,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
id: NewHarnessController.codingId,
label: 'Coding',
detail: 'Work in any code project',
- mark: (size) => Icon(LucideIcons.code, size: size),
+ mark: (size) => Icon(AppIcons.code, size: size),
),
for (final harness in _harnessOptions)
AgentChoice(
@@ -1602,7 +1602,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
padding: const EdgeInsets.only(right: 8),
child: AppIconButton(
key: const Key('new-agent-task-clear'),
- icon: LucideIcons.x300,
+ icon: AppIcons.close,
tooltip: 'Clear the task',
onPressed: _choicesLocked ? null : _task.clear,
),
@@ -1668,10 +1668,10 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
detail: mode.detail,
leading: () => Icon(
mode.risky
- ? LucideIcons.shieldOff
+ ? AppIcons.shieldOff
: mode.id == kDefaultPermissionMode
- ? LucideIcons.shieldCheck
- : LucideIcons.shield,
+ ? AppIcons.shieldCheck
+ : AppIcons.shield,
size: 16,
color: mode.risky
? grid.AppPalette.dangerFill
@@ -1727,7 +1727,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
value: _machineId,
moreKey: const Key('new-agent-machine-more'),
moreLabel: 'More machines',
- moreLeading: const Icon(LucideIcons.monitor, size: 22),
+ moreLeading: const Icon(AppIcons.monitor, size: 22),
optionKey: (id) => ValueKey('new-agent-machine-$id'),
showDetails: true,
compact: true,
@@ -1746,9 +1746,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
leading: () => Icon(
_machineOnline(machine)
? (machine.isLocalMachine
- ? LucideIcons.laptop
- : LucideIcons.monitor)
- : LucideIcons.monitorOff,
+ ? AppIcons.laptop
+ : AppIcons.monitor)
+ : AppIcons.monitorOff,
size: 22,
color: _machineOnline(machine)
? grid.AppPalette.textPrimary
diff --git a/desktop/lib/widgets/new_agent_project_picker.dart b/desktop/lib/widgets/new_agent_project_picker.dart
index 535ef721b..038f20675 100644
--- a/desktop/lib/widgets/new_agent_project_picker.dart
+++ b/desktop/lib/widgets/new_agent_project_picker.dart
@@ -1,8 +1,8 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:path/path.dart' as p;
import '../core/models.dart';
@@ -162,7 +162,7 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
value: entry.key,
label: entry.value,
detail: entry.key,
- leading: () => const Icon(LucideIcons.folder, size: 18),
+ leading: () => const Icon(AppIcons.folder, size: 18),
),
];
}
@@ -245,7 +245,7 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
? null
: projectFolderSlug(_name!),
leading: Icon(
- widget.terminal ? LucideIcons.house : LucideIcons.folderPlus,
+ widget.terminal ? AppIcons.house : AppIcons.folderPlus,
size: 22,
),
selected: _source == _ProjectSource.newProject,
@@ -262,7 +262,7 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
detail: _source == _ProjectSource.local && _folder != null
? p.basename(_folder!)
: null,
- leading: const Icon(LucideIcons.folderOpen, size: 22),
+ leading: const Icon(AppIcons.folderOpen, size: 22),
selected: _source == _ProjectSource.local,
onPressed: widget.locked || _browsing ? null : _browse,
),
@@ -273,7 +273,7 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
size: widget.tileSize,
label: 'Git',
detail: _repository?.name,
- leading: const Icon(LucideIcons.gitBranch, size: 22),
+ leading: const Icon(AppIcons.gitBranch, size: 22),
selected: _source == _ProjectSource.git,
onPressed: widget.locked ? null : _git,
),
@@ -316,8 +316,8 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
: null,
leading: widget.terminalStyle
? Text(selectedRecent ? '>' : ' ')
- : const Icon(LucideIcons.history, size: 22),
- trailing: const Icon(Icons.keyboard_arrow_down, size: 18),
+ : const Icon(AppIcons.history, size: 22),
+ trailing: const Icon(AppIcons.chevronDown, size: 18),
),
),
),
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index aa240b1e1..435f8ed18 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -1,8 +1,11 @@
import 'dart:async';
import 'dart:convert';
+import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import 'package:flutter_svg/flutter_svg.dart';
import 'package:xterm/xterm.dart' show TerminalTheme;
import '../shortcuts/app_keymap.dart';
@@ -16,10 +19,11 @@ import '../state/new_harness.dart';
import '../state/device_form.dart';
import 'box_chrome.dart' show kTerminalCornerRadius, terminalPaneBorder;
import 'dsh_install_panel.dart' show describeInstallFailure;
+import 'desktop_chrome.dart';
+import 'engine_identity.dart';
-/// Agent, Project, and collapsed Options in a compact terminal grid.
+/// Desktop composer and legacy terminal launch form sharing the same draft.
/// Enter on the selected launch action starts with the displayed defaults.
-/// Selecting a field reveals its chooser beside the centered form.
class NewHarnessForm extends StatefulWidget {
const NewHarnessForm({
super.key,
@@ -31,6 +35,9 @@ class NewHarnessForm extends StatefulWidget {
this.onLinkProfile,
this.onNeedsForm,
this.devicePort,
+ this.desktop = false,
+ this.embedded = false,
+ this.footer,
});
final NewHarnessController controller;
@@ -39,9 +46,14 @@ class NewHarnessForm extends StatefulWidget {
final FutureOr<void> Function()? onBrowse;
final VoidCallback? onStore, onLinkProfile, onNeedsForm;
final DeviceFormPort? devicePort;
+ final bool desktop;
+
+ /// The same composer can live in a tab, without a modal route or Close button.
+ final bool embedded;
+ final Widget? footer;
@override
- State<NewHarnessForm> createState() => _NewHarnessFormState();
+ State<NewHarnessForm> createState() => NewHarnessFormState();
}
enum _Row {
@@ -56,13 +68,46 @@ enum _Row {
start,
}
-class _NewHarnessFormState extends State<NewHarnessForm> {
+/// The workspace backdrop shares the form's dismissal hierarchy. A chooser
+/// consumes a dismissal before the composer (and its draft) can be dismissed.
+class NewHarnessFormState extends State<NewHarnessForm> {
NewHarnessController get box => widget.controller;
final _focus = FocusNode(debugLabel: 'new-harness-form');
final _inputFocus = FocusNode(debugLabel: 'new-harness-query');
final _queryText = TextEditingController();
+ late final _taskText = TextEditingController(text: box.task);
+ final _taskFocus = FocusNode(debugLabel: 'New harness task');
+ final _machineMenu = MenuController();
+ final _machineFocus = FocusNode(debugLabel: 'Repo machine');
+ bool get _desktopStartEnabled =>
+ !box.busy &&
+ !box.linkingProfile &&
+ box.requiredChoice == null &&
+ !box.taskTooLong;
+ FocusNode get _desktopDefaultFocus => box.takesTask
+ ? _taskFocus
+ : _desktopStartEnabled
+ ? _desktopFocus[_Row.start]!
+ : _focus;
+ final _dialogScope = FocusScopeNode(
+ debugLabel: 'New harness dialog',
+ traversalEdgeBehavior: TraversalEdgeBehavior.closedLoop,
+ );
+ final _desktopCanvasKey = GlobalKey();
+ final _desktopCloseAnchor = GlobalKey();
+ final _desktopAnchors = {for (final row in _Row.values) row: GlobalKey()};
+ final _desktopFocus = {
+ for (final row in _Row.values)
+ row: FocusNode(debugLabel: 'New harness ${row.name}'),
+ };
+ FocusNode? _chooserOrigin;
+ GlobalKey? _chooserAnchor;
+ bool _restoreChoiceFocus = false;
+ bool? _chooserTraversal;
+ bool _focusScheduled = false;
final _fieldsScroll = ScrollController();
final _choicesScroll = ScrollController();
+ final _desktopNoticesScroll = ScrollController();
_Row _row = _Row.start;
final _itemKeys = {for (final row in _Row.values) row: GlobalKey()};
final _choiceKey = GlobalKey();
@@ -78,7 +123,10 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
List<_Row> get _rows => [
for (final row in _Row.values)
- if ((!_advancedRows.contains(row) || box.advancedOpen) &&
+ if ((row != _Row.advanced || !widget.desktop) &&
+ (widget.desktop ||
+ !_advancedRows.contains(row) ||
+ box.advancedOpen) &&
(row != _Row.profile || box.usesProfile) &&
(row != _Row.model || !box.isTerminal) &&
(row != _Row.approvals || box.hasModes))
@@ -100,9 +148,10 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
terminalThemeStore.addListener(_onBox);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
+ box.useDesktopChoices(widget.desktop);
if (box.checking) _row = _Row.start;
_syncField();
- _focus.requestFocus();
+ (widget.desktop ? _desktopDefaultFocus : _focus).requestFocus();
});
}
@@ -113,8 +162,16 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
terminalThemeStore.removeListener(_onBox);
_inputFocus.dispose();
_queryText.dispose();
+ _taskText.dispose();
+ _taskFocus.dispose();
+ _machineFocus.dispose();
+ _dialogScope.dispose();
+ for (final node in _desktopFocus.values) {
+ node.dispose();
+ }
_fieldsScroll.dispose();
_choicesScroll.dispose();
+ _desktopNoticesScroll.dispose();
_focus.dispose();
super.dispose();
}
@@ -122,6 +179,12 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
NewHarnessField? _observedField;
void _onBox() {
if (!mounted) return;
+ if (_taskText.text != box.task) {
+ _taskText.value = TextEditingValue(
+ text: box.task,
+ selection: TextSelection.collapsed(offset: box.task.length),
+ );
+ }
if (_queryText.text != box.query) {
_queryText.value = TextEditingValue(
text: box.query,
@@ -145,7 +208,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
NewHarnessField.launch => _Row.start,
_ => _row,
};
- if (_advancedRows.contains(next) && !box.advancedOpen) {
+ final hidden = !widget.desktop && _advancedRows.contains(next);
+ if (hidden && !box.advancedOpen) {
box.toggleAdvanced();
}
if (next != _row) {
@@ -156,14 +220,80 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
}
if (_row == _Row.model && !_picking) _takeWheel();
setState(() {});
+ // A required choice or a pending launch disables Start. Keep Escape and
+ // keyboard recovery inside the dialog while its button rebuilds.
+ if (widget.desktop &&
+ _desktopFocus[_Row.start]!.hasFocus &&
+ !_desktopStartEnabled) {
+ _focusEditor();
+ }
_revealRow();
}
void _focusEditor() {
+ if (_focusScheduled) return;
+ _focusScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
+ _focusScheduled = false;
if (!mounted) return;
- (_picking ? _inputFocus : _focus).requestFocus();
+ if (_picking) {
+ if (!_machineMenu.isOpen && !_machineFocus.hasFocus) {
+ _inputFocus.requestFocus();
+ }
+ } else if (widget.desktop) {
+ final origin = _chooserOrigin;
+ if (_restoreChoiceFocus &&
+ origin?.context != null &&
+ origin!.canRequestFocus) {
+ origin.requestFocus();
+ if (_chooserTraversal case final forward?) {
+ forward ? origin.nextFocus() : origin.previousFocus();
+ }
+ } else {
+ _desktopDefaultFocus.requestFocus();
+ }
+ _restoreChoiceFocus = false;
+ _chooserTraversal = null;
+ } else {
+ _focus.requestFocus();
+ }
+ });
+ }
+
+ void dismissFromOutside() {
+ if (widget.desktop) {
+ if (_machineMenu.isOpen) {
+ _machineMenu.close();
+ } else if (_picking && !box.locked) {
+ _closeDesktopChooser();
+ } else if (!widget.embedded && box.requestDismiss()) {
+ widget.onClose();
+ }
+ } else {
+ _runCommand(_cancel);
+ }
+ }
+
+ /// Cmd-N on an empty tab returns to its existing draft rather than opening
+ /// a second composer with a second launch receipt.
+ void focusComposer() {
+ _closeDesktopChooser();
+ _restoreChoiceFocus = false;
+ }
+
+ void _closeDesktopChooser({bool? next}) {
+ _machineMenu.close();
+ _folderAction = null;
+ box.setQuery('');
+ box.focusField(NewHarnessField.launch);
+ setState(() {
+ _row = _Row.start;
+ _listOpen = false;
+ _hideChoices = true;
});
+ _restoreChoiceFocus = true;
+ _chooserTraversal = next;
+ _focusEditor();
}
/// The field a row edits, or null where the row is its own answer.
@@ -204,7 +334,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
String _label(_Row row) => switch (row) {
_Row.advanced => 'Options',
- _Row.project => 'Project',
+ _Row.project => widget.desktop ? 'Repo' : 'Project',
_Row.agent => box.harnessId == null ? 'Agent' : 'Harness',
_Row.model => 'Model',
_Row.branch => 'Branch',
@@ -396,13 +526,22 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_choicesScroll.hasClients &&
box.cursor >= 0 &&
box.cursor < box.options.length) {
- final top =
- List.generate(
- box.cursor,
- _choiceLines,
- ).fold<int>(0, (a, b) => a + b) *
- _rowHeight;
- final bottom = top + _choiceLines(box.cursor) * _rowHeight;
+ final top = widget.desktop
+ ? 6 +
+ List.generate(
+ box.cursor,
+ _desktopChoiceHeight,
+ ).fold<double>(0, (a, b) => a + b)
+ : List.generate(
+ box.cursor,
+ _choiceLines,
+ ).fold<int>(0, (a, b) => a + b) *
+ _rowHeight;
+ final bottom =
+ top +
+ (widget.desktop
+ ? _desktopChoiceHeight(box.cursor)
+ : _choiceLines(box.cursor) * _rowHeight);
final position = _choicesScroll.position;
if (top < position.pixels ||
bottom > position.pixels + position.viewportDimension) {
@@ -486,8 +625,24 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_revealRow();
}
- void _switchPane() {
+ void _switchPane({bool reverse = false}) {
if (box.locked) return;
+ if (widget.desktop &&
+ _picking &&
+ box.field == NewHarnessField.projectMenu) {
+ if (!reverse && _inputFocus.hasFocus) {
+ _machineFocus.requestFocus();
+ return;
+ }
+ if (reverse && _machineFocus.hasFocus) {
+ _inputFocus.requestFocus();
+ return;
+ }
+ }
+ if (widget.desktop && _picking) {
+ _closeDesktopChooser(next: !reverse);
+ return;
+ }
if (_picking) {
_backToRows();
} else if (_hasChoices) {
@@ -509,8 +664,11 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_blocked(_row) == null;
bool _isComposing() =>
- _queryText.value.composing.isValid &&
- !_queryText.value.composing.isCollapsed;
+ (_queryText.value.composing.isValid &&
+ !_queryText.value.composing.isCollapsed) ||
+ (_taskFocus.hasFocus &&
+ _taskText.value.composing.isValid &&
+ !_taskText.value.composing.isCollapsed);
/// Typing filters the focused field's choices; Return commits the selection.
void _onTyped(String value) {
@@ -578,7 +736,9 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
i >= 0 && i < box.options.length && covered < height;
i += direction
) {
- covered += _choiceLines(i) * _rowHeight;
+ covered += widget.desktop
+ ? _desktopChoiceHeight(i)
+ : _choiceLines(i) * _rowHeight;
count++;
}
box.page(direction, count);
@@ -605,6 +765,16 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
/// open a prompt or the system chooser instead of answering the row.
void _openDoor(NewHarnessOption option) {
if (box.locked || !option.enabled) return;
+ if (option.id == NewHarnessController.changeMachineId) {
+ // focusField(machine) remembers the prompt and its uncommitted query.
+ // Clearing first loses a typed name/path when Escape comes back here.
+ _chooseFolderMachine(switch (box.field) {
+ NewHarnessField.projectName => NewHarnessController.newProjectId,
+ NewHarnessField.projectRepository => NewHarnessController.repositoryId,
+ _ => NewHarnessController.existingProjectId,
+ }, preferLocal: false);
+ return;
+ }
box.setQuery('');
if (option.id == NewHarnessController.manageModelsId) {
unawaited(box.app.runLocalModel(context));
@@ -626,14 +796,6 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
unawaited(box.refreshProfiles());
return;
}
- if (option.id == NewHarnessController.changeMachineId) {
- _chooseFolderMachine(switch (box.field) {
- NewHarnessField.projectName => NewHarnessController.newProjectId,
- NewHarnessField.projectRepository => NewHarnessController.repositoryId,
- _ => NewHarnessController.existingProjectId,
- }, preferLocal: false);
- return;
- }
if (option.id == NewHarnessController.browseId) {
unawaited(_browse());
return;
@@ -643,6 +805,21 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
void _chooseFolderMachine(String action, {bool preferLocal = true}) {
_folderAction = action;
+ if (widget.desktop && preferLocal) {
+ // The selected machine already scopes the repo. Open its folder picker
+ // directly; typed folder paths remain available when no picker is wired.
+ box.focusField(switch (action) {
+ NewHarnessController.newProjectId => NewHarnessField.projectName,
+ NewHarnessController.repositoryId => NewHarnessField.projectRepository,
+ _ => NewHarnessField.project,
+ });
+ setState(() => _listOpen = true);
+ if (action == NewHarnessController.existingProjectId &&
+ widget.onBrowse != null) {
+ unawaited(_browse(direct: true));
+ }
+ return;
+ }
box.focusField(NewHarnessField.machine);
if (preferLocal) {
final local = box.options.indexWhere(
@@ -653,11 +830,13 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
setState(() => _listOpen = true);
}
- Future<void> _browse() async {
+ Future<void> _browse({bool direct = false}) async {
final machineId = box.machineId;
+ var failed = false;
try {
await widget.onBrowse?.call();
} on Exception {
+ failed = true;
if (mounted &&
box.machineId == machineId &&
box.field == NewHarnessField.project) {
@@ -665,7 +844,19 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
}
}
if (!mounted) return;
- if (box.field == NewHarnessField.launch) _selectRow(_Row.project);
+ if (direct && box.machineId == machineId && !failed) {
+ if (box.field == NewHarnessField.launch) {
+ _closeDesktopChooser();
+ return;
+ } else if (box.field == NewHarnessField.project) {
+ _folderAction = null;
+ box.focusField(NewHarnessField.projectMenu);
+ setState(() => _listOpen = true);
+ }
+ }
+ if (!direct && box.field == NewHarnessField.launch) {
+ _selectRow(_Row.project);
+ }
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _focusEditor();
});
@@ -676,6 +867,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
Future<void> _start() async {
if (box.busy) return;
+ _restoreChoiceFocus = false;
if (box.requiredChoice case final choice?) {
box.focusField(choice.field);
setState(() => _listOpen = true);
@@ -697,7 +889,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_focusEditor();
_revealRow();
} else {
- _focus.requestFocus();
+ _focusEditor();
}
}
}
@@ -712,9 +904,26 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_openDoor(option);
} else {
final field = box.field;
+ if (widget.desktop && field == NewHarnessField.machine) {
+ // The controller owns the originating prompt: names and repository
+ // URLs travel to another machine; paths only survive on the same one.
+ box.accept(option);
+ _focusEditor();
+ _revealRow();
+ return;
+ }
final prompt = _prompts.contains(box.field);
box.applyOption(option);
- if (box.error != null) return;
+ final taskWarning =
+ (field == NewHarnessField.harness ||
+ field == NewHarnessField.agent) &&
+ box.isTerminal &&
+ box.engine == option.id &&
+ box.compatibleEngines.contains(option.id) &&
+ box.task.trim().isNotEmpty
+ ? box.error
+ : null;
+ if (box.error != null && taskWarning == null) return;
box.setQuery('');
if (field == NewHarnessField.machine && _folderAction != null) {
box.focusField(switch (_folderAction) {
@@ -733,14 +942,27 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
box.focusField(NewHarnessField.harness);
}
_folderAction = null;
- _selectRow(_Row.start);
+ if (widget.desktop) {
+ _closeDesktopChooser();
+ } else {
+ _selectRow(_Row.start);
+ }
}
+ // Terminal was selected successfully. Keep the draft warning visible
+ // after returning to the composer, where Start still asks for consent.
+ if (taskWarning != null) box.warn(taskWarning);
}
_focusEditor();
_revealRow();
}
void _confirm() {
+ if (widget.desktop &&
+ _machineFocus.hasFocus &&
+ box.field == NewHarnessField.projectMenu) {
+ _machineMenu.open();
+ return;
+ }
// Return chooses a value in the list; only the start row launches.
if (_picking) {
final option = box.selected;
@@ -765,6 +987,14 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
}
void _cancel() {
+ if (widget.desktop && _machineMenu.isOpen) {
+ _machineMenu.close();
+ return;
+ }
+ if (widget.desktop && !_picking) {
+ if (!widget.embedded && box.requestDismiss()) widget.onClose();
+ return;
+ }
if (box.locked) {
if (box.requestDismiss()) widget.onClose();
return;
@@ -773,8 +1003,17 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
if (box.field == NewHarnessField.agent && _picking) {
box.focusField(NewHarnessField.harness);
setState(() => _listOpen = true);
+ } else if (widget.desktop && box.field == NewHarnessField.machine) {
+ box.back();
+ setState(() => _listOpen = true);
} else if (_prompts.contains(box.field) && _folderAction != null) {
- _chooseFolderMachine(_folderAction!, preferLocal: false);
+ if (widget.desktop) {
+ _folderAction = null;
+ box.focusField(NewHarnessField.projectMenu);
+ setState(() => _listOpen = true);
+ } else {
+ _chooseFolderMachine(_folderAction!, preferLocal: false);
+ }
} else if (_prompts.contains(box.field) ||
(box.field == NewHarnessField.machine && _folderAction != null)) {
_folderAction = null;
@@ -782,6 +1021,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
box.focusField(NewHarnessField.projectMenu);
_listOpen = true;
});
+ } else if (widget.desktop && _picking) {
+ _closeDesktopChooser();
} else if (_picking || (!_hideChoices && _hasChoices)) {
setState(() {
_listOpen = false;
@@ -800,7 +1041,90 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_revealRow();
}
+ void _runCreationCommand(VoidCallback action) {
+ if (box.locked) return;
+ _runCommand(action);
+ }
+
+ void _openCreationRow(_Row row) {
+ _machineMenu.close();
+ _folderAction = null;
+ // A direct shortcut enters the top-level chooser, even when another
+ // chooser currently owns a nested project or specialized-agent prompt.
+ box.focusField(
+ row == _Row.project
+ ? NewHarnessField.projectMenu
+ : NewHarnessField.harness,
+ );
+ _activateRow(row);
+ }
+
+ void _openMachineChooser() {
+ if (box.locked) return;
+ _folderAction = null;
+ _chooserOrigin = _desktopFocus[_Row.project];
+ _chooserAnchor = _desktopAnchors[_Row.project];
+ _restoreChoiceFocus = false;
+ if (box.field != NewHarnessField.projectMenu) _selectRow(_Row.project);
+ box.focusField(NewHarnessField.projectMenu);
+ setState(() => _listOpen = true);
+ _focusEditor();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && box.field == NewHarnessField.projectMenu && _picking) {
+ _machineFocus.requestFocus();
+ _machineMenu.open();
+ }
+ });
+ }
+
+ void _creationMachine() {
+ if (_picking && _prompts.contains(box.field)) {
+ _openDoor(
+ const NewHarnessOption(
+ id: NewHarnessController.changeMachineId,
+ title: 'Change Machine',
+ synthetic: true,
+ ),
+ );
+ } else {
+ _openMachineChooser();
+ }
+ }
+
+ void _creationProject(String action) {
+ _openCreationRow(_Row.project);
+ final option = box.options.where((item) => item.id == action).firstOrNull;
+ if (option != null) _openDoor(option);
+ }
+
+ void _creationBrowse() {
+ if (box.field != NewHarnessField.project) {
+ _creationProject(NewHarnessController.existingProjectId);
+ return;
+ }
+ _openDoor(
+ const NewHarnessOption(
+ id: NewHarnessController.browseId,
+ title: 'Browse Folder',
+ synthetic: true,
+ ),
+ );
+ }
+
+ void _creationTask() {
+ if (_picking) _closeDesktopChooser();
+ _restoreChoiceFocus = false;
+ _chooserTraversal = null;
+ _focusEditor();
+ }
+
+ List<NewHarnessOption> get _recentProjectChoices => box.options
+ .where((option) => !option.synthetic && option.project?.folder != null)
+ .toList();
+
KeyEventResult _onKey(FocusNode node, KeyEvent event) {
+ // The cascading menu owns its own arrow, Enter, and Escape handling.
+ if (_machineMenu.isOpen) return KeyEventResult.ignored;
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
@@ -809,9 +1133,65 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
event.logicalKey == LogicalKeyboardKey.numpadEnter)) {
return KeyEventResult.handled;
}
+ if (widget.desktop && !_picking) {
+ if (_isComposing()) return KeyEventResult.skipRemainingHandlers;
+ if (event.logicalKey == LogicalKeyboardKey.escape) {
+ if (event is KeyDownEvent) _cancel();
+ return KeyEventResult.handled;
+ }
+ if (_taskFocus.hasFocus &&
+ !HardwareKeyboard.instance.isShiftPressed &&
+ !HardwareKeyboard.instance.isMetaPressed &&
+ !HardwareKeyboard.instance.isControlPressed &&
+ !HardwareKeyboard.instance.isAltPressed &&
+ (event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter)) {
+ if (event is KeyDownEvent) unawaited(_start());
+ return KeyEventResult.handled;
+ }
+ if (KeymapTheme.of(context) == null &&
+ HardwareKeyboard.instance.isMetaPressed &&
+ event.logicalKey == LogicalKeyboardKey.enter) {
+ if (event is KeyDownEvent) unawaited(_start());
+ return KeyEventResult.handled;
+ }
+ if (_focus.hasPrimaryFocus &&
+ (event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter)) {
+ if (event is KeyDownEvent) unawaited(_start());
+ return KeyEventResult.handled;
+ }
+ // Shift-Enter belongs to the editor; native buttons own activation.
+ return KeyEventResult.ignored;
+ }
// Candidate navigation and confirmation belong to the input method. Keep
// these keys out of both the picker and ancestor focus-traversal shortcuts.
if (_isComposing()) return KeyEventResult.skipRemainingHandlers;
+ if (widget.desktop && box.field == NewHarnessField.projectMenu) {
+ if (_machineFocus.hasFocus) {
+ if (event.logicalKey == LogicalKeyboardKey.tab) {
+ if (HardwareKeyboard.instance.isShiftPressed) {
+ _inputFocus.requestFocus();
+ } else {
+ _closeDesktopChooser(next: true);
+ }
+ return KeyEventResult.handled;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter ||
+ event.logicalKey == LogicalKeyboardKey.arrowDown ||
+ event.logicalKey == LogicalKeyboardKey.arrowRight) {
+ _machineMenu.open();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.tab &&
+ !HardwareKeyboard.instance.isShiftPressed) {
+ _machineFocus.requestFocus();
+ return KeyEventResult.handled;
+ }
+ }
if (event.logicalKey == LogicalKeyboardKey.keyR &&
(HardwareKeyboard.instance.isMetaPressed ||
HardwareKeyboard.instance.isControlPressed) &&
@@ -920,7 +1300,9 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
TerminalTheme get _theme =>
terminalThemeFor(grid.AppTheme.palette.value, terminalThemeStore.value);
- Color get _faint => _theme.foreground.withValues(alpha: .54);
+ Color get _faint => widget.desktop
+ ? DesktopChrome.muted
+ : _theme.foreground.withValues(alpha: .54);
// Only the column that owns the keys carries Open Harness's full highlight.
Color get _activeFill => _theme.selection;
@@ -938,8 +1320,11 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
/// Its line height IS the row, so every line of every text on this form —
/// wrapped ones included — lands on the grid by itself. A two-line notice
/// is exactly two rows; nothing needs a box around it to stay in step.
- TextStyle _ink([Color? color]) =>
- terminalContentStyle(color: color ?? _theme.foreground);
+ TextStyle _ink([Color? color]) => widget.desktop
+ ? DesktopChrome.text(
+ color: color == _theme.foreground ? DesktopChrome.foreground : color,
+ )
+ : terminalContentStyle(color: color ?? _theme.foreground);
/// THE GRID. A terminal has two units and positions nothing in pixels:
///
@@ -957,6 +1342,11 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
double _rowHeight = 20;
void _measureGrid(BuildContext context) {
+ if (widget.desktop) {
+ _cell = 8;
+ _rowHeight = (MediaQuery.textScalerOf(context).scale(14) * 1.45 + 12);
+ return;
+ }
final cell = terminalCellSizeOf(context);
_cell = cell.width;
_rowHeight = cell.height;
@@ -1023,18 +1413,69 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
_revealRow();
}
_measureGrid(context);
+ final recentProjects =
+ widget.desktop && box.field == NewHarnessField.projectMenu
+ ? _recentProjectChoices
+ : const <NewHarnessOption>[];
final form = KeymapRegion(
- contextKind: KeymapContext.picker,
+ contextKind:
+ widget.desktop &&
+ _picking &&
+ (_projectFields.contains(box.field) ||
+ box.field == NewHarnessField.machine && _folderAction != null)
+ ? KeymapContext.project
+ : KeymapContext.picker,
composing: _isComposing,
actions: {
- 'picker.accept': () => _runCommand(_confirm),
+ if (widget.desktop) ...{
+ 'creation.agent': () =>
+ _runCreationCommand(() => _openCreationRow(_Row.agent)),
+ 'creation.project': () =>
+ _runCreationCommand(() => _openCreationRow(_Row.project)),
+ 'creation.project_machine': () =>
+ _runCreationCommand(_creationMachine),
+ 'creation.task': () => _runCreationCommand(_creationTask),
+ 'creation.options': () =>
+ _runCreationCommand(() => _activateRow(_Row.advanced)),
+ 'creation.project_new': () => _runCreationCommand(
+ () => _creationProject(NewHarnessController.newProjectId),
+ ),
+ 'creation.project_existing': () => _runCreationCommand(
+ () => _creationProject(NewHarnessController.existingProjectId),
+ ),
+ 'creation.project_repository': () => _runCreationCommand(
+ () => _creationProject(NewHarnessController.repositoryId),
+ ),
+ if (widget.onBrowse != null)
+ 'creation.project_browse': () =>
+ _runCreationCommand(_creationBrowse),
+ if (box.field == NewHarnessField.projectMenu)
+ for (
+ var index = 0;
+ index < recentProjects.length && index < 9;
+ index++
+ )
+ 'creation.project_recent_${index + 1}': () =>
+ _runCreationCommand(() {
+ final choices = _recentProjectChoices;
+ if (index < choices.length) _acceptChoice(choices[index]);
+ }),
+ },
+ if (widget.desktop)
+ 'picker.add_here': () {
+ if (!_isComposing() && !_picking) unawaited(_start());
+ },
+ if ((!widget.desktop || _picking) && !_machineMenu.isOpen) ...{
+ 'picker.accept': () => _runCommand(_confirm),
+ 'picker.next': () =>
+ _runCommand(() => _picking ? _stepMatch(1) : _moveRow(1)),
+ 'picker.previous': () =>
+ _runCommand(() => _picking ? _stepMatch(-1) : _moveRow(-1)),
+ 'picker.complete': () => _runCommand(_switchPane),
+ 'picker.complete_back': () =>
+ _runCommand(() => _switchPane(reverse: true)),
+ },
'picker.cancel': () => _runCommand(_cancel),
- 'picker.next': () =>
- _runCommand(() => _picking ? _stepMatch(1) : _moveRow(1)),
- 'picker.previous': () =>
- _runCommand(() => _picking ? _stepMatch(-1) : _moveRow(-1)),
- 'picker.complete': () => _runCommand(_switchPane),
- 'picker.complete_back': () => _runCommand(_switchPane),
'picker.more_options': () {
if (!box.locked) _toggleAdvanced();
},
@@ -1042,67 +1483,80 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
child: Focus(
key: const ValueKey('new-harness-form'),
focusNode: _focus,
+ skipTraversal: widget.desktop,
onKeyEvent: _onKey,
- child: LayoutBuilder(
- builder: (context, constraints) {
- final columns = (constraints.maxWidth / _cell).floor();
- final rows = (constraints.maxHeight / _rowHeight).floor();
- final mainColumns = columns.clamp(1, 56);
- final contentRows =
- _rows.length +
- 5 +
- (box.task.isNotEmpty ? 1 : 0) +
- _noticeRows(context, mainColumns);
- final mainRows = rows.clamp(1, contentRows);
- final left = (columns - mainColumns) ~/ 2;
- final top = (rows - mainRows) ~/ 2;
- final available = columns - left - mainColumns - 1;
- final beside = available >= 28;
- final showChoices = _hasChoices && (_picking || !_hideChoices);
- final pickerColumns = beside
- ? available.clamp(28, 40)
- : mainColumns;
- final notice = _picking ? box.error ?? box.status : null;
- final pickerRows = rows.clamp(
- 1,
- 16 +
- (notice == null
- ? 0
- : 1 + _textRows(context, notice, pickerColumns - 6)),
- );
- final pickerTop = top.clamp(0, rows - pickerRows);
- final replaceForm = _picking && !beside;
- return Stack(
- children: [
- Positioned(
- left: left * _cell,
- top: (replaceForm ? pickerTop : top) * _rowHeight,
- width: mainColumns * _cell,
- height: (replaceForm ? pickerRows : mainRows) * _rowHeight,
- child: _surface(
- const ValueKey('new-harness-surface'),
- _installing != null
- ? _installPane(_installing!)
- : replaceForm
- ? _sidePane()
- : _items(),
- ),
- ),
- if (showChoices && beside)
- Positioned(
- left: (left + mainColumns + 1) * _cell,
- top: pickerTop * _rowHeight,
- width: pickerColumns * _cell,
- height: pickerRows * _rowHeight,
- child: _surface(
- const ValueKey('new-harness-chooser-surface'),
- _sidePane(),
- ),
- ),
- ],
- );
- },
- ),
+ child: widget.desktop
+ ? Material(
+ type: MaterialType.transparency,
+ child: _desktopComposer(),
+ )
+ : LayoutBuilder(
+ builder: (context, constraints) {
+ final columns = (constraints.maxWidth / _cell).floor();
+ final rows = (constraints.maxHeight / _rowHeight).floor();
+ final mainColumns = columns.clamp(1, 56);
+ final contentRows =
+ _rows.length +
+ 5 +
+ (box.task.isNotEmpty ? 1 : 0) +
+ _noticeRows(context, mainColumns);
+ final mainRows = rows.clamp(1, contentRows);
+ final left = (columns - mainColumns) ~/ 2;
+ final top = (rows - mainRows) ~/ 2;
+ final available = columns - left - mainColumns - 1;
+ final beside = available >= 28;
+ final showChoices =
+ _hasChoices && (_picking || !_hideChoices);
+ final pickerColumns = beside
+ ? available.clamp(28, 40)
+ : mainColumns;
+ final notice = _picking ? box.error ?? box.status : null;
+ final pickerRows = rows.clamp(
+ 1,
+ 16 +
+ (notice == null
+ ? 0
+ : 1 +
+ _textRows(
+ context,
+ notice,
+ pickerColumns - 6,
+ )),
+ );
+ final pickerTop = top.clamp(0, rows - pickerRows);
+ final replaceForm = _picking && !beside;
+ return Stack(
+ children: [
+ Positioned(
+ left: left * _cell,
+ top: (replaceForm ? pickerTop : top) * _rowHeight,
+ width: mainColumns * _cell,
+ height:
+ (replaceForm ? pickerRows : mainRows) * _rowHeight,
+ child: _surface(
+ const ValueKey('new-harness-surface'),
+ _installing != null
+ ? _installPane(_installing!)
+ : replaceForm
+ ? _sidePane()
+ : _items(),
+ ),
+ ),
+ if (showChoices && beside)
+ Positioned(
+ left: (left + mainColumns + 1) * _cell,
+ top: pickerTop * _rowHeight,
+ width: pickerColumns * _cell,
+ height: pickerRows * _rowHeight,
+ child: _surface(
+ const ValueKey('new-harness-chooser-surface'),
+ _sidePane(),
+ ),
+ ),
+ ],
+ );
+ },
+ ),
),
);
return TextSelectionTheme(
@@ -1111,13 +1565,14 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
selectionColor: _theme.selection,
selectionHandleColor: _theme.cursor,
),
- child: form,
+ child: widget.desktop
+ ? FocusScope(node: _dialogScope, child: form)
+ : form,
);
}
Widget _surface(Key key, Widget child) => Material(
key: key,
- elevation: 0,
color: _theme.background,
surfaceTintColor: Colors.transparent,
shape: RoundedRectangleBorder(
@@ -1128,6 +1583,1128 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
child: DefaultTextStyle.merge(style: _ink(), child: child),
);
+ Widget _desktopComposer() => DesktopChrome(
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final choosing = _picking;
+ final anchor = _desktopChooserBounds(constraints);
+ final closeBounds = _desktopCloseBounds();
+ return Stack(
+ key: _desktopCanvasKey,
+ children: [
+ Align(
+ alignment: const Alignment(0, -.12),
+ child: SizedBox(
+ width: (constraints.maxWidth - (widget.embedded ? 48 : 0))
+ .clamp(0.0, 680.0),
+ child: ExcludeFocus(
+ excluding: choosing,
+ child: ExcludeSemantics(
+ excluding: choosing,
+ child: IgnorePointer(
+ ignoring: choosing,
+ child: Material(
+ key: const ValueKey('new-harness-surface'),
+ type: MaterialType.transparency,
+ child: Semantics(
+ label: 'New harness',
+ scopesRoute: !widget.embedded,
+ namesRoute: !widget.embedded,
+ explicitChildNodes: true,
+ child: FocusTraversalGroup(
+ policy: OrderedTraversalPolicy(),
+ child: SingleChildScrollView(
+ controller: _fieldsScroll,
+ padding: const EdgeInsets.symmetric(vertical: 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _desktopHeader(),
+ const SizedBox(height: 12),
+ if (_installing case final run?)
+ _desktopInstallPane(run)
+ else ...[
+ _desktopTaskEditor(),
+ const SizedBox(height: 6),
+ _desktopSettings(),
+ if (box.requiredChoice
+ case final required?) ...[
+ const SizedBox(height: 14),
+ Semantics(
+ liveRegion: true,
+ child: _desktopRequiredChoice(
+ required.field,
+ required.message,
+ ),
+ ),
+ ],
+ if (!choosing &&
+ (box.error != null ||
+ box.status != null) &&
+ box.error !=
+ box.requiredChoice?.message) ...[
+ const SizedBox(height: 12),
+ _status(),
+ ],
+ if (box.taskTooLong ||
+ !box.takesTask &&
+ box.task.isNotEmpty) ...[
+ const SizedBox(height: 12),
+ Text(
+ box.taskTooLong
+ ? 'Your message is too long.'
+ : 'Your task is kept when you switch agents.',
+ style: DesktopChrome.text(
+ size: 12,
+ color: box.taskTooLong
+ ? _theme.red
+ : DesktopChrome.muted,
+ ),
+ ),
+ ],
+ ],
+ if (widget.footer case final footer?) ...[
+ const SizedBox(height: 56),
+ footer,
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ if (choosing) ...[
+ Positioned.fill(
+ child: GestureDetector(
+ key: const ValueKey('new-harness-chooser-dismiss'),
+ behavior: HitTestBehavior.opaque,
+ onTap: () => _closeDesktopChooser(),
+ child: const ColoredBox(color: Colors.transparent),
+ ),
+ ),
+ Positioned.fromRect(
+ rect: anchor,
+ child: _desktopMachineAnchor(
+ child: DesktopDialogSurface(
+ radius: DesktopChrome.menuRadius,
+ key: const ValueKey('new-harness-chooser-surface'),
+ elevation: 8,
+ child: _desktopChooser(),
+ ),
+ ),
+ ),
+ // Keep the explicit Close action above the chooser's outside-tap
+ // surface, while the other composer controls remain inactive.
+ if (closeBounds != null)
+ Positioned.fromRect(
+ rect: closeBounds,
+ child: _desktopCloseButton(),
+ ),
+ ],
+ ],
+ );
+ },
+ ),
+ );
+
+ Widget _desktopRequiredChoice(NewHarnessField field, String message) {
+ final color = box.needsProject && box.error == null
+ ? DesktopChrome.muted
+ : Theme.of(context).colorScheme.error;
+ final text = Text(
+ field == NewHarnessField.machine
+ ? 'This machine is unavailable.'
+ : message,
+ style: DesktopChrome.text(size: 13, color: color),
+ textAlign: TextAlign.start,
+ );
+ if (field != NewHarnessField.machine) return text;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ text,
+ const SizedBox(height: 8),
+ FocusTraversalOrder(
+ order: const NumericFocusOrder(11),
+ child: TextButton.icon(
+ key: const ValueKey('new-harness-recover-machine'),
+ onPressed: box.locked ? null : _openMachineChooser,
+ icon: const Icon(AppIcons.chevronRight, size: 16),
+ iconAlignment: IconAlignment.end,
+ label: const Text('Choose a machine'),
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _desktopHeader() {
+ final folder = box.project.folder;
+ final projectName =
+ box.project.name ??
+ folder?.split(RegExp(r'[/\\]')).where((p) => p.isNotEmpty).lastOrNull ??
+ box.project.repository?.name ??
+ 'Choose repo';
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ _desktopField(
+ order: 1,
+ anchor: _desktopAnchors[_Row.agent]!,
+ child: _desktopChoiceButton(
+ _Row.agent,
+ AppIcons.code,
+ capsule: true,
+ ),
+ ),
+ _desktopField(
+ order: 3,
+ anchor: _desktopAnchors[_Row.project]!,
+ maxWidth: 340,
+ child: _desktopChoiceButton(
+ _Row.project,
+ AppIcons.folder,
+ label: box.app.stateOf(box.machineId)?.isLocalMachine == true
+ ? projectName
+ : '$projectName · ${box.machineLabel}',
+ capsule: true,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (!widget.embedded) ...[
+ const SizedBox(width: 8),
+ FocusTraversalOrder(
+ // Start remains last: Tab wraps to Agent and Shift-Tab reaches Close.
+ order: const NumericFocusOrder(9.9),
+ child: KeyedSubtree(
+ key: _desktopCloseAnchor,
+ child: Opacity(
+ opacity: _picking ? 0 : 1,
+ child: _desktopCloseButton(behindChooser: _picking),
+ ),
+ ),
+ ),
+ ],
+ ],
+ );
+ }
+
+ Rect? _desktopCloseBounds() {
+ final canvas = _desktopCanvasKey.currentContext?.findRenderObject();
+ final close = _desktopCloseAnchor.currentContext?.findRenderObject();
+ if (canvas is! RenderBox || close is! RenderBox || !close.hasSize) {
+ return null;
+ }
+ return close.localToGlobal(Offset.zero, ancestor: canvas) & close.size;
+ }
+
+ Widget _desktopCloseButton({bool behindChooser = false}) => IconButton(
+ key: ValueKey(
+ behindChooser ? 'new-harness-close-behind' : 'new-harness-close',
+ ),
+ tooltip: 'Close new harness',
+ mouseCursor: SystemMouseCursors.click,
+ onPressed: () {
+ if (box.requestDismiss()) widget.onClose();
+ },
+ icon: const Icon(AppIcons.close, size: 18),
+ visualDensity: VisualDensity.compact,
+ );
+
+ Widget _desktopTaskEditor() => ListenableBuilder(
+ listenable: _taskFocus,
+ builder: (context, _) => Material(
+ key: const ValueKey('new-harness-composer'),
+ color: DesktopChrome.field,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12),
+ side: BorderSide(
+ color: _taskFocus.hasFocus
+ ? DesktopChrome.focusRing
+ : DesktopChrome.rim,
+ ),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.all(14),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ FocusTraversalOrder(
+ order: const NumericFocusOrder(4),
+ child: TextField(
+ key: const ValueKey('new-harness-task'),
+ controller: _taskText,
+ focusNode: _taskFocus,
+ canRequestFocus: box.takesTask,
+ minLines: 2,
+ maxLines: 7,
+ textInputAction: TextInputAction.send,
+ readOnly: box.locked || !box.takesTask,
+ style: DesktopChrome.text(size: 15),
+ cursorColor: DesktopChrome.accent,
+ onChanged: box.setTask,
+ onSubmitted: (_) {
+ if (!_isComposing() && !_picking) unawaited(_start());
+ },
+ onTapOutside: (_) {},
+ decoration: InputDecoration(
+ hintText: box.takesTask
+ ? 'Harness anything'
+ : 'Open a terminal in this repo',
+ hintStyle: DesktopChrome.text(
+ size: 15,
+ color: DesktopChrome.muted,
+ ),
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ isCollapsed: true,
+ filled: false,
+ ),
+ ),
+ ),
+ const SizedBox(height: 12),
+ Align(
+ alignment: Alignment.centerRight,
+ child: _desktopStartButton(),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+
+ Widget _desktopSettings() => LayoutBuilder(
+ builder: (context, constraints) {
+ final controls = Wrap(
+ key: const ValueKey('new-harness-agent-settings'),
+ spacing: 2,
+ runSpacing: 4,
+ children: [
+ if (!box.isTerminal)
+ _desktopField(
+ order: 5,
+ anchor: _desktopAnchors[_Row.model]!,
+ child: _desktopChoiceButton(_Row.model, AppIcons.sparkles),
+ ),
+ if (box.hasModes)
+ _desktopField(
+ order: 6,
+ anchor: _desktopAnchors[_Row.approvals]!,
+ child: _desktopChoiceButton(_Row.approvals, AppIcons.shieldCheck),
+ ),
+ if (box.usesProfile)
+ _desktopField(
+ order: 7,
+ anchor: _desktopAnchors[_Row.profile]!,
+ child: _desktopChoiceButton(_Row.profile, AppIcons.user),
+ ),
+ ],
+ );
+ final gitControls = Row(
+ key: const ValueKey('new-harness-git-settings'),
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ if (box.canUseWorktree)
+ _desktopField(
+ order: 8,
+ anchor: _desktopAnchors[_Row.worktree]!,
+ child: SizedBox(
+ width: 100 * MediaQuery.textScalerOf(context).scale(1),
+ child: Semantics(
+ checked: box.worktree,
+ child: DesktopPill(
+ key: const ValueKey('new-harness-field-worktree'),
+ focusNode: _desktopFocus[_Row.worktree],
+ label: 'Worktree',
+ icon: box.worktree ? AppIcons.squareCheck : AppIcons.square,
+ semanticLabel:
+ 'New worktree, ${box.worktree ? 'on' : 'off'}',
+ quiet: true,
+ compact: true,
+ textSize: 12,
+ foregroundColor: DesktopChrome.muted,
+ tooltip: 'Create an isolated checkout for this harness',
+ onPressed: box.locked ? null : box.toggleWorktree,
+ ),
+ ),
+ ),
+ ),
+ if (box.isGitProject || box.checkingGit || box.gitError != null)
+ Flexible(
+ child: _desktopField(
+ order: 9,
+ anchor: _desktopAnchors[_Row.branch]!,
+ child: _desktopChoiceButton(
+ _Row.branch,
+ AppIcons.gitBranch,
+ label: box.branchRowLabel.split(' · ').first,
+ ),
+ ),
+ ),
+ ],
+ );
+ if (constraints.maxWidth <
+ 620 * MediaQuery.textScalerOf(context).scale(1)) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ controls,
+ if (!box.isTerminal) const SizedBox(height: 2),
+ gitControls,
+ ],
+ );
+ }
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(child: controls),
+ const SizedBox(width: 16),
+ SizedBox(width: constraints.maxWidth * .48, child: gitControls),
+ ],
+ );
+ },
+ );
+
+ Widget _desktopField({
+ required double order,
+ required GlobalKey anchor,
+ required Widget child,
+ double maxWidth = 280,
+ }) => FocusTraversalOrder(
+ order: NumericFocusOrder(order),
+ child: ConstrainedBox(
+ key: anchor,
+ constraints: BoxConstraints(maxWidth: maxWidth),
+ child: child,
+ ),
+ );
+
+ Widget _desktopChoiceButton(
+ _Row row,
+ IconData icon, {
+ String? label,
+ bool capsule = false,
+ }) => DesktopPill(
+ key: ValueKey('new-harness-field-${row.name}'),
+ focusNode: _desktopFocus[row],
+ label: label ?? _value(row),
+ semanticLabel: '${_label(row)}, ${_value(row)}',
+ icon: row == _Row.agent ? null : icon,
+ leading: row == _Row.agent
+ ? EngineMark(engine: box.harnessId ?? box.engine, size: 16)
+ : null,
+ menu: capsule,
+ capsule: capsule,
+ quiet: !capsule,
+ compact: !capsule,
+ textSize: capsule ? 13 : 12,
+ truncateFromStart: row == _Row.branch,
+ foregroundColor: capsule ? null : DesktopChrome.muted,
+ tooltip: _desktopChoiceTooltip(row),
+ onPressed: box.locked || _blocked(row) != null
+ ? null
+ : () => _activateRow(row),
+ );
+
+ String _desktopChoiceTooltip(_Row row) {
+ if (_blocked(row) case final reason?) return '${_label(row)}: $reason';
+ final action = switch (row) {
+ _Row.model => 'Choose model',
+ _Row.approvals => 'Choose approval mode',
+ _Row.profile => 'Choose Codex profile',
+ _ => _label(row),
+ };
+ return '$action: ${_value(row)}';
+ }
+
+ Widget _desktopStartButton() => ListenableBuilder(
+ listenable: _desktopFocus[_Row.start]!,
+ builder: (context, _) {
+ final label = box.busy
+ ? (_checkingLaunch ? 'Checking…' : 'Starting…')
+ : box.checking
+ ? 'Check status'
+ : 'New Harness';
+ return FocusTraversalOrder(
+ order: const NumericFocusOrder(10),
+ child: FilledButton(
+ key: const ValueKey('new-harness-field-start'),
+ focusNode: _desktopFocus[_Row.start],
+ onPressed: _desktopStartEnabled ? _start : null,
+ style:
+ FilledButton.styleFrom(
+ backgroundColor: grid.AppPalette.accent,
+ foregroundColor: Colors.white,
+ enabledMouseCursor: SystemMouseCursors.click,
+ disabledMouseCursor: SystemMouseCursors.basic,
+ minimumSize: const Size(90, 32),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 6,
+ ),
+ textStyle: DesktopChrome.text(size: 13, medium: true),
+ shape: const StadiumBorder(),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: grid.AppDesktop.focusWidth,
+ color: states.contains(WidgetState.focused)
+ ? Colors.white
+ : Colors.transparent,
+ ),
+ ),
+ backgroundColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? null
+ : states.contains(WidgetState.focused)
+ ? Color.alphaBlend(
+ Colors.white.withValues(alpha: .12),
+ grid.AppPalette.accent,
+ )
+ : grid.AppPalette.accent,
+ ),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (box.busy) ...[
+ const SizedBox(
+ width: 13,
+ height: 13,
+ child: CircularProgressIndicator(
+ strokeWidth: 1.5,
+ color: Colors.white,
+ ),
+ ),
+ const SizedBox(width: 8),
+ ],
+ Text(label),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+
+ Rect _desktopChooserBounds(BoxConstraints constraints) {
+ final preferredWidth = switch (box.field) {
+ NewHarnessField.harness || NewHarnessField.agent => 304.0,
+ NewHarnessField.model => 440.0,
+ // Keep room for the query beside its machine at enlarged text sizes.
+ // Fixed space covers both insets, icons, gaps, the capped machine pill,
+ // and refresh; measuring the labels also supports nonlinear text scaling.
+ NewHarnessField.projectMenu => math.max(
+ 400.0,
+ _desktopTextSize('Search repos', 14).width +
+ _desktopTextSize('in', 12).width +
+ 278,
+ ),
+ NewHarnessField.project => 400.0,
+ NewHarnessField.mode => 380.0,
+ NewHarnessField.profile => 320.0,
+ _ => 360.0,
+ };
+ final width = (constraints.maxWidth - 24).clamp(0.0, preferredWidth);
+ final maximum = (constraints.maxHeight - 24).clamp(0.0, 420.0);
+ // Include the search controls, its vertical padding, list padding, and rim.
+ // Refresh is taller than one text line, even when only two rows remain.
+ var contentHeight = _desktopSearchHeight + 20 + 2;
+ if (!_desktopRepositoryEntry) contentHeight += 12;
+ if (box.options.isEmpty && !_desktopRepositoryEntry) contentHeight += 48;
+ for (var i = 0; i < box.options.length && contentHeight < maximum; i++) {
+ contentHeight += _desktopChoiceHeight(i);
+ }
+ if (_desktopRepositoryEntry) {
+ if (box.error ?? box.status case final message?) {
+ final painter = TextPainter(
+ text: TextSpan(text: message, style: _ink()),
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ )..layout(maxWidth: (width - 26).clamp(1, double.infinity));
+ contentHeight += painter.height.ceilToDouble() + 16;
+ painter.dispose();
+ }
+ } else if (box.choicesStatus != null ||
+ box.modelNotice != null && _row == _Row.model ||
+ box.error != null ||
+ box.status != null) {
+ contentHeight = maximum;
+ }
+ final height = contentHeight.clamp(0.0, maximum);
+ final canvas = _desktopCanvasKey.currentContext?.findRenderObject();
+ final target = _chooserAnchor?.currentContext?.findRenderObject();
+ var left = (constraints.maxWidth - width) / 2;
+ var top = (constraints.maxHeight - height) / 2;
+ if (canvas is RenderBox &&
+ target is RenderBox &&
+ target.hasSize &&
+ canvas.hasSize) {
+ final origin = target.localToGlobal(Offset.zero, ancestor: canvas);
+ left = origin.dx.clamp(
+ 12.0,
+ (constraints.maxWidth - width - 12).clamp(12.0, double.infinity),
+ );
+ final below = origin.dy + target.size.height + 8;
+ if (below >= 12 && below + height <= constraints.maxHeight - 12) {
+ top = below;
+ } else if (origin.dy - height - 8 >= 12) {
+ top = origin.dy - height - 8;
+ }
+ }
+ return Rect.fromLTWH(left, top, width, height);
+ }
+
+ String get _desktopChooserTitle => switch (box.field) {
+ NewHarnessField.machine => 'Choose machine',
+ NewHarnessField.projectMenu => 'Choose repo',
+ NewHarnessField.project => 'Open folder',
+ NewHarnessField.projectName => 'New folder',
+ NewHarnessField.projectRepository => 'Clone repository',
+ NewHarnessField.agent => 'Run ${box.harnessLabel} with',
+ NewHarnessField.harness => 'Choose agent',
+ NewHarnessField.model => 'Choose model',
+ NewHarnessField.mode => 'Approvals',
+ NewHarnessField.profile => 'Codex profile',
+ NewHarnessField.branch => 'Choose branch',
+ _ => 'Choose an option',
+ };
+
+ bool get _desktopRepositoryEntry =>
+ box.field == NewHarnessField.projectRepository &&
+ box.options.isEmpty &&
+ !box.refreshingChoices;
+
+ Widget _desktopChooser() => Semantics(
+ key: const ValueKey('new-harness-choices'),
+ container: true,
+ explicitChildNodes: true,
+ focused: true,
+ label: _desktopChooserTitle,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ ListenableBuilder(
+ listenable: _inputFocus,
+ builder: (context, _) => DecoratedBox(
+ decoration: BoxDecoration(
+ border: Border(
+ bottom: BorderSide(
+ color:
+ _desktopRepositoryEntry &&
+ box.error == null &&
+ box.status == null
+ ? Colors.transparent
+ : _inputFocus.hasFocus
+ ? DesktopChrome.foreground.withValues(alpha: .24)
+ : DesktopChrome.rim,
+ ),
+ ),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
+ child: SizedBox(
+ height: _desktopSearchHeight,
+ child: _searchBar(),
+ ),
+ ),
+ ),
+ ),
+ Expanded(child: _desktopChooserContent()),
+ ],
+ ),
+ );
+
+ Widget _desktopChooserContent() => LayoutBuilder(
+ builder: (context, constraints) {
+ final notices = <Widget>[
+ if (box.choicesStatus case final status?)
+ Semantics(
+ liveRegion: true,
+ child: Text(status, style: DesktopChrome.metadata()),
+ ),
+ if (_row == _Row.model)
+ if (box.modelNotice case final notice?)
+ Text(notice, style: DesktopChrome.metadata()),
+ if (box.error != null || box.status != null) _status(),
+ ];
+ final feedback = Scrollbar(
+ controller: _desktopNoticesScroll,
+ thumbVisibility: true,
+ child: SingleChildScrollView(
+ key: const ValueKey('new-harness-chooser-notices'),
+ controller: _desktopNoticesScroll,
+ padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (var i = 0; i < notices.length; i++) ...[
+ if (i > 0) const SizedBox(height: 8),
+ notices[i],
+ ],
+ ],
+ ),
+ ),
+ );
+ if (_desktopRepositoryEntry) {
+ return notices.isEmpty ? const SizedBox.shrink() : feedback;
+ }
+ final choiceHeight = box.options.isEmpty
+ ? 0.0
+ : _desktopChoiceHeight(box.cursor.clamp(0, box.options.length - 1)) +
+ 12;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(
+ child: box.options.isEmpty && !box.refreshingChoices
+ ? Center(
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: Text(
+ switch (box.field) {
+ NewHarnessField.projectName =>
+ 'Create a folder in ~/harnesses.',
+ _ => 'No matches',
+ },
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ textAlign: TextAlign.center,
+ ),
+ ),
+ )
+ : Scrollbar(
+ controller: _choicesScroll,
+ child: ListView.builder(
+ controller: _choicesScroll,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6,
+ vertical: 6,
+ ),
+ itemCount: box.options.length,
+ itemExtentBuilder: (i, _) => _desktopChoiceHeight(i),
+ itemBuilder: (context, i) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (_headingBefore(i))
+ SizedBox(
+ height: _desktopGroupHeight,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8,
+ ),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ box.options[i].group!,
+ style: DesktopChrome.text(
+ size: 11,
+ color: DesktopChrome.muted,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ),
+ ),
+ if (_desktopRecentDivider(i))
+ Divider(height: 13, color: DesktopChrome.rim),
+ Expanded(child: _desktopOption(box.options[i])),
+ ],
+ ),
+ ),
+ ),
+ ),
+ if (notices.isNotEmpty)
+ ConstrainedBox(
+ // Search stays pinned. Keep the current choice fully visible
+ // when space permits, and every notice readable by scrolling.
+ constraints: BoxConstraints(
+ maxHeight: (constraints.maxHeight - choiceHeight)
+ .clamp(
+ constraints.maxHeight * .25,
+ constraints.maxHeight * .45,
+ )
+ .clamp(0.0, _desktopLineHeight('Notice', 14) * 3 + 16),
+ ),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ border: Border(top: BorderSide(color: DesktopChrome.rim)),
+ ),
+ child: feedback,
+ ),
+ ),
+ ],
+ );
+ },
+ );
+
+ Size _desktopTextSize(String text, double size) {
+ final painter = TextPainter(
+ text: TextSpan(
+ text: text,
+ style: DesktopChrome.text(size: size),
+ ),
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ maxLines: 1,
+ )..layout();
+ final dimensions = painter.size;
+ painter.dispose();
+ return dimensions;
+ }
+
+ double _desktopLineHeight(String text, double size) =>
+ _desktopTextSize(text, size).height.ceilToDouble();
+
+ double get _desktopGroupHeight => _desktopLineHeight('Ag', 11) + 12;
+ double get _desktopSearchHeight =>
+ _desktopLineHeight('Ag', 14).clamp(32.0, double.infinity);
+ bool _desktopRecentDivider(int i) =>
+ box.field == NewHarnessField.projectMenu &&
+ i > 0 &&
+ !box.options[i].synthetic &&
+ box.options[i - 1].synthetic;
+ double _desktopChoiceHeight(int i) =>
+ 16 +
+ _desktopLineHeight(_desktopOptionTitle(box.options[i]), 13) +
+ (_desktopOptionDetail(box.options[i]).isEmpty
+ ? 0
+ : 3 + _desktopLineHeight(_desktopOptionDetail(box.options[i]), 12)) +
+ (_headingBefore(i) ? _desktopGroupHeight : 0) +
+ (_desktopRecentDivider(i) ? 13 : 0);
+
+ bool _desktopOpensFolderPicker(NewHarnessOption option) =>
+ widget.onBrowse != null &&
+ (option.id == NewHarnessController.existingProjectId ||
+ option.id == NewHarnessController.browseId);
+
+ String _desktopOptionTitle(NewHarnessOption option) {
+ if (option.id == NewHarnessController.existingProjectId &&
+ widget.onBrowse != null) {
+ return 'Open Folder…';
+ }
+ final folder = option.project?.folder;
+ if (box.field == NewHarnessField.projectMenu && folder != null) {
+ return folder
+ .split(RegExp(r'[/\\]'))
+ .where((part) => part.isNotEmpty)
+ .lastOrNull ??
+ folder;
+ }
+ return option.title;
+ }
+
+ String _desktopOptionDetail(NewHarnessOption option) {
+ if (box.field == NewHarnessField.machine ||
+ box.field == NewHarnessField.harness ||
+ box.field == NewHarnessField.agent ||
+ _isDoor(option)) {
+ return '';
+ }
+ final machine = box.app
+ .stateOf(option.machineId ?? box.machineId)
+ ?.machine
+ .displayName;
+ if (machine != null && option.detail.startsWith('$machine:')) {
+ final path = option.detail.substring(machine.length + 1);
+ return option.machineId == null || option.machineId == box.machineId
+ ? path
+ : '$machine · $path';
+ }
+ return option.detail;
+ }
+
+ IconData _desktopOptionIcon(NewHarnessOption option) {
+ if (option.id == NewHarnessController.newProjectId) {
+ return AppIcons.plus;
+ }
+ if (option.id == NewHarnessController.browseId ||
+ option.id == NewHarnessController.existingProjectId) {
+ return AppIcons.folderOpen;
+ }
+ if (option.id == NewHarnessController.changeMachineId) {
+ return AppIcons.monitor;
+ }
+ if (option.id == NewHarnessController.refreshProfilesId ||
+ option.id == NewHarnessController.refreshModelsId) {
+ return AppIcons.refreshCw;
+ }
+ if (option.id == NewHarnessController.linkProfileId) {
+ return AppIcons.plus;
+ }
+ if (option.id == NewHarnessController.storeId) return AppIcons.layoutGrid;
+ return switch (box.field) {
+ NewHarnessField.branch => AppIcons.waypoints,
+ NewHarnessField.projectMenu ||
+ NewHarnessField.project ||
+ NewHarnessField.projectName => AppIcons.folder,
+ NewHarnessField.projectRepository => AppIcons.code,
+ NewHarnessField.model => AppIcons.sparkles,
+ NewHarnessField.profile => AppIcons.user,
+ NewHarnessField.mode => AppIcons.shieldCheck,
+ _ => AppIcons.code,
+ };
+ }
+
+ Widget _desktopOption(NewHarnessOption option) {
+ final title = _desktopOptionTitle(option);
+ final highlighted = identical(option, box.selected) && !_machineMenu.isOpen;
+ final ink = highlighted
+ ? DesktopChrome.onSelection
+ : DesktopChrome.foreground;
+ final muted = highlighted
+ ? DesktopChrome.selectionDetail
+ : DesktopChrome.muted;
+ final titleStyle = DesktopChrome.text(
+ size: 13,
+ color: option.enabled ? ink : muted,
+ );
+ final detail = _desktopOptionDetail(option);
+ final current = box.isCurrent(option) && !_isDoor(option);
+ final note = box.field == NewHarnessField.machine
+ ? _unlinked(option)
+ ? 'Not linked'
+ : box.app.stateOf(option.id)?.isOffline == true
+ ? 'Offline'
+ : null
+ : !option.enabled
+ ? option.why
+ : null;
+ return Semantics(
+ key: ValueKey('new-harness-option-${option.id}'),
+ selected: highlighted,
+ enabled: option.enabled && !box.locked,
+ button: true,
+ value: current ? 'Current selection' : null,
+ hint: _unlinked(option) ? 'Link required' : null,
+ child: Tooltip(
+ message: [
+ title,
+ if (detail.isNotEmpty) detail,
+ if (!option.enabled) option.why else ?note,
+ ].join('\n'),
+ child: Material(
+ color: highlighted
+ ? DesktopChrome.activeSelection
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ child: InkWell(
+ canRequestFocus: false,
+ mouseCursor: box.locked
+ ? SystemMouseCursors.basic
+ : SystemMouseCursors.click,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ hoverColor: DesktopChrome.foreground.withValues(alpha: .06),
+ splashFactory: NoSplash.splashFactory,
+ onTap: !box.locked ? () => _acceptChoice(option) : null,
+ child: Padding(
+ key: highlighted ? _choiceKey : null,
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
+ child: Row(
+ children: [
+ if (box.field != NewHarnessField.machine) ...[
+ if ((box.field == NewHarnessField.harness ||
+ box.field == NewHarnessField.agent) &&
+ !_isDoor(option))
+ EngineMark(
+ engine: option.engine ?? option.id,
+ size: 16,
+ enabled: option.enabled,
+ )
+ else if (option.id == NewHarnessController.repositoryId ||
+ box.field == NewHarnessField.projectRepository)
+ SvgPicture.asset(
+ 'assets/octicons/mark-github.svg',
+ width: 16,
+ height: 16,
+ colorFilter: ColorFilter.mode(muted, BlendMode.srcIn),
+ excludeFromSemantics: true,
+ )
+ else
+ Icon(
+ _desktopOptionIcon(option),
+ size: 16,
+ color: option.enabled
+ ? muted
+ : muted.withValues(alpha: .6),
+ ),
+ const SizedBox(width: 10),
+ ],
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ if (box.field == NewHarnessField.branch &&
+ !option.synthetic)
+ DesktopSuffixText(title, style: titleStyle)
+ else
+ Text(
+ title,
+ style: titleStyle,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ if (detail.isNotEmpty) ...[
+ const SizedBox(height: 3),
+ Text(
+ detail,
+ style: DesktopChrome.text(size: 12, color: muted),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
+ ],
+ ),
+ ),
+ if (note?.isNotEmpty == true) ...[
+ const SizedBox(width: 8),
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 95),
+ child: Text(
+ note!,
+ style: DesktopChrome.text(size: 11, color: muted),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ],
+ const SizedBox(width: 8),
+ SizedBox(
+ width: 16,
+ child: current
+ ? Icon(
+ AppIcons.check,
+ size: 16,
+ color: highlighted ? ink : DesktopChrome.accent,
+ )
+ : _isDoor(option) && !_desktopOpensFolderPicker(option)
+ ? Icon(AppIcons.chevronRight, size: 16, color: muted)
+ : null,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _desktopInstallPane(DshInstallRun run) => Semantics(
+ key: const ValueKey('new-harness-install'),
+ liveRegion: true,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ run.failed
+ ? '${box.harnessLabel} could not be installed'
+ : run.done
+ ? '${box.harnessLabel} is ready'
+ : 'Setting up ${box.harnessLabel}',
+ style: DesktopChrome.text(size: 16, medium: true),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ 'On ${box.machineLabel}',
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ ),
+ const SizedBox(height: 20),
+ for (final (phase, label) in [
+ ('clone', 'Download harness'),
+ ('setup', 'Set up tools'),
+ ('doctor', 'Check requirements'),
+ ])
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 7),
+ child: Row(
+ children: [
+ Icon(
+ run.done || (run.reached(phase) && run.phase != phase)
+ ? AppIcons.circleCheck
+ : run.failed
+ ? AppIcons.circleAlert
+ : AppIcons.circle,
+ size: 18,
+ color: run.failed ? _theme.red : DesktopChrome.accent,
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(label, style: DesktopChrome.text(size: 13)),
+ ),
+ if (run.took(phase) case final duration?)
+ Text(
+ _took(duration),
+ style: DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (run.failed) ...[
+ const SizedBox(height: 12),
+ Text(
+ describeInstallFailure(run, box.harnessLabel).title,
+ style: DesktopChrome.text(size: 13, color: _theme.red),
+ ),
+ if (describeInstallFailure(run, box.harnessLabel).body
+ case final body?)
+ Text(
+ body,
+ style: DesktopChrome.text(size: 13, color: DesktopChrome.muted),
+ ),
+ if (describeInstallFailure(run, box.harnessLabel).command
+ case final command?)
+ SelectableText(command, style: grid.AppType.mono()),
+ if (describeInstallFailure(run, box.harnessLabel).hint
+ case final hint?)
+ Text(
+ hint,
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ ),
+ ] else if (run.line ?? run.detail case final status?) ...[
+ const SizedBox(height: 12),
+ Text(
+ status,
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ ),
+ ],
+ const SizedBox(height: 20),
+ Row(
+ children: [
+ Expanded(
+ child: _Elapsed(
+ run: run,
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ ),
+ ),
+ _desktopStartButton(),
+ ],
+ ),
+ ],
+ ),
+ );
+
Widget _items() => Padding(
padding: EdgeInsets.fromLTRB(_margin, _rowHeight, _margin, _rowHeight),
child: Scrollbar(
@@ -1422,7 +2999,13 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
child: Text(
box.error ?? box.status!,
key: const ValueKey('new-harness-status'),
- style: _ink(box.error != null ? _theme.red : _faint),
+ style: _ink(
+ box.error != null
+ ? widget.desktop
+ ? Theme.of(context).colorScheme.error
+ : _theme.red
+ : _faint,
+ ),
),
);
@@ -1508,30 +3091,258 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
/// What the prompt is actually for. A path prompt is not a search — it
/// wants a folder typed at it — so it borrows the controller's own words
/// rather than calling everything "Search".
- String get _promptHint => box.field == NewHarnessField.agent
+ String get _promptHint => widget.desktop
+ ? switch (box.field) {
+ NewHarnessField.projectMenu => 'Search repos',
+ NewHarnessField.projectName => 'Enter project name',
+ NewHarnessField.projectRepository => 'Enter GitHub URL',
+ NewHarnessField.agent => 'Run ${box.harnessLabel} with',
+ NewHarnessField.mode => 'Search approvals',
+ NewHarnessField.profile => 'Search profiles',
+ _ => box.hint,
+ }
+ : box.field == NewHarnessField.agent
? 'Run ${box.harnessLabel} with'
: box.hint;
+ bool get _desktopNestedChooser =>
+ _prompts.contains(box.field) ||
+ box.field == NewHarnessField.agent ||
+ box.field == NewHarnessField.machine;
+
+ String _repoMachineLabel(String id) =>
+ box.app.stateOf(id)?.isLocalMachine == true
+ ? Theme.of(context).platform == TargetPlatform.macOS
+ ? 'This Mac'
+ : 'This computer'
+ : box.app.stateOf(id)?.machine.displayName ?? id;
+
+ void _selectRepoMachine(String id) {
+ if (box.locked) return;
+ // Recheck a live inventory: a machine can go offline with this menu open.
+ final choice = box.machineChoices.where((m) => m.id == id).firstOrNull;
+ if (choice == null || !choice.enabled) {
+ box.warn(choice?.why ?? 'This machine is no longer available.');
+ return;
+ }
+ box.focusField(NewHarnessField.machine);
+ box.accept(choice);
+ _inputFocus.requestFocus();
+ _focusEditor();
+ }
+
+ // Anchor to the whole repo popover so both top edges align and the child
+ // menu sits beyond its rim, rather than overlapping the search field.
+ Widget _desktopMachineAnchor({required Widget child}) => MenuAnchor(
+ controller: _machineMenu,
+ childFocusNode: _machineFocus,
+ consumeOutsideTap: true,
+ alignmentOffset: const Offset(8, 0),
+ onOpen: () => setState(() {}),
+ onClose: () {
+ if (mounted) setState(() {});
+ },
+ style: MenuStyle(
+ alignment: Alignment.topRight,
+ backgroundColor: WidgetStatePropertyAll(DesktopChrome.surface),
+ surfaceTintColor: const WidgetStatePropertyAll(Colors.transparent),
+ elevation: const WidgetStatePropertyAll(grid.AppMenu.elevation),
+ maximumSize: const WidgetStatePropertyAll(Size(264, 420)),
+ padding: const WidgetStatePropertyAll(EdgeInsets.all(6)),
+ shape: WidgetStatePropertyAll(
+ DesktopChrome.shape(radius: DesktopChrome.menuRadius),
+ ),
+ ),
+ menuChildren: [
+ for (final option in box.machineChoices)
+ MenuItemButton(
+ key: ValueKey('new-harness-machine-option-${option.id}'),
+ autofocus: option.id == box.machineId && option.enabled,
+ onPressed: option.enabled && !box.locked
+ ? () => _selectRepoMachine(option.id)
+ : null,
+ style:
+ MenuItemButton.styleFrom(
+ foregroundColor: DesktopChrome.foreground,
+ disabledForegroundColor: DesktopChrome.muted,
+ enabledMouseCursor: SystemMouseCursors.click,
+ disabledMouseCursor: SystemMouseCursors.basic,
+ side: BorderSide.none,
+ backgroundColor: option.id == box.machineId
+ ? DesktopChrome.selection
+ : Colors.transparent,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 8,
+ ),
+ textStyle: DesktopChrome.text(size: 13),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ ),
+ ).copyWith(
+ foregroundColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? DesktopChrome.muted
+ : states.contains(WidgetState.focused) ||
+ states.contains(WidgetState.hovered)
+ ? DesktopChrome.onSelection
+ : DesktopChrome.foreground,
+ ),
+ iconColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? DesktopChrome.muted
+ : states.contains(WidgetState.focused) ||
+ states.contains(WidgetState.hovered)
+ ? DesktopChrome.onSelection
+ : DesktopChrome.muted,
+ ),
+ backgroundColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? Colors.transparent
+ : states.contains(WidgetState.focused) ||
+ states.contains(WidgetState.hovered)
+ ? DesktopChrome.activeSelection
+ : option.id == box.machineId
+ ? DesktopChrome.selection
+ : Colors.transparent,
+ ),
+ ),
+ child: SizedBox(
+ width: 232,
+ child: Row(
+ children: [
+ Icon(
+ box.app.stateOf(option.id)?.isLocalMachine == true
+ ? AppIcons.laptop
+ : AppIcons.monitor,
+ size: 16,
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ _repoMachineLabel(option.id),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ if (!option.enabled ||
+ box.app.stateOf(option.id)?.isLocalMachine ==
+ true) ...[
+ const SizedBox(height: 3),
+ Text(
+ !option.enabled
+ ? box.app.stateOf(option.id)?.needsLink == true
+ ? 'Not linked'
+ : 'Offline'
+ : option.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.caption(height: 1.35),
+ ),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(width: 8),
+ SizedBox(
+ width: 16,
+ child: option.id == box.machineId
+ ? Icon(AppIcons.check, size: 16)
+ : null,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ child: child,
+ );
+
+ // Handle traversal before MenuAnchor's menu-bar shortcuts consume arrows.
+ Widget _repoMachinePicker() => Focus(
+ canRequestFocus: false,
+ onKeyEvent: _onKey,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 160),
+ child: DesktopPill(
+ key: const ValueKey('new-harness-repo-machine'),
+ focusNode: _machineFocus,
+ label: _repoMachineLabel(box.machineId),
+ semanticLabel: 'Machine, ${_repoMachineLabel(box.machineId)}',
+ tooltip: 'Machine: ${box.machineLabel}',
+ menu: true,
+ menuIcon: AppIcons.chevronRight,
+ compact: true,
+ quiet: true,
+ onPressed: box.locked
+ ? null
+ : () {
+ _machineFocus.requestFocus();
+ _machineMenu.isOpen
+ ? _machineMenu.close()
+ : _machineMenu.open();
+ },
+ ),
+ ),
+ );
+
Widget _searchBar() {
return Padding(
key: _searchKey,
- padding: EdgeInsets.symmetric(horizontal: _margin),
+ padding: EdgeInsets.symmetric(horizontal: widget.desktop ? 8 : _margin),
child: Row(
- crossAxisAlignment: CrossAxisAlignment.baseline,
+ crossAxisAlignment: widget.desktop
+ ? CrossAxisAlignment.center
+ : CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
SizedBox(
- width: _gutter,
- child: Text(
- '>',
- key: const ValueKey('new-harness-prompt'),
- textAlign: TextAlign.center,
- style: _ink(_picking ? _theme.foreground : _faint),
- ),
+ width: widget.desktop ? 32 : _gutter,
+ child: widget.desktop
+ ? _desktopNestedChooser
+ ? ExcludeFocus(
+ child: IconButton(
+ key: const ValueKey('new-harness-chooser-back'),
+ tooltip: 'Back',
+ mouseCursor: SystemMouseCursors.click,
+ padding: EdgeInsets.zero,
+ style: const ButtonStyle(
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ constraints: const BoxConstraints.tightFor(
+ width: 32,
+ height: 32,
+ ),
+ onPressed: box.locked
+ ? null
+ : () => _runCommand(_cancel),
+ icon: Icon(
+ AppIcons.chevronLeft,
+ size: 18,
+ color: _faint,
+ ),
+ ),
+ )
+ : Icon(AppIcons.search, size: 16, color: _faint)
+ : Text(
+ '>',
+ key: const ValueKey('new-harness-prompt'),
+ textAlign: TextAlign.center,
+ style: _ink(_picking ? _theme.foreground : _faint),
+ ),
),
+ if (widget.desktop) const SizedBox(width: 8),
Expanded(
child: Actions(
actions: {
+ DismissIntent: CallbackAction<DismissIntent>(
+ onInvoke: (_) {
+ _runCommand(_cancel);
+ return null;
+ },
+ ),
PasteTextIntent: CallbackAction<PasteTextIntent>(
onInvoke: (_) {
unawaited(_pasteQuery());
@@ -1546,7 +3357,9 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
readOnly: box.locked,
showCursor: _picking,
style: _ink(_theme.foreground),
- cursorColor: _theme.cursor,
+ cursorColor: widget.desktop
+ ? DesktopChrome.foreground
+ : _theme.cursor,
cursorWidth: 2,
cursorRadius: Radius.zero,
cursorOpacityAnimates: false,
@@ -1574,6 +3387,15 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
),
),
),
+ if (widget.desktop && box.field == NewHarnessField.projectMenu) ...[
+ const SizedBox(width: 8),
+ Text(
+ 'in',
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ ),
+ const SizedBox(width: 2),
+ _repoMachinePicker(),
+ ],
if (box.canRefreshChoices)
// Held to two cells by one row: a Material button's 48px tap
// target would make the prompt taller than every other line.
@@ -1582,8 +3404,20 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
child: InkWell(
key: const ValueKey('new-harness-refresh'),
canRequestFocus: false,
+ mouseCursor: box.refreshingChoices
+ ? SystemMouseCursors.basic
+ : SystemMouseCursors.click,
onTap: box.refreshingChoices ? null : box.refreshChoices,
- child: Text('[ Refresh ]', style: _ink(_faint)),
+ child: widget.desktop
+ ? Padding(
+ padding: const EdgeInsets.all(8),
+ child: Icon(
+ AppIcons.refreshCw,
+ size: 18,
+ color: _faint,
+ ),
+ )
+ : Text('[ Refresh ]', style: _ink(_faint)),
),
),
],
@@ -1728,6 +3562,11 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
}
void _activateRow(_Row row) {
+ if (widget.desktop) {
+ _chooserOrigin = _desktopFocus[row];
+ _chooserAnchor = _desktopAnchors[row];
+ _restoreChoiceFocus = false;
+ }
_selectRow(row);
if (row == _Row.advanced) {
_toggleAdvanced();
@@ -1742,6 +3581,17 @@ class _NewHarnessFormState extends State<NewHarnessForm> {
void _toggleAdvanced() {
if (box.locked) return;
+ if (widget.desktop) {
+ // Keep remapped Options commands useful after removing the disclosure.
+ _activateRow(
+ !box.isTerminal
+ ? _Row.model
+ : box.isGitProject
+ ? _Row.branch
+ : _Row.project,
+ );
+ return;
+ }
box.toggleAdvanced();
setState(() {
_row = _Row.advanced;
diff --git a/desktop/lib/widgets/new_harness_help.dart b/desktop/lib/widgets/new_harness_help.dart
index 64771486d..c7a04da7a 100644
--- a/desktop/lib/widgets/new_harness_help.dart
+++ b/desktop/lib/widgets/new_harness_help.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart';
import '../shared/widgets/app_dialog.dart';
@@ -116,11 +116,8 @@ class _HarnessHelpDialogState extends State<_HarnessHelpDialog> {
};
return Dialog(
key: ValueKey('harness-help-guide-${widget.topic.name}'),
- backgroundColor: AppPalette.swarmField,
- surfaceTintColor: Colors.transparent,
insetPadding: EdgeInsets.all(compact ? 16 : 24),
constraints: const BoxConstraints(maxWidth: 800, maxHeight: 920),
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
clipBehavior: Clip.antiAlias,
child: Column(
mainAxisSize: MainAxisSize.min,
@@ -141,7 +138,7 @@ class _HarnessHelpDialogState extends State<_HarnessHelpDialog> {
minimumSize: const Size(40, 40),
shape: const CircleBorder(),
),
- icon: const Icon(LucideIcons.x, size: 22),
+ icon: const Icon(AppIcons.close, size: 22),
),
),
),
@@ -223,14 +220,14 @@ class _HarnessHelpDialogState extends State<_HarnessHelpDialog> {
],
HarnessHelpTopic.machine => const [
_HelpOption(
- leading: Icon(LucideIcons.laptop, size: 28),
+ leading: Icon(AppIcons.laptop, size: 28),
title: 'This computer',
description:
'A good place to start. Work with the files and tools on the computer '
'you’re using, without setting up another machine.',
),
_HelpOption(
- leading: Icon(LucideIcons.monitor, size: 28),
+ leading: Icon(AppIcons.monitor, size: 28),
title: 'Remote machine',
description:
'Choose another linked computer when your project or tools are there. '
@@ -241,26 +238,26 @@ class _HarnessHelpDialogState extends State<_HarnessHelpDialog> {
],
HarnessHelpTopic.project => const [
_HelpOption(
- leading: Icon(LucideIcons.folderPlus, size: 28),
+ leading: Icon(AppIcons.folderPlus, size: 28),
title: 'New project',
description: 'Start fresh. Harness creates a new folder on your selected machine for your work.',
),
_HelpOption(
- leading: Icon(LucideIcons.folderOpen, size: 28),
+ leading: Icon(AppIcons.folderOpen, size: 28),
title: 'Existing folder',
description:
'Choose a folder that’s already on your selected machine. '
'Your new harness will work with the files in that folder.',
),
_HelpOption(
- leading: Icon(LucideIcons.gitBranch, size: 28),
+ leading: Icon(AppIcons.gitBranch, size: 28),
title: 'Git',
description:
'Bring a project from GitHub. Paste a repository link and Harness '
'clones it onto your selected machine before starting.',
),
_HelpOption(
- leading: Icon(LucideIcons.history, size: 28),
+ leading: Icon(AppIcons.history, size: 28),
title: 'Recent',
description:
'Quickly choose a project folder you’ve used on this machine before. '
diff --git a/desktop/lib/widgets/notification_inbox.dart b/desktop/lib/widgets/notification_inbox.dart
index 1150b12ac..f4647ac42 100644
--- a/desktop/lib/widgets/notification_inbox.dart
+++ b/desktop/lib/widgets/notification_inbox.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -9,12 +10,7 @@ import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
import '../state/harness_activity.dart';
import '../state/notification_inbox.dart';
-import '../terminal/terminal_text.dart';
-import '../terminal/terminal_theme.dart';
-import '../terminal/terminal_theme_store.dart';
-import 'box_chrome.dart';
-import 'harness_activity_mark.dart';
-import 'terminal_text_action.dart';
+import 'desktop_chrome.dart';
Future<void> showNotificationInbox(
BuildContext context, {
@@ -83,9 +79,9 @@ class _NotificationInboxState extends State<NotificationInbox> {
setState(() => _selected = _rows[index].id);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_scroll.hasClients) return;
- final line = terminalCellSizeOf(context).height;
- final top = line + index * line * 3;
- final bottom = top + line * 3;
+ final extent = _rowExtent;
+ final top = 8 + index * extent;
+ final bottom = top + extent;
final viewport = _scroll.position.viewportDimension;
final offset = top < _scroll.offset
? top
@@ -132,266 +128,318 @@ class _NotificationInboxState extends State<NotificationInbox> {
super.dispose();
}
+ double _lineHeight(TextStyle style) {
+ final painter = TextPainter(
+ text: TextSpan(text: 'Ag', style: style),
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ maxLines: 1,
+ )..layout();
+ final height = painter.height.ceilToDouble();
+ painter.dispose();
+ return height;
+ }
+
+ double get _rowExtent =>
+ _lineHeight(DesktopChrome.control(medium: true)) +
+ _lineHeight(DesktopChrome.metadata()) +
+ 28;
+
+ Color _statusColor(HarnessActivity activity) => switch (activity) {
+ HarnessActivity.needsInput ||
+ HarnessActivity.starting => grid.AppPalette.warn,
+ HarnessActivity.failed => Theme.of(context).colorScheme.error,
+ HarnessActivity.done => grid.AppPalette.online,
+ _ => DesktopChrome.muted,
+ };
+
+ KeyEventResult _onKey(FocusNode node, KeyEvent event) {
+ if (!node.hasPrimaryFocus ||
+ event is! KeyDownEvent ||
+ HardwareKeyboard.instance.isMetaPressed ||
+ HardwareKeyboard.instance.isControlPressed ||
+ HardwareKeyboard.instance.isAltPressed) {
+ return KeyEventResult.ignored;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.arrowDown ||
+ event.logicalKey == LogicalKeyboardKey.arrowUp) {
+ _move(event.logicalKey == LogicalKeyboardKey.arrowDown ? 1 : -1);
+ return KeyEventResult.handled;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter) {
+ final row = _rows.where((row) => row.id == _selected).firstOrNull;
+ if (row != null) unawaited(_open(row));
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
+
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
grid.AppTheme.watch(context);
- return ValueListenableBuilder(
- valueListenable: terminalThemeStore,
- builder: (context, _, _) {
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
- final cell = terminalCellSizeOf(context);
- final style = terminalContentStyle(color: theme.foreground);
- return LayoutBuilder(
- builder: (context, constraints) {
- final width = math.min(
- cell.width * 64,
- math.max(0.0, constraints.maxWidth - cell.width * 2),
- );
- final available = math.max(
- 0.0,
- constraints.maxHeight - widget.topInset - cell.height * 2,
- );
- final height = math.min(
- available,
- cell.height *
- (_rows.isEmpty
- ? 5
- : math.min(
- 23,
- 3 + _rows.length * 3 + (_error == null ? 0 : 2),
- )),
- );
- return Dialog(
- alignment: Alignment.topRight,
- insetPadding: EdgeInsets.fromLTRB(
- cell.width,
- widget.topInset + cell.height,
- cell.width,
- cell.height,
- ),
- backgroundColor: theme.background,
- elevation: 0,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(kTerminalCornerRadius),
- side: terminalPaneBorder(focused: true),
- ),
- child: SizedBox(
- key: const ValueKey('notification-inbox'),
- width: width,
- height: height,
- child: Focus(
- focusNode: _focus,
- autofocus: true,
- onKeyEvent: (node, event) {
- if (!node.hasPrimaryFocus ||
- event is! KeyDownEvent ||
- HardwareKeyboard.instance.isMetaPressed ||
- HardwareKeyboard.instance.isControlPressed ||
- HardwareKeyboard.instance.isAltPressed) {
- return KeyEventResult.ignored;
- }
- if (event.logicalKey == LogicalKeyboardKey.arrowDown ||
- event.logicalKey == LogicalKeyboardKey.arrowUp) {
- _move(
- event.logicalKey == LogicalKeyboardKey.arrowDown
- ? 1
- : -1,
- );
- return KeyEventResult.handled;
- }
- if (event.logicalKey == LogicalKeyboardKey.enter ||
- event.logicalKey == LogicalKeyboardKey.numpadEnter) {
- final row = _rows
- .where((row) => row.id == _selected)
- .firstOrNull;
- if (row != null) unawaited(_open(row));
- return KeyEventResult.handled;
- }
- return KeyEventResult.ignored;
- },
- child: DefaultTextStyle(
- style: style,
- child: Padding(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height,
- ),
- child: Column(
- children: [
- SizedBox(
- height: cell.height,
- child: Row(
- children: [
- Expanded(
+ return DesktopChrome(
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final width = math.min(
+ 440.0,
+ math.max(0.0, constraints.maxWidth - 32),
+ );
+ final available = math.max(
+ 0.0,
+ constraints.maxHeight - widget.topInset - 32,
+ );
+ return Dialog(
+ alignment: Alignment.topRight,
+ insetPadding: EdgeInsets.fromLTRB(16, widget.topInset + 16, 16, 16),
+ backgroundColor: Colors.transparent,
+ surfaceTintColor: Colors.transparent,
+ elevation: 0,
+ constraints: BoxConstraints(maxWidth: width),
+ child: SizedBox(
+ key: const ValueKey('notification-inbox'),
+ width: width,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: math.min(520, available),
+ ),
+ child: DesktopDialogSurface(
+ radius: 12,
+ elevation: 12,
+ child: Semantics(
+ scopesRoute: true,
+ namesRoute: true,
+ explicitChildNodes: true,
+ label: 'Notifications',
+ child: Focus(
+ focusNode: _focus,
+ autofocus: true,
+ onKeyEvent: _onKey,
+ child: ListenableBuilder(
+ listenable: _focus,
+ builder: (context, _) => Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _header(),
+ Divider(height: 1, color: DesktopChrome.rim),
+ Flexible(
+ child: _rows.isEmpty
+ ? Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 24,
+ vertical: 40,
+ ),
+ child: Text(
+ 'No notifications',
+ textAlign: TextAlign.center,
+ style: DesktopChrome.control(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ )
+ : ListView.builder(
+ controller: _scroll,
+ shrinkWrap: true,
+ itemCount: _rows.length,
+ padding: const EdgeInsets.all(8),
+ itemExtent: _rowExtent,
+ itemBuilder: (context, index) =>
+ _notificationRow(_rows[index]),
+ ),
+ ),
+ if (_error != null && _rows.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ 20,
+ 4,
+ 20,
+ 16,
+ ),
+ child: Semantics(
+ liveRegion: true,
child: Text(
- 'Notifications${_rows.isEmpty ? '' : ' ${_rows.length}'}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
+ _error!,
+ style: DesktopChrome.control(
+ color: Theme.of(context)
+ .colorScheme
+ .error,
+ ),
),
),
- TerminalTextAction(
- label: 'x',
- onPressed: () => Navigator.of(context).pop(),
- ),
- ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ );
+ }
+
+ Widget _header() => Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 12, 12),
+ child: Row(
+ children: [
+ Expanded(
+ child: Semantics(
+ header: true,
+ label: 'Notifications${_rows.isEmpty ? '' : ', ${_rows.length}'}',
+ excludeSemantics: true,
+ child: Row(
+ children: [
+ Flexible(
+ child: Text(
+ 'Notifications',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.heading(),
+ ),
+ ),
+ if (_rows.isNotEmpty) ...[
+ const SizedBox(width: 8),
+ Text('${_rows.length}', style: DesktopChrome.metadata()),
+ ],
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ IconButton(
+ key: const ValueKey('notification-inbox-close'),
+ tooltip: 'Close notifications',
+ onPressed: () => Navigator.of(context).pop(),
+ icon: const Icon(AppIcons.close, size: 18),
+ constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
+ padding: const EdgeInsets.all(6),
+ ),
+ ],
+ ),
+ );
+
+ Widget _notificationRow(InboxNotification row) {
+ final opening = row.id == _opening;
+ final activity = opening
+ ? HarnessActivity.starting
+ : switch (row.unavailable) {
+ null => row.activity,
+ 'Starting' => HarnessActivity.starting,
+ 'Start failed' => HarnessActivity.failed,
+ _ => HarnessActivity.offline,
+ };
+ final statusLabel = opening
+ ? 'Opening…'
+ : row.unavailable == null
+ ? row.label
+ : '${row.label} · ${row.unavailable}';
+ final onTap = row.unavailable == null && _opening == null
+ ? () => unawaited(_open(row))
+ : null;
+ final selected = row.id == _selected;
+ final focused = selected && _focus.hasPrimaryFocus;
+ return Semantics(
+ label: '${row.title}, $statusLabel, ${row.detail}',
+ button: true,
+ excludeSemantics: true,
+ enabled: onTap != null,
+ onTap: onTap,
+ selected: selected,
+ focused: focused,
+ child: MouseRegion(
+ cursor: onTap != null
+ ? SystemMouseCursors.click
+ : SystemMouseCursors.basic,
+ onEnter: (_) {
+ if (_opening == null) setState(() => _selected = row.id);
+ },
+ child: Material(
+ color: selected ? DesktopChrome.selection : Colors.transparent,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(8),
+ side: BorderSide(
+ width: 1.5,
+ color: focused ? DesktopChrome.accent : Colors.transparent,
+ ),
+ ),
+ child: InkWell(
+ key: ValueKey('notification:${row.id}'),
+ canRequestFocus: false,
+ onTap: onTap,
+ borderRadius: BorderRadius.circular(8),
+ hoverColor: DesktopChrome.foreground.withValues(alpha: .05),
+ highlightColor: DesktopChrome.foreground.withValues(alpha: .10),
+ splashFactory: NoSplash.splashFactory,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
+ child: Row(
+ children: [
+ Expanded(
+ child: Tooltip(
+ message: '${row.title}\n${row.detail}',
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ row.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(
+ medium: true,
+ color: row.unavailable == null
+ ? DesktopChrome.foreground
+ : DesktopChrome.muted,
),
),
- Expanded(
- child: _rows.isEmpty
- ? Center(
- child: Text(
- 'No notifications',
- style: style.copyWith(
- color: theme.foreground.withValues(
- alpha: .55,
- ),
- ),
- ),
- )
- : ListView.builder(
- controller: _scroll,
- itemCount: _rows.length,
- padding: EdgeInsets.only(top: cell.height),
- itemExtent: cell.height * 3,
- itemBuilder: (context, index) {
- final row = _rows[index];
- final opening = row.id == _opening;
- final activity = opening
- ? HarnessActivity.starting
- : switch (row.unavailable) {
- null => row.activity,
- 'Starting' =>
- HarnessActivity.starting,
- 'Start failed' =>
- HarnessActivity.failed,
- _ => HarnessActivity.offline,
- };
- final statusLabel = opening
- ? 'Opening…'
- : row.unavailable == null
- ? row.label
- : '${row.label} · ${row.unavailable}';
- final onTap =
- row.unavailable == null &&
- _opening == null
- ? () => unawaited(_open(row))
- : null;
- final selected = row.id == _selected;
- return Semantics(
- label:
- '${row.title}, ${row.label}, ${row.detail}${row.unavailable == null ? '' : ', ${row.unavailable}'}',
- button: true,
- excludeSemantics: true,
- enabled: onTap != null,
- onTap: onTap,
- selected: selected,
- child: MouseRegion(
- cursor: onTap != null
- ? SystemMouseCursors.click
- : SystemMouseCursors.basic,
- onEnter: (_) {
- if (_opening == null) {
- setState(
- () => _selected = row.id,
- );
- }
- },
- child: GestureDetector(
- key: ValueKey(
- 'notification:${row.id}',
- ),
- behavior: HitTestBehavior.opaque,
- onTap: onTap,
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.stretch,
- children: [
- ColoredBox(
- color: selected
- ? theme.selection
- : Colors.transparent,
- child: SizedBox(
- height: cell.height,
- child: Row(
- children: [
- Expanded(
- child: Text(
- row.title,
- maxLines: 1,
- overflow:
- TextOverflow
- .ellipsis,
- ),
- ),
- SizedBox(
- width: cell.width,
- ),
- Tooltip(
- message: statusLabel,
- child: SizedBox(
- width: cell.width,
- child: Text(
- activity.mark,
- textAlign:
- TextAlign
- .center,
- style: style.copyWith(
- color:
- activityColor(
- activity,
- theme,
- ),
- fontFamilyFallback: [
- ...?style
- .fontFamilyFallback,
- 'Apple Symbols',
- 'DejaVu Sans',
- ],
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- Text(
- row.detail,
- maxLines: 1,
- overflow:
- TextOverflow.ellipsis,
- style: style.copyWith(
- color: theme.foreground
- .withValues(alpha: .55),
- ),
- ),
- ],
- ),
- ),
- ),
- );
- },
- ),
+ const SizedBox(height: 4),
+ Text(
+ row.detail,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
),
- if (_error != null)
- Text(
- _error!,
- style: style.copyWith(color: theme.red),
- ),
],
),
),
),
- ),
+ const SizedBox(width: 12),
+ Tooltip(
+ message: statusLabel,
+ child: SizedBox(
+ width: math.max(
+ 20,
+ MediaQuery.textScalerOf(context).scale(16),
+ ),
+ child: Text(
+ activity.mark,
+ textAlign: TextAlign.center,
+ maxLines: 1,
+ style:
+ DesktopChrome.text(
+ size: 16,
+ medium: true,
+ color: _statusColor(activity),
+ ).copyWith(
+ fontFamilyFallback: [
+ ...?DesktopChrome.text().fontFamilyFallback,
+ 'Apple Symbols',
+ 'DejaVu Sans',
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
),
- );
- },
- );
- },
+ ),
+ ),
+ ),
+ ),
);
}
}
diff --git a/desktop/lib/widgets/onboarding_card.dart b/desktop/lib/widgets/onboarding_card.dart
index 0cf704951..9b83c1c46 100644
--- a/desktop/lib/widgets/onboarding_card.dart
+++ b/desktop/lib/widgets/onboarding_card.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart';
@@ -45,7 +46,7 @@ class OnboardingCard extends StatelessWidget {
tooltip: 'Dismiss suggestion',
onPressed: onDismiss,
visualDensity: VisualDensity.compact,
- icon: const Icon(Icons.close, size: 14),
+ icon: const Icon(AppIcons.close, size: 14),
),
],
),
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 0a76bc4ad..ffa1a6b3b 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -3,6 +3,7 @@ import '../sharing/shared_harness_panel.dart';
import 'dart:async';
import 'dart:typed_data';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart';
@@ -35,7 +36,8 @@ import 'terminal_panel.dart';
import 'harness_activity_mark.dart';
import 'web_pane_panel.dart';
import 'pane_resize_handle.dart';
-import 'box_chrome.dart';
+import 'box_chrome.dart' show kWorkspaceInset, terminalPaneBorder, PaneOpacity;
+import 'desktop_chrome.dart';
/// The view drawn alone when only one fits (a phone): the real zoom, else the
/// focused view, else the first before anything has focus.
@@ -50,6 +52,7 @@ class PaneGrid extends StatelessWidget {
required this.notifier,
this.swarmMode = false,
this.empty,
+ this.onOpenModels,
this.soloFocused = false,
this.companionViewer,
});
@@ -57,6 +60,8 @@ class PaneGrid extends StatelessWidget {
final AppNotifier notifier;
final bool swarmMode;
final Widget? empty;
+ final void Function(int paneId, String machineId, String agentId)?
+ onOpenModels;
/// Draw only the focused view, full size, as if zoomed — without zooming:
/// the tab's saved layout and zoom stay as they are (a phone shows one
@@ -77,6 +82,7 @@ class PaneGrid extends StatelessWidget {
notifier: notifier,
dragging: dragging,
empty: empty,
+ onOpenModels: onOpenModels,
soloFocused: soloFocused,
companionViewer: companionViewer,
);
@@ -93,6 +99,7 @@ class PaneGrid extends StatelessWidget {
dragging: dragging,
visible: visible,
swarmMode: swarmMode,
+ onOpenModels: onOpenModels,
companionViewer: companionViewer,
);
final cells = <Widget>[
@@ -240,12 +247,15 @@ class _SwarmCanvas extends StatefulWidget {
required this.notifier,
required this.dragging,
this.empty,
+ this.onOpenModels,
this.soloFocused = false,
this.companionViewer,
});
final AppNotifier notifier;
final AgentDragRef? dragging;
final Widget? empty;
+ final void Function(int paneId, String machineId, String agentId)?
+ onOpenModels;
final bool soloFocused;
final WidgetBuilder? companionViewer;
@override
@@ -583,6 +593,7 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
dragging: widget.dragging,
visible: rectangles.containsKey(pane.id),
swarmMode: true,
+ onOpenModels: widget.onOpenModels,
solo: widget.soloFocused,
companionViewer: widget.companionViewer,
),
@@ -628,40 +639,45 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
right: 24,
child: IgnorePointer(
child: Center(
- child: TerminalBox(
- key: const ValueKey('pane-resize-hint'),
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 12,
- vertical: 8,
- ),
- child: Wrap(
- spacing: 18,
- runSpacing: 6,
- children: [
- Text(
- 'resize >',
- style: boxMonoStyle(color: grid.AppPalette.swarmAccent),
- ),
- for (final (key, action) in const [
- ('arrows', 'resize'),
- ('shift', 'larger steps'),
- ('tab', 'next divider'),
- ('esc', 'done'),
- ])
- Text.rich(
- TextSpan(
- children: [
- TextSpan(
- text: '$key ',
- style: TextStyle(color: boxText(.70)),
- ),
- TextSpan(text: action),
- ],
- ),
- style: kBoxFaintStyle,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 760),
+ child: DesktopDialogSurface(
+ key: const ValueKey('pane-resize-hint'),
+ radius: DesktopChrome.menuRadius,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 16,
+ vertical: 12,
+ ),
+ child: Wrap(
+ spacing: 16,
+ runSpacing: 8,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ Text(
+ 'Resize panes',
+ style: DesktopChrome.control(medium: true),
),
- ],
+ for (final (key, action) in const [
+ ('Arrow keys', 'Adjust'),
+ ('Shift', 'Larger steps'),
+ ('Tab', 'Next divider'),
+ ('Esc', 'Done'),
+ ])
+ Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: '$key ',
+ style: DesktopChrome.control(medium: true),
+ ),
+ TextSpan(text: action),
+ ],
+ ),
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
),
),
),
@@ -1163,7 +1179,7 @@ class _Gap extends StatelessWidget {
/// How round a card's corners are — a pane, and the rail beside it. Public for the same reason
/// [kPaneGap] is: the rail is a card now, and two places typing 10 is how they drift apart.
-const double kPaneRadius = kTerminalCornerRadius;
+const double kPaneRadius = grid.AppDesktop.paneRadius;
/// How round a pane's corners are — the shared card radius, so a terminal does not read as a different
/// KIND of surface from the rail beside it.
@@ -1177,6 +1193,7 @@ class _PaneCell extends StatelessWidget {
required this.dragging,
this.visible = true,
this.swarmMode = false,
+ this.onOpenModels,
this.solo = false,
this.companionViewer,
});
@@ -1186,6 +1203,8 @@ class _PaneCell extends StatelessWidget {
final AgentDragRef? dragging;
final bool visible;
final bool swarmMode;
+ final void Function(int paneId, String machineId, String agentId)?
+ onOpenModels;
final WidgetBuilder? companionViewer;
/// Drawn alone under [PaneGrid.soloFocused]: it reads as the only view — no
@@ -1301,6 +1320,7 @@ class _PaneCell extends StatelessWidget {
single: _single,
visible: visible,
swarmMode: swarmMode,
+ onOpenModels: onOpenModels,
),
),
),
@@ -1320,6 +1340,7 @@ class _PaneContent extends StatelessWidget {
required this.single,
required this.visible,
required this.swarmMode,
+ this.onOpenModels,
});
final AppNotifier notifier;
@@ -1327,6 +1348,8 @@ class _PaneContent extends StatelessWidget {
final bool single;
final bool visible;
final bool swarmMode;
+ final void Function(int paneId, String machineId, String agentId)?
+ onOpenModels;
@override
Widget build(BuildContext context) {
@@ -1426,7 +1449,7 @@ class _PaneContent extends StatelessWidget {
if (machine == null) {
notice = terminalNotice(
label: 'Unavailable',
- icon: Icons.cloud_off,
+ icon: AppIcons.cloudOff,
detail: notifier.machineInventoryLoaded
? 'This machine isn’t available. Retained output is read only.'
: 'Waiting for this machine. Retained output is read only.',
@@ -1434,7 +1457,7 @@ class _PaneContent extends StatelessWidget {
} else if (needsLink) {
notice = terminalNotice(
label: 'Link required',
- icon: Icons.link_off,
+ icon: AppIcons.unlink,
detail:
'${machine.machine.displayName} needs linking. Retained output is read only.',
// A tile still showing its last screen gets the same way out as an
@@ -1449,14 +1472,14 @@ class _PaneContent extends StatelessWidget {
} else if (offline) {
notice = terminalNotice(
label: 'Offline',
- icon: Icons.cloud_off,
+ icon: AppIcons.cloudOff,
detail:
'${machine.machine.displayName} is offline. Retained output is read only.',
);
} else if (agent == null || !agent.terminalAvailable) {
notice = terminalNotice(
label: 'Unavailable',
- icon: Icons.terminal,
+ icon: AppIcons.terminal,
detail:
agent?.terminalUnavailableReason ??
'This harness is unavailable on ${machine.machine.displayName}. Retained output is read only.',
@@ -1472,7 +1495,7 @@ class _PaneContent extends StatelessWidget {
final unconfirmed = agent.launchError == 'RESUME_UNCONFIRMED';
notice = terminalNotice(
label: unconfirmed ? 'Not confirmed' : 'Start failed',
- icon: unconfirmed ? Icons.help_outline : Icons.error_outline,
+ icon: unconfirmed ? AppIcons.circleHelp : AppIcons.circleAlert,
detail: unconfirmed
? 'The engine is still running here; the daemon has not confirmed '
'which conversation it reopened.'
@@ -1517,6 +1540,10 @@ class _PaneContent extends StatelessWidget {
notice: notice,
onToggleComposer: () => notifier.toggleComposer(pane.id),
onClose: single && !swarmMode ? null : close,
+ onOpenModels: onOpenModels == null
+ ? null
+ : () =>
+ onOpenModels!(pane.id, session.machineId, session.agentId),
// The same confirmation the rail's row menu opens. Only for an
// agent the machine still lists — a pane whose agent is already
// gone has nothing to end.
@@ -1561,7 +1588,7 @@ class _PaneContent extends StatelessWidget {
return _PaneStatus(
activity: activityMark,
title: wantedAgentId == null ? 'Machine' : kUntitledPane,
- icon: listFailed || stale ? Icons.cloud_off : Icons.link_off,
+ icon: listFailed || stale ? AppIcons.cloudOff : AppIcons.unlink,
message: listFailed
? 'Could not load machines. Retry to reconnect.'
: waiting
@@ -1579,7 +1606,7 @@ class _PaneContent extends StatelessWidget {
return _PaneStatus(
activity: activityMark,
title: agentName ?? machine.machine.displayName,
- icon: Icons.link_off,
+ icon: AppIcons.unlink,
message:
'${machine.machine.displayName} is not linked to this computer yet. '
'Link it with the remote password set on that machine.',
@@ -1605,7 +1632,7 @@ class _PaneContent extends StatelessWidget {
compactMessage: machine.isLocalMachine
? 'Harness is not running on this computer.'
: 'Harness is not running on ${machine.machine.displayName}.',
- compactIcon: Icons.cloud_off,
+ compactIcon: AppIcons.cloudOff,
full: HarnessJoinGuideScreen(
notifier: notifier,
machineState: machine,
@@ -1617,7 +1644,7 @@ class _PaneContent extends StatelessWidget {
return _PaneStatus(
activity: activityMark,
title: machine.machine.displayName,
- icon: Icons.check_circle_outline,
+ icon: AppIcons.circleCheck,
message: 'This machine is ready. Drag a harness here to open it.',
onClose: close,
);
@@ -1626,7 +1653,7 @@ class _PaneContent extends StatelessWidget {
return _PaneStatus(
activity: activityMark,
title: wantedAgentId,
- icon: Icons.help_outline,
+ icon: AppIcons.circleHelp,
message: 'This harness is no longer on ${machine.machine.displayName}.',
onClose: close,
);
@@ -1635,7 +1662,7 @@ class _PaneContent extends StatelessWidget {
return _PaneStatus(
activity: activityMark,
title: agentName,
- icon: Icons.terminal,
+ icon: AppIcons.terminal,
message:
agent.terminalUnavailableReason ??
'This harness has no available terminal.',
@@ -1650,7 +1677,7 @@ class _PaneContent extends StatelessWidget {
return _PaneStatus(
activity: activityMark,
title: agentName,
- icon: Icons.terminal,
+ icon: AppIcons.terminal,
message:
'Open this harness here. Another screen may be using its terminal; '
'opening takes it, because ${machine.machine.displayName} runs an '
@@ -1665,7 +1692,7 @@ class _PaneContent extends StatelessWidget {
return _PaneStatus(
activity: activityMark,
title: agentName,
- icon: Icons.hourglass_empty,
+ icon: AppIcons.hourglass,
message: 'Attaching…',
onClose: single && !swarmMode ? null : close,
busy: true,
@@ -1750,7 +1777,10 @@ class _FileDropZoneState extends State<_FileDropZone> {
),
child: Text(
'Drop to attach',
- style: grid.AppType.label(color: AppColors.text),
+ style: grid.AppType.mono(
+ fontWeight: FontWeight.w500,
+ color: AppColors.text,
+ ),
),
),
),
@@ -1986,7 +2016,8 @@ class _SwapZone extends StatelessWidget {
),
child: Text(
'Swap with this pane',
- style: grid.AppType.label(
+ style: grid.AppType.mono(
+ fontWeight: FontWeight.w500,
color: AppColors.text,
),
),
@@ -2072,34 +2103,32 @@ class _PaneHeader extends StatelessWidget {
grid.AppTheme.watch(context);
// The pane's head is a drag handle too: with the title bar hidden it is
// the top edge of the window.
- return PaneHeaderHoverRegion(
- child: WindowDragArea(
- child: SizedBox(
- height: 46,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 14),
- child: Row(
- children: [
- Expanded(
- child: Row(
- children: [
- Flexible(
- child: Text(
- title,
- overflow: TextOverflow.ellipsis,
- style: grid.AppType.monoLabel(
- color: AppColors.text,
- fontWeight: FontWeight.w600,
- ),
+ return WindowDragArea(
+ child: SizedBox(
+ height: 46,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ child: Row(
+ children: [
+ Expanded(
+ child: Row(
+ children: [
+ Flexible(
+ child: Text(
+ title,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.monoLabel(
+ color: AppColors.text,
+ fontWeight: FontWeight.w600,
),
),
- ?activity,
- ],
- ),
+ ),
+ ?activity,
+ ],
),
- if (onClose != null) PaneCloseButton(onPressed: onClose!),
- ],
- ),
+ ),
+ if (onClose != null) PaneCloseButton(onPressed: onClose!),
+ ],
),
),
),
@@ -2235,7 +2264,10 @@ class _DropZone extends StatelessWidget {
paneId == null
? 'Open ${candidate.first?.name ?? 'harness'} here'
: 'Show ${candidate.first?.name ?? 'harness'} in this pane',
- style: grid.AppType.label(color: AppColors.text),
+ style: grid.AppType.mono(
+ fontWeight: FontWeight.w500,
+ color: AppColors.text,
+ ),
),
),
),
@@ -2263,7 +2295,7 @@ class _AddSlot extends StatelessWidget {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
- Icon(Icons.add, size: 24, color: AppColors.mutedStrong),
+ Icon(AppIcons.plus, size: 24, color: AppColors.mutedStrong),
const SizedBox(height: 8),
Text(
'Drop here for a new pane',
@@ -2335,7 +2367,7 @@ class _EmptyGrid extends StatelessWidget {
const SizedBox(height: 16),
FilledButton.icon(
key: const ValueKey('empty-grid-new-agent'),
- icon: const Icon(Icons.add, size: 16),
+ icon: const Icon(AppIcons.plus, size: 16),
label: const Text('New Harness'),
onPressed: () => showNewAgentDialog(
context,
diff --git a/desktop/lib/widgets/pane_header_actions.dart b/desktop/lib/widgets/pane_header_actions.dart
index 2c889920b..14e337a39 100644
--- a/desktop/lib/widgets/pane_header_actions.dart
+++ b/desktop/lib/widgets/pane_header_actions.dart
@@ -1,7 +1,7 @@
import 'package:flutter/widgets.dart';
/// Pane-local model selection and optional standalone terminal context.
-/// Closing, zooming, and stopping remain keyboard/menu commands.
+/// The pane keeps its fixed close target outside this flexible group.
class PaneHeaderActions extends StatelessWidget {
const PaneHeaderActions({
super.key,
diff --git a/desktop/lib/widgets/pane_menu.dart b/desktop/lib/widgets/pane_menu.dart
index ec58d4a13..0cd8a1e7c 100644
--- a/desktop/lib/widgets/pane_menu.dart
+++ b/desktop/lib/widgets/pane_menu.dart
@@ -6,18 +6,18 @@ import 'package:flutter/services.dart';
import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
-import 'box_chrome.dart';
+import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/app_type.dart';
import '../theme/app_theme.dart';
+import 'desktop_chrome.dart';
import 'engine_identity.dart';
import 'transient_menus.dart';
/// The pane header's menu, as one shape for every list that wants to look like it.
///
-/// Born in the model picker and shared from here so any second list that wants this shape is
-/// the same menu rather than a second drawing of it: the same overlay, the same rows, the same
-/// quiet fill on the current row instead of a tick.
+/// Model choices and Find options share desktop chrome without changing their
+/// pane's terminal styling or the overlay's interaction contract.
///
/// Shown in an OVERLAY rather than as a modal route. `showMenu` puts a full-screen modal barrier
/// under its menu, and that barrier EATS the click that dismisses it: closing the menu and then
@@ -88,9 +88,9 @@ Future<T?> showPaneMenu<T>({
// column. A BODY does neither: it is handed the menu's box and lays itself out, which
// is what a panel with something pinned above and below a scrolling middle needs.
child: body != null
- ? TerminalBox(child: body(close))
+ ? _PaneMenuSurface(child: body(close))
: IntrinsicWidth(
- child: TerminalBox(
+ child: _PaneMenuSurface(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
@@ -113,6 +113,37 @@ Future<T?> showPaneMenu<T>({
return completer.future;
}
+class _PaneMenuSurface extends StatelessWidget {
+ const _PaneMenuSurface({required this.child});
+
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final highContrast = MediaQuery.highContrastOf(context);
+ return Material(
+ key: const ValueKey('pane-menu-surface'),
+ color: grid.AppMenu.fill,
+ surfaceTintColor: Colors.transparent,
+ elevation: grid.AppMenu.elevation,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(grid.AppMenu.panelRadius),
+ side: BorderSide(
+ color: highContrast
+ ? DesktopChrome.foreground.withValues(alpha: .55)
+ : grid.AppMenu.rim,
+ ),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: DefaultTextStyle.merge(
+ style: DesktopChrome.control(),
+ child: child,
+ ),
+ );
+ }
+}
+
/// Position against the actual overlay, including panes beside the left edge
/// and short windows. Long model catalogs scroll inside the available height.
class _PaneMenuPosition extends SingleChildLayoutDelegate {
@@ -203,60 +234,100 @@ class _PaneMenuFocusState extends State<_PaneMenuFocus> {
node: _scope,
autofocus: true,
onKeyEvent: _key,
- child: FocusTraversalGroup(child: widget.child),
+ // Scrolling can move rows above a pinned search field. Keep keyboard
+ // order tied to the list, not those temporary screen coordinates.
+ child: FocusTraversalGroup(
+ policy: WidgetOrderTraversalPolicy(),
+ child: widget.child,
+ ),
),
);
}
}
-/// One selectable row of a pane menu.
-///
-/// The hover is the SAME rectangle as the selected fill — inset by [kPaneMenuInset] and rounded
-/// the same — so a row looks like one thing whether the pointer is on it or the choice is. An
-/// InkWell around the whole item painted edge to edge and square, over a selected fill that was
-/// neither, and the two reading as different shapes made the current row look like the odd one
-/// out.
-///
-/// Same SHAPE, one fill. The fill belongs to the CHOSEN row and to nothing else: focus paints
-/// none at all (it is a keyboard position, not a decision) and hover paints the weaker
-/// [AppColors.rowHover], which moves with the pointer and so can never be mistaken for where the
-/// agent is. A tick was tried and taken out again — the fill is the whole signal, and a second one
-/// beside it was a column every row paid for.
-/// ⚠️ The cursor is STATED, in both places that can answer for it. A pane menu is drawn in an
-/// overlay above a terminal, and what a person sees while hovering a row was whatever the surface
-/// underneath asked for — an arrow over rows that are the whole point of the menu. `InkWell` carries
-/// a clickable cursor of its own in principle, and in this app it was not what reached the screen;
-/// the control that OPENS this menu needed both annotations before a hand appeared, and these rows
-/// need the same. The cursor a person sees is the innermost annotation under the pointer, so the
-/// MouseRegion covers the row and the InkWell answers for its own ink.
-Widget paneMenuItem({required VoidCallback onTap, required Widget child}) =>
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: kPaneMenuInset),
- child: MouseRegion(
- cursor: SystemMouseCursors.click,
- child: InkWell(
- onTap: onTap,
- mouseCursor: SystemMouseCursors.click,
- borderRadius: BorderRadius.circular(kPaneMenuRowRadius),
- // ⚠️ STATED, all three. Left to the Material default the hover landed close enough to
- // the selected fill to be indistinguishable, so the row under the pointer and the row
- // the agent is actually on looked equally chosen — two highlights, one menu. The
- // palette has always had a weaker tone for exactly this ([AppColors.rowHover]); the
- // menu simply never asked for it. Splash and highlight go transparent because an ink
- // ripple is a THIRD fill on the same rectangle, and it lingers after the tap.
- hoverColor: AppColors.rowHover,
- splashColor: Colors.transparent,
- highlightColor: Colors.transparent,
- // ⚠️ The one that actually put two highlights on screen. The menu moves focus to its
- // FIRST row as it opens (`_PaneMenuFocus`, so Enter activates something), and an InkWell
- // paints focus with a fill of its own — so the top row was lit before the pointer moved
- // and the agent's real row was lit too. Focus is a keyboard position, not a choice; only
- // the chosen row is filled.
- focusColor: Colors.transparent,
- child: child,
- ),
- ),
+/// One inset action in the compact menu. Its child owns the row's content.
+Widget paneMenuItem({
+ required VoidCallback onTap,
+ Widget? child,
+ Widget Function(BuildContext context, bool active)? builder,
+}) => Padding(
+ padding: const EdgeInsets.symmetric(horizontal: kPaneMenuInset),
+ child: PaneMenuAction(onPressed: onTap, builder: builder, child: child),
+);
+
+/// A blue active row is separate from the stored choice. Content builders use
+/// the active ink; chosen models carry a checkmark without a competing rim.
+class PaneMenuAction extends StatefulWidget {
+ const PaneMenuAction({
+ super.key,
+ required this.onPressed,
+ this.child,
+ this.builder,
+ this.selected,
+ }) : assert((child == null) != (builder == null));
+
+ final VoidCallback onPressed;
+ final Widget? child;
+ final Widget Function(BuildContext context, bool active)? builder;
+ final bool? selected;
+
+ @override
+ State<PaneMenuAction> createState() => _PaneMenuActionState();
+}
+
+class _PaneMenuActionState extends State<PaneMenuAction> {
+ final _states = WidgetStatesController();
+
+ @override
+ void dispose() {
+ _states.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return ValueListenableBuilder(
+ valueListenable: _states,
+ builder: (context, states, _) {
+ final active =
+ states.contains(WidgetState.focused) ||
+ states.contains(WidgetState.hovered) ||
+ states.contains(WidgetState.pressed);
+ return TextButton(
+ statesController: _states,
+ onPressed: widget.onPressed,
+ style: TextButton.styleFrom(
+ foregroundColor: active
+ ? grid.AppDesktop.onSelection
+ : DesktopChrome.foreground,
+ backgroundColor: active
+ ? grid.AppDesktop.selection
+ : widget.selected == true
+ ? grid.AppSurface.accentWash
+ : Colors.transparent,
+ minimumSize: const Size(0, DesktopChrome.controlHeight),
+ padding: EdgeInsets.zero,
+ alignment: Alignment.centerLeft,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),
+ ),
+ side: const BorderSide(color: Colors.transparent, width: 1.5),
+ textStyle: DesktopChrome.control(),
+ enabledMouseCursor: SystemMouseCursors.click,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ splashFactory: NoSplash.splashFactory,
+ overlayColor: Colors.transparent,
+ ),
+ child: Semantics(
+ selected: widget.selected,
+ child: widget.builder?.call(context, active) ?? widget.child!,
+ ),
+ );
+ },
);
+ }
+}
/// A line that states something rather than offering it — no hover, no tap.
Widget paneMenuEmpty(String text) => Padding(
diff --git a/desktop/lib/widgets/pane_model_status.dart b/desktop/lib/widgets/pane_model_status.dart
index a4dbd4801..89b3dc4f4 100644
--- a/desktop/lib/widgets/pane_model_status.dart
+++ b/desktop/lib/widgets/pane_model_status.dart
@@ -6,6 +6,8 @@
/// daemon's (`grid.note`), in the words of `resting_model_words.dart`.
library;
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../core/models.dart';
@@ -18,13 +20,15 @@ import 'resting_model_words.dart';
/// the room [paneStartingChipWidth] asks the header to leave it.
const double _kChipMark = 14;
const double _kChipGap = 6;
-const EdgeInsets _kChipPadding = EdgeInsets.symmetric(horizontal: 6, vertical: 4);
+const EdgeInsets _kChipPadding = EdgeInsets.symmetric(
+ horizontal: 6,
+ vertical: 4,
+);
/// The note strip's one line: tall enough for its "Pick another" button, and the same height with
/// or without one, so a note that loses its action does not resize the terminal again.
const double _kNoteHeight = 30;
-
/// The chip's words for [phase].
String startingChipLabel(ModelStartPhase phase) => switch (phase) {
ModelStartPhase.starting => kStartingUp,
@@ -49,7 +53,7 @@ class PaneStartingChip extends StatelessWidget {
Widget build(BuildContext context) {
final label = startingChipLabel(phase);
final mark = Icon(
- Icons.hourglass_top,
+ AppIcons.hourglass,
size: _kChipMark,
color: AppColors.textSoft,
);
@@ -132,8 +136,8 @@ class PaneModelNote extends StatelessWidget {
children: [
Icon(
switch (note) {
- GridNoteOffline() => Icons.cloud_off,
- GridNoteNotServed() => Icons.info_outline,
+ GridNoteOffline() => AppIcons.cloudOff,
+ GridNoteNotServed() => AppIcons.info,
},
size: _kChipMark,
color: AppColors.warning,
diff --git a/desktop/lib/widgets/prompt_context.dart b/desktop/lib/widgets/prompt_context.dart
index addf273b3..2975572a1 100644
--- a/desktop/lib/widgets/prompt_context.dart
+++ b/desktop/lib/widgets/prompt_context.dart
@@ -1,7 +1,7 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/rendering.dart' show OverflowBoxFit;
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/appearance_prefs_store.dart';
@@ -129,7 +129,7 @@ class _PromptContextViewState extends State<PromptContextView> {
label: 'Machine',
value: data.machine!,
ascii: '@',
- icon: LucideIcons.monitor300,
+ icon: AppIcons.monitor,
color: grid.AppPalette.swarmAccent,
),
if (prefs.project && data.project?.isNotEmpty == true)
@@ -137,7 +137,7 @@ class _PromptContextViewState extends State<PromptContextView> {
label: 'Project',
value: data.project!,
ascii: '/',
- icon: LucideIcons.folder300,
+ icon: AppIcons.folder,
color: grid.AppPalette.teal,
),
if (prefs.branch && data.branch?.isNotEmpty == true)
@@ -145,7 +145,7 @@ class _PromptContextViewState extends State<PromptContextView> {
label: 'Branch',
value: data.branch!,
ascii: 'git:',
- icon: LucideIcons.gitBranch300,
+ icon: AppIcons.gitBranch,
color: grid.AppPalette.online,
),
];
diff --git a/desktop/lib/widgets/prompt_customize.dart b/desktop/lib/widgets/prompt_customize.dart
index 8052dfe37..baf746a36 100644
--- a/desktop/lib/widgets/prompt_customize.dart
+++ b/desktop/lib/widgets/prompt_customize.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -9,6 +10,7 @@ import '../shared/theme/status_line_style.dart';
import '../terminal/terminal_text.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
+import 'desktop_chrome.dart';
import 'status_line.dart';
import 'workspace_pull_request_label.dart';
@@ -18,18 +20,15 @@ class PromptCustomize extends StatelessWidget {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
grid.AppTheme.watch(context);
return ListenableBuilder(
listenable: Listenable.merge([store, terminalThemeStore]),
builder: (context, _) {
final prefs = store.value.prompt;
- final cell = terminalCellSizeOf(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
- final style = terminalContentStyle(color: theme.foreground);
void choose(PromptPrefs next) => unawaited(store.setPrompt(next));
StatusLineParts example(StatusLineStyle format) => statusLineParts(
provider: '',
@@ -54,84 +53,36 @@ class PromptCustomize extends StatelessWidget {
color: prefs.color,
segmentOffset: previewContext.segments.length,
).single.background;
- final buttonStyle = TextButton.styleFrom(
- alignment: Alignment.centerLeft,
- foregroundColor: theme.foreground,
- minimumSize: Size.zero,
- padding: EdgeInsets.symmetric(horizontal: cell.width),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- shape: const RoundedRectangleBorder(),
- textStyle: style,
- );
- Widget toggle(
- String name,
- String label,
- bool value,
- ValueChanged<bool> change,
- ) => SizedBox(
- height: cell.height,
- child: TextButton(
- key: ValueKey('prompt-$name'),
- style: buttonStyle,
- onPressed: () => change(!value),
- child: Semantics(
- checked: value,
- label: label,
- child: ExcludeSemantics(
- child: Text('${value ? '[x]' : '[ ]'} $label', style: style),
- ),
- ),
- ),
- );
return SingleChildScrollView(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height,
- ),
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Text('Status line', style: style),
- SizedBox(height: cell.height),
+ Text('Status line', style: DesktopChrome.heading()),
+ const SizedBox(height: 8),
+ Text(
+ 'Choose how the focused pane’s context appears in the footer. '
+ 'Changes save as you choose.',
+ style: DesktopChrome.metadata(),
+ ),
for (final format in StatusLineStyle.values) ...[
if (format == StatusLineStyle.standard ||
- format == StatusLineStyle.agnoster) ...[
- Text(
- format.segmented ? 'Powerline' : 'Minimal',
- style: style.copyWith(
- color: theme.foreground.withValues(alpha: .6),
+ format == StatusLineStyle.agnoster)
+ Padding(
+ padding: const EdgeInsets.only(top: 24, bottom: 8),
+ child: Text(
+ format.segmented ? 'Powerline' : 'Minimal',
+ style: DesktopChrome.control(medium: true),
),
),
- SizedBox(height: cell.height),
- ],
- SizedBox(
- height: cell.height,
- child: TextButton(
- key: ValueKey('prompt-style-${format.name}'),
- style: buttonStyle.copyWith(
- backgroundColor: WidgetStatePropertyAll(
- prefs.statusStyle == format
- ? theme.selection
- : Colors.transparent,
- ),
- ),
- onPressed: () =>
- choose(prefs.copyWith(statusStyle: format)),
- child: Semantics(
- selected: prefs.statusStyle == format,
- child: Text(
- '${prefs.statusStyle == format ? '>' : ' '} ${format.label}',
- style: style,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- ),
- ),
- Padding(
- padding: EdgeInsets.only(left: cell.width * 3),
- child: SizedBox(
- height: cell.height,
+ _StatusStyleChoice(
+ key: ValueKey('prompt-style-${format.name}'),
+ format: format,
+ selected: prefs.statusStyle == format,
+ onPressed: () => choose(prefs.copyWith(statusStyle: format)),
+ preview: _StatusPreviewWell(
+ key: ValueKey('prompt-example-well-${format.name}'),
+ background: theme.background,
child: StatusLine(
key: ValueKey('prompt-example-${format.name}'),
parts: example(format),
@@ -140,30 +91,28 @@ class PromptCustomize extends StatelessWidget {
),
),
),
- SizedBox(height: cell.height),
+ const SizedBox(height: 4),
],
- Text('Preview', style: style),
- SizedBox(height: cell.height),
- ColoredBox(
- color: theme.background,
- child: Padding(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width,
- vertical: cell.height,
- ),
- child: Row(
+ const SizedBox(height: 20),
+ Text('Preview', style: DesktopChrome.control(medium: true)),
+ const SizedBox(height: 8),
+ _StatusPreviewWell(
+ key: const ValueKey('prompt-preview-well'),
+ background: theme.background,
+ child: Builder(
+ builder: (context) => Row(
+ mainAxisSize: MainAxisSize.min,
children: [
- Flexible(
- child: StatusLine(
- key: const ValueKey('prompt-preview'),
- parts: previewContext,
- color: prefs.color,
- textAlign: TextAlign.left,
- workspaceBar: true,
- nextBackground: prBackground,
- ),
+ StatusLine(
+ key: const ValueKey('prompt-preview'),
+ parts: previewContext,
+ color: prefs.color,
+ textAlign: TextAlign.left,
+ workspaceBar: true,
+ nextBackground: prBackground,
),
- if (!joined) SizedBox(width: cell.width),
+ if (!joined)
+ SizedBox(width: terminalCellSizeOf(context).width),
WorkspacePullRequestLabel(
number: 298,
state: 'Merged',
@@ -175,44 +124,43 @@ class PromptCustomize extends StatelessWidget {
),
),
),
- SizedBox(height: cell.height),
- toggle(
- 'machine',
- 'Machine',
- prefs.machine,
- (value) => choose(prefs.copyWith(machine: value)),
+ const SizedBox(height: 24),
+ Text(
+ 'Show in the footer',
+ style: DesktopChrome.control(medium: true),
),
- toggle(
- 'project',
- 'Project',
- prefs.project,
- (value) => choose(prefs.copyWith(project: value)),
+ const SizedBox(height: 8),
+ _StatusToggle(
+ key: const ValueKey('prompt-machine'),
+ label: 'Machine',
+ value: prefs.machine,
+ onChanged: (value) => choose(prefs.copyWith(machine: value)),
),
- toggle(
- 'branch',
- 'Branch',
- prefs.branch,
- (value) => choose(prefs.copyWith(branch: value)),
+ _StatusToggle(
+ key: const ValueKey('prompt-project'),
+ label: 'Project',
+ value: prefs.project,
+ onChanged: (value) => choose(prefs.copyWith(project: value)),
),
- toggle(
- 'color',
- 'Color',
- prefs.color,
- (value) => choose(prefs.copyWith(color: value)),
+ _StatusToggle(
+ key: const ValueKey('prompt-branch'),
+ label: 'Branch',
+ value: prefs.branch,
+ onChanged: (value) => choose(prefs.copyWith(branch: value)),
),
- SizedBox(height: cell.height),
- Text(
- 'Applies to the focused pane in the top bar. Saved as you choose.',
- style: style.copyWith(
- color: theme.foreground.withValues(alpha: .6),
- ),
+ const SizedBox(height: 8),
+ _StatusToggle(
+ key: const ValueKey('prompt-color'),
+ label: 'Use color',
+ value: prefs.color,
+ onChanged: (value) => choose(prefs.copyWith(color: value)),
),
- SizedBox(height: cell.height),
- SizedBox(
- height: cell.height,
- child: TextButton(
+ const SizedBox(height: 24),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: DesktopPill(
key: const ValueKey('prompt-reset'),
- style: buttonStyle,
+ label: 'Reset status line',
onPressed: () => choose(
prefs.copyWith(
statusStyle: StatusLineStyle.standard,
@@ -222,7 +170,6 @@ class PromptCustomize extends StatelessWidget {
color: true,
),
),
- child: Text('[ Reset status line ]', style: style),
),
),
],
@@ -232,3 +179,182 @@ class PromptCustomize extends StatelessWidget {
);
}
}
+
+class _StatusStyleChoice extends StatelessWidget {
+ const _StatusStyleChoice({
+ super.key,
+ required this.format,
+ required this.selected,
+ required this.onPressed,
+ required this.preview,
+ });
+
+ final StatusLineStyle format;
+ final bool selected;
+ final VoidCallback onPressed;
+ final Widget preview;
+
+ @override
+ Widget build(BuildContext context) {
+ final highContrast = MediaQuery.highContrastOf(context);
+ return MergeSemantics(
+ child: Semantics(
+ label: format.label,
+ selected: selected,
+ inMutuallyExclusiveGroup: true,
+ child: TextButton(
+ onPressed: onPressed,
+ style:
+ TextButton.styleFrom(
+ alignment: Alignment.centerLeft,
+ foregroundColor: DesktopChrome.foreground,
+ backgroundColor: selected
+ ? DesktopChrome.selection
+ : Colors.transparent,
+ minimumSize: const Size(0, DesktopChrome.controlHeight),
+ padding: const EdgeInsets.all(10),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ splashFactory: NoSplash.splashFactory,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ ),
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? DesktopChrome.accent
+ : highContrast && selected
+ ? DesktopChrome.foreground.withValues(alpha: .45)
+ : Colors.transparent,
+ ),
+ ),
+ overlayColor: WidgetStateProperty.resolveWith(
+ (states) => DesktopChrome.foreground.withValues(
+ alpha: states.contains(WidgetState.pressed)
+ ? .12
+ : states.contains(WidgetState.hovered)
+ ? (highContrast ? .10 : .05)
+ : 0,
+ ),
+ ),
+ ),
+ child: ExcludeSemantics(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Icon(
+ selected ? AppIcons.circleDot : AppIcons.circle,
+ size: 18,
+ color: selected
+ ? DesktopChrome.accent
+ : DesktopChrome.muted,
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ format.label,
+ style: DesktopChrome.control(medium: selected),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ preview,
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// These are real terminal/status samples, independent of the surrounding UI's
+/// text scaling. A large terminal font scrolls without changing its glyphs.
+class _StatusPreviewWell extends StatelessWidget {
+ const _StatusPreviewWell({
+ super.key,
+ required this.background,
+ required this.child,
+ });
+
+ final Color background;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) => DecoratedBox(
+ decoration: BoxDecoration(
+ color: background,
+ borderRadius: BorderRadius.circular(6),
+ border: Border.all(color: DesktopChrome.rim),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
+ // The choice's button label can be semibold; its terminal sample cannot
+ // inherit that weight. Each renderer supplies its own font and colors.
+ child: DefaultTextStyle(
+ style: const TextStyle(
+ fontWeight: FontWeight.normal,
+ fontStyle: FontStyle.normal,
+ ),
+ child: MediaQuery.withNoTextScaling(
+ child: SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ child: child,
+ ),
+ ),
+ ),
+ ),
+ );
+}
+
+class _StatusToggle extends StatefulWidget {
+ const _StatusToggle({
+ super.key,
+ required this.label,
+ required this.value,
+ required this.onChanged,
+ });
+
+ final String label;
+ final bool value;
+ final ValueChanged<bool> onChanged;
+
+ @override
+ State<_StatusToggle> createState() => _StatusToggleState();
+}
+
+class _StatusToggleState extends State<_StatusToggle> {
+ bool _focused = false;
+
+ @override
+ Widget build(BuildContext context) => CheckboxListTile(
+ value: widget.value,
+ onChanged: (value) => widget.onChanged(value!),
+ onFocusChange: (value) => setState(() => _focused = value),
+ controlAffinity: ListTileControlAffinity.leading,
+ title: Text(widget.label, style: DesktopChrome.control()),
+ activeColor: DesktopChrome.accent,
+ checkColor: DesktopChrome.accent.computeLuminance() > .179
+ ? Colors.black
+ : Colors.white,
+ side: BorderSide(color: DesktopChrome.muted, width: 1.5),
+ contentPadding: const EdgeInsets.symmetric(horizontal: 8),
+ minLeadingWidth: 0,
+ horizontalTitleGap: 8,
+ minTileHeight: DesktopChrome.controlHeight,
+ visualDensity: VisualDensity.compact,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ side: BorderSide(
+ width: 1.5,
+ color: _focused ? DesktopChrome.accent : Colors.transparent,
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/remote_folder_picker.dart b/desktop/lib/widgets/remote_folder_picker.dart
index 126c99010..90d9cb62c 100644
--- a/desktop/lib/widgets/remote_folder_picker.dart
+++ b/desktop/lib/widgets/remote_folder_picker.dart
@@ -5,6 +5,7 @@ import '../terminal/terminal_text.dart';
import '../shared/widgets/labeled_field.dart';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
@@ -14,6 +15,7 @@ import '../state/app_state.dart';
import '../theme/app_theme.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/skeleton.dart';
+import 'desktop_chrome.dart';
/// Browses the selected machine through fs_list_dir. The native folder chooser
/// would return a path on this computer instead of the agent's machine.
@@ -23,6 +25,7 @@ Future<String?> showRemoteFolderPicker(
required String machineId,
String? initialPath,
bool terminal = false,
+ bool desktop = false,
}) => showAppDialog<String>(
context: context,
builder: (context) => ListenableBuilder(
@@ -30,7 +33,7 @@ Future<String?> showRemoteFolderPicker(
builder: (context, _) {
final theme = Theme.of(context);
return Theme(
- data: terminal
+ data: terminal && !desktop
? theme.copyWith(
textTheme: theme.textTheme.apply(
fontSizeFactor:
@@ -43,6 +46,7 @@ Future<String?> showRemoteFolderPicker(
machineId: machineId,
initialPath: initialPath,
terminal: terminal,
+ desktop: desktop,
),
);
},
@@ -55,12 +59,13 @@ class _RemoteFolderPickerDialog extends StatefulWidget {
required this.machineId,
this.initialPath,
this.terminal = false,
+ this.desktop = false,
});
final AppNotifier notifier;
final String machineId;
final String? initialPath;
- final bool terminal;
+ final bool terminal, desktop;
@override
State<_RemoteFolderPickerDialog> createState() =>
@@ -85,6 +90,8 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
_path != null &&
_location.text.trim() == _path;
+ bool get _composing => !_location.value.composing.isCollapsed;
+
// The remote machine may use different path separators than this desktop.
p.Context get _paths => p.Context(
style:
@@ -193,27 +200,43 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
}
void _refresh() {
- if (_loading) return;
+ if (_loading || _composing) return;
final highlighted = _selected >= 0 && _selected < _entries.length
? _entries[_selected]
: null;
unawaited(_load(_path, highlight: highlighted, refreshing: true));
}
+ void _retry() {
+ unawaited(_load(_requestedPath));
+ _locationFocus.requestFocus();
+ }
+
void _openPath() {
final path = _location.text.trim();
- if (path.isEmpty || (_loading && path == _requestedPath)) return;
+ if (_composing || path.isEmpty || (_loading && path == _requestedPath)) {
+ return;
+ }
_load(path);
}
void _up() {
- if (_blocking) return;
+ if (_blocking || _composing) return;
final parent = _parentPath;
if (parent != null) _load(parent, highlight: _paths.basename(_path!));
}
void _select() {
- if (_canSelect) Navigator.of(context).pop(_path);
+ if (_canSelect && !_composing) Navigator.of(context).pop(_path);
+ }
+
+ void _editLocation() {
+ if (_composing) return;
+ _locationFocus.requestFocus();
+ _location.selection = TextSelection(
+ baseOffset: 0,
+ extentOffset: _location.text.length,
+ );
}
void _openSelected() {
@@ -222,6 +245,12 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
}
}
+ void _openEntry(int index) {
+ _foldersFocus.requestFocus();
+ setState(() => _selected = index);
+ _openSelected();
+ }
+
void _revealSelection() {
if (!_scroll.hasClients || _selected < 0) return;
final top = _selected * _rowHeight;
@@ -252,16 +281,32 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
} else if (key == LogicalKeyboardKey.enter ||
key == LogicalKeyboardKey.numpadEnter ||
key == LogicalKeyboardKey.arrowRight) {
- _openSelected();
+ if (event is KeyDownEvent) _openSelected();
} else if (key == LogicalKeyboardKey.arrowDown ||
key == LogicalKeyboardKey.arrowUp ||
key == LogicalKeyboardKey.home ||
- key == LogicalKeyboardKey.end) {
+ key == LogicalKeyboardKey.end ||
+ key == LogicalKeyboardKey.pageDown ||
+ key == LogicalKeyboardKey.pageUp) {
if (!_blocking && _entries.isNotEmpty) {
+ final page = _scroll.hasClients
+ ? math.max(
+ 1,
+ (_scroll.position.viewportDimension / _rowHeight).floor(),
+ )
+ : 1;
setState(() {
_selected = switch (key) {
LogicalKeyboardKey.home => 0,
LogicalKeyboardKey.end => _entries.length - 1,
+ LogicalKeyboardKey.pageDown => (_selected + page).clamp(
+ 0,
+ _entries.length - 1,
+ ),
+ LogicalKeyboardKey.pageUp => (_selected - page).clamp(
+ 0,
+ _entries.length - 1,
+ ),
LogicalKeyboardKey.arrowUp => (_selected - 1).clamp(
0,
_entries.length - 1,
@@ -290,6 +335,373 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
_ => 'Couldn’t open this folder. Try again.',
};
+ Widget _pathField() => Focus(
+ onKeyEvent: (node, event) {
+ if (_composing) {
+ return KeyEventResult.skipRemainingHandlers;
+ }
+ if (event is KeyDownEvent &&
+ event.logicalKey == LogicalKeyboardKey.arrowDown &&
+ !HardwareKeyboard.instance.isAltPressed &&
+ !HardwareKeyboard.instance.isControlPressed &&
+ !HardwareKeyboard.instance.isMetaPressed &&
+ !HardwareKeyboard.instance.isShiftPressed &&
+ _location.value.composing.isCollapsed &&
+ !_blocking &&
+ _entries.isNotEmpty) {
+ _foldersFocus.requestFocus();
+ _revealSelection();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: Semantics(
+ label: widget.desktop ? 'Folder path' : null,
+ child: TextField(
+ key: const Key('remote-folder-path'),
+ controller: _location,
+ focusNode: _locationFocus,
+ autofocus: true,
+ autocorrect: false,
+ enableSuggestions: false,
+ // A path: typed and pasted, so set to be copied exactly.
+ style: widget.terminal && !widget.desktop
+ ? terminalTextStyle(color: grid.AppPalette.textPrimary)
+ : grid.AppType.mono(color: grid.AppPalette.textPrimary),
+ decoration: InputDecoration(
+ hintText: 'Enter a full folder path…',
+ isDense: widget.desktop,
+ filled: widget.desktop ? true : null,
+ fillColor: widget.desktop ? DesktopChrome.field : null,
+ border: widget.desktop
+ ? OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ )
+ : null,
+ enabledBorder: widget.desktop
+ ? OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ )
+ : null,
+ focusedBorder: widget.desktop
+ ? OutlineInputBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.fieldRadius,
+ ),
+ borderSide: BorderSide(
+ color: DesktopChrome.focusRing,
+ width: grid.AppDesktop.focusWidth,
+ ),
+ )
+ : null,
+ suffixIcon: IconButton(
+ tooltip: 'Open path',
+ onPressed:
+ _location.text.trim().isEmpty ||
+ (_loading && _location.text.trim() == _requestedPath)
+ ? null
+ : _openPath,
+ icon: const Icon(AppIcons.arrowRight, size: 18),
+ ),
+ ),
+ onChanged: (_) => setState(() {
+ _edit++;
+ _error = null;
+ }),
+ onEditingComplete: () {},
+ onSubmitted: (_) => _openPath(),
+ ),
+ ),
+ );
+
+ Widget _folderList(double listHeight) => Focus(
+ focusNode: _foldersFocus,
+ onKeyEvent: _folderKey,
+ onFocusChange: (_) => setState(() {}),
+ child: Container(
+ key: const Key('remote-folder-list'),
+ height: listHeight,
+ decoration: BoxDecoration(
+ color: widget.desktop ? DesktopChrome.field : AppColors.background,
+ border: Border.all(
+ color: _foldersFocus.hasFocus
+ ? widget.desktop
+ ? DesktopChrome.focusRing
+ : AppColors.accent
+ : widget.desktop
+ ? DesktopChrome.rim
+ : AppColors.border,
+ width: _foldersFocus.hasFocus && widget.desktop ? 2 : 1,
+ ),
+ borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: _blocking
+ ? const _FolderRowsSkeleton()
+ : _entries.isEmpty
+ ? Center(
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: Text(
+ _path == null
+ ? 'Enter a path or open your home folder.'
+ : 'No subfolders here.',
+ textAlign: TextAlign.center,
+ style: widget.desktop
+ ? DesktopChrome.text(size: 13, color: DesktopChrome.muted)
+ : Theme.of(context).textTheme.bodySmall,
+ ),
+ ),
+ )
+ : ListView.builder(
+ controller: _scroll,
+ itemExtent: _rowHeight,
+ itemCount: _entries.length,
+ itemBuilder: (context, index) => Semantics(
+ button: true,
+ label: _entries[index],
+ hint: 'Open folder',
+ selected: index == _selected,
+ excludeSemantics: true,
+ onTap: () => _openEntry(index),
+ child: Material(
+ color: index == _selected && _foldersFocus.hasFocus
+ ? widget.desktop
+ ? DesktopChrome.selection
+ : AppColors.selected
+ : Colors.transparent,
+ child: InkWell(
+ splashFactory: widget.desktop
+ ? NoSplash.splashFactory
+ : null,
+ canRequestFocus: false,
+ onTap: () => _openEntry(index),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Row(
+ children: [
+ Icon(
+ AppIcons.folder,
+ size: 18,
+ color: widget.desktop
+ ? DesktopChrome.accent
+ : AppColors.mutedStrong,
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ _entries[index],
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: widget.desktop
+ ? DesktopChrome.text()
+ : null,
+ ),
+ ),
+ Icon(
+ AppIcons.chevronRight,
+ size: 16,
+ color: widget.desktop
+ ? DesktopChrome.muted
+ : AppColors.mutedStrong,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ Widget _desktopDialog(BuildContext context, String? machine, bool mac) {
+ final scale = MediaQuery.textScalerOf(context);
+ final listHeight =
+ (MediaQuery.sizeOf(context).height - 290 - scale.scale(60)).clamp(
+ 140.0,
+ 290.0,
+ );
+ return DesktopChrome(
+ child: Dialog(
+ key: const ValueKey('desktop-remote-folder-dialog'),
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ insetPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 620, maxHeight: 620),
+ child: DesktopDialogSurface(
+ child: Semantics(
+ scopesRoute: true,
+ namesRoute: true,
+ explicitChildNodes: true,
+ label: 'Choose a folder',
+ child: FocusTraversalGroup(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ DesktopDialogHeader(
+ title: 'Choose a folder',
+ detail: 'On ${machine ?? 'the remote machine'}',
+ ),
+ Divider(height: 1, color: DesktopChrome.rim),
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(
+ grid.AppDesktop.panelPadding,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ ExcludeSemantics(
+ child: Text(
+ 'Folder path',
+ style: DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ),
+ const SizedBox(height: 6),
+ _pathField(),
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ DesktopPill(
+ key: const Key('remote-folder-up'),
+ label: 'Up',
+ semanticLabel: 'Up one folder',
+ icon: AppIcons.arrowUp,
+ compact: true,
+ tooltip: mac
+ ? 'Up one folder (⌘↑ or ⌥↑)'
+ : 'Up one folder (Alt+↑)',
+ onPressed: _blocking || _parentPath == null
+ ? null
+ : _up,
+ ),
+ DesktopPill(
+ key: const Key('remote-folder-home'),
+ label: 'Home',
+ icon: AppIcons.house,
+ compact: true,
+ tooltip: 'Home folder on this machine',
+ onPressed: () => _load(null),
+ ),
+ DesktopPill(
+ key: const Key('remote-folder-refresh'),
+ label: 'Refresh',
+ icon: AppIcons.refreshCw,
+ compact: true,
+ tooltip: mac
+ ? 'Refresh folders (⌘R)'
+ : 'Refresh folders (Ctrl+R)',
+ onPressed: _loading ? null : _refresh,
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ if (_path != null &&
+ _location.text.trim() != _path) ...[
+ Text(
+ 'Showing $_path',
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ const SizedBox(height: 8),
+ ],
+ if (_error != null) ...[
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ _errorMessage(_error!),
+ style: DesktopChrome.text(
+ size: 13,
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
+ const SizedBox(height: 8),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: DesktopPill(
+ label: 'Retry',
+ icon: AppIcons.refreshCw,
+ onPressed: _retry,
+ ),
+ ),
+ const SizedBox(height: 12),
+ ],
+ _folderList(listHeight),
+ if (_error == null && _truncated && !_loading) ...[
+ const SizedBox(height: 12),
+ Text(
+ 'More folders are available. Enter their full path to open them.',
+ style: DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ Divider(height: 1, color: DesktopChrome.rim),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 16),
+ child: Wrap(
+ alignment: WrapAlignment.end,
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ OutlinedButton(
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ key: const Key('remote-folder-select'),
+ onPressed: _canSelect ? _select : null,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Flexible(
+ child: Text('Select this folder'),
+ ),
+ const SizedBox(width: 12),
+ Text(
+ mac ? '⌘↵' : 'Ctrl↵',
+ style: grid.AppType.monoMeta(),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
@@ -297,7 +709,7 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
_rowHeight = math.max(
36,
scale.scale(
- widget.terminal
+ widget.terminal && !widget.desktop
? terminalFontStore.size
: grid.AppType.bodySize,
) *
@@ -358,244 +770,132 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): _up,
SingleActivator(LogicalKeyboardKey.keyR, meta: mac, control: !mac):
_refresh,
+ if (widget.desktop) ...{
+ SingleActivator(LogicalKeyboardKey.keyL, meta: mac, control: !mac):
+ _editLocation,
+ const SingleActivator(
+ LogicalKeyboardKey.keyG,
+ meta: true,
+ shift: true,
+ ): _editLocation,
+ const SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): _up,
+ },
},
- child: AlertDialog(
- title: const Text('Choose a folder'),
- scrollable: true,
- // Material's 20 here left MORE air between the title and the
- // machine line below it (16) than between that line and the next
- // section (12), so the one line that belongs to the title floated
- // between the two blocks instead of sitting under it. 10 groups it
- // with its title and the section below starts a clear 16 later.
- contentPadding: const EdgeInsets.fromLTRB(24, 10, 24, 24),
- content: SizedBox(
- width: 520,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- 'On ${machine ?? 'the remote machine'}',
- style: Theme.of(context).textTheme.bodySmall,
- ),
- const SizedBox(height: 16),
- if (widget.terminal)
- Text('Folder path', style: terminalTextStyle())
- else
- const FieldLabel('Folder path'),
- // The label was flush against its field, while the Folders
- // header gets ~8 from the icon buttons beside it centring.
- const SizedBox(height: 6),
- Focus(
- onKeyEvent: (node, event) {
- if (event is KeyDownEvent &&
- event.logicalKey == LogicalKeyboardKey.arrowDown &&
- !HardwareKeyboard.instance.isAltPressed &&
- !HardwareKeyboard.instance.isControlPressed &&
- !HardwareKeyboard.instance.isMetaPressed &&
- !HardwareKeyboard.instance.isShiftPressed &&
- _location.value.composing.isCollapsed &&
- !_blocking &&
- _entries.isNotEmpty) {
- _foldersFocus.requestFocus();
- _revealSelection();
- return KeyEventResult.handled;
- }
- return KeyEventResult.ignored;
- },
- child: TextField(
- key: const Key('remote-folder-path'),
- controller: _location,
- focusNode: _locationFocus,
- autofocus: true,
- // A path: typed and pasted, so set to be copied exactly.
- style: widget.terminal
- ? terminalTextStyle(color: grid.AppPalette.textPrimary)
- : grid.AppType.mono(color: grid.AppPalette.textPrimary),
- decoration: InputDecoration(
- hintText: 'Enter a full folder path…',
- suffixIcon: IconButton(
- tooltip: 'Open path',
- onPressed:
- _location.text.trim().isEmpty ||
- (_loading &&
- _location.text.trim() == _requestedPath)
- ? null
- : _openPath,
- icon: const Icon(Icons.arrow_forward, size: 18),
- ),
- ),
- onChanged: (_) => setState(() {
- _edit++;
- _error = null;
- }),
- onEditingComplete: () {},
- onSubmitted: (_) => _openPath(),
- ),
- ),
- const SizedBox(height: 8),
- Row(
- children: [
- Expanded(
- child: Text(
- _path != null && _location.text.trim() != _path
- ? 'Showing $_path'
- : 'Folders',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: Theme.of(context).textTheme.labelMedium,
- ),
- ),
- IconButton(
- key: const Key('remote-folder-home'),
- tooltip: 'Home folder on this machine',
- onPressed: () => _load(null),
- icon: const Icon(Icons.home_outlined, size: 18),
- ),
- IconButton(
- tooltip: 'Refresh folders',
- onPressed: _loading ? null : _refresh,
- icon: const Icon(Icons.refresh, size: 18),
- ),
- IconButton(
- tooltip: mac
- ? 'Up one folder (⌥↑)'
- : 'Up one folder (Alt+↑)',
- onPressed: _blocking || _parentPath == null ? null : _up,
- icon: const Icon(Icons.arrow_upward, size: 18),
- ),
- ],
- ),
- Focus(
- focusNode: _foldersFocus,
- onKeyEvent: _folderKey,
- onFocusChange: (_) => setState(() {}),
- child: Container(
- key: const Key('remote-folder-list'),
- height: listHeight,
- decoration: BoxDecoration(
- color: AppColors.background,
- border: Border.all(
- color: _foldersFocus.hasFocus
- ? AppColors.accent
- : AppColors.border,
- ),
- borderRadius: BorderRadius.circular(
- grid.AppCard.insetRadius,
+ child: widget.desktop
+ ? _desktopDialog(context, machine, mac)
+ : AlertDialog(
+ title: const Text('Choose a folder'),
+ scrollable: true,
+ // Material's 20 here left MORE air between the title and the
+ // machine line below it (16) than between that line and the next
+ // section (12), so the one line that belongs to the title floated
+ // between the two blocks instead of sitting under it. 10 groups it
+ // with its title and the section below starts a clear 16 later.
+ contentPadding: const EdgeInsets.fromLTRB(24, 10, 24, 24),
+ content: SizedBox(
+ width: 520,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ 'On ${machine ?? 'the remote machine'}',
+ style: Theme.of(context).textTheme.bodySmall,
),
- ),
- clipBehavior: Clip.antiAlias,
- child: _blocking
- ? const _FolderRowsSkeleton()
- : _entries.isEmpty
- ? Center(
- child: Padding(
- padding: const EdgeInsets.all(16),
- child: Text(
- _path == null
- ? 'Enter a path or open your home folder.'
- : 'No subfolders here.',
- textAlign: TextAlign.center,
- style: Theme.of(context).textTheme.bodySmall,
- ),
+ const SizedBox(height: 16),
+ if (widget.terminal)
+ Text('Folder path', style: terminalTextStyle())
+ else
+ const FieldLabel('Folder path'),
+ // The label was flush against its field, while the Folders
+ // header gets ~8 from the icon buttons beside it centring.
+ const SizedBox(height: 6),
+ _pathField(),
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ _path != null && _location.text.trim() != _path
+ ? 'Showing $_path'
+ : 'Folders',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context).textTheme.labelMedium,
),
- )
- : ListView.builder(
- controller: _scroll,
- itemExtent: _rowHeight,
- itemCount: _entries.length,
- itemBuilder: (context, index) => Semantics(
- selected: index == _selected,
- child: Material(
- color:
- index == _selected && _foldersFocus.hasFocus
- ? AppColors.selected
- : Colors.transparent,
- child: InkWell(
- canRequestFocus: false,
- onTap: () {
- _foldersFocus.requestFocus();
- setState(() => _selected = index);
- _openSelected();
- },
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 12,
- ),
- child: Row(
- children: [
- Icon(
- Icons.folder_outlined,
- size: 18,
- color: AppColors.mutedStrong,
- ),
- const SizedBox(width: 10),
- Expanded(
- child: Text(
- _entries[index],
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- Icon(
- Icons.chevron_right,
- size: 16,
- color: AppColors.mutedStrong,
- ),
- ],
- ),
- ),
+ ),
+ IconButton(
+ key: const Key('remote-folder-home'),
+ tooltip: 'Home folder on this machine',
+ onPressed: () => _load(null),
+ icon: const Icon(AppIcons.house, size: 18),
+ ),
+ IconButton(
+ tooltip: 'Refresh folders',
+ onPressed: _loading ? null : _refresh,
+ icon: const Icon(AppIcons.refreshCw, size: 18),
+ ),
+ IconButton(
+ tooltip: mac
+ ? 'Up one folder (⌥↑)'
+ : 'Up one folder (Alt+↑)',
+ onPressed: _blocking || _parentPath == null
+ ? null
+ : _up,
+ icon: const Icon(AppIcons.arrowUp, size: 18),
+ ),
+ ],
+ ),
+ _folderList(listHeight),
+ if (_error != null) ...[
+ const SizedBox(height: 8),
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Semantics(
+ liveRegion: true,
+ child: Text(
+ _errorMessage(_error!),
+ style: Theme.of(context).textTheme.bodySmall
+ ?.copyWith(
+ color: Theme.of(context)
+ .colorScheme
+ .error,
+ ),
),
),
),
- ),
- ),
- ),
- if (_error != null) ...[
- const SizedBox(height: 8),
- Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Expanded(
- child: Semantics(
- liveRegion: true,
- child: Text(
- _errorMessage(_error!),
- style: Theme.of(context).textTheme.bodySmall
- ?.copyWith(color: AppColors.danger),
- ),
+ const SizedBox(width: 8),
+ TextButton(
+ onPressed: _retry,
+ child: const Text('Retry'),
+ ),
+ ],
),
- ),
- const SizedBox(width: 8),
- TextButton(
- onPressed: () => _load(_requestedPath),
- child: const Text('Retry'),
- ),
+ ] else if (_truncated && !_loading) ...[
+ const SizedBox(height: 8),
+ Text(
+ 'More folders are available. Enter their full path to open them.',
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ ],
],
),
- ] else if (_truncated && !_loading) ...[
- const SizedBox(height: 8),
- Text(
- 'More folders are available. Enter their full path to open them.',
- style: Theme.of(context).textTheme.bodySmall,
+ ),
+ actions: [
+ TextButton(
+ style: actionStyle,
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ style: actionStyle,
+ onPressed: _canSelect ? _select : null,
+ child: const Text('Select this folder'),
),
],
- ],
- ),
- ),
- actions: [
- TextButton(
- style: actionStyle,
- onPressed: () => Navigator.of(context).pop(),
- child: const Text('Cancel'),
- ),
- FilledButton(
- style: actionStyle,
- onPressed: _canSelect ? _select : null,
- child: const Text('Select this folder'),
- ),
- ],
- ),
+ ),
),
);
}
diff --git a/desktop/lib/widgets/restart_agent_action.dart b/desktop/lib/widgets/restart_agent_action.dart
index 71085c844..d0e2d0014 100644
--- a/desktop/lib/widgets/restart_agent_action.dart
+++ b/desktop/lib/widgets/restart_agent_action.dart
@@ -4,8 +4,10 @@ import 'package:flutter/material.dart';
import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
-import '../terminal/terminal_text.dart';
-import 'box_chrome.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
+import 'box_chrome.dart' show BoxAnnouncer;
import 'engine_identity.dart';
import 'terminal_prompt.dart';
@@ -181,150 +183,136 @@ class _RestartAgentPromptState extends State<_RestartAgentPrompt> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
- return ListenableBuilder(
- listenable: terminalFontStore,
- builder: (context, _) => TerminalPromptKeys(
- focusNode: _focus,
- inputFocus: _focus,
- accept: _accept,
- cancel: _confirmAgain ? _cancelAgain : _close,
- pageDown: () => _page(1),
- pageUp: () => _page(-1),
- child: TerminalPrompt(
- child: Column(
- key: const ValueKey('agent-restart-prompt'),
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Flexible(
- child: ExcludeFocus(
- child: SingleChildScrollView(
- controller: _body,
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- _terminal ? 'Restart Terminal' : 'Restart Harness',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- const SizedBox(height: 12),
- Text(
- _attempt.agent?.name ?? widget.agentId,
- style: boxMonoStyle(weight: FontWeight.w600),
- ),
- if (widget.notifier
- .stateOf(widget.machineId)
- ?.machine
- .displayName
- case final machine?)
- Text(machine, style: boxMonoStyle(color: kBoxFaint)),
- if (!_confirmAgain) ...[
- const SizedBox(height: 10),
- Text(
- _terminal
- ? 'Starts a fresh shell in the same pane.'
- : 'Restarts the harness in the same pane and tries to resume its conversation.',
- style: boxMonoStyle(color: boxText(.70)),
- ),
- if (_busy) ...[
- const SizedBox(height: 8),
- Text(
- 'Restart continues if you close this prompt.',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ],
- if (_error case final error?) ...[
- const SizedBox(height: 12),
- Text(
- error,
- style: boxMonoStyle(color: boxErrorText),
- ),
- ],
- if (_fresh) ...[
- const SizedBox(height: 12),
- Text(
- 'Started a new conversation. The previous conversation could not be resumed.',
- style: boxMonoStyle(color: boxErrorText),
- ),
- ],
- ],
- ],
- ),
- ),
+ grid.AppTheme.watch(context);
+ final uncertain = _attempt.awaitingConfirmation && !_closeOnly;
+ final status = _busy
+ ? 'Restarting…'
+ : _confirmAgain
+ ? 'May have already restarted.'
+ : uncertain
+ ? 'Restart not confirmed.'
+ : null;
+ final actionLabel = uncertain ? 'Check status' : 'Retry';
+ final closeLabel = _confirmAgain ? 'Cancel' : 'Close';
+ return TerminalPromptKeys(
+ focusNode: _focus,
+ inputFocus: _focus,
+ accept: _accept,
+ cancel: _confirmAgain ? _cancelAgain : _close,
+ pageDown: () => _page(1),
+ pageUp: () => _page(-1),
+ child: DesktopPromptSurface(
+ key: const ValueKey('agent-restart-prompt'),
+ body: ExcludeFocusTraversal(
+ child: DesktopPromptScrollBody(
+ controller: _body,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ _terminal ? 'Restart Terminal' : 'Restart Harness',
+ style: DesktopChrome.heading(),
),
- ),
- if (_confirmAgain) ...[
- Padding(
- padding: const EdgeInsets.fromLTRB(14, 0, 14, 8),
- child: Wrap(
- spacing: 12,
- children: [
- terminalPromptButton(
- 'Cancel',
- _cancelAgain,
- focusNode: _cancel,
- ),
- terminalPromptButton(
- 'Restart',
- _restartAgain,
- key: const Key('restart-again-confirm'),
- ),
- ],
- ),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ _attempt.agent?.name ?? widget.agentId,
+ style: DesktopChrome.text(size: 14, medium: true),
),
- ] else if (_attempt.awaitingConfirmation && !_busy && !_closeOnly)
- Padding(
- padding: const EdgeInsets.fromLTRB(14, 0, 14, 8),
- child: Align(
- alignment: Alignment.centerLeft,
- child: terminalPromptButton(
- 'Restart again…',
- _askAgain,
- key: const Key('restart-again'),
- ),
+ if (widget.notifier
+ .stateOf(widget.machineId)
+ ?.machine
+ .displayName
+ case final machine?) ...[
+ const SizedBox(height: 4),
+ Text(machine, style: DesktopChrome.metadata()),
+ ],
+ const SizedBox(height: DesktopChrome.groupGap),
+ if (_confirmAgain)
+ Text(
+ 'Start another restart attempt for this harness?',
+ style: DesktopChrome.text(size: 13),
+ )
+ else ...[
+ Text(
+ _terminal ? 'Starts a fresh shell in the same pane.' : 'Restarts the harness in the same pane and tries to resume its conversation.',
+ style: DesktopChrome.text(size: 13),
),
- ),
- BoxHintStrip(
- message: _busy
- ? 'Restarting…'
- : (_confirmAgain
- ? 'May have already restarted.'
- : (_attempt.awaitingConfirmation && !_closeOnly
- ? 'Restart not confirmed.'
- : null)),
- isError: !_busy && _attempt.awaitingConfirmation,
- hints: [
- if (!_busy)
- BoxHint(
- terminalPromptHint(context, 'picker.accept', 'enter'),
- _confirmAgain
- ? 'select'
- : (_closeOnly
- ? 'close'
- : (_attempt.awaitingConfirmation && !_closeOnly
- ? 'check status'
- : 'retry')),
- onTap: _confirmAgain
- ? null
- : (_closeOnly ? _close : _retry),
+ if (_busy) ...[
+ const SizedBox(height: 8),
+ Text(
+ 'Restart continues if you close this dialog.',
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
),
- if (_confirmAgain)
- BoxHint(
- terminalPromptHint(context, 'picker.complete', 'tab'),
- 'controls',
+ ],
+ if (_error case final error?) ...[
+ const SizedBox(height: 12),
+ DesktopPromptMessage(
+ error,
+ color: uncertain
+ ? grid.AppPalette.warn
+ : Theme.of(context).colorScheme.error,
),
- BoxHint(
- terminalPromptHint(context, 'picker.cancel', 'esc'),
- _confirmAgain ? 'back' : 'close',
- onTap: _confirmAgain ? _cancelAgain : _close,
- ),
+ ],
+ if (_fresh) ...[
+ const SizedBox(height: 12),
+ DesktopPromptMessage(
+ 'Started a new conversation. The previous conversation could not be resumed.',
+ color: grid.AppPalette.warn,
+ ),
+ ],
],
- ),
- ],
+ ],
+ ),
),
),
+ footer: status == null
+ ? null
+ : Semantics(
+ liveRegion: true,
+ child: DesktopPromptMessage(
+ status,
+ color: _busy ? DesktopChrome.muted : grid.AppPalette.warn,
+ ),
+ ),
+ actions: [
+ if (!_confirmAgain && uncertain && !_busy)
+ OutlinedButton(
+ key: const Key('restart-again'),
+ onPressed: _askAgain,
+ child: const Text('Restart again…'),
+ ),
+ Tooltip(
+ message:
+ '$closeLabel · ${terminalPromptHint(context, 'picker.cancel', 'esc')}',
+ child: _closeOnly && !_confirmAgain && !_busy
+ ? FilledButton(onPressed: _close, child: const Text('Close'))
+ : TextButton(
+ focusNode: _confirmAgain ? _cancel : null,
+ onPressed: _confirmAgain ? _cancelAgain : _close,
+ child: Text(closeLabel),
+ ),
+ ),
+ if (_confirmAgain)
+ FilledButton(
+ key: const Key('restart-again-confirm'),
+ onPressed: _restartAgain,
+ style: grid.dangerButtonStyle(),
+ child: const Text('Restart'),
+ )
+ else if (!_busy && !_closeOnly)
+ Tooltip(
+ message:
+ '$actionLabel · ${terminalPromptHint(context, 'picker.accept', 'enter')}',
+ child: FilledButton(
+ key: const Key('agent-restart-retry'),
+ onPressed: _retry,
+ child: Text(actionLabel),
+ ),
+ ),
+ ],
),
);
}
diff --git a/desktop/lib/widgets/resting_section.dart b/desktop/lib/widgets/resting_section.dart
index b2b344e05..9b3e3df24 100644
--- a/desktop/lib/widgets/resting_section.dart
+++ b/desktop/lib/widgets/resting_section.dart
@@ -7,12 +7,15 @@ library;
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../core/models.dart';
-import '../shared/theme/app_type.dart';
+import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
-import '../theme/app_theme.dart';
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
+import 'pane_menu.dart';
import 'resting_model_words.dart';
/// How far a row that will not answer is faded — every computer serving it seems offline. Listed
@@ -72,31 +75,34 @@ class RestingSectionNotes extends StatelessWidget {
final VoidCallback onWake;
@override
- Widget build(BuildContext context) => Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (words.subtitle case final subtitle?)
- Padding(
- padding: EdgeInsets.fromLTRB(inset, 0, inset, 4),
- child: Tooltip(
- message: words.tooltip ?? '',
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (words.subtitle case final subtitle?)
+ Padding(
+ padding: EdgeInsets.fromLTRB(inset, 0, inset, 4),
+ child: Tooltip(
+ message: words.tooltip ?? '',
+ child: Text(subtitle, style: DesktopChrome.metadata()),
+ ),
+ ),
+ // Above the list it is about ("Not answering right now" over the last known models), or in
+ // place of one.
+ if (words.sentence case final sentence?)
+ Padding(
+ padding: EdgeInsets.fromLTRB(inset, 4, inset, 8),
child: Text(
- subtitle,
- style: AppType.caption(color: AppColors.muted),
+ sentence,
+ style: DesktopChrome.text(size: 13, color: DesktopChrome.muted),
),
),
- ),
- // Above the list it is about ("Not answering right now" over the last known models), or in
- // place of one.
- if (words.sentence case final sentence?)
- Padding(
- padding: EdgeInsets.fromLTRB(inset, 4, inset, 8),
- child: Text(sentence, style: AppType.body(color: AppColors.textSoft)),
- ),
- if (words.offerWake) _WakeRow(inset: inset, onTap: onWake),
- ],
- );
+ if (words.offerWake) _WakeRow(inset: inset, onTap: onWake),
+ ],
+ );
+ }
}
/// "Show models" for a resting section with no record: the one way to learn what it serves short
@@ -108,45 +114,44 @@ class _WakeRow extends StatelessWidget {
final VoidCallback onTap;
@override
- Widget build(BuildContext context) => MouseRegion(
- cursor: SystemMouseCursors.click,
- child: InkWell(
- onTap: onTap,
- mouseCursor: SystemMouseCursors.click,
- borderRadius: BorderRadius.circular(8),
- hoverColor: AppColors.rowHover,
- child: Padding(
- padding: EdgeInsets.symmetric(horizontal: inset, vertical: 10),
- child: Row(
- children: [
- SizedBox(
- width: _kWakeIconColumn,
- child: Icon(
- Icons.visibility_outlined,
- size: _kWakeIconSize,
- color: AppColors.textSoft,
- ),
+ Widget build(BuildContext context) => PaneMenuAction(
+ onPressed: onTap,
+ builder: (context, active) => Padding(
+ padding: EdgeInsets.symmetric(horizontal: inset, vertical: 10),
+ child: Row(
+ children: [
+ SizedBox(
+ width: _kWakeIconColumn,
+ child: Icon(
+ AppIcons.eye,
+ size: _kWakeIconSize,
+ color: active ? grid.AppDesktop.onSelection : DesktopChrome.muted,
),
- SizedBox(width: inset),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- kShowModels,
- style: AppType.label(color: AppColors.text),
+ ),
+ SizedBox(width: inset),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ kShowModels,
+ style: DesktopChrome.control(
+ medium: true,
+ color: active ? grid.AppDesktop.onSelection : null,
),
- const SizedBox(height: 2),
- Text(
- kShowModelsWait,
- style: AppType.monoMeta(color: AppColors.mutedStrong),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ kShowModelsWait,
+ style: DesktopChrome.metadata(
+ color: active ? grid.AppDesktop.onSelection : null,
),
- ],
- ),
+ ),
+ ],
),
- ],
- ),
+ ),
+ ],
),
),
);
@@ -163,25 +168,67 @@ Future<bool> confirmSwitchAnyway(
}) async =>
await showAppDialog<bool>(
context: context,
- builder: (context) => AlertDialog(
- title: const Text(kSwitchAnyway),
- content: SizedBox(
- width: 360,
- child: Text(
- offlineNoteSentence(offline.machine, model),
- style: AppType.body(color: AppColors.textSoft, height: 1.4),
- ),
- ),
- actions: [
- TextButton(
- onPressed: () => Navigator.pop(context, false),
- child: const Text('Cancel'),
- ),
- FilledButton(
- onPressed: () => Navigator.pop(context, true),
- child: const Text(kSwitchAnywayAction),
- ),
- ],
- ),
+ builder: (_) => _SwitchAnywayPrompt(model: model, offline: offline),
) ??
false;
+
+class _SwitchAnywayPrompt extends StatefulWidget {
+ const _SwitchAnywayPrompt({required this.model, required this.offline});
+
+ final String model;
+ final GridModelUnavailable offline;
+
+ @override
+ State<_SwitchAnywayPrompt> createState() => _SwitchAnywayPromptState();
+}
+
+class _SwitchAnywayPromptState extends State<_SwitchAnywayPrompt> {
+ final _cancel = FocusNode(debugLabel: 'Cancel model switch');
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _cancel.requestFocus();
+ }
+ });
+ }
+
+ @override
+ void dispose() {
+ _cancel.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return DesktopPromptSurface(
+ body: DesktopPromptScrollBody(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(kSwitchAnyway, style: DesktopChrome.heading()),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ offlineNoteSentence(widget.offline.machine, widget.model),
+ style: DesktopChrome.text(size: 13),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ focusNode: _cancel,
+ onPressed: () => Navigator.pop(context, false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text(kSwitchAnywayAction),
+ ),
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/widgets/session_tail_view.dart b/desktop/lib/widgets/session_tail_view.dart
index 1354bbbdf..a000a99b5 100644
--- a/desktop/lib/widgets/session_tail_view.dart
+++ b/desktop/lib/widgets/session_tail_view.dart
@@ -3,6 +3,12 @@ import 'package:flutter/material.dart';
import '../state/harness_sessions.dart';
import '../state/session_tail.dart';
+/// Use the same under-a-minute wording as the search result's activity label.
+String sessionPreviewAge(DateTime at, DateTime now) =>
+ now.difference(at).inMinutes < 1
+ ? 'now'
+ : '${harnessActivityAge(at, now)} ago';
+
/// A session's latest turns as Cmd-P previews them: bottom-anchored like the
/// agent's own terminal, newest at the bottom, scrolled up for older ones.
/// Scrolling near the top pages in the rows above. The latest ask stays in
@@ -122,8 +128,7 @@ class _SessionTailViewState extends State<SessionTailView> {
Text(
[
'Asked',
- if (lastAsk.at case final at?)
- '${harnessActivityAge(at, when)} ago',
+ if (lastAsk.at case final at?) sessionPreviewAge(at, when),
].join(' · '),
style: muted,
),
@@ -231,7 +236,7 @@ class _TailRowView extends StatelessWidget {
children: [
if (opens) ...[
if (row.at case final at?)
- Text('${harnessActivityAge(at, now)} ago', style: muted),
+ Text(sessionPreviewAge(at, now), style: muted),
Text.rich(
key: askKey,
TextSpan(
diff --git a/desktop/lib/widgets/session_work_dialog.dart b/desktop/lib/widgets/session_work_dialog.dart
index 1de0a1fa6..214c25138 100644
--- a/desktop/lib/widgets/session_work_dialog.dart
+++ b/desktop/lib/widgets/session_work_dialog.dart
@@ -3,17 +3,14 @@ import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import 'package:flutter_svg/flutter_svg.dart';
import 'package:url_launcher/url_launcher.dart';
-import 'package:xterm/xterm.dart' show TerminalTheme;
import '../core/agent_git_context.dart';
import '../core/models.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../terminal/terminal_text.dart';
-import '../terminal/terminal_theme.dart';
-import '../terminal/terminal_theme_store.dart';
-import 'box_chrome.dart';
-import 'terminal_text_action.dart';
+import '../shared/theme/pull_request_icon.dart';
+import 'desktop_chrome.dart';
/// Inspection only. This surface never sends terminal input or mutates a checkout.
class SessionWorkDialog extends StatefulWidget {
@@ -101,6 +98,18 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
if (mounted && !opened) setState(() => _error = 'Could not open GitHub');
}
+ void _page(int direction) {
+ final scroll = _branches ? _branchScroll : _prScroll;
+ if (!scroll.hasClients) return;
+ final position = scroll.position;
+ scroll.jumpTo(
+ (position.pixels + direction * position.viewportDimension * .9).clamp(
+ position.minScrollExtent,
+ position.maxScrollExtent,
+ ),
+ );
+ }
+
@override
void dispose() {
_revision++;
@@ -114,126 +123,94 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- return ValueListenableBuilder(
- valueListenable: terminalThemeStore,
- builder: (context, _, _) {
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
- final cell = terminalCellSizeOf(context);
- final style = terminalContentStyle(color: theme.foreground);
- final muted = style.copyWith(
- color: theme.foreground.withValues(alpha: .65),
- );
- final data = _data;
- final branches = [...?data?.branchRows]
- ..sort((a, b) {
- final checked = (b.checkedOut ? 1 : 0) - (a.checkedOut ? 1 : 0);
- return checked != 0 ? checked : a.branch.compareTo(b.branch);
- });
- final prs = [...?data?.pullRequests];
- int rank(AgentWorkPr pr) => switch (pr.state) {
- 'Open' || 'Draft' => 0,
- 'Merged' || 'Closed' => 2,
- _ => 1,
- };
- prs.sort((a, b) {
- final state = rank(a).compareTo(rank(b));
- final time = (pullRequestTime(b) ?? b.at).compareTo(
- pullRequestTime(a) ?? a.at,
- );
- return state != 0
- ? state
- : time != 0
- ? time
- : a.url.toString().compareTo(b.url.toString());
- });
- String repoName(String repository) =>
- repository.replaceFirst(RegExp(r'^github\.com/'), '');
- final repositories = {
- ...branches.map(
- (b) => b.repository == null ? null : repoName(b.repository!),
- ),
- ...prs.map((pr) => pr.url.pathSegments.take(2).join('/')),
- };
- final repository = repositories.length == 1
- ? repositories.single
- : null;
- final items = _branches ? branches.length : prs.length;
- final prIndices = {
- for (var i = 0; i < prs.length; i++) ValueKey('pr-${prs[i].url}'): i,
- };
- Widget line(String value, {bool dim = false, String? tooltip}) =>
- SizedBox(
- height: cell.height,
- child: Tooltip(
- message: tooltip ?? value,
- child: Text(
- value,
- style: dim ? muted : style,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- );
- Widget tab(String label, bool branches) {
- final selected = _branches == branches;
- return Semantics(
- selected: selected,
- child: TextButton(
- key: ValueKey(branches ? 'git-branches-tab' : 'git-prs-tab'),
- focusNode: branches ? _branchTab : _prTab,
- onPressed: () => setState(() => _branches = branches),
- style: _actionStyle(theme).copyWith(
- foregroundColor: WidgetStatePropertyAll(
- selected ? theme.foreground : muted.color,
- ),
- ),
- child: SizedBox(
- height: cell.height,
- child: Text(
- label,
- style: (selected ? style : muted).copyWith(
- decoration: selected ? TextDecoration.underline : null,
- ),
- ),
- ),
- ),
- );
- }
+ final data = _data;
+ final branches = [...?data?.branchRows]
+ ..sort((a, b) {
+ final checked = (b.checkedOut ? 1 : 0) - (a.checkedOut ? 1 : 0);
+ return checked != 0 ? checked : a.branch.compareTo(b.branch);
+ });
+ final prs = [...?data?.pullRequests];
+ int rank(AgentWorkPr pr) => switch (pr.state) {
+ 'Open' || 'Draft' => 0,
+ 'Merged' || 'Closed' => 2,
+ _ => 1,
+ };
+ prs.sort((a, b) {
+ final state = rank(a).compareTo(rank(b));
+ final time = (pullRequestTime(b) ?? b.at).compareTo(
+ pullRequestTime(a) ?? a.at,
+ );
+ return state != 0
+ ? state
+ : time != 0
+ ? time
+ : a.url.toString().compareTo(b.url.toString());
+ });
+ String repoName(String repository) =>
+ repository.replaceFirst(RegExp(r'^github\.com/'), '');
+ final repositories = {
+ ...branches.map(
+ (b) => b.repository == null ? null : repoName(b.repository!),
+ ),
+ ...prs.map((pr) => pr.url.pathSegments.take(2).join('/')),
+ };
+ final repository = repositories.length == 1 ? repositories.single : null;
+ final items = _branches ? branches.length : prs.length;
+ final prIndices = {
+ for (var i = 0; i < prs.length; i++) ValueKey('pr-${prs[i].url}'): i,
+ };
+ final status = !widget.online
+ ? 'Offline'
+ : _error ??
+ (data?.state == 'unavailable' || data?.state == 'uncertain'
+ ? 'Git unavailable'
+ : _unavailable.isNotEmpty
+ ? 'GitHub unavailable'
+ : null);
+ Widget tab(String label, bool branches) => DesktopPill(
+ key: ValueKey(branches ? 'git-branches-tab' : 'git-prs-tab'),
+ label: label,
+ selected: _branches == branches,
+ focusNode: branches ? _branchTab : _prTab,
+ onPressed: () => setState(() => _branches = branches),
+ );
- return Dialog(
- backgroundColor: theme.background,
- elevation: 0,
- insetPadding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height * 2,
- ),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(kTerminalCornerRadius),
- side: terminalPaneBorder(focused: true),
+ return DesktopChrome(
+ child: Dialog(
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ insetPadding: const EdgeInsets.all(16),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: math.max(
+ 0,
+ math.min(MediaQuery.sizeOf(context).height - 32, 620),
+ ),
),
- child: ConstrainedBox(
+ child: SizedBox(
key: const ValueKey('work-dialog-surface'),
- constraints: BoxConstraints(
- maxHeight: math.max(
- 0,
- math.min(
- MediaQuery.sizeOf(context).height - cell.height * 4,
- cell.height * 28,
- ),
- ),
- ),
- child: SizedBox(
- width: cell.width * 92,
+ width: 720,
+ child: DesktopDialogSurface(
child: Padding(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height,
- ),
+ padding: const EdgeInsets.all(24),
child: Focus(
+ autofocus: true,
onKeyEvent: (node, event) {
+ final keys = HardwareKeyboard.instance;
+ if ((event is KeyDownEvent || event is KeyRepeatEvent) &&
+ !keys.isAltPressed &&
+ !keys.isControlPressed &&
+ !keys.isMetaPressed &&
+ !keys.isShiftPressed &&
+ (event.logicalKey == LogicalKeyboardKey.pageDown ||
+ event.logicalKey == LogicalKeyboardKey.pageUp)) {
+ _page(
+ event.logicalKey == LogicalKeyboardKey.pageDown
+ ? 1
+ : -1,
+ );
+ return KeyEventResult.handled;
+ }
if (event is! KeyDownEvent) return KeyEventResult.ignored;
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
FocusScope.of(context).nextFocus();
@@ -247,11 +224,33 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
},
child: Column(
mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- line(widget.agent.displayName),
- if (repository != null) line(repository, dim: true),
- SizedBox(height: cell.height),
+ Semantics(
+ header: true,
+ child: Tooltip(
+ message: widget.agent.displayName,
+ child: Text(
+ widget.agent.displayName,
+ style: DesktopChrome.heading(),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ),
+ if (repository != null) ...[
+ const SizedBox(height: 4),
+ Tooltip(
+ message: repository,
+ child: Text(
+ repository,
+ style: DesktopChrome.metadata(),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ],
+ const SizedBox(height: 16),
Focus(
onKeyEvent: (node, event) {
if (event is! KeyDownEvent ||
@@ -267,29 +266,50 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
(branches ? _branchTab : _prTab).requestFocus();
return KeyEventResult.handled;
},
- child: LayoutBuilder(
- builder: (context, constraints) => Wrap(
- spacing: cell.width * 3,
- children: [
- tab(
- '${constraints.maxWidth < cell.width * 36 ? 'PRs' : 'Pull requests'} (${prs.length})',
- false,
- ),
- tab('Branches (${branches.length})', true),
- ],
- ),
+ child: Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ tab(
+ data == null
+ ? 'Pull requests'
+ : 'Pull requests (${prs.length})',
+ false,
+ ),
+ tab(
+ data == null
+ ? 'Branches'
+ : 'Branches (${branches.length})',
+ true,
+ ),
+ ],
),
),
- SizedBox(height: cell.height),
+ const SizedBox(height: 12),
+ Divider(
+ height: 1,
+ thickness: 1,
+ color: DesktopChrome.rim,
+ ),
+ const SizedBox(height: 8),
Flexible(
child: items == 0
- ? line(
- _loading
- ? 'Loading…'
- : _branches
- ? 'No branches'
- : 'No pull requests',
- dim: true,
+ ? Padding(
+ padding: const EdgeInsets.symmetric(
+ vertical: 20,
+ ),
+ child: Text(
+ _loading
+ ? 'Loading…'
+ : data == null
+ ? 'Work history is unavailable'
+ : _branches
+ ? 'No branches'
+ : 'No pull requests',
+ style: DesktopChrome.control(
+ color: DesktopChrome.muted,
+ ),
+ ),
)
: ListView.builder(
key: ValueKey(
@@ -301,8 +321,8 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
? _branchScroll
: _prScroll,
shrinkWrap: true,
+ padding: EdgeInsets.zero,
itemCount: items,
- itemExtent: cell.height * (_branches ? 2 : 3),
findChildIndexCallback: _branches
? null
: (key) => prIndices[key],
@@ -311,9 +331,6 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
final branch = branches[index];
return _BranchRow(
branch: branch,
- cell: cell,
- style: style,
- muted: muted,
repository: repository == null
? branch.repository
: null,
@@ -323,10 +340,6 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
return _PullRequestRow(
key: ValueKey('pr-${pr.url}'),
pr: pr,
- cell: cell,
- theme: theme,
- style: style,
- muted: muted,
showRepository: repository == null,
unavailable: _unavailable.contains(
pr.url.toString(),
@@ -336,50 +349,60 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
},
),
),
- if (_nextOffset != null && widget.online)
- TerminalTextAction(
- label: 'Load more',
- padding: EdgeInsets.zero,
- onPressed: _loading
- ? null
- : () => unawaited(_refresh(_nextOffset!)),
- ),
- if (!widget.online)
- line('Offline', dim: true)
- else if (_error != null)
- line(_error!, dim: true)
- else if (data?.state == 'unavailable' ||
- data?.state == 'uncertain')
- line('Git unavailable', dim: true)
- else if (_unavailable.isNotEmpty)
- line('GitHub unavailable', dim: true),
- if (data?.truncated == true)
- line(
- 'Partial history',
- dim: true,
- tooltip: 'Only recorded branches and pull requests are available.',
+ if (_nextOffset != null && widget.online) ...[
+ const SizedBox(height: 8),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: DesktopPill(
+ label: 'Load more',
+ onPressed: _loading
+ ? null
+ : () => unawaited(_refresh(_nextOffset!)),
+ ),
),
- SizedBox(height: cell.height),
- SizedBox(
- width: double.infinity,
- child: Wrap(
- alignment: WrapAlignment.spaceBetween,
- children: [
- if (widget.online)
- TerminalTextAction(
- label: _loading ? 'Refreshing…' : 'Refresh',
- padding: EdgeInsets.zero,
- onPressed: _loading
- ? null
- : () => unawaited(_refresh(0)),
- ),
- TerminalTextAction(
- label: 'Close',
- padding: EdgeInsets.zero,
- onPressed: () => Navigator.of(context).pop(),
+ ],
+ if (status != null) ...[
+ const SizedBox(height: 12),
+ Semantics(
+ liveRegion: _error != null,
+ child: Text(
+ status,
+ style: DesktopChrome.control(
+ color: widget.online && _error != null
+ ? Theme.of(context).colorScheme.error
+ : DesktopChrome.muted,
),
- ],
+ ),
+ ),
+ ],
+ if (data?.truncated == true) ...[
+ const SizedBox(height: 8),
+ Tooltip(
+ message: 'Only recorded branches and pull requests are available.',
+ child: Text(
+ 'Partial history',
+ style: DesktopChrome.metadata(),
+ ),
),
+ ],
+ const SizedBox(height: 16),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ if (widget.online)
+ DesktopPill(
+ label: _loading ? 'Refreshing…' : 'Refresh',
+ onPressed: _loading
+ ? null
+ : () => unawaited(_refresh(0)),
+ )
+ else
+ const SizedBox.shrink(),
+ DesktopPill(
+ label: 'Close',
+ onPressed: () => Navigator.of(context).pop(),
+ ),
+ ],
),
],
),
@@ -387,52 +410,21 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
),
),
),
- );
- },
+ ),
+ ),
);
}
}
-ButtonStyle _actionStyle(TerminalTheme theme) =>
- TextButton.styleFrom(
- alignment: Alignment.centerLeft,
- foregroundColor: theme.foreground,
- padding: EdgeInsets.zero,
- minimumSize: Size.zero,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- shape: const RoundedRectangleBorder(),
- splashFactory: NoSplash.splashFactory,
- ).copyWith(
- overlayColor: WidgetStateProperty.resolveWith(
- (states) =>
- states.any(
- {
- WidgetState.focused,
- WidgetState.hovered,
- WidgetState.pressed,
- }.contains,
- )
- ? theme.selection
- : Colors.transparent,
- ),
- );
-
class _PullRequestRow extends StatelessWidget {
const _PullRequestRow({
super.key,
required this.pr,
- required this.cell,
- required this.theme,
- required this.style,
- required this.muted,
required this.showRepository,
required this.unavailable,
required this.onPressed,
});
final AgentWorkPr pr;
- final Size cell;
- final TerminalTheme theme;
- final TextStyle style, muted;
final bool showRepository, unavailable;
final VoidCallback onPressed;
@@ -460,121 +452,145 @@ class _PullRequestRow extends StatelessWidget {
if (pr.checkedAt != null) 'Checked ${localWorkTime(pr.checkedAt!)}',
'Open on GitHub',
].join('\n');
- final color = switch (pr.state) {
- 'Open' => theme.green,
- 'Merged' => theme.brightMagenta,
- 'Closed' => theme.brightRed,
- _ => muted.color,
- };
+ final color = pullRequestIconColor(
+ state,
+ null,
+ brightness: grid.AppTheme.brightness.value,
+ );
+ final highContrast = MediaQuery.highContrastOf(context);
Widget text(String value, TextStyle style) =>
Text(value, style: style, maxLines: 1, overflow: TextOverflow.ellipsis);
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- SizedBox(
- height: cell.height,
- child: Tooltip(
- message: details,
- child: TextButton(
- key: ValueKey('work-pr-${pr.url}'),
- onPressed: onPressed,
- style: _actionStyle(theme),
- child: Semantics(
- label: details.replaceAll('\n', ' · '),
- excludeSemantics: true,
- child: Row(
- children: [
- Expanded(child: text(title, style)),
- SizedBox(width: cell.width * 2),
- text(state, style.copyWith(color: color)),
- ],
+ return Tooltip(
+ message: details,
+ child: TextButton(
+ key: ValueKey('work-pr-${pr.url}'),
+ onPressed: onPressed,
+ style:
+ TextButton.styleFrom(
+ alignment: Alignment.centerLeft,
+ foregroundColor: DesktopChrome.foreground,
+ backgroundColor: Colors.transparent,
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
+ minimumSize: const Size(0, 48),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
),
),
- ),
- ),
- ),
- SizedBox(
- height: cell.height,
- child: Tooltip(
- message: details,
- child: ExcludeSemantics(
- child: MouseRegion(
- cursor: SystemMouseCursors.click,
- child: GestureDetector(
- onTap: onPressed,
- behavior: HitTestBehavior.opaque,
- child: Row(
- children: [
- Expanded(child: text(metadata, muted)),
- if (date != null) ...[
- SizedBox(width: cell.width * 2),
- text(date, muted),
- ],
- ],
- ),
+ splashFactory: NoSplash.splashFactory,
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? (highContrast
+ ? DesktopChrome.accent
+ : DesktopChrome.focusRing)
+ : Colors.transparent,
),
),
+ overlayColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.pressed)
+ ? DesktopChrome.foreground.withValues(alpha: .12)
+ : states.contains(WidgetState.hovered)
+ ? DesktopChrome.foreground.withValues(
+ alpha: highContrast ? .10 : .05,
+ )
+ : Colors.transparent,
+ ),
),
+ child: Semantics(
+ label: details.replaceAll('\n', ' · '),
+ excludeSemantics: true,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: text(title, DesktopChrome.control(medium: true)),
+ ),
+ const SizedBox(width: 12),
+ SvgPicture.asset(
+ pullRequestIconAsset(state),
+ width: 16,
+ height: 16,
+ colorFilter: ColorFilter.mode(color, BlendMode.srcIn),
+ ),
+ const SizedBox(width: 6),
+ text(
+ state,
+ DesktopChrome.metadata(color: DesktopChrome.foreground),
+ ),
+ ],
+ ),
+ if (metadata.isNotEmpty || date != null) ...[
+ const SizedBox(height: 4),
+ Row(
+ children: [
+ Expanded(child: text(metadata, DesktopChrome.metadata())),
+ if (date != null) ...[
+ const SizedBox(width: 12),
+ text(date, DesktopChrome.metadata()),
+ ],
+ ],
+ ),
+ ],
+ ],
),
),
- ],
+ ),
);
}
}
class _BranchRow extends StatelessWidget {
- const _BranchRow({
- required this.branch,
- required this.cell,
- required this.style,
- required this.muted,
- required this.repository,
- });
+ const _BranchRow({required this.branch, required this.repository});
final AgentBranchRow branch;
- final Size cell;
- final TextStyle style, muted;
final String? repository;
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
- final compact = constraints.maxWidth < cell.width * 45;
+ final compact =
+ constraints.maxWidth < MediaQuery.textScalerOf(context).scale(400);
final status = branch.checkedOut ? 'Checked out' : null;
return Tooltip(
message: [branch.branch, ?repository, ?status].join('\n'),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- SizedBox(
- height: cell.height,
- child: Row(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
children: [
Expanded(
child: Text(
branch.branch,
- style: style,
+ style: DesktopChrome.control(medium: true),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
if (!compact && status != null) ...[
- SizedBox(width: cell.width * 2),
- Text(status, style: muted),
+ const SizedBox(width: 12),
+ Text(status, style: DesktopChrome.metadata()),
],
],
),
- ),
- if (repository != null || compact && status != null)
- SizedBox(
- height: cell.height,
- child: Text(
+ if (repository != null || compact && status != null) ...[
+ const SizedBox(height: 4),
+ Text(
[?repository, if (compact) ?status].join(' · '),
- style: muted,
+ style: DesktopChrome.metadata(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
- ),
- ],
+ ],
+ ],
+ ),
),
);
},
diff --git a/desktop/lib/widgets/status_line.dart b/desktop/lib/widgets/status_line.dart
index ae3a8d579..fd9a2676c 100644
--- a/desktop/lib/widgets/status_line.dart
+++ b/desktop/lib/widgets/status_line.dart
@@ -21,6 +21,8 @@ class StatusLine extends StatelessWidget {
this.workspaceBar = false,
this.emphasized = false,
this.middleEllipsis = false,
+ this.surfaceBackground,
+ this.monochromeColor,
});
final StatusLineParts parts;
final bool color;
@@ -33,6 +35,14 @@ class StatusLine extends StatelessWidget {
final bool emphasized;
final bool middleEllipsis;
+ /// Set only when the status is displayed outside its terminal surface.
+ final Color? surfaceBackground;
+
+ /// Secondary context keeps the chosen wording, fields, and status face, but
+ /// uses one ink without colored segment backgrounds. The focused workspace
+ /// footer does not set this and retains its full customized appearance.
+ final Color? monochromeColor;
+
@override
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
@@ -44,18 +54,33 @@ class StatusLine extends StatelessWidget {
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
+ final foreground =
+ monochromeColor ??
+ (surfaceBackground == null
+ ? theme.foreground
+ : statusLineInkOnSurface(theme.foreground, surfaceBackground!));
final style = workspaceBar
- ? workspaceBarTextStyle(
- color: theme.foreground,
- emphasized: emphasized,
- )
- : terminalContentStyle(color: theme.foreground);
- final segments = statusLinePaintSegments(
+ ? workspaceBarTextStyle(color: foreground, emphasized: emphasized)
+ : terminalContentStyle(color: foreground);
+ final resolvedSegments = statusLinePaintSegments(
parts,
theme,
color: color,
segmentOffset: segmentOffset,
+ surfaceBackground: surfaceBackground,
);
+ final segments = monochromeColor == null
+ ? resolvedSegments
+ : [
+ for (final (index, segment) in resolvedSegments.indexed)
+ StatusLinePaintSegment(
+ '${parts.style.segmented && index > 0 ? ' ' : ''}'
+ '${segment.text}',
+ monochromeColor!,
+ null,
+ branchSymbol: segment.branchSymbol,
+ ),
+ ];
final cell = workspaceBar
? workspaceBarCellSizeOf(context)
: terminalCellSizeOf(context);
@@ -63,7 +88,7 @@ class StatusLine extends StatelessWidget {
double measure(String text) => workspaceBar
? workspaceBarTextSizeOf(context, text).width
: _measure(text, style, scaler);
- if (!parts.style.segmented) {
+ if (!parts.style.segmented || monochromeColor != null) {
Widget line(List<StatusLinePaintSegment> visible) => Text.rich(
TextSpan(
children: [
diff --git a/desktop/lib/widgets/swarm_attention.dart b/desktop/lib/widgets/swarm_attention.dart
index 02ce3a047..eded38772 100644
--- a/desktop/lib/widgets/swarm_attention.dart
+++ b/desktop/lib/widgets/swarm_attention.dart
@@ -1,5 +1,6 @@
import 'swarm_search_field.dart';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/theme/app_type.dart';
@@ -160,7 +161,7 @@ class _SwarmAttentionState extends State<_SwarmAttention> {
IconButton(
tooltip: 'Close notifications',
onPressed: () => Navigator.pop(context),
- icon: const Icon(Icons.close, size: 18),
+ icon: const Icon(AppIcons.close, size: 18),
),
],
),
diff --git a/desktop/lib/widgets/swarm_command_picker.dart b/desktop/lib/widgets/swarm_command_picker.dart
index 3c1822bd0..d2dbd9542 100644
--- a/desktop/lib/widgets/swarm_command_picker.dart
+++ b/desktop/lib/widgets/swarm_command_picker.dart
@@ -1,12 +1,12 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/swarm_navigation.dart';
import '../state/swarm_search.dart';
-import '../terminal/terminal_text.dart';
-import '../terminal/terminal_theme.dart';
-import '../terminal/terminal_theme_store.dart';
-import 'box_chrome.dart';
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import 'desktop_chrome.dart';
import 'swarm_search_input.dart';
import 'swarm_switcher.dart';
@@ -43,62 +43,126 @@ class _SwarmCommandPickerState extends State<SwarmCommandPicker> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
return ListenableBuilder(
- listenable: Listenable.merge([
- terminalFontStore,
- grid.AppTheme.palette,
- terminalThemeStore,
- ]),
+ listenable: widget.search,
builder: (context, _) {
- final cell = terminalCellSizeOf(context);
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
- return Dialog(
- key: const ValueKey('resource-command-picker'),
- alignment: const Alignment(0, -0.12),
- insetPadding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height * 2,
- ),
- elevation: 0,
- surfaceTintColor: Colors.transparent,
- clipBehavior: Clip.antiAlias,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(kTerminalCornerRadius),
- side: terminalPaneBorder(focused: true),
- ),
- backgroundColor: theme.background,
- child: TextSelectionTheme(
- data: TextSelectionThemeData(selectionColor: theme.selection),
- child: SizedBox(
- width: cell.width * 80,
- height: cell.height * 24,
- child: SwarmSearchKeys(
- search: widget.search,
- editing: _query,
- onChoose: _choose,
- onClose: _close,
- onRefocus: _focus.requestFocus,
- child: SwarmSearchResults(
+ return DesktopChrome(
+ child: Dialog(
+ key: const ValueKey('resource-command-picker'),
+ alignment: const Alignment(0, -0.12),
+ insetPadding: const EdgeInsets.symmetric(
+ horizontal: 20,
+ vertical: 24,
+ ),
+ elevation: grid.AppDesktop.dialogElevation,
+ shadowColor: grid.AppDesktop.shadow,
+ surfaceTintColor: Colors.transparent,
+ clipBehavior: Clip.antiAlias,
+ shape: DesktopChrome.shape(),
+ backgroundColor: DesktopChrome.surface,
+ child: TextSelectionTheme(
+ data: TextSelectionThemeData(
+ selectionColor: DesktopChrome.selection,
+ ),
+ child: SizedBox(
+ width: 620,
+ height: 440,
+ child: SwarmSearchKeys(
+ desktop: true,
search: widget.search,
+ editing: _query,
onChoose: _choose,
+ onClose: _close,
onRefocus: _focus.requestFocus,
- terminal: true,
- bios: true,
- header: SwarmSearchInput(
- inputKey: const ValueKey('resource-command-input'),
- controller: _query,
- focusNode: _focus,
- search: widget.search,
- onClose: _close,
- onChanged: widget.search.setQuery,
- hintText: 'Search actions',
- prompt: '>',
- terminal: true,
- bios: true,
+ child: Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 8, 12, 8),
+ child: Row(
+ children: [
+ Icon(
+ AppIcons.search,
+ size: 20,
+ color: DesktopChrome.muted,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: SwarmSearchInput(
+ inputKey: const ValueKey(
+ 'resource-command-input',
+ ),
+ controller: _query,
+ focusNode: _focus,
+ search: widget.search,
+ onClose: _close,
+ onChanged: widget.search.setQuery,
+ hintText: 'Search actions',
+ ),
+ ),
+ ExcludeFocus(
+ child: IconButton(
+ key: const ValueKey('resource-command-close'),
+ tooltip: 'Close actions',
+ onPressed: _close,
+ icon: const Icon(AppIcons.close, size: 18),
+ ),
+ ),
+ ],
+ ),
+ ),
+ Divider(height: 1, color: DesktopChrome.rim),
+ Expanded(
+ child: SwarmSearchResults(
+ search: widget.search,
+ onChoose: _choose,
+ onRefocus: _focus.requestFocus,
+ showPreview: false,
+ ),
+ ),
+ Divider(height: 1, color: DesktopChrome.rim),
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 18,
+ vertical: 12,
+ ),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: effectiveCommandHint(
+ context,
+ 'picker.accept',
+ contextKind: KeymapContext.picker,
+ ),
+ style: grid.AppType.monoMeta(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ const TextSpan(text: ' Run action '),
+ TextSpan(
+ text: effectiveCommandHint(
+ context,
+ 'picker.cancel',
+ contextKind: KeymapContext.picker,
+ ),
+ style: grid.AppType.monoMeta(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ const TextSpan(text: ' Back'),
+ ],
+ ),
+ style: DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ),
+ ),
+ ],
),
),
),
diff --git a/desktop/lib/widgets/swarm_dialogs.dart b/desktop/lib/widgets/swarm_dialogs.dart
index c56a21562..8af2ebc55 100644
--- a/desktop/lib/widgets/swarm_dialogs.dart
+++ b/desktop/lib/widgets/swarm_dialogs.dart
@@ -1,10 +1,12 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/theme/app_type.dart';
+import '../shared/theme/app_theme.dart' show AppPalette;
+
import '../core/desktop_window.dart';
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/app_select_field.dart';
@@ -14,6 +16,7 @@ import '../state/swarm_catalog.dart';
import 'machines_panel.dart';
import 'remote_folder_picker.dart';
import 'clone_repository_dialog.dart';
+import 'desktop_chrome.dart';
import 'terminal_name_prompt.dart';
import 'terminal_prompt.dart';
@@ -25,7 +28,7 @@ Future<String?> showSwarmRenameDialog(
context,
keymap: keymap,
builder: (_) => TerminalNamePrompt(
- title: 'Rename Swarm',
+ title: 'Rename Tab',
name: name,
fieldKey: const Key('tab-rename-input'),
fieldLabel: 'Swarm name',
@@ -89,6 +92,7 @@ class _ProjectDialogState extends State<_ProjectDialog> {
notifier: widget.notifier,
machineId: id,
initialPath: path,
+ desktop: true,
);
if (!mounted || revision != _machineRevision) return;
setState(() {
@@ -126,100 +130,114 @@ class _ProjectDialogState extends State<_ProjectDialog> {
@override
Widget build(BuildContext context) {
- return AlertDialog(
- title: const Text('Add project'),
- content: SizedBox(
- width: 460,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- 'Choose an existing working folder.',
- style: AppType.body(
- color: grid.AppTheme.pick(
- grid.AppPalette.textSecondary,
- Colors.white60,
- ),
- ),
- ),
- const SizedBox(height: 20),
- if (machineId != null)
- AppSelectField<String>(
- value: machineId!,
- options: [
- for (final machine in widget.notifier.machineStates.values)
- SelectOption(
- value: machine.machine.machineId,
- label: machine.isLocalMachine
- ? 'This computer'
- : machine.machine.displayName,
+ return Dialog(
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ insetPadding: const EdgeInsets.all(24),
+ child: SizedBox(
+ width: 508,
+ child: DesktopDialogSurface(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text('Add project', style: DesktopChrome.heading()),
+ const SizedBox(height: 20),
+ Flexible(
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Choose an existing working folder.',
+ style: AppType.body(color: AppPalette.textSecondary),
+ ),
+ const SizedBox(height: 20),
+ if (machineId != null)
+ AppSelectField<String>(
+ value: machineId!,
+ options: [
+ for (final machine
+ in widget.notifier.machineStates.values)
+ SelectOption(
+ value: machine.machine.machineId,
+ label: machine.isLocalMachine
+ ? 'This computer'
+ : machine.machine.displayName,
+ ),
+ ],
+ onChanged: (value) => setState(() {
+ if (machineId == value) return;
+ _machineRevision++;
+ machineId = value;
+ path = null;
+ error = null;
+ }),
+ ),
+ const SizedBox(height: 16),
+ OutlinedButton.icon(
+ onPressed: machineId == null || picking
+ ? null
+ : browse,
+ icon: const Icon(AppIcons.folderOpen, size: 17),
+ label: Text(
+ path ?? 'Choose folder',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ if (widget.notifier
+ .stateOf(machineId ?? '')
+ ?.isLocalMachine ==
+ true)
+ TextButton(
+ onPressed: picking ? null : clone,
+ child: const Text('Clone repository…'),
+ ),
+ if (error != null)
+ Text(
+ error!,
+ style: AppType.body(
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ],
),
- ],
- onChanged: (value) => setState(() {
- if (machineId == value) return;
- _machineRevision++;
- machineId = value;
- path = null;
- error = null;
- }),
- ),
- const SizedBox(height: 16),
- OutlinedButton.icon(
- onPressed: machineId == null || picking ? null : browse,
- icon: const Icon(Icons.folder_open, size: 17),
- label: Text(
- path ?? 'Choose folder',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- if (widget.notifier.stateOf(machineId ?? '')?.isLocalMachine ==
- true)
- TextButton(
- onPressed: picking ? null : clone,
- style: TextButton.styleFrom(
- foregroundColor: grid.AppTheme.pick(
- grid.AppPalette.textSecondary,
- Colors.white70,
),
),
- child: const Text('Clone repository…'),
- ),
- if (error != null)
- // Pale orange only reads on a dark dialog; a light one takes
- // the deep warning ink.
- Text(
- error!,
- style: AppType.body(
- color: grid.AppTheme.pick(
- grid.AppPalette.warn,
- Colors.orangeAccent,
- ),
+ const SizedBox(height: 24),
+ OverflowBar(
+ alignment: MainAxisAlignment.end,
+ spacing: 8,
+ overflowSpacing: 8,
+ children: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: path == null || folderName.isEmpty || picking
+ ? null
+ : () => Navigator.pop(
+ context,
+ SavedSwarmProject(
+ machineId: machineId!,
+ path: path!,
+ name: folderName,
+ ),
+ ),
+ child: const Text('Add project'),
+ ),
+ ],
),
- ),
- ],
+ ],
+ ),
+ ),
),
),
- actions: [
- TextButton(
- onPressed: () => Navigator.pop(context),
- child: const Text('Cancel'),
- ),
- FilledButton(
- onPressed: path == null || folderName.isEmpty || picking
- ? null
- : () => Navigator.pop(
- context,
- SavedSwarmProject(
- machineId: machineId!,
- path: path!,
- name: folderName,
- ),
- ),
- child: const Text('Add project'),
- ),
- ],
);
}
}
diff --git a/desktop/lib/widgets/swarm_icon.dart b/desktop/lib/widgets/swarm_icon.dart
index 9028036ec..022b8aea0 100644
--- a/desktop/lib/widgets/swarm_icon.dart
+++ b/desktop/lib/widgets/swarm_icon.dart
@@ -1,4 +1,6 @@
-import 'package:flutter/cupertino.dart';
+import 'package:flutter/widgets.dart';
+
+import '../shared/theme/app_icons.dart';
/// Four agents sharing one workspace. Native menus use the corresponding
/// `square.grid.2x2` symbol in SwarmTitlebar.swift.
@@ -10,5 +12,5 @@ class SwarmIcon extends StatelessWidget {
@override
Widget build(BuildContext context) =>
- Icon(CupertinoIcons.square_grid_2x2, size: size, color: color);
+ Icon(AppIcons.layoutGrid, size: size, color: color);
}
diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dart
index c08e26a50..cf175a4d8 100644
--- a/desktop/lib/widgets/swarm_resource_preview.dart
+++ b/desktop/lib/widgets/swarm_resource_preview.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -25,6 +26,7 @@ import 'api_picker_form.dart';
import 'swarm_search_preview.dart';
import 'swarm_preview_scroll.dart';
import 'terminal_text_action.dart';
+import 'desktop_chrome.dart';
import 'key_hints.dart';
const resourcePickerCommands = {
@@ -81,6 +83,7 @@ class SwarmResourcePreview extends StatefulWidget {
required this.onRefocus,
required this.onModalChanged,
required this.onCommands,
+ this.resourcePollInterval,
this.onViewMachine,
});
final SwarmSearchController search;
@@ -90,6 +93,10 @@ class SwarmResourcePreview extends StatefulWidget {
final ValueChanged<bool> onModalChanged;
final VoidCallback onCommands;
+ /// Override the resource refresh cadence for an isolated fixture. Omitted
+ /// intervals poll every ten seconds in the app and stay disabled in tests.
+ final Duration? resourcePollInterval;
+
/// Where View takes a machine instead of scoping the picker to it, when
/// the host composition asks for that ([WorkspaceChrome.viewMachineCloses]).
final ValueChanged<String>? onViewMachine;
@@ -171,16 +178,26 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
widget.onRefocus();
}
- void _focusActions({bool last = false}) {
+ void _focusActions() {
final selectedId = row?.id;
if (selectedId == null) return;
- void focus() {
+ void focus({bool afterBuild = false}) {
if (!mounted || row?.id != selectedId) return;
final actions = _visibleActions()
.where((a) => a.onPressed != null)
.toList();
- final action = last ? actions.lastOrNull : actions.firstOrNull;
+ final action = actions.firstOrNull;
final node = action == null ? _actionFocus : _buttonFocus[action.command];
+ // A selection can arrive immediately before Return, before its preview
+ // has built these buttons. Retry once after that frame rather than
+ // focusing an unattached scope and losing the first keyboard action.
+ if (!afterBuild && action != null && node?.context == null) {
+ WidgetsBinding.instance.addPostFrameCallback(
+ (_) => focus(afterBuild: true),
+ );
+ WidgetsBinding.instance.ensureVisualUpdate();
+ return;
+ }
(node ?? _actionFocus).requestFocus();
if (node?.context case final context?) Scrollable.ensureVisible(context);
}
@@ -193,16 +210,12 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
}
}
- bool _traverseActions(bool forward, {bool stay = false}) {
+ bool _traverseActions(bool forward) {
if (row == null ||
widget.search.showsTypeHints ||
!widget.search.supportsPreview) {
return false;
}
- if (!_actionFocus.hasFocus) {
- _focusActions(last: !forward);
- return true;
- }
final actions = _visibleActions()
.where((a) => a.onPressed != null)
.toList();
@@ -212,9 +225,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
final next = index < 0
? (forward ? 0 : actions.length - 1)
: index + (forward ? 1 : -1);
- if (next < 0 || next >= actions.length) {
- if (!stay) widget.onRefocus();
- } else {
+ if (next >= 0 && next < actions.length) {
final node = _buttonFocus[actions[next].command]!;
node.requestFocus();
if (node.context case final context?) Scrollable.ensureVisible(context);
@@ -266,9 +277,12 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
widget.controls.dispatch = _dispatch;
widget.controls.commands = _commands;
widget.search.addListener(_searchChanged);
- if (!kUnderTest) {
+ final interval =
+ widget.resourcePollInterval ??
+ (kUnderTest ? null : const Duration(seconds: 10));
+ if (interval != null) {
_resourceTimer = Timer.periodic(
- const Duration(seconds: 10),
+ interval,
(_) => unawaited(_readResources()),
);
}
@@ -277,12 +291,24 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
SwarmPreviewScrollController _scrollController() =>
SwarmPreviewScrollController(
search: widget.search,
- lineHeight: () => terminalCellSizeOf(context).height,
+ lineHeight: () => DesktopChrome.of(context)
+ ? MediaQuery.textScalerOf(context).scale(13) * 1.5
+ : terminalCellSizeOf(context).height,
);
@override
void didUpdateWidget(SwarmResourcePreview oldWidget) {
super.didUpdateWidget(oldWidget);
+ if (oldWidget.controls != widget.controls) {
+ if (oldWidget.controls.dispatch == _dispatch) {
+ oldWidget.controls.dispatch = null;
+ }
+ if (oldWidget.controls.commands == _commands) {
+ oldWidget.controls.commands = null;
+ }
+ widget.controls.dispatch = _dispatch;
+ widget.controls.commands = _commands;
+ }
if (oldWidget.search != widget.search) {
oldWidget.search.removeListener(_searchChanged);
widget.search.addListener(_searchChanged);
@@ -293,8 +319,10 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
@override
void dispose() {
- widget.controls.dispatch = null;
- widget.controls.commands = null;
+ // A new palette can register its preview before the previous overlay is
+ // disposed. Only release this preview's own callbacks.
+ if (widget.controls.dispatch == _dispatch) widget.controls.dispatch = null;
+ if (widget.controls.commands == _commands) widget.controls.commands = null;
widget.search.removeListener(_searchChanged);
_resourceTimer?.cancel();
_actionFocus.dispose();
@@ -327,7 +355,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
return true;
}
if (command == 'picker.resource_add_api' && widget.search.isModelMode) {
- _editApi(null);
+ _addApi();
return true;
}
if (command == 'picker.focus_actions') {
@@ -336,7 +364,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
}
if (_actionFocus.hasFocus &&
(command == 'picker.next' || command == 'picker.previous')) {
- return _traverseActions(command == 'picker.next', stay: true);
+ return _traverseActions(command == 'picker.next');
}
if (command == 'picker.cancel') {
if (!_actionFocus.hasFocus) return false;
@@ -344,6 +372,9 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
return true;
}
if (command == 'picker.accept') {
+ // An empty result remains an inert picker, including the native command
+ // bridge. Consume Return so it cannot escape to the workspace beneath it.
+ if (row == null) return true;
if (_actionFocus.hasFocus) {
if (_focusedResource != row?.id) {
widget.onRefocus();
@@ -368,7 +399,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
final selected = row!;
unawaited(_run(() => widget.search.getModel(selected)));
}
- if (row?.isCreate == true) _editApi(null);
+ if (row?.isCreate == true) _addApi();
// Model rows perform Use/Get directly; unavailable rows stay put.
return true;
}
@@ -486,6 +517,9 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
_pending.add(id);
_errors.remove(id);
});
+ // A control becomes disabled while its request is running. Return to the
+ // query before Flutter drops that button's focus into an unnamed scope.
+ if (_actionFocus.hasFocus) widget.onRefocus();
String? error;
try {
error = await action();
@@ -509,8 +543,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
HarnessSession? get _session {
final selected = row;
- if (selected?.agentId == null) return null;
- final machine = app.stateOf(selected!.machineId!);
+ if (selected == null || selected.agentId == null) return null;
+ final machine = app.stateOf(selected.machineId!);
final agent = machine?.agents
.where((agent) => agent.id == selected.agentId)
.firstOrNull;
@@ -584,6 +618,52 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
Widget _actionButtons() {
final target = row?.id;
final cell = terminalCellSizeOf(context);
+ final desktop = DesktopChrome.of(context);
+ Widget button(_ResourceAction action) {
+ final node = _buttonFocus.putIfAbsent(
+ action.command,
+ () => FocusNode(debugLabel: action.label),
+ );
+ final VoidCallback? invoke = action.onPressed == null
+ ? null
+ : () {
+ if (row?.id != target) return;
+ // Resolve again so stale widgets cannot act on an old resource.
+ final current = _visibleActions()
+ .where((a) => a.command == action.command)
+ .firstOrNull;
+ current?.onPressed?.call();
+ };
+ if (desktop) {
+ final shortcut = effectiveCommandHint(
+ context,
+ action.command,
+ contextKind: KeymapContext.picker,
+ );
+ return Semantics(
+ liveRegion: action.label == 'Working…',
+ child: DesktopPill(
+ key: ValueKey('resource-action:${action.command}'),
+ focusNode: node,
+ label: action.label,
+ compact: true,
+ onPressed: invoke,
+ foregroundColor: action.command == 'picker.resource_remove'
+ ? Theme.of(context).colorScheme.error
+ : null,
+ tooltip: [action.label, ?shortcut].join(' · '),
+ ),
+ );
+ }
+ return TerminalTextAction(
+ key: ValueKey('resource-action:${action.command}'),
+ focusNode: node,
+ label: action.label,
+ padding: EdgeInsets.zero,
+ onPressed: invoke,
+ );
+ }
+
final controls = Focus(
focusNode: _actionFocus,
onFocusChange: (focused) {
@@ -592,34 +672,13 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
},
child: Wrap(
key: const ValueKey('swarm-search-resource-actions'),
- spacing: cell.width * 2,
- runSpacing: cell.height,
- children: [
- for (final action in _visibleActions())
- TerminalTextAction(
- key: ValueKey('resource-action:${action.command}'),
- focusNode: _buttonFocus.putIfAbsent(
- action.command,
- () => FocusNode(debugLabel: action.label),
- ),
- label: action.label,
- padding: EdgeInsets.zero,
- onPressed: action.onPressed == null
- ? null
- : () {
- if (row?.id != target) return;
- // Resolve again so stale widgets cannot operate on an old resource.
- final current = _visibleActions()
- .where((a) => a.command == action.command)
- .firstOrNull;
- current?.onPressed?.call();
- },
- ),
- ],
+ spacing: desktop ? 8 : cell.width * 2,
+ runSpacing: desktop ? 8 : cell.height,
+ children: [for (final action in _visibleActions()) button(action)],
),
);
- void next() => _traverseActions(true, stay: true);
- void previous() => _traverseActions(false, stay: true);
+ void next() => _traverseActions(true);
+ void previous() => _traverseActions(false);
if (KeymapTheme.of(context) != null) {
return KeymapRegion(
contextKind: KeymapContext.picker,
@@ -645,6 +704,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
}
Widget _controlHints() {
+ final desktop = DesktopChrome.of(context);
String? key(String command) => effectiveCommandHint(
context,
command,
@@ -681,7 +741,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
? 'setup'
: 'Manage'
: widget.search.actionLabel(row)}',
- if (key('picker.complete') case final tab?) '$tab pane',
+ if (key('picker.complete') case final tab?)
+ '$tab ${desktop ? 'controls' : 'pane'}',
if (key('picker.cancel') case final escape? when managing || starting)
'$escape ${starting ? 'cancel' : 'back'}',
];
@@ -692,13 +753,15 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
);
return Padding(
padding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height,
+ horizontal: desktop ? 18 : cell.width * 2,
+ vertical: desktop ? 12 : cell.height,
),
child: Text(
hints.join(' · '),
key: const ValueKey('resource-control-hints'),
- style: terminalContentStyle(color: theme.muted),
+ style: desktop
+ ? DesktopChrome.text(size: 11, color: DesktopChrome.muted)
+ : terminalContentStyle(color: theme.muted),
),
);
}
@@ -706,7 +769,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
List<_ResourceAction> _actions() {
final search = widget.search;
final selected = row;
- final busy = _pending.contains(selected?.id ?? search.title);
+ if (selected == null) return const [];
+ final busy = _pending.contains(selected.id);
if (search.isModelDownloadsRow(selected)) {
return [
_ResourceAction(
@@ -716,7 +780,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
),
];
}
- if (selected?.isCreate == true) {
+ if (selected.isCreate) {
if (search.isMachineMode) {
return [
_ResourceAction(
@@ -735,14 +799,14 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
return [
_ResourceAction(
'Add',
- busy ? null : () => _editApi(null),
+ busy ? null : _addApi,
command: 'picker.accept',
),
];
}
return [
_ResourceAction(
- selected!.title.replaceFirst('New ', 'Create '),
+ selected.title.replaceFirst('New ', 'Create '),
busy ? null : _open,
command: 'picker.accept',
),
@@ -750,11 +814,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
}
if (search.isStoreMode) {
return [
- _ResourceAction(
- 'Open in Store',
- selected == null ? null : _open,
- command: 'picker.accept',
- ),
+ _ResourceAction('Open in Store', _open, command: 'picker.accept'),
];
}
if (search.isModelMode) {
@@ -850,8 +910,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
),
];
}
- if (selected?.isMachine == true) {
- final machine = app.stateOf(selected!.machineId!);
+ if (selected.isMachine) {
+ final machine = app.stateOf(selected.machineId!);
if (machine == null) return [];
final secondary = _secondaryActions();
return [
@@ -888,7 +948,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
_ResourceAction(
session?.needsInput == true
? 'Answer'
- : selected?.isProject == true
+ : selected.isProject
? 'Harnesses'
: session?.agent.isStopped == true
? 'Resume & open'
@@ -916,6 +976,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
];
}
+ void _addApi() => _editApi(null);
+
void _editApi(String? id, {bool removing = false}) {
final catalog = widget.search.models;
if (catalog == null) return;
@@ -969,7 +1031,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
if (selected?.isCreate != true)
_ResourceAction(
'Add API connection',
- () => _editApi(null),
+ _addApi,
command: 'picker.resource_add_api',
),
if (model?.api case final api?) ...[
@@ -1062,7 +1124,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
}
Widget _modelPreview() {
- final catalog = widget.search.models!;
+ final catalog = widget.search.models;
+ if (catalog == null) return _details(['No matching models']);
if (widget.search.isModelDownloadsRow(row)) {
return _details(
widget.search.modelDownloadsVisible
@@ -1083,7 +1146,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
catalog.manager.scanning ? 'Finding models…' : 'No matching models',
]);
}
- final cell = terminalCellSizeOf(context);
+ final desktop = DesktopChrome.of(context);
+ final cell = desktop ? const Size(8, 16) : terminalCellSizeOf(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
@@ -1136,6 +1200,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
: entry.status;
Widget labelValue(String label, String value) {
+ if (desktop) return _desktopDetail(label, value);
return Padding(
padding: EdgeInsets.only(bottom: cell.height * .6),
child: Row(
@@ -1163,7 +1228,15 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
Widget errorLine(String text) {
return Padding(
padding: EdgeInsets.only(top: cell.height),
- child: Text(text, style: terminalContentStyle(color: theme.yellow)),
+ child: Text(
+ text,
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: Theme.of(context).colorScheme.error,
+ )
+ : terminalContentStyle(color: theme.yellow),
+ ),
);
}
@@ -1176,13 +1249,17 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
children: [
Text(
entry.name,
- style: terminalContentStyle(color: theme.foreground)
- .copyWith(fontWeight: FontWeight.bold),
+ style: desktop
+ ? DesktopChrome.text(size: 15, medium: true)
+ : terminalContentStyle(color: theme.foreground)
+ .copyWith(fontWeight: FontWeight.bold),
),
SizedBox(height: cell.height),
Text(
inUse ? '$statusWord · this harness is on it' : statusWord,
- style: terminalContentStyle(color: theme.foreground),
+ style: desktop
+ ? DesktopChrome.text(size: 12, color: DesktopChrome.muted)
+ : terminalContentStyle(color: theme.foreground),
),
if (widget.search.modelUseErrorId == entry.id &&
widget.search.modelUseError != null)
@@ -1250,15 +1327,18 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
SizedBox(height: cell.height * .4),
Text(
sentence,
- style: terminalContentStyle(color: theme.foreground),
+ style: desktop
+ ? DesktopChrome.text(size: 12, color: DesktopChrome.muted)
+ : terminalContentStyle(color: theme.foreground),
),
],
] else ...[
- labelValue(
- 'Machine',
- entry.node ??
- (entry.source == 'Local' ? machineTitle : entry.source),
- ),
+ if (!desktop || entry.node != null || entry.source == 'Local')
+ labelValue(
+ 'Machine',
+ entry.node ??
+ (entry.source == 'Local' ? machineTitle : entry.source),
+ ),
if (entry.subscription case final subscription?) ...[
...((subscription['details'] as List?) ?? const [])
.map((d) => '$d')
@@ -1291,8 +1371,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
],
if (operation?.error case final err?) errorLine(err),
if (catalog.manager.error case final err?) errorLine(err),
- SizedBox(height: cell.height),
- _actionButtons(),
+ if (!desktop) ...[SizedBox(height: cell.height), _actionButtons()],
],
);
}
@@ -1417,9 +1496,72 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
], controls: true);
}
+ Widget _desktopDetail(String label, String value) => Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final scale = MediaQuery.textScalerOf(context).scale(12) / 12;
+ final style = DesktopChrome.text(size: 12, color: DesktopChrome.muted);
+ // Keep the shared label column wide enough for its longest label in
+ // the actual system font, including enlarged accessibility text.
+ final measure = TextPainter(
+ text: TextSpan(text: 'Machine', style: style),
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ maxLines: 1,
+ )..layout();
+ final labelWidth = math.max(72 * scale, measure.width + 12);
+ measure.dispose();
+ final labelText = Text(label, style: style);
+ final valueText = Text(value, style: DesktopChrome.text(size: 12));
+ return constraints.maxWidth < 260 * scale
+ ? Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [labelText, const SizedBox(height: 2), valueText],
+ )
+ : Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(width: labelWidth, child: labelText),
+ Expanded(child: valueText),
+ ],
+ );
+ },
+ ),
+ );
+
/// The preview's lines: the first is the title, `''` is a blank row, and a `(label, value)`
- /// pair is a labelled row — [_kDetailLabelColumns] columns of label, the value wrapping beside it.
+ /// pair is a labelled row — [_kDetailLabelColumns] terminal columns of label.
Widget _details(List<Object> lines, {bool controls = false}) {
+ if (DesktopChrome.of(context)) {
+ return ListView(
+ controller: _scroll,
+ padding: const EdgeInsets.all(18),
+ children: [
+ for (var i = 0; i < lines.length; i++)
+ switch (lines[i]) {
+ '' => const SizedBox(height: 12),
+ (final String label, final String value) => _desktopDetail(
+ label,
+ value,
+ ),
+ final line => Padding(
+ padding: EdgeInsets.only(bottom: i == 0 ? 5 : 3),
+ child: Text(
+ '$line',
+ style: DesktopChrome.text(
+ size: i == 0 ? 15 : 12,
+ medium: i == 0,
+ color: i == 0
+ ? DesktopChrome.foreground
+ : DesktopChrome.muted,
+ ),
+ ),
+ ),
+ },
+ ],
+ );
+ }
final cell = terminalCellSizeOf(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
@@ -1464,6 +1606,47 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
}
Widget _typeHints() {
+ if (DesktopChrome.of(context)) {
+ return ListView(
+ controller: _scroll,
+ padding: const EdgeInsets.all(18),
+ children: [
+ Text(
+ 'Find your next task',
+ style: DesktopChrome.text(size: 15, medium: true),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ 'Search harnesses, or type a prefix to choose a category.',
+ style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),
+ ),
+ const SizedBox(height: 12),
+ Wrap(
+ key: const ValueKey('swarm-search-type-hints'),
+ spacing: 6,
+ runSpacing: 6,
+ children: [
+ for (final (prefix, label) in [
+ ('@', 'Machines'),
+ ('#', 'Projects'),
+ (':', 'Models'),
+ ('*', 'Store'),
+ ('>', 'Commands'),
+ ])
+ DesktopPill(
+ key: ValueKey('swarm-search-scope:$prefix'),
+ label: '$prefix $label',
+ compact: true,
+ onPressed: () {
+ widget.search.setQuery('$prefix ');
+ widget.onRefocus();
+ },
+ ),
+ ],
+ ),
+ ],
+ );
+ }
final cell = terminalCellSizeOf(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
@@ -1532,108 +1715,50 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
terminal: true,
);
}
- final cell = terminalCellSizeOf(context);
+ final desktop = DesktopChrome.of(context);
+ final cell = desktop ? const Size(9, 12) : terminalCellSizeOf(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (widget.search.isModelMode &&
- widget.search.models?.manager.error != null)
- Padding(
- padding: EdgeInsets.fromLTRB(
- cell.width * 2,
- cell.height,
- cell.width * 2,
- 0,
- ),
- child: Text(
- 'Local models · ${widget.search.models!.manager.error}',
- key: const ValueKey('local-model-inventory-notice'),
- style: terminalContentStyle(color: theme.yellow),
- ),
- ),
- if (_pending.contains(row?.id))
- Padding(
- padding: EdgeInsets.fromLTRB(
- cell.width * 2,
- cell.height,
- cell.width * 2,
- 0,
- ),
- child: Text(
- 'Working…',
- style: terminalContentStyle(color: theme.muted),
- ),
+ final actions = [
+ if (desktop || !_isManagement)
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ cell.width * 2,
+ cell.height,
+ cell.width * 2,
+ 0,
),
- if (_errors[row?.id] case final error?)
- Padding(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height,
- ),
- child: Text(
- error,
- style: terminalContentStyle(color: theme.yellow),
- ),
- ),
- Expanded(
- child: _editingApi
- ? ApiPickerForm(
- key: _apiFormKey,
- controller: widget.search.models!.manager.apis,
- connectionId: _apiConnectionId,
- removing: _apiRemoving,
- onClose: _closeApiForm,
- onFocusChanged: widget.search.setManaging,
- onSwitchPane: _switchPane,
- )
- : _editingMachine
- ? MachinePickerForm(
- key: _formKey,
- app: app,
- kind: _machineForm!,
- machineId: row?.machineId,
- onClose: _closeMachineForm,
- onFocusChanged: widget.search.setManaging,
- onSwitchPane: _switchPane,
- )
- : widget.search.showsTypeHints
- ? _typeHints()
- : row?.isCreate == true
- ? _details([
- ...widget.search.createDescription.split('\n'),
- ], controls: _machineSetup)
- : widget.search.isStoreMode
- ? _details([
- if (row?.storeId case final id?) ...[
- widget.search.storeEntries[id]?.name ?? '',
- widget.search.storeEntries[id]?.category ?? '',
- '',
- widget.search.storeEntries[id]?.description ?? '',
- if (widget.search.storeEntries[id]?.author
- case final author?)
- 'By $author',
- ] else
- 'No matching store entries',
- ])
- : row?.isMachine == true
- ? _machinePreview()
- : widget.search.isModelMode
- ? _modelPreview()
- : SwarmSearchPreview(
- key: const ValueKey('swarm-search-preview'),
- search: widget.search,
- terminal: true,
- ),
+ child: _actionButtons(),
),
- if (row != null &&
- !widget.search.showsTypeHints &&
- !_editingMachine &&
- !_editingApi) ...[
- if (!_isManagement)
+ if (KeyHints.visibleOf(context)) _controlHints(),
+ ];
+ return LayoutBuilder(
+ builder: (context, constraints) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (widget.search.isModelMode &&
+ widget.search.models?.manager.error != null)
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ cell.width * 2,
+ cell.height,
+ cell.width * 2,
+ 0,
+ ),
+ child: Text(
+ 'Local models · ${widget.search.models!.manager.error}',
+ key: const ValueKey('local-model-inventory-notice'),
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: Theme.of(context).colorScheme.error,
+ )
+ : terminalContentStyle(color: theme.yellow),
+ ),
+ ),
+ if (_pending.contains(row?.id) && (!desktop || _session == null))
Padding(
padding: EdgeInsets.fromLTRB(
cell.width * 2,
@@ -1641,11 +1766,104 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
cell.width * 2,
0,
),
- child: _actionButtons(),
+ child: Text(
+ 'Working…',
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ )
+ : terminalContentStyle(color: theme.muted),
+ ),
+ ),
+ if (_errors[row?.id] case final error?)
+ Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: Text(
+ error,
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: Theme.of(context).colorScheme.error,
+ )
+ : terminalContentStyle(color: theme.yellow),
+ ),
),
- if (KeyHints.visibleOf(context)) _controlHints(),
+ Expanded(
+ child: _editingApi
+ ? ApiPickerForm(
+ key: _apiFormKey,
+ controller: widget.search.models!.manager.apis,
+ connectionId: _apiConnectionId,
+ removing: _apiRemoving,
+ onClose: _closeApiForm,
+ onFocusChanged: widget.search.setManaging,
+ onSwitchPane: _switchPane,
+ )
+ : _editingMachine
+ ? MachinePickerForm(
+ key: _formKey,
+ app: app,
+ kind: _machineForm!,
+ machineId: row?.machineId,
+ onClose: _closeMachineForm,
+ onFocusChanged: widget.search.setManaging,
+ onSwitchPane: _switchPane,
+ )
+ : widget.search.showsTypeHints
+ ? _typeHints()
+ : row?.isCreate == true
+ ? _details([
+ ...widget.search.createDescription.split('\n'),
+ ], controls: _machineSetup)
+ : widget.search.isStoreMode
+ ? _details([
+ if (row?.storeId case final id?) ...[
+ widget.search.storeEntries[id]?.name ?? '',
+ widget.search.storeEntries[id]?.category ?? '',
+ '',
+ widget.search.storeEntries[id]?.description ?? '',
+ if (widget.search.storeEntries[id]?.author
+ case final author?)
+ 'By $author',
+ ] else
+ 'No matching store entries',
+ ])
+ : row?.isMachine == true
+ ? _machinePreview()
+ : widget.search.isModelMode
+ ? _modelPreview()
+ : SwarmSearchPreview(
+ key: const ValueKey('swarm-search-preview'),
+ search: widget.search,
+ terminal: true,
+ ),
+ ),
+ if (row != null &&
+ !widget.search.showsTypeHints &&
+ !_editingMachine &&
+ !_editingApi) ...[
+ if (desktop)
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: math.min(140, constraints.maxHeight * .55),
+ ),
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: actions,
+ ),
+ ),
+ )
+ else
+ ...actions,
+ ],
],
- ],
+ ),
);
},
);
diff --git a/desktop/lib/widgets/swarm_search_field.dart b/desktop/lib/widgets/swarm_search_field.dart
index 35190e36a..7f27384d3 100644
--- a/desktop/lib/widgets/swarm_search_field.dart
+++ b/desktop/lib/widgets/swarm_search_field.dart
@@ -1,11 +1,8 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:harness/terminal/terminal_text.dart';
-import '../shared/theme/app_theme.dart' as grid;
-import '../shared/theme/app_type.dart';
-
-Color get _rim => grid.AppTheme.pick(grid.AppPalette.textFaint, Colors.white24);
+import '../shared/theme/app_theme.dart';
class SwarmSearchField extends StatefulWidget {
const SwarmSearchField({
@@ -56,7 +53,7 @@ class _SwarmSearchFieldState extends State<SwarmSearchField> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
+ AppTheme.watch(context);
final onMove = widget.onMove;
final onSubmitted = widget.onSubmitted;
return CallbackShortcuts(
@@ -90,36 +87,17 @@ class _SwarmSearchFieldState extends State<SwarmSearchField> {
autofocus: widget.autofocus,
onChanged: widget.onChanged,
onSubmitted: (_) => onSubmitted?.call(),
- style: AppType.mono(),
+ style: AppType.body(),
decoration: InputDecoration(
hintText: widget.hintText,
- // Dark palettes keep the navy well this field was tuned in; on a
- // light one it would be a dark hole under dark ink, so the field
- // takes the search surface, a faint-ink rim and the secondary hint.
- hintStyle: AppType.mono(
- color: grid.AppTheme.pick(
- grid.AppPalette.textSecondary,
- Colors.white60,
- ),
- ),
- prefixIcon: const Icon(Icons.search, size: 18),
+ hintStyle: AppType.body(color: AppPalette.textSecondary),
+ prefixIcon: const Icon(AppIcons.search, size: 18),
filled: true,
- fillColor: grid.AppTheme.pick(
- grid.AppPalette.swarmSearchSurface,
- const Color(0xa6111521),
- ),
+ fillColor: AppDesktop.field,
contentPadding: const EdgeInsets.symmetric(
horizontal: 14,
vertical: 14,
),
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(8),
- borderSide: BorderSide(color: _rim),
- ),
- enabledBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(8),
- borderSide: BorderSide(color: _rim),
- ),
),
),
);
diff --git a/desktop/lib/widgets/swarm_search_input.dart b/desktop/lib/widgets/swarm_search_input.dart
index 853096a9d..bfc0f55a0 100644
--- a/desktop/lib/widgets/swarm_search_input.dart
+++ b/desktop/lib/widgets/swarm_search_input.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:harness/terminal/terminal_text.dart';
@@ -6,6 +7,7 @@ import '../state/swarm_search.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
import 'box_chrome.dart';
+import 'desktop_chrome.dart';
/// The shared input for the start page, Open Agent and split searches.
/// Flutter owns the caret and result navigation; native chrome only opens it.
@@ -78,6 +80,39 @@ class SwarmSearchInput extends StatelessWidget {
}
Widget _buildInput(BuildContext context) {
+ if (DesktopChrome.of(context)) {
+ return TextField(
+ key: inputKey,
+ groupId: groupId ?? EditableText,
+ controller: controller,
+ focusNode: focusNode,
+ autofocus: autofocus,
+ onChanged: onChanged,
+ onTap: onOpen,
+ onTapAlwaysCalled: true,
+ onTapOutside: (_) => onTapOutside?.call(),
+ autocorrect: false,
+ enableSuggestions: false,
+ style: DesktopChrome.text(size: 17),
+ cursorColor: DesktopChrome.foreground,
+ cursorWidth: 2,
+ textAlignVertical: TextAlignVertical.center,
+ decoration: InputDecoration(
+ constraints: BoxConstraints.tightFor(
+ height: MediaQuery.textScalerOf(context).scale(17) * 1.45 + 24,
+ ),
+ hintText: hintText ?? search?.hint ?? kSwarmSearchHint,
+ hintStyle: DesktopChrome.text(size: 17, color: DesktopChrome.muted),
+ hintMaxLines: 1,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ filled: false,
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(vertical: 12),
+ ),
+ );
+ }
final open = search != null;
final terminalStyle = terminal || prompt != null;
final theme = terminalThemeFor(
@@ -163,7 +198,11 @@ class SwarmSearchInput extends StatelessWidget {
)
: terminal
? null
- : Icon(Icons.search, size: fontSize + 4, color: boxText(.60)),
+ : Icon(
+ AppIcons.search,
+ size: fontSize + 4,
+ color: boxText(.60),
+ ),
prefixIconConstraints: BoxConstraints(
minWidth: prompt != null
? 36
diff --git a/desktop/lib/widgets/swarm_search_preview.dart b/desktop/lib/widgets/swarm_search_preview.dart
index 68afc7ade..ea4ae81cd 100644
--- a/desktop/lib/widgets/swarm_search_preview.dart
+++ b/desktop/lib/widgets/swarm_search_preview.dart
@@ -1,8 +1,8 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show ScrollCacheExtent;
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/terminal/terminal_text.dart';
import 'package:xterm/xterm.dart' show TerminalTheme;
@@ -19,6 +19,7 @@ import '../state/swarm_search.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
import 'box_chrome.dart';
+import 'desktop_chrome.dart';
import 'engine_identity.dart';
import 'search_result_text.dart' show SessionSnippetText;
import 'session_tail_view.dart';
@@ -111,7 +112,9 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
SwarmPreviewScrollController _scrollController() =>
SwarmPreviewScrollController(
search: widget.search,
- lineHeight: () => terminalCellSizeOf(context).height,
+ lineHeight: () => DesktopChrome.of(context)
+ ? MediaQuery.textScalerOf(context).scale(13) * 1.5
+ : terminalCellSizeOf(context).height,
);
@override
@@ -189,12 +192,23 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
Size cell,
TerminalTheme theme,
) {
- final terminal = widget.terminal;
- final muted = terminal ? terminalContentStyle(color: theme.muted) : _muted;
- final body = terminal
+ final desktop = DesktopChrome.of(context);
+ final terminal = widget.terminal && !desktop;
+ final muted = desktop
+ ? DesktopChrome.text(size: 12, color: DesktopChrome.muted)
+ : terminal
+ ? terminalContentStyle(color: theme.muted)
+ : _muted;
+ final body = desktop
+ ? _desktopBody
+ : terminal
? terminalContentStyle(color: theme.foreground)
: _body;
- final warning = terminal ? theme.yellow : _waitingInk;
+ final warning = desktop
+ ? grid.AppPalette.warn
+ : terminal
+ ? theme.yellow
+ : _waitingInk;
final gap = terminal ? cell.height : 12.0;
final key = _externalKey(row)!;
final tail = app.sessionTails.read(key);
@@ -204,7 +218,9 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
children: [
Text(
row.title,
- style: terminal
+ style: desktop
+ ? DesktopChrome.text(size: 15, medium: true)
+ : terminal
? body
: AppType.monoLabel(fontWeight: FontWeight.w600, height: 1.25),
),
@@ -248,31 +264,26 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
);
}
_scroll.reversed = true;
- return Column(
+ return _tailLayout(
key: ValueKey('preview-content:${row.id}'),
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: padding.copyWith(bottom: gap),
- child: header,
- ),
- Expanded(
- child: SessionTailView(
- tail: tail,
- tails: app.sessionTails,
- tailKey: key,
- controller: _scroll,
- words: [
- for (final word in widget.search.wordsQuery.split(RegExp(r'\s+')))
- if (word.length > 1) word,
- ],
- body: body,
- muted: muted,
- gap: gap,
- padding: padding.copyWith(top: 0),
- ),
- ),
- ],
+ header: Padding(
+ padding: padding.copyWith(bottom: gap),
+ child: header,
+ ),
+ content: SessionTailView(
+ tail: tail,
+ tails: app.sessionTails,
+ tailKey: key,
+ controller: _scroll,
+ words: [
+ for (final word in widget.search.wordsQuery.split(RegExp(r'\s+')))
+ if (word.length > 1) word,
+ ],
+ body: body,
+ muted: muted,
+ gap: gap,
+ padding: padding.copyWith(top: 0),
+ ),
);
}
@@ -304,9 +315,16 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
);
}
_scroll.reversed = true;
- final terminal = widget.terminal;
- final muted = terminal ? terminalContentStyle(color: theme.muted) : _muted;
- final body = terminal
+ final desktop = DesktopChrome.of(context);
+ final terminal = widget.terminal && !desktop;
+ final muted = desktop
+ ? DesktopChrome.text(size: 12, color: DesktopChrome.muted)
+ : terminal
+ ? terminalContentStyle(color: theme.muted)
+ : _muted;
+ final body = desktop
+ ? _desktopBody
+ : terminal
? terminalContentStyle(color: theme.foreground)
: _body;
final gap = terminal ? cell.height : 12.0;
@@ -323,71 +341,96 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
found.turn < tail.rows.first.turn)
? found
: null;
- return Column(
+ return _tailLayout(
key: ValueKey('preview-content:${row.id}'),
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: padding.copyWith(bottom: gap),
- child: _AgentPreview(
- app: app,
- item: item,
- dense: widget.compactHeader,
- terminal: terminal,
- part: _Part.header,
- ),
- ),
- if (earlier != null)
+ header: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
Padding(
- padding: EdgeInsets.fromLTRB(padding.left, 0, padding.right, gap),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- [
- 'Matched earlier',
- if (earlier.at case final at?)
- '${harnessActivityAge(at, DateTime.now())} ago',
- ].join(' · '),
- style: muted,
- ),
- SessionSnippetText(
- earlier,
- key: ValueKey('preview-found:${earlier.destinationId}'),
- style: body,
- maxLines: 2,
- ),
- ],
+ padding: padding.copyWith(bottom: gap),
+ child: _AgentPreview(
+ app: app,
+ item: item,
+ dense: widget.compactHeader,
+ terminal: terminal,
+ part: _Part.header,
),
),
- Expanded(
- child: SessionTailView(
- tail: tail,
- tails: app.sessionTails,
- tailKey: key,
- controller: _scroll,
- words: [
- for (final word in widget.search.wordsQuery.split(RegExp(r'\s+')))
- if (word.length > 1) word,
- ],
- body: body,
- muted: muted,
- gap: gap,
- padding: padding.copyWith(top: 0),
- footer: live
- ? _AgentPreview(
- app: app,
- item: item,
- terminal: terminal,
- part: _Part.footer,
- )
- : null,
- ),
- ),
- ],
+ if (earlier != null)
+ Padding(
+ padding: EdgeInsets.fromLTRB(padding.left, 0, padding.right, gap),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ [
+ 'Matched earlier',
+ if (earlier.at case final at?)
+ sessionPreviewAge(at, DateTime.now()),
+ ].join(' · '),
+ style: muted,
+ ),
+ SessionSnippetText(
+ earlier,
+ key: ValueKey('preview-found:${earlier.destinationId}'),
+ style: body,
+ maxLines: 2,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ content: SessionTailView(
+ tail: tail,
+ tails: app.sessionTails,
+ tailKey: key,
+ controller: _scroll,
+ words: [
+ for (final word in widget.search.wordsQuery.split(RegExp(r'\s+')))
+ if (word.length > 1) word,
+ ],
+ body: body,
+ muted: muted,
+ gap: gap,
+ padding: padding.copyWith(top: 0),
+ footer: live
+ ? _AgentPreview(
+ app: app,
+ item: item,
+ terminal: terminal,
+ part: _Part.footer,
+ )
+ : null,
+ ),
);
}
+ Widget _tailLayout({
+ required Key key,
+ required Widget header,
+ required Widget content,
+ }) => LayoutBuilder(
+ key: key,
+ builder: (context, constraints) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (DesktopChrome.of(context))
+ ConstrainedBox(
+ constraints: BoxConstraints(maxHeight: constraints.maxHeight * .42),
+ child: ScrollConfiguration(
+ behavior: ScrollConfiguration.of(context)
+ .copyWith(scrollbars: false),
+ child: SingleChildScrollView(primary: false, child: header),
+ ),
+ )
+ else
+ header,
+ Expanded(child: content),
+ ],
+ ),
+ );
+
@override
void dispose() {
_warm?.cancel();
@@ -400,8 +443,11 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
+ final desktop = DesktopChrome.of(context);
final cell = widget.terminal ? terminalCellSizeOf(context) : Size.zero;
- final padding = widget.terminal
+ final padding = desktop
+ ? const EdgeInsets.all(18)
+ : widget.terminal
? EdgeInsets.symmetric(
horizontal: cell.width * 2,
vertical: cell.height,
@@ -427,18 +473,28 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
children: [
Text(
row.title,
- style: terminalContentStyle(color: theme.foreground),
+ style: desktop
+ ? DesktopChrome.text(size: 15, medium: true)
+ : terminalContentStyle(color: theme.foreground),
),
if (row.detail.isNotEmpty)
Text(
row.detail,
- style: terminalContentStyle(color: theme.muted),
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ )
+ : terminalContentStyle(color: theme.muted),
),
if (row.shortcut case final shortcut?) ...[
- SizedBox(height: cell.height),
+ SizedBox(height: desktop ? 12 : cell.height),
Text(
shortcut,
- style: terminalContentStyle(color: theme.muted),
+ style: desktop
+ ? grid.AppType.monoMeta(color: DesktopChrome.muted)
+ .copyWith(fontSize: 12)
+ : terminalContentStyle(color: theme.muted),
),
],
],
@@ -467,7 +523,11 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
itemBuilder: (context, index) => index == 0
? Padding(
padding: EdgeInsets.only(
- bottom: widget.terminal ? cell.height : 24,
+ bottom: desktop
+ ? 16
+ : widget.terminal
+ ? cell.height
+ : 24,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -475,7 +535,9 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
Text(
row.title,
// The list leads the eye; this confirms it.
- style: widget.terminal
+ style: desktop
+ ? DesktopChrome.text(size: 15, medium: true)
+ : widget.terminal
? terminalContentStyle(
color: theme.foreground,
)
@@ -483,10 +545,16 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
fontWeight: FontWeight.w600,
),
),
- if (!widget.terminal) const SizedBox(height: 6),
+ if (desktop || !widget.terminal)
+ const SizedBox(height: 6),
Text(
row.detail,
- style: widget.terminal
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ )
+ : widget.terminal
? terminalContentStyle(color: theme.muted)
: _muted,
),
@@ -495,11 +563,20 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
if (agents.isEmpty && !row.isCreate)
Padding(
padding: EdgeInsets.only(
- top: widget.terminal ? cell.height : 24,
+ top: desktop
+ ? 16
+ : widget.terminal
+ ? cell.height
+ : 24,
),
child: Text(
'No recent harness text available.',
- style: widget.terminal
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ )
+ : widget.terminal
? terminalContentStyle(color: theme.muted)
: _muted,
),
@@ -559,6 +636,10 @@ TextStyle get _body => AppType.monoLabel(
const Color(0xffe1e1e4),
),
);
+TextStyle get _desktopBody => grid.AppType.mono(
+ color: DesktopChrome.foreground,
+ height: 1.5,
+).copyWith(fontSize: 12);
// The non-terminal preview's state colours. The dark ones are pale tints that
// vanish on a light ground, where the matching status tokens take over.
@@ -599,13 +680,21 @@ class _AgentPreview extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
+ final desktop = DesktopChrome.of(context);
+ final terminal = this.terminal && !desktop;
final cell = terminal ? terminalCellSizeOf(context) : Size.zero;
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
- final muted = terminal ? terminalContentStyle(color: theme.muted) : _muted;
- final body = terminal
+ final muted = desktop
+ ? DesktopChrome.text(size: 12, color: DesktopChrome.muted)
+ : terminal
+ ? terminalContentStyle(color: theme.muted)
+ : _muted;
+ final body = desktop
+ ? _desktopBody
+ : terminal
? terminalContentStyle(color: theme.foreground)
: _body;
Widget section(String label, String text, {int? maxLines}) =>
@@ -627,6 +716,12 @@ class _AgentPreview extends StatelessWidget {
: 'Idle');
final color = offline
? muted.color!
+ : desktop
+ ? waiting != null
+ ? grid.AppPalette.warn
+ : working
+ ? DesktopChrome.accent
+ : grid.AppPalette.online
: waiting != null
? terminal
? theme.yellow
@@ -672,7 +767,9 @@ class _AgentPreview extends StatelessWidget {
children: [
Text(
'Needs your input',
- style: terminal
+ style: desktop
+ ? DesktopChrome.text(size: 12, medium: true, color: color)
+ : terminal
? terminalContentStyle(color: color)
: AppType.monoLabel(
fontWeight: FontWeight.w600,
@@ -698,7 +795,42 @@ class _AgentPreview extends StatelessWidget {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- if (terminal) ...[
+ if (desktop) ...[
+ Tooltip(
+ message: agent.displayName,
+ child: Text(
+ agent.displayName,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(size: 15, medium: true),
+ ),
+ ),
+ const SizedBox(height: 5),
+ Text(
+ [
+ machine.machine.displayName,
+ if (project?.label case final name? when name.isNotEmpty) name,
+ ?project?.shownBranch,
+ ].join(' · '),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: grid.AppType.monoMeta(color: DesktopChrome.muted)
+ .copyWith(fontSize: 11),
+ ),
+ const SizedBox(height: 6),
+ Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: state,
+ style: TextStyle(color: color),
+ ),
+ TextSpan(text: ' · ${agentIdentity(agent).label}'),
+ ],
+ ),
+ style: muted,
+ ),
+ ] else if (terminal) ...[
Text(agent.displayName, style: body),
Text(
statusLineParts(
@@ -750,7 +882,7 @@ class _AgentPreview extends StatelessWidget {
],
],
),
- if (!dense && !terminal) ...[
+ if (!desktop && !dense && !terminal) ...[
const SizedBox(height: 10),
Wrap(
spacing: 8,
@@ -767,9 +899,7 @@ class _AgentPreview extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
Icon(
- waiting != null
- ? LucideIcons.hand300
- : LucideIcons.circle300,
+ waiting != null ? AppIcons.hand : AppIcons.circle,
size: 10,
color: color,
),
@@ -791,7 +921,8 @@ class _AgentPreview extends StatelessWidget {
),
],
if (part == _Part.header) ...[
- if (!terminal &&
+ if (!desktop &&
+ !terminal &&
(project?.label.isNotEmpty == true || project?.branch != null))
Padding(
padding: const EdgeInsets.only(top: 6),
@@ -814,7 +945,7 @@ class _AgentPreview extends StatelessWidget {
overflow: TextOverflow.ellipsis,
style: excerpt == null ? muted : body,
),
- if (project != null && !terminal)
+ if (project != null && !terminal && !desktop)
Padding(
padding: EdgeInsets.only(top: terminal ? cell.height : 8),
child: Text(
@@ -826,6 +957,8 @@ class _AgentPreview extends StatelessWidget {
SizedBox(
height: terminal
? cell.height
+ : desktop
+ ? 16
: dense
? 16
: 26,
@@ -839,7 +972,7 @@ class _AgentPreview extends StatelessWidget {
_ => 'Found in what you asked',
},
if (found.at case final at?)
- '${harnessActivityAge(at, DateTime.now())} ago',
+ sessionPreviewAge(at, DateTime.now()),
].join(' · '),
style: terminal
? muted
@@ -915,17 +1048,13 @@ class _AgentPreview extends StatelessWidget {
),
if (!terminal) const SizedBox(height: 8),
if (project?.cwd case final cwd?) Text(cwd, style: muted),
- if (!terminal)
+ if (!terminal && !desktop)
if (project?.branch case final branch?)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Row(
children: [
- Icon(
- LucideIcons.gitBranch300,
- size: 12,
- color: muted.color,
- ),
+ Icon(AppIcons.gitBranch, size: 12, color: muted.color),
const SizedBox(width: 6),
Expanded(child: Text(branch, style: muted)),
],
@@ -953,27 +1082,40 @@ class _Section extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
+ final desktop = DesktopChrome.of(context);
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
);
return Padding(
padding: EdgeInsets.only(
- bottom: terminal ? terminalCellSizeOf(context).height : 24,
+ bottom: desktop
+ ? 16
+ : terminal
+ ? terminalCellSizeOf(context).height
+ : 24,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
- style: terminal
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ medium: true,
+ color: DesktopChrome.muted,
+ )
+ : terminal
? terminalContentStyle(color: theme.muted)
: _muted.copyWith(fontWeight: FontWeight.w500),
),
- if (!terminal) const SizedBox(height: 7),
+ if (desktop || !terminal) const SizedBox(height: 6),
Text(
_displayText(text),
- style: terminal
+ style: desktop
+ ? _desktopBody
+ : terminal
? terminalContentStyle(color: theme.foreground)
: _body,
maxLines: maxLines,
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index ad87168ac..9d526c365 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -1,10 +1,11 @@
import 'dart:async';
+import 'dart:math' as math;
import 'swarm_search_field.dart';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show ScrollCacheExtent;
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:flutter/services.dart';
import '../shortcuts/app_keymap.dart';
@@ -17,6 +18,7 @@ import '../shared/theme/status_line_style.dart';
import '../terminal/terminal_text.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
+import 'desktop_chrome.dart';
import 'search_result_text.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -63,6 +65,11 @@ class _SwarmHistoryState extends State<_SwarmHistory> {
final _query = TextEditingController();
final _focus = FocusNode(debugLabel: 'History search');
void _choose(SwarmSearchSelection choice) => Navigator.pop(context, choice);
+ void _close() => Navigator.pop(context);
+
+ bool get _composing =>
+ _query.value.composing.isValid && !_query.value.composing.isCollapsed;
+
@override
void dispose() {
_query.dispose();
@@ -72,47 +79,75 @@ class _SwarmHistoryState extends State<_SwarmHistory> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
- return Dialog(
- alignment: const Alignment(0, -0.5),
- insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 48),
- child: SizedBox(
- width: 680,
- height: 480,
- child: Padding(
- padding: const EdgeInsets.all(16),
- child: SwarmSearchKeys(
- search: widget.search,
- editing: _query,
- onChoose: _choose,
- onClose: () => Navigator.pop(context),
- onRefocus: _focus.requestFocus,
- child: Column(
- children: [
- Row(
- children: [
- Text('History', style: grid.AppType.monoLabel()),
- Spacer(),
- Text('This window', style: boxMonoStyle(color: kBoxFaint)),
- ],
- ),
- const SizedBox(height: 16),
- SwarmSearchField(
- controller: _query,
- focusNode: _focus,
- autofocus: true,
- hintText: 'Search history',
- onChanged: widget.search.setQuery,
+ return DesktopChrome(
+ child: Dialog(
+ alignment: const Alignment(0, -0.5),
+ insetPadding: const EdgeInsets.all(20),
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ child: SizedBox(
+ width: 680,
+ height: 480,
+ child: DesktopDialogSurface(
+ child: Actions(
+ // EditableText can resolve Escape before the picker shortcuts.
+ // A composing editor keeps that key; Close remains available.
+ actions: {
+ DismissIntent: CallbackAction<DismissIntent>(
+ onInvoke: (_) {
+ if (!_composing) _close();
+ return null;
+ },
),
- const SizedBox(height: 8),
- Expanded(
- child: SwarmSearchResults(
- search: widget.search,
- onChoose: _choose,
- onRefocus: _focus.requestFocus,
+ },
+ child: Column(
+ children: [
+ DesktopDialogHeader(
+ title: 'History',
+ detail: 'This window',
+ onClose: _close,
),
- ),
- ],
+ Expanded(
+ // Enter belongs to the focused Close button in the header;
+ // result acceptance only applies within the search area.
+ child: SwarmSearchKeys(
+ desktop: true,
+ search: widget.search,
+ editing: _query,
+ onChoose: _choose,
+ onClose: _close,
+ onRefocus: _focus.requestFocus,
+ child: Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: DesktopChrome.panelPadding,
+ ),
+ child: SwarmSearchField(
+ controller: _query,
+ focusNode: _focus,
+ autofocus: true,
+ hintText: 'Search history',
+ onChanged: widget.search.setQuery,
+ ),
+ ),
+ const SizedBox(height: DesktopChrome.controlGap),
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
+ child: SwarmSearchResults(
+ search: widget.search,
+ onChoose: _choose,
+ onRefocus: _focus.requestFocus,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
),
),
),
@@ -134,6 +169,7 @@ class SwarmSearchKeys extends StatelessWidget {
this.onCommands,
this.onRefocus,
this.previewControls,
+ this.desktop = false,
required this.child,
});
final SwarmSearchController? search;
@@ -148,6 +184,7 @@ class SwarmSearchKeys extends StatelessWidget {
final VoidCallback? onCommands;
final VoidCallback? onRefocus;
final SearchPreviewControls? previewControls;
+ final bool desktop;
final Widget child;
@override
@@ -196,6 +233,14 @@ class SwarmSearchKeys extends StatelessWidget {
}
});
void complete(bool forward) => run(() {
+ if (desktop) {
+ if (forward) {
+ FocusManager.instance.primaryFocus?.nextFocus();
+ } else {
+ FocusManager.instance.primaryFocus?.previousFocus();
+ }
+ return;
+ }
if (previewControls?.invoke(
forward ? 'picker.complete' : 'picker.complete_back',
) ==
@@ -331,12 +376,13 @@ class SwarmSearchKeys extends StatelessWidget {
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
move(1),
const SingleActivator(LogicalKeyboardKey.arrowUp): () => move(-1),
- if (previewControls != null) ...{
+ if (previewControls != null)
const SingleActivator(
LogicalKeyboardKey.period,
meta: true,
): () =>
run(() => previewControls!.invoke('picker.resource_more')),
+ if (previewControls != null || desktop) ...{
const SingleActivator(LogicalKeyboardKey.tab): () =>
complete(true),
const SingleActivator(
@@ -463,6 +509,7 @@ class SwarmSearchResults extends StatefulWidget {
this.bios = false,
this.header,
this.previewBuilder,
+ this.showPreview = true,
});
final SwarmSearchController search;
final ValueChanged<SwarmSearchSelection> onChoose;
@@ -476,6 +523,7 @@ class SwarmSearchResults extends StatefulWidget {
final bool bios;
final Widget? header;
final Widget Function()? previewBuilder;
+ final bool showPreview;
@override
State<SwarmSearchResults> createState() => _SwarmSearchResultsState();
}
@@ -492,6 +540,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
Timer? _activityClock;
final _resultsKey = GlobalKey();
double _rowHeight = 56;
+ double _modelHeadingHeight = 28;
+ bool _desktopRows = false;
bool _revealScheduled = false;
bool _createPinned = false;
int _lastPage = 0;
@@ -528,12 +578,20 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
return items;
}
+ double _modelItemHeight(({int? index, String? heading, String? key}) item) =>
+ !_desktopRows || item.index != null
+ ? _rowHeight
+ : item.heading == null
+ ? 8
+ : _modelHeadingHeight;
+
double _fittedHeight(
BoxConstraints constraints, {
required bool sideBySide,
required bool unavailable,
}) {
- final stacked = search.hasPreview && !sideBySide;
+ final hasPreview = widget.showPreview && search.hasPreview;
+ final stacked = hasPreview && !sideBySide;
if (stacked && search.resultsFromBottom) return constraints.maxHeight;
final available = stacked
? (constraints.maxHeight - 8) * 5 / 11
@@ -549,7 +607,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
: widget.terminal
? 9
: 12;
- final count = search.hasPreview
+ final count = hasPreview
? capacity.clamp(1, maxRows)
: search.rows.length.clamp(1, capacity.clamp(1, maxRows));
final listHeight = chrome + count * _rowHeight;
@@ -570,6 +628,21 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
search.resultPage.addListener(_pageResults);
}
+ @override
+ void didUpdateWidget(SwarmSearchResults oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.search != search) {
+ oldWidget.search.removeListener(_changed);
+ oldWidget.search.resultPage.removeListener(_pageResults);
+ search.addListener(_changed);
+ search.resultPage.addListener(_pageResults);
+ _lastPage = search.resultPage.value;
+ _announced = null;
+ _rowWidgets.clear();
+ _revealSelection();
+ }
+ }
+
void _pageResults() {
final pages = search.resultPage.value - _lastPage;
_lastPage = search.resultPage.value;
@@ -630,11 +703,16 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
void _scrollToSelection() {
if (!_scroll.hasClients || search.rows.isEmpty) return;
+ final modelRows = _modelRows;
final index = search.isModelMode
- ? _modelRows.indexWhere((item) => item.index == search.cursor)
+ ? modelRows.indexWhere((item) => item.index == search.cursor)
: search.cursor - (_createPinned ? 1 : 0);
if (index < 0) return;
- final top = index * _rowHeight;
+ final top = search.isModelMode
+ ? modelRows
+ .take(index)
+ .fold(0.0, (height, item) => height + _modelItemHeight(item))
+ : index * _rowHeight;
final bottom = top + _rowHeight;
final position = _scroll.position;
final offset = top < position.pixels
@@ -682,6 +760,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
terminalThemeStore.value,
);
final scale = MediaQuery.textScalerOf(context);
+ final desktop = DesktopChrome.of(context);
final cell = widget.bios ? terminalCellSizeOf(context) : Size.zero;
final keyHints = KeyHints.visibleOf(context);
final acceptKey = keyHints
@@ -705,8 +784,9 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
return LayoutBuilder(
builder: (context, constraints) {
final sideBySide = constraints.maxWidth >= widget.sideBySideMinWidth;
- final resultWidth = search.hasPreview && sideBySide
- ? (constraints.maxWidth - 1) * .6
+ final resultWidth =
+ widget.showPreview && search.hasPreview && sideBySide
+ ? (constraints.maxWidth - 1) * (desktop ? .44 : .6)
: constraints.maxWidth;
final stacked =
widget.terminal &&
@@ -728,6 +808,12 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
// result. Other pickers retain their descriptions and spacing.
_rowHeight = cell.height * (singleLine ? 1 : 3);
}
+ if (desktop) {
+ _rowHeight =
+ scale.scale(14) * (search.isCommandMode ? 1.5 : 2.8) + 16;
+ }
+ _desktopRows = desktop;
+ _modelHeadingHeight = scale.scale(12) * 1.45 + 12;
final height = widget.fitRows
? _fittedHeight(
constraints,
@@ -776,9 +862,11 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
compactAction,
grid.AppType.monoFamily,
grid.AppTheme.palette.value,
+ desktop ? grid.AppTheme.brightness.value : null,
widget.bios ? theme : null,
acceptKey,
widget.terminal,
+ desktop,
stacked,
activityAge,
row.isModel ? search.modelRowAction(row) : null,
@@ -831,26 +919,74 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
if (focused) _focusResult(row.id);
},
selected: highlighted,
- selectedColor: boxText(1),
- hoverColor: Colors.transparent,
+ selectedColor: desktop
+ ? DesktopChrome.foreground
+ : boxText(1),
+ hoverColor: desktop
+ ? DesktopChrome.foreground.withValues(alpha: .045)
+ : Colors.transparent,
+ focusColor: desktop
+ ? DesktopChrome.accent.withValues(alpha: .08)
+ : null,
// BoxRowHighlight draws the selection, the same
// in both modes of the box.
selectedTileColor: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
- widget.terminal ? 0 : 6,
+ widget.terminal && !desktop
+ ? 0
+ : desktop
+ ? 10
+ : 6,
),
),
dense: true,
visualDensity: VisualDensity.compact,
minVerticalPadding: 0,
horizontalTitleGap: 10,
- minLeadingWidth: 20,
- contentPadding: const EdgeInsets.symmetric(horizontal: 10),
+ minLeadingWidth: desktop ? 28 : 20,
+ contentPadding: EdgeInsets.symmetric(
+ horizontal: desktop ? 14 : 10,
+ ),
// The dock uses its full-row highlight for
// selection; prefixes only appear in the input.
- leading: widget.terminal
+ leading: widget.terminal && !desktop
? null
+ : desktop
+ ? row.isStore
+ ? StoreMark(size: 28, enabled: canSubmit)
+ : row.agentId != null ||
+ row.isStoreEntry ||
+ (row.isSwarm && row.members.length == 1)
+ ? EngineMark(
+ engine: row.storeId ?? row.engine,
+ size: 28,
+ enabled: canSubmit,
+ )
+ : row.isSwarm
+ ? SwarmIcon(
+ size: 26,
+ color: highlighted
+ ? DesktopChrome.onSelection
+ : DesktopChrome.muted,
+ )
+ : Icon(
+ row.isProject
+ ? AppIcons.folder
+ : row.isMachine
+ ? AppIcons.laptop
+ : row.isModel
+ ? AppIcons.sparkles
+ : row.isCreate
+ ? AppIcons.plus
+ : row.isCommand
+ ? AppIcons.command
+ : AppIcons.terminal,
+ size: 22,
+ color: highlighted
+ ? DesktopChrome.onSelection
+ : DesktopChrome.muted,
+ )
: Row(
mainAxisSize: MainAxisSize.min,
children: [
@@ -863,7 +999,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
? const SizedBox(width: 2)
: row.isCreate
? Icon(
- LucideIcons.plus300,
+ AppIcons.plus,
size: 18,
color: boxText(.70),
)
@@ -878,13 +1014,13 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
)
: row.isProject
? Icon(
- LucideIcons.folderOpen,
+ AppIcons.folderOpen,
size: 18,
color: boxText(.60),
)
: row.isMachine
? Icon(
- LucideIcons.monitor300,
+ AppIcons.monitor,
size: 18,
color: boxText(.60),
)
@@ -895,9 +1031,21 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
search: search,
row: row,
terminal: widget.terminal,
- stacked: stacked,
+ stacked: desktop || stacked,
+ highlighted: desktop && highlighted,
),
- trailing: widget.terminal
+ trailing: desktop
+ ? row.shortcut == null
+ ? null
+ : Text(
+ row.shortcut!,
+ style: grid.AppType.monoMeta(
+ color: highlighted
+ ? DesktopChrome.selectionDetail
+ : DesktopChrome.muted,
+ ),
+ )
+ : widget.terminal
? (highlighted
? Text(
acceptKey ?? '',
@@ -954,7 +1102,19 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
_focusResult(row.id);
}
},
- child: widget.bios
+ child: desktop
+ ? Padding(
+ padding: const EdgeInsets.symmetric(vertical: 2),
+ child: Material(
+ key: ValueKey('swarm-search-line:${row.id}'),
+ color: highlighted
+ ? DesktopChrome.activeSelection
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(10),
+ child: tile,
+ ),
+ )
+ : widget.bios
? tile
: BoxRowHighlight(
terminal: widget.terminal,
@@ -982,39 +1142,53 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
?widget.header,
Expanded(
child: search.rows.isEmpty
- ? Center(
- child: Text(
- search.isCommandMode
- ? 'No matching commands'
- : search.sessionFilter == SessionFilter.needsInput
- ? search.matchQuery.isEmpty
- ? 'No harnesses need your input'
- : 'No matching harnesses'
- : search.isModelMode
- ? 'No matching models'
- : search.isStoreMode
- ? 'No matching store entries'
- : search.isHelpMode
- ? 'No matching modes or help'
- : search.isProjectMode
- ? 'No matching projects'
- : search.isMachineMode
- ? 'No matching machines'
- : search.adding &&
- search.query.isEmpty &&
- search.capacity <= 0
- ? 'This swarm is full (${AppNotifier.maxPanes} panes). Open a new swarm to add more.'
- : search.adding && search.query.isEmpty
- ? 'No harnesses yet. Start a harness or choose @ machines to connect a machine.'
- : search.adding
- ? 'No matching harnesses'
- : 'No matching results',
- style: widget.bios
- ? terminalContentStyle(color: theme.muted)
- : grid.AppType.monoLabel(
- fontWeight: FontWeight.w400,
- color: boxText(.60),
- ),
+ ? _SearchInventoryEmptyState(
+ search: search,
+ child: Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Text(
+ search.isCommandMode
+ ? 'No matching commands'
+ : search.sessionFilter ==
+ SessionFilter.needsInput
+ ? search.matchQuery.isEmpty
+ ? 'No harnesses need your input'
+ : 'No matching harnesses'
+ : search.isModelMode
+ ? 'No matching models'
+ : search.isStoreMode
+ ? 'No matching store entries'
+ : search.isHelpMode
+ ? 'No matching modes or help'
+ : search.isProjectMode
+ ? 'No matching projects'
+ : search.isMachineMode
+ ? 'No matching machines'
+ : search.adding &&
+ search.query.isEmpty &&
+ search.capacity <= 0
+ ? 'This tab is full (${AppNotifier.maxPanes} panes). Open a new tab to add more.'
+ : search.adding && search.query.isEmpty
+ ? desktop
+ ? 'No harnesses yet. Start one with New Harness, or choose Machines to connect a computer.'
+ : 'No harnesses yet. Start an agent or choose @ machines to connect a machine.'
+ : search.adding
+ ? 'No matching harnesses'
+ : 'No matching results',
+ textAlign: TextAlign.center,
+ style: desktop
+ ? DesktopChrome.text(
+ color: DesktopChrome.muted,
+ )
+ : widget.bios
+ ? terminalContentStyle(color: theme.muted)
+ : grid.AppType.monoLabel(
+ fontWeight: FontWeight.w400,
+ color: boxText(.60),
+ ),
+ ),
+ ),
),
)
: Padding(
@@ -1030,6 +1204,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
order: const NumericFocusOrder(1),
child: FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
+ descendantsAreTraversable: !desktop,
child: ListView.builder(
key: const ValueKey('swarm-search-result-list'),
padding: EdgeInsets.symmetric(
@@ -1048,7 +1223,13 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
itemCount: search.isModelMode
? modelRows.length
: search.rows.length - (pinCreate ? 1 : 0),
- itemExtent: _rowHeight,
+ itemExtent: desktop && search.isModelMode
+ ? null
+ : _rowHeight,
+ itemExtentBuilder: desktop && search.isModelMode
+ ? (index, _) =>
+ _modelItemHeight(modelRows[index])
+ : null,
itemBuilder: (context, index) {
if (!search.isModelMode) {
return buildRow(
@@ -1070,18 +1251,30 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
padding: EdgeInsets.symmetric(
horizontal: widget.bios
? cell.width * 3
+ : desktop
+ ? 14
: 10,
),
- child: Text(
- item.heading!,
- maxLines: 1,
- style: widget.bios
- ? terminalContentStyle(
- color: theme.muted,
- )
- : grid.AppType.monoLabel(
- color: boxText(.60),
- ),
+ child: Align(
+ alignment: desktop
+ ? Alignment.centerLeft
+ : Alignment.topLeft,
+ child: Text(
+ item.heading!,
+ maxLines: 1,
+ style: desktop
+ ? DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ )
+ : widget.bios
+ ? terminalContentStyle(
+ color: theme.muted,
+ )
+ : grid.AppType.monoLabel(
+ color: boxText(.60),
+ ),
+ ),
),
),
);
@@ -1111,7 +1304,9 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
: 'No room to open this ${selected.isSwarm || selected.isGroup ? 'group' : 'harness'}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: widget.bios
+ style: desktop
+ ? DesktopChrome.text(color: DesktopChrome.muted)
+ : widget.bios
? terminalContentStyle(color: theme.muted)
: grid.AppType.monoLabel(
fontWeight: FontWeight.w400,
@@ -1128,7 +1323,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
),
);
final preview =
- search.hasPreview &&
+ widget.showPreview &&
+ search.hasPreview &&
(!widget.bios || sideBySide || widget.previewBuilder != null)
? widget.previewBuilder?.call() ??
SwarmSearchPreview(
@@ -1145,9 +1341,15 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
? Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- // The list is what is being read; the preview confirms it.
- Expanded(flex: 5, child: results),
- if (widget.terminal)
+ // A compact list leaves room to read the selected work.
+ Expanded(flex: desktop ? 11 : 5, child: results),
+ if (desktop)
+ VerticalDivider(
+ width: 1,
+ thickness: 1,
+ color: DesktopChrome.rim,
+ )
+ else if (widget.terminal)
VerticalDivider(
width: 1,
thickness: 1,
@@ -1156,11 +1358,33 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
)
else
const SizedBox(width: 8),
- Expanded(flex: 5, child: preview ?? const SizedBox()),
+ Expanded(
+ flex: desktop ? 14 : 5,
+ child: preview ?? const SizedBox(),
+ ),
],
)
: preview == null
? results
+ : desktop
+ ? Column(
+ children: [
+ SizedBox(
+ height: math.min(
+ height * .45,
+ 16 +
+ _rowHeight *
+ (search.isModelMode
+ ? modelRows.length
+ : search.rows.length)
+ .clamp(1, 4),
+ ),
+ child: results,
+ ),
+ Divider(height: 1, color: DesktopChrome.rim),
+ Expanded(child: preview),
+ ],
+ )
: search.resultsFromBottom
? Column(
children: [
@@ -1237,6 +1461,93 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
}
}
+/// Inventory refreshes can leave the cached catalog unchanged, so listen to
+/// their presentation state directly without changing search ranking or focus.
+class _SearchInventoryEmptyState extends StatelessWidget {
+ const _SearchInventoryEmptyState({required this.search, required this.child});
+
+ final SwarmSearchController search;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) {
+ if (!DesktopChrome.of(context) ||
+ search.history != null ||
+ search.isCommandMode ||
+ search.isHelpMode ||
+ search.isModelMode ||
+ search.isStoreMode) {
+ return child;
+ }
+ return ListenableBuilder(
+ listenable: search.app,
+ builder: (context, _) {
+ final app = search.app;
+ final pending = app.machinesLoading || app.machinesRefreshing;
+ final error = app.machineListError;
+ if (!pending && error == null) return child;
+ final resource = search.isMachineMode
+ ? 'machines'
+ : search.isProjectMode
+ ? 'projects'
+ : 'harnesses';
+ void retry() {
+ if (!app.machinesLoading && !app.machinesRefreshing) {
+ unawaited(app.retryMachines());
+ }
+ }
+
+ return Center(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(24),
+ child: Semantics(
+ key: const ValueKey('swarm-search-inventory-state'),
+ liveRegion: true,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ pending
+ ? 'Loading $resource…'
+ : 'Couldn’t load your $resource',
+ textAlign: TextAlign.center,
+ style: DesktopChrome.text(color: DesktopChrome.muted),
+ ),
+ if (error != null) ...[
+ if (!pending) ...[
+ const SizedBox(height: 8),
+ Text(
+ error,
+ textAlign: TextAlign.center,
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ const SizedBox(height: 12),
+ KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: KeymapRegion.of(context)?.composing,
+ actions: {
+ ...?KeymapRegion.of(context)?.actions,
+ 'picker.accept': retry,
+ 'picker.refresh': retry,
+ },
+ child: DesktopPill(
+ key: const ValueKey('swarm-search-inventory-retry'),
+ label: pending ? 'Retrying…' : 'Retry',
+ onPressed: pending ? null : retry,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+}
+
// Typing changes the match text even when the row, its controls, and its focus
// state stay the same. Listen here so the cached row can keep that state.
class _SearchRowContent extends StatefulWidget {
@@ -1365,6 +1676,138 @@ class _SearchRowContentState extends State<_SearchRowContent> {
(terms.isEmpty || matches.length < terms.take(12).toSet().length)
? hit
: null;
+ if (DesktopChrome.of(context)) {
+ final ink = widget.highlighted
+ ? DesktopChrome.onSelection
+ : DesktopChrome.foreground;
+ final muted = widget.highlighted
+ ? DesktopChrome.selectionDetail
+ : DesktopChrome.muted;
+ final title = widget.search.isModelMode && row.isCreate
+ ? 'Add API connection'
+ : widget.search.isModelDownloadsRow(row)
+ ? widget.search.modelDownloadsVisible
+ ? 'Hide catalog'
+ : 'Get models'
+ : row.title;
+ final unavailable = widget.search.sessionUnavailable(row);
+ final api = row.isModel ? widget.search.apiRowState(row) : null;
+ final underApi = row.isModel && widget.search.isApiModelRow(row);
+ final modelStatus = row.isModel
+ ? widget.search.modelRowStatus(row)
+ : null;
+ final status = unavailable ?? api?.hint ?? modelStatus;
+ final modelFacts = row.isModel
+ ? widget.search
+ .modelRowFacts(row)
+ ?.trim()
+ .replaceAll(RegExp(r' {2,}'), ' · ')
+ : null;
+ final activity = widget.search.activityOf(row);
+ final age = activity == null
+ ? null
+ : widget.search.openedAt.difference(activity).inMinutes < 1
+ ? 'now'
+ : harnessActivityAge(activity, widget.search.openedAt);
+ final detail = row.terminalDetail ?? row.detail;
+ Widget trailingLabel(String text) => Text(
+ text,
+ key: api != null
+ ? ValueKey('api-row-hint:${row.id}')
+ : row.isModel
+ ? ValueKey('model-row-status:${row.id}')
+ : null,
+ maxLines: 1,
+ textAlign: TextAlign.right,
+ style: DesktopChrome.metadata(
+ color: widget.highlighted
+ ? DesktopChrome.selectionDetail
+ : row.isModel && widget.search.modelRowLive(row)
+ ? grid.AppTheme.pick(
+ const Color(0xFF246C3F),
+ const Color(0xFF86E6A3),
+ )
+ : row.isModel && widget.search.modelRowFailed(row)
+ ? Theme.of(context).colorScheme.error
+ : muted,
+ ),
+ );
+ return Semantics(
+ label:
+ '$title\n$detail${status == null ? '' : ', $status'}'
+ '${status == null && activity != null ? ', Last active ${activity.toLocal()}' : ''}'
+ '${snippet == null ? '' : ', Found in conversation: ${snippet.plainSnippet}'}',
+ excludeSemantics: true,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ if (underApi) const SizedBox(width: 32),
+ if (api != null) ...[
+ Icon(
+ key: ValueKey('api-row-marker:${row.id}'),
+ api.open ? AppIcons.chevronDown : AppIcons.chevronRight,
+ size: 16,
+ color: muted,
+ ),
+ const SizedBox(width: 4),
+ ],
+ Expanded(
+ child: SearchResultText(
+ title,
+ matches: matches.where((match) => match.title),
+ style: DesktopChrome.text(
+ color: unavailable == null ? ink : muted,
+ ),
+ ),
+ ),
+ if (status ?? age case final trailing?) ...[
+ const SizedBox(width: 12),
+ if (status == null && activity != null)
+ Tooltip(
+ message: 'Last active ${activity.toLocal()}',
+ child: trailingLabel(trailing),
+ )
+ else if (row.isModel && api == null)
+ SizedBox(
+ width: MediaQuery.textScalerOf(context).scale(96),
+ child: trailingLabel(trailing),
+ )
+ else
+ trailingLabel(trailing),
+ ],
+ ],
+ ),
+ if (modelFacts != null) ...[
+ const SizedBox(height: 2),
+ Text(
+ modelFacts,
+ key: ValueKey('model-row-facts:${row.id}'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(color: muted),
+ ),
+ ] else if (!row.isCommand &&
+ !underApi &&
+ (detail.isNotEmpty || snippet != null)) ...[
+ const SizedBox(height: 2),
+ snippet != null
+ ? SessionSnippetText(
+ snippet,
+ style: DesktopChrome.text(size: 12, color: muted),
+ )
+ : SearchResultText(
+ detail,
+ matches: matches.where((match) => !match.title),
+ style: DesktopChrome.metadata(color: muted),
+ ),
+ ],
+ ],
+ ),
+ );
+ }
if (widget.bios) {
final theme = terminalThemeFor(
grid.AppTheme.palette.value,
@@ -1616,7 +2059,7 @@ class _SearchRowContentState extends State<_SearchRowContent> {
iconOffset: row.detailBranchOffset ?? 0,
inlineIcon: widget.terminal || row.detailBranchOffset == null
? null
- : Icon(LucideIcons.gitBranch300, size: 12, color: boxText(.60)),
+ : Icon(AppIcons.gitBranch, size: 12, color: boxText(.60)),
matches: matches.where((match) => !match.title),
style: widget.terminal
? boxMonoStyle(color: kBoxFaint)
@@ -1682,7 +2125,7 @@ class SwarmSearchActionLabel extends StatelessWidget {
if (_returnChord.hasMatch(hint)) ...[
if (hint.length > 1)
Text(hint.substring(0, hint.length - 1), style: boxMonoStyle()),
- const Icon(Icons.keyboard_return, size: 14),
+ const Icon(AppIcons.cornerDownLeft, size: 14),
] else
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 96),
diff --git a/desktop/lib/widgets/take_over_dialog.dart b/desktop/lib/widgets/take_over_dialog.dart
index 4dce768b3..6c246902d 100644
--- a/desktop/lib/widgets/take_over_dialog.dart
+++ b/desktop/lib/widgets/take_over_dialog.dart
@@ -1,10 +1,11 @@
import 'package:flutter/material.dart';
+import '../shared/theme/app_theme.dart' as grid;
import '../shortcuts/app_keymap.dart';
import '../state/swarm_navigation.dart' show externalEngineName;
import '../state/take_over.dart';
-import '../terminal/terminal_text.dart';
-import 'box_chrome.dart';
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
import 'terminal_prompt.dart';
export '../state/take_over.dart';
@@ -67,109 +68,85 @@ class _TakeOverPromptState extends State<_TakeOverPrompt> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
final busy = widget.busy;
- return ListenableBuilder(
- listenable: terminalFontStore,
- builder: (context, _) => TerminalPromptKeys(
- cancel: () => _pick(null),
- child: TerminalPrompt(
+ return TerminalPromptKeys(
+ cancel: () => _pick(null),
+ child: DesktopPromptSurface(
+ body: DesktopPromptScrollBody(
child: Column(
- mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- 'Move to Harness',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- const SizedBox(height: 12),
- Text(
- widget.title,
- key: const ValueKey('take-over-title'),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(weight: FontWeight.w600),
- ),
- if (widget.machine case final machine?) ...[
- const SizedBox(height: 4),
- Text(machine, style: boxMonoStyle(color: kBoxFaint)),
- ],
- const SizedBox(height: 10),
- Text(
- busy
- ? '$_engineName is working on it in a terminal.'
- : 'It is open in $_engineName in a terminal. '
- 'Moving it here quits it there.',
- style: boxMonoStyle(color: boxText(.70)),
- ),
- const SizedBox(height: 8),
- Text(
- busy
- ? engineResumesWithMessage.contains(widget.engine)
- ? 'Wait moves it here when this turn ends. '
- 'Take Over Now stops the turn and tells it to continue.'
- : 'Wait moves it here when this turn ends. '
- 'Take Over Now stops the turn; it picks up when you ask.'
- : 'The conversation is kept.',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ],
- ),
+ Text('Move to Harness', style: DesktopChrome.heading()),
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ widget.title,
+ key: const ValueKey('take-over-title'),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(size: 14, medium: true),
),
- Padding(
- padding: const EdgeInsets.fromLTRB(14, 0, 14, 10),
- child: Wrap(
- spacing: 12,
- children: [
- if (busy) ...[
- terminalPromptButton(
- 'Wait',
- () => _pick(TakeOver.wait),
- focusNode: _first,
- key: const Key('take-over-wait'),
- ),
- terminalPromptButton(
- 'Take Over Now',
- () => _pick(TakeOver.now),
- danger: true,
- key: const Key('take-over-now'),
- ),
- ] else
- terminalPromptButton(
- 'Move Here',
- () => _pick(TakeOver.idle),
- focusNode: _first,
- key: const Key('take-over-move'),
- ),
- terminalPromptButton('Cancel', () => _pick(null)),
- ],
+ if (widget.machine case final machine?) ...[
+ const SizedBox(height: 4),
+ Text(
+ machine,
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
),
+ ],
+ const SizedBox(height: 16),
+ Text(
+ busy
+ ? '$_engineName is working on it in a terminal.'
+ : 'It is open in $_engineName in a terminal. '
+ 'Moving it here quits it there.',
+ style: DesktopChrome.text(size: 13),
),
- BoxHintStrip(
- hints: [
- BoxHint(
- terminalPromptHint(context, 'picker.accept', 'enter'),
- 'select',
- ),
- BoxHint(
- terminalPromptHint(context, 'picker.complete', 'tab'),
- 'controls',
- ),
- BoxHint(
- terminalPromptHint(context, 'picker.cancel', 'esc'),
- 'close',
- onTap: () => _pick(null),
- ),
- ],
+ const SizedBox(height: 8),
+ Text(
+ busy
+ ? engineResumesWithMessage.contains(widget.engine)
+ ? 'Wait moves it here when this turn ends. '
+ 'Take Over Now stops the turn and tells it to continue.'
+ : 'Wait moves it here when this turn ends. '
+ 'Take Over Now stops the turn; it picks up when you ask.'
+ : 'The conversation is kept.',
+ style: DesktopChrome.text(size: 13, color: DesktopChrome.muted),
),
],
),
),
+ actions: [
+ TextButton(
+ onPressed: () => _pick(null),
+ style: TextButton.styleFrom(
+ foregroundColor: DesktopChrome.foreground,
+ textStyle: DesktopChrome.text(size: 13),
+ ),
+ child: const Text('Cancel'),
+ ),
+ if (busy)
+ OutlinedButton(
+ key: const Key('take-over-now'),
+ onPressed: () => _pick(TakeOver.now),
+ style: OutlinedButton.styleFrom(
+ foregroundColor: Theme.of(context).colorScheme.error,
+ textStyle: DesktopChrome.text(size: 13),
+ ),
+ child: const Text('Take Over Now'),
+ ),
+ FilledButton(
+ key: Key(busy ? 'take-over-wait' : 'take-over-move'),
+ focusNode: _first,
+ onPressed: () => _pick(busy ? TakeOver.wait : TakeOver.idle),
+ style: FilledButton.styleFrom(
+ textStyle: DesktopChrome.text(size: 13),
+ ),
+ child: Text(busy ? 'Wait' : 'Move Here'),
+ ),
+ ],
),
);
}
diff --git a/desktop/lib/widgets/task_palette.dart b/desktop/lib/widgets/task_palette.dart
index f3d574a6e..14a05e437 100644
--- a/desktop/lib/widgets/task_palette.dart
+++ b/desktop/lib/widgets/task_palette.dart
@@ -1,11 +1,12 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../core/models.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_dialog.dart';
+import 'desktop_chrome.dart';
import '../state/app_state.dart';
import 'engine_identity.dart';
@@ -88,62 +89,6 @@ Future<void> showTaskPalette(
).whenComplete(() => spoken?.cancelled());
}
-/// The design's own values, lifted rather than approximated.
-///
-/// Every number here is read off the `Palette_*` CSS module the design team published on the product
-/// page — the same component, already drawn for this exact feature down to the "taken" row and the
-/// confidence column. Naming them together is what keeps a later "small tidy" from drifting off it one
-/// value at a time; if the page changes, this block is the diff.
-abstract final class _D {
- /// The opaque sheet.
- static const width = 680.0;
- static const radius = 16.0;
- static const fill = Color(0xFF1E1E21);
- static const rim = Color(0x1FFFFFFF); // rgba(255,255,255,.12)
-
- /// The lit top edge — `inset 0 1px 0 rgba(255,255,255,.06)`. A one-pixel highlight is most of what
- /// makes glass read as glass rather than as a grey box.
- static const innerLight = Color(0x0FFFFFFF);
-
- /// The veil.
- static const veil = kDialogVeilTint;
-
- /// ABOVE the middle, deliberately: the list grows downwards, and a box pinned to the centre would
- /// jump every time the answer arrived. Anchored high, it stays put and the results unroll beneath it.
- static const lift = -0.38;
-
- /// The field.
- static const fieldInk = Color(0xFFF4F4F6);
- static const hint = Color(0xFF6E6E76);
- static const caret = Color(0xFFE6E6EA);
-
- /// The rows.
- static const sep = Color(0x14FFFFFF); // rgba(255,255,255,.08)
- static const activeFill = Color(0x14FFFFFF);
- static const engineInk = Color(0xFFF4F4F6);
- static const machineInk = Color(0xFF8A8A92);
- static const machineDim = Color(0xFF6A6A72);
- static const nameInk = Color(0xFFD0D0D6);
- static const questionInk = Color(0xFF7C7C84);
- static const questionMark = Color(0xFFB9F0CF);
-
- /// Green means "this one", in both places it appears: the fit that is worth considering, and the row
- /// that took the work.
- static const green = Color(0xFF3DDC84);
- static const takenFill = Color(0x243DDC84); // rgba(61,220,132,.14)
- static const takenRim = Color(0x733DDC84); // rgba(61,220,132,.45)
- static const lowFit = Color(0xFF8A8A92);
-
- /// The five columns. Fixed, and that IS the feature: three rows whose machine and fit line up can be
- /// read down a column, which is the comparison the person was stopped to make. Flex columns put the
- /// same facts at three different x positions and turn a comparison into three separate readings.
- static const colIcon = 16.0;
- static const colName = 118.0;
- static const colMachine = 190.0;
- static const colFit = 44.0;
- static const colGap = 12.0;
-}
-
/// Below this the palette stops guessing and asks.
///
/// It is not a tuned number, it is the router's own top band: the classifier is told to answer **0.85+
@@ -426,13 +371,20 @@ class _TaskPaletteState extends State<_TaskPalette> {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
- if (event.logicalKey == LogicalKeyboardKey.escape) {
- Navigator.of(context).pop();
- return KeyEventResult.handled;
- }
final isEnter =
event.logicalKey == LogicalKeyboardKey.enter ||
event.logicalKey == LogicalKeyboardKey.numpadEnter;
+ final isEscape = event.logicalKey == LogicalKeyboardKey.escape;
+ final composing = _text.value.composing;
+ if (composing.isValid && !composing.isCollapsed) {
+ return isEnter || isEscape
+ ? KeyEventResult.skipRemainingHandlers
+ : KeyEventResult.ignored;
+ }
+ if (isEscape) {
+ Navigator.of(context).pop();
+ return KeyEventResult.handled;
+ }
// ⇧Enter is the newline — ignored here so the field does what it always does with it.
final shift = HardwareKeyboard.instance.isShiftPressed;
if (isEnter && !shift && _stage != _Stage.choosing) {
@@ -462,23 +414,19 @@ class _TaskPaletteState extends State<_TaskPalette> {
grid.AppTheme.watch(context);
return Stack(
children: [
- // The veil, built rather than tinted — see showTaskPalette. Tapping it closes, which is what the
- // barrier it replaces did.
Positioned.fill(
- child: GestureDetector(
- onTap: () => Navigator.of(context).maybePop(),
- behavior: HitTestBehavior.opaque,
- child: const ColoredBox(color: _D.veil),
+ child: DesktopDialogBackdrop(
+ onDismiss: () => Navigator.of(context).maybePop(),
),
),
- Center(
- child: FractionalTranslation(
- translation: const Offset(0, _D.lift),
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 24),
+ SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Align(
+ alignment: const Alignment(0, -.18),
child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: _D.width),
- child: _sheet(),
+ constraints: const BoxConstraints(maxWidth: 680),
+ child: SingleChildScrollView(child: _sheet()),
),
),
),
@@ -487,52 +435,13 @@ class _TaskPaletteState extends State<_TaskPalette> {
);
}
- /// An opaque sheet avoids compositing and blurring the live terminals.
- Widget _sheet() {
- return ClipRRect(
- borderRadius: BorderRadius.circular(_D.radius),
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: _D.fill,
- borderRadius: BorderRadius.circular(_D.radius),
- border: Border.all(color: _D.rim),
- boxShadow: const [
- BoxShadow(
- color: Color(0x99000000),
- blurRadius: 12,
- offset: Offset(0, 4),
- ),
- ],
- ),
- // TRANSPARENT Material, and it is required rather than decorative: dropping Dialog for a
- // hand-built veil dropped the Material ancestor with it, and TextField and InkWell both
- // assert without one. `transparency` provides it while painting nothing, so the glass above
- // stays the only surface — a MaterialType.canvas here would put an opaque sheet over it.
- child: Material(
- type: MaterialType.transparency,
- child: Stack(
- children: [
- Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [_field(), _results()],
- ),
- // `inset 0 1px 0 rgba(255,255,255,.06)`.
- const Positioned(
- left: 0,
- right: 0,
- top: 0,
- child: ColoredBox(
- color: _D.innerLight,
- child: SizedBox(height: 1),
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
+ Widget _sheet() => DesktopDialogSurface(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [_field(), _results()],
+ ),
+ );
/// The field, with Material's own skin switched OFF.
///
@@ -562,8 +471,8 @@ class _TaskPaletteState extends State<_TaskPalette> {
// Read-only rather than disabled while the router thinks: a disabled field drops the focus,
// and the focus is what Esc is listening on.
readOnly: working || _stage == _Stage.sent,
- style: grid.AppType.mono(color: _D.fieldInk, height: 1.35),
- cursorColor: _D.caret,
+ style: DesktopChrome.text(size: 17, height: 1.35),
+ cursorColor: DesktopChrome.accent,
cursorWidth: 2,
cursorRadius: Radius.zero,
decoration: InputDecoration(
@@ -577,13 +486,17 @@ class _TaskPaletteState extends State<_TaskPalette> {
focusedBorder: InputBorder.none,
disabledBorder: InputBorder.none,
hintText: 'Describe the work…',
- hintStyle: grid.AppType.mono(color: _D.hint, height: 1.35),
+ hintStyle: DesktopChrome.text(
+ size: 17,
+ color: DesktopChrome.muted,
+ height: 1.35,
+ ),
),
),
),
// The whole of the waiting state, in the field's own right margin: a 16px ring at right:24.
if (working) ...[
- const Positioned(
+ Positioned(
right: 24,
top: 0,
bottom: 0,
@@ -593,7 +506,7 @@ class _TaskPaletteState extends State<_TaskPalette> {
height: 16,
child: CircularProgressIndicator(
strokeWidth: 1.8,
- color: _D.hint,
+ color: DesktopChrome.muted,
),
),
),
@@ -609,7 +522,7 @@ class _TaskPaletteState extends State<_TaskPalette> {
child: Center(
child: Text(
'${_elapsed}s',
- style: grid.AppType.monoMeta(color: _D.hint),
+ style: grid.AppType.caption(color: DesktopChrome.muted),
),
),
),
@@ -631,9 +544,9 @@ class _TaskPaletteState extends State<_TaskPalette> {
padding: const EdgeInsets.fromLTRB(16, 6, 16, 8),
child: Text(
_note,
- style: grid.AppType.monoLabel(
+ style: grid.AppType.body(
fontWeight: FontWeight.w400,
- color: _D.questionInk,
+ color: DesktopChrome.muted,
height: 1.45,
),
),
@@ -649,9 +562,12 @@ class _TaskPaletteState extends State<_TaskPalette> {
padding: EdgeInsets.fromLTRB(16, 8, 16, 6),
child: Row(
children: [
- Icon(Icons.check, size: 14, color: _D.green),
+ Icon(AppIcons.check, size: 14, color: DesktopChrome.accent),
SizedBox(width: 8),
- Text('on it', style: grid.AppType.monoLabel(color: _D.green)),
+ Text(
+ 'Task sent',
+ style: grid.AppType.body(color: DesktopChrome.accent),
+ ),
],
),
),
@@ -693,8 +609,8 @@ class _TaskPaletteState extends State<_TaskPalette> {
Widget _panel(List<Widget> children) => Container(
padding: const EdgeInsets.fromLTRB(8, 6, 8, 8),
- decoration: const BoxDecoration(
- border: Border(top: BorderSide(color: _D.sep)),
+ decoration: BoxDecoration(
+ border: Border(top: BorderSide(color: DesktopChrome.rim)),
),
child: Column(
mainAxisSize: MainAxisSize.min,
@@ -714,12 +630,12 @@ class _TaskPaletteState extends State<_TaskPalette> {
final reason = (answer?.reason ?? '').trim();
final weighed = answer?.weighed ?? 0;
final machines = answer?.machines ?? 0;
- final base = grid.AppType.monoLabel(
+ final base = grid.AppType.body(
fontWeight: FontWeight.w400,
- color: _D.questionInk,
+ color: DesktopChrome.muted,
height: 1.45,
);
- final mark = grid.AppType.monoLabel(color: _D.questionMark);
+ final mark = grid.AppType.body(color: DesktopChrome.foreground);
return Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 4),
child: Column(
@@ -759,8 +675,8 @@ class _TaskPaletteState extends State<_TaskPalette> {
'“$reason”',
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: grid.AppType.monoMeta(
- color: _D.machineDim,
+ style: grid.AppType.caption(
+ color: DesktopChrome.muted,
fontStyle: FontStyle.italic,
),
),
@@ -770,103 +686,87 @@ class _TaskPaletteState extends State<_TaskPalette> {
);
}
- /// One candidate, on the design's five-column grid.
+ /// Shared picker anatomy keeps machine context legible in narrow windows.
Widget _row(
RouteCandidate candidate, {
required bool active,
required bool taken,
}) {
final fit = candidate.confidence;
- // Green is a claim, and it is only made about the leader. Everything else is grey — a runner-up
- // wearing the same colour as the pick would be the palette arguing with itself.
- final leader = fit > 0 && candidate.agentId == (_answer?.agentId ?? '');
- return InkWell(
- onTap: taken
- ? null
- : () => unawaited(
- _commit(
- candidate.agentId,
- candidate.machineId,
- _text.text.trim(),
- ),
- ),
- borderRadius: BorderRadius.circular(10),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
- decoration: BoxDecoration(
- color: taken
- ? _D.takenFill
- : active
- ? _D.activeFill
- : null,
- borderRadius: BorderRadius.circular(10),
- border: taken ? Border.all(color: _D.takenRim) : null,
- ),
- child: Row(
- children: [
- // Greyed and lifted, so a row of six vendors reads as one list instead of six brand marks.
- SizedBox(
- width: _D.colIcon,
- height: _D.colIcon,
- child: ColorFiltered(
- colorFilter: const ColorFilter.matrix(<double>[
- 0.2126 * 1.3, 0.7152 * 1.3, 0.0722 * 1.3, 0, 0, //
- 0.2126 * 1.3, 0.7152 * 1.3, 0.0722 * 1.3, 0, 0, //
- 0.2126 * 1.3, 0.7152 * 1.3, 0.0722 * 1.3, 0, 0, //
- 0, 0, 0, 1, 0,
- ]),
- child: EngineMark(engine: candidate.engine, size: _D.colIcon),
- ),
- ),
- const SizedBox(width: _D.colGap),
- SizedBox(
- width: _D.colName,
- child: Text(
- candidate.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: grid.AppType.monoLabel(
- color: taken ? const Color(0xFFDFFBE9) : _D.engineInk,
+ final selected = active || taken;
+ final ink = selected
+ ? grid.AppDesktop.onSelection
+ : DesktopChrome.foreground;
+ final detail = selected
+ ? grid.AppDesktop.selectionDetail
+ : DesktopChrome.muted;
+ final description = [
+ if (candidate.machine.isNotEmpty) candidate.machine,
+ if (candidate.recent.isNotEmpty) candidate.recent,
+ ].join(' · ');
+ return Semantics(
+ selected: active,
+ child: InkWell(
+ mouseCursor: taken
+ ? SystemMouseCursors.basic
+ : SystemMouseCursors.click,
+ onTap: taken
+ ? null
+ : () => unawaited(
+ _commit(
+ candidate.agentId,
+ candidate.machineId,
+ _text.text.trim(),
),
),
- ),
- const SizedBox(width: _D.colGap),
- SizedBox(
- width: _D.colMachine,
- child: Text(
- candidate.machine,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: grid.AppType.monoMeta(
- color: taken ? const Color(0xFF9FD9B6) : _D.machineInk,
- ),
- ),
- ),
- const SizedBox(width: _D.colGap),
- Expanded(
- child: Text(
- candidate.recent,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: grid.AppType.monoMeta(
- color: taken ? const Color(0xFFDFFBE9) : _D.nameInk,
- ),
+ borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(
+ color: selected ? grid.AppDesktop.selection : null,
+ borderRadius: BorderRadius.circular(grid.AppDesktop.rowRadius),
+ ),
+ child: Row(
+ children: [
+ EngineMark(
+ engine: candidate.engine,
+ size: grid.AppDesktop.identitySize,
),
- ),
- const SizedBox(width: _D.colGap),
- SizedBox(
- width: _D.colFit,
- // Drawn only where there IS one: 0 means the router said nothing about this candidate, and
- // a printed 0.00 would be a claim it never made.
- child: Text(
- fit > 0 ? fit.toStringAsFixed(2) : '',
- textAlign: TextAlign.right,
- style: grid.AppType.monoMeta(
- color: leader || taken ? _D.green : _D.lowFit,
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ candidate.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(color: ink, medium: true),
+ ),
+ if (description.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(
+ description,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(color: detail),
+ ),
+ ],
+ ],
),
),
- ),
- ],
+ if (fit > 0 || taken) ...[
+ const SizedBox(width: 12),
+ if (taken)
+ Icon(AppIcons.check, size: 16, color: ink)
+ else
+ Text(
+ fit.toStringAsFixed(2),
+ style: DesktopChrome.metadata(color: detail),
+ ),
+ ],
+ ],
+ ),
),
),
);
diff --git a/desktop/lib/widgets/terminal_composer.dart b/desktop/lib/widgets/terminal_composer.dart
index a370f2677..312645101 100644
--- a/desktop/lib/widgets/terminal_composer.dart
+++ b/desktop/lib/widgets/terminal_composer.dart
@@ -1,8 +1,8 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../theme/app_theme.dart';
@@ -344,9 +344,7 @@ class ComposerGrip extends StatelessWidget {
width: 40,
height: height,
child: Icon(
- expanded
- ? LucideIcons.chevronDown300
- : LucideIcons.chevronUp300,
+ expanded ? AppIcons.chevronDown : AppIcons.chevronUp,
size: 12,
// One step up from the faint ink this started on, in both directions at once:
// the token resolves lighter on dark and darker on light, so the glyph gains
diff --git a/desktop/lib/widgets/terminal_find_bar.dart b/desktop/lib/widgets/terminal_find_bar.dart
index 2bb7e8cd0..ed2db0b66 100644
--- a/desktop/lib/widgets/terminal_find_bar.dart
+++ b/desktop/lib/widgets/terminal_find_bar.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -6,6 +7,7 @@ import '../shared/theme/app_type.dart';
import '../terminal/terminal_text.dart';
import '../terminal/terminal_search.dart';
import 'box_chrome.dart';
+import 'desktop_chrome.dart';
import 'pane_menu.dart';
class TerminalFindBar extends StatefulWidget {
@@ -167,31 +169,72 @@ class TerminalFindBarState extends State<TerminalFindBar> {
Widget option(
String label,
String hint,
- VoidCallback action,
- ) => paneMenuItem(
+ VoidCallback action, {
+ bool? checked,
+ }) => paneMenuItem(
onTap: () => close(action),
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
- child: Row(
- children: [
- Expanded(
- child: Text(label, style: AppType.body(color: boxText(1))),
- ),
- const SizedBox(width: 16),
- Text(hint, style: kBoxFaintStyle),
- ],
+ builder: (context, active) => Semantics(
+ toggled: checked,
+ child: Builder(
+ builder: (context) {
+ grid.AppTheme.watch(context);
+ return Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 8,
+ ),
+ child: Row(
+ children: [
+ SizedBox(
+ width: 16,
+ child: checked == true
+ ? Icon(
+ AppIcons.check,
+ size: 16,
+ color: active
+ ? grid.AppDesktop.onSelection
+ : DesktopChrome.foreground,
+ )
+ : null,
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ label,
+ style: DesktopChrome.control(
+ color: active ? grid.AppDesktop.onSelection : null,
+ ),
+ ),
+ ),
+ const SizedBox(width: 16),
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 140),
+ child: Text(
+ hint,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(
+ color: active ? grid.AppDesktop.onSelection : null,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ },
),
),
);
return [
option(
'Match case',
- _activeSearch?.caseSensitive == true ? 'on' : 'off',
+ _activeSearch?.caseSensitive == true ? 'On' : 'Off',
_toggleCase,
+ checked: _activeSearch?.caseSensitive == true,
),
if ((_activeSearch?.count ?? 0) > 0) ...[
- option('Next match', 'enter', () => widget.onStep(1)),
- option('Previous match', 'shift-enter', () => widget.onStep(-1)),
+ option('Next match', 'Enter', () => widget.onStep(1)),
+ option('Previous match', 'Shift+Enter', () => widget.onStep(-1)),
],
];
},
@@ -205,9 +248,13 @@ class TerminalFindBarState extends State<TerminalFindBar> {
@override
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
- return ListenableBuilder(
- listenable: terminalFontStore,
- builder: (context, _) => _buildBar(context),
+ // Find is part of the terminal's fixed-grid chrome. Its desktop options are
+ // inserted in the root Overlay and retain that overlay's platform text size.
+ return MediaQuery.withNoTextScaling(
+ child: ListenableBuilder(
+ listenable: terminalFontStore,
+ builder: (context, _) => _buildBar(context),
+ ),
);
}
@@ -305,7 +352,7 @@ class TerminalFindBarState extends State<TerminalFindBar> {
Tooltip(
message: 'This terminal is read only',
child: Icon(
- Icons.lock_outline,
+ AppIcons.lock,
size: 14,
color: boxText(.54),
),
@@ -358,7 +405,7 @@ class TerminalFindBarState extends State<TerminalFindBar> {
Builder(
builder: (context) => button(
'Find options',
- const Icon(Icons.more_horiz),
+ const Icon(AppIcons.ellipsis),
() => _openOptions(context),
),
)
@@ -380,7 +427,7 @@ class TerminalFindBarState extends State<TerminalFindBar> {
),
button(
'Previous match (Shift-Enter)',
- const Icon(Icons.keyboard_arrow_up),
+ const Icon(AppIcons.chevronUp),
count > 0
? () {
widget.onStep(-1);
@@ -390,7 +437,7 @@ class TerminalFindBarState extends State<TerminalFindBar> {
),
button(
'Next match (Enter)',
- const Icon(Icons.keyboard_arrow_down),
+ const Icon(AppIcons.chevronDown),
count > 0
? () {
widget.onStep(1);
@@ -401,7 +448,7 @@ class TerminalFindBarState extends State<TerminalFindBar> {
],
button(
'Close find (Esc)',
- const Icon(Icons.close),
+ const Icon(AppIcons.close),
widget.onClose,
),
],
diff --git a/desktop/lib/widgets/terminal_name_prompt.dart b/desktop/lib/widgets/terminal_name_prompt.dart
index a35594b57..41cc191a3 100644
--- a/desktop/lib/widgets/terminal_name_prompt.dart
+++ b/desktop/lib/widgets/terminal_name_prompt.dart
@@ -2,8 +2,10 @@ import 'dart:async';
import 'package:flutter/material.dart';
-import '../terminal/terminal_text.dart';
-import 'box_chrome.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import 'box_chrome.dart' show BoxAnnouncer, ReadlineKeys;
+import 'desktop_chrome.dart';
+import 'desktop_prompt_surface.dart';
import 'terminal_prompt.dart';
/// One rename editor for tabs, agents, and machines. A remote save may outlive
@@ -36,6 +38,7 @@ class _TerminalNamePromptState extends State<TerminalNamePrompt> {
text: widget.name,
)..selection = TextSelection(baseOffset: 0, extentOffset: widget.name.length);
final _input = FocusNode(debugLabel: 'Rename input');
+ final _body = ScrollController();
final _announcer = BoxAnnouncer();
bool _saving = false;
String? _error;
@@ -52,6 +55,7 @@ class _TerminalNamePromptState extends State<TerminalNamePrompt> {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && ModalRoute.of(context)?.isCurrent != false) {
_input.requestFocus();
+ if (_body.hasClients) _body.jumpTo(_body.position.maxScrollExtent);
}
});
}
@@ -60,6 +64,7 @@ class _TerminalNamePromptState extends State<TerminalNamePrompt> {
void dispose() {
_text.dispose();
_input.dispose();
+ _body.dispose();
super.dispose();
}
@@ -76,6 +81,13 @@ class _TerminalNamePromptState extends State<TerminalNamePrompt> {
});
_input.requestFocus();
_announcer.row(context, error);
+ // Enlarged text can make the title and detail scroll. Keep the field and
+ // its validation at the end of that scroll area above the fixed actions.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _body.hasClients) {
+ _body.jumpTo(_body.position.maxScrollExtent);
+ }
+ });
}
void _accept() {
@@ -124,118 +136,136 @@ class _TerminalNamePromptState extends State<TerminalNamePrompt> {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
- return ListenableBuilder(
- listenable: terminalFontStore,
- builder: (context, _) => TerminalPromptKeys(
- inputFocus: _input,
- composing: () => _composing,
- cancel: _close,
- accept: _accept,
- child: TerminalPrompt(
+ grid.AppTheme.watch(context);
+ final errorColor = Theme.of(context).colorScheme.error;
+ final border = OutlineInputBorder(
+ borderRadius: BorderRadius.circular(grid.AppDesktop.fieldRadius),
+ borderSide: BorderSide(color: DesktopChrome.rim),
+ );
+ return TerminalPromptKeys(
+ inputFocus: _input,
+ composing: () => _composing,
+ cancel: _close,
+ accept: _accept,
+ child: DesktopPromptSurface(
+ width: 460,
+ body: DesktopPromptScrollBody(
+ controller: _body,
child: Column(
- mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Flexible(
- child: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(widget.title, style: boxMonoStyle(color: kBoxFaint)),
- if (widget.detail case final detail?) ...[
- const SizedBox(height: 6),
- Text(
- detail,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ],
- const SizedBox(height: 10),
- ReadlineKeys(
- controller: _text,
- enabled: !_saving,
- onChanged: _changed,
- child: Semantics(
- label: widget.fieldLabel,
- child: TextField(
- key: widget.fieldKey,
- controller: _text,
- focusNode: _input,
- readOnly: _saving,
- maxLength: widget.maxLength,
- style: boxMonoStyle(),
- textAlignVertical: TextAlignVertical.center,
- textInputAction: TextInputAction.done,
- decoration: InputDecoration(
- hintText: widget.fieldLabel,
- hintStyle: boxMonoStyle(color: kBoxFaint),
- counterText: '',
- suffixText:
- widget.maxLength != null &&
- _text.text.characters.length >=
- widget.maxLength! - 10
- ? '${_text.text.characters.length}/${widget.maxLength}'
- : null,
- suffixStyle: kBoxFaintStyle,
- isDense: true,
- filled: false,
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- prefixIcon: Padding(
- padding: const EdgeInsets.only(right: 10),
- child: Center(
- widthFactor: 1,
- heightFactor: 1,
- child: Text(
- 'name >',
- style: boxMonoStyle(color: boxText(.70)),
- ),
- ),
- ),
- prefixIconConstraints: const BoxConstraints(
- minHeight: 38,
- ),
- contentPadding: EdgeInsets.zero,
- ),
- onChanged: _changed,
- onEditingComplete: () {},
- onSubmitted: (_) => _save(),
- ),
- ),
- ),
- if (_saving)
- Text(
- 'Saving continues if you close this prompt.',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ],
+ DesktopDialogHeader(
+ title: widget.title,
+ padding: EdgeInsets.zero,
+ ),
+ if (widget.detail case final detail?) ...[
+ const SizedBox(height: 8),
+ Text(
+ detail,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
),
),
+ ],
+ const SizedBox(height: DesktopChrome.groupGap),
+ Text(
+ widget.fieldLabel,
+ style: DesktopChrome.text(size: 13, medium: true),
),
- BoxHintStrip(
- message: _error ?? (_saving ? 'Saving name…' : null),
- isError: _error != null,
- hints: [
- if (!_saving)
- BoxHint(
- terminalPromptHint(context, 'picker.accept', 'enter'),
- 'save',
- onTap: _save,
+ const SizedBox(height: 8),
+ ReadlineKeys(
+ controller: _text,
+ enabled: !_saving,
+ onChanged: _changed,
+ child: Semantics(
+ label: widget.fieldLabel,
+ child: TextField(
+ key: widget.fieldKey,
+ controller: _text,
+ focusNode: _input,
+ readOnly: _saving,
+ maxLength: widget.maxLength,
+ style: DesktopChrome.text(size: 14),
+ cursorColor: DesktopChrome.accent,
+ textAlignVertical: TextAlignVertical.center,
+ textInputAction: TextInputAction.done,
+ decoration: InputDecoration(
+ hintText: widget.fieldLabel,
+ hintStyle: DesktopChrome.text(color: DesktopChrome.muted),
+ counterText: '',
+ suffixText:
+ widget.maxLength != null &&
+ _text.text.characters.length >=
+ widget.maxLength! - 10
+ ? '${_text.text.characters.length}/${widget.maxLength}'
+ : null,
+ suffixStyle: DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ ),
+ isDense: true,
+ filled: true,
+ fillColor: DesktopChrome.field,
+ border: border,
+ enabledBorder: border,
+ focusedBorder: border.copyWith(
+ borderSide: BorderSide(
+ color: DesktopChrome.focusRing,
+ width: grid.AppDesktop.focusWidth,
+ ),
+ ),
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 10,
+ ),
),
- BoxHint(
- terminalPromptHint(context, 'picker.cancel', 'esc'),
- 'close',
- onTap: _close,
+ onChanged: _changed,
+ onEditingComplete: () {},
+ onSubmitted: (_) => _save(),
),
- ],
+ ),
),
+ if (_error != null || _saving) ...[
+ const SizedBox(height: 12),
+ Semantics(
+ liveRegion: true,
+ child: DesktopPromptMessage(
+ _error ?? 'Saving name… You can close this dialog while it finishes.',
+ color: _error == null ? DesktopChrome.muted : errorColor,
+ ),
+ ),
+ ],
],
),
),
+ actions: [
+ Tooltip(
+ message:
+ 'Cancel · ${terminalPromptHint(context, 'picker.cancel', 'esc')}',
+ child: TextButton(
+ onPressed: _close,
+ style: TextButton.styleFrom(
+ foregroundColor: DesktopChrome.foreground,
+ textStyle: DesktopChrome.text(size: 13),
+ ),
+ child: const Text('Cancel'),
+ ),
+ ),
+ Tooltip(
+ message:
+ 'Save · ${terminalPromptHint(context, 'picker.accept', 'enter')}',
+ child: FilledButton(
+ onPressed: _saving ? null : _save,
+ style: FilledButton.styleFrom(
+ textStyle: DesktopChrome.text(size: 13),
+ ),
+ child: Text(_saving ? 'Saving…' : 'Save'),
+ ),
+ ),
+ ],
),
);
}
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 68981323d..520e69108 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -6,9 +6,9 @@ import 'dart:async';
import 'dart:convert';
import 'dart:math' as math;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
@@ -113,6 +113,9 @@ class TerminalPanel extends StatefulWidget {
/// where there is nothing to close it back to.
final VoidCallback? onClose;
+ /// Opens the workspace's shared model picker for this exact pane.
+ final VoidCallback? onOpenModels;
+
final VoidCallback? onDelete;
final VoidCallback? onToggleZoom;
@@ -185,6 +188,7 @@ class TerminalPanel extends StatefulWidget {
this.notice,
this.onToggleComposer,
this.onClose,
+ this.onOpenModels,
this.onDelete,
this.onToggleZoom,
this.zoomed = false,
@@ -2460,6 +2464,7 @@ class _TerminalPanelState extends State<TerminalPanel>
project: agent == null ? null : machine?.projectOf(agent),
compact: widget.compactHeader,
close: widget.onClose != null,
+ openModels: widget.onOpenModels != null,
delete: widget.onDelete != null,
composer: widget.composerVisible,
toggleComposer: widget.onToggleComposer != null,
@@ -2482,6 +2487,9 @@ class _TerminalPanelState extends State<TerminalPanel>
? null
: () => widget.onToggleZoom?.call(),
onClose: widget.onClose == null ? null : () => widget.onClose?.call(),
+ onOpenModels: widget.onOpenModels == null
+ ? null
+ : () => widget.onOpenModels?.call(),
onDelete: widget.onDelete == null
? null
: () => widget.onDelete?.call(),
@@ -2558,6 +2566,7 @@ class _TerminalHeader extends StatelessWidget {
final TerminalNotice? notice;
final bool readOnly;
final VoidCallback? onClose;
+ final VoidCallback? onOpenModels;
/// Ends the agent (with a confirmation), as the rail's row menu does. Null
/// where the pane cannot name a live agent to end.
@@ -2594,6 +2603,7 @@ class _TerminalHeader extends StatelessWidget {
this.notice,
this.readOnly = false,
this.onClose,
+ this.onOpenModels,
this.onDelete,
required this.onReconnect,
this.compact = false,
@@ -2639,25 +2649,25 @@ class _TerminalHeader extends StatelessWidget {
TerminalSessionStatus.controlling => null,
TerminalSessionStatus.opening => terminalNotice(
label: 'Connecting',
- icon: Icons.sync,
+ icon: AppIcons.refreshCw,
detail:
'Connecting to this terminal. Retained output is read only.',
),
TerminalSessionStatus.resyncing => terminalNotice(
label: 'Restoring',
- icon: Icons.sync,
+ icon: AppIcons.refreshCw,
detail: 'Restoring this terminal. Retained output is read only.',
),
TerminalSessionStatus.takenOver => terminalNotice(
label: 'Take control',
- icon: Icons.lock_outline,
+ icon: AppIcons.lock,
detail:
'Read only: ${taker ?? 'another app'} controls this terminal. Take control moves input ownership to this app.',
),
TerminalSessionStatus.error ||
TerminalSessionStatus.closed => terminalNotice(
label: 'Reconnect',
- icon: Icons.refresh,
+ icon: AppIcons.refreshCw,
detail:
session.errorMessage ??
session.errorCode ??
@@ -2692,7 +2702,7 @@ class _TerminalHeader extends StatelessWidget {
].join('\n');
// Reserve space for the pane-local model selector.
// Engines without a picker keep their existing header width.
- final showModelPicker = !compact && modelPickerSupports(session.engineId);
+ final showModelPicker = modelPickerSupports(session.engineId);
// The picker: a model id up to 220px and its padding.
final pickerWidth = showModelPicker ? 250.0 : 0.0;
final closeWidth = onClose == null
@@ -2757,7 +2767,9 @@ class _TerminalHeader extends StatelessWidget {
);
// The name/status retain space while model and project text yield.
final rightWidth = math.min(
- compact ? closeWidth : desiredRightWidth,
+ compact
+ ? math.min(actionsWidth, constraints.maxWidth * .38)
+ : desiredRightWidth,
math.max(0.0, constraints.maxWidth - 99),
);
return Row(
@@ -2902,7 +2914,14 @@ class _TerminalHeader extends StatelessWidget {
else if (!compact)
Padding(
padding: const EdgeInsets.all(4),
- child: Icon(Icons.circle, size: 8, color: color),
+ child: Container(
+ width: 8,
+ height: 8,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: color,
+ ),
+ ),
),
],
),
@@ -2921,34 +2940,28 @@ class _TerminalHeader extends StatelessWidget {
child: _LinkModeMark(mode: session.linkMode!),
),
ConstrainedBox(
- constraints: BoxConstraints(maxWidth: rightWidth),
+ constraints: BoxConstraints(
+ maxWidth: math.max(0, rightWidth - closeWidth),
+ ),
child: PaneHeaderActions(
- trailing: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- if (showPr)
- Flexible(
- child: ConstrainedBox(
- constraints: BoxConstraints(maxWidth: badgeWidth),
- child: PullRequestBadge(
- compact: narrow,
- identity: (
- session.machineId,
- agent.id,
- project?.cwd,
- project?.shownBranch,
- ),
- read: () => notifier.readAgentPullRequest(
- session.machineId,
- agent.id,
- ),
+ trailing: showPr
+ ? ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: badgeWidth),
+ child: PullRequestBadge(
+ compact: narrow,
+ identity: (
+ session.machineId,
+ agent.id,
+ project?.cwd,
+ project?.shownBranch,
+ ),
+ read: () => notifier.readAgentPullRequest(
+ session.machineId,
+ agent.id,
),
),
- ),
- if (onClose != null)
- PaneCloseButton(onPressed: onClose!),
- ],
- ),
+ )
+ : null,
modelPicker: showModelPicker
? GridModelPicker(
key: ValueKey((
@@ -2957,6 +2970,7 @@ class _TerminalHeader extends StatelessWidget {
session.agentId,
)),
paneHeader: true,
+ onOpen: onOpenModels,
enabled: !readOnly && !session.readOnly,
compact: narrow,
notifier: notifier,
@@ -3020,13 +3034,14 @@ class _TerminalHeader extends StatelessWidget {
),
),
),
+ if (onClose != null) PaneCloseButton(onPressed: onClose!),
],
);
},
),
),
);
- final strip = PaneHeaderHoverRegion(child: header);
+ final strip = header;
final handle = paneDrag;
if (handle == null) return strip;
@@ -3118,17 +3133,17 @@ class _LinkModeMark extends StatelessWidget {
Widget build(BuildContext context) {
final (icon, color, label) = switch (mode) {
'p2p' => (
- LucideIcons.link2,
+ AppIcons.link2,
AppColors.success,
'P2P · Direct peer connection',
),
'turn' => (
- LucideIcons.waypoints,
+ AppIcons.waypoints,
AppColors.warning,
'TURN · Via Cloudflare relay',
),
_ => (
- LucideIcons.server,
+ AppIcons.server,
AppColors.mutedStrong,
'WS · Via Harness WebSocket relay',
),
@@ -3209,7 +3224,7 @@ class _ControlBanner extends StatelessWidget {
grid.AppTheme.watch(context);
// A notice that failed is red; everything else on this strip is the amber
// of "paused, and you can do something about it".
- final ink = notice != null && notice!.icon == Icons.error_outline
+ final ink = notice != null && notice!.icon == AppIcons.circleAlert
? AppColors.danger
: AppColors.warning;
final detail = this.detail;
@@ -3259,7 +3274,7 @@ class _ControlBanner extends StatelessWidget {
final lead = notice != null
? Icon(notice!.icon, size: 16, color: ink)
: !busy
- ? Icon(Icons.lock_outline, size: 16, color: ink)
+ ? Icon(AppIcons.lock, size: 16, color: ink)
: SizedBox(
width: 16,
height: 16,
@@ -3276,7 +3291,7 @@ class _ControlBanner extends StatelessWidget {
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: grid.AppType.label(
+ style: grid.AppType.mono(
color: AppColors.text,
fontWeight: FontWeight.w600,
),
@@ -3365,10 +3380,17 @@ class _ControlBannerButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final onAccent = Theme.of(context).colorScheme.onPrimary;
+ final scheme = Theme.of(context).colorScheme;
+ final onAccent = scheme.onSurface;
return FilledButton(
onPressed: onPressed,
style: FilledButton.styleFrom(
+ backgroundColor: Color.alphaBlend(
+ scheme.onSurface.withValues(alpha: .10),
+ scheme.surface,
+ ),
+ foregroundColor: scheme.onSurface,
+ side: BorderSide(color: scheme.onSurface.withValues(alpha: .14)),
minimumSize: const Size(0, 28),
padding: const EdgeInsets.fromLTRB(12, 0, 8, 0),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
@@ -3377,7 +3399,12 @@ class _ControlBannerButton extends StatelessWidget {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- Flexible(child: Text(label, style: grid.AppType.label())),
+ Flexible(
+ child: Text(
+ label,
+ style: grid.AppType.mono(fontWeight: FontWeight.w500),
+ ),
+ ),
if (showReturnKey) ...[
const SizedBox(width: 8),
Container(
@@ -3388,7 +3415,7 @@ class _ControlBannerButton extends StatelessWidget {
),
child: Semantics(
label: 'Return',
- child: Icon(Icons.keyboard_return, size: 12, color: onAccent),
+ child: Icon(AppIcons.cornerDownLeft, size: 12, color: onAccent),
),
),
],
@@ -3432,7 +3459,10 @@ class _TransferProgressBadge extends StatelessWidget {
child: Text(
'$label$percentLabel',
overflow: TextOverflow.ellipsis,
- style: grid.AppType.label(color: AppColors.textSoft),
+ style: grid.AppType.mono(
+ color: AppColors.textSoft,
+ fontWeight: FontWeight.w500,
+ ),
),
),
const SizedBox(width: 8),
@@ -3440,7 +3470,10 @@ class _TransferProgressBadge extends StatelessWidget {
onTap: onCancel,
child: Text(
'CANCEL',
- style: grid.AppType.label(color: AppColors.textSoft),
+ style: grid.AppType.mono(
+ color: AppColors.textSoft,
+ fontWeight: FontWeight.w500,
+ ),
),
),
],
diff --git a/desktop/lib/widgets/terminal_prompt.dart b/desktop/lib/widgets/terminal_prompt.dart
index ae8776ac2..e8f4c6f0d 100644
--- a/desktop/lib/widgets/terminal_prompt.dart
+++ b/desktop/lib/widgets/terminal_prompt.dart
@@ -182,6 +182,7 @@ class TerminalPromptKeys extends StatelessWidget {
final focused = Focus(
focusNode: focusNode,
autofocus: true,
+ skipTraversal: true,
onKeyEvent: (_, event) => _key(context, event),
child: child,
);
diff --git a/desktop/lib/widgets/terminal_text_action.dart b/desktop/lib/widgets/terminal_text_action.dart
index 527d977da..a86e2a4dc 100644
--- a/desktop/lib/widgets/terminal_text_action.dart
+++ b/desktop/lib/widgets/terminal_text_action.dart
@@ -1,11 +1,9 @@
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../terminal/terminal_text.dart';
-import '../terminal/terminal_theme.dart';
-import '../terminal/terminal_theme_store.dart';
+import 'desktop_chrome.dart';
-/// A named terminal action: brackets, one text row, and a flat focus highlight.
+/// Named workspace actions use the same rounded desktop buttons as dialogs.
class TerminalTextAction extends StatelessWidget {
const TerminalTextAction({
super.key,
@@ -23,55 +21,28 @@ class TerminalTextAction extends StatelessWidget {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
grid.AppTheme.watch(context);
- return ValueListenableBuilder(
- valueListenable: terminalThemeStore,
- builder: (context, _, _) {
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
- final cell = terminalCellSizeOf(context);
- return TextButton(
- focusNode: focusNode,
- onPressed: onPressed,
- style:
- TextButton.styleFrom(
- foregroundColor: overArtwork ? Colors.white : theme.foreground,
- backgroundColor: overArtwork
- ? const Color(0xcc242424)
- : Colors.transparent,
- textStyle: terminalContentStyle(),
- padding:
- padding ?? EdgeInsets.symmetric(horizontal: cell.width),
- disabledForegroundColor: theme.foreground.withValues(
- alpha: .28,
- ),
- minimumSize: Size.zero,
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- shape: const RoundedRectangleBorder(),
- splashFactory: NoSplash.splashFactory,
- ).copyWith(
- overlayColor: WidgetStateProperty.resolveWith(
- (states) =>
- states.any(
- {
- WidgetState.hovered,
- WidgetState.focused,
- WidgetState.pressed,
- }.contains,
- )
- ? theme.selection.withValues(alpha: .5)
- : Colors.transparent,
- ),
- ),
- child: SizedBox(
- height: cell.height,
- child: Text('[ $label ]', semanticsLabel: label),
- ),
- );
- },
+ final foreground = overArtwork ? Colors.white : DesktopChrome.foreground;
+ return TextButton(
+ focusNode: focusNode,
+ onPressed: onPressed,
+ style: TextButton.styleFrom(
+ foregroundColor: foreground,
+ disabledForegroundColor: foreground.withValues(alpha: .38),
+ backgroundColor: overArtwork
+ ? const Color(0xcc303030)
+ : foreground.withValues(alpha: .07),
+ side: BorderSide(color: foreground.withValues(alpha: .14)),
+ shape: const StadiumBorder(),
+ minimumSize: const Size(0, 32),
+ padding: (padding ?? EdgeInsets.zero).add(
+ const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
+ ),
+ textStyle: DesktopChrome.text(size: 13),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ splashFactory: NoSplash.splashFactory,
+ ),
+ child: Text(label),
);
}
}
diff --git a/desktop/lib/widgets/update_notice.dart b/desktop/lib/widgets/update_notice.dart
index 06b79ab74..1e1c94b8f 100644
--- a/desktop/lib/widgets/update_notice.dart
+++ b/desktop/lib/widgets/update_notice.dart
@@ -1,7 +1,7 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/terminal/terminal_text.dart';
import '../core/app_version.dart';
@@ -109,8 +109,8 @@ class UpdateNotice extends StatelessWidget {
)
: Icon(
failed
- ? LucideIcons.triangleAlert300
- : LucideIcons.arrowDownToLine300,
+ ? AppIcons.triangleAlert
+ : AppIcons.arrowDownToLine,
size: 16,
color: markColor,
),
@@ -312,7 +312,7 @@ Future<void> showUpdateCheckDialog(
builder: (context, setState) {
if (checking) {
return const _UpdateDialog(
- icon: LucideIcons.refreshCw300,
+ icon: AppIcons.refreshCw,
title: 'Checking for updates…',
body: 'Looking for a newer version of Harness.',
busy: true,
@@ -320,7 +320,7 @@ Future<void> showUpdateCheckDialog(
}
if (current.status == DesktopUpdateCheckStatus.failed) {
return _UpdateDialog(
- icon: LucideIcons.triangleAlert300,
+ icon: AppIcons.triangleAlert,
tone: _DialogTone.warning,
title: 'Couldn’t check for updates',
body:
@@ -349,7 +349,7 @@ Future<void> showUpdateCheckDialog(
}
if (current.status == DesktopUpdateCheckStatus.disabled) {
return const _UpdateDialog(
- icon: LucideIcons.info300,
+ icon: AppIcons.info,
title: 'Updates are off for this build',
body: 'This build does not check for or install desktop updates.',
);
@@ -359,7 +359,7 @@ Future<void> showUpdateCheckDialog(
return FutureBuilder<String>(
future: installedVersion ??= runningAppVersion(),
builder: (context, snapshot) => _UpdateDialog(
- icon: LucideIcons.circleCheck300,
+ icon: AppIcons.circleCheck,
tone: _DialogTone.ok,
title: 'You’re up to date',
body: snapshot.hasData
@@ -383,7 +383,7 @@ Future<void> showUpdateCheckDialog(
final installingVersion =
notifier.availableUpdate?.version ?? update.version;
return _UpdateDialog(
- icon: LucideIcons.arrowDownToLine300,
+ icon: AppIcons.arrowDownToLine,
title: installing
? 'Installing Harness $installingVersion…'
: 'Harness ${update.version} is available',
diff --git a/desktop/lib/widgets/verdict_marks.dart b/desktop/lib/widgets/verdict_marks.dart
index 00eb7afee..71f80b535 100644
--- a/desktop/lib/widgets/verdict_marks.dart
+++ b/desktop/lib/widgets/verdict_marks.dart
@@ -1,8 +1,9 @@
// The one status a harness's verdict puts in the viewer pane's title: ready,
// or what stands in the way, or where the work is. One mark, each new state
// replacing the last — a status, not a history.
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/terminal/terminal_text.dart';
import '../core/models.dart';
@@ -32,25 +33,25 @@ class VerdictStatus extends StatelessWidget {
final last = verdict.currentPhase;
final (icon, color, label, weight) = working
? (
- LucideIcons.loaderCircle,
+ AppIcons.loaderCircle,
AppColors.text,
active?.name ?? 'Working',
FontWeight.w600,
)
: verdict.ready
- ? (LucideIcons.circleCheck, AppColors.success, 'Ready', FontWeight.w700)
+ ? (AppIcons.circleCheck, AppColors.success, 'Ready', FontWeight.w700)
: verdict.errors > 0
? (
- LucideIcons.circleX,
+ AppIcons.circleX,
AppColors.danger,
_count(verdict.errors, 'error'),
FontWeight.w600,
)
: active != null
- ? (LucideIcons.circleDot, AppColors.text, active.name, FontWeight.w700)
+ ? (AppIcons.circleDot, AppColors.text, active.name, FontWeight.w700)
: verdict.warnings > 0
? (
- LucideIcons.triangleAlert,
+ AppIcons.triangleAlert,
AppColors.warning,
_count(verdict.warnings, 'warning'),
FontWeight.w600,
@@ -58,8 +59,8 @@ class VerdictStatus extends StatelessWidget {
: last != null
? (
last.state == AgentPhaseState.failed
- ? LucideIcons.x
- : LucideIcons.check,
+ ? AppIcons.close
+ : AppIcons.check,
last.state == AgentPhaseState.failed
? AppColors.danger
: AppColors.success,
@@ -67,7 +68,7 @@ class VerdictStatus extends StatelessWidget {
FontWeight.w500,
)
: (
- LucideIcons.circleDashed,
+ AppIcons.circleDashed,
AppColors.mutedStrong,
'Checked',
FontWeight.w500,
diff --git a/desktop/lib/widgets/web_download_button.dart b/desktop/lib/widgets/web_download_button.dart
index d0c9c656e..f3bbb6113 100644
--- a/desktop/lib/widgets/web_download_button.dart
+++ b/desktop/lib/widgets/web_download_button.dart
@@ -22,7 +22,7 @@ class WebDownloadButton extends StatelessWidget {
static final uri = Uri.parse(
'https://www.autonomous.ai/harness-app?page=download',
);
- static const _text = '[ Download app ]';
+ static const _text = 'Download app';
static double widthOf(BuildContext context) =>
workspaceBarTextSizeOf(context, _text).width +
diff --git a/desktop/lib/widgets/web_pane_panel.dart b/desktop/lib/widgets/web_pane_panel.dart
index 71de024cd..2fbe6c6ed 100644
--- a/desktop/lib/widgets/web_pane_panel.dart
+++ b/desktop/lib/widgets/web_pane_panel.dart
@@ -1,6 +1,6 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
@@ -353,7 +353,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
if (widget.pane.viewerError case final error?) {
return _Notice(
key: const ValueKey('web-pane-error'),
- icon: LucideIcons.unplug,
+ icon: AppIcons.unplug,
title: 'Viewer unavailable',
detail: error,
);
@@ -368,7 +368,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
final page = url == null ? null : Uri.tryParse(url);
return _Notice(
key: const ValueKey('web-pane-placeholder'),
- icon: LucideIcons.globe,
+ icon: AppIcons.globe,
title: 'Viewer',
detail: page == null
? 'No viewer yet.'
@@ -390,7 +390,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
ColoredBox(
color: grid.AppPalette.windowBg,
child: _Notice(
- icon: LucideIcons.unplug,
+ icon: AppIcons.unplug,
title: 'Waiting for the viewer',
detail: _failure!,
action: TextButton(
@@ -448,15 +448,15 @@ class _ViewerActions extends StatelessWidget {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
- action('Reload viewer', LucideIcons.refreshCw, onReload),
+ action('Reload viewer', AppIcons.refreshCw, onReload),
const SizedBox(width: 2),
action(
zoomed ? 'Restore harnesses' : 'Zoom viewer',
- zoomed ? LucideIcons.minimize : LucideIcons.maximize,
+ zoomed ? AppIcons.minimize : AppIcons.maximize,
onZoom,
),
const SizedBox(width: 2),
- action('Close viewer', LucideIcons.x, onClose),
+ action('Close viewer', AppIcons.close, onClose),
],
);
}
@@ -479,7 +479,7 @@ class _Notice extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
- child: Padding(
+ child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
diff --git a/desktop/lib/widgets/workspace_bar_control.dart b/desktop/lib/widgets/workspace_bar_control.dart
index f9cc8f4f5..235fe72aa 100644
--- a/desktop/lib/widgets/workspace_bar_control.dart
+++ b/desktop/lib/widgets/workspace_bar_control.dart
@@ -98,13 +98,13 @@ class _WorkspaceBarControlState extends State<WorkspaceBarControl> {
}
}
-/// The numeric prefix is navigation, not a different name worth repeating.
+/// The visible name needs a tooltip only when clipped or shortened.
String? workspaceTabTooltip(
String label,
String name, {
required bool clipped,
}) {
- final visibleName = label.replaceFirst(RegExp(r'^\d+:'), '').trim();
+ final visibleName = label.trim();
final hint = [
if (clipped) label,
if (name.trim().isNotEmpty && name.trim() != visibleName && name != label)
diff --git a/desktop/lib/widgets/workspace_machine_prompt.dart b/desktop/lib/widgets/workspace_machine_prompt.dart
new file mode 100644
index 000000000..8b3332bb3
--- /dev/null
+++ b/desktop/lib/widgets/workspace_machine_prompt.dart
@@ -0,0 +1,57 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import 'desktop_chrome.dart';
+
+/// The empty workspace's next step before its creation form is ready.
+/// Inventory and choosing a machine remain owned by the workspace.
+class WorkspaceMachinePrompt extends StatelessWidget {
+ const WorkspaceMachinePrompt({
+ super.key,
+ required this.loading,
+ required this.onChoose,
+ this.preparing = false,
+ });
+
+ final bool loading;
+ final VoidCallback onChoose;
+ final bool preparing;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Semantics(
+ header: true,
+ child: Text(
+ 'Harness anything',
+ textAlign: TextAlign.center,
+ style: grid.AppType.display(color: DesktopChrome.foreground),
+ ),
+ ),
+ const SizedBox(height: 8),
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ preparing
+ ? 'Preparing your harness…'
+ : loading
+ ? 'Finding your machines…'
+ : 'Choose a machine to start a new harness.',
+ textAlign: TextAlign.center,
+ style: DesktopChrome.text(color: DesktopChrome.muted),
+ ),
+ ),
+ if (!preparing) ...[
+ const SizedBox(height: 24),
+ FilledButton(
+ onPressed: onChoose,
+ child: const Text('Choose a machine'),
+ ),
+ ],
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/widgets/workspace_notifications_button.dart b/desktop/lib/widgets/workspace_notifications_button.dart
index d49127287..0bbeb4992 100644
--- a/desktop/lib/widgets/workspace_notifications_button.dart
+++ b/desktop/lib/widgets/workspace_notifications_button.dart
@@ -1,5 +1,5 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/workspace_bar_style.dart';
import 'workspace_bar_control.dart';
@@ -41,7 +41,7 @@ class WorkspaceNotificationsButton extends StatelessWidget {
style: const TextStyle(fontSize: 9, fontWeight: FontWeight.w600),
),
child: Icon(
- LucideIcons.bell,
+ AppIcons.bell,
size: 17,
color: foreground.withValues(
alpha: onPressed == null
diff --git a/desktop/lib/widgets/workspace_quick_start.dart b/desktop/lib/widgets/workspace_quick_start.dart
index 19575ecd7..4ab2b23b6 100644
--- a/desktop/lib/widgets/workspace_quick_start.dart
+++ b/desktop/lib/widgets/workspace_quick_start.dart
@@ -1,9 +1,9 @@
import 'package:flutter/material.dart';
-import 'package:harness/terminal/terminal_text.dart';
+import '../shared/theme/app_theme.dart' as grid;
import '../shortcuts/app_keymap.dart';
import '../state/workspace_learning.dart';
-import 'box_chrome.dart';
+import 'desktop_chrome.dart';
/// A temporary guide beside real work. It never requests terminal focus.
class WorkspaceQuickStart extends StatelessWidget {
@@ -19,7 +19,7 @@ class WorkspaceQuickStart extends StatelessWidget {
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
final next = learning.next;
final (command, label) = switch (next) {
WorkspaceLesson.agent => ('swarm.new', 'Open your first harness'),
@@ -37,44 +37,44 @@ class WorkspaceQuickStart extends StatelessWidget {
'Workspace ready. Keep learning at your own pace.',
),
};
- final keys = KeymapTheme.of(context)?.hint(command);
- final hint = keys == null ? null : boxKeyLabel(keys);
- return TerminalBox(
- docked: true,
+ final hint = KeymapTheme.of(context)?.hint(command);
+ return Container(
+ width: double.infinity,
+ decoration: BoxDecoration(
+ color: grid.AppSurface.recess,
+ border: Border(bottom: BorderSide(color: DesktopChrome.rim)),
+ ),
child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Wrap(
- spacing: 14,
- runSpacing: 2,
+ spacing: 16,
+ runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
next == null
- ? 'quick start [done]'
- : 'quick start ${next.index + 1}/4',
- style: boxMonoStyle(color: kBoxFaint),
+ ? 'Quick start · Complete'
+ : 'Quick start · ${next.index + 1} of 4',
+ style: DesktopChrome.metadata(),
),
Semantics(
liveRegion: true,
- child: Text(label, style: boxMonoStyle()),
+ child: Text(label, style: DesktopChrome.control()),
),
- TextButton(
+ DesktopPill(
key: const ValueKey('quick-start-action'),
onPressed: next == null ? onPractice : () => onCommand(command),
- child: Text(
- next == null
- ? 'Keyboard practice'
- : '${hint == null ? '' : '$hint '}${next == WorkspaceLesson.commands ? 'Search commands' : 'Try it'}',
- style: boxMonoStyle(),
- ),
+ compact: true,
+ label: next == null
+ ? 'Keyboard practice'
+ : '${hint == null ? '' : '$hint '}${next == WorkspaceLesson.commands ? 'Search commands' : 'Try it'}',
),
- TextButton(
+ DesktopPill(
key: const ValueKey('quick-start-pause'),
onPressed: learning.pause,
- child: Text(
- next == null ? 'Done' : 'Pause guide',
- style: boxMonoStyle(color: kBoxFaint),
- ),
+ compact: true,
+ quiet: true,
+ label: next == null ? 'Done' : 'Pause guide',
),
],
),
diff --git a/desktop/lib/widgets/workspace_share_button.dart b/desktop/lib/widgets/workspace_share_button.dart
index c885e0e3f..07e4e63b1 100644
--- a/desktop/lib/widgets/workspace_share_button.dart
+++ b/desktop/lib/widgets/workspace_share_button.dart
@@ -17,7 +17,7 @@ class WorkspaceShareButton extends StatelessWidget {
final String tooltip;
final VoidCallback? onPressed;
- static const text = '[ Share ]';
+ static const text = 'Share';
static double widthOf(BuildContext context) =>
workspaceBarTextSizeOf(context, text).width +
diff --git a/desktop/lib/widgets/workspace_start_guide.dart b/desktop/lib/widgets/workspace_start_guide.dart
index 417f110d0..cc90d82cb 100644
--- a/desktop/lib/widgets/workspace_start_guide.dart
+++ b/desktop/lib/widgets/workspace_start_guide.dart
@@ -1,11 +1,11 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
-import 'package:harness/terminal/terminal_text.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
import '../shortcuts/keymap_commands.dart';
-import 'box_chrome.dart';
+import 'desktop_chrome.dart';
import 'welcome_project_example.dart';
/// A quiet, live keyboard map for an empty workspace. The drawing illustrates
@@ -29,12 +29,12 @@ class WorkspaceStartGuide extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- final ink = grid.AppTheme.palette.value.foreground;
- final faint = ink.withValues(alpha: .62);
- final accent = grid.AppPalette.swarmAccent;
- final stroke = faint.withValues(alpha: .30);
+ final ink = DesktopChrome.foreground;
+ final faint = DesktopChrome.muted;
+ final accent = DesktopChrome.accent;
+ final stroke = DesktopChrome.rim;
return Material(
- color: grid.AppPalette.swarmWelcome,
+ color: DesktopChrome.surface,
child: LayoutBuilder(
builder: (context, constraints) {
final scale = grid.appTextScaleOf(context);
@@ -57,43 +57,63 @@ class WorkspaceStartGuide extends StatelessWidget {
TextSpan(text: label),
],
),
- style: boxMonoStyle(color: ink),
+ style: DesktopChrome.control(medium: true),
),
const SizedBox(height: 4),
- Text(explanation, style: boxMonoStyle(color: faint)),
+ Text(explanation, style: DesktopChrome.metadata()),
],
),
);
+ final newTab = callout(
+ 'swarm.new',
+ 'New Tab',
+ 'Group multiple harnesses in one tab.',
+ );
+ final store = callout(
+ 'app.store',
+ 'Harness Store',
+ 'Code, 3D design, circuits, video, and more.',
+ );
+ final shortcuts = Align(
+ alignment: Alignment.centerLeft,
+ child: DesktopPill(
+ key: const ValueKey('workspace-all-shortcuts'),
+ onPressed: onShortcuts,
+ quiet: true,
+ label:
+ '${_hint(context, 'keyboard.help')} All keyboard shortcuts'
+ .trimLeft(),
+ ),
+ );
+ final newPane = callout(
+ 'agent.open',
+ 'New Pane',
+ 'Add a harness beside your work.',
+ );
final diagram = Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
- padding: const EdgeInsets.only(bottom: 40),
+ padding: const EdgeInsets.only(bottom: 24),
child: Text(
'Follow your curiosity. Build across disciplines.',
textAlign: TextAlign.center,
- style: boxMonoStyle(color: ink, weight: FontWeight.w600),
+ style: DesktopChrome.heading(),
),
),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Flexible(
- child: callout(
- 'swarm.new',
- 'New Swarm',
- 'Group multiple harnesses in one swarm.',
- ),
- ),
- Flexible(
- child: callout(
- 'app.store',
- 'Harness Store',
- 'Code, 3D design, circuits, video, and more.',
- ),
- ),
- ],
- ),
+ if (compact)
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [newTab, const SizedBox(height: 8), store],
+ )
+ else
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Flexible(child: newTab),
+ Flexible(child: store),
+ ],
+ ),
SizedBox(
height: 14,
width: double.infinity,
@@ -101,7 +121,11 @@ class WorkspaceStartGuide extends StatelessWidget {
),
ExcludeSemantics(
child: Container(
- decoration: BoxDecoration(border: Border.all(color: stroke)),
+ decoration: BoxDecoration(
+ color: DesktopChrome.field,
+ border: Border.all(color: stroke),
+ borderRadius: BorderRadius.circular(8),
+ ),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
@@ -123,24 +147,24 @@ class WorkspaceStartGuide extends StatelessWidget {
'robot arm',
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(color: faint),
+ style: DesktopChrome.control(),
),
),
if (!compact) ...[
const SizedBox(width: 32),
Text(
'launch video',
- style: boxMonoStyle(color: faint),
+ style: DesktopChrome.control(),
),
],
const SizedBox(width: 20),
- Text('+', style: boxMonoStyle(color: faint)),
+ Icon(AppIcons.plus, size: 16, color: faint),
],
),
),
Text(
compact ? 'Store' : 'Harness Store',
- style: boxMonoStyle(color: faint),
+ style: DesktopChrome.control(),
),
],
),
@@ -213,35 +237,18 @@ class WorkspaceStartGuide extends StatelessWidget {
width: double.infinity,
child: CustomPaint(painter: _GuideArrows(stroke)),
),
- Row(
- children: [
- Expanded(
- child: Align(
- alignment: Alignment.centerLeft,
- child: TextButton(
- key: const ValueKey('workspace-all-shortcuts'),
- onPressed: onShortcuts,
- style: TextButton.styleFrom(foregroundColor: faint),
- child: Text(
- '${_hint(context, 'keyboard.help')} All Keyboard Shortcuts'
- .trimLeft(),
- style: boxMonoStyle(color: faint),
- ),
- ),
- ),
- ),
- Expanded(
- child: Align(
- alignment: Alignment.center,
- child: callout(
- 'agent.open',
- 'New Pane',
- 'Add a harness beside your work.',
- ),
- ),
- ),
- ],
- ),
+ if (compact)
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [newPane, const SizedBox(height: 8), shortcuts],
+ )
+ else
+ Row(
+ children: [
+ Expanded(child: shortcuts),
+ Expanded(child: newPane),
+ ],
+ ),
],
);
final horizontalPadding = compact ? 16.0 : 24.0;
@@ -286,7 +293,6 @@ class _DrawnPane extends StatelessWidget {
final bool showLocation;
@override
Widget build(BuildContext context) {
- TerminalFontScope.watch(context);
final copy = Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -295,7 +301,7 @@ class _DrawnPane extends StatelessWidget {
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(color: ink),
+ style: DesktopChrome.control(color: ink, medium: true),
),
if (showLocation) ...[
const SizedBox(height: 6),
@@ -303,7 +309,7 @@ class _DrawnPane extends StatelessWidget {
'This Mac:~/work/robot-arm',
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(color: faint),
+ style: grid.AppType.monoMeta(color: faint),
),
],
const SizedBox(height: 10),
@@ -319,7 +325,7 @@ class _DrawnPane extends StatelessWidget {
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(color: ink),
+ style: grid.AppType.monoLabel(color: ink),
),
],
);
diff --git a/desktop/lib/widgets/workspace_store_button.dart b/desktop/lib/widgets/workspace_store_button.dart
index 44ba5b324..ceb326df5 100644
--- a/desktop/lib/widgets/workspace_store_button.dart
+++ b/desktop/lib/widgets/workspace_store_button.dart
@@ -1,8 +1,10 @@
+import 'dart:math' as math;
+
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../shared/theme/workspace_bar_style.dart';
import '../store/store_mark.dart';
+import 'desktop_chrome.dart';
import 'workspace_bar_control.dart';
/// The Store's rounded, marked button, restored from the original tab bar.
@@ -18,8 +20,19 @@ class WorkspaceStoreButton extends StatelessWidget {
final String tooltip;
final VoidCallback? onPressed;
- static double widthOf(BuildContext context) =>
- workspaceBarTextSizeOf(context, 'Harness Store').width + 52;
+ static Size _labelSize(BuildContext context) {
+ final painter = TextPainter(
+ text: TextSpan(text: 'Harness Store', style: DesktopChrome.control()),
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ maxLines: 1,
+ )..layout();
+ final size = painter.size;
+ painter.dispose();
+ return size;
+ }
+
+ static double widthOf(BuildContext context) => _labelSize(context).width + 52;
@override
Widget build(BuildContext context) {
@@ -32,7 +45,10 @@ class WorkspaceStoreButton extends StatelessWidget {
onPressed: onPressed,
builder: (context, emphasized) => Container(
width: width,
- height: workspaceBarControlHeight(context),
+ height: math.max(
+ grid.AppControl.heightSmall,
+ _labelSize(context).height + 12,
+ ),
padding: const EdgeInsets.symmetric(horizontal: 12),
decoration: ShapeDecoration(
color: Color.alphaBlend(
@@ -61,7 +77,7 @@ class WorkspaceStoreButton extends StatelessWidget {
'Harness Store',
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: workspaceBarTextStyle(
+ style: DesktopChrome.control(
color: accent.withValues(alpha: enabled ? 1 : .45),
),
),
diff --git a/desktop/lib/widgets/workspace_subscription_usage.dart b/desktop/lib/widgets/workspace_subscription_usage.dart
new file mode 100644
index 000000000..42d0c6b2c
--- /dev/null
+++ b/desktop/lib/widgets/workspace_subscription_usage.dart
@@ -0,0 +1,96 @@
+import 'package:flutter/painting.dart';
+
+import '../shared/theme/status_line_style.dart';
+import '../theme/app_theme.dart';
+
+enum WorkspaceUsageTone { normal, low, exhausted }
+
+/// One shared reading for the Flutter and native workspace footers. The Models
+/// controller owns freshness, limiting windows and account deduplication.
+class WorkspaceSubscriptionUsage {
+ const WorkspaceSubscriptionUsage._(this.segments, this.detail);
+
+ final List<({String text, WorkspaceUsageTone tone})> segments;
+ String get text => segments.map((part) => part.text).join();
+ final String detail;
+
+ /// Names stay neutral. Only a known remaining percentage carries urgency;
+ /// use the model picker's 20% low-water mark and reserve red for exhaustion.
+ List<StatusLinePaintSegment> paintSegments({
+ required Color foreground,
+ required Color surface,
+ }) => [
+ for (final part in segments)
+ StatusLinePaintSegment(
+ part.text,
+ statusLineInkOnSurface(switch (part.tone) {
+ WorkspaceUsageTone.normal => foreground,
+ WorkspaceUsageTone.low => AppColors.warning,
+ WorkspaceUsageTone.exhausted => AppColors.danger,
+ }, surface),
+ null,
+ ),
+ ];
+
+ factory WorkspaceSubscriptionUsage.fromRows(List<Map<String, Object?>> rows) {
+ final accounts = rows
+ .where((row) => row['status'] != 'Not signed in')
+ .toList();
+ final counts = <Object?, int>{};
+ for (final row in accounts) {
+ counts.update(row['engine'], (count) => count + 1, ifAbsent: () => 1);
+ }
+ final segments = <({String text, WorkspaceUsageTone tone})>[];
+ final details = <String>['Remaining subscription usage'];
+ final positions = <Object?, int>{};
+ for (final row in accounts) {
+ final engine = row['engine'];
+ final provider = switch (engine) {
+ 'claude' => 'Claude',
+ 'codex' => 'Codex',
+ _ => row['title'] as String? ?? 'Subscription',
+ };
+ final account = row['account'] as String? ?? '';
+ final position = positions.update(
+ engine,
+ (n) => n + 1,
+ ifAbsent: () => 1,
+ );
+ final name = counts[engine]! > 1
+ ? '$provider ${account.isEmpty ? position : account}'
+ : provider;
+ final status = row['status'] as String? ?? 'Usage unavailable';
+ final remaining = row['remainingPercent'];
+ final figure = remaining is num && remaining.isFinite
+ ? status.replaceFirst(RegExp(r' remaining$'), '')
+ : '—';
+ segments.add((
+ text: '${segments.isEmpty ? '' : ' '}$name ',
+ tone: WorkspaceUsageTone.normal,
+ ));
+ segments.add((
+ text: figure,
+ tone: remaining is! num || !remaining.isFinite
+ ? WorkspaceUsageTone.normal
+ : remaining <= 0
+ ? WorkspaceUsageTone.exhausted
+ : remaining <= 20
+ ? WorkspaceUsageTone.low
+ : WorkspaceUsageTone.normal,
+ ));
+ details.add(
+ '$name${account.isNotEmpty && counts[engine] == 1 ? ' ($account)' : ''}: $status',
+ );
+ final windows = row['details'];
+ if (windows is List) details.addAll(windows.whereType<String>());
+ }
+ return WorkspaceSubscriptionUsage._(
+ segments.isEmpty
+ ? const [(text: 'Subscriptions', tone: WorkspaceUsageTone.normal)]
+ : List.unmodifiable(segments),
+ segments.isEmpty
+ ? 'View subscriptions and remaining usage'
+ : details.join('\n'),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/workspace_welcome.dart b/desktop/lib/widgets/workspace_welcome.dart
index 8ec0f4686..fd1ce274d 100644
--- a/desktop/lib/widgets/workspace_welcome.dart
+++ b/desktop/lib/widgets/workspace_welcome.dart
@@ -1,8 +1,8 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
@@ -11,10 +11,13 @@ import '../state/swarm_catalog.dart';
import '../state/swarm_navigation.dart';
import '../state/welcome_sessions.dart';
import 'engine_identity.dart';
+import 'desktop_chrome.dart';
import '../shared/theme/appearance_prefs_store.dart';
+import '../shared/theme/status_line_style.dart';
import '../shared/theme/harness_background.dart';
import 'swarm_wallpaper.dart';
import 'terminal_text_action.dart';
+import 'status_line.dart';
import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
import '../shortcuts/keymap_commands.dart';
@@ -25,8 +28,8 @@ import '../terminal/terminal_theme.dart' show lightTerminalTheme;
///
/// With [app], it also offers what to pick up: the harnesses you were just
/// with and the Claude Code and Codex conversations on your machines that
-/// Harness did not start ([WelcomeSessions]), numbered 1–9 like the terminal
-/// client's home. [onOpen] opens one in this tab, as Cmd-P would.
+/// Harness did not start ([WelcomeSessions]), limited to six recent visits.
+/// [onOpen] opens one in this tab, as Cmd-P would.
class WorkspaceWelcome extends StatefulWidget {
const WorkspaceWelcome({
super.key,
@@ -34,6 +37,7 @@ class WorkspaceWelcome extends StatefulWidget {
this.app,
this.projects = const [],
this.onOpen,
+ this.composerBuilder,
});
final ValueChanged<String> onCommand;
@@ -41,6 +45,10 @@ class WorkspaceWelcome extends StatefulWidget {
final List<SavedSwarmProject> projects;
final ValueChanged<SwarmDestination>? onOpen;
+ /// Embedded creation and the popup supply the exact same form. Welcome
+ /// only contributes its existing recent-session data beneath that form.
+ final Widget Function(Widget? recentSessions)? composerBuilder;
+
@override
State<WorkspaceWelcome> createState() => _WorkspaceWelcomeState();
}
@@ -48,7 +56,7 @@ class WorkspaceWelcome extends StatefulWidget {
class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
// Resolve the icon at compile time. Lazy initialization of Lucide's large
// generated library overflows the browser debug runtime's stack here.
- static const _phoneIcon = LucideIcons.smartphone500;
+ static const _phoneIcon = AppIcons.smartphone;
WelcomeSessions? _sessions;
int _cursor = 0;
final _focus = FocusNode(debugLabel: 'Welcome sessions');
@@ -75,6 +83,7 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
/// Focus anywhere else (a field, a dialog, Cmd-P) is left alone, and the
/// app's shortcuts are read before any of this.
void _claimFocus() {
+ if (widget.composerBuilder != null) return;
if (!mounted || _focus.hasPrimaryFocus || !_focus.canRequestFocus) return;
final primary = FocusManager.instance.primaryFocus;
if (primary != null && !_focus.ancestors.contains(primary)) return;
@@ -163,7 +172,14 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
Widget _buildWelcome(BuildContext context) {
grid.AppTheme.watch(context);
- final palette = grid.AppTheme.palette.value;
+ if (widget.composerBuilder case final composer?) {
+ return Material(
+ key: const ValueKey('workspace-welcome'),
+ color: grid.AppPalette.windowBg,
+ child: composer(_desktopSessions()),
+ );
+ }
+ final palette = grid.AppTheme.surfacePalette;
final background = appearancePrefsStore.value.background;
final hasArtwork = background != HarnessBackground.plain;
final ink = hasArtwork
@@ -340,6 +356,131 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
);
}
+ Widget? _desktopSessions() {
+ final sessions = _sessions;
+ if (sessions == null || sessions.rows.isEmpty) return null;
+ return Column(
+ key: const ValueKey('welcome-sessions'),
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8, left: 10),
+ child: Semantics(
+ header: true,
+ child: Text('Recent harnesses', style: DesktopChrome.metadata()),
+ ),
+ ),
+ for (final (index, row) in sessions.rows.indexed)
+ TextButton(
+ key: ValueKey('welcome-session-${row.id}'),
+ onPressed: () => _open(index),
+ style:
+ TextButton.styleFrom(
+ foregroundColor: DesktopChrome.muted,
+ backgroundColor: Colors.transparent,
+ enabledMouseCursor: SystemMouseCursors.click,
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 8,
+ ),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.rowRadius,
+ ),
+ ),
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? (MediaQuery.highContrastOf(context)
+ ? DesktopChrome.accent
+ : DesktopChrome.focusRing)
+ : Colors.transparent,
+ ),
+ ),
+ ),
+ child: Row(
+ children: [
+ ExcludeSemantics(
+ child: EngineMark(engine: row.engine, size: 18),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ row.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ if (_recentContext(row) case final context?) ...[
+ const SizedBox(height: 2),
+ context,
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(width: 16),
+ if (sessions.lastUsedAt(row) case final at?)
+ Text(
+ sessions.readAt.difference(at).inMinutes < 1
+ ? 'now'
+ : harnessActivityAge(at, sessions.readAt),
+ style: DesktopChrome.text(
+ size: 12,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget? _recentContext(SwarmDestination row) {
+ final context = row.promptContext;
+ if (context == null) {
+ return row.detail.isEmpty
+ ? null
+ : Text(
+ row.detail,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ );
+ }
+ final prefs = appearancePrefsStore.value.prompt;
+ final parts = statusLineParts(
+ provider: '',
+ machine: prefs.machine ? context.machine ?? '' : '',
+ project: prefs.project ? context.project ?? '' : '',
+ branch: prefs.branch ? context.branch : null,
+ style: prefs.statusStyle,
+ separateMachine: true,
+ );
+ if (parts.text.isEmpty) return null;
+ return Tooltip(
+ message: parts.text,
+ child: StatusLine(
+ parts: parts,
+ color: prefs.color,
+ workspaceBar: true,
+ textAlign: TextAlign.left,
+ middleEllipsis: true,
+ surfaceBackground: grid.AppPalette.windowBg,
+ monochromeColor: DesktopChrome.muted,
+ ),
+ );
+ }
+
/// The commands, each with its shortcut: the whole page before there is
/// anything to pick up, and the column beside the list after.
Widget _commands(
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 964443c50..d6496e0d0 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -2,6 +2,17 @@ import Cocoa
import FlutterMacOS
import ImageIO
+/// The native counterpart of AppIcons: regular monochrome system outlines.
+/// Controls share one optical size; hover changes ink, never the silhouette.
+private enum HarnessControlSymbols {
+ static let size: CGFloat = 16
+ static let configuration = NSImage.SymbolConfiguration(pointSize: size, weight: .regular)
+ static func image(_ name: String, description: String? = nil) -> NSImage? {
+ NSImage(systemSymbolName: name, accessibilityDescription: description)?
+ .withSymbolConfiguration(configuration)
+ }
+}
+
/// Real AppKit controls in the title bar, beside the system traffic lights.
/// https://developer.apple.com/documentation/appkit/nstitlebaraccessoryviewcontroller/layoutattribute
final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
@@ -108,7 +119,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
private func sendTabAction(_ method: String, arguments: Any?) {
- guard ["daemon", "focusedModel", "focusedContext", "harnessControls", "machineControls", "modelControls", "select", "close", "new", "rename", "commands", "notifications", "notificationInbox", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
+ guard ["daemon", "subscriptions", "focusedContext", "harnessControls", "machineControls", "modelControls", "select", "close", "new", "rename", "commands", "notifications", "notificationInbox", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
channel.invokeMethod(method, arguments: arguments)
return
}
@@ -151,7 +162,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private func setKeymap(_ map: HarnessNativeKeymap) {
keymap = map
// Mouse controls teach the effective shortcuts, including user remaps.
- strip.newButton.toolTip = "New Swarm " + (map.hint(for: "swarm.new", context: "workspace") ?? "")
+ strip.newButton.toolTip = "New Tab " + (map.hint(for: "swarm.new", context: "workspace") ?? "")
if let main = NSApp.mainMenu, let window {
let menu = main as? HarnessKeymapMenu ?? HarnessKeymapMenu.replacing(main)
if NSApp.mainMenu !== menu { NSApp.mainMenu = menu }
@@ -259,13 +270,13 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
addPhone.target = self
addPhone.representedObject = "addPhone"
addPhone.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "addPhone")
- addPhone.image = NSImage(systemSymbolName: "iphone", accessibilityDescription: nil)
+ addPhone.image = HarnessControlSymbols.image("iphone")
appMenu.insertItem(addPhone, at: appMenu.index(of: settings) + 1)
let customize = NSMenuItem(title: "Customize Harness", action: #selector(menuAction(_:)), keyEquivalent: "")
customize.target = self
customize.representedObject = "customize"
customize.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "customize")
- customize.image = NSImage(systemSymbolName: "paintpalette", accessibilityDescription: nil)
+ customize.image = HarnessControlSymbols.image("paintpalette")
appMenu.insertItem(customize, at: appMenu.index(of: settings))
HarnessAppMenu.arrange()
}
@@ -285,7 +296,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
"commands": "command", "notifications": "bell",
]
if let symbol = symbols[action] {
- item.image = NSImage(systemSymbolName: symbol, accessibilityDescription: title)
+ item.image = HarnessControlSymbols.image(symbol, description: title)
}
menu.addItem(item)
}
@@ -307,14 +318,14 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
add(file, "Restart Harness", "e", "restartAgent", [.command, .shift])
add(file, "Share Harness", "s", "shareAgent", [.command, .shift])
file.addItem(.separator())
- add(file, "New Swarm", "t", "new")
- add(file, "Rename Swarm", "r", "renameActive", [.command, .shift])
- add(file, "Close Swarm", "w", "closeActive")
+ add(file, "New Tab", "t", "new")
+ add(file, "Rename Tab", "r", "renameActive", [.command, .shift])
+ add(file, "Close Tab", "w", "closeActive")
file.addItem(.separator())
add(file, "Split Right", "r", "splitRight")
add(file, "Split Down", "d", "splitDown")
add(file, "Zoom Pane", "", "zoomPane")
- add(file, "Move Pane to Swarm", "m", "movePaneToTab", [.command, .shift])
+ add(file, "Move Pane to Tab", "m", "movePaneToTab", [.command, .shift])
add(file, "Close Pane", "w", "closePane", [.command, .shift])
install(file, at: 1)
@@ -397,7 +408,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
command("Back", "[", "historyBack")
command("Forward", "]", "historyForward")
// No default chord: ⌘⇧T is New Terminal now. A person can give this one in keybindings.jsonc.
- let reopen = NSMenuItem(title: "Reopen Closed Swarm or Pane", action: #selector(menuAction(_:)), keyEquivalent: "")
+ let reopen = NSMenuItem(title: "Reopen Closed Tab or Pane", action: #selector(menuAction(_:)), keyEquivalent: "")
reopen.target = self
reopen.representedObject = "reopen"
reopen.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "reopen")
@@ -446,7 +457,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
historyMenu.addItem(item)
}
if entries.isEmpty {
- let item = NSMenuItem(title: closed ? "No Recently Closed Swarms or Panes" : "No Recent Visits", action: nil, keyEquivalent: "")
+ let item = NSMenuItem(title: closed ? "No Recently Closed Tabs or Panes" : "No Recent Visits", action: nil, keyEquivalent: "")
item.isEnabled = false
historyMenu.addItem(item)
}
@@ -542,7 +553,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private enum SwarmIdentity {
// Same four separate tiles as widgets/swarm_icon.dart.
- static let menuIcon = NSImage(systemSymbolName: "square.grid.2x2", accessibilityDescription: nil)
+ static let menuIcon = HarnessControlSymbols.image("square.grid.2x2")
}
private struct SwarmMachineEntry: Equatable {
@@ -632,7 +643,7 @@ private final class SwarmHistoryMenuRow: NSView {
: selected ? .selectedMenuItemTextColor : .labelColor
let attributes: [NSAttributedString.Key: Any] = [.font: NSFont.menuFont(ofSize: 0), .foregroundColor: color]
if item.state == .on {
- let mark = NSImage(systemSymbolName: "checkmark", accessibilityDescription: nil)!
+ let mark = HarnessControlSymbols.image("checkmark")!
let tinted = mark.copy() as! NSImage
tinted.lockFocus()
color.set()
@@ -856,6 +867,15 @@ private struct SwarmNativePalette: Equatable {
/// [SwarmTitlebarStrip.updatePalette] sets from this.
let dark: Bool
+ // Mirrors AppPalette.textPrimary; navigation follows its surface, while the
+ // footer continues to honor the selected terminal/status foreground.
+ var navigationForeground: NSColor {
+ let color = tabBar.usingColorSpace(.sRGB) ?? tabBar
+ let light = color.redComponent * 0.2126 + color.greenComponent * 0.7152 + color.blueComponent * 0.0722 > 0.5
+ return light ? NSColor(srgbRed: 26 / 255, green: 26 / 255, blue: 24 / 255, alpha: 1)
+ : NSColor(white: 245 / 255, alpha: 1)
+ }
+
init(_ values: [String: Any] = [:]) {
func color(_ name: String, _ fallback: UInt32) -> NSColor {
let supplied = values[name] as? Int64
@@ -940,39 +960,25 @@ private func workspaceBarTextWidth(_ text: String, font: NSFont) -> CGFloat {
(text as NSString).size(withAttributes: [.font: workspaceBarEmphasisFont(font)]).width)
}
-/// Terminal symbols with a shared text baseline and a visible hover/focus cue.
-private final class SwarmStatusSymbolButton: SwarmIconButton {
- var foreground = NSColor(white: 0.85, alpha: 1) { didSet { needsDisplay = true } }
-
- override func draw(_ dirtyRect: NSRect) {
- let active = isEnabled && (hovered || hasKeyboardFocus || isHighlighted)
- let regularFont = font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
- let line = NSAttributedString(string: title, attributes: [
- .font: active ? workspaceBarEmphasisFont(regularFont) : regularFont,
- .foregroundColor: foreground.withAlphaComponent(isEnabled ? 0.75 : 0.28),
- ])
- let size = line.size()
- line.draw(in: NSRect(x: (bounds.width - size.width) / 2,
- y: (bounds.height - size.height) / 2, width: size.width, height: size.height))
- }
-}
-
/// Plain toolbar icons emphasize the glyph without a button well.
private class SwarmPlainIconButton: SwarmIconButton {
var foreground = NSColor.white { didSet { needsDisplay = true } }
+ var restingOpacity: CGFloat = 0.75 { didSet { needsDisplay = true } }
+ var highContrastRestingOpacity: CGFloat? { didSet { needsDisplay = true } }
override func draw(_ dirtyRect: NSRect) {
let emphasized = isEnabled && (hovered || hasKeyboardFocus || isHighlighted)
// Draw only the glyph: AppKit can paint a hover bezel even on a borderless
// NSButton. Emphasis belongs to the bell, never a background around it.
- if let symbol = image?.withSymbolConfiguration(NSImage.SymbolConfiguration(
- pointSize: 17, weight: emphasized ? .semibold : .regular)) {
+ if let symbol = image?.withSymbolConfiguration(symbolConfiguration ?? HarnessControlSymbols.configuration) {
let rect = NSRect(x: (bounds.width - symbol.size.width) / 2,
y: (bounds.height - symbol.size.height) / 2,
width: symbol.size.width, height: symbol.size.height)
NSGraphicsContext.current?.cgContext.beginTransparencyLayer(auxiliaryInfo: nil)
symbol.draw(in: rect)
- foreground.withAlphaComponent(isEnabled ? (emphasized ? 1 : 0.75) : 0.28).setFill()
+ let quietOpacity = NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast
+ ? highContrastRestingOpacity ?? restingOpacity : restingOpacity
+ foreground.withAlphaComponent(isEnabled ? (emphasized ? 1 : quietOpacity) : 0.28).setFill()
rect.fill(using: .sourceIn)
NSGraphicsContext.current?.cgContext.endTransparencyLayer()
}
@@ -1515,7 +1521,7 @@ private final class SwarmContextButton: SwarmIconButton {
}
}
-/// A fixed top-bar companion slot. Bundled artwork and legacy ASCII share the
+/// A fixed footer companion slot. Bundled artwork and legacy ASCII share the
/// same footprint; changing a frame or growth stage never moves adjacent tabs.
private final class SwarmSymbolButton: SwarmIconButton {
var glyph = ""
@@ -1734,10 +1740,10 @@ private final class SwarmTabStrip: NSView {
var emit: ((String, Any?) -> Void)?
private let scroll = SwarmStripScrollView()
private let document = NSView()
- fileprivate let newButton = SwarmStatusSymbolButton()
+ fileprivate let newButton = SwarmPlainIconButton()
fileprivate let contextButton = SwarmContextButton()
- fileprivate let focusedModelButton = SwarmContextButton()
- private var focusedModelTarget: [String: Any]?
+ fileprivate let subscriptionUsageButton = SwarmContextButton()
+ private var subscriptionUsageState: [String: Any]?
fileprivate let pullRequestButton = SwarmContextButton()
fileprivate let shareButton = SwarmShareButton()
fileprivate let notificationsButton = SwarmNotificationButton()
@@ -1745,12 +1751,13 @@ private final class SwarmTabStrip: NSView {
fileprivate let storeButton = SwarmStoreButton()
private var shareTarget: [String: Any]?
private var barFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
+ private let navigationFont = NSFont.systemFont(ofSize: 13, weight: .regular)
fileprivate let daemonButton = SwarmSymbolButton()
private var daemonArt = SwarmDaemonArt()
private var daemonHovering = false
fileprivate let voiceLabel = SwarmVoiceLabel()
// What the status line holds, apart from whether the daemon's voice covers it.
- private var hasFocusedModel = false
+ private var hasSubscriptionUsage = false
private var hasPullRequest = false
private(set) var voiceActive = false
private var terminalForeground = NSColor(white: 0.85, alpha: 1)
@@ -1763,6 +1770,8 @@ private final class SwarmTabStrip: NSView {
private var activityTimer: Timer?
private var activityObservers: [NSObjectProtocol] = []
private var motionObserver: NSObjectProtocol?
+ private var modifierMonitor: Any?
+ private var shortcutHintsVisible = false
private var lastBackgroundClick: (time: TimeInterval, point: NSPoint)?
// Dragging is explicit below. AppKit must not also start a titlebar gesture.
override var mouseDownCanMoveWindow: Bool { false }
@@ -1781,12 +1790,12 @@ private final class SwarmTabStrip: NSView {
newButton.target = self
newButton.action = #selector(newSwarm)
addSubview(newButton)
- newButton.setAccessibilityLabel("New Swarm")
+ newButton.setAccessibilityLabel("New Tab")
newButton.isEnabled = false
- newButton.toolTip = "New Swarm ⌘T"
- newButton.image = nil
- newButton.title = "+"
- newButton.imagePosition = .noImage
+ newButton.toolTip = "New Tab ⌘T"
+ newButton.image = HarnessControlSymbols.image("plus")
+ newButton.title = ""
+ newButton.imagePosition = .imageOnly
contextButton.isBordered = false
contextButton.alignment = .right
contextButton.target = self
@@ -1796,13 +1805,13 @@ private final class SwarmTabStrip: NSView {
self.emit?("focusedContext", ["field": field, "paneId": paneId])
}
statusBar.addSubview(contextButton)
- focusedModelButton.isBordered = false
- focusedModelButton.textAlignment = .center
- focusedModelButton.target = self
- focusedModelButton.action = #selector(openFocusedModel)
- focusedModelButton.setAccessibilityLabel("Switch focused pane model")
- focusedModelButton.isHidden = true
- statusBar.addSubview(focusedModelButton)
+ subscriptionUsageButton.isBordered = false
+ subscriptionUsageButton.textAlignment = .center
+ subscriptionUsageButton.target = self
+ subscriptionUsageButton.action = #selector(openSubscriptions)
+ subscriptionUsageButton.setAccessibilityLabel("Remaining subscription usage")
+ subscriptionUsageButton.isHidden = true
+ statusBar.addSubview(subscriptionUsageButton)
pullRequestButton.isBordered = false
pullRequestButton.target = self
pullRequestButton.action = #selector(openFocusedPullRequest)
@@ -1829,11 +1838,11 @@ private final class SwarmTabStrip: NSView {
self.setDaemonHover(true)
}
daemonButton.onExit = { [weak self] in self?.setDaemonHover(false) }
- addSubview(daemonButton)
+ statusBar.addSubview(daemonButton)
notificationsButton.isBordered = false
notificationsButton.focusRingType = .none
notificationsButton.title = ""
- notificationsButton.image = NSImage(systemSymbolName: "bell", accessibilityDescription: nil)
+ notificationsButton.image = HarnessControlSymbols.image("bell")
notificationsButton.imagePosition = .imageOnly
notificationsButton.target = self
notificationsButton.action = #selector(openNotifications)
@@ -1843,7 +1852,7 @@ private final class SwarmTabStrip: NSView {
searchButton.isBordered = false
searchButton.focusRingType = .none
searchButton.title = ""
- searchButton.image = NSImage(systemSymbolName: "magnifyingglass", accessibilityDescription: nil)
+ searchButton.image = HarnessControlSymbols.image("magnifyingglass")
searchButton.imagePosition = .imageOnly
searchButton.isEnabled = false
searchButton.target = self
@@ -1852,7 +1861,7 @@ private final class SwarmTabStrip: NSView {
addSubview(searchButton)
storeButton.isBordered = false
storeButton.title = "Harness Store"
- storeButton.font = barFont
+ storeButton.font = navigationFont
storeButton.palette = palette
storeButton.image = SwarmHistoryIcons().image(engine: "store", asset: "assets/store/polymath.png")
storeButton.isEnabled = false
@@ -1876,8 +1885,8 @@ private final class SwarmTabStrip: NSView {
statusBar.setAccessibilityRole(.group)
statusBar.setAccessibilityLabel("Focused pane status")
statusBar.setAccessibilityParent(self)
- setAccessibilityChildren([scroll, newButton, searchButton, notificationsButton, storeButton, daemonButton, statusBar])
- statusBar.setAccessibilityChildren([contextButton, pullRequestButton, voiceLabel, shareButton, focusedModelButton])
+ setAccessibilityChildren([scroll, newButton, searchButton, notificationsButton, storeButton, statusBar])
+ statusBar.setAccessibilityChildren([subscriptionUsageButton, daemonButton, shareButton, voiceLabel, contextButton, pullRequestButton])
registerForDraggedTypes([swarmPasteboardType])
scroll.contentView.postsBoundsChangedNotifications = true
for name in [NSApplication.didBecomeActiveNotification, NSApplication.didResignActiveNotification,
@@ -1898,6 +1907,22 @@ private final class SwarmTabStrip: NSView {
forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil, queue: .main) {
[weak self] _ in self?.syncActivityAnimation()
}
+ // Observe only; Flutter/AppKit keep ownership of every shortcut and IME event.
+ modifierMonitor = NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { [weak self] event in
+ guard let self, let window = self.window,
+ event.window === window || (event.window == nil && window.isKeyWindow) else { return event }
+ self.setShortcutHintsVisible(event.modifierFlags.contains(.command))
+ return event
+ }
+ for name in [NSApplication.didResignActiveNotification, NSWindow.didResignKeyNotification] {
+ activityObservers.append(NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) {
+ [weak self] notification in
+ guard let self else { return }
+ if name == NSApplication.didResignActiveNotification || notification.object as? NSWindow === self.window {
+ self.setShortcutHintsVisible(false)
+ }
+ })
+ }
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
@@ -1906,12 +1931,19 @@ private final class SwarmTabStrip: NSView {
daemonRevealTimer?.invalidate()
activityObservers.forEach(NotificationCenter.default.removeObserver)
if let motionObserver { NSWorkspace.shared.notificationCenter.removeObserver(motionObserver) }
+ if let modifierMonitor { NSEvent.removeMonitor(modifierMonitor) }
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { setDaemonHover(false) }
syncActivityAnimation()
+ setShortcutHintsVisible(window?.isKeyWindow == true && NSEvent.modifierFlags.contains(.command))
+ }
+
+ private func setShortcutHintsVisible(_ visible: Bool) {
+ shortcutHintsVisible = visible
+ for tab in tabs { tab.showsShortcutHint = visible && actionsEnabled }
}
private var visibleWorkingTabs: [SwarmTabButton] {
@@ -1954,7 +1986,11 @@ private final class SwarmTabStrip: NSView {
NSApp.appearance = NSAppearance(named: palette.dark ? .darkAqua : .aqua)
storeButton.palette = palette
newButton.contentTintColor = palette.accent
- for tab in tabs { tab.palette = palette }
+ newButton.foreground = palette.navigationForeground
+ for tab in tabs {
+ tab.palette = palette
+ tab.foreground = palette.navigationForeground
+ }
needsDisplay = true
}
@@ -1963,7 +1999,14 @@ private final class SwarmTabStrip: NSView {
// Workspace teardown clears its controls without changing appearance.
if let palette = state["palette"] as? [String: Any] { updatePalette(palette) }
actionsEnabled = state["enabled"] as? Bool == true
- statusBar.isHidden = (state["tabs"] as? [Any])?.isEmpty != false
+ // The footer is a sibling above Flutter. Let Flutter's modal backdrop
+ // cover this area too, including hit testing and accessibility.
+ statusBar.isHidden = (state["tabs"] as? [Any])?.isEmpty != false || state["footerCovered"] as? Bool == true
+ let passiveFooter = state["footerPassive"] as? Bool == true
+ statusBar.setAccessibilityHidden(passiveFooter || statusBar.isHidden)
+ setAccessibilityChildren(
+ [scroll, newButton, searchButton, notificationsButton, storeButton] +
+ (statusBar.isHidden || passiveFooter ? [] : [statusBar]))
reduceMotion = state["reduceMotion"] as? Bool == true
if let style = state["barStyle"] as? [String: Any] {
let size = CGFloat(min(36, max(8, (style["size"] as? NSNumber)?.doubleValue ?? 13)))
@@ -1973,22 +2016,22 @@ private final class SwarmTabStrip: NSView {
terminalForeground = statusColor(style["foreground"], fallback: terminalForeground)
}
for control in [newButton] {
- control.font = barFont
- control.foreground = terminalForeground
+ control.font = navigationFont
+ control.foreground = palette.navigationForeground
control.isEnabled = actionsEnabled
}
- storeButton.font = barFont
+ storeButton.font = navigationFont
storeButton.isEnabled = actionsEnabled
- searchButton.foreground = terminalForeground
+ searchButton.foreground = palette.navigationForeground
searchButton.isEnabled = actionsEnabled
searchButton.toolTip = state["searchTooltip"] as? String ?? "Search harnesses"
storeButton.toolTip = state["storeTooltip"] as? String ?? "Harness Store"
- focusedModelButton.font = barFont
- focusedModelButton.foreground = terminalForeground
- focusedModelButton.contentPadding = ("m" as NSString).size(withAttributes: [.font: barFont]).width
- focusedModelTarget = state["focusedModel"] as? [String: Any]
- focusedModelButton.update(focusedModelTarget, enabled: actionsEnabled)
- hasFocusedModel = focusedModelTarget != nil
+ subscriptionUsageButton.font = barFont
+ subscriptionUsageButton.foreground = terminalForeground
+ subscriptionUsageButton.contentPadding = ("m" as NSString).size(withAttributes: [.font: barFont]).width
+ subscriptionUsageState = state["subscriptionUsage"] as? [String: Any]
+ subscriptionUsageButton.update(subscriptionUsageState, enabled: actionsEnabled)
+ hasSubscriptionUsage = subscriptionUsageState != nil
contextButton.font = barFont
contextButton.foreground = terminalForeground
contextButton.update(state["focusedContext"] as? [String: Any], enabled: actionsEnabled)
@@ -2007,7 +2050,7 @@ private final class SwarmTabStrip: NSView {
shareButton.setAccessibilityHelp(shareButton.toolTip)
hasPullRequest = state["pullRequest"] != nil
notificationsButton.count = max(0, state["unread"] as? Int ?? 0)
- notificationsButton.foreground = terminalForeground
+ notificationsButton.foreground = palette.navigationForeground
notificationsButton.isEnabled = actionsEnabled
notificationsButton.toolTip = notificationsButton.count == 0
? "Notifications" : "Notifications · \(notificationsButton.count) unread"
@@ -2029,14 +2072,21 @@ private final class SwarmTabStrip: NSView {
tabOrderChanged = tabOrderChanged || ids != previousOrder
for tab in tabs where !ids.contains(tab.swarmId) { tab.removeFromSuperview() }
let previous = Dictionary(uniqueKeysWithValues: tabs.map { ($0.swarmId, $0) })
- tabs = rows.compactMap { row in
+ tabs = rows.enumerated().compactMap { index, row in
guard let id = row["id"] as? String else { return nil }
let tab = previous[id] ?? SwarmTabButton(id: id)
tab.palette = palette
- tab.name = row["name"] as? String ?? "New Swarm"
- tab.displayLabel = row["label"] as? String ?? tab.name
- tab.labelFont = barFont
- tab.foreground = terminalForeground
+ tab.name = row["name"] as? String ?? "New Tab"
+ let displayLabel = row["label"] as? String ?? tab.name
+ // Older Dart payloads generated an index prefix. The explicit hint key
+ // marks the new clean-label payload, including a custom title like "1: Plan".
+ tab.displayLabel = row["label"] != nil && !row.keys.contains("shortcutHint")
+ ? displayLabel.replacingOccurrences(of: #"^\d+:"#, with: "", options: .regularExpression)
+ : displayLabel
+ tab.shortcutHint = row.keys.contains("shortcutHint")
+ ? row["shortcutHint"] as? String : (index < 9 ? "⌘\(index + 1)" : nil)
+ tab.showsShortcutHint = shortcutHintsVisible && actionsEnabled
+ tab.foreground = palette.navigationForeground
tab.selected = id == activeId
tab.keyboardFocus = tabsFocused && id == activeId
tab.actionsEnabled = actionsEnabled
@@ -2085,7 +2135,7 @@ private final class SwarmTabStrip: NSView {
if let gate = daemonMayAppear { return gate() }
guard NSEvent.pressedMouseButtons == 0 else { return false }
guard let window else { return true }
- return !bounds.contains(convert(window.mouseLocationOutsideOfEventStream, from: nil))
+ return !statusBar.bounds.contains(statusBar.convert(window.mouseLocationOutsideOfEventStream, from: nil))
}
private func setDaemonHover(_ hovered: Bool) {
@@ -2169,7 +2219,7 @@ private final class SwarmTabStrip: NSView {
private func applyStatusVisibility() {
voiceLabel.isHidden = !voiceActive
contextButton.isHidden = voiceActive
- focusedModelButton.isHidden = !hasFocusedModel
+ subscriptionUsageButton.isHidden = !hasSubscriptionUsage
pullRequestButton.isHidden = !hasPullRequest || voiceActive
voiceLabel.needsDisplay = true
}
@@ -2180,16 +2230,12 @@ private final class SwarmTabStrip: NSView {
let activeWasVisible = active.map { scroll.documentVisibleRect.intersects($0.frame) } ?? false
let previousScrollSize = scroll.frame.size
let previousDocumentSize = document.frame.size
- let cell = ceil(("m" as NSString).size(withAttributes: [.font: barFont]).width)
+ let cell: CGFloat = 8
let trailing = cell
- let toolHeight = workspaceBarControlHeight(barFont)
- let daemonWidth = daemonButton.isHidden ? 0 : min(daemonButton.preferredWidth, max(0, bounds.width - trailing * 2))
- let daemonHeight = min(bounds.height, max(36, toolHeight))
- daemonButton.frame = NSRect(x: bounds.width - trailing - daemonWidth,
- y: (bounds.height - daemonHeight) / 2, width: daemonWidth, height: daemonHeight)
+ let toolHeight: CGFloat = 32
let storeWidth = min(storeButton.preferredWidth,
- max(0, bounds.width - cell * 14 - daemonWidth))
- storeButton.frame = NSRect(x: daemonButton.frame.minX - storeWidth,
+ max(0, bounds.width - cell * 14))
+ storeButton.frame = NSRect(x: bounds.width - trailing - storeWidth,
y: (bounds.height - toolHeight) / 2, width: storeWidth, height: toolHeight)
let iconWidth = cell * 4
notificationsButton.frame = NSRect(x: storeButton.frame.minX - iconWidth,
@@ -2197,8 +2243,8 @@ private final class SwarmTabStrip: NSView {
searchButton.frame = NSRect(x: notificationsButton.frame.minX - iconWidth,
y: (bounds.height - toolHeight) / 2, width: iconWidth, height: toolHeight)
// Only navigation actions share the tab row. Context has the full footer.
- let tabBudget = max(0, searchButton.frame.minX - cell * 5)
- let widths = tabs.map { max($0.minimumWidth, min($0.preferredWidth, tabBudget)) }
+ let tabBudget = max(0, searchButton.frame.minX - cell * 6)
+ let widths = tabs.map { min($0.preferredWidth, tabBudget) }
let total = widths.reduce(0, +)
let occupied = min(total, tabBudget)
let scrollX = cell
@@ -2211,7 +2257,7 @@ private final class SwarmTabStrip: NSView {
x += width
}
newButton.frame = NSRect(x: scroll.frame.maxX, y: (bounds.height - toolHeight) / 2,
- width: cell * 3, height: toolHeight)
+ width: 32, height: toolHeight)
if statusBar.superview == nil {
statusBar.setFrameSize(NSSize(width: bounds.width, height: preferredStatusBarHeight))
}
@@ -2229,21 +2275,25 @@ private final class SwarmTabStrip: NSView {
let height = workspaceBarControlHeight(barFont)
let y = (statusBar.bounds.height - height) / 2
let available = max(0, statusBar.bounds.width - cell * 2)
+ let daemonWidth = daemonButton.isHidden ? 0 : min(daemonButton.preferredWidth, available * 0.5)
let shareWidth = shareButton.isHidden ? 0 : min(shareButton.preferredWidth, available * 0.3)
- let modelBudget = max(0, available - shareWidth - cell * 4)
- let modelWidth = hasFocusedModel ? min(focusedModelButton.preferredWidth, modelBudget * 0.4) : 0
- focusedModelButton.frame = NSRect(x: statusBar.bounds.width - cell - modelWidth,
- y: y, width: modelWidth, height: height)
- let shareRight = focusedModelButton.frame.minX - (modelWidth > 0 ? cell : 0)
- shareButton.frame = NSRect(x: shareRight - shareWidth, y: y, width: shareWidth, height: height)
- let contextRight = shareButton.frame.minX - (shareWidth > 0 ? cell : 0) - cell * 2
- let statusWidth = max(0, contextRight - cell)
- voiceLabel.frame = NSRect(x: cell, y: y, width: statusWidth, height: height)
+ let usageBudget = max(0, available - daemonWidth - shareWidth - cell * 4)
+ let usageWidth = hasSubscriptionUsage ? min(subscriptionUsageButton.preferredWidth, usageBudget * 0.45) : 0
+ subscriptionUsageButton.frame = NSRect(x: cell,
+ y: y, width: usageWidth, height: height)
+ let daemonLeft = subscriptionUsageButton.frame.maxX + (usageWidth > 0 ? cell * 2 : 0)
+ daemonButton.frame = NSRect(x: daemonLeft, y: y, width: daemonWidth, height: height)
+ let shareLeft = daemonButton.frame.maxX + (daemonWidth > 0 ? cell : 0)
+ shareButton.frame = NSRect(x: shareLeft, y: y, width: shareWidth, height: height)
+ let contextLeft = shareButton.frame.maxX + (shareWidth > 0 || daemonWidth > 0 ? cell * 2 : 0)
+ let statusWidth = max(0, statusBar.bounds.width - cell - contextLeft)
+ voiceLabel.frame = NSRect(x: contextLeft, y: y, width: statusWidth, height: height)
let prWidth = hasPullRequest ? min(pullRequestButton.preferredWidth, statusWidth * 0.3) : 0
let joined = contextButton.isSegmented && pullRequestButton.isSegmented && prWidth > 0
let prGap = prWidth > 0 && !joined ? cell : 0
let contextWidth = min(contextButton.preferredWidth, max(0, statusWidth - prWidth - prGap))
- contextButton.frame = NSRect(x: cell, y: y, width: contextWidth, height: height)
+ let contextX = statusBar.bounds.width - cell - prWidth - prGap - contextWidth
+ contextButton.frame = NSRect(x: contextX, y: y, width: contextWidth, height: height)
pullRequestButton.frame = NSRect(x: contextButton.frame.maxX + prGap,
y: y, width: prWidth, height: height)
contextButton.nextBackground = joined && pullRequestButton.drawsSegments
@@ -2252,10 +2302,10 @@ private final class SwarmTabStrip: NSView {
// links after allocating their row, including offscreen render fixtures.
contextButton.layoutSubtreeIfNeeded()
pullRequestButton.layoutSubtreeIfNeeded()
- focusedModelButton.layoutSubtreeIfNeeded()
+ subscriptionUsageButton.layoutSubtreeIfNeeded()
}
override func draw(_ dirtyRect: NSRect) {
- // A fine rule joins the flat tabs to the workspace.
+ // A fine rule joins the active tab's outward shoulders to the workspace.
palette.workspace.setFill()
NSRect(x: 0, y: 0, width: bounds.width, height: 1).fill()
}
@@ -2280,11 +2330,9 @@ private final class SwarmTabStrip: NSView {
hypot(event.locationInWindow.x - first.point.x,
event.locationInWindow.y - first.point.y) <= 4
}
- @objc private func openFocusedModel() {
- guard actionsEnabled, focusedModelButton.isEnabled,
- let paneId = focusedModelTarget?["paneId"] as? Int,
- let agentId = focusedModelTarget?["agentId"] as? String else { return }
- emit?("focusedModel", ["paneId": paneId, "agentId": agentId])
+ @objc private func openSubscriptions() {
+ guard actionsEnabled, subscriptionUsageButton.isEnabled else { return }
+ emit?("subscriptions", nil)
}
@objc private func openDaemon() {
setDaemonHover(false)
@@ -2335,20 +2383,46 @@ private final class SwarmTabStrip: NSView {
}
private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidation {
+ // Mirrors AppDesktop.tabRadius/tabShoulder in desktop-design-system.md.
+ private static let upperRadius: CGFloat = 10
+ private static let shoulder: CGFloat = 8
+ private static let topInset: CGFloat = 6
+ // Mirror AppDesktop.tabCloseInset: keep the 32pt hover target inside the
+ // curved tab body, with equal space reserved around the centered title.
+ private static let trailingInset: CGFloat = 8
+ private static let accessorySide: CGFloat = 32
+ private static let contentInset: CGFloat = trailingInset + accessorySide
+ private static let gap: CGFloat = 6
+ private static let activityWidth: CGFloat = 16
+
var palette = SwarmNativePalette() {
didSet { if palette != oldValue { needsDisplay = true } }
}
let swarmId: String
- var name = "New Swarm" { didSet { if name != oldValue { invalidateLabel(); updateAccessibility() } } }
- var displayLabel = "New Swarm" { didSet { if displayLabel != oldValue { invalidateLabel() } } }
- var foreground = NSColor(white: 0.85, alpha: 1) { didSet { if foreground != oldValue { invalidateLabel() } } }
- private var cellWidth: CGFloat { ceil(("m" as NSString).size(withAttributes: [.font: labelFont]).width) }
- var minimumWidth: CGFloat {
- activityLabel == nil ? 0 : (labelPrefix as NSString).size(withAttributes: [.font: labelFont]).width + cellWidth * 4
- }
- private var activitySpace: CGFloat { activityLabel == nil ? 0 : cellWidth * 2 }
- private var naturalContentWidth: CGFloat { max(label.size().width, emphasizedLabel.size().width) + activitySpace }
- var preferredWidth: CGFloat { min(cellWidth * 24, ceil(naturalContentWidth + cellWidth * 2)) }
+ var name = "New Tab" { didSet { if name != oldValue { invalidateLabel(); updateAccessibility() } } }
+ var displayLabel = "New Tab" { didSet { if displayLabel != oldValue { invalidateLabel() } } }
+ var shortcutHint: String? { didSet { if shortcutHint != oldValue { invalidateLabel(); updateAccessibility() } } }
+ var showsShortcutHint = false {
+ didSet { if showsShortcutHint != oldValue { needsLayout = true; needsDisplay = true } }
+ }
+ var foreground = NSColor(white: 0.85, alpha: 1) {
+ didSet {
+ if foreground != oldValue { invalidateLabel() }
+ closeButton.foreground = foreground
+ }
+ }
+ private var indicatorWidth: CGFloat {
+ min(72, max(activityLabel == nil ? 0 : Self.activityWidth, shortcutLabel?.size().width ?? 0))
+ }
+ private var reservedIndicatorSpace: CGFloat { indicatorWidth == 0 ? 0 : indicatorWidth + Self.gap }
+ private var activitySpace: CGFloat {
+ (activityMark?.isEmpty ?? true) && !displaysShortcut ? 0 : reservedIndicatorSpace
+ }
+ private var naturalTitleWidth: CGFloat { max(label.size().width, emphasizedLabel.size().width) }
+ var minimumWidth: CGFloat { Self.contentInset * 2 + reservedIndicatorSpace + 16 }
+ var preferredWidth: CGFloat {
+ min(260, max(112, ceil(naturalTitleWidth + reservedIndicatorSpace + Self.contentInset * 2)))
+ }
var selected = false { didSet { if selected != oldValue { invalidateLabel(); updateAccessibility() } } }
var attention = false { didSet { if attention != oldValue { invalidateLabel(); updateAccessibility() } } }
var activity: SwarmTabActivity? {
@@ -2363,24 +2437,26 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
if let activity { return activity.working ? harnessActivityFrames[activityFrame] : activity.mark }
return attention ? "?" : nil
}
- private var labelPrefix: String {
- guard let colon = displayLabel.firstIndex(of: ":") else { return "" }
- return String(displayLabel[...colon])
+ private var titleRect: NSRect {
+ let width = min(naturalTitleWidth, max(0, bounds.width - Self.contentInset * 2 - activitySpace))
+ return NSRect(x: (bounds.width - width - activitySpace) / 2, y: 0,
+ width: width, height: bounds.height)
}
- private var contentRect: NSRect {
- let available = max(0, bounds.width - cellWidth * 2)
- let width = min(available, naturalContentWidth)
- return NSRect(x: cellWidth + (available - width) / 2, y: 0, width: width, height: bounds.height)
+ private var indicatorRect: NSRect {
+ if bounds.width < minimumWidth {
+ let width = min(indicatorWidth, max(0, bounds.width - 16))
+ return NSRect(x: bounds.midX - width / 2, y: 0, width: width, height: bounds.height)
+ }
+ return NSRect(x: titleRect.maxX + Self.gap, y: 0, width: indicatorWidth, height: bounds.height)
}
private var activityRect: NSRect {
if bounds.width < minimumWidth {
- return NSRect(x: bounds.midX - cellWidth / 2, y: 0, width: cellWidth, height: bounds.height)
+ return NSRect(x: bounds.midX - Self.activityWidth / 2, y: 0, width: Self.activityWidth, height: bounds.height)
}
- return NSRect(x: contentRect.maxX - cellWidth,
- y: 0, width: cellWidth, height: bounds.height)
+ return NSRect(x: indicatorRect.midX - Self.activityWidth / 2,
+ y: 0, width: Self.activityWidth, height: bounds.height)
}
- /// The strip holds the keyboard on this, the selected tab — drawn like a
- /// focused control, though the keys themselves stay in Flutter.
+ /// The strip holds the keyboard on this tab; Flutter still owns the keys.
var keyboardFocus = false { didSet { if keyboardFocus != oldValue { needsDisplay = true; updateAccessibility() } } }
var showsDivider = false { didSet { if showsDivider != oldValue { needsDisplay = true } } }
var contentCenterY: CGFloat = 20
@@ -2388,10 +2464,11 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
var hoverChanged: (() -> Void)?
var isHovered: Bool { hovered && actionsEnabled }
private let selectButton = SwarmSelectButton()
+ private let closeButton = SwarmPlainIconButton()
/// Whether the middle button went down on THIS tab — see otherMouseUp.
private var middleDown = false
- /// Status text and numbered tabs share the compact workspace face.
- var labelFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular) {
+ /// Tab navigation stays in system UI type, independent of terminal/status preferences.
+ var labelFont = NSFont.systemFont(ofSize: 13, weight: .regular) {
didSet { if oldValue != labelFont { invalidateLabel() } }
}
private var cachedLabel: NSAttributedString?
@@ -2399,6 +2476,8 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
var actionsEnabled = true {
didSet {
selectButton.isEnabled = actionsEnabled
+ closeButton.isEnabled = actionsEnabled
+ updateAccessoryVisibility()
needsDisplay = true
}
}
@@ -2419,8 +2498,21 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
selectButton.target = self
selectButton.action = #selector(selectSwarm)
addSubview(selectButton)
+ closeButton.title = ""
+ closeButton.isBordered = false
+ closeButton.image = HarnessControlSymbols.image("xmark")
+ // Match the small visible cross of the pane's 12pt Lucide close mark.
+ closeButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 8, weight: .regular)
+ closeButton.restingOpacity = 0.45
+ closeButton.highContrastRestingOpacity = 0.7
+ closeButton.imagePosition = .imageOnly
+ closeButton.foreground = foreground
+ closeButton.target = self
+ closeButton.action = #selector(closeSwarm)
+ closeButton.isHidden = true
+ addSubview(closeButton)
let menu = NSMenu()
- for (title, action) in [("Rename Swarm…", #selector(renameSwarm)), ("Close Swarm", #selector(closeSwarm))] {
+ for (title, action) in [("Rename Tab…", #selector(renameSwarm)), ("Close Tab", #selector(closeSwarm))] {
let item = NSMenuItem(title: title, action: action, keyEquivalent: "")
item.target = self
menu.addItem(item)
@@ -2432,12 +2524,12 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
override func layout() {
super.layout()
selectButton.frame = bounds
- let visibleName = displayLabel.replacingOccurrences(of: #"^\d+:"#, with: "", options: .regularExpression)
- .trimmingCharacters(in: .whitespacesAndNewlines)
+ closeButton.frame = NSRect(x: max(0, bounds.width - Self.trailingInset - Self.accessorySide),
+ y: contentCenterY - Self.accessorySide / 2, width: min(Self.accessorySide, bounds.width), height: Self.accessorySide)
let fullName = name.trimmingCharacters(in: .whitespacesAndNewlines)
var hints: [String] = []
- if naturalContentWidth > max(0, bounds.width - cellWidth * 2) { hints.append(displayLabel) }
- if !fullName.isEmpty && fullName != visibleName && fullName != displayLabel { hints.append(name) }
+ if max(label.size().width, emphasizedLabel.size().width) > titleRect.width { hints.append(displayLabel) }
+ if !fullName.isEmpty && fullName != displayLabel { hints.append(name) }
if let activityLabel { hints.append(activityLabel) }
toolTip = hints.isEmpty ? nil : hints.joined(separator: "\n")
}
@@ -2454,12 +2546,18 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
private func setHovered(_ value: Bool) {
guard hovered != value else { return }
hovered = value
+ updateAccessoryVisibility()
needsDisplay = true
hoverChanged?()
}
+ private var displaysShortcut: Bool { actionsEnabled && showsShortcutHint && shortcutLabel != nil }
+ private func updateAccessoryVisibility() {
+ closeButton.isHidden = !isHovered
+ }
private func invalidateLabel() {
cachedLabel = nil
cachedEmphasizedLabel = nil
+ updateAccessoryVisibility()
needsDisplay = true
needsLayout = true
}
@@ -2477,63 +2575,99 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
private var emphasizedLabel: NSAttributedString {
if let cachedEmphasizedLabel { return cachedEmphasizedLabel }
let emphasized = NSMutableAttributedString(attributedString: label)
- emphasized.addAttribute(.font, value: workspaceBarEmphasisFont(labelFont),
+ emphasized.addAttribute(.font, value: NSFont.systemFont(ofSize: labelFont.pointSize, weight: .medium),
range: NSRange(location: 0, length: emphasized.length))
cachedEmphasizedLabel = emphasized
return emphasized
}
+ private var shortcutLabel: NSAttributedString? {
+ guard let shortcutHint, !shortcutHint.isEmpty else { return nil }
+ let paragraph = NSMutableParagraphStyle()
+ paragraph.alignment = .center
+ paragraph.lineBreakMode = .byTruncatingTail
+ return NSAttributedString(string: shortcutHint, attributes: [
+ .font: NSFont.systemFont(ofSize: 12, weight: .regular),
+ .foregroundColor: foreground.withAlphaComponent(0.75), .paragraphStyle: paragraph])
+ }
+ private var tabShape: NSBezierPath {
+ let path = NSBezierPath()
+ let top = max(0, bounds.maxY - Self.topInset)
+ let shoulder = min(Self.shoulder, bounds.width / 4, top / 3)
+ let radius = min(Self.upperRadius, max(0, bounds.width / 2 - shoulder), max(0, (top - shoulder) / 2))
+ let left = bounds.minX + shoulder, right = bounds.maxX - shoulder
+ let k: CGFloat = 0.55228475
+ path.move(to: NSPoint(x: bounds.minX, y: 0))
+ path.curve(to: NSPoint(x: left, y: shoulder),
+ controlPoint1: NSPoint(x: bounds.minX + shoulder * k, y: 0),
+ controlPoint2: NSPoint(x: left, y: shoulder * (1 - k)))
+ path.line(to: NSPoint(x: left, y: top - radius))
+ path.curve(to: NSPoint(x: left + radius, y: top),
+ controlPoint1: NSPoint(x: left, y: top - radius * (1 - k)),
+ controlPoint2: NSPoint(x: left + radius * (1 - k), y: top))
+ path.line(to: NSPoint(x: right - radius, y: top))
+ path.curve(to: NSPoint(x: right, y: top - radius),
+ controlPoint1: NSPoint(x: right - radius * (1 - k), y: top),
+ controlPoint2: NSPoint(x: right, y: top - radius * (1 - k)))
+ path.line(to: NSPoint(x: right, y: shoulder))
+ path.curve(to: NSPoint(x: bounds.maxX, y: 0),
+ controlPoint1: NSPoint(x: right, y: shoulder * (1 - k)),
+ controlPoint2: NSPoint(x: bounds.maxX - shoulder * k, y: 0))
+ path.close()
+ return path
+ }
override func draw(_ dirtyRect: NSRect) {
- let active = actionsEnabled &&
- (hovered || keyboardFocus || selectButton.hasKeyboardFocus || selectButton.isHighlighted)
- let text = active ? emphasizedLabel : label
if selected {
palette.workspace.setFill()
- bounds.fill()
- }
+ tabShape.fill()
+ } else if isHovered || (actionsEnabled && selectButton.isHighlighted) {
+ foreground.withAlphaComponent(selectButton.isHighlighted ? 0.08 : 0.04).setFill()
+ tabShape.fill()
+ }
+ if showsDivider {
+ foreground.withAlphaComponent(0.16).setFill()
+ NSRect(x: bounds.maxX - 0.5, y: 10, width: 1, height: max(0, bounds.height - 20)).fill()
+ }
+ if actionsEnabled && (keyboardFocus || selectButton.hasKeyboardFocus) {
+ NSColor.controlAccentColor.setStroke()
+ let focus = NSBezierPath(roundedRect: NSRect(x: Self.shoulder + 2, y: 3,
+ width: max(0, bounds.width - 2 * (Self.shoulder + 2)), height: max(0, bounds.height - Self.topInset - 6)),
+ xRadius: Self.upperRadius - 2, yRadius: Self.upperRadius - 2)
+ focus.lineWidth = 1.5
+ focus.stroke()
+ }
+ let text = selected ? emphasizedLabel : label
if bounds.width >= minimumWidth {
- let y = contentCenterY - text.size().height / 2
- if activity != nil || attention {
- // Keep the number and trailing activity cell; only the name truncates.
- let x = contentRect.minX
- let prefix = text.attributedSubstring(from: NSRange(location: 0, length: labelPrefix.utf16.count))
- prefix.draw(at: NSPoint(x: x, y: y))
- let start = labelPrefix.utf16.count
- let title = NSMutableAttributedString(attributedString:
- text.attributedSubstring(from: NSRange(location: start, length: text.length - start)))
- let paragraph = NSMutableParagraphStyle()
- paragraph.lineBreakMode = .byTruncatingTail
- paragraph.alignment = .left
- title.addAttribute(.paragraphStyle, value: paragraph, range: NSRange(location: 0, length: title.length))
- let titleX = x + prefix.size().width
- title.draw(in: NSRect(x: titleX, y: y, width: max(0, activityRect.minX - cellWidth - titleX), height: text.size().height))
- } else {
- text.draw(in: NSRect(x: cellWidth, y: y,
- width: max(0, bounds.width - cellWidth * 2), height: text.size().height))
- }
+ text.draw(in: NSRect(x: titleRect.minX, y: contentCenterY - text.size().height / 2,
+ width: titleRect.width, height: text.size().height))
}
- if let activityMark {
- let font = active ? workspaceBarEmphasisFont(labelFont) : labelFont
+ if !displaysShortcut, let activityMark {
+ let font = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
let paused = activityMark == "||"
let marker = NSAttributedString(string: activityMark,
attributes: [.font: paused ? NSFontManager.shared.convert(font, toSize: font.pointSize * 0.65) : font,
- .kern: paused ? -cellWidth * 0.25 : 0,
+ .kern: paused ? -font.pointSize * 0.15 : 0,
.foregroundColor: activity?.color ?? NSColor.systemOrange])
NSGraphicsContext.saveGraphicsState()
- let padding = bounds.width < minimumWidth ? 0 : cellWidth
- NSRect(x: padding, y: 0, width: max(0, bounds.width - padding * 2), height: bounds.height).clip()
+ bounds.clip()
marker.draw(at: NSPoint(x: activityRect.midX - marker.size().width / 2,
y: contentCenterY - marker.size().height / 2))
NSGraphicsContext.restoreGraphicsState()
}
+ if displaysShortcut, let shortcut = shortcutLabel {
+ shortcut.draw(in: NSRect(x: indicatorRect.minX, y: contentCenterY - shortcut.size().height / 2,
+ width: indicatorRect.width, height: shortcut.size().height))
+ }
}
// Overflowed tabs might not be drawn. Their names and selection still need
// to be available to VoiceOver and automation before they scroll into view.
private func updateAccessibility() {
setAccessibilityLabel(name)
selectButton.setAccessibilityLabel("Select \(name)")
+ closeButton.setAccessibilityLabel("Close \(name)")
+ closeButton.toolTip = "Close Tab"
selectButton.setAccessibilityValue(selected ? "Selected" : "")
let help = [activityLabel,
- keyboardFocus ? "Keyboard is on the swarms. Press Return to type in this swarm." : nil].compactMap { $0 }
+ keyboardFocus ? "Keyboard is on the tabs. Press Return to type in this tab." : nil].compactMap { $0 }
selectButton.setAccessibilityHelp(help.isEmpty ? nil : help.joined(separator: ". "))
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { actionsEnabled }
@@ -2574,14 +2708,16 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
beginDraggingSession(with: [dragging], event: event, source: self)
}
func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { .move }
- override func accessibilityChildren() -> [Any]? { [selectButton] }
+ override func accessibilityChildren() -> [Any]? {
+ closeButton.isHidden ? [selectButton] : [selectButton, closeButton]
+ }
@objc private func selectSwarm() { if actionsEnabled { emit?("select", ["id": swarmId]) } }
@objc private func closeSwarm() { if actionsEnabled { emit?("close", ["id": swarmId]) } }
@objc private func renameSwarm() { if actionsEnabled { emit?("rename", ["id": swarmId]) } }
}
-/// One keyboard-accessible selection target. Closing stays in the native menu
-/// and Command-W, leaving the label centered across the whole tab.
+/// The full tab remains a selection/drag target; the hover close button sits
+/// above its trailing slot. Native menu actions and Command-W remain available.
private class SwarmTabActionButton: SwarmIconButton {
weak var owner: SwarmTabButton?
override var showsHoverFill: Bool { false }
diff --git a/desktop/test/add_phone_dialog_test.dart b/desktop/test/add_phone_dialog_test.dart
index f3c64db3b..0945e2ea7 100644
--- a/desktop/test/add_phone_dialog_test.dart
+++ b/desktop/test/add_phone_dialog_test.dart
@@ -175,7 +175,7 @@ void main() {
);
expect(find.byType(PhonePairQr), findsNothing);
expect(daemon.codes, isEmpty);
- await tester.tap(find.text('[ Connect a machine ]'));
+ await tester.tap(find.widgetWithText(TextButton, 'Connect a machine'));
await tester.pump();
expect(opened, isTrue);
expect(find.byType(AddPhoneDialog), findsNothing);
@@ -342,20 +342,20 @@ void main() {
await tester.pump();
expect(find.byKey(const ValueKey('add-phone-devices')), findsOneWidget);
expect(find.text("Dee's iPhone"), findsOneWidget);
- expect(find.text('online'), findsOneWidget);
+ expect(find.text('Online'), findsOneWidget);
// A pairing that never said who it is says so in plain words.
expect(find.text('Linked device'), findsOneWidget);
expect(find.text('2d'), findsNWidgets(2));
// Three, then the rest on request: the list must not outweigh the QR.
expect(find.text('Older phone'), findsNothing);
- await tester.tap(find.text('[ + 2 more ]'));
+ await tester.tap(find.widgetWithText(TextButton, 'Show 2 more'));
await tester.pump();
expect(find.text('Oldest phone'), findsOneWidget);
await tester.tap(
find.descendant(
of: find.byKey(const ValueKey('add-phone-device-BBBB')),
- matching: find.text('[ remove ]'),
+ matching: find.widgetWithText(TextButton, 'Remove'),
),
);
await tester.pump();
@@ -381,7 +381,7 @@ void main() {
removeDevice: (_) async => false,
);
await tester.pump();
- await tester.tap(find.text('[ remove ]'));
+ await tester.tap(find.widgetWithText(TextButton, 'Remove'));
await tester.pump();
await tester.pump();
expect(find.text("Dee's iPhone"), findsOneWidget);
diff --git a/desktop/test/api_model_picker_test.dart b/desktop/test/api_model_picker_test.dart
index 7e58228b0..c0521b923 100644
--- a/desktop/test/api_model_picker_test.dart
+++ b/desktop/test/api_model_picker_test.dart
@@ -2,6 +2,8 @@
// its chat models folded under its row, Enter shows them, and Use moves the focused pane's agent onto
// one through the daemon — which reads the endpoint and key itself. Only this computer's harnesses
// can use its APIs, and an API that takes no Bearer key stays tools-only.
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -195,18 +197,24 @@ void main() {
),
findsOneWidget,
);
- expect(find.textContaining('models to run a harness'), findsNothing);
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('swarm-search-preview')),
+ matching: find.textContaining('models to run a harness'),
+ ),
+ findsNothing,
+ );
// Folded: a marker to open it, and how many models it has at the end of its row.
expect(
tester
- .widget<Text>(
+ .widget<Icon>(
find.byKey(
const ValueKey('api-row-marker:model:api:openrouter'),
),
)
- .data,
- '▸',
+ .icon,
+ AppIcons.chevronRight,
);
expect(
tester
@@ -249,7 +257,7 @@ void main() {
final marker = find.byKey(
const ValueKey('api-row-marker:model:api:openrouter'),
);
- expect(tester.widget<Text>(marker).data, '▾');
+ expect(tester.widget<Icon>(marker).icon, AppIcons.chevronDown);
expect(
tester
.getTopLeft(
@@ -426,8 +434,17 @@ void main() {
find.byKey(const ValueKey('api-form-input:key')),
'fixture-key',
);
- // Tab from the last field reaches Save; Enter presses it.
- await key(tester, LogicalKeyboardKey.tab);
+ // Traverse the secondary controls, then the fixed footer action.
+ final save = find.byKey(const ValueKey('api-form:save'));
+ for (
+ var step = 0;
+ step < 6 && !tester.widget<FilledButton>(save).focusNode!.hasFocus;
+ step++
+ ) {
+ await key(tester, LogicalKeyboardKey.tab);
+ }
+ expect(tester.widget<FilledButton>(save).focusNode!.hasFocus, isTrue);
+ expect(save.hitTestable(), findsOneWidget);
await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
diff --git a/desktop/test/app_choice_picker_test.dart b/desktop/test/app_choice_picker_test.dart
index 2b5447bd6..c88c88423 100644
--- a/desktop/test/app_choice_picker_test.dart
+++ b/desktop/test/app_choice_picker_test.dart
@@ -88,7 +88,8 @@ void main() {
);
expect(
((container.decoration! as BoxDecoration).border! as Border).top.color,
- Colors.transparent,
+ isNot(Colors.transparent),
+ reason: 'The returned keyboard focus stays visible without selecting it',
);
expect(
tester
diff --git a/desktop/test/app_icon_button_spin_test.dart b/desktop/test/app_icon_button_spin_test.dart
index d93a46c6e..140dc76cd 100644
--- a/desktop/test/app_icon_button_spin_test.dart
+++ b/desktop/test/app_icon_button_spin_test.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart';
@@ -17,6 +18,8 @@ void main() {
of: find.byType(AppIconButton),
matching: find.byType(RotationTransition),
);
+ Color? ink(WidgetTester tester) =>
+ IconTheme.of(tester.element(find.byType(Icon))).color;
Future<void> pumpButton(
WidgetTester tester, {
@@ -34,7 +37,7 @@ void main() {
home: Scaffold(
body: Center(
child: AppIconButton(
- icon: Icons.refresh,
+ icon: AppIcons.refreshCw,
spinning: spinning,
onPressed: onPressed,
),
@@ -87,24 +90,24 @@ void main() {
tester,
) async {
await pumpButton(tester, spinning: true, onPressed: () {});
- final spinningInk = tester.widget<Icon>(find.byType(Icon)).color;
+ final spinningInk = ink(tester);
await tester.pumpWidget(const SizedBox.shrink());
await pumpButton(tester, spinning: false, onPressed: () {});
- expect(spinningInk, tester.widget<Icon>(find.byType(Icon)).color);
+ expect(spinningInk, ink(tester));
// A button with nothing to do is the one that greys out.
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: Center(
- child: AppIconButton(icon: Icons.refresh, onPressed: null),
+ child: AppIconButton(icon: AppIcons.refreshCw, onPressed: null),
),
),
),
);
await tester.pump();
- expect(tester.widget<Icon>(find.byType(Icon)).color, AppPalette.textFaint);
+ expect(ink(tester), AppPalette.textFaint);
});
testWidgets('the glyph stops upright immediately when the work finishes', (
diff --git a/desktop/test/app_menu_test.dart b/desktop/test/app_menu_test.dart
index 6eb4e0ef8..27e56f2b2 100644
--- a/desktop/test/app_menu_test.dart
+++ b/desktop/test/app_menu_test.dart
@@ -9,6 +9,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/app_shell.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/settings/settings_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
import 'package:harness/state/pane_preset.dart';
@@ -48,6 +49,37 @@ Future<void> _mount(WidgetTester tester, AppNotifier app) async {
}
void main() {
+ testWidgets('desktop shell preserves platform text size and contrast', (
+ tester,
+ ) async {
+ final app = createApp()..status = AppStatus.authenticated;
+ tester.platformDispatcher.textScaleFactorTestValue = 1.6;
+ tester.platformDispatcher.accessibilityFeaturesTestValue =
+ const FakeAccessibilityFeatures(highContrast: true);
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ addTearDown(tester.platformDispatcher.clearAccessibilityFeaturesTestValue);
+ await tester.pumpWidget(
+ ProviderScope(
+ overrides: [appStateProvider.overrideWithValue(app)],
+ child: HarnessApp(
+ authenticatedScreen: (_) =>
+ const Scaffold(body: Text('Readable desktop controls')),
+ ),
+ ),
+ );
+ await tester.pump();
+ final context = tester.element(find.text('Readable desktop controls'));
+ expect(MediaQuery.textScalerOf(context).scale(10), 16);
+ expect(MediaQuery.highContrastOf(context), isTrue);
+ final theme = Theme.of(context);
+ final rim = theme.outlinedButtonTheme.style!.side!.resolve({})!;
+ expect(rim.width, 2);
+ expect(rim.color.a, greaterThan(.5));
+ expect(theme.textTheme.bodyMedium!.fontFamily, grid.AppType.sansFamily);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
testWidgets('held app menu commands open only one dialog', (tester) async {
final app = createApp();
await _mount(tester, app);
diff --git a/desktop/test/app_select_field_review_test.dart b/desktop/test/app_select_field_review_test.dart
new file mode 100644
index 000000000..77e236bef
--- /dev/null
+++ b/desktop/test/app_select_field_review_test.dart
@@ -0,0 +1,266 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/widgets/app_menu.dart';
+import 'package:harness/shared/widgets/app_select_field.dart';
+
+import 'support/real_fonts.dart';
+
+const _appearanceOptions = [
+ SelectOption(value: 'system', label: 'Automatic'),
+ SelectOption(value: 'light', label: 'Light'),
+ SelectOption(value: 'dark', label: 'Dark'),
+];
+
+Widget _host(
+ Widget child, {
+ required GlobalKey boundary,
+ Brightness brightness = Brightness.light,
+ double scale = 1,
+}) => RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ themeAnimationDuration: Duration.zero,
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topCenter,
+ child: Padding(padding: const EdgeInsets.all(24), child: child),
+ ),
+ ),
+ ),
+);
+
+Future<void> _capture(
+ WidgetTester tester,
+ GlobalKey boundary,
+ String name,
+) async {
+ final directory = Platform.environment['APP_SELECT_CAPTURE_DIR'];
+ if (directory == null) return;
+ final shadows = debugDisableShadows;
+ try {
+ debugDisableShadows = false;
+ for (final render in tester.allRenderObjects) {
+ render.markNeedsPaint();
+ }
+ await tester.pump();
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage();
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ } finally {
+ debugDisableShadows = shadows;
+ for (final render in tester.allRenderObjects) {
+ render.markNeedsPaint();
+ }
+ await tester.pump();
+ }
+}
+
+Future<void> _open(WidgetTester tester) async {
+ await tester.tap(find.byType(AppSelectField<String>));
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+}
+
+void _expectAllOptionsVisible(WidgetTester tester) {
+ final scroll = tester.state<ScrollableState>(find.byType(Scrollable));
+ expect(scroll.position.maxScrollExtent, 0);
+ final viewport = tester.getRect(find.byType(Scrollable));
+ for (final row in find.byType(AppMenuItem).evaluate()) {
+ final rect = tester.getRect(find.byWidget(row.widget));
+ expect(rect.top, greaterThanOrEqualTo(viewport.top));
+ expect(rect.bottom, lessThanOrEqualTo(viewport.bottom));
+ }
+}
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ if (Platform.isMacOS) {
+ final sans = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in [grid.AppType.sansFamily, 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sans))).load();
+ }
+ }
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
+ });
+
+ tearDown(() {
+ grid.AppTheme.brightness.value = Brightness.light;
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets('short ${brightness.name} menu fits at $scale text size', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(800, 600);
+ addTearDown(tester.view.reset);
+ grid.AppTheme.brightness.value = brightness;
+ final boundary = GlobalKey();
+ String? picked;
+ await tester.pumpWidget(
+ _host(
+ AppSelectField<String>(
+ semanticLabel: 'Appearance',
+ width: 280,
+ value: 'system',
+ options: _appearanceOptions,
+ onChanged: (value) => picked = value,
+ ),
+ boundary: boundary,
+ brightness: brightness,
+ scale: scale,
+ ),
+ );
+ await _open(tester);
+ _expectAllOptionsVisible(tester);
+ expect(picked, isNull);
+ await _capture(tester, boundary, 'select-${brightness.name}-$scale');
+ await tester.tap(find.widgetWithText(AppMenuItem, 'Dark'));
+ await tester.pumpAndSettle();
+ expect(picked, 'dark');
+ expect(find.byType(AppMenuItem), findsNothing);
+ });
+ }
+ }
+
+ testWidgets('large detail rows use their actual natural height', (
+ tester,
+ ) async {
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ _host(
+ AppSelectField<String>(
+ width: 460,
+ value: 'invite',
+ textStyle: grid.AppType.body().copyWith(fontSize: 18),
+ options: const [
+ SelectOption(
+ value: 'invite',
+ label: 'Invite only',
+ detail: 'Only people you invite.',
+ ),
+ SelectOption(value: 'public', label: 'Public'),
+ ],
+ onChanged: (_) {},
+ ),
+ boundary: boundary,
+ scale: 2,
+ ),
+ );
+ await _open(tester);
+ _expectAllOptionsVisible(tester);
+ await _capture(tester, boundary, 'select-detail-2.0');
+ });
+
+ testWidgets('a small window still scrolls to keyboard-selected choices', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(360, 240);
+ addTearDown(tester.view.reset);
+ final boundary = GlobalKey();
+ String? picked;
+ await tester.pumpWidget(
+ _host(
+ AppSelectField<String>(
+ width: 280,
+ value: '0',
+ options: [
+ for (var i = 0; i < 10; i++)
+ SelectOption(value: '$i', label: 'Choice $i'),
+ const SelectOption(value: 'last', label: 'Last choice'),
+ ],
+ onChanged: (value) => picked = value,
+ ),
+ boundary: boundary,
+ scale: 2,
+ ),
+ );
+ await _open(tester);
+ final scroll = tester.state<ScrollableState>(find.byType(Scrollable));
+ expect(scroll.position.maxScrollExtent, greaterThan(0));
+ final viewport = tester.getRect(find.byType(Scrollable));
+ expect(viewport.top, greaterThanOrEqualTo(0));
+ expect(viewport.bottom, lessThanOrEqualTo(240));
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyL, character: 'l');
+ await tester.pumpAndSettle();
+ final last = tester.getRect(
+ find.widgetWithText(AppMenuItem, 'Last choice'),
+ );
+ expect(last.top, greaterThanOrEqualTo(viewport.top));
+ expect(last.bottom, lessThanOrEqualTo(viewport.bottom));
+ expect(scroll.position.pixels, greaterThan(0));
+ expect(picked, isNull);
+ await _capture(tester, boundary, 'select-small-window-2.0');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(picked, 'last');
+ expect(find.byType(AppMenuItem), findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('filter results shrink naturally with large text', (
+ tester,
+ ) async {
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ _host(
+ AppSelectField<String>(
+ width: 360,
+ value: '0',
+ options: [
+ for (var i = 0; i < 9; i++)
+ SelectOption(value: '$i', label: 'Choice $i'),
+ const SelectOption(value: 'match', label: 'Matching option'),
+ ],
+ filterable: true,
+ onChanged: (_) {},
+ ),
+ boundary: boundary,
+ scale: 2,
+ ),
+ );
+ await _open(tester);
+ final menuScroll = tester
+ .stateList<ScrollableState>(find.byType(Scrollable))
+ .where((scroll) => scroll.position.axis == Axis.vertical)
+ .single;
+ expect(menuScroll.position.maxScrollExtent, greaterThan(0));
+ await tester.enterText(find.byKey(const Key('app-select-filter')), 'match');
+ await tester.pumpAndSettle();
+ expect(find.byType(AppMenuItem), findsOneWidget);
+ expect(menuScroll.position.maxScrollExtent, 0);
+ await _capture(tester, boundary, 'select-filtered-2.0');
+ expect(tester.takeException(), isNull);
+ });
+}
diff --git a/desktop/test/app_select_field_test.dart b/desktop/test/app_select_field_test.dart
index 0745fbee4..ecaf31b6c 100644
--- a/desktop/test/app_select_field_test.dart
+++ b/desktop/test/app_select_field_test.dart
@@ -1,7 +1,9 @@
+import 'dart:ui' show SemanticsAction, Tristate;
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/widgets/app_menu.dart';
import 'package:harness/shared/widgets/app_select_field.dart';
@@ -49,6 +51,110 @@ Future<void> _open(WidgetTester tester) async {
void main() {
tearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ testWidgets('accessible selector announces purpose, value and open state', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ String? chosen;
+ await tester.pumpWidget(
+ _host(
+ StatefulBuilder(
+ builder: (context, setState) => AppSelectField<String?>(
+ semanticLabel: 'Terminal font',
+ value: chosen,
+ options: _options,
+ width: 280,
+ onChanged: (value) => setState(() => chosen = value),
+ ),
+ ),
+ top: true,
+ ),
+ );
+ final trigger = find.bySemanticsLabel('Terminal font');
+ final closed = tester.getSemantics(trigger);
+ expect(closed.getSemanticsData().value, 'System, SF Pro');
+ expect(closed.getSemanticsData().flagsCollection.isButton, isTrue);
+ expect(
+ closed.getSemanticsData().flagsCollection.isExpanded,
+ Tristate.isFalse,
+ );
+ expect(closed.getSemanticsData().hasAction(SemanticsAction.tap), isTrue);
+ // Activating through assistive technology must open the same working menu.
+ tester
+ .renderObject(trigger)
+ .owner!
+ .semanticsOwner!
+ .performAction(closed.id, SemanticsAction.tap);
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .getSemantics(trigger)
+ .getSemanticsData()
+ .flagsCollection
+ .isExpanded,
+ Tristate.isTrue,
+ );
+ expect(chosen, isNull, reason: 'opening does not change the setting');
+ await tester.tap(find.widgetWithText(AppMenuItem, 'Menlo'));
+ await tester.pumpAndSettle();
+ expect(chosen, 'Menlo');
+ final updated = tester.getSemantics(trigger).getSemanticsData();
+ expect(updated.label, 'Terminal font');
+ expect(updated.value, 'Menlo');
+ expect(updated.flagsCollection.isExpanded, Tristate.isFalse);
+ expect(updated.flagsCollection.isFocused, Tristate.isTrue);
+ } finally {
+ semantics.dispose();
+ }
+ });
+
+ testWidgets('large text fits and focus remains distinct from selection', (
+ tester,
+ ) async {
+ final focus = FocusNode();
+ addTearDown(focus.dispose);
+ await tester.pumpWidget(
+ _host(
+ MediaQuery(
+ data: const MediaQueryData(
+ textScaler: TextScaler.linear(2),
+ highContrast: true,
+ disableAnimations: true,
+ ),
+ child: AppSelectField<String>(
+ width: 280,
+ value: 'a',
+ options: const [SelectOption(value: 'a', label: 'Alpha')],
+ selected: false,
+ focusNode: focus,
+ onChanged: (_) {},
+ ),
+ ),
+ ),
+ );
+ final field = tester.getRect(_field);
+ final label = tester.getRect(find.text('Alpha'));
+ expect(label.top, greaterThan(field.top));
+ expect(label.bottom, lessThan(field.bottom));
+ final box = find.descendant(
+ of: _field,
+ matching: find.byType(AnimatedContainer),
+ );
+ Border rim() =>
+ (tester.widget<AnimatedContainer>(box).decoration! as BoxDecoration)
+ .border!
+ as Border;
+ final before = rim();
+ focus.requestFocus();
+ await tester.pump();
+ expect(rim().top.color, isNot(before.top.color));
+ expect(rim().top.width, before.top.width);
+ expect(tester.getRect(find.text('Alpha')), label);
+ expect(tester.widget<AnimatedContainer>(box).duration, Duration.zero);
+ expect(tester.takeException(), isNull);
+ });
+
testWidgets('typing a name focuses a choice without applying it', (
tester,
) async {
@@ -147,7 +253,7 @@ void main() {
tester,
) async {
// The regression this exists for: the leading slot was once filled with
- // `Icons.check_box_outline_blank` to keep the labels aligned. That glyph
+ // `AppIcons.square` to keep the labels aligned. That glyph
// draws a real outlined square, so a pick-one menu rendered as a list of
// empty checkboxes — and put a border where §1 allows none.
await tester.pumpWidget(
@@ -163,7 +269,7 @@ void main() {
await _open(tester);
expect(find.byType(AppMenuItem), findsNWidgets(3));
- expect(find.byIcon(Icons.check_box_outline_blank), findsNothing);
+ expect(find.byIcon(AppIcons.square), findsNothing);
// Exactly one glyph in the whole panel: the tick on the chosen row.
expect(
find.descendant(
@@ -172,7 +278,7 @@ void main() {
),
findsOneWidget,
);
- expect(find.byIcon(LucideIcons.check300), findsOneWidget);
+ expect(find.byIcon(AppIcons.check), findsOneWidget);
});
testWidgets('the choice is marked three ways, not by colour alone', (
@@ -199,7 +305,7 @@ void main() {
// 1. the tick, 2. the heavier label. (3. the accent wash is painted by an
// `Ink` and is checked by eye, not here.)
- expect(find.byIcon(LucideIcons.check300), findsOneWidget);
+ expect(find.byIcon(AppIcons.check), findsOneWidget);
expect(labelIn('Menlo').style?.fontWeight, grid.AppFont.medium);
expect(labelIn('Helvetica Neue').style?.fontWeight, grid.AppFont.regular);
});
@@ -256,12 +362,12 @@ void main() {
SelectOption(
value: 'a',
label: 'Alpha',
- leading: () => const Icon(Icons.circle, size: 14),
+ leading: () => const Icon(AppIcons.dot, size: 14),
),
SelectOption(
value: 'b',
label: 'Beta',
- leading: () => const Icon(Icons.square, size: 14),
+ leading: () => const Icon(AppIcons.square, size: 14),
),
],
onChanged: (_) {},
@@ -286,9 +392,9 @@ void main() {
reason: 'the ticked row and the unticked one start on the same column',
);
// Both marks are drawn, and the tick is drawn as well as them, not instead.
- expect(find.byIcon(Icons.circle), findsWidgets);
- expect(find.byIcon(Icons.square), findsWidgets);
- expect(find.byIcon(LucideIcons.check300), findsOneWidget);
+ expect(find.byIcon(AppIcons.dot), findsWidgets);
+ expect(find.byIcon(AppIcons.square), findsWidgets);
+ expect(find.byIcon(AppIcons.check), findsOneWidget);
});
testWidgets('picking a row reports it and closes the panel', (tester) async {
@@ -347,7 +453,7 @@ void main() {
width: 188,
),
AppMenuItem(
- icon: Icons.circle,
+ icon: AppIcons.dot,
label: 'A context row',
onPressed: () {},
),
diff --git a/desktop/test/asset_paths_test.dart b/desktop/test/asset_paths_test.dart
index dec59ad1b..fad62c4b7 100644
--- a/desktop/test/asset_paths_test.dart
+++ b/desktop/test/asset_paths_test.dart
@@ -22,16 +22,19 @@ import 'package:flutter_test/flutter_test.dart';
///
/// Interpolated paths (the wallpapers build theirs from an enum) cannot be seen
/// from here and are covered by the suites that load them.
-final _assetLiteral = RegExp(r'''['"](assets/[A-Za-z0-9_./-]+\.[A-Za-z0-9]+)['"]''');
+final _assetLiteral = RegExp(
+ r'''['"](assets/[A-Za-z0-9_./-]+\.[A-Za-z0-9]+)['"]''',
+);
void main() {
test('every asset path named in lib/ resolves to a file', () {
final missing = <String>[];
var checked = 0;
- for (final file in Directory('lib')
- .listSync(recursive: true)
- .whereType<File>()
- .where((f) => f.path.endsWith('.dart'))) {
+ for (final file
+ in Directory('lib')
+ .listSync(recursive: true)
+ .whereType<File>()
+ .where((f) => f.path.endsWith('.dart'))) {
final source = file.readAsStringSync();
for (final match in _assetLiteral.allMatches(source)) {
final path = match.group(1)!;
@@ -39,10 +42,20 @@ void main() {
if (!File(path).existsSync()) missing.add('$path (${file.path})');
}
}
- expect(checked, greaterThan(50), reason: 'the scan found almost nothing — '
- 'the pattern probably stopped matching how paths are written');
- expect(missing, isEmpty, reason: 'named in code, absent on disk:\n'
- '${missing.join('\n')}');
+ expect(
+ checked,
+ greaterThan(50),
+ reason:
+ 'the scan found almost nothing — '
+ 'the pattern probably stopped matching how paths are written',
+ );
+ expect(
+ missing,
+ isEmpty,
+ reason:
+ 'named in code, absent on disk:\n'
+ '${missing.join('\n')}',
+ );
});
test('every bundled asset is named by code, or is a licence beside one', () {
@@ -63,7 +76,8 @@ void main() {
.where((f) => f.path.endsWith('.dart'))
.map((f) => f.readAsStringSync())
.join('\n');
- final manifest = File('assets/store/covers/sources.json').readAsStringSync();
+ final manifest = File('assets/store/covers/sources.json')
+ .readAsStringSync();
bool named(String name) => source.contains(name) || manifest.contains(name);
bool attribution(String name) =>
@@ -73,21 +87,34 @@ void main() {
name == 'sources.json';
final orphans = <String>[];
- for (final file in Directory('assets')
- .listSync(recursive: true)
- .whereType<File>()) {
+ final siblingCache = <String, List<String>>{};
+ for (final file in Directory(
+ 'assets',
+ ).listSync(recursive: true).whereType<File>()) {
final path = file.path;
final name = path.split('/').last;
final dir = path.substring(0, path.length - name.length);
+ // These two directories are selected by the literal slot/portrait ternary.
+ if ((dir == 'assets/daemon-art/slot/' ||
+ dir == 'assets/daemon-art/portrait/') &&
+ source.contains(r"assets/daemon-art/${slot ? 'slot' : 'portrait'}")) {
+ continue;
+ }
if (attribution(name) || named(name)) continue;
// A folder code builds paths into. `assets/` itself is excluded: every
// path in the app starts with it, so it would account for everything.
if (dir != 'assets/' && source.contains(dir)) continue;
final stem = name.split('.').first;
- final siblings = Directory(dir)
- .listSync()
- .whereType<File>()
- .map((f) => f.path.split('/').last)
+ final siblings = siblingCache
+ .putIfAbsent(
+ dir,
+ () =>
+ Directory(dir)
+ .listSync()
+ .whereType<File>()
+ .map((f) => f.path.split('/').last)
+ .toList(),
+ )
.where((s) => s != name && s.split('.').first == stem);
if (siblings.any(named)) continue;
orphans.add(path);
diff --git a/desktop/test/autonomous_device_pairing_test.dart b/desktop/test/autonomous_device_pairing_test.dart
index f3fe61a96..b1e866209 100644
--- a/desktop/test/autonomous_device_pairing_test.dart
+++ b/desktop/test/autonomous_device_pairing_test.dart
@@ -1,6 +1,8 @@
import 'dart:async';
+import 'dart:ui' show SemanticsAction;
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/autonomous_device/autonomous_device_cli.dart';
import 'package:harness/shared/widgets/app_icon_button.dart';
@@ -13,6 +15,7 @@ class FakeAutonomousDeviceCli extends AutonomousDeviceCli {
bool unsupported = false;
int statusCalls = 0;
Completer<void>? statusWait;
+ Completer<void>? pairWait;
String? pairFailure;
bool networkBlocked = false;
List<Map<String, dynamic>> discovered = [
@@ -50,6 +53,7 @@ class FakeAutonomousDeviceCli extends AutonomousDeviceCli {
required String deviceId,
}) async {
submissions.add({'code': code, 'deviceId': deviceId});
+ if (pairWait != null) await pairWait!.future;
if (pairFailure != null) {
throw AutonomousDeviceCliException('CODE_MISMATCH', pairFailure!);
}
@@ -107,6 +111,49 @@ void main() {
await tester.pumpAndSettle();
}
+ testWidgets(
+ 'pairing controls keep separate accessible purposes and actions',
+ (tester) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ final cli = FakeAutonomousDeviceCli();
+ await open(tester, cli);
+ final picker = find.bySemanticsLabel('Autonomous robot');
+ final pickerNode = tester.getSemantics(picker);
+ final codeNode = tester.getSemantics(
+ find.bySemanticsLabel('Six-character code'),
+ );
+ final refreshNode = tester.getSemantics(
+ find.byTooltip('Refresh Autonomous robot status'),
+ );
+ expect(pickerNode.getSemanticsData().label, 'Autonomous robot');
+ expect(pickerNode.getSemanticsData().value, 'Select a device');
+ expect(pickerNode.getSemanticsData().flagsCollection.isButton, isTrue);
+ expect(codeNode.id, isNot(pickerNode.id));
+ expect(codeNode.getSemanticsData().flagsCollection.isTextField, isTrue);
+ expect(
+ codeNode.getSemanticsData().hasAction(SemanticsAction.tap),
+ isTrue,
+ );
+ expect(refreshNode.id, isNot(pickerNode.id));
+ expect(
+ refreshNode.getSemanticsData().tooltip,
+ 'Refresh Autonomous robot status',
+ );
+ expect(
+ refreshNode.getSemanticsData().hasAction(SemanticsAction.tap),
+ isTrue,
+ );
+ await select(tester, 'device-1');
+ expect(tester.getSemantics(picker).getSemanticsData().value, 'Kitchen');
+ expect(cli.submissions, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ } finally {
+ semantics.dispose();
+ }
+ },
+ );
+
testWidgets(
'code input and discovery are immediate without address or intent',
(tester) async {
@@ -226,6 +273,118 @@ void main() {
await select(tester, 'device-2');
expect(tester.widget<TextField>(codeField).controller!.text, isEmpty);
});
+
+ for (final (outcome, error) in [
+ (
+ 'failure',
+ const AutonomousDeviceCliException('CODE_MISMATCH', 'Mismatch'),
+ ),
+ (
+ 'cancellation',
+ const AutonomousDeviceCliException('CANCELLED', 'Pairing was cancelled.'),
+ ),
+ ]) {
+ testWidgets(
+ 'pending device selection ignores keys and recovers after $outcome',
+ (tester) async {
+ tester.view.physicalSize = const Size(880, 560);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final semantics = tester.ensureSemantics();
+ try {
+ final pending = Completer<void>();
+ final cli = FakeAutonomousDeviceCli()
+ ..pairWait = pending
+ ..discovered.add({'id': 'device-2', 'name': 'Desk'});
+ await open(tester, cli);
+ final picker = find.byKey(const Key('autonomous-device-selection'));
+ await tester.tap(picker);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Kitchen').last);
+ await tester.pumpAndSettle();
+ final previousSelection = tester
+ .widget<AppSelectField<String?>>(picker)
+ .onChanged;
+ await tester.enterText(codeField, 'ABC234');
+ await tester.tap(find.text('Pair'));
+ await tester.pump();
+ expect(find.text('Pairing…'), findsOneWidget);
+ final pendingPicker = tester
+ .getSemantics(find.bySemanticsLabel('Autonomous robot'))
+ .getSemanticsData();
+ expect(pendingPicker.label, 'Autonomous robot');
+ expect(pendingPicker.value, 'Kitchen');
+ expect(pendingPicker.hasAction(SemanticsAction.tap), isFalse);
+ expect(cli.submissions, [
+ {'code': 'ABC234', 'deviceId': 'device-1'},
+ ]);
+
+ // The pending selector is unavailable to Tab/Enter just as it is to a
+ // pointer, so the displayed device cannot diverge from this operation.
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Desk'), findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ // A selection queued before the pending rebuild follows the same guard.
+ previousSelection('device-2');
+ await tester.pump();
+ expect(
+ tester.widget<AppSelectField<String?>>(picker).value,
+ 'device-1',
+ );
+ expect(cli.submissions, hasLength(1));
+
+ pending.completeError(error);
+ await tester.pumpAndSettle();
+ expect(find.text(error.userMessage), findsOneWidget);
+ expect(tester.widget<TextField>(codeField).enabled, isTrue);
+ final editablePicker = tester
+ .getSemantics(find.bySemanticsLabel('Autonomous robot'))
+ .getSemanticsData();
+ expect(editablePicker.label, 'Autonomous robot');
+ expect(editablePicker.value, 'Kitchen');
+ expect(editablePicker.flagsCollection.isButton, isTrue);
+ expect(editablePicker.hasAction(SemanticsAction.tap), isTrue);
+ for (
+ var i = 0;
+ i < 4 && !Focus.of(tester.element(find.text('Kitchen'))).hasFocus;
+ i++
+ ) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ }
+ expect(
+ Focus.of(tester.element(find.text('Kitchen'))).hasFocus,
+ isTrue,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Desk'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<AppSelectField<String?>>(picker).value,
+ 'device-2',
+ );
+ expect(find.text(error.userMessage), findsNothing);
+ cli.pairWait = null;
+ await submit(tester, 'DEF567');
+ expect(cli.submissions.map((row) => row['deviceId']), [
+ 'device-1',
+ 'device-2',
+ ]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ } finally {
+ semantics.dispose();
+ }
+ },
+ );
+ }
testWidgets('lost discovery clears selection and never retargets code', (
tester,
) async {
diff --git a/desktop/test/boot_flow_widget_test.dart b/desktop/test/boot_flow_widget_test.dart
index a1b19496e..79f275d7e 100644
--- a/desktop/test/boot_flow_widget_test.dart
+++ b/desktop/test/boot_flow_widget_test.dart
@@ -2,6 +2,7 @@ import 'support/resource_picker.dart';
import 'support/workspace_tools.dart';
import 'swarm_interactions_test.dart' show chord;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/services.dart';
import 'dart:async';
@@ -22,7 +23,6 @@ import 'package:harness/update/desktop_updater.dart';
import 'package:harness/update/manual_update_check.dart';
import 'package:harness/widgets/update_notice.dart';
import 'package:harness/widgets/bootstrapping_screen.dart';
-import 'package:harness/widgets/terminal_progress.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -547,7 +547,7 @@ void main() {
// the wordmark left when the screen stopped being a logo over a button.
expect(find.text('Your agents, wherever they run'), findsOneWidget);
expect(find.text('Sign in'), findsOneWidget);
- expect(find.byIcon(Icons.login), findsOneWidget);
+ expect(find.byIcon(AppIcons.logIn), findsOneWidget);
});
testWidgets('bootstrapping shows branded startup screen (pre-login)', (
@@ -566,8 +566,8 @@ void main() {
// LoginScreen. Keep this on the real RootShell so notifier wiring remains
// covered as well as the standalone screen's presentation tests.
expect(find.byType(BootstrappingScreen), findsOneWidget);
- expect(find.byType(TerminalProgressLine), findsOneWidget);
- expect(find.text(r'$ harness start'), findsOneWidget);
+ expect(find.byType(CircularProgressIndicator), findsOneWidget);
+ expect(find.text('Opening your workspace'), findsOneWidget);
expect(find.text('Opening Harness…'), findsOneWidget);
expect(find.text('Sign in'), findsNothing);
});
@@ -583,8 +583,8 @@ void main() {
);
await tester.pump();
- expect(find.text(r'$ harness doctor'), findsOneWidget);
- expect(find.textContaining('read-only'), findsOneWidget);
+ expect(find.text('Checking this computer'), findsOneWidget);
+ expect(find.text("This check doesn't install anything."), findsOneWidget);
expect(find.text('ENVIRONMENT SETUP'), findsNothing);
expect(find.text('Pre-flight check'), findsNothing);
});
@@ -613,7 +613,7 @@ void main() {
expect(app.status, AppStatus.checkingEnvironment);
expect(
- find.text('all checks passed · opening your workspace'),
+ find.text('All checks passed. Opening your workspace…'),
findsOneWidget,
);
expect(find.text('Continue to sign in'), findsNothing);
@@ -870,14 +870,14 @@ void main() {
),
);
await tester.pump();
- expect(find.byType(TerminalProgressLine), findsOneWidget);
+ expect(find.byType(BootstrappingScreen), findsOneWidget);
expect(find.text('Sign in'), findsNothing);
app.status = AppStatus.unauthenticated;
app.notifyListeners();
await tester.pump();
- expect(find.byType(TerminalProgressLine), findsNothing);
+ expect(find.byType(BootstrappingScreen), findsNothing);
expect(find.text('Sign in'), findsOneWidget);
});
diff --git a/desktop/test/bootstrapping_screen_test.dart b/desktop/test/bootstrapping_screen_test.dart
index 66d5e0bf1..8656d96fb 100644
--- a/desktop/test/bootstrapping_screen_test.dart
+++ b/desktop/test/bootstrapping_screen_test.dart
@@ -1,18 +1,20 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/terminal/terminal_font_store.dart';
import 'package:harness/widgets/bootstrapping_screen.dart';
-import 'package:harness/widgets/box_chrome.dart';
-import 'package:harness/widgets/terminal_progress.dart';
+import 'package:xterm/xterm.dart';
Widget _host({
String? message,
bool reduceMotion = false,
double textScale = 1,
+ Brightness brightness = Brightness.dark,
}) {
- grid.AppTheme.brightness.value = Brightness.dark;
+ grid.AppTheme.brightness.value = brightness;
return MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
+ theme: grid.buildAppTheme(brightness: brightness),
home: MediaQuery(
data: MediaQueryData(
size: const Size(880, 560),
@@ -27,21 +29,18 @@ Widget _host({
}
void main() {
- testWidgets('is the terminal box, with a truthful fallback status', (
+ testWidgets('opens with a task heading and a truthful fallback status', (
tester,
) async {
await tester.pumpWidget(_host());
await tester.pump(const Duration(milliseconds: 100));
- // The first thing the app shows is the box the new tab uses, not a card
- // with a headline: one terminal, from the first frame.
- expect(find.byType(TerminalBox), findsOneWidget);
- expect(find.text(r'$ harness start'), findsOneWidget);
+ expect(find.text('Opening your workspace'), findsOneWidget);
expect(find.text('Opening Harness…'), findsOneWidget);
- expect(find.byType(TerminalProgressLine), findsOneWidget);
- // Nothing on the line is bigger than the terminal's own text.
- final title = tester.widget<Text>(find.text(r'$ harness start'));
- expect(title.style?.fontSize, boxMonoStyle().fontSize);
+ expect(find.byType(CircularProgressIndicator), findsOneWidget);
+ expect(find.textContaining('%'), findsNothing);
+ final title = tester.widget<Text>(find.text('Opening your workspace'));
+ expect(title.style?.fontFamily, grid.AppType.sansFamily);
});
testWidgets('shows the daemon status as an accessible live update', (
@@ -59,31 +58,94 @@ void main() {
semantics.dispose();
});
- testWidgets('Reduce Motion leaves the bar still', (tester) async {
+ testWidgets('Reduce Motion uses a static waiting indicator', (tester) async {
await tester.pumpWidget(_host(reduceMotion: true));
await tester.pump(const Duration(milliseconds: 300));
- expect(find.byType(TerminalProgressLine), findsOneWidget);
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ expect(find.byIcon(AppIcons.hourglass), findsOneWidget);
expect(
tester.binding.hasScheduledFrame,
isFalse,
- reason: 'a bar that kept travelling would never settle',
+ reason: 'startup must not continuously animate under Reduce Motion',
);
});
- testWidgets('fits the minimum window at the largest supported UI scale', (
+ testWidgets(
+ 'keeps bounded recent activity and announces the current message',
+ (tester) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ for (final message in [
+ 'Opening Harness…',
+ 'Checking account…',
+ 'Checking account…',
+ 'Starting local service…',
+ 'Connecting to local service…',
+ 'Restoring your workspace…',
+ ]) {
+ await tester.pumpWidget(_host(message: message, reduceMotion: true));
+ }
+ expect(find.text('Recent activity'), findsOneWidget);
+ expect(find.text('Opening Harness…'), findsNothing);
+ expect(find.text('Checking account…'), findsOneWidget);
+ expect(find.text('Starting local service…'), findsOneWidget);
+ expect(find.text('Connecting to local service…'), findsOneWidget);
+ expect(
+ tester.getSemantics(find.byKey(const Key('boot-status'))).value,
+ 'Restoring your workspace…',
+ );
+ } finally {
+ semantics.dispose();
+ }
+ },
+ );
+
+ testWidgets('startup typography is independent of the terminal preference', (
tester,
) async {
- tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = const Size(880, 560);
- addTearDown(tester.view.resetDevicePixelRatio);
- addTearDown(tester.view.resetPhysicalSize);
-
- await tester.pumpWidget(_host(textScale: 19 / 14));
- await tester.pump(const Duration(milliseconds: 100));
-
- expect(tester.takeException(), isNull);
- expect(find.text(r'$ harness start'), findsOneWidget);
- expect(find.text('Opening Harness…'), findsOneWidget);
+ final original = terminalFontStore.value;
+ addTearDown(() => terminalFontStore.value = original);
+ await tester.pumpWidget(_host(reduceMotion: true));
+ final title = find.text('Opening your workspace');
+ final style = tester.widget<Text>(title).style;
+ final size = tester.getSize(title);
+ terminalFontStore.value = const TerminalStyle(
+ fontFamily: 'Courier New',
+ fontSize: 22,
+ );
+ await tester.pump();
+ expect(tester.widget<Text>(title).style, style);
+ expect(tester.getSize(title), size);
});
+
+ for (final brightness in Brightness.values) {
+ testWidgets('long startup status fits a narrow ${brightness.name} window', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(360, 360);
+ addTearDown(tester.view.reset);
+ const message =
+ 'Connecting to the local Harness service and restoring your saved '
+ 'workspace with its open projects…';
+ await tester.pumpWidget(
+ _host(
+ textScale: 1.6,
+ brightness: brightness,
+ reduceMotion: true,
+ message: message,
+ ),
+ );
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ expect(find.text('Opening your workspace'), findsOneWidget);
+ final text = tester.widget<Text>(find.text(message));
+ expect(text.maxLines, isNull);
+ expect(
+ tester.widget<Scaffold>(find.byType(Scaffold)).backgroundColor,
+ grid.AppPalette.windowBg,
+ );
+ });
+ }
}
diff --git a/desktop/test/box_flows_test.dart b/desktop/test/box_flows_test.dart
index c8b6066d9..09cdd27a5 100644
--- a/desktop/test/box_flows_test.dart
+++ b/desktop/test/box_flows_test.dart
@@ -33,7 +33,7 @@ void main() {
tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller;
testWidgets(
- 'canceled edits and tasks do not replace successful launch defaults',
+ 'dismissed edits resume and explicit agent/project choices become defaults',
(tester) async {
final app = createApp();
seedMixedAgents(app);
@@ -55,9 +55,11 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
await chord(tester, LogicalKeyboardKey.keyN);
- expect(box(tester).task, '');
- expect(box(tester).engine, 'codex');
- expect(box(tester).project.folder, '/work/openharness');
+ expect(box(tester).task, 'Review this project');
+ expect(box(tester).engine, 'opencode');
+ expect(box(tester).project.folder, '/work/selected-before-task');
+ expect(app.agentPreference.value, 'opencode');
+ expect(app.projectHistory.selected('m'), '/work/selected-before-task');
expect(app.panes, hasLength(1));
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
@@ -89,20 +91,11 @@ void main() {
);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- controller.move(
- controller.options.indexWhere(
- (row) => row.id == NewHarnessController.browseId,
- ) -
- controller.cursor,
- );
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
FocusManager.instance.primaryFocus?.unfocus();
picker.answer.complete(null);
await tester.pumpAndSettle();
+ expect(picker.opened, 1);
+ expect(controller.field, NewHarnessField.projectMenu);
expect(FocusManager.instance.primaryFocus?.debugLabel, 'new-harness-query');
await typeHarnessQuery(tester, 'robotics');
expect(controller.query, 'robotics');
@@ -139,17 +132,6 @@ void main() {
);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- controller.move(
- controller.options.indexWhere(
- (row) => row.id == NewHarnessController.browseId,
- ) -
- controller.cursor,
- );
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
expect(picker.opened, 1);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
@@ -189,17 +171,6 @@ void main() {
);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- controller.move(
- controller.options.indexWhere(
- (row) => row.id == NewHarnessController.browseId,
- ) -
- controller.cursor,
- );
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
await tester.pump();
expect(find.text('Choose a folder'), findsOneWidget);
expect(
@@ -221,7 +192,7 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
- testWidgets('changing source panes never changes fresh launch defaults', (
+ testWidgets('each source pane retains its own draft and launch defaults', (
tester,
) async {
final app = createApp();
@@ -251,7 +222,13 @@ void main() {
app.focusPane(first.id);
await tester.pump();
await chord(tester, LogicalKeyboardKey.keyN);
- expect(box(tester).project.folder, '/work/openharness');
+ expect(box(tester).project.folder, '/work/first-draft');
+ expect(app.projectHistory.selected('m'), '/work/openharness');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ app.focusPane(other.id);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.keyN);
+ expect(box(tester).project.folder, '/work/second-draft');
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
});
diff --git a/desktop/test/box_render_preview_test.dart b/desktop/test/box_render_preview_test.dart
index 4a89de295..a4d9b3f0c 100644
--- a/desktop/test/box_render_preview_test.dart
+++ b/desktop/test/box_render_preview_test.dart
@@ -1,8 +1,10 @@
import 'support/open_harness.dart';
import 'support/launch_menu.dart';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:harness/shared/theme/appearance_prefs_store.dart';
import 'package:harness/shared/theme/prompt_style.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'dart:async';
import 'dart:io';
@@ -22,6 +24,10 @@ import 'package:harness/state/pane_preset.dart';
import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/grid_model_picker.dart';
import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/widgets/delete_agent_dialog.dart';
+import 'package:harness/widgets/restart_agent_action.dart';
+import 'package:harness/widgets/fork_agent_dialog.dart';
+import 'package:harness/widgets/machine_actions.dart';
import 'package:harness/ws/ws_conn.dart';
import 'swarm_interactions_test.dart' show chord;
@@ -175,6 +181,196 @@ Future<void> loadPreviewFonts() async {
void main() {
final dir = Platform.environment['BOX_RENDER_DIR'];
+ // Isolated synthetic fixtures let the confirmation family be reviewed without
+ // navigating unrelated surfaces or connecting to a real machine.
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.7]) {
+ testWidgets(
+ 'desktop confirmations render in ${brightness.name} at $scale',
+ skip: dir == null,
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ (tester) async {
+ await tester.runAsync(loadPreviewFonts);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ final oldShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ addTearDown(() => debugDisableShadows = oldShadows);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = scale == 1
+ ? const Size(900, 700)
+ : const Size(480, 360);
+ addTearDown(tester.view.reset);
+
+ Future<void> open(void Function(BuildContext) show) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => show(context),
+ child: const Text('Open fixture'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open fixture'));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> shot(String name, String closeLabel) async {
+ expect(find.text(closeLabel).hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pump(const Duration(milliseconds: 50));
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(
+ Uri.file(
+ '$dir/confirmation-$name-${brightness.name}-$scale.png',
+ ),
+ ),
+ );
+ }
+
+ Future<void> close() async {
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.pumpWidget(const SizedBox());
+ }
+
+ AppNotifier fixture(WsConn connection) {
+ final app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!
+ ..nodeOnline = true
+ ..agents = const [
+ Agent(
+ id: 'a0',
+ name: 'Improve search and keyboard navigation',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ ];
+ app.adoptSessionForTest(terminal('a0', []));
+ addTearDown(app.dispose);
+ return app;
+ }
+
+ final stopping = StopConnection();
+ final stopApp = fixture(stopping);
+ await open((context) {
+ confirmDeleteAgent(
+ context,
+ stopApp,
+ 'm',
+ 'a0',
+ 'Improve search and keyboard navigation',
+ engine: 'codex',
+ );
+ });
+ await shot('stop', 'Cancel');
+ await tester.tap(find.byKey(const Key('agent-stop-confirm')));
+ await tester.pumpAndSettle();
+ await shot('stop-pending', 'Close');
+ stopping.stopReplies.single.complete({
+ 'error': 'OFFLINE',
+ 'detail': 'Reconnect to this machine and try again.',
+ });
+ await tester.pumpAndSettle();
+ await shot('stop-error', 'Cancel');
+ await tester.tap(find.byKey(const Key('agent-stop-confirm')));
+ await tester.pumpAndSettle();
+ stopping.stopReplies.last.complete({
+ 'error': 'OFFLINE',
+ 'detail': List.generate(
+ 12,
+ (index) =>
+ 'Diagnostic ${index + 1}: reconnect to this machine and try again.',
+ ).join('\n'),
+ });
+ await tester.pumpAndSettle();
+ await shot('stop-long-error', 'Cancel');
+ await close();
+
+ final restarting = RestartConnection();
+ final restartApp = fixture(restarting);
+ await open(
+ (context) => restartHarness(context, restartApp, 'm', 'a0'),
+ );
+ await shot('restart-pending', 'Close');
+ restarting.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ await tester.pumpAndSettle();
+ await shot('restart-uncertain', 'Close');
+ await tester.tap(find.byKey(const Key('restart-again')));
+ await tester.pumpAndSettle();
+ await shot('restart-again', 'Cancel');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await close();
+
+ final forking = ForkConnection();
+ final forkApp = fixture(forking);
+ await open((context) {
+ forkHarness(
+ context,
+ forkApp,
+ 'm',
+ 'a0',
+ 'Improve search and keyboard navigation',
+ engine: 'codex',
+ );
+ });
+ await shot('fork', 'Cancel');
+ await tester.enterText(
+ find.byKey(const ValueKey('fork-task')),
+ 'Explore a simpler search layout.\nKeep the keyboard shortcuts.',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await shot('fork-pending', 'Close');
+ forking.forkReplies.single.completeError(
+ const WsRequestTimeout('agent_fork'),
+ );
+ await tester.pumpAndSettle();
+ await shot('fork-uncertain', 'Close');
+ await close();
+
+ final machineApp = fixture(_PreviewConnection());
+ final machineApi = MachineApi()..deleteReply = Completer<void>();
+ machineApp.api = machineApi;
+ await open(
+ (context) => confirmDeleteMachine(
+ context,
+ machineApp,
+ machineId: 'm',
+ displayName: 'Studio Mac · Development and release builds',
+ ),
+ );
+ await shot('delete-machine', 'Cancel');
+ await tester.tap(find.byKey(const Key('machine-delete-confirm')));
+ await tester.pumpAndSettle();
+ await shot('delete-machine-pending', 'Close');
+ machineApi.deleteReply!.completeError(
+ ApiException('Could not reach your account. Try again.'),
+ );
+ await tester.pumpAndSettle();
+ await shot('delete-machine-error', 'Cancel');
+ await close();
+ debugDisableShadows = oldShadows;
+ },
+ );
+ }
+ }
+
testWidgets(
'renders the box to PNGs',
skip: dir == null,
@@ -593,7 +789,7 @@ void main() {
await tester.pump();
tester
.widget<IconButton>(
- find.widgetWithIcon(IconButton, Icons.more_horiz).first,
+ find.widgetWithIcon(IconButton, AppIcons.ellipsis).first,
)
.focusNode!
.requestFocus();
diff --git a/desktop/test/browser_machine_actions_test.dart b/desktop/test/browser_machine_actions_test.dart
index 95cb2dc85..86a14e763 100644
--- a/desktop/test/browser_machine_actions_test.dart
+++ b/desktop/test/browser_machine_actions_test.dart
@@ -1,9 +1,9 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
@@ -52,7 +52,7 @@ class _Connection extends WsConn {
void main() {
// Initialize the generated icon library before entering the deep widget-build stack in DDC.
- setUpAll(() => expect(LucideIcons.sparkles.codePoint, greaterThan(0)));
+ setUpAll(() => expect(AppIcons.sparkles.codePoint, greaterThan(0)));
late AppNotifier app;
late Map<String, _Connection> connections;
setUp(() {
diff --git a/desktop/test/button_hover_test.dart b/desktop/test/button_hover_test.dart
index 75814a232..54955f430 100644
--- a/desktop/test/button_hover_test.dart
+++ b/desktop/test/button_hover_test.dart
@@ -11,16 +11,21 @@
// 1. the theme declares a hover overlay for each button kind;
// 2. a `styleFrom` at a call site restates it, because `styleFrom` REPLACES
// the theme's style rather than merging with it.
+
import 'dart:math' as math;
import 'dart:ui' show PointerDeviceKind;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart';
+import 'package:harness/shared/theme/color_palette.dart';
import 'package:harness/shared/widgets/app_icon_button.dart';
+import 'support/real_fonts.dart';
+
const _hovered = {WidgetState.hovered};
Color _over(Color base, Color layer) {
@@ -47,6 +52,8 @@ double _contrast(Color a, Color b) {
}
void main() {
+ setUpAll(loadRealFonts);
+
for (final brightness in [Brightness.dark, Brightness.light]) {
group('on ${brightness.name}', () {
late ThemeData theme;
@@ -58,6 +65,74 @@ void main() {
tearDown(() => AppTheme.brightness.value = Brightness.light);
+ testWidgets('capsules keep space around enlarged system text', (
+ tester,
+ ) async {
+ for (final scale in [1.0, 1.7, 2.0]) {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: theme,
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ spacing: 16,
+ children: [
+ TextButton(
+ key: const Key('text-button'),
+ onPressed: () {},
+ child: const Text('Close', key: Key('text-label')),
+ ),
+ OutlinedButton(
+ key: const Key('outlined-button'),
+ onPressed: () {},
+ child: const Text(
+ 'Troubleshooting details',
+ key: Key('outlined-label'),
+ ),
+ ),
+ FilledButton(
+ key: const Key('filled-button'),
+ onPressed: () {},
+ child: const Text(
+ 'Link machine',
+ key: Key('filled-label'),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ for (final kind in ['text', 'outlined', 'filled']) {
+ final button = tester.getRect(find.byKey(Key('$kind-button')));
+ final label = tester.getRect(find.byKey(Key('$kind-label')));
+ expect(
+ label.top - button.top,
+ greaterThanOrEqualTo(6),
+ reason: '$kind at $scale needs space above its label',
+ );
+ expect(
+ button.bottom - label.bottom,
+ greaterThanOrEqualTo(6),
+ reason: '$kind at $scale needs space below its label',
+ );
+ if (scale == 1) {
+ expect(button.height, 32);
+ } else {
+ expect(button.height, greaterThan(32));
+ }
+ }
+ expect(tester.takeException(), isNull);
+ }
+ });
+
test('every button kind declares a hover overlay', () {
final kinds = {
'text': theme.textButtonTheme.style,
@@ -89,6 +164,56 @@ void main() {
);
});
+ test('error text stays readable on ordinary desktop surfaces', () {
+ final originalPalette = AppTheme.palette.value;
+ addTearDown(() => AppTheme.palette.value = originalPalette);
+ for (final palette in HarnessPalette.values) {
+ AppTheme.palette.value = palette;
+ final error = buildAppTheme(brightness: brightness).colorScheme.error;
+ for (final surface in {
+ 'page': AppPalette.windowBg,
+ 'card': AppPalette.cardBg,
+ 'content card': AppCard.base,
+ 'menu': AppMenu.fill,
+ 'field': AppDesktop.field,
+ }.entries) {
+ expect(
+ _contrast(error, surface.value),
+ greaterThanOrEqualTo(4.5),
+ reason: '${palette.name} ${surface.key} must carry error text',
+ );
+ }
+ }
+ });
+
+ test('Increase Contrast strengthens neutral controls and focus', () {
+ final accessible = buildAppTheme(
+ brightness: brightness,
+ highContrast: true,
+ );
+ final surface = accessible.colorScheme.surface;
+ for (final control in [
+ accessible.textButtonTheme.style!,
+ accessible.outlinedButtonTheme.style!,
+ ]) {
+ final rest = control.side!.resolve({})!;
+ final focused = control.side!.resolve({WidgetState.focused})!;
+ expect(rest.width, focused.width);
+ expect(
+ _contrast(_over(surface, rest.color), surface),
+ greaterThanOrEqualTo(3),
+ );
+ expect(
+ _contrast(_over(surface, focused.color), surface),
+ greaterThanOrEqualTo(3),
+ );
+ expect(
+ control.side!.resolve({WidgetState.disabled})!.color.a,
+ lessThan(rest.color.a),
+ );
+ }
+ });
+
// An overlay that exists but cannot be seen is the same bug wearing a
// value. These are measured on the surfaces buttons actually sit on.
test('the hover wash is visible on the surfaces buttons sit on', () {
@@ -120,31 +245,43 @@ void main() {
theme: buildAppTheme(brightness: Brightness.dark),
home: Scaffold(
body: Center(
- child: AppIconButton(icon: Icons.add, onPressed: () => presses++),
+ child: AppIconButton(
+ icon: AppIcons.plus,
+ onPressed: () => presses++,
+ ),
),
),
),
);
final button = find.byType(AppIconButton);
- final fill = find.descendant(
+ final material = find.descendant(
of: button,
- matching: find.byType(AnimatedContainer),
+ matching: find.byType(Material),
);
- Color background() =>
- (tester.widget<AnimatedContainer>(fill).decoration! as BoxDecoration)
- .color!;
- expect(background().a, 0);
+ BorderSide rim() =>
+ (tester.widget<Material>(material).shape! as OutlinedBorder).side;
+ Color? ink() => IconTheme.of(tester.element(find.byType(Icon))).color;
+ final restingInk = ink();
+ final bounds = tester.getRect(button);
+ expect(bounds.size, const Size(32, 32));
+ expect(rim().color.a, 0);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
await mouse.moveTo(tester.getCenter(button));
await tester.pumpAndSettle();
- expect(background().a, greaterThan(0));
+ expect(ink(), isNot(restingInk));
+ expect(rim().color.a, 0, reason: 'hover is distinct from keyboard focus');
await mouse.moveTo(Offset.zero);
await tester.pumpAndSettle();
- expect(background().a, 0);
+ expect(ink(), restingInk);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
- expect(background().a, greaterThan(0));
+ expect(rim().color.a, greaterThan(0));
+ expect(
+ tester.getRect(button),
+ bounds,
+ reason: 'focus must not move controls',
+ );
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
expect(presses, 2);
diff --git a/desktop/test/channel_workspace_test.dart b/desktop/test/channel_workspace_test.dart
index ae97888fe..74159f2ea 100644
--- a/desktop/test/channel_workspace_test.dart
+++ b/desktop/test/channel_workspace_test.dart
@@ -3,83 +3,288 @@ import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/teams/team_controller.dart';
import 'package:harness/teams/team_workspace.dart';
+import 'package:harness/terminal/terminal_font_store.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'support/team_fixture.dart';
import 'support/real_fonts.dart';
void main() {
- setUpAll(loadRealFonts);
- for (final width in [390.0, 1280.0]) {
- testWidgets(
- 'tab channel history at $width has no team setup or human question composer',
- (tester) async {
- tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = Size(width, 820);
- addTearDown(tester.view.reset);
- final calls = <Map<String, dynamic>>[];
- final controller = TeamController(
- channelTabId: 'device',
- request: (p) async {
- calls.add(p);
- return {
- 'team': {
- ...teamFixture(),
- 'name': 'Device',
- 'channel': {'tabId': 'device'},
- },
- };
+ setUpAll(() async {
+ await loadRealFonts();
+ if (Platform.isMacOS &&
+ Platform.environment['CHANNEL_RENDER_DIR'] != null) {
+ final font = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(font))).load();
+ }
+ }
+ await (FontLoader(
+ 'MaterialIcons',
+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
+ });
+
+ Future<void> capture(WidgetTester tester, String name) async {
+ final directory = Platform.environment['CHANNEL_RENDER_DIR'];
+ if (directory == null) return;
+ final oldShadows = debugDisableShadows;
+ try {
+ debugDisableShadows = false;
+ for (final object in tester.allRenderObjects) {
+ object.markNeedsPaint();
+ }
+ await tester.pump();
+ final boundary = tester.renderObject<RenderRepaintBoundary>(
+ find.byKey(const ValueKey('channel-preview')),
+ );
+ await tester.runAsync(() async {
+ final image = await boundary.toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ } finally {
+ debugDisableShadows = oldShadows;
+ for (final object in tester.allRenderObjects) {
+ object.markNeedsPaint();
+ }
+ await tester.pump();
+ }
+ }
+
+ Future<TeamController> show(
+ WidgetTester tester, {
+ required List<Map<String, dynamic>> calls,
+ Map<String, dynamic>? fixture,
+ Brightness brightness = Brightness.dark,
+ Size size = const Size(390, 620),
+ double scale = 1,
+ VoidCallback? onClose,
+ String? error,
+ }) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ final model = TeamController(
+ channelTabId: 'device',
+ request: (payload) async {
+ calls.add(payload);
+ if (error != null) throw TeamRequestError(error);
+ return {
+ 'team': {
+ ...fixture ?? teamFixture(),
+ 'name': 'Device',
+ 'channel': {'tabId': 'device'},
},
- );
- final capture = GlobalKey();
- await tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: Scaffold(
- body: RepaintBoundary(
- key: capture,
- child: TeamWorkspace(
- controller: controller,
- candidates: const [],
- machineName: 'Mac',
- onClose: () {},
- onOpen: (_, _) {},
- ),
- ),
+ };
+ },
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: RepaintBoundary(
+ key: const ValueKey('channel-preview'),
+ child: Scaffold(
+ body: TeamWorkspace(
+ controller: model,
+ candidates: const [],
+ machineName: 'Mac',
+ onClose: onClose ?? () {},
+ onOpen: (_, _) {},
),
),
- );
- await tester.pumpAndSettle();
- expect(find.text('Device'), findsOneWidget);
- expect(find.textContaining('This swarm only'), findsOneWidget);
- expect(find.byKey(const Key('team-question')), findsNothing);
- expect(find.byKey(const Key('team-new')), findsNothing);
- expect(find.text('New question'), findsNothing);
- expect(find.textContaining('Use GET /api/daemons.'), findsOneWidget);
- expect(calls.map((p) => p['action']), everyElement('channel_get'));
- expect(tester.takeException(), isNull);
- final renderDir = Platform.environment['CHANNEL_RENDER_DIR'];
- if (renderDir != null) {
- await tester.runAsync(() async {
- final boundary =
- capture.currentContext!.findRenderObject()!
- as RenderRepaintBoundary;
- final image = await boundary.toImage();
- final bytes = await image.toByteData(
- format: ui.ImageByteFormat.png,
- );
- await Directory(renderDir).create(recursive: true);
- await File('$renderDir/channel-${width.toInt()}.png')
- .writeAsBytes(bytes!.buffer.asUint8List());
- image.dispose();
- });
- }
- await tester.pumpWidget(const SizedBox());
- controller.dispose();
- },
+ ),
+ ),
);
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox());
+ model.dispose();
+ });
+ await tester.pumpAndSettle();
+ return model;
}
+
+ for (final width in [390.0, 1280.0]) {
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets(
+ 'tab channel $width ${brightness.name} $scale keeps the same read-only history',
+ (tester) async {
+ final calls = <Map<String, dynamic>>[];
+ await show(
+ tester,
+ calls: calls,
+ brightness: brightness,
+ size: Size(width, width == 390 && scale == 2 ? 360 : 820),
+ scale: scale,
+ );
+ expect(find.text('Device'), findsOneWidget);
+ expect(find.textContaining('This tab only'), findsOneWidget);
+ expect(find.byKey(const Key('team-question')), findsNothing);
+ expect(find.byKey(const Key('team-new')), findsNothing);
+ expect(find.text('New question'), findsNothing);
+ expect(
+ find.textContaining('Use GET /api/daemons.'),
+ findsOneWidget,
+ );
+ expect(calls.map((p) => p['action']), everyElement('channel_get'));
+ expect(tester.takeException(), isNull);
+ if (width == 390 && scale == 2) {
+ expect(
+ tester
+ .getSize(find.byKey(const ValueKey('team-compact-content')))
+ .height,
+ greaterThan(220),
+ );
+ expect(
+ find.byKey(const ValueKey('team-close')).hitTestable(),
+ findsOneWidget,
+ );
+ }
+ await capture(
+ tester,
+ 'channel-${brightness.name}-${width.toInt()}-$scale',
+ );
+ if (width == 390 || scale == 2) {
+ await tester.ensureVisible(
+ find.textContaining('Use GET /api/daemons.'),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await capture(
+ tester,
+ 'answer-${brightness.name}-${width.toInt()}-$scale',
+ );
+ }
+ },
+ );
+ }
+ }
+ }
+
+ testWidgets(
+ 'page keys scroll the active list and keyboard focus keeps row geometry',
+ (tester) async {
+ final calls = <Map<String, dynamic>>[];
+ final fixture = teamFixture();
+ final exchange = (fixture['exchanges'] as List).first as Map;
+ fixture['exchanges'] = [
+ for (var i = 0; i < 24; i++)
+ {
+ ...exchange,
+ 'id': 'exchange-$i',
+ 'createdAt': i,
+ 'text':
+ 'Review $i: Which endpoint should the frontend use while the owner machine reconnects?',
+ },
+ ];
+ var closed = false;
+ final model = await show(
+ tester,
+ calls: calls,
+ fixture: fixture,
+ size: const Size(390, 540),
+ scale: 1.6,
+ onClose: () => closed = true,
+ );
+ final compact = tester
+ .widget<SingleChildScrollView>(
+ find.byKey(const ValueKey('team-compact-content')),
+ )
+ .controller!;
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
+ await tester.pump();
+ expect(compact.offset, greaterThan(0));
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
+ await tester.pump();
+ expect(compact.offset, 0);
+
+ final row = find.byKey(const ValueKey('team-exchange-exchange-23'));
+ await tester.ensureVisible(row);
+ await tester.pumpAndSettle();
+ final before = tester.getRect(row);
+ await tester.tap(row);
+ await tester.pumpAndSettle();
+ expect(model.selectedExchange, 'exchange-23');
+ expect(tester.getRect(row), before);
+ final button = find.descendant(
+ of: row,
+ matching: find.byType(TextButton),
+ );
+ Focus.of(
+ tester.element(
+ find.descendant(of: button, matching: find.byType(Text)).first,
+ ),
+ ).requestFocus();
+ await tester.pump();
+ final style = tester.widget<TextButton>(button).style!;
+ expect(
+ style.side!.resolve({WidgetState.focused})!.color,
+ DesktopChrome.focusRing,
+ );
+ expect(
+ style.backgroundColor!.resolve({WidgetState.focused}),
+ DesktopChrome.selection,
+ );
+ final list = tester
+ .widget<ListView>(find.byKey(const ValueKey('team-exchanges')))
+ .controller!;
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
+ await tester.pump();
+ expect(list.offset, greaterThan(0));
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
+ await tester.pump();
+ expect(list.offset, 0);
+
+ final originalFont = terminalFontStore.value;
+ addTearDown(() => terminalFontStore.value = originalFont);
+ terminalFontStore.value = originalFont.copyWith(fontSize: 26);
+ await tester.pumpAndSettle();
+ expect(tester.getRect(row), before);
+ expect(calls.map((p) => p['action']), everyElement('channel_get'));
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ expect(closed, isTrue);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'a long failed read remains readable without enabling team actions',
+ (tester) async {
+ final calls = <Map<String, dynamic>>[];
+ await show(
+ tester,
+ calls: calls,
+ size: const Size(390, 360),
+ scale: 2,
+ error: 'The owner is unavailable. ' * 20,
+ );
+ expect(find.text('No teams yet. Start with two sessions.'), findsNothing);
+ final retry = find.widgetWithText(TextButton, 'Retry reading swarm');
+ await tester.ensureVisible(retry);
+ await tester.pumpAndSettle();
+ expect(retry.hitTestable(), findsOneWidget);
+ expect(calls.map((p) => p['action']), everyElement('channel_get'));
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'unavailable-dark-2.0');
+ },
+ );
}
diff --git a/desktop/test/clone_repository_dialog_test.dart b/desktop/test/clone_repository_dialog_test.dart
index eded67d1f..e3583f647 100644
--- a/desktop/test/clone_repository_dialog_test.dart
+++ b/desktop/test/clone_repository_dialog_test.dart
@@ -77,6 +77,62 @@ Future<void> _openClone(
}
void main() {
+ testWidgets('clone URL takes keyboard focus and owns composing Escape', (
+ tester,
+ ) async {
+ var closed = false;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => TextButton(
+ onPressed: () async {
+ await showCloneRepositoryDialog(context);
+ closed = true;
+ },
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ final input = find.byKey(const ValueKey('clone-repository-url'));
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ const value = TextEditingValue(
+ text: 'owner/repository',
+ selection: TextSelection.collapsed(offset: 16),
+ composing: TextRange(start: 6, end: 16),
+ );
+ tester.testTextInput.updateEditingValue(value);
+ await tester.pump();
+ expect(tester.widget<TextField>(input).controller!.value, value);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(closed, isFalse);
+ expect(tester.widget<TextField>(input).controller!.value, value);
+ expect(
+ tester.widget<EditableText>(find.byType(EditableText)).focusNode.hasFocus,
+ isTrue,
+ );
+ tester.testTextInput.updateEditingValue(
+ value.copyWith(composing: TextRange.empty),
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(closed, isTrue);
+ expect(find.byType(CloneRepositoryDialog), findsNothing);
+ closed = false;
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ tester.testTextInput.updateEditingValue(value);
+ await tester.pump();
+ expect(tester.widget<TextField>(input).controller!.value, value);
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(closed, isTrue);
+ expect(find.byType(CloneRepositoryDialog), findsNothing);
+ });
+
testWidgets('clone failure is visible with large text and keyboard retry', (
tester,
) async {
diff --git a/desktop/test/color_palette_test.dart b/desktop/test/color_palette_test.dart
index bb9e894ff..c1ec2cbd9 100644
--- a/desktop/test/color_palette_test.dart
+++ b/desktop/test/color_palette_test.dart
@@ -58,9 +58,12 @@ void main() {
});
test('palette text is readable and terminal themes are cached', () {
- double contrast(Color foreground, Color background) =>
- (foreground.computeLuminance() + .05) /
- (background.computeLuminance() + .05);
+ double contrast(Color foreground, Color background) {
+ final a = foreground.computeLuminance() + .05;
+ final b = background.computeLuminance() + .05;
+ return a > b ? a / b : b / a;
+ }
+
for (final palette in HarnessPalette.values) {
expect(
contrast(palette.foreground, palette.background),
@@ -148,10 +151,7 @@ void main() {
for (final palette in [HarnessPalette.paper, HarnessPalette.mist]) {
expect(palette.isDark, isFalse, reason: palette.name);
expect(palette.nativeColors['dark'], 0, reason: palette.name);
- final terminal = terminalThemeFor(
- palette,
- TerminalThemeChoice.matchApp,
- );
+ final terminal = terminalThemeFor(palette, TerminalThemeChoice.matchApp);
expect(terminal.foreground, palette.foreground);
// The light ramp, not the dark one's pale yellow and white.
expect(terminal.yellow, lightTerminalTheme.yellow);
@@ -164,11 +164,22 @@ void main() {
// Every ANSI slot is somebody's output text on this ground.
for (final slot in [
- terminal.black, terminal.red, terminal.green, terminal.yellow,
- terminal.blue, terminal.magenta, terminal.cyan, terminal.white,
- terminal.brightBlack, terminal.brightRed, terminal.brightGreen,
- terminal.brightYellow, terminal.brightBlue, terminal.brightMagenta,
- terminal.brightCyan, terminal.brightWhite,
+ terminal.black,
+ terminal.red,
+ terminal.green,
+ terminal.yellow,
+ terminal.blue,
+ terminal.magenta,
+ terminal.cyan,
+ terminal.white,
+ terminal.brightBlack,
+ terminal.brightRed,
+ terminal.brightGreen,
+ terminal.brightYellow,
+ terminal.brightBlue,
+ terminal.brightMagenta,
+ terminal.brightCyan,
+ terminal.brightWhite,
]) {
expect(
contrast(slot, palette.background),
@@ -202,8 +213,10 @@ void main() {
grid.AppTheme.brightness.value = Brightness.dark;
expect(HarnessPalette.graphite.nativeColors['dark'], 1);
expect(
- terminalThemeFor(HarnessPalette.graphite, TerminalThemeChoice.matchApp)
- .yellow,
+ terminalThemeFor(
+ HarnessPalette.graphite,
+ TerminalThemeChoice.matchApp,
+ ).yellow,
darkTerminalTheme.yellow,
);
});
@@ -234,9 +247,7 @@ void main() {
await tester.ensureVisible(find.byKey(const ValueKey('palette-forest')));
expect(
tester
- .getSemantics(
- find.bySemanticsLabel('Forest palette'),
- )
+ .getSemantics(find.bySemanticsLabel('Forest palette'))
.getSemanticsData()
.hasAction(SemanticsAction.tap),
isTrue,
diff --git a/desktop/test/command_dock_interaction_test.dart b/desktop/test/command_dock_interaction_test.dart
index 236acbec4..f91611639 100644
--- a/desktop/test/command_dock_interaction_test.dart
+++ b/desktop/test/command_dock_interaction_test.dart
@@ -9,7 +9,7 @@ import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/widgets/engine_identity.dart';
import 'package:harness/widgets/search_result_text.dart';
-import 'package:harness/terminal/terminal_text.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_switcher.dart';
@@ -97,7 +97,15 @@ void main() {
final row = find.byKey(ValueKey(agentDestinationId('m', 'a0')));
expect(
find.descendant(of: row, matching: find.byType(EngineMark)),
- findsNothing,
+ findsOneWidget,
+ );
+ expect(
+ tester
+ .widget<EngineMark>(
+ find.descendant(of: row, matching: find.byType(EngineMark)),
+ )
+ .engine,
+ previous.engine,
);
expect(
find.descendant(of: row, matching: find.text('33m')),
@@ -117,7 +125,13 @@ void main() {
startsWith('Last active '),
);
expect(
- find.descendant(of: row, matching: find.byType(SearchResultText)),
+ find.descendant(
+ of: row,
+ matching: find.byWidgetPredicate(
+ (widget) =>
+ widget is SearchResultText && widget.text == previous.name,
+ ),
+ ),
findsOneWidget,
);
await tester.enterText(
@@ -128,15 +142,15 @@ void main() {
final detail = tester.widget<Text>(
find.descendant(
of: find.byKey(const ValueKey('swarm-search-preview')),
- matching: find.text('M2:openharness (feature/login-redirect)'),
+ matching: find.text('M2 · openharness · feature/login-redirect'),
),
);
for (final label in ['M2', 'openharness', 'feature/login-redirect']) {
expect(detail.data, contains(label));
}
- expect(detail.style!.fontFamily, terminalFontStore.value.fontFamily);
- expect(detail.style!.fontSize, terminalFontStore.size);
- expect(detail.style!.height, terminalFontStore.value.height);
+ expect(detail.style!.fontFamily, grid.AppType.monoFamily);
+ expect(detail.style!.fontSize, 11);
+ expect(detail.style!.height, grid.AppType.monoMeta().height);
final create = find.byKey(const ValueKey(kSwarmCreateRowId));
expect(create, findsNothing);
expect(find.text('Harness:'), findsNothing);
@@ -179,6 +193,11 @@ void main() {
expect(search.selected, isNull);
expect(search.rows.any((row) => row.isCreate), isFalse);
await key(tester, LogicalKeyboardKey.tab);
+ expect(search.selected, isNull);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isFalse);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowDown);
expect(search.selected, search.rows.first);
expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
await tester.enterText(input, 'nothing-like-this');
diff --git a/desktop/test/command_picker_rendering_test.dart b/desktop/test/command_picker_rendering_test.dart
index 8bc62fa5d..b324a4320 100644
--- a/desktop/test/command_picker_rendering_test.dart
+++ b/desktop/test/command_picker_rendering_test.dart
@@ -16,6 +16,7 @@ import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/widgets/search_result_text.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'package:harness/widgets/swarm_switcher.dart';
import 'package:xterm/xterm.dart';
@@ -66,7 +67,7 @@ void main() {
);
testWidgets(
- 'commands retain the Cmd-P terminal grid, editor and live appearance',
+ 'commands retain the native palette, editor and live appearance',
(tester) async {
final originalFont = terminalFontStore.value;
final originalPalette = grid.AppTheme.palette.value;
@@ -102,8 +103,10 @@ void main() {
.search;
expect(search.isCommandMode, isTrue);
expect(search.hasPreview, isTrue);
- expect(tester.getRect(_panel), bounds);
- expect(tester.getRect(_input), inputBounds);
+ expect(tester.getRect(_panel).topLeft, bounds.topLeft);
+ expect(tester.getRect(_panel).width, bounds.width);
+ expect(tester.getRect(_input).topLeft, inputBounds.topLeft);
+ expect(tester.getRect(_input).height, inputBounds.height);
expect(
tester.state<EditableTextState>(
find.descendant(of: _input, matching: find.byType(EditableText)),
@@ -114,11 +117,11 @@ void main() {
expect(find.byType(SwarmSearchCount), findsNothing);
expect(
find.descendant(of: _panel, matching: find.byType(Icon)),
- findsNothing,
+ findsWidgets,
);
expect(
find.descendant(of: _panel, matching: find.byType(ListTile)),
- findsNothing,
+ findsWidgets,
);
await tester.enterText(_input, '> new harness');
@@ -130,46 +133,40 @@ void main() {
void checkAppearance() {
final field = tester.widget<TextField>(_input);
final pane = tester.widget<TerminalView>(find.byType(TerminalView));
- final cell = terminalCellSizeOf(tester.element(_input));
- final line = find.byKey(ValueKey('swarm-search-line:${selected.id}'));
- expect(tester.getSize(line).height, closeTo(cell.height, .01));
- expect(tester.widget<Container>(line).color, pane.theme.selection);
- expect(tester.widget<Material>(_panel).color, pane.theme.background);
+ final line = find.byKey(ValueKey(selected.id));
+ expect(tester.getSize(line).height, greaterThanOrEqualTo(28));
+ final surface = find
+ .descendant(of: _panel, matching: find.byType(Material))
+ .first;
+ expect(tester.widget<Material>(surface).color, DesktopChrome.surface);
expect(field.cursorWidth, 2);
- expect(field.cursorColor, pane.theme.cursor);
+ expect(field.cursorColor, DesktopChrome.foreground);
final title = find.descendant(
of: line,
matching: find.byType(SearchResultText),
);
expect(
- tester.getTopLeft(title).dx,
- closeTo(tester.getTopLeft(_input).dx, .01),
+ tester.getRect(_panel).contains(tester.getCenter(title)),
+ isTrue,
);
- final shortcut = find.byKey(
- ValueKey('swarm-search-shortcut:${selected.id}'),
+ final shortcut = find.descendant(
+ of: line,
+ matching: find.text(selected.shortcut!),
);
expect(tester.widget<Text>(shortcut).data, selected.shortcut);
final previewText = tester.widgetList<Text>(
find.descendant(of: _preview, matching: find.byType(Text)),
);
- expect(previewText.map((text) => text.data), [
- selected.title,
- selected.detail,
- selected.shortcut,
- ]);
+ expect(
+ previewText.map((text) => text.data),
+ containsAll([selected.title, selected.detail, selected.shortcut]),
+ );
for (final style in [
field.style!,
tester.widget<SearchResultText>(title).style,
- tester.widget<Text>(shortcut).style!,
- ...previewText.map((text) => text.style!),
]) {
- expect(style.fontFamily, pane.textStyle.fontFamily);
- expect(style.fontFamilyFallback, pane.textStyle.fontFamilyFallback);
- expect(style.fontSize, pane.textStyle.fontSize);
- expect(style.fontWeight, pane.textStyle.toTextStyle().fontWeight);
- expect(style.height, pane.textStyle.height);
- expect(style.letterSpacing, 0);
- expect(style.wordSpacing, 0);
+ expect(style.fontFamily, DesktopChrome.text().fontFamily);
+ expect(style.fontSize, inInclusiveRange(13, 17));
}
expect(field.controller, same(controller));
expect(controller.value, editing);
@@ -213,7 +210,7 @@ void main() {
expect(tester.getRect(_panel), bounds);
expect(controller.text, isEmpty);
expect(
- find.byKey(const ValueKey('swarm-search-type-hints')),
+ find.byKey(const ValueKey('search-category-Machines')),
findsOneWidget,
);
await key(tester, LogicalKeyboardKey.escape);
@@ -226,11 +223,8 @@ void main() {
shift: true,
);
expect(tester.widget<TextField>(_input).controller!.text, '>');
- expect(
- tester.widget<SwarmSearchResults>(find.byType(SwarmSearchResults)).bios,
- isTrue,
- );
- expect(tester.getRect(_panel), bounds);
+ expect(tester.getRect(_panel).topLeft, bounds.topLeft);
+ expect(tester.getRect(_panel).width, bounds.width);
expect(frames, isEmpty);
await tester.pumpWidget(const SizedBox());
},
@@ -241,7 +235,7 @@ void main() {
);
for (final size in [const Size(1280, 800), const Size(400, 600)]) {
- testWidgets('commands page and preview on the terminal grid at $size', (
+ testWidgets('commands page and preview fit the native palette at $size', (
tester,
) async {
final originalFont = terminalFontStore.value;
@@ -274,6 +268,8 @@ void main() {
expect(search.cursor, first);
await key(tester, LogicalKeyboardKey.tab);
expect(search.cursor, first);
+ expect(field.focusNode!.hasFocus, isFalse);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
expect(field.focusNode!.hasFocus, isTrue);
expect(
find.byKey(const ValueKey('swarm-search-resource-actions')),
diff --git a/desktop/test/connection_review_render_test.dart b/desktop/test/connection_review_render_test.dart
new file mode 100644
index 000000000..e1a285ad3
--- /dev/null
+++ b/desktop/test/connection_review_render_test.dart
@@ -0,0 +1,242 @@
+// Optional PNGs: HARNESS_CONNECTION_CAPTURE_DIR=/private/tmp/connection-review
+// flutter test test/connection_review_render_test.dart
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_link.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/add_phone_dialog.dart';
+import 'package:harness/widgets/link_machine_dialog.dart';
+import 'package:harness/widgets/link_machine_screen.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/password_cli.dart';
+
+class _ReviewCli extends PasswordCli {
+ String connectError = "Incorrect password. Try again.";
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) async => CliLinkConnectResult(error: connectError);
+}
+
+void main() {
+ setUpAll(loadPreviewFonts);
+ for (final brightness in Brightness.values) {
+ for (final (size, scale) in [
+ (const Size(720, 560), 1.0),
+ (const Size(720, 560), 2.0),
+ (const Size(480, 360), 1.6),
+ ]) {
+ testWidgets('connection forms ${brightness.name}, $size, $scale text', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ final oldShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ addTearDown(() => debugDisableShadows = oldShadows);
+ final cli = _ReviewCli();
+ final multilineError = List.generate(
+ 12,
+ (index) =>
+ 'Connection diagnostic $index: could not complete the request.',
+ ).join('\n');
+ if (size.width == 480) cli.connectError = multilineError;
+ final app =
+ AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLink: cli,
+ )
+ ..status = AppStatus.authenticated
+ ..signedIn = true
+ ..currentUser = const CurrentUserProfile(
+ email: '[email protected]',
+ );
+ addTearDown(app.dispose);
+ const local = Machine(
+ machineId: 'local',
+ name: 'This Mac',
+ authMode: MachineAuthMode.remote,
+ );
+ const remote = Machine(
+ machineId: 'remote',
+ name: 'Design Studio',
+ authMode: MachineAuthMode.remote,
+ );
+ app.machines = [local, remote];
+ app.machineStates['local'] = MachineState(local)..localOnly = true;
+ app.machineStates['remote'] = MachineState(remote)..needsLink = true;
+ final boundary = GlobalKey();
+ late BuildContext opener;
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(scale),
+ disableAnimations: true,
+ ),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) {
+ opener = context;
+ return const SizedBox.expand();
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+
+ Future<void> capture(String name) async {
+ expect(tester.takeException(), isNull);
+ final directory =
+ Platform.environment['HARNESS_CONNECTION_CAPTURE_DIR'];
+ if (directory == null) return;
+ await tester.runAsync(() async {
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final picture = await render.toImage();
+ try {
+ final bytes = await picture.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name-${brightness.name}-$scale.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ } finally {
+ picture.dispose();
+ }
+ });
+ }
+
+ if (size.width > 480) {
+ unawaited(
+ showAddPhoneDialog(
+ opener,
+ app,
+ pair: (_, cancel) async {
+ await cancel.whenCancel;
+ return const PhonePairAnswer.failed('CANCELLED');
+ },
+ signInCode: () async =>
+ (code: 'synthetic-code', ttl: const Duration(seconds: 90)),
+ listDevices: () async => [
+ PairedDevice(
+ fingerprint: 'FIXTURE',
+ label: 'Design team iPhone',
+ pairedAt: DateTime(2026, 9, 28),
+ online: true,
+ ),
+ ],
+ removeDevice: (_) async => false,
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Done').hitTestable(), findsOneWidget);
+ expect(find.byType(PhonePairQr).hitTestable(), findsOneWidget);
+ await capture('add-phone');
+ await tester.ensureVisible(find.text('Remove'));
+ await tester.tap(find.text('Remove'));
+ await tester.pumpAndSettle();
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('add-phone-status')),
+ );
+ expect(
+ find.text("Couldn't remove Design team iPhone. Try again."),
+ findsOneWidget,
+ );
+ await capture('add-phone-error');
+ await tester.tap(find.text('Done'));
+ await tester.pumpAndSettle();
+ }
+
+ unawaited(showLinkMachineDialog(opener, app));
+ await tester.pumpAndSettle();
+ expect(find.text('Close').hitTestable(), findsOneWidget);
+ await capture('set-password');
+ await tester.enterText(
+ find.byKey(const Key('remote-password-field')),
+ 'fixture',
+ );
+ await tester.enterText(
+ find.byKey(const Key('remote-password-confirm-field')),
+ 'different',
+ );
+ await tester.ensureVisible(
+ find.byKey(const Key('remote-password-set-button')),
+ );
+ await tester.tap(find.byKey(const Key('remote-password-set-button')));
+ await tester.pumpAndSettle();
+ expect(cli.passwords, isEmpty);
+ expect(
+ find.text('Passwords do not match').hitTestable(),
+ findsOneWidget,
+ );
+ await capture('set-password-error');
+ if (size.width == 480) {
+ cli.setResult = RemotePasswordSetResult(error: multilineError);
+ await tester.enterText(
+ find.byKey(const Key('remote-password-confirm-field')),
+ 'fixture',
+ );
+ await tester.tap(find.byKey(const Key('remote-password-set-button')));
+ await tester.pumpAndSettle();
+ expect(find.text('Close').hitTestable(), findsOneWidget);
+ expect(
+ find.byKey(const Key('remote-password-set-button')).hitTestable(),
+ findsOneWidget,
+ );
+ expect(find.text(multilineError), findsOneWidget);
+ await capture('set-password-long-error');
+ }
+
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+
+ unawaited(showLinkMachineScreenDialog(opener, app, 'remote'));
+ await tester.pumpAndSettle();
+ expect(find.text('Close').hitTestable(), findsOneWidget);
+ expect(find.text('Link machine').hitTestable(), findsOneWidget);
+ await capture('link-machine');
+ await tester.enterText(
+ find.byKey(const Key('remote-password-connect-field')),
+ 'fixture',
+ );
+ await tester.tap(find.text('Link machine'));
+ await tester.pumpAndSettle();
+ expect(find.text(cli.connectError).hitTestable(), findsOneWidget);
+ await capture('link-machine-error');
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+ await tester.pumpWidget(const SizedBox());
+ debugDisableShadows = oldShadows;
+ });
+ }
+ }
+}
diff --git a/desktop/test/daemon_off_test.dart b/desktop/test/daemon_off_test.dart
index 05749ae09..90d1cfbc1 100644
--- a/desktop/test/daemon_off_test.dart
+++ b/desktop/test/daemon_off_test.dart
@@ -5,7 +5,6 @@
// no habits, no keys taken, no commands, no easter row, no notices.
import 'dart:async';
import 'dart:convert';
-import 'dart:io';
import 'dart:math';
import 'package:flutter/gestures.dart';
@@ -216,71 +215,70 @@ void main() {
},
);
- testWidgets(
- 'illustrated Tim lives at the far right and hover preserves focus',
- (tester) async {
- await mount(tester, on: true);
- expect(
- find.ancestor(
- of: slot,
- matching: find.byKey(const ValueKey('workspace-tab-bar')),
- ),
- findsOneWidget,
- );
- expect(
- find.ancestor(
- of: slot,
- matching: find.byKey(const ValueKey('workspace-status-bar')),
- ),
- findsNothing,
- );
- final store = find.byKey(const ValueKey('swarm-store-button'));
- expect(
- tester.getRect(slot).left,
- greaterThanOrEqualTo(tester.getRect(store).right),
- );
- expect(tester.getSize(slot).width, 44);
- final focus = FocusManager.instance.primaryFocus;
- final before = zoo.zoo.toJson();
- final remoteBefore = remote.zoo.toJson();
- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- await mouse.addPointer(location: const Offset(2, 400));
- await mouse.moveTo(tester.getCenter(slot));
- await tester.pump(const Duration(milliseconds: 250));
- final preview = find.byKey(const ValueKey('daemon-hover-preview'));
- expect(preview, findsOneWidget);
- expect(FocusManager.instance.primaryFocus, same(focus));
- expect(
- tester
- .widget<DaemonIllustration>(
- find.descendant(
- of: preview,
- matching: find.byType(DaemonIllustration),
- ),
- )
- .size,
- 350,
- );
- expect(
- zoo.zoo.toJson(),
- before,
- reason: 'looking never hatches or changes progress',
- );
- await mouse.moveTo(const Offset(2, 400));
- await tester.pump();
- expect(preview, findsNothing);
- await mouse.moveTo(tester.getCenter(slot));
- await tester.pump(const Duration(milliseconds: 250));
- expect(preview, findsOneWidget);
- await experiments.set(feature, false);
- await tester.pump();
- expect(preview, findsNothing);
- expect(slot, findsNothing);
- expect(remote.zoo.toJson(), remoteBefore);
- await mouse.removePointer();
- await unmount(tester);
- },
- );
+ testWidgets('illustrated Tim lives in the footer and hover preserves focus', (
+ tester,
+ ) async {
+ await mount(tester, on: true);
+ expect(
+ find.ancestor(
+ of: slot,
+ matching: find.byKey(const ValueKey('workspace-status-bar')),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.ancestor(
+ of: slot,
+ matching: find.byKey(const ValueKey('workspace-tab-bar')),
+ ),
+ findsNothing,
+ );
+ final footer = find.byKey(const ValueKey('workspace-status-bar'));
+ expect(
+ tester.getRect(slot).left,
+ greaterThanOrEqualTo(tester.getRect(footer).left),
+ );
+ expect(tester.getSize(slot).width, 44);
+ final focus = FocusManager.instance.primaryFocus;
+ final before = zoo.zoo.toJson();
+ final remoteBefore = remote.zoo.toJson();
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: const Offset(2, 400));
+ await mouse.moveTo(tester.getCenter(slot));
+ await tester.pump(const Duration(milliseconds: 250));
+ final preview = find.byKey(const ValueKey('daemon-hover-preview'));
+ expect(preview, findsOneWidget);
+ expect(FocusManager.instance.primaryFocus, same(focus));
+ expect(
+ tester
+ .widget<DaemonIllustration>(
+ find.descendant(
+ of: preview,
+ matching: find.byType(DaemonIllustration),
+ ),
+ )
+ .size,
+ 350,
+ );
+ expect(
+ zoo.zoo.toJson(),
+ before,
+ reason: 'looking never hatches or changes progress',
+ );
+ await mouse.moveTo(const Offset(2, 400));
+ await tester.pump();
+ expect(preview, findsNothing);
+ await mouse.moveTo(tester.getCenter(slot));
+ await tester.pump(const Duration(milliseconds: 250));
+ expect(preview, findsOneWidget);
+ await experiments.set(feature, false);
+ await tester.pump();
+ expect(preview, findsNothing);
+ expect(slot, findsNothing);
+ expect(remote.zoo.toJson(), remoteBefore);
+ await mouse.removePointer();
+ await unmount(tester);
+ });
for (final native in [false, true]) {
for (final shown in [false, true]) {
@@ -802,22 +800,22 @@ void main() {
},
);
- testWidgets('a 404 is off: no slot and the bar from before daemons, at '
+ testWidgets('a 404 is off: no slot and the disabled-feature bar, at '
'every width', (tester) async {
seedStatusBarWorkspace(app);
- // This historical layout includes Share; keep its independent experiment
- // enabled while checking that daemons reserve no space.
+ // Compare the same workspace with the creature feature disabled. The
+ // independent Share control may change appearance without granting an
+ // absent daemon any space in either bar.
await experiments.set(ExperimentalFeature.shareButton, true);
- await mount(tester);
- await tester.pump();
+ await mount(tester, enabled: false);
+ expect(remote.fetches, 0);
+ expect(slot, findsNothing);
+ final before = await measureStatusBar(tester);
+ await setCreature(tester, true);
expect(remote.fetches, 1);
expect(zoo.daemons, DaemonsSwitch.off);
expect(slot, findsNothing);
- final before = jsonDecode(
- File('test/fixtures/status_bar_before_daemons.json').readAsStringSync(),
- );
- final now = await measureStatusBar(tester);
- expect(jsonDecode(jsonEncode(now)), before);
+ expect(await measureStatusBar(tester), before);
expect(slot, findsNothing);
await unmount(tester);
});
@@ -827,17 +825,25 @@ void main() {
seedStatusBarWorkspace(app);
await experiments.set(ExperimentalFeature.shareButton, true);
final gate = Completer<void>();
- await mount(tester, on: true, gate: gate);
+ await mount(tester, on: true, enabled: false, gate: gate);
+ expect(remote.fetches, 0);
+ expect(slot, findsNothing);
+ final before = await measureStatusBar(tester);
+ await setCreature(tester, true);
+ expect(remote.fetches, 1);
expect(zoo.daemons, DaemonsSwitch.unknown);
- final before = jsonDecode(
- File('test/fixtures/status_bar_before_daemons.json').readAsStringSync(),
- );
- expect(jsonDecode(jsonEncode(await measureStatusBar(tester))), before);
+ expect(slot, findsNothing);
+ expect(await measureStatusBar(tester), before);
gate.complete();
await tester.pump();
await tester.pump();
expect(zoo.daemons, DaemonsSwitch.on);
expect(slot, findsOneWidget, reason: 'on (200): as today');
+ expect(
+ await measureStatusBar(tester),
+ isNot(before),
+ reason: 'a present daemon is the state that may take bar space',
+ );
await unmount(tester);
});
diff --git a/desktop/test/daemon_review_render_test.dart b/desktop/test/daemon_review_render_test.dart
index 64837b54a..61bee0dec 100644
--- a/desktop/test/daemon_review_render_test.dart
+++ b/desktop/test/daemon_review_render_test.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
// Real-font review captures of the daemon: the status slot in every mood and
// nest stage (with a shiny `*`, alerts and replies), the hatch
// reveal's frames and rarity tells (drop init's plates at the reveal size),
@@ -146,6 +147,9 @@ Future<DaemonFace> _face(WidgetTester tester, Zoo zoo) async {
}
Future<void> _fonts() async {
+ await (FontLoader(
+ 'MaterialIcons',
+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
if (Platform.isMacOS) {
for (final (family, path) in [
('.AppleSystemUIFont', '/System/Library/Fonts/SFNS.ttf'),
@@ -170,6 +174,8 @@ Future<void> _capture(
Widget Function(BuildContext context) build, {
Brightness brightness = Brightness.dark,
Duration settle = const Duration(milliseconds: 50),
+ double textScale = 1,
+ bool highContrast = false,
Future<void> Function()? act,
}) async {
tester.view.devicePixelRatio = 1;
@@ -202,7 +208,11 @@ Future<void> _capture(
debugShowCheckedModeBanner: false,
theme: grid.buildAppTheme(brightness: brightness),
builder: (context, child) => MediaQuery(
- data: MediaQuery.of(context).copyWith(disableAnimations: true),
+ data: MediaQuery.of(context).copyWith(
+ disableAnimations: true,
+ highContrast: highContrast,
+ textScaler: TextScaler.linear(textScale),
+ ),
child: TerminalFontScope(child: child!),
),
home: Builder(
@@ -224,11 +234,27 @@ Future<void> _capture(
// for the displayed providers so a passing capture cannot hide an empty
// portrait while the small, already-cached slot happens to be ready.
final images = find.byType(Image).evaluate().toList();
- await tester.runAsync(() async {
- for (final element in images) {
- await precacheImage((element.widget as Image).image, element);
+ for (final element in images) {
+ var decoded = false;
+ Object? imageError;
+ unawaited(
+ precacheImage(
+ (element.widget as Image).image,
+ element,
+ onError: (error, _) => imageError = error,
+ ).then((_) => decoded = true),
+ );
+ // A provider already resolving in the fake zone needs pumps between its
+ // async asset reads. Awaiting that stream only in runAsync deadlocks it.
+ for (var attempt = 0; attempt < 500 && !decoded; attempt++) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 10)),
+ );
+ await tester.pump();
}
- });
+ expect(decoded, isTrue, reason: '$name: image decoding completed');
+ expect(imageError, isNull, reason: '$name: image decoding succeeded');
+ }
await tester.pump();
expect(tester.takeException(), isNull, reason: name);
final output = _output;
@@ -871,7 +897,7 @@ void main() {
child: Padding(
padding: const EdgeInsets.all(10),
child: SizedBox(
- width: terminalCellSizeOf(context).width * 46,
+ width: 480,
child: DaemonPanel(
face: face,
onClose: () {},
@@ -1324,7 +1350,7 @@ void main() {
child: Padding(
padding: const EdgeInsets.all(10),
child: SizedBox(
- width: terminalCellSizeOf(context).width * 46,
+ width: 480,
child: DaemonPanel(
face: face,
brain: brain,
@@ -1393,6 +1419,127 @@ void main() {
await tester.pump();
}
+ // Desktop chrome around the exact same fake zoo, brain and reveal state.
+ // Large text remains independent of the terminal art, and action details
+ // still have to fit wholly in the viewport before approval keys arm.
+ for (final (name, tab, brightness, size, scale) in [
+ ('desktop-now-dark', 'now', Brightness.dark, const Size(500, 760), 1.0),
+ ('desktop-now-light', 'now', Brightness.light, const Size(500, 760), 1.0),
+ ('desktop-now-scaled', 'now', Brightness.dark, const Size(360, 640), 1.7),
+ ('desktop-zoo-scaled', 'zoo', Brightness.light, const Size(360, 640), 1.7),
+ (
+ 'desktop-settings-scaled',
+ 'settings',
+ Brightness.light,
+ const Size(360, 640),
+ 1.7,
+ ),
+ (
+ 'desktop-lessons-scaled',
+ 'lessons',
+ Brightness.dark,
+ const Size(360, 640),
+ 1.7,
+ ),
+ ]) {
+ testWidgets('desktop daemon: $name', (tester) async {
+ final (face, brain) = await pairPanel(tester, tab);
+ await _capture(
+ tester,
+ name,
+ size,
+ brightness: brightness,
+ textScale: scale,
+ highContrast: scale > 1,
+ act: () async {
+ if (tab == 'now') {
+ final row = find.byKey(const ValueKey('daemon-row-ask:ask:7'));
+ await Scrollable.ensureVisible(tester.element(row), alignment: .05);
+ await tester.pump();
+ }
+ await settle(tester);
+ },
+ (context) => panelFor(context, face, brain),
+ );
+ final heading = tester.widget<Text>(
+ find.byKey(const ValueKey('daemon-panel-title')),
+ );
+ expect(heading.style!.fontFamily, grid.AppType.sansFamily);
+ if (tab == 'now') {
+ expect(
+ brain.wasShown('ask:7'),
+ isTrue,
+ reason: 'whole proposal and bounded detail can fit at this size',
+ );
+ expect(
+ find.byKey(const ValueKey('daemon-key-ask:ask:7-y')),
+ findsOneWidget,
+ );
+ final detail = tester.widget<DaemonDetailBox>(
+ find.byKey(const ValueKey('daemon-detail-ask:ask:7')),
+ );
+ expect(detail.text, contains('first prompt: run the migrations'));
+ expect(detail.style.fontFamily, terminalFontFamily);
+ }
+ await tester.pumpWidget(const SizedBox());
+ face.sync(const DaemonWatch());
+ await tester.pump(const Duration(minutes: 3));
+ });
+ }
+
+ for (final (name, stage, brightness) in [
+ ('desktop-hatch-name-dark', HatchStage.name, Brightness.dark),
+ ('desktop-hatch-name-light', HatchStage.name, Brightness.light),
+ ('desktop-hatch-consent-scaled', HatchStage.consent, Brightness.light),
+ ('desktop-hatch-suggest-scaled', HatchStage.suggest, Brightness.dark),
+ ]) {
+ testWidgets('desktop daemon: $name', (tester) async {
+ await _capture(
+ tester,
+ name,
+ const Size(360, 640),
+ brightness: brightness,
+ textScale: 1.7,
+ highContrast: true,
+ act: stage == HatchStage.name
+ ? () async {
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('daemon-hatch-name')),
+ );
+ await tester.pump();
+ }
+ : null,
+ (context) => Padding(
+ padding: const EdgeInsets.all(10),
+ child: DaemonHatchReveal(
+ roster: _roster,
+ egg: egg,
+ result: Future.value(
+ const ZooHatch(eggId: 'egg1', daemonId: 'tim', shiny: false),
+ ),
+ zoo: () => _paired('tim'),
+ onClose: () {},
+ still: HatchFrame(stage: stage, bannerRows: 5),
+ reduceMotion: true,
+ ),
+ ),
+ );
+ if (stage == HatchStage.name) {
+ final input = find.byKey(const ValueKey('daemon-hatch-name'));
+ await tester.ensureVisible(input);
+ await tester.tap(input);
+ await tester.enterText(input, 'Scout');
+ expect(tester.widget<TextField>(input).controller!.text, 'Scout');
+ expect(
+ tester.widget<TextField>(input).style!.fontFamily,
+ grid.AppType.sansFamily,
+ );
+ expect(tester.takeException(), isNull);
+ }
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
// ── round 4: consent, trust, and a panel you can scan ──────────────────
testWidgets('panel tab 1: now (the line, what waits, the brief, what tim '
@@ -1416,8 +1563,8 @@ void main() {
act: () => settle(tester),
(context) => panelFor(context, face, brain),
);
- expect(find.text('1 Now'), findsOneWidget);
- expect(find.text('<tim> start codex in ~/code/api?'), findsOneWidget);
+ expect(find.text('Now'), findsOneWidget);
+ expect(find.text('tim: start codex in ~/code/api?'), findsOneWidget);
expect(find.text('codex@laptop'), findsOneWidget, reason: 'the harness');
expect(
find.textContaining('first prompt: run the migrations'),
@@ -1452,7 +1599,7 @@ void main() {
const Size(560, 1250),
(context) => panelFor(context, face, brain),
);
- expect(find.text('2 Zoo'), findsOneWidget);
+ expect(find.text('Zoo'), findsOneWidget);
expect(find.byKey(const ValueKey('daemon-portrait')), findsOneWidget);
expect(find.byKey(const ValueKey('daemon-panel-zoo')), findsOneWidget);
await tester.pumpWidget(const SizedBox());
@@ -1513,8 +1660,8 @@ void main() {
const Size(560, 1300),
(context) => panelFor(context, face, brain),
);
- expect(find.text('4 Settings'), findsOneWidget);
- expect(find.text('(*) suggest'), findsOneWidget);
+ expect(find.text('Settings'), findsOneWidget);
+ expect(find.text('suggest'), findsOneWidget);
expect(find.byKey(const ValueKey('daemon-panel-floor')), findsOneWidget);
expect(
find.textContaining('tim watches your harnesses since 2026-09-26'),
@@ -1562,7 +1709,7 @@ void main() {
act: () => settle(tester),
(context) => panelFor(context, face, brain),
);
- expect(find.text('(~) act on key waits for your yes'), findsOneWidget);
+ expect(find.text('act on key · waits for your yes'), findsOneWidget);
expect(
find.byKey(const ValueKey('daemon-key-confirm:confirm:autonomy:k1-y')),
findsOneWidget,
@@ -1625,8 +1772,12 @@ void main() {
brightness: Brightness.light,
(context) => panelFor(context, face, brain),
);
- expect(find.text('(*) act within rules'), findsOneWidget);
- expect(find.text('[act within rules]'), findsOneWidget, reason: 'badge');
+ expect(find.text('act within rules'), findsNWidgets(2));
+ expect(
+ find.byKey(const ValueKey('daemon-panel-autonomy-badge')),
+ findsOneWidget,
+ reason: 'badge',
+ );
await tester.pumpWidget(const SizedBox());
face.sync(const DaemonWatch());
await tester.pump(const Duration(minutes: 3));
diff --git a/desktop/test/daemon_workspace_test.dart b/desktop/test/daemon_workspace_test.dart
index 62f7088f1..3c17e6755 100644
--- a/desktop/test/daemon_workspace_test.dart
+++ b/desktop/test/daemon_workspace_test.dart
@@ -228,10 +228,7 @@ void main() {
final id = remote.zoo.daemons.single.id;
final def = daemonRoster.byId(id)!;
expect(find.byKey(const ValueKey('daemon-hatch-card')), findsOneWidget);
- expect(
- find.textContaining("fork() returned 0. it's a $id."),
- findsOneWidget,
- );
+ expect(find.textContaining("Meet $id."), findsOneWidget);
expect(glyph(tester), isNot(r'\_(oo)_/'), reason: 'revealed');
// Copy puts a fenced code block on the clipboard.
String? copied;
@@ -288,19 +285,25 @@ void main() {
final id = remote.zoo.daemons.single.id;
expect(find.byKey(const ValueKey('daemon-hatch-card')), findsOneWidget);
// Nobody has said yet whether it may watch: [ next ], not [ close ].
- expect(find.text('[ close ]'), findsNothing);
+ expect(find.text('Close'), findsNothing);
await skipName(tester);
await tester.tap(find.byKey(const ValueKey('daemon-hatch-next')));
await tester.pump();
expect(find.byKey(const ValueKey('daemon-consent')), findsOneWidget);
expect(find.text('What $id sees'), findsOneWidget);
for (final what in ['reads', 'writes', 'runs', 'does']) {
- expect(find.text(what), findsOneWidget);
+ expect(
+ find.text('${what[0].toUpperCase()}${what.substring(1)}'),
+ findsOneWidget,
+ );
}
expect(find.textContaining('your next prompt'), findsOneWidget);
expect(find.textContaining('never a plain terminal'), findsOneWidget);
expect(find.textContaining('a lesson only with your yes'), findsOneWidget);
expect(remote.zoo.consent, isNull, reason: 'nothing until an answer');
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('daemon-consent-watch')),
+ );
await tester.tap(find.byKey(const ValueKey('daemon-consent-watch')));
await tester.pump();
await zoo.flush();
@@ -308,6 +311,9 @@ void main() {
expect(remote.zoo.autonomy, 'watch', reason: 'a yes starts at watch');
// Suggest is its own step.
expect(find.text('Let $id suggest answers?'), findsOneWidget);
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('daemon-consent-suggest-yes')),
+ );
await tester.tap(find.byKey(const ValueKey('daemon-consent-suggest-yes')));
await tester.pump();
await zoo.flush();
@@ -339,6 +345,9 @@ void main() {
await skipName(tester);
await tester.tap(find.byKey(const ValueKey('daemon-hatch-next')));
await tester.pump();
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('daemon-consent-not-now')),
+ );
await tester.tap(find.byKey(const ValueKey('daemon-consent-not-now')));
await tester.pump();
await zoo.flush();
@@ -353,10 +362,16 @@ void main() {
);
await tester.tap(find.byKey(const ValueKey('daemon-consent')));
await tester.pump();
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('daemon-consent-watch')),
+ );
await tester.tap(find.byKey(const ValueKey('daemon-consent-watch')));
await tester.pump();
await zoo.flush();
expect(remote.zoo.watching, isTrue);
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('daemon-consent-keep-watch')),
+ );
await tester.tap(find.byKey(const ValueKey('daemon-consent-keep-watch')));
await tester.pump();
expect(remote.zoo.autonomy, 'watch');
@@ -525,13 +540,13 @@ void main() {
await openControls(tester);
expect(find.byKey(const ValueKey('daemon-panel')), findsOneWidget);
// Four tabs, tmux's window list; now is first. 2 is the zoo.
- expect(find.text('1 Now'), findsOneWidget);
- expect(find.text('2 Zoo'), findsOneWidget);
+ expect(find.text('Now'), findsOneWidget);
+ expect(find.text('Zoo'), findsOneWidget);
expect(find.byKey(const ValueKey('daemon-panel-line')), findsOneWidget);
expect(find.byKey(const ValueKey('daemon-portrait')), findsNothing);
await key(tester, LogicalKeyboardKey.digit2);
await tester.pump();
- expect(find.text('2 Zoo'), findsOneWidget);
+ expect(find.text('Zoo'), findsOneWidget);
expect(find.byKey(const ValueKey('daemon-portrait')), findsOneWidget);
await tester.ensureVisible(find.byKey(const ValueKey('daemon-details')));
await tester.tap(find.byKey(const ValueKey('daemon-details')));
@@ -588,7 +603,7 @@ void main() {
expect(find.byKey(const ValueKey('daemon-panel')), findsNothing);
// It opens again where it was left.
await openControls(tester, section: 'settings');
- expect(find.text('4 Settings'), findsOneWidget);
+ expect(find.text('Settings'), findsOneWidget);
await skipName(tester);
await key(tester, LogicalKeyboardKey.escape);
await tester.pump();
@@ -808,8 +823,8 @@ void main() {
await tester.pump();
app.adoptSessionForTest(terminal('a0', []));
app.adoptSessionForTest(terminal('a1', []));
- // Adoption changes focus without notifying; render its model control before
- // measuring the creature so only the turn events differ below.
+ // The adoption seam does not notify. Lay out the focused pane and its
+ // model control before comparing the bar against subsequent turn events.
app.notifyListeners();
await tester.pump();
final beforeTurns = tester.getRect(slot);
@@ -867,13 +882,13 @@ void main() {
// The switches are on the settings tab: 4.
await tester.tap(find.byKey(const ValueKey('companion-settings')));
await tester.pump();
- expect(find.text('4 Settings'), findsOneWidget);
+ expect(find.text('Settings'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('daemon-quiet')));
await tester.pump();
- expect(find.text('[ quiet: on ]'), findsOneWidget);
+ expect(find.text('Quiet on'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('daemon-motion')));
await tester.pump();
- expect(find.text('[ motion: off ]'), findsOneWidget);
+ expect(find.text('Motion off'), findsOneWidget);
await skipName(tester);
await key(tester, LogicalKeyboardKey.escape);
await tester.pump(const Duration(seconds: 3));
@@ -1113,36 +1128,52 @@ void main() {
await tester.pump();
}
- testWidgets('Talk opens the collection viewer and real terminal without sending a model turn', (tester) async {
- await mount(tester, seed: zooWithTim);
- app.stateOf('m')!.nodeOnline = true;
- await frame(tester, 'daemon_state', state());
- app.stateOf('m')!.agents.add(const Agent(
- id: 'pair1', name: 'Companions', engine: 'claude',
- dsh: 'autonomous/pair', terminalAvailable: true,
- ));
- app.adoptSessionForTest(terminal('pair1', []));
- await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true);
- await tester.pump();
- await tester.pump();
- final opening = frames.lastWhere((f) => f.$1 == 'daemon_open');
- expect(opening.$2.containsKey('text'), isFalse);
- await frame(tester, 'daemon_open_result', {
- 'requestId': opening.$2['requestId'], 'ok': true,
- 'agentId': 'pair1', 'setupRequired': true,
- });
- await tester.pump();
- expect(app.activeSwarm.isCompanions, isTrue);
- expect(app.panes, hasLength(2));
- expect(app.panes.first.isCompanion, isTrue);
- expect(app.panes.first.ownerAgentId, 'pair1');
- expect(app.panes.last.agentId, 'pair1');
- expect(app.focusedPane!.agentId, 'pair1');
- expect(find.byKey(const ValueKey('companion-home')), findsOneWidget);
- expect(find.byKey(const ValueKey('companion-chat-input')), findsNothing);
- expect(frames.where((f) => f.$1 == 'daemon_talk'), isEmpty);
- await unmount(tester);
- });
+ testWidgets(
+ 'Talk opens the collection viewer and real terminal without sending a model turn',
+ (tester) async {
+ await mount(tester, seed: zooWithTim);
+ app.stateOf('m')!.nodeOnline = true;
+ await frame(tester, 'daemon_state', state());
+ app
+ .stateOf('m')!
+ .agents
+ .add(
+ const Agent(
+ id: 'pair1',
+ name: 'Companions',
+ engine: 'claude',
+ dsh: 'autonomous/pair',
+ terminalAvailable: true,
+ ),
+ );
+ app.adoptSessionForTest(terminal('pair1', []));
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true);
+ await tester.pump();
+ await tester.pump();
+ final opening = frames.lastWhere((f) => f.$1 == 'daemon_open');
+ expect(opening.$2.containsKey('text'), isFalse);
+ await frame(tester, 'daemon_open_result', {
+ 'requestId': opening.$2['requestId'],
+ 'ok': true,
+ 'agentId': 'pair1',
+ 'setupRequired': true,
+ });
+ await tester.pump();
+ expect(app.activeSwarm.isCompanions, isTrue);
+ expect(app.panes, hasLength(2));
+ expect(app.panes.first.isCompanion, isTrue);
+ expect(app.panes.first.ownerAgentId, 'pair1');
+ expect(app.panes.last.agentId, 'pair1');
+ expect(app.focusedPane!.agentId, 'pair1');
+ expect(find.byKey(const ValueKey('companion-home')), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('companion-chat-input')),
+ findsNothing,
+ );
+ expect(frames.where((f) => f.$1 == 'daemon_talk'), isEmpty);
+ await unmount(tester);
+ },
+ );
testWidgets('keys first: [g] opens the harness here; the asks list keeps '
'what waits, and y answers it', (tester) async {
@@ -1283,7 +1314,8 @@ void main() {
expect(
frames.where((f) => f.$2['doneSeen'] == true),
hasLength(2),
- reason: 'opening the viewer and then its controls each acknowledges a look',
+ reason:
+ 'opening the viewer and then its controls each acknowledges a look',
);
expect(find.byKey(const ValueKey('daemon-slot-tally')), findsNothing);
expect(
@@ -1312,7 +1344,7 @@ void main() {
for (final level in zooAutonomyLevels) {
expect(find.byKey(ValueKey('daemon-autonomy:$level')), findsOneWidget);
}
- expect(find.text('(*) watch'), findsOneWidget, reason: 'the default');
+ expect(find.text('watch'), findsOneWidget, reason: 'the default');
expect(
find.textContaining('your key approves one waiting answer at a time'),
findsOneWidget,
@@ -1324,10 +1356,7 @@ void main() {
),
findsOneWidget,
);
- expect(
- find.text('[ rules: ~/.config/harness/pair.jsonc ]'),
- findsOneWidget,
- );
+ expect(find.text('Open rules file'), findsOneWidget);
await tapIn(
tester,
find.byKey(const ValueKey('daemon-autonomy:suggest')),
@@ -1335,7 +1364,7 @@ void main() {
await zoo.flush();
expect(remote.zoo.autonomy, 'suggest');
await frame(tester, 'daemon_state', {...state(), 'autonomy': 'suggest'});
- expect(find.text('(*) suggest'), findsOneWidget);
+ expect(find.text('suggest'), findsOneWidget);
// A raise above suggest is a request: harnessd asks for a yes here.
await tapIn(
tester,
@@ -1367,7 +1396,7 @@ void main() {
'autonomyRequested': 'act-on-key',
'confirms': [confirm],
});
- expect(find.text('(~) act on key waits for your yes'), findsOneWidget);
+ expect(find.text('act on key · waits for your yes'), findsOneWidget);
expect(
find.textContaining('it drives harnesses it started without asking'),
findsOneWidget,
@@ -1403,7 +1432,10 @@ void main() {
find.byKey(const ValueKey('daemon-panel-autonomy-badge')),
findsOneWidget,
);
- expect(find.text('[act on key]'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('daemon-panel-autonomy-badge')),
+ findsOneWidget,
+ );
await skipName(tester);
await key(tester, LogicalKeyboardKey.escape);
await tester.pump();
@@ -1510,7 +1542,7 @@ void main() {
await tester.pump();
await key(tester, LogicalKeyboardKey.digit3);
await tester.pump();
- expect(find.text('3 Lessons'), findsOneWidget);
+ expect(find.text('Lessons'), findsOneWidget);
expect(find.text('pending "run-migrations-safely"'), findsOneWidget);
expect(find.text('learned note for api · 2026-09-25'), findsOneWidget);
// No approve here: a window's own say-so is never the person's yes.
@@ -1851,27 +1883,37 @@ void main() {
await unmount(tester);
});
- testWidgets('an unavailable companion engine explains setup and retries in the same DSH', (tester) async {
- await mount(tester, seed: zooWithTim);
- await frame(tester, 'daemon_state', state());
- await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true);
- await tester.pump();
- await tester.pump();
- final opening = frames.lastWhere((f) => f.$1 == 'daemon_open');
- final tab = app.activeSwarm.id;
- await frame(tester, 'daemon_open_result', {
- 'requestId': opening.$2['requestId'], 'ok': false, 'error': 'NO_ENGINE',
- });
- await tester.pump();
- expect(find.text('Install Claude Code or Codex to talk with your companion.'), findsOneWidget);
- await tester.tap(find.text('Open terminal'));
- await tester.pump();
- await tester.pump();
- expect(frames.where((f) => f.$1 == 'daemon_open'), hasLength(2));
- expect(frames.where((f) => f.$1 == 'daemon_talk'), isEmpty);
- expect(app.activeSwarm.id, tab);
- await unmount(tester);
- });
+ testWidgets(
+ 'an unavailable companion engine explains setup and retries in the same DSH',
+ (tester) async {
+ await mount(tester, seed: zooWithTim);
+ await frame(tester, 'daemon_state', state());
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true);
+ await tester.pump();
+ await tester.pump();
+ final opening = frames.lastWhere((f) => f.$1 == 'daemon_open');
+ final tab = app.activeSwarm.id;
+ await frame(tester, 'daemon_open_result', {
+ 'requestId': opening.$2['requestId'],
+ 'ok': false,
+ 'error': 'NO_ENGINE',
+ });
+ await tester.pump();
+ expect(
+ find.text(
+ 'Install Claude Code or Codex to talk with your companion.',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.text('Open terminal'));
+ await tester.pump();
+ await tester.pump();
+ expect(frames.where((f) => f.$1 == 'daemon_open'), hasLength(2));
+ expect(frames.where((f) => f.$1 == 'daemon_talk'), isEmpty);
+ expect(app.activeSwarm.id, tab);
+ await unmount(tester);
+ },
+ );
testWidgets('presence: the pane in front (none clears it), and idle is '
'away with how long', (tester) async {
diff --git a/desktop/test/daemons/illustrated_identity_test.dart b/desktop/test/daemons/illustrated_identity_test.dart
index db4dbfb0d..f2541e4f7 100644
--- a/desktop/test/daemons/illustrated_identity_test.dart
+++ b/desktop/test/daemons/illustrated_identity_test.dart
@@ -1,6 +1,5 @@
import 'dart:async';
import 'dart:convert';
-import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/painting.dart';
@@ -32,10 +31,15 @@ Future<ui.Image> decoded(ImageProvider provider) async {
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
- test('native palette metadata is bundled with the same ten species', () async {
- final styles = jsonDecode(await rootBundle.loadString('assets/daemon-art/styles.json')) as Map;
- expect(styles.keys.toSet(), IllustratedArt.species.toSet());
- });
+ test(
+ 'native palette metadata is bundled with the same ten species',
+ () async {
+ final styles = jsonDecode(
+ await rootBundle.loadString('assets/daemon-art/styles.json'),
+ ) as Map;
+ expect(styles.keys.toSet(), IllustratedArt.species.toSet());
+ },
+ );
test('the integer shader preserves eyes and alpha while colouring and marking the coat', () {
final pixels = Uint8List.fromList([
100,
diff --git a/desktop/test/desktop_compact_launch_test.dart b/desktop/test/desktop_compact_launch_test.dart
new file mode 100644
index 000000000..4625e79c1
--- /dev/null
+++ b/desktop/test/desktop_compact_launch_test.dart
@@ -0,0 +1,818 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/pane_arrangement.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+
+class _CompactApp extends AppNotifier {
+ _CompactApp({String machineName = 'Studio Mac'})
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ ) {
+ final machine = Machine(
+ machineId: 'm',
+ name: machineName,
+ authMode: MachineAuthMode.remote,
+ );
+ machines = [machine];
+ machineStates['m'] = MachineState(machine)
+ ..localOnly = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..engines.replace(const [
+ EngineAvailability(
+ engine: 'codex',
+ installed: true,
+ supportsCodexHome: true,
+ ),
+ EngineAvailability(engine: 'claude', installed: true),
+ ]);
+ }
+
+ final launches = <Map<String, Object?>>[];
+ bool missingMain = false;
+ Completer<String?>? pendingLaunch;
+ String? launchError = 'Fixture launch declined. Try again.';
+
+ @override
+ Future<void> probeEngines(String machineId, {bool force = false}) async {}
+ @override
+ Future<void> probeDsh(String machineId, {bool force = false}) async {}
+ @override
+ Future<Map<String, dynamic>> readGitProject(
+ String machineId,
+ String path, {
+ bool refresh = false,
+ }) async => {
+ 'isGit': true,
+ 'branch': missingMain ? 'feature' : 'main',
+ 'branches': [
+ if (!missingMain) {'ref': 'refs/heads/main', 'name': 'main'},
+ {'ref': 'refs/heads/feature', 'name': 'feature'},
+ ],
+ };
+ @override
+ Future<Map<String, dynamic>> listCodexProfiles(
+ String machineId, {
+ Set<String> observedPaths = const {},
+ }) async => {
+ 'profiles': [
+ {'path': '/profiles/work', 'label': 'Work'},
+ ],
+ };
+ @override
+ Future<Map<String, dynamic>> listRemoteFolder(
+ String machineId,
+ String? path,
+ ) async => {'path': path ?? '/work', 'entries': []};
+
+ @override
+ Future<String?> createAgent(
+ String machineId, {
+ required String engine,
+ required String? folder,
+ bool bypassPermission = false,
+ String? permissionMode,
+ String? codexHome,
+ String? dsh,
+ GridModel? model,
+ String? prompt,
+ String? name,
+ String? agent,
+ ProjectFolderRequest? projectFolder,
+ String? swarmId,
+ PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
+ }) async {
+ launches.add({
+ 'machine': machineId,
+ 'engine': engine,
+ 'folder': folder,
+ 'prompt': prompt,
+ 'permissions': permissionMode,
+ 'projectFolder': projectFolder,
+ });
+ return pendingLaunch?.future ?? Future.value(launchError);
+ }
+}
+
+class _CompactFixture {
+ _CompactFixture(this.app, this.box, this.map);
+ final _CompactApp app;
+ final NewHarnessController box;
+ final MemoryKeymap map;
+ final form = GlobalKey<NewHarnessFormState>();
+ final image = GlobalKey();
+ int closed = 0;
+ int created = 0;
+
+ void dispose() {
+ box.dispose();
+ map.dispose();
+ app.dispose();
+ }
+}
+
+final _surface = find.byKey(const ValueKey('new-harness-surface'));
+final _task = find.byKey(const ValueKey('new-harness-task'));
+final _start = find.byKey(const ValueKey('new-harness-field-start'));
+final _agent = find.byKey(const ValueKey('new-harness-field-agent'));
+final _machine = find.byKey(const ValueKey('new-harness-machine'));
+final _close = find.byKey(const ValueKey('new-harness-close'));
+final _chooser = find.byKey(const ValueKey('new-harness-chooser-surface'));
+
+bool _focused(WidgetTester tester, Finder target) {
+ final element = tester.element(target);
+ var found = FocusManager.instance.primaryFocus?.context == element;
+ FocusManager.instance.primaryFocus?.context?.visitAncestorElements((
+ ancestor,
+ ) {
+ if (ancestor == element) found = true;
+ return !found;
+ });
+ return found;
+}
+
+Future<void> _focus(WidgetTester tester, Finder target) async {
+ for (var i = 0; i < 32 && !_focused(tester, target); i++) {
+ await key(tester, LogicalKeyboardKey.tab);
+ }
+ expect(
+ _focused(tester, target),
+ isTrue,
+ reason: '$target must be reachable with Tab',
+ );
+}
+
+Future<_CompactFixture> _mount(
+ WidgetTester tester, {
+ String engine = 'codex',
+ NewHarnessDraft? draft,
+ Size size = const Size(1100, 800),
+ double scale = 1,
+ Brightness brightness = Brightness.dark,
+ String machineName = 'Studio Mac',
+ bool pending = false,
+ bool missingMain = false,
+ String? harnessId,
+}) async {
+ final app = _CompactApp(machineName: machineName);
+ app.missingMain = missingMain;
+ if (harnessId != null) {
+ app.machineStates['m']!.dsh.replace([
+ DshEntry(
+ id: harnessId,
+ name: 'Review Tool',
+ engine: 'codex',
+ description: 'Synthetic installed agent',
+ installed: true,
+ ),
+ ]);
+ }
+ if (pending) app.pendingLaunch = Completer<String?>();
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: engine,
+ harnessId: harnessId,
+ folder: '/work/repo',
+ draft: draft,
+ );
+ final fixture = _CompactFixture(app, box, MemoryKeymap());
+ addTearDown(fixture.dispose);
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final previousBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: KeymapProvider(
+ keymap: fixture.map,
+ child: KeymapHost(
+ keymap: fixture.map,
+ enabled: () => true,
+ actions: const {},
+ child: RepaintBoundary(
+ key: fixture.image,
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Stack(
+ children: [
+ Positioned.fill(
+ child: GestureDetector(
+ key: const ValueKey('compact-workspace-backdrop'),
+ behavior: HitTestBehavior.opaque,
+ onTap: () =>
+ fixture.form.currentState?.dismissFromOutside(),
+ child: const SizedBox.expand(),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.all(24),
+ child: NewHarnessForm(
+ key: fixture.form,
+ controller: box,
+ desktop: true,
+ onClose: () => fixture.closed++,
+ onCreated: () => fixture.created++,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return fixture;
+}
+
+const _nativeCompactJourneys = {
+ 'empty composer is agent-first, wide, and ready for Return',
+ 'Tab visits each visible control once and wraps to New harness',
+ 'visible editor accepts focus without replacing its configuration (mouse=false)',
+ 'codex settings are direct and chooser cancellation preserves the configuration',
+ 'quick settings survive message editing and chooser acceptance',
+ 'an initially missing branch keeps Return and Escape inside the composer',
+ 'an agent becoming unavailable while Start is focused preserves Escape',
+};
+
+void main({bool nativeSmoke = false}) {
+ void journey(String description, Future<void> Function(WidgetTester) body) {
+ if (nativeSmoke && !_nativeCompactJourneys.contains(description)) return;
+ testWidgets(
+ description,
+ body,
+ timeout: nativeSmoke ? const Timeout(Duration(seconds: 45)) : null,
+ );
+ }
+
+ final renderDir = Platform.environment['COMPACT_LAUNCH_RENDER_DIR'];
+ setUpAll(() async {
+ if (renderDir != null) await loadPreviewFonts();
+ });
+
+ Future<void> capture(
+ WidgetTester tester,
+ _CompactFixture fixture,
+ String name,
+ ) async {
+ if (renderDir == null) return;
+ await tester.runAsync(() async {
+ final boundary =
+ fixture.image.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ final folder = Directory(renderDir)..createSync(recursive: true);
+ await File('${folder.path}/$name.png')
+ .writeAsBytes(data!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ journey('empty composer is agent-first, wide, and ready for Return', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ expect(tester.getSize(_surface).width, 680);
+ expect(_task, findsOneWidget);
+ expect(
+ tester.widget<TextField>(_task).decoration?.hintText,
+ 'Harness anything',
+ );
+ expect(find.byKey(const ValueKey('new-harness-settings')), findsNothing);
+ expect(find.byKey(const ValueKey('new-harness-task-toggle')), findsNothing);
+ expect(
+ find.byKey(const ValueKey('new-harness-field-advanced')),
+ findsNothing,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-approvals')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-worktree')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-model')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-profile')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-branch')),
+ findsOneWidget,
+ );
+ expect(_machine, findsNothing);
+ expect(
+ tester.getTopRight(_agent).dx,
+ lessThan(
+ tester
+ .getTopLeft(find.byKey(const ValueKey('new-harness-field-project')))
+ .dx,
+ ),
+ );
+ expect(_focused(tester, _task), isTrue);
+ await capture(tester, fixture, 'composer-dark');
+ expect(tester.widget<TextField>(_task).controller!.text, isEmpty);
+ expect(fixture.box.task, isEmpty);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ expect(fixture.app.launches.single['prompt'], isNull);
+ expect(fixture.app.launches.single['machine'], 'm');
+ expect(fixture.app.launches.single['engine'], 'codex');
+ expect(fixture.closed, 0);
+ });
+
+ journey('Tab visits each visible control once and wraps to New harness', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ for (final target in [
+ find.byKey(const ValueKey('new-harness-field-model')),
+ find.byKey(const ValueKey('new-harness-field-approvals')),
+ find.byKey(const ValueKey('new-harness-field-profile')),
+ find.byKey(const ValueKey('new-harness-field-worktree')),
+ find.byKey(const ValueKey('new-harness-field-branch')),
+ _close,
+ _start,
+ _agent,
+ find.byKey(const ValueKey('new-harness-field-project')),
+ _task,
+ ]) {
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ _focused(tester, target),
+ isTrue,
+ reason:
+ 'Expected $target, focused ${FocusManager.instance.primaryFocus?.debugLabel}',
+ );
+ }
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(
+ _focused(tester, find.byKey(const ValueKey('new-harness-field-project'))),
+ isTrue,
+ );
+ expect(fixture.app.launches, isEmpty);
+ });
+
+ journey(
+ 'an initially missing branch keeps Return and Escape inside the composer',
+ (tester) async {
+ final fixture = await _mount(tester, missingMain: true);
+ expect(fixture.box.requiredChoice?.field, NewHarnessField.branch);
+ expect(tester.widget<FilledButton>(_start).onPressed, isNull);
+ expect(_task, findsOneWidget);
+ expect(_chooser, findsNothing);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsOneWidget);
+ expect(fixture.box.field, NewHarnessField.branch);
+ expect(fixture.app.launches, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(fixture.closed, 0);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(fixture.closed, 1);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ journey(
+ 'an agent becoming unavailable while Start is focused preserves Escape',
+ (tester) async {
+ final fixture = await _mount(tester, harnessId: 'fixture/review-tool');
+ await _focus(tester, _start);
+ expect(_focused(tester, _start), isTrue);
+ expect(fixture.box.requiredChoice, isNull);
+ fixture.app.machineStates['m']!.dsh.replace(const []);
+ fixture.app.notifyListeners();
+ await tester.pump(const Duration(milliseconds: 150));
+ await tester.pumpAndSettle();
+ expect(fixture.box.requiredChoice?.field, NewHarnessField.harness);
+ expect(tester.widget<FilledButton>(_start).onPressed, isNull);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(fixture.closed, 1);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ for (final submitKey in [
+ LogicalKeyboardKey.enter,
+ LogicalKeyboardKey.numpadEnter,
+ ]) {
+ journey(
+ 'a promptless agent without main directs ${submitKey.keyLabel} to the branch chooser',
+ (tester) async {
+ final fixture = await _mount(
+ tester,
+ engine: 'cursor',
+ missingMain: true,
+ );
+ expect(tester.widget<TextField>(_task).readOnly, isTrue);
+ expect(fixture.box.requiredChoice?.field, NewHarnessField.branch);
+ expect(tester.widget<FilledButton>(_start).onPressed, isNull);
+ await key(tester, submitKey);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsOneWidget);
+ expect(fixture.box.field, NewHarnessField.branch);
+ expect(fixture.app.launches, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(fixture.closed, 0);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(fixture.closed, 1);
+ },
+ );
+ }
+
+ for (final mouse in [true, false]) {
+ journey(
+ 'visible editor accepts focus without replacing its configuration (mouse=$mouse)',
+ (tester) async {
+ final fixture = await _mount(tester);
+ final controller = fixture.box;
+ final project = controller.project;
+ final originalWorktree = controller.worktree;
+ if (mouse) {
+ await tester.tap(_task);
+ } else {
+ await _focus(tester, _task);
+ }
+ await tester.pumpAndSettle();
+ expect(tester.getSize(_surface).width, 680);
+ expect(_focused(tester, _task), isTrue);
+ expect(
+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller,
+ same(controller),
+ );
+ expect(controller.project, project);
+ expect(controller.worktree, originalWorktree);
+ await capture(
+ tester,
+ fixture,
+ 'composer-task-${mouse ? 'mouse' : 'keyboard'}',
+ );
+ await tester.enterText(_task, 'A first question');
+ await _focus(tester, _agent);
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(_task, findsOneWidget);
+ expect(controller.task, 'A first question');
+ expect(tester.getSize(_surface).width, 680);
+ expect(_focused(tester, _agent), isTrue);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+ }
+
+ journey(
+ 'visible task owns Shift-Enter and Cmd-Return submits the exact task',
+ (tester) async {
+ final fixture = await _mount(tester);
+ await tester.enterText(_task, 'Inspect launch');
+ await key(tester, LogicalKeyboardKey.enter, shift: true);
+ expect(fixture.app.launches, isEmpty);
+ // macOS text insertion follows the platform editing channel after the key.
+ // sendKeyEvent alone does not synthesize that operating-system edit.
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'Inspect launch\n',
+ selection: TextSelection.collapsed(offset: 15),
+ ),
+ );
+ await tester.pump();
+ expect(fixture.box.task, 'Inspect launch\n');
+ await tester.enterText(_task, 'Inspect launch\nPreserve the settings');
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ expect(
+ fixture.app.launches.single['prompt'],
+ 'Inspect launch\nPreserve the settings',
+ );
+ },
+ );
+
+ journey(
+ 'clearing a task keeps the editor visible and preserves keyboard focus',
+ (tester) async {
+ final fixture = await _mount(tester);
+ await tester.enterText(_task, 'Retain this draft');
+ await tester.pumpAndSettle();
+ expect(_task, findsOneWidget);
+ expect(fixture.box.task, 'Retain this draft');
+ expect(_focused(tester, _task), isTrue);
+ await tester.enterText(_task, '');
+ await tester.pumpAndSettle();
+ expect(_task, findsOneWidget);
+ expect(_focused(tester, _task), isTrue);
+ expect(fixture.box.task, isEmpty);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ for (final engine in ['codex', 'claude', 'terminal']) {
+ journey(
+ '$engine settings are direct and chooser cancellation preserves the configuration',
+ (tester) async {
+ final fixture = await _mount(tester, engine: engine);
+ final engineBefore = fixture.box.engine;
+ final projectBefore = fixture.box.project;
+ final model = find.byKey(const ValueKey('new-harness-field-model'));
+ final approvals = find.byKey(
+ const ValueKey('new-harness-field-approvals'),
+ );
+ final profile = find.byKey(const ValueKey('new-harness-field-profile'));
+ expect(model, engine == 'terminal' ? findsNothing : findsOneWidget);
+ expect(approvals, engine == 'terminal' ? findsNothing : findsOneWidget);
+ expect(profile, engine == 'codex' ? findsOneWidget : findsNothing);
+ expect(
+ find.byKey(const ValueKey('new-harness-field-advanced')),
+ findsNothing,
+ );
+ final target = engine == 'terminal'
+ ? find.byKey(const ValueKey('new-harness-field-project'))
+ : model;
+ await _focus(tester, target);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(_chooser, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(_focused(tester, target), isTrue);
+ expect(tester.getSize(_surface).width, 680);
+ if (engine == 'codex') {
+ await capture(tester, fixture, 'direct-settings-dark');
+ }
+ expect(fixture.box.engine, engineBefore);
+ expect(fixture.box.project, projectBefore);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+ }
+
+ for (final field in ['project', 'agent', 'approvals']) {
+ journey('$field chooser dismisses one level and restores its origin', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ final target = find.byKey(ValueKey('new-harness-field-$field'));
+ await _focus(tester, target);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(_chooser, findsOneWidget);
+ await tester.tapAt(const Offset(5, 5));
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ expect(_focused(tester, target), isTrue);
+ expect(fixture.closed, 0);
+ expect(tester.getSize(_surface).width, 680);
+ await tester.tapAt(const Offset(5, 5));
+ await tester.pumpAndSettle();
+ expect(fixture.closed, 1);
+ });
+ }
+
+ journey(
+ 'held Return and a busy Start produce one launch, with failure recovery',
+ (tester) async {
+ final fixture = await _mount(tester, pending: true);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await tester.sendKeyRepeatEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(fixture.app.launches, hasLength(1));
+ expect(tester.widget<FilledButton>(_start).onPressed, isNull);
+ await tester.tap(_start, warnIfMissed: false);
+ await tester.pump();
+ expect(fixture.app.launches, hasLength(1));
+ fixture.app.pendingLaunch!.complete('Offline. Try again.');
+ await tester.pumpAndSettle();
+ fixture.app.pendingLaunch = null;
+ expect(find.text('Offline. Try again.'), findsWidgets);
+ expect(tester.widget<FilledButton>(_start).onPressed, isNotNull);
+ expect(
+ _focused(tester, _task),
+ isTrue,
+ reason:
+ 'Failure should leave Return ready to retry without an extra Tab',
+ );
+ await _focus(tester, _start);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(2));
+ expect(fixture.box.task, isEmpty);
+ expect(_task, findsOneWidget);
+ },
+ );
+
+ journey('quick settings survive message editing and chooser acceptance', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ final worktree = find.byKey(const ValueKey('new-harness-field-worktree'));
+ final before = fixture.box.worktree;
+ await tester.tap(worktree);
+ await tester.pumpAndSettle();
+ expect(fixture.box.worktree, !before);
+ final branch = find.byKey(const ValueKey('new-harness-field-branch'));
+ await tester.tap(branch);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(_focused(tester, branch), isTrue);
+ expect(fixture.box.worktree, !before);
+ await tester.enterText(_task, 'Preserve my worktree preference');
+ final agent = find.byKey(const ValueKey('new-harness-field-agent'));
+ await tester.tap(agent);
+ await tester.pumpAndSettle();
+ final claude = find.byKey(const ValueKey('new-harness-option-claude'));
+ expect(claude, findsOneWidget);
+ await tester.tap(claude);
+ await tester.pumpAndSettle();
+ expect(fixture.box.engine, 'claude');
+ expect(fixture.box.task, 'Preserve my worktree preference');
+ expect(fixture.box.worktree, !before);
+ expect(_focused(tester, agent), isTrue);
+ expect(fixture.app.launches, isEmpty);
+ });
+
+ journey('IME composition in the task blocks Return and Cmd-Return', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ await tester.tap(_task);
+ await tester.pumpAndSettle();
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: '選択',
+ selection: TextSelection.collapsed(offset: 2),
+ composing: TextRange(start: 0, end: 2),
+ ),
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(fixture.app.launches, isEmpty);
+ expect(fixture.box.task, '選択');
+ expect(_focused(tester, _task), isTrue);
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: '選択',
+ selection: TextSelection.collapsed(offset: 2),
+ ),
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ expect(fixture.app.launches.single['prompt'], '選択');
+ });
+
+ journey('legacy expanded-settings draft restores into direct controls', (
+ tester,
+ ) async {
+ final draft = NewHarnessDraft(
+ machineId: 'm',
+ engine: 'claude',
+ project: const NewHarnessProject.folder('/work/repo'),
+ task: '',
+ permissionMode: 'ask',
+ advancedOpen: true,
+ worktree: false,
+ );
+ final fixture = await _mount(tester, draft: draft);
+ expect(_task, findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('new-harness-field-model')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-approvals')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-advanced')),
+ findsNothing,
+ );
+ expect(tester.getSize(_surface).width, 680);
+ expect(_focused(tester, _task), isTrue);
+ expect(fixture.box.engine, 'claude');
+ expect(fixture.box.worktree, isFalse);
+ expect(fixture.box.mode, 'ask');
+ });
+
+ journey('restored and empty drafts both focus the prompt', (tester) async {
+ final source = await _mount(tester);
+ source.box.setTask('Draft from earlier');
+ final draft = source.box.draft;
+ await tester.pumpWidget(const SizedBox());
+ final restored = await _mount(tester, draft: draft);
+ expect(restored.box.task, 'Draft from earlier');
+ expect(
+ tester.widget<TextField>(_task).controller!.text,
+ 'Draft from earlier',
+ );
+ expect(_focused(tester, _task), isTrue);
+ expect(tester.getSize(_surface).width, 680);
+ restored.box.setTask('');
+ final empty = restored.box.draft;
+ await tester.pumpWidget(const SizedBox());
+ final emptyFixture = await _mount(tester, draft: empty);
+ expect(_task, findsOneWidget);
+ expect(_focused(tester, _task), isTrue);
+ expect(tester.getSize(_surface).width, 680);
+ expect(emptyFixture.box.project, draft.project);
+ expect(emptyFixture.box.worktree, draft.worktree);
+ });
+
+ for (final brightness in [Brightness.dark, Brightness.light]) {
+ for (final scale in [1.0, 1.6]) {
+ journey('composer controls fit 600x520 ${brightness.name} scale=$scale', (
+ tester,
+ ) async {
+ final fixture = await _mount(
+ tester,
+ size: const Size(600, 520),
+ scale: scale,
+ brightness: brightness,
+ machineName: 'Studio Mac development workstation',
+ );
+ expect(tester.takeException(), isNull);
+ expect(tester.getSize(_surface).width, lessThanOrEqualTo(552));
+ await capture(tester, fixture, 'composer-${brightness.name}-$scale');
+ await _focus(tester, _task);
+ expect(_focused(tester, _task), isTrue);
+ await tester.enterText(
+ _task,
+ 'A task with enough text to wrap across the smaller window safely.',
+ );
+ for (final field in [
+ 'model',
+ 'approvals',
+ 'profile',
+ 'worktree',
+ 'branch',
+ ]) {
+ final control = find.byKey(ValueKey('new-harness-field-$field'));
+ await _focus(tester, control);
+ await tester.pumpAndSettle();
+ expect(control.hitTestable(), findsOneWidget);
+ }
+ expect(tester.takeException(), isNull);
+ await _focus(tester, _start);
+ expect(_start.hitTestable(), findsOneWidget);
+ await capture(
+ tester,
+ fixture,
+ 'composer-filled-${brightness.name}-$scale',
+ );
+ expect(fixture.app.launches, isEmpty);
+ });
+ }
+ }
+}
diff --git a/desktop/test/desktop_composer_layout_test.dart b/desktop/test/desktop_composer_layout_test.dart
new file mode 100644
index 000000000..c4d6e63f5
--- /dev/null
+++ b/desktop/test/desktop_composer_layout_test.dart
@@ -0,0 +1,1605 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/pane_arrangement.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+
+/// A launch boundary that records the user's reviewed choices without starting
+/// an agent, preparing a worktree, or contacting a real machine.
+class _ReviewApp extends AppNotifier {
+ _ReviewApp({
+ required String machineName,
+ this.git = true,
+ this.branchNames = const ['main', 'feature/review'],
+ }) : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ ) {
+ final machine = Machine(
+ machineId: 'review',
+ name: machineName,
+ authMode: MachineAuthMode.remote,
+ );
+ machines = [machine];
+ machineStates[machine.machineId] = MachineState(machine)
+ ..localOnly = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..engines.replace(const [
+ EngineAvailability(
+ engine: 'codex',
+ installed: true,
+ supportsCodexHome: true,
+ ),
+ EngineAvailability(engine: 'claude', installed: true),
+ ]);
+ }
+
+ final bool git;
+ final List<String> branchNames;
+ final launches = <Map<String, Object?>>[];
+
+ @override
+ Future<void> probeEngines(String machineId, {bool force = false}) async {}
+
+ @override
+ Future<void> probeDsh(String machineId, {bool force = false}) async {}
+
+ @override
+ Future<GridModels> refreshGridModels(String machineId) async =>
+ const GridModels.unreachable();
+
+ @override
+ Future<Map<String, dynamic>> readGitProject(
+ String machineId,
+ String path, {
+ bool refresh = false,
+ }) async => {
+ 'isGit': git,
+ if (git) ...{
+ 'branch': 'main',
+ 'branches': [
+ for (final name in branchNames)
+ {'ref': 'refs/heads/$name', 'name': name},
+ ],
+ },
+ };
+
+ @override
+ Future<Map<String, dynamic>> listCodexProfiles(
+ String machineId, {
+ Set<String> observedPaths = const {},
+ }) async => {
+ 'profiles': [
+ {'path': '/profiles/work', 'label': 'Work'},
+ ],
+ };
+
+ @override
+ Future<Map<String, dynamic>> listRemoteFolder(
+ String machineId,
+ String? path,
+ ) async => {'path': path ?? '/work', 'entries': []};
+
+ @override
+ Future<String?> createAgent(
+ String machineId, {
+ required String engine,
+ required String? folder,
+ bool bypassPermission = false,
+ String? permissionMode,
+ String? codexHome,
+ String? dsh,
+ GridModel? model,
+ String? prompt,
+ String? name,
+ String? agent,
+ ProjectFolderRequest? projectFolder,
+ String? swarmId,
+ PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
+ }) async {
+ launches.add({
+ 'machine': machineId,
+ 'engine': engine,
+ 'folder': folder,
+ 'prompt': prompt,
+ 'permissions': permissionMode,
+ 'profile': codexHome,
+ 'projectFolder': projectFolder,
+ });
+ return 'Synthetic review stops at the launch boundary.';
+ }
+}
+
+class _ReviewFixture {
+ _ReviewFixture(this.app, this.box, this.map);
+
+ final _ReviewApp app;
+ final NewHarnessController box;
+ final MemoryKeymap map;
+ final form = GlobalKey<NewHarnessFormState>();
+ final image = GlobalKey();
+ int closes = 0;
+
+ void dispose() {
+ box.dispose();
+ map.dispose();
+ app.dispose();
+ }
+}
+
+Finder _field(String name) => find.byKey(ValueKey('new-harness-field-$name'));
+final _surface = find.byKey(const ValueKey('new-harness-surface'));
+final _composer = find.byKey(const ValueKey('new-harness-composer'));
+final _task = find.byKey(const ValueKey('new-harness-task'));
+final _machine = find.byKey(const ValueKey('new-harness-repo-machine'));
+final _close = find.byKey(const ValueKey('new-harness-close'));
+final _chooser = find.byKey(const ValueKey('new-harness-chooser-surface'));
+final _query = find.byKey(const ValueKey('new-harness-query'));
+
+bool _focused(WidgetTester tester, Finder finder) {
+ if (finder.evaluate().isEmpty) return false;
+ final element = tester.element(finder);
+ var found = FocusManager.instance.primaryFocus?.context == element;
+ FocusManager.instance.primaryFocus?.context?.visitAncestorElements((
+ ancestor,
+ ) {
+ if (ancestor == element) found = true;
+ return !found;
+ });
+ return found;
+}
+
+Future<void> _focus(WidgetTester tester, Finder finder) async {
+ for (var attempt = 0; attempt < 16 && !_focused(tester, finder); attempt++) {
+ await key(tester, LogicalKeyboardKey.tab);
+ await tester.pumpAndSettle();
+ }
+ expect(
+ _focused(tester, finder),
+ isTrue,
+ reason: '$finder is reachable by Tab',
+ );
+}
+
+void _expectReadingOrder(Rect before, Rect after) {
+ expect(
+ before.bottom <= after.top ||
+ (before.center.dy - after.center.dy).abs() <= 1 &&
+ before.right < after.left,
+ isTrue,
+ reason: 'Settings retain reading order when wider fonts wrap the row',
+ );
+}
+
+Future<_ReviewFixture> _mount(
+ WidgetTester tester, {
+ String engine = 'codex',
+ String machineName = 'office',
+ String folder = '/work/autonomous-harness',
+ bool git = true,
+ List<String> branchNames = const ['main', 'feature/review'],
+ Size size = const Size(1200, 800),
+ double scale = 1,
+ Brightness brightness = Brightness.dark,
+ NewHarnessDraft? draft,
+ FutureOr<void> Function(_ReviewFixture)? onBrowse,
+}) async {
+ final app = _ReviewApp(
+ machineName: machineName,
+ git: git,
+ branchNames: branchNames,
+ );
+ final box = NewHarnessController(
+ app,
+ machineId: 'review',
+ engine: engine,
+ folder: folder,
+ draft: draft,
+ );
+ final fixture = _ReviewFixture(app, box, MemoryKeymap());
+ addTearDown(fixture.dispose);
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final previousBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid
+ .buildAppTheme(brightness: brightness)
+ .copyWith(platform: TargetPlatform.macOS),
+ builder: (context, child) => RepaintBoundary(
+ key: fixture.image,
+ child: MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ ),
+ home: KeymapProvider(
+ keymap: fixture.map,
+ child: KeymapHost(
+ keymap: fixture.map,
+ enabled: () => true,
+ actions: const {},
+ child: RepaintBoundary(
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Stack(
+ children: [
+ Positioned.fill(
+ child: DesktopDialogBackdrop(
+ onDismiss: () =>
+ fixture.form.currentState?.dismissFromOutside(),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.all(24),
+ child: NewHarnessForm(
+ key: fixture.form,
+ controller: box,
+ desktop: true,
+ onBrowse: onBrowse == null
+ ? null
+ : () => onBrowse(fixture),
+ onClose: () => fixture.closes++,
+ onCreated: () => fail('The fake launch must not succeed'),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return fixture;
+}
+
+void main() {
+ final renderDir = Platform.environment['COMPOSER_LAYOUT_RENDER_DIR'];
+ setUpAll(() async {
+ if (renderDir != null) await loadPreviewFonts();
+ });
+
+ Future<void> capture(
+ WidgetTester tester,
+ _ReviewFixture fixture,
+ String name,
+ ) async {
+ if (renderDir == null) return;
+ final previousDisableShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ final boundary =
+ fixture.image.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ void repaint(RenderObject object) {
+ object.markNeedsPaint();
+ object.visitChildren(repaint);
+ }
+
+ try {
+ final images = tester.widgetList<Image>(
+ find.descendant(
+ of: find.byKey(fixture.image),
+ matching: find.byType(Image),
+ ),
+ );
+ await tester.runAsync(() async {
+ await Future.wait([
+ for (final image in images)
+ precacheImage(image.image, fixture.image.currentContext!),
+ ]);
+ });
+ // Changing the debug flag does not invalidate an already painted layer.
+ // Repaint the physical shapes so captures contain actual soft shadows.
+ repaint(boundary);
+ await tester.pumpAndSettle();
+ await tester.runAsync(() async {
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ final directory = Directory(renderDir)..createSync(recursive: true);
+ await File('${directory.path}/$name.png')
+ .writeAsBytes(data!.buffer.asUint8List());
+ image.dispose();
+ });
+ } finally {
+ debugDisableShadows = previousDisableShadows;
+ repaint(boundary);
+ await tester.pump();
+ }
+ }
+
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'wide composer follows the reviewed ${brightness.name} layout',
+ (tester) async {
+ final fixture = await _mount(tester, brightness: brightness);
+ final surface = tester.getRect(_surface);
+ final composer = tester.getRect(_composer);
+ final agent = tester.getRect(_field('agent'));
+ final repo = tester.getRect(_field('project'));
+ final action = tester.getRect(_field('start'));
+ final model = tester.getRect(_field('model'));
+ final approvals = tester.getRect(_field('approvals'));
+ final profile = tester.getRect(_field('profile'));
+ final worktree = tester.getRect(_field('worktree'));
+ final branch = tester.getRect(_field('branch'));
+
+ expect(surface.width, 680);
+ expect(
+ tester.widget<Material>(_surface).type,
+ MaterialType.transparency,
+ );
+ expect(agent.right, lessThan(repo.left));
+ expect(_machine, findsNothing);
+ expect(agent.center.dy, closeTo(repo.center.dy, 1));
+ expect(repo.bottom, lessThan(composer.top));
+ expect(composer.contains(action.topLeft), isTrue);
+ expect(composer.contains(action.bottomRight), isTrue);
+ expect(action.right, greaterThan(composer.right - 28));
+ expect(action.bottom, greaterThan(composer.bottom - 28));
+ expect(model.top, greaterThan(composer.bottom));
+ _expectReadingOrder(model, approvals);
+ _expectReadingOrder(approvals, profile);
+ expect(profile.right, lessThan(worktree.left));
+ expect(worktree.right, lessThanOrEqualTo(branch.left));
+ expect(worktree.center.dy, closeTo(branch.center.dy, 1));
+ expect(branch.right, greaterThan(surface.center.dx));
+ expect(find.text('New Harness'), findsOneWidget);
+ expect(
+ tester.widget<TextField>(_task).decoration!.hintText,
+ 'Harness anything',
+ );
+ expect(find.text('Options'), findsNothing);
+ expect(find.text('Add task'), findsNothing);
+ expect(_field('advanced'), findsNothing);
+ expect(_focused(tester, _task), isTrue);
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ await capture(tester, fixture, 'composer-${brightness.name}');
+ },
+ );
+ }
+
+ testWidgets(
+ 'footer controls show their purpose and keep stable focus geometry',
+ (tester) async {
+ final fixture = await _mount(tester);
+ Material buttonMaterial(Finder control) => tester.widget<Material>(
+ find.descendant(of: control, matching: find.byType(Material)).first,
+ );
+ for (final name in [
+ 'model',
+ 'approvals',
+ 'profile',
+ 'worktree',
+ 'branch',
+ ]) {
+ final control = _field(name);
+ expect(
+ find.descendant(of: control, matching: find.byType(Icon)),
+ findsOneWidget,
+ );
+ final before = tester.getRect(control);
+ final resting = buttonMaterial(control);
+ await _focus(tester, control);
+ final focused = buttonMaterial(control);
+ expect(tester.getRect(control), before);
+ final restingShape = resting.shape! as OutlinedBorder;
+ final focusedShape = focused.shape! as OutlinedBorder;
+ expect(focusedShape.runtimeType, restingShape.runtimeType);
+ expect(focusedShape.side.width, restingShape.side.width);
+ expect(focusedShape.side.color, Colors.transparent);
+ expect(
+ focused.color != resting.color ||
+ focusedShape.side.color != restingShape.side.color,
+ isTrue,
+ );
+ }
+ for (final (name, message) in [
+ ('model', 'Choose model: OpenAI'),
+ ('approvals', 'Choose approval mode: Auto-approve'),
+ ('profile', 'Choose Codex profile: Default'),
+ ]) {
+ final tooltip = tester.widget<Tooltip>(
+ find.descendant(of: _field(name), matching: find.byType(Tooltip)),
+ );
+ expect(tooltip.message, message);
+ }
+ expect(find.text('Worktree'), findsOneWidget);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ testWidgets('agent identity is shown by the Codex and Claude marks', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ Finder mark(Finder control) =>
+ find.descendant(of: control, matching: find.byType(EngineMark));
+ expect(tester.widget<EngineMark>(mark(_field('agent'))).engine, 'codex');
+ expect(
+ find.descendant(
+ of: _field('agent'),
+ matching: find.byKey(const ValueKey('engine-icon-codex')),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: _field('agent'),
+ matching: find.byIcon(AppIcons.code),
+ ),
+ findsNothing,
+ );
+ await tester.tap(_field('agent'));
+ await tester.pumpAndSettle();
+ final codex = find.byKey(const ValueKey('new-harness-option-codex'));
+ final claude = find.byKey(const ValueKey('new-harness-option-claude'));
+ expect(tester.widget<EngineMark>(mark(codex)).engine, 'codex');
+ expect(tester.widget<EngineMark>(mark(claude)).engine, 'claude');
+ await tester.tap(claude);
+ await tester.pumpAndSettle();
+ expect(tester.widget<EngineMark>(mark(_field('agent'))).engine, 'claude');
+ expect(
+ find.descendant(
+ of: _field('agent'),
+ matching: find.byKey(const ValueKey('engine-icon-claude')),
+ ),
+ findsOneWidget,
+ );
+ expect(_field('profile'), findsNothing);
+ expect(fixture.app.launches, isEmpty);
+ await capture(tester, fixture, 'composer-claude-dark');
+ });
+
+ testWidgets('clickable controls use a hand; the prompt keeps a text cursor', (
+ tester,
+ ) async {
+ await _mount(tester);
+ final pointer = await tester.createGesture(
+ kind: ui.PointerDeviceKind.mouse,
+ pointer: 7,
+ );
+ await pointer.addPointer(location: Offset.zero);
+ addTearDown(pointer.removePointer);
+ for (final control in [
+ _field('agent'),
+ _field('project'),
+ _field('branch'),
+ _field('worktree'),
+ _field('start'),
+ _close,
+ ]) {
+ await pointer.moveTo(tester.getCenter(control));
+ await tester.pump();
+ expect(
+ RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
+ SystemMouseCursors.click,
+ reason: '$control should invite clicking',
+ );
+ }
+ await pointer.moveTo(tester.getCenter(_task));
+ await tester.pump();
+ expect(
+ RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
+ SystemMouseCursors.text,
+ );
+ });
+
+ testWidgets('X closes immediately even with a chooser open', (tester) async {
+ final fixture = await _mount(tester);
+ await tester.enterText(_task, 'Keep this draft');
+ await tester.tap(_field('agent'));
+ await tester.pumpAndSettle();
+ await tester.tap(_close);
+ await tester.pump();
+ expect(fixture.closes, 1);
+ expect(fixture.box.task, 'Keep this draft');
+ expect(fixture.app.launches, isEmpty);
+ });
+
+ testWidgets('the platform send action submits the exact prompt once', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ await tester.enterText(_task, 'First line\nSecond line');
+ await tester.testTextInput.receiveAction(TextInputAction.send);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ expect(fixture.app.launches.single['prompt'], 'First line\nSecond line');
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.6]) {
+ testWidgets('GitHub entry stays compact at ${brightness.name} $scale', (
+ tester,
+ ) async {
+ final fixture = await _mount(
+ tester,
+ brightness: brightness,
+ scale: scale,
+ size: scale == 1 ? const Size(1200, 800) : const Size(640, 540),
+ );
+ await tester.enterText(_task, 'Keep the task draft');
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('GitHub'));
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(_query).decoration!.hintText,
+ 'Enter GitHub URL',
+ );
+ expect(find.text('github.com/owner/repo or owner/repo'), findsNothing);
+ expect(find.text('No matches'), findsNothing);
+ expect(tester.getSize(_chooser).height, lessThan(80));
+ final entryHeight = tester.getSize(_chooser).height;
+ expect(_focused(tester, _query), isTrue);
+ await capture(tester, fixture, 'github-${brightness.name}-$scale');
+
+ await tester.enterText(_query, 'not a repository');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final error = find.byKey(const ValueKey('new-harness-status'));
+ expect(error.hitTestable(), findsOneWidget);
+ expect(
+ tester.getRect(error).bottom,
+ lessThan(tester.getRect(_chooser).bottom),
+ );
+ expect(
+ tester.getSize(_chooser).height,
+ lessThanOrEqualTo(entryHeight + tester.getSize(error).height + 18),
+ reason:
+ 'Validation gets only its text and padding, not an empty list.',
+ );
+ await capture(
+ tester,
+ fixture,
+ 'github-error-${brightness.name}-$scale',
+ );
+
+ await tester.enterText(_query, 'autonomous-ai/openharness');
+ await tester.pumpAndSettle();
+ expect(find.text('Clone openharness').hitTestable(), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(fixture.box.task, 'Keep the task draft');
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ });
+ }
+ testWidgets('Repo and side-by-side machine menus fit ${brightness.name}', (
+ tester,
+ ) async {
+ final fixture = await _mount(
+ tester,
+ brightness: brightness,
+ onBrowse: (_) {},
+ );
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(_query.hitTestable(), findsOneWidget);
+ final menu = tester.getRect(_chooser);
+ expect(menu.width, greaterThanOrEqualTo(400));
+ final hint = find.descendant(
+ of: _query,
+ matching: find.text('Search repos'),
+ );
+ expect(
+ tester.renderObject<RenderParagraph>(hint).didExceedMaxLines,
+ isFalse,
+ );
+ expect(menu.height, lessThan(280));
+ expect(fixture.box.options.take(3).map((o) => o.title), [
+ 'Open Folder',
+ 'New Folder',
+ 'GitHub',
+ ]);
+ expect(
+ tester.getRect(_query).center.dy,
+ closeTo(tester.getRect(_machine).center.dy, 1),
+ );
+ expect(
+ tester.getRect(_query).right,
+ lessThan(tester.getRect(_machine).left),
+ );
+ await capture(tester, fixture, 'repo-menu-${brightness.name}');
+ await tester.tap(_machine);
+ await tester.pumpAndSettle();
+ final local = find.byKey(
+ const ValueKey('new-harness-machine-option-review'),
+ );
+ expect(local, findsOneWidget);
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(tester.getRect(local).left, greaterThan(menu.right));
+ expect(tester.getRect(local).top, closeTo(menu.top + 6, 2));
+ expect(
+ find.descendant(of: local, matching: find.text('office')),
+ findsOneWidget,
+ );
+ await capture(tester, fixture, 'machine-menu-${brightness.name}');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(local, findsNothing);
+ expect(_chooser, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(_focused(tester, _field('project')), isTrue);
+ expect(fixture.closes, 0);
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ });
+ }
+
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'Repo search remains readable with enlarged text ${brightness.name}',
+ (tester) async {
+ final fixture = await _mount(
+ tester,
+ brightness: brightness,
+ size: const Size(880, 560),
+ scale: 2,
+ );
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ final hint = find.descendant(
+ of: _query,
+ matching: find.text('Search repos'),
+ );
+ expect(
+ tester.renderObject<RenderParagraph>(hint).didExceedMaxLines,
+ isFalse,
+ );
+ expect(_machine.hitTestable(), findsOneWidget);
+ expect(tester.getRect(_chooser).right, lessThanOrEqualTo(880));
+ expect(
+ tester.getRect(_query).right,
+ lessThan(tester.getRect(_machine).left),
+ );
+ await capture(tester, fixture, 'repo-menu-enlarged-${brightness.name}');
+ await tester.enterText(_query, 'openharness');
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(_query).controller!.text,
+ 'openharness',
+ );
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
+ testWidgets('Repo scopes folders to its machine and preserves the draft', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ const remote = Machine(
+ machineId: 'remote',
+ name: 'Build server',
+ authMode: MachineAuthMode.remote,
+ );
+ fixture.app.machineStates['remote'] = MachineState(remote)
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..engines.replace(const [
+ EngineAvailability(engine: 'codex', installed: true),
+ ]);
+ await fixture.app.projectHistory.select('remote', '/srv/remote-repo');
+ await tester.enterText(_task, 'Keep my unsent task across machines');
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ expect(find.text('This Mac'), findsOneWidget);
+ expect(
+ fixture.box.options
+ .where((o) => !o.synthetic)
+ .every((o) => o.machineId == 'review'),
+ isTrue,
+ );
+
+ // Tab reaches the machine control from search; arrows stay in its menu.
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(_focused(tester, _machine), isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(
+ find.byKey(const ValueKey('new-harness-machine-option-remote')),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(fixture.box.machineId, 'remote');
+ expect(find.text('remote-repo'), findsOneWidget);
+ expect(
+ fixture.box.options
+ .where((o) => !o.synthetic)
+ .every((o) => o.machineId == 'remote'),
+ isTrue,
+ );
+ await tester.tap(
+ find.byKey(
+ const ValueKey('new-harness-option-project:remote:/srv/remote-repo'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(_focused(tester, _field('project')), isTrue);
+ expect(find.text('remote-repo · Build server'), findsOneWidget);
+ expect(fixture.box.project.folder, '/srv/remote-repo');
+
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, 'remote');
+ await tester.tap(_machine);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(fixture.box.query, 'remote');
+ expect(fixture.box.machineId, 'remote');
+ await tester.tap(_machine);
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-machine-option-review')),
+ );
+ await tester.pumpAndSettle();
+ expect(fixture.box.machineId, 'review');
+ expect(fixture.box.project.folder, '/work/autonomous-harness');
+ expect(fixture.box.query, isEmpty);
+ expect(fixture.box.task, 'Keep my unsent task across machines');
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final field in ['project', 'branch', 'model']) {
+ testWidgets('long $field notices keep search and choices usable at 390x360 '
+ '${brightness.name} scale=2', (tester) async {
+ final fixture = await _mount(
+ tester,
+ size: const Size(390, 360),
+ scale: 2,
+ brightness: brightness,
+ machineName: field == 'model'
+ ? 'Development computer for the design team, frontend platform, '
+ 'and shared test projects in the main office'
+ : 'office',
+ );
+ await tester.enterText(_task, 'Keep my task while I recover');
+ await tester.ensureVisible(_field(field));
+ await tester.tap(_field(field));
+ await tester.pumpAndSettle();
+ const longError =
+ 'Could not clone the repository.\n'
+ 'fatal: unable to access https://github.com/design-team/frontend-platform: '
+ 'The requested URL returned error: 403.\n'
+ 'Check that the repository URL is correct and that this computer has access. '
+ 'Your project choice and prompt are kept. Try again when access is restored.';
+ if (field == 'project') {
+ await tester.enterText(_query, 'Git');
+ final editor = tester.widget<TextField>(_query).controller!;
+ editor.value = editor.value.copyWith(
+ composing: const TextRange(start: 0, end: 3),
+ );
+ fixture.box.warn(longError);
+ } else if (field == 'branch') {
+ fixture.box.branchRefreshError = longError;
+ fixture.box.warn(
+ 'Your project and prompt are kept. Retry the branch refresh.',
+ );
+ } else {
+ expect(fixture.box.modelNotice, contains('Could not load models'));
+ }
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ final search = tester.getRect(_query);
+ final notices = find.byKey(
+ const ValueKey('new-harness-chooser-notices'),
+ );
+ final list = find.descendant(
+ of: _chooser,
+ matching: find.byType(ListView),
+ );
+ final noticeController = tester
+ .widget<SingleChildScrollView>(notices)
+ .controller!;
+ final queryController = tester.widget<TextField>(_query).controller!;
+ final query = queryController.value;
+ expect(noticeController.position.maxScrollExtent, greaterThan(0));
+ expect(
+ tester.getSize(list).height,
+ greaterThan(tester.getSize(notices).height),
+ );
+ expect(_query.hitTestable(), findsOneWidget);
+ expect(_focused(tester, _query), isTrue);
+ final selected = fixture.box.options[fixture.box.cursor];
+ final selectedChoice = find.byKey(
+ ValueKey('new-harness-option-${selected.id}'),
+ );
+ expect(selectedChoice.hitTestable(), findsOneWidget);
+ expect(
+ tester.getRect(selectedChoice).bottom,
+ lessThanOrEqualTo(tester.getRect(list).bottom),
+ reason: 'The active choice stays fully visible above long notices.',
+ );
+ await capture(tester, fixture, 'recovery-$field-${brightness.name}-2');
+
+ await tester.drag(notices, const Offset(0, -240));
+ await tester.pumpAndSettle();
+ expect(noticeController.offset, greaterThan(0));
+ expect(tester.getRect(_query), search);
+ expect(queryController.value, query);
+ expect(_focused(tester, _query), isTrue);
+ noticeController.jumpTo(noticeController.position.maxScrollExtent);
+ await tester.pump();
+ final lastNotice = field == 'model'
+ ? find.text(fixture.box.modelNotice!)
+ : find.byKey(const ValueKey('new-harness-status'));
+ expect(
+ tester.getRect(lastNotice).bottom,
+ lessThanOrEqualTo(tester.getRect(notices).bottom),
+ reason: 'The full notice can be read without displacing search or choices.',
+ );
+ if (field == 'project') {
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ fixture.box.field,
+ NewHarnessField.projectMenu,
+ reason: 'IME confirmation must not activate a project choice.',
+ );
+ expect(queryController.value, query);
+ queryController.clearComposing();
+ }
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(fixture.box.task, 'Keep my task while I recover');
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ });
+ }
+
+ for (final removed in [false, true]) {
+ testWidgets(
+ '${removed ? "removed" : "offline"} machine recovery opens the existing chooser '
+ '${brightness.name} at enlarged text',
+ (tester) async {
+ final fixture = await _mount(
+ tester,
+ size: removed ? const Size(390, 360) : const Size(600, 520),
+ scale: removed ? 2 : 1.6,
+ brightness: brightness,
+ );
+ const remote = Machine(
+ machineId: 'remote',
+ name: 'Build server',
+ authMode: MachineAuthMode.remote,
+ );
+ fixture.app.machineStates['remote'] = MachineState(remote)
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..engines.replace(const [
+ EngineAvailability(engine: 'codex', installed: true),
+ ]);
+ await fixture.app.projectHistory.select(
+ 'remote',
+ '/srv/recovery-repo',
+ );
+ final taskDraft = removed
+ ? 'Keep my unsent task\n'
+ 'First review detail\n'
+ 'Second review detail\n'
+ 'Third review detail\n'
+ 'Fourth review detail\n'
+ 'Fifth review detail\n'
+ 'Sixth review detail'
+ : 'Keep my unsent task across machines';
+ await tester.enterText(_task, taskDraft);
+ final editor = tester.widget<TextField>(_task).controller!;
+ editor.value = editor.value.copyWith(
+ composing: const TextRange(start: 0, end: 4),
+ );
+ final draft = editor.value;
+ if (removed) {
+ fixture.app.machineStates.remove('review');
+ fixture.app.machines.removeWhere(
+ (machine) => machine.machineId == 'review',
+ );
+ } else {
+ fixture.app.stateOf('review')!.nodeOnline = false;
+ }
+ fixture.app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(editor.value, draft);
+ expect(fixture.box.machineId, 'review');
+ expect(
+ tester.widget<FilledButton>(_field('start')).onPressed,
+ isNull,
+ );
+ expect(_machine, findsNothing);
+ final recovery = find.byKey(
+ const ValueKey('new-harness-recover-machine'),
+ );
+ await tester.ensureVisible(recovery);
+ await tester.pumpAndSettle();
+ expect(recovery.hitTestable(), findsOneWidget);
+ expect(find.text('This machine is unavailable.'), findsOneWidget);
+ expect(find.text('Choose a machine'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await capture(
+ tester,
+ fixture,
+ 'recovery-machine-${brightness.name}-$removed',
+ );
+
+ // A genuine user activation ends composition; the inventory update
+ // above must leave it intact while the draft editor still owns it.
+ editor.clearComposing();
+ if (brightness == Brightness.dark) {
+ await _focus(tester, recovery);
+ await key(tester, LogicalKeyboardKey.enter);
+ } else {
+ await tester.tap(recovery);
+ }
+ await tester.pumpAndSettle();
+ expect(_chooser, findsOneWidget);
+ expect(_machine, findsOneWidget);
+ expect(tester.getRect(_chooser).top, greaterThanOrEqualTo(24));
+ expect(
+ tester.getRect(_chooser).bottom,
+ lessThanOrEqualTo(tester.view.physicalSize.height - 24),
+ );
+ final remoteChoice = find.byKey(
+ const ValueKey('new-harness-machine-option-remote'),
+ );
+ expect(remoteChoice.hitTestable(), findsOneWidget);
+ await capture(
+ tester,
+ fixture,
+ 'recovery-machine-menu-${brightness.name}-$removed',
+ );
+ await tester.tap(remoteChoice);
+ await tester.pumpAndSettle();
+ expect(fixture.box.machineId, 'remote');
+ final project = find.byKey(
+ const ValueKey(
+ 'new-harness-option-project:remote:/srv/recovery-repo',
+ ),
+ );
+ await tester.ensureVisible(project);
+ await tester.tap(project);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(fixture.box.project.folder, '/srv/recovery-repo');
+ expect(fixture.box.task, taskDraft);
+ expect(fixture.box.requiredChoice, isNull);
+ expect(
+ tester.widget<FilledButton>(_field('start')).onPressed,
+ isNotNull,
+ );
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+ }
+
+ for (final (size, scale, name) in [
+ (const Size(1200, 800), 1.0, 'wide'),
+ (const Size(600, 520), 1.6, 'narrow'),
+ ]) {
+ testWidgets(
+ 'a long branch keeps one baseline with Worktree in $name layout',
+ (tester) async {
+ const branch =
+ 'feature/refine-machine-and-repository-choice-with-a-very-long-branch-name';
+ final fixture = await _mount(
+ tester,
+ size: size,
+ scale: scale,
+ branchNames: ['main', branch],
+ );
+ await _focus(tester, _field('branch'));
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, branch);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final worktreeBounds = tester.getRect(_field('worktree'));
+ final branchBounds = tester.getRect(_field('branch'));
+ expect(worktreeBounds.center.dy, closeTo(branchBounds.center.dy, 1));
+ expect(worktreeBounds.right, lessThanOrEqualTo(branchBounds.left));
+ expect(_field('branch').hitTestable(), findsOneWidget);
+ final branchText = tester.widget<Text>(
+ find.descendant(of: _field('branch'), matching: find.byType(Text)),
+ );
+ expect(branchText.maxLines, 1);
+ expect(branchText.data, startsWith('…'));
+ expect(branch.endsWith(branchText.data!.substring(1)), isTrue);
+ expect(branchText.semanticsLabel, contains(branch));
+ await tester.tap(_field('worktree'));
+ await tester.pumpAndSettle();
+ expect(find.text('Worktree'), findsOneWidget);
+ expect(tester.getRect(_field('worktree')), worktreeBounds);
+ expect(tester.getRect(_field('branch')), branchBounds);
+ expect(fixture.box.branchRef, 'refs/heads/$branch');
+ expect(fixture.box.worktree, isFalse);
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ await capture(tester, fixture, 'long-branch-$name');
+ },
+ );
+ }
+
+ testWidgets(
+ 'every visible control takes one Tab stop with no hidden options',
+ (tester) async {
+ final fixture = await _mount(tester);
+ final cycle = [
+ _field('model'),
+ _field('approvals'),
+ _field('profile'),
+ _field('worktree'),
+ _field('branch'),
+ _close,
+ _field('start'),
+ _field('agent'),
+ _field('project'),
+ _task,
+ ];
+ expect(_focused(tester, _task), isTrue);
+ for (final target in cycle) {
+ await key(tester, LogicalKeyboardKey.tab);
+ await tester.pumpAndSettle();
+ expect(
+ _focused(tester, target),
+ isTrue,
+ reason:
+ 'Expected $target; focus is '
+ '${FocusManager.instance.primaryFocus?.debugLabel}',
+ );
+ }
+ for (final target in cycle.reversed.skip(1)) {
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ await tester.pumpAndSettle();
+ expect(_focused(tester, target), isTrue);
+ }
+ expect(_chooser, findsNothing);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ testWidgets('direct controls expose names and the worktree checked state', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ final semantics = tester.ensureSemantics();
+ for (final label in [
+ 'Agent, Codex',
+ 'Repo, office:/work/autonomous-harness',
+ 'Model, OpenAI',
+ 'Approvals, Auto-approve',
+ 'Profile, Default',
+ ]) {
+ final node = tester.getSemantics(find.bySemanticsLabel(label));
+ expect(node.getSemanticsData().hasAction(ui.SemanticsAction.tap), isTrue);
+ }
+ var worktree = tester.getSemantics(_field('worktree')).getSemanticsData();
+ expect(worktree.flagsCollection.isChecked, ui.CheckedState.isTrue);
+ await _focus(tester, _field('worktree'));
+ await key(tester, LogicalKeyboardKey.space);
+ await tester.pumpAndSettle();
+ worktree = tester.getSemantics(_field('worktree')).getSemanticsData();
+ expect(worktree.flagsCollection.isChecked, ui.CheckedState.isFalse);
+ expect(fixture.box.worktree, isFalse);
+ expect(fixture.app.launches, isEmpty);
+ semantics.dispose();
+ });
+
+ testWidgets(
+ 'initial Return creates an empty session with reviewed defaults',
+ (tester) async {
+ final fixture = await _mount(tester);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ final launch = fixture.app.launches.single;
+ expect(launch['machine'], 'review');
+ expect(launch['engine'], 'codex');
+ expect(launch['prompt'], isNull);
+ expect(launch['permissions'], 'auto');
+ final folder = launch['projectFolder']! as ProjectFolderRequest;
+ expect(folder.gitSource, '/work/autonomous-harness');
+ expect(folder.createsWorktree, isTrue);
+ expect(folder.branchRef, 'refs/heads/main');
+ expect(fixture.closes, 0);
+ },
+ );
+
+ testWidgets(
+ 'editor Shift-Enter stays multiline and Return sends the exact draft',
+ (tester) async {
+ final fixture = await _mount(tester);
+ const task =
+ 'Explore the current flow.\nThen discuss a plan — no changes yet.';
+ await tester.enterText(_task, task);
+ await key(tester, LogicalKeyboardKey.enter, shift: true);
+ expect(fixture.app.launches, isEmpty);
+ expect(_focused(tester, _task), isTrue);
+ // Native text insertion is owned by the editing channel, not sendKeyEvent.
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: '$task\n',
+ selection: TextSelection.collapsed(offset: task.length + 1),
+ ),
+ );
+ await tester.pump();
+ expect(fixture.box.task, '$task\n');
+ const completeTask = '$task\nCompare the alternatives.';
+ await tester.enterText(_task, completeTask);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ expect(fixture.app.launches.single['prompt'], completeTask);
+ },
+ );
+
+ testWidgets('unlabelled launch button retains editor keys and remapping', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ Finder hint(String label) =>
+ find.descendant(of: _field('start'), matching: find.text(label));
+ expect(hint('↵'), findsNothing);
+ await tester.tap(_task);
+ await tester.pumpAndSettle();
+ expect(hint('↵'), findsNothing);
+ expect(hint('⌘↵'), findsNothing);
+ await key(tester, LogicalKeyboardKey.enter, shift: true);
+ expect(fixture.app.launches, isEmpty);
+
+ fixture.map.apply(
+ '{"bindings":[{"keys":"cmd+enter","command":null,"when":"picker"}]}',
+ );
+ await tester.pumpAndSettle();
+ expect(hint('⌘↵'), findsNothing);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(fixture.app.launches, isEmpty);
+
+ fixture.map.apply(
+ '{"bindings":[{"keys":"f8","command":"picker.add_here","when":"picker"},'
+ '{"keys":"cmd+enter","command":null,"when":"picker"}]}',
+ );
+ await tester.pumpAndSettle();
+ expect(hint('F8'), findsNothing);
+ await key(tester, LogicalKeyboardKey.f8);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ expect(fixture.app.launches.single['prompt'], isNull);
+ });
+
+ testWidgets(
+ 'each menu dismisses by mouse without dismissing or editing the form',
+ (tester) async {
+ final fixture = await _mount(tester);
+ const draft = 'Keep this while exploring the settings';
+ await tester.enterText(_task, draft);
+ for (final trigger in [
+ _field('agent'),
+ _field('project'),
+ _field('model'),
+ _field('approvals'),
+ _field('profile'),
+ _field('branch'),
+ ]) {
+ await tester.tap(trigger);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsOneWidget);
+ await tester.tapAt(const Offset(30, 30));
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing, reason: '$trigger closes one level');
+ expect(_focused(tester, trigger), isTrue);
+ expect(fixture.closes, 0);
+ expect(fixture.box.task, draft);
+ expect(fixture.app.launches, isEmpty);
+ }
+ await tester.tapAt(const Offset(10, 10));
+ await tester.pumpAndSettle();
+ expect(fixture.closes, 1);
+ expect(fixture.box.draft.task, draft);
+ },
+ );
+
+ testWidgets(
+ 'approval and branch choices require a separate launch activation',
+ (tester) async {
+ final fixture = await _mount(tester);
+ await _focus(tester, _field('approvals'));
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Approves routine actions in the sandbox'),
+ findsOneWidget,
+ );
+ expect(find.text('No approvals and no sandbox. Risky'), findsOneWidget);
+ await capture(tester, fixture, 'approval-options-dark');
+ await tester.enterText(_query, 'Full access');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(fixture.box.mode, 'full');
+ expect(_focused(tester, _field('approvals')), isTrue);
+ expect(fixture.app.launches, isEmpty);
+
+ await _focus(tester, _field('worktree'));
+ await key(tester, LogicalKeyboardKey.space);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(_focused(tester, _field('branch')), isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, 'feature/review');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(_focused(tester, _field('branch')), isTrue);
+ expect(fixture.app.launches, isEmpty);
+ await tester.tap(_field('start'));
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ final launch = fixture.app.launches.single;
+ expect(launch['permissions'], 'full');
+ final folder = launch['projectFolder']! as ProjectFolderRequest;
+ expect(folder.createsWorktree, isFalse);
+ expect(folder.branchRef, 'refs/heads/feature/review');
+ },
+ );
+
+ testWidgets(
+ 'switching agents removes inapplicable controls and their Tab stops',
+ (tester) async {
+ final fixture = await _mount(tester);
+ await tester.enterText(_task, 'Keep a draft while changing agents');
+ await tester.tap(_field('agent'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('new-harness-option-claude')));
+ await tester.pumpAndSettle();
+ expect(_field('profile'), findsNothing);
+ expect(_field('model'), findsOneWidget);
+ expect(_field('approvals'), findsOneWidget);
+ await _focus(tester, _field('approvals'));
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(_focused(tester, _field('worktree')), isTrue);
+
+ await tester.tap(_field('agent'));
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, 'Terminal');
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-option-terminal')),
+ );
+ await tester.pumpAndSettle();
+ expect(fixture.box.engine, 'terminal');
+ for (final name in [
+ 'model',
+ 'approvals',
+ 'profile',
+ 'worktree',
+ 'branch',
+ ]) {
+ expect(_field(name), findsNothing);
+ }
+ expect(tester.widget<TextField>(_task).readOnly, isTrue);
+ await _focus(tester, _field('project'));
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(_focused(tester, _close), isTrue);
+ expect(fixture.box.task, 'Keep a draft while changing agents');
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'Open Folder invokes the picker directly and cancellation keeps context',
+ (tester) async {
+ var browses = 0;
+ var accept = false;
+ final fixture = await _mount(
+ tester,
+ onBrowse: (fixture) {
+ browses++;
+ expect(fixture.box.machineId, 'review');
+ if (accept) fixture.box.setFolder('/work/another-repo');
+ },
+ );
+ await tester.enterText(
+ _task,
+ 'Preserve the draft through native browsing',
+ );
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ final open = find.byKey(
+ const ValueKey('new-harness-option-project:existing'),
+ );
+ expect(
+ find.descendant(of: open, matching: find.text('Open Folder…')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: open, matching: find.byIcon(AppIcons.chevronRight)),
+ findsNothing,
+ reason: 'The native picker opens directly instead of a submenu',
+ );
+ await tester.tap(open);
+ await tester.pumpAndSettle();
+ expect(browses, 1);
+ expect(_chooser, findsOneWidget);
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(fixture.box.project.folder, '/work/autonomous-harness');
+ accept = true;
+ await tester.tap(open);
+ await tester.pumpAndSettle();
+ expect(browses, 2);
+ expect(_chooser, findsNothing);
+ expect(fixture.box.project.folder, '/work/another-repo');
+ expect(_focused(tester, _field('project')), isTrue);
+ expect(fixture.box.task, 'Preserve the draft through native browsing');
+ expect(fixture.closes, 0);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ testWidgets('folder browsing can retry after failure from its path prompt', (
+ tester,
+ ) async {
+ var browses = 0;
+ final fixture = await _mount(
+ tester,
+ onBrowse: (fixture) {
+ browses++;
+ if (browses == 1) throw const FileSystemException('Synthetic failure');
+ if (browses == 3) fixture.box.setFolder('/work/retry-repo');
+ },
+ );
+ fixture.map.apply(
+ '{"bindings":[{"keys":"f7","command":"creation.project_browse","when":"picker"}]}',
+ );
+ await tester.enterText(_task, 'Keep this question through folder recovery');
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-option-project:existing')),
+ );
+ await tester.pumpAndSettle();
+ expect(browses, 1);
+ expect(fixture.box.field, NewHarnessField.project);
+ expect(find.text('Could not browse folders. Try again.'), findsWidgets);
+ expect(_focused(tester, _query), isTrue);
+
+ // A failed native picker leaves a usable path prompt. Its browse shortcut
+ // retries that prompt directly, instead of opening another machine step.
+ await key(tester, LogicalKeyboardKey.f7);
+ await tester.pumpAndSettle();
+ expect(browses, 2);
+ expect(fixture.box.field, NewHarnessField.project);
+ expect(_chooser, findsOneWidget);
+ expect(_focused(tester, _query), isTrue);
+ expect(fixture.box.project.folder, '/work/autonomous-harness');
+
+ await key(tester, LogicalKeyboardKey.f7);
+ await tester.pumpAndSettle();
+ expect(browses, 3);
+ expect(_chooser, findsNothing);
+ expect(fixture.box.project.folder, '/work/retry-repo');
+ expect(fixture.box.task, 'Keep this question through folder recovery');
+ expect(fixture.closes, 0);
+ expect(fixture.app.launches, isEmpty);
+ });
+
+ testWidgets(
+ 'a footer menu opens above its control when the draft grows tall',
+ (tester) async {
+ final fixture = await _mount(
+ tester,
+ size: const Size(900, 1000),
+ scale: 1.4,
+ branchNames: [
+ 'main',
+ 'feature/review',
+ for (var i = 0; i < 20; i++) 'feature/iteration-$i',
+ ],
+ );
+ const draft =
+ 'First, inspect the current flow.\n'
+ 'Discuss the constraints.\n'
+ 'Compare the possible designs.\n'
+ 'Keep existing shortcuts.\n'
+ 'Make cancellation predictable.\n'
+ 'Check the resulting interaction.\n'
+ 'Then tell me what you recommend.';
+ await tester.enterText(_task, draft);
+ await _focus(tester, _field('branch'));
+ final branch = tester.getRect(_field('branch'));
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final menu = tester.getRect(_chooser);
+ expect(menu.bottom, closeTo(branch.top - 8, 1));
+ expect(menu.top, greaterThanOrEqualTo(36));
+ expect(menu.right, lessThanOrEqualTo(864));
+ expect(_query.hitTestable(), findsOneWidget);
+ await tester.enterText(_query, 'feature/review');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(_focused(tester, _field('branch')), isTrue);
+ expect(fixture.box.branchRef, 'refs/heads/feature/review');
+ expect(fixture.box.task, draft);
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ for (final git in [true, false]) {
+ testWidgets('Terminal Options shortcut reaches Repo for git=$git', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester, engine: 'terminal', git: git);
+ fixture.map.apply(
+ '{"bindings":[{"keys":"f7","command":"creation.options","when":"picker"}]}',
+ );
+ await key(tester, LogicalKeyboardKey.f7);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsOneWidget);
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(
+ find.byKey(const ValueKey('new-harness-option-project:existing')),
+ findsOneWidget,
+ );
+ expect(_focused(tester, _query), isTrue);
+ expect(_field('model'), findsNothing);
+ expect(_field('branch'), findsNothing);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(_focused(tester, _field('project')), isTrue);
+
+ // The older default shortcut follows the same visible fallback.
+ await key(tester, LogicalKeyboardKey.period, cmd: true);
+ await tester.pumpAndSettle();
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(_chooser, findsOneWidget);
+ expect(fixture.closes, 0);
+ expect(fixture.app.launches, isEmpty);
+ });
+ }
+
+ testWidgets(
+ 'restored drafts keep text and settings visible and focus the editor',
+ (tester) async {
+ final original = await _mount(tester);
+ await tester.enterText(_task, 'A saved question, ready to continue');
+ await tester.tap(_field('worktree'));
+ await tester.tap(_field('profile'));
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-option-profile:/profiles/work')),
+ );
+ await tester.pumpAndSettle();
+ final draft = original.box.draft;
+ await tester.pumpWidget(const SizedBox());
+ final restored = await _mount(tester, draft: draft);
+ expect(_focused(tester, _task), isTrue);
+ expect(tester.widget<TextField>(_task).controller!.text, draft.task);
+ expect(restored.box.worktree, isFalse);
+ expect(restored.box.profileLabel, 'Work');
+ expect(find.text('Work'), findsOneWidget);
+ expect(_field('profile'), findsOneWidget);
+ expect(_field('branch'), findsOneWidget);
+ expect(restored.app.launches, isEmpty);
+ },
+ );
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.6]) {
+ testWidgets(
+ 'long controls remain reachable at 600x520 ${brightness.name} scale=$scale',
+ (tester) async {
+ final fixture = await _mount(
+ tester,
+ machineName: 'Office Mac development workstation with a long name',
+ folder: '/work/a-repository-with-a-long-but-recognizable-name',
+ size: const Size(600, 520),
+ scale: scale,
+ brightness: brightness,
+ );
+ expect(tester.takeException(), isNull);
+ expect(tester.getSize(_surface).width, lessThanOrEqualTo(552));
+ await tester.enterText(
+ _task,
+ 'A question with enough text to span several lines in a narrow '
+ 'window. Preserve the same controls at enlarged text sizes.',
+ );
+ for (final control in [
+ _field('model'),
+ _field('approvals'),
+ _field('profile'),
+ _field('worktree'),
+ _field('branch'),
+ _field('start'),
+ ]) {
+ await _focus(tester, control);
+ await tester.ensureVisible(control);
+ await tester.pumpAndSettle();
+ expect(control.hitTestable(), findsOneWidget);
+ final rect = tester.getRect(control);
+ expect(rect.left, greaterThanOrEqualTo(24));
+ expect(rect.right, lessThanOrEqualTo(576));
+ expect(tester.takeException(), isNull);
+ }
+ await capture(tester, fixture, 'narrow-${brightness.name}-$scale');
+ await tester.ensureVisible(_field('project'));
+ await tester.pumpAndSettle();
+ expect(_field('project').hitTestable(), findsOneWidget);
+ await capture(
+ tester,
+ fixture,
+ 'narrow-project-${brightness.name}-$scale',
+ );
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ await tester.tap(_machine);
+ await tester.pumpAndSettle();
+ final local = find.byKey(
+ const ValueKey('new-harness-machine-option-review'),
+ );
+ final bounds = tester.getRect(local);
+ expect(bounds.left, greaterThanOrEqualTo(0));
+ expect(bounds.right, lessThanOrEqualTo(600));
+ expect(bounds.bottom, lessThanOrEqualTo(520));
+ expect(local.hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await capture(
+ tester,
+ fixture,
+ 'narrow-machine-${brightness.name}-$scale',
+ );
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+ }
+ }
+}
diff --git a/desktop/test/desktop_dialog_interaction_test.dart b/desktop/test/desktop_dialog_interaction_test.dart
new file mode 100644
index 000000000..9351ec09c
--- /dev/null
+++ b/desktop/test/desktop_dialog_interaction_test.dart
@@ -0,0 +1,1308 @@
+import 'dart:async';
+
+import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/desktop_search_panel.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/ws/ws_conn.dart';
+import 'package:xterm/xterm.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' show mount, native, nativeChannel;
+import 'support/launch_menu.dart' show focusLaunchRow, openLaunchRow;
+import 'support/mixed_agents.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+// These scenarios run the actual workspace overlays and native method-channel
+// dispatch. The only transport is this in-memory fixture: no user state or
+// running daemon is involved.
+class _DialogConnection extends WsConn {
+ _DialogConnection(String machine)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: machine,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final starts = <Map<String, dynamic>>[];
+ Completer<Map<String, dynamic>>? pendingStart;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ switch (type) {
+ case 'engines_probe':
+ return {
+ 'engines': [
+ {'engine': 'codex', 'installed': true, 'supportsCodexHome': true},
+ {'engine': 'claude', 'installed': true},
+ ],
+ };
+ case 'dsh_list':
+ return {'dsh': []};
+ case 'codex_profiles_list':
+ return {
+ 'profiles': [
+ {'path': '/profiles/work', 'label': 'Work'},
+ ],
+ };
+ case 'fs_list_dir':
+ return {'path': payload['path'] ?? '/work', 'entries': []};
+ case 'agent_create':
+ starts.add(Map.of(payload));
+ if (pendingStart case final pending?) return pending.future;
+ throw const WsRequestFailure(
+ responseType: 'agent_create_result',
+ code: 'INVALID_ENGINE',
+ detail: 'Fixture launch declined.',
+ );
+ default:
+ return {};
+ }
+ }
+}
+
+class _Workspace {
+ _Workspace(this.app, this.keymap, this.connections, this.input, this.folders);
+
+ final AppNotifier app;
+ final MemoryKeymap keymap;
+ final Map<String, _DialogConnection> connections;
+ final List<TerminalBinaryFrame> input;
+ final _FolderPicker folders;
+
+ Iterable<Map<String, dynamic>> get starts =>
+ connections.values.expand((connection) => connection.starts);
+}
+
+class _FolderPicker extends FileSelectorPlatform {
+ int opened = 0;
+ Completer<String?>? pending;
+
+ @override
+ Future<String?> getDirectoryPath({
+ String? initialDirectory,
+ String? confirmButtonText,
+ }) {
+ opened++;
+ return pending?.future ?? Future.value(null);
+ }
+}
+
+final _form = find.byType(NewHarnessForm);
+final _task = find.byKey(const ValueKey('new-harness-task'));
+final _query = find.byKey(const ValueKey('new-harness-query'));
+final _chooser = find.byKey(const ValueKey('new-harness-chooser-surface'));
+final _search = find.byKey(const ValueKey('swarm-search-input'));
+
+NewHarnessController _box(WidgetTester tester) =>
+ tester.widget<NewHarnessForm>(_form).controller;
+
+bool _ownsFocus(WidgetTester tester, Finder finder) {
+ final element = tester.element(finder);
+ var owned = FocusManager.instance.primaryFocus?.context == element;
+ FocusManager.instance.primaryFocus?.context?.visitAncestorElements((parent) {
+ if (parent == element) owned = true;
+ return !owned;
+ });
+ return owned;
+}
+
+Future<_Workspace> _mount(
+ WidgetTester tester, {
+ bool nativeMenus = false,
+ // Cmd-N above a terminal exercises the popup. Empty tabs now embed it.
+ bool withTerminal = true,
+ String? bindings,
+}) async {
+ final previousEntry = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = previousEntry);
+ final previousFolderPicker = FileSelectorPlatform.instance;
+ final folders = _FolderPicker();
+ FileSelectorPlatform.instance = folders;
+ addTearDown(() => FileSelectorPlatform.instance = previousFolderPicker);
+ final connections = <String, _DialogConnection>{};
+ final app = createApp(
+ connectionForTest: (machine) =>
+ connections.putIfAbsent(machine, () => _DialogConnection(machine)),
+ );
+ final map = MemoryKeymap();
+ if (bindings != null) map.apply(bindings);
+ addTearDown(app.dispose);
+ addTearDown(map.dispose);
+ seedMixedAgents(app);
+ app.machineStates['m']!.localOnly = true;
+ app.gitProjectReaderForTest = (_, _) async => {
+ 'isGit': true,
+ 'branch': 'main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ {'ref': 'refs/heads/feature', 'name': 'feature'},
+ ],
+ };
+ await app.agentPreference.remember('codex');
+ await app.projectHistory.select('m', '/work/openharness');
+ final input = <TerminalBinaryFrame>[];
+ if (withTerminal) app.adoptSessionForTest(terminal('a0', input));
+ if (nativeMenus) {
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ (_) async => null,
+ );
+ addTearDown(() {
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ null,
+ );
+ });
+ }
+ await mount(tester, app, map, native: nativeMenus);
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump();
+ });
+ return _Workspace(app, map, connections, input, folders);
+}
+
+Future<void> _new(WidgetTester tester) async {
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pumpAndSettle();
+ expect(_form, findsOneWidget);
+ // These journeys start from the visible editor. The launch-entry suite
+ // independently verifies the empty dialog's initial prompt focus.
+ await _tabTo(tester, _task);
+}
+
+Future<void> _nativeCommand(WidgetTester tester, String command) async {
+ final dispatched = native(tester, 'keymapCommand', {'command': command});
+ await tester.pump();
+ await dispatched;
+ await tester.pump();
+}
+
+Future<void> _tabTo(WidgetTester tester, Finder target) async {
+ for (var i = 0; i < 50 && !_ownsFocus(tester, target); i++) {
+ await key(tester, LogicalKeyboardKey.tab);
+ }
+ expect(
+ _ownsFocus(tester, target),
+ isTrue,
+ reason: 'The visible control must be reachable without the pointer.',
+ );
+}
+
+const _nativeSmokeJourneys = {
+ 'Tab reaches the visible editor and Shift-Return never launches',
+ 'Tab and Shift-Tab remain inside the composer and reach controls',
+ 'Space opens a focused chooser without starting',
+ 'Return opens a focused chooser without starting',
+ 'agent and repo appear in order above the composer',
+ 'Tab leaves a chooser without applying its highlight',
+ 'Shift-Tab leaves a chooser without applying its highlight',
+ 'Escape closes only the chooser and returns to its control',
+ 'outside click closes only the chooser and returns to its control',
+ 'Cmd-P and Cmd-N replace each other without losing the composer',
+ 'focused Cmd-P preview control owns Return',
+ 'Return on Close search restores terminal focus without opening a result',
+};
+
+void main({bool nativeSmoke = false}) {
+ void journey(String description, Future<void> Function(WidgetTester) body) {
+ if (nativeSmoke && !_nativeSmokeJourneys.contains(description)) return;
+ testWidgets(
+ description,
+ body,
+ timeout: nativeSmoke ? const Timeout(Duration(seconds: 45)) : null,
+ );
+ }
+
+ journey('Tab reaches the visible editor and Shift-Return never launches', (
+ tester,
+ ) async {
+ final workspace = await _mount(tester, withTerminal: true);
+ await _new(tester);
+ expect(_ownsFocus(tester, _task), isTrue);
+ await tester.enterText(_task, 'Review keyboard navigation');
+ await key(tester, LogicalKeyboardKey.enter, shift: true);
+ expect(workspace.starts, isEmpty);
+ expect(workspace.input, isEmpty);
+ expect(_form, findsOneWidget);
+ expect(_ownsFocus(tester, _task), isTrue);
+ });
+
+ journey('Tab and Shift-Tab remain inside the composer and reach controls', (
+ tester,
+ ) async {
+ await _mount(tester, withTerminal: true);
+ await _new(tester);
+ final seen = <String>{};
+ for (var i = 0; i < 32; i++) {
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ _ownsFocus(tester, _form),
+ isTrue,
+ reason:
+ 'Tab $i must stay in the dialog; focus is '
+ '${FocusManager.instance.primaryFocus?.debugLabel}.',
+ );
+ for (final field in ['project', 'agent', 'model', 'approvals', 'start']) {
+ if (_ownsFocus(
+ tester,
+ find.byKey(ValueKey('new-harness-field-$field')),
+ )) {
+ seen.add(field);
+ }
+ }
+ }
+ expect(
+ seen,
+ containsAll(['project', 'agent', 'model', 'approvals', 'start']),
+ );
+ for (var i = 0; i < 20; i++) {
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(
+ _ownsFocus(tester, _form),
+ isTrue,
+ reason: 'Reverse traversal must stay in the same dialog.',
+ );
+ }
+ });
+
+ for (final activation in [
+ LogicalKeyboardKey.space,
+ LogicalKeyboardKey.enter,
+ ]) {
+ journey(
+ '${activation == LogicalKeyboardKey.space ? 'Space' : 'Return'} opens a focused chooser without starting',
+ (tester) async {
+ final workspace = await _mount(tester);
+ await _new(tester);
+ await focusLaunchRow(tester, 'agent');
+ await key(tester, activation);
+ expect(_chooser, findsOneWidget);
+ expect(_ownsFocus(tester, _query), isTrue);
+ expect(workspace.starts, isEmpty);
+ },
+ );
+ }
+
+ journey('agent and repo appear in order above the composer', (tester) async {
+ await _mount(tester);
+ await _new(tester);
+ final agent = find.byKey(const ValueKey('new-harness-field-agent'));
+ final machine = find.byKey(const ValueKey('new-harness-machine'));
+ final project = find.byKey(const ValueKey('new-harness-field-project'));
+ expect(machine, findsNothing);
+ expect(tester.getTopLeft(agent).dy, tester.getTopLeft(project).dy);
+ expect(
+ tester.getTopRight(agent).dx,
+ lessThan(tester.getTopLeft(project).dx),
+ );
+ expect(
+ tester.getBottomLeft(project).dy,
+ lessThan(tester.getTopLeft(_task).dy),
+ );
+ });
+
+ for (final reverse in [false, true]) {
+ journey(
+ '${reverse ? 'Shift-Tab' : 'Tab'} leaves a chooser without applying its highlight',
+ (tester) async {
+ final workspace = await _mount(tester);
+ await _new(tester);
+ await openLaunchRow(tester, 'agent');
+ final box = _box(tester);
+ final engine = box.engine;
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.tab, shift: reverse);
+ expect(_chooser, findsNothing);
+ expect(box.engine, engine);
+ expect(
+ _ownsFocus(
+ tester,
+ find.byKey(
+ ValueKey(
+ reverse
+ ? 'new-harness-field-start'
+ : 'new-harness-field-project',
+ ),
+ ),
+ ),
+ isTrue,
+ );
+ expect(workspace.starts, isEmpty);
+ },
+ );
+ }
+
+ for (final dismissal in ['Escape', 'outside click']) {
+ journey('$dismissal closes only the chooser and returns to its control', (
+ tester,
+ ) async {
+ final workspace = await _mount(tester);
+ await _new(tester);
+ const task = 'Keep this task while I inspect another agent';
+ await tester.enterText(_task, task);
+ final original = _box(tester);
+ final engine = original.engine;
+ await openLaunchRow(tester, 'agent');
+ await tester.enterText(_query, 'cla');
+ if (dismissal == 'Escape') {
+ await key(tester, LogicalKeyboardKey.escape);
+ } else {
+ await tester.tapAt(const Offset(10, 400));
+ await tester.pump();
+ }
+ expect(_form, findsOneWidget);
+ expect(_box(tester), same(original));
+ expect(_chooser, findsNothing);
+ expect(original.task, task);
+ expect(original.engine, engine);
+ expect(original.query, isEmpty);
+ expect(tester.widget<TextField>(_task).controller!.text, task);
+ expect(
+ _ownsFocus(
+ tester,
+ find.byKey(const ValueKey('new-harness-field-agent')),
+ ),
+ isTrue,
+ reason: 'Cancel returns to the control that opened the chooser.',
+ );
+ expect(workspace.starts, isEmpty);
+ });
+ }
+
+ journey('accepting an agent preserves the task and does not submit it', (
+ tester,
+ ) async {
+ final workspace = await _mount(tester);
+ await _new(tester);
+ await tester.enterText(_task, 'Keep the draft when changing agents');
+ await openLaunchRow(tester, 'agent');
+ await tester.enterText(_query, 'Claude');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(_chooser, findsNothing);
+ expect(_box(tester).engine, 'claude');
+ expect(_box(tester).task, 'Keep the draft when changing agents');
+ expect(workspace.starts, isEmpty);
+ expect(_form, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ workspace.starts,
+ isEmpty,
+ reason: 'A quick second Return after choosing must not submit the task.',
+ );
+ });
+
+ for (final field in [
+ 'machine',
+ 'project',
+ 'model',
+ 'approvals',
+ 'branch',
+ 'profile',
+ ]) {
+ journey('outside-click dismissal preserves the $field chooser owner', (
+ tester,
+ ) async {
+ final workspace = await _mount(tester);
+ await _new(tester);
+ await tester.enterText(_task, 'Inspect $field without losing this task');
+ final box = _box(tester);
+ final task = box.task;
+ final opener = find.byKey(
+ ValueKey(
+ field == 'machine'
+ ? 'new-harness-field-project'
+ : 'new-harness-field-$field',
+ ),
+ );
+ await tester.tap(opener);
+ await tester.pump();
+ if (field == 'machine') {
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-repo-machine')),
+ );
+ await tester.pump();
+ }
+ expect(_chooser, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(
+ workspace.starts,
+ isEmpty,
+ reason: 'The global Start chord must not accept and launch a chooser.',
+ );
+ await tester.tapAt(const Offset(10, 400));
+ await tester.pump();
+ if (field == 'machine') {
+ expect(_chooser, findsOneWidget);
+ await tester.tapAt(const Offset(10, 400));
+ await tester.pump();
+ }
+ expect(_form, findsOneWidget);
+ expect(_chooser, findsNothing);
+ expect(_box(tester), same(box));
+ expect(box.task, task);
+ expect(_ownsFocus(tester, opener), isTrue);
+ expect(workspace.starts, isEmpty);
+ });
+ }
+
+ for (final (action, prompt) in [
+ (NewHarnessController.newProjectId, NewHarnessField.projectName),
+ (NewHarnessController.repositoryId, NewHarnessField.projectRepository),
+ ]) {
+ journey('$action uses the selected machine and Escape returns one level', (
+ tester,
+ ) async {
+ final workspace = await _mount(tester);
+ await _new(tester);
+ await tester.enterText(_task, 'Keep my work while exploring projects');
+ final box = _box(tester);
+ final originalProject = box.project;
+ final machine = box.machineId;
+ await openLaunchRow(tester, 'project');
+ await tester.tap(find.byKey(ValueKey('new-harness-option-$action')));
+ await tester.pump();
+ expect(
+ box.field,
+ prompt,
+ reason: 'Machine was already chosen in the composer context row.',
+ );
+ expect(box.machineId, machine);
+ expect(_chooser, findsOneWidget);
+ expect(_ownsFocus(tester, _query), isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(_chooser, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(_chooser, findsNothing);
+ expect(_form, findsOneWidget);
+ expect(box.project, originalProject);
+ expect(box.task, 'Keep my work while exploring projects');
+ expect(
+ _ownsFocus(
+ tester,
+ find.byKey(const ValueKey('new-harness-field-project')),
+ ),
+ isTrue,
+ );
+ expect(workspace.starts, isEmpty);
+ });
+ }
+
+ for (final path in <String?>[null, '/work/picked-repo']) {
+ journey(
+ 'Open Folder goes directly to the native picker (${path == null ? 'cancel' : 'choose'})',
+ (tester) async {
+ final workspace = await _mount(tester);
+ await _new(tester);
+ await tester.enterText(
+ _task,
+ 'Keep this message while choosing a repo',
+ );
+ final box = _box(tester);
+ final project = box.project;
+ workspace.folders.pending = Completer<String?>();
+ await openLaunchRow(tester, 'project');
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-option-project:existing')),
+ );
+ await tester.pump();
+ expect(workspace.folders.opened, 1);
+ expect(workspace.starts, isEmpty);
+ workspace.folders.pending!.complete(path);
+ await tester.pumpAndSettle();
+ expect(box.task, 'Keep this message while choosing a repo');
+ expect(box.machineId, 'm');
+ if (path == null) {
+ expect(box.project, project);
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(_chooser, findsOneWidget);
+ expect(_ownsFocus(tester, _query), isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ } else {
+ expect(box.project.folder, path);
+ expect(_chooser, findsNothing);
+ }
+ expect(_form, findsOneWidget);
+ expect(
+ _ownsFocus(
+ tester,
+ find.byKey(const ValueKey('new-harness-field-project')),
+ ),
+ isTrue,
+ );
+ expect(workspace.starts, isEmpty);
+ },
+ );
+ }
+
+ for (final dismissal in ['Escape', 'outside click']) {
+ journey('composer closes on $dismissal and restores its draft on reopen', (
+ tester,
+ ) async {
+ await _mount(tester);
+ await _new(tester);
+ const task = 'Unfinished review with a meaningful draft';
+ await tester.enterText(_task, task);
+ if (dismissal == 'Escape') {
+ await key(tester, LogicalKeyboardKey.escape);
+ } else {
+ await tester.tapAt(const Offset(10, 400));
+ await tester.pump();
+ }
+ expect(_form, findsNothing);
+ await _new(tester);
+ expect(_box(tester).task, task);
+ expect(tester.widget<TextField>(_task).controller!.text, task);
+ expect(_ownsFocus(tester, _task), isTrue);
+ });
+ }
+
+ journey('Cmd-P and Cmd-N replace each other without losing the composer', (
+ tester,
+ ) async {
+ final workspace = await _mount(tester, withTerminal: true);
+ await _new(tester);
+ await tester.enterText(_task, 'Resume after checking existing work');
+ await openLaunchRow(tester, 'agent');
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ expect(_form, findsNothing);
+ expect(_search, findsOneWidget);
+ expect(_ownsFocus(tester, _search), isTrue);
+ await _new(tester);
+ expect(_search, findsNothing);
+ expect(_chooser, findsNothing);
+ expect(_box(tester).task, 'Resume after checking existing work');
+ expect(_ownsFocus(tester, _task), isTrue);
+ expect(workspace.input, isEmpty);
+ expect(workspace.starts, isEmpty);
+ });
+
+ journey(
+ 'long mixed mouse and keyboard setup keeps the draft and dismisses one level',
+ (tester) async {
+ final workspace = await _mount(tester, withTerminal: true);
+ await _new(tester);
+ const task =
+ 'Explore the API first.\nKeep the UI simple — then discuss it.';
+ await tester.enterText(_task, task);
+ final original = _box(tester);
+ final project = original.project;
+ final machine = original.machineId;
+ Finder field(String name) =>
+ find.byKey(ValueKey('new-harness-field-$name'));
+
+ void expectStableDraft() {
+ expect(_form, findsOneWidget);
+ expect(_box(tester), same(original));
+ expect(original.task, task);
+ expect(tester.widget<TextField>(_task).controller!.text, task);
+ expect(original.project, project);
+ expect(original.machineId, machine);
+ expect(workspace.starts, isEmpty);
+ expect(workspace.input, isEmpty);
+ expect(tester.takeException(), isNull);
+ }
+
+ Future<void> open(Finder opener, {required bool keyboard}) async {
+ if (keyboard) {
+ await _tabTo(tester, opener);
+ await key(tester, LogicalKeyboardKey.enter);
+ } else {
+ await tester.ensureVisible(opener);
+ await tester.tap(opener);
+ }
+ await tester.pumpAndSettle();
+ expect(_chooser, findsOneWidget);
+ expect(_ownsFocus(tester, _query), isTrue);
+ expectStableDraft();
+ }
+
+ Future<void> choose(
+ String id,
+ String query, {
+ required bool keyboard,
+ }) async {
+ await tester.enterText(_query, query);
+ await tester.pumpAndSettle();
+ if (keyboard) {
+ expect(original.selected?.id, id);
+ await key(tester, LogicalKeyboardKey.enter);
+ } else {
+ final option = find.byKey(ValueKey('new-harness-option-$id'));
+ await tester.ensureVisible(option);
+ await tester.tap(option);
+ }
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expectStableDraft();
+ }
+
+ final chosenModes = <String, String>{};
+ for (var round = 0; round < 4; round++) {
+ final keyboard = round.isOdd;
+ final engine = keyboard ? 'codex' : 'claude';
+ await open(field('agent'), keyboard: keyboard);
+ await choose(engine, engine, keyboard: !keyboard);
+ expect(original.engine, engine);
+ expect(original.mode, chosenModes[engine] ?? 'auto');
+ expect(field('profile'), keyboard ? findsOneWidget : findsNothing);
+
+ final (mode, modeLabel) = switch (round) {
+ 1 => ('full', 'Full access'),
+ 2 => ('auto', 'Auto-approve'),
+ _ => ('ask', 'Ask first'),
+ };
+ await open(field('approvals'), keyboard: !keyboard);
+ await choose(mode, modeLabel, keyboard: keyboard);
+ expect(original.mode, mode);
+ chosenModes[engine] = mode;
+
+ if (engine == 'codex') {
+ final profile = round == 1 ? '/profiles/work' : null;
+ await open(field('profile'), keyboard: keyboard);
+ await choose(
+ profile == null ? 'profile:default' : 'profile:$profile',
+ profile == null ? 'Default' : 'Work',
+ keyboard: !keyboard,
+ );
+ expect(original.draft.profile?.path, profile);
+ }
+
+ final model = original.modelLabel;
+ await open(field('model'), keyboard: !keyboard);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await tester.tapAt(const Offset(10, 400));
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(_ownsFocus(tester, field('model')), isTrue);
+ expect(original.modelLabel, model);
+ expectStableDraft();
+
+ final worktree = original.worktree;
+ if (keyboard) {
+ await _tabTo(tester, field('worktree'));
+ await key(tester, LogicalKeyboardKey.space);
+ } else {
+ await tester.tap(field('worktree'));
+ }
+ await tester.pumpAndSettle();
+ expect(original.worktree, !worktree);
+ expect(find.text('Worktree'), findsOneWidget);
+ final branch = original.worktree ? 'feature' : 'main';
+ await open(field('branch'), keyboard: keyboard);
+ await choose('refs/heads/$branch', branch, keyboard: !keyboard);
+ expect(original.branchRef, 'refs/heads/$branch');
+
+ await open(field('project'), keyboard: !keyboard);
+ final newFolder = find.byKey(
+ const ValueKey('new-harness-option-project:name'),
+ );
+ await tester.ensureVisible(newFolder);
+ await tester.tap(newFolder);
+ await tester.pumpAndSettle();
+ expect(original.field, NewHarnessField.projectName);
+ final folderDraft = 'scratch-round-$round';
+ await tester.enterText(_query, folderDraft);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(_query).controller!.text, folderDraft);
+ expect(_chooser, findsOneWidget);
+ expectStableDraft();
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-chooser-back')),
+ );
+ await tester.pumpAndSettle();
+ expect(original.field, NewHarnessField.projectMenu);
+ expect(_chooser, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(_ownsFocus(tester, field('project')), isTrue);
+ expectStableDraft();
+
+ final machineControl = find.byKey(
+ const ValueKey('new-harness-field-project'),
+ );
+ await open(machineControl, keyboard: keyboard);
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-repo-machine')),
+ );
+ await tester.pumpAndSettle();
+ expect(original.field, NewHarnessField.projectMenu);
+ expect(
+ find.byKey(const ValueKey('new-harness-machine-option-m')),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsOneWidget);
+ await tester.tapAt(const Offset(10, 400));
+ await tester.pumpAndSettle();
+ expect(_chooser, findsNothing);
+ expect(_ownsFocus(tester, machineControl), isTrue);
+ expectStableDraft();
+ }
+
+ final accepted = original.draft;
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.pumpAndSettle();
+ expect(_form, findsNothing);
+ expect(_ownsFocus(tester, _search), isTrue);
+ await tester.enterText(_search, 'review');
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await _new(tester);
+ final restored = _box(tester).draft;
+ expect(restored.task, task);
+ expect(restored.engine, accepted.engine);
+ expect(restored.machineId, accepted.machineId);
+ expect(restored.project, accepted.project);
+ expect(restored.permissionMode, accepted.permissionMode);
+ expect(restored.profile?.path, accepted.profile?.path);
+ expect(restored.worktree, accepted.worktree);
+ expect(restored.branchRef, accepted.branchRef);
+ expect(_ownsFocus(tester, _task), isTrue);
+ expect(_chooser, findsNothing);
+ expect(_search, findsNothing);
+ expect(workspace.starts, isEmpty);
+ expect(workspace.input, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ journey('remapped chooser keys and native cancel have the same hierarchy', (
+ tester,
+ ) async {
+ final workspace = await _mount(
+ tester,
+ nativeMenus: true,
+ bindings: '''{"bindings":[
+ {"keys":"ctrl+j","command":"picker.next","when":"picker"},
+ {"keys":"ctrl+k","command":"picker.previous","when":"picker"},
+ {"keys":"ctrl+g","command":"picker.cancel","when":"picker"}
+ ]}''',
+ );
+ await _new(tester);
+ await tester.enterText(_task, 'Native menu and keyboard should agree');
+ await openLaunchRow(tester, 'agent');
+ final box = _box(tester);
+ final initial = box.cursor;
+ await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
+ expect(box.cursor, isNot(initial));
+ await key(tester, LogicalKeyboardKey.keyK, ctrl: true);
+ expect(box.cursor, initial);
+ await _nativeCommand(tester, 'picker.cancel');
+ expect(_chooser, findsNothing);
+ expect(_form, findsOneWidget);
+ expect(box.task, 'Native menu and keyboard should agree');
+ await key(tester, LogicalKeyboardKey.keyG, ctrl: true);
+ expect(_form, findsNothing);
+ expect(workspace.starts, isEmpty);
+ });
+
+ for (final (command, field) in [
+ ('creation.agent', NewHarnessField.harness),
+ ('creation.project', NewHarnessField.projectMenu),
+ ('creation.project_machine', NewHarnessField.projectMenu),
+ ]) {
+ journey('advertised $command remap opens its chooser from the task', (
+ tester,
+ ) async {
+ final workspace = await _mount(
+ tester,
+ bindings:
+ '{"bindings":[{"keys":"ctrl+alt+g","command":"$command","when":"picker"}]}',
+ );
+ await _new(tester);
+ await tester.enterText(_task, 'Direct keyboard access to configuration');
+ await key(tester, LogicalKeyboardKey.keyG, ctrl: true, alt: true);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsOneWidget);
+ expect(_box(tester).field, field);
+ if (command == 'creation.project_machine') {
+ expect(
+ find.byKey(const ValueKey('new-harness-machine-option-m')),
+ findsOneWidget,
+ );
+ } else {
+ expect(_ownsFocus(tester, _query), isTrue);
+ }
+ expect(_box(tester).task, 'Direct keyboard access to configuration');
+ expect(workspace.starts, isEmpty);
+ });
+ }
+
+ journey('advertised creation.task remap returns from a chooser to the task', (
+ tester,
+ ) async {
+ await _mount(
+ tester,
+ bindings: '{"bindings":[{"keys":"ctrl+alt+t","command":"creation.task","when":"picker"}]}',
+ );
+ await _new(tester);
+ await tester.enterText(_task, 'Return here without cycling every control');
+ await openLaunchRow(tester, 'agent');
+ await key(tester, LogicalKeyboardKey.keyT, ctrl: true, alt: true);
+ expect(_chooser, findsNothing);
+ expect(_ownsFocus(tester, _task), isTrue);
+ expect(_box(tester).task, 'Return here without cycling every control');
+ });
+
+ journey('native creation command uses the same focused form action', (
+ tester,
+ ) async {
+ await _mount(tester, nativeMenus: true);
+ await _new(tester);
+ await _nativeCommand(tester, 'creation.project_machine');
+ expect(_chooser, findsOneWidget);
+ expect(_box(tester).field, NewHarnessField.projectMenu);
+ expect(
+ find.byKey(const ValueKey('new-harness-machine-option-m')),
+ findsOneWidget,
+ );
+ });
+
+ for (final (command, field) in [
+ ('creation.project_new', NewHarnessField.projectName),
+ ('creation.project_existing', NewHarnessField.projectMenu),
+ ('creation.project_repository', NewHarnessField.projectRepository),
+ ]) {
+ journey('$command remap works in the project keymap context', (
+ tester,
+ ) async {
+ final workspace = await _mount(
+ tester,
+ bindings:
+ '{"bindings":[{"keys":"ctrl+alt+b","command":"$command","when":"project"}]}',
+ );
+ await _new(tester);
+ await openLaunchRow(tester, 'project');
+ final machine = _box(tester).machineId;
+ await key(tester, LogicalKeyboardKey.keyB, ctrl: true, alt: true);
+ await tester.pumpAndSettle();
+ expect(_chooser, findsOneWidget);
+ expect(_box(tester).field, field);
+ expect(_box(tester).machineId, machine);
+ expect(_ownsFocus(tester, _query), isTrue);
+ expect(
+ workspace.folders.opened,
+ command == 'creation.project_existing' ? 1 : 0,
+ );
+ expect(workspace.starts, isEmpty);
+ });
+ }
+
+ journey(
+ 'legacy options command opens Model and recent-project shortcuts preserve the task',
+ (tester) async {
+ final workspace = await _mount(
+ tester,
+ bindings: '''{"bindings":[
+ {"keys":"ctrl+alt+o","command":"creation.options","when":"picker"},
+ {"keys":"ctrl+alt+1","command":"creation.project_recent_1","when":"project"}
+ ]}''',
+ );
+ await _new(tester);
+ await tester.enterText(
+ _task,
+ 'Keep task while applying direct shortcuts',
+ );
+ await key(tester, LogicalKeyboardKey.keyO, ctrl: true, alt: true);
+ expect(_box(tester).field, NewHarnessField.model);
+ expect(_chooser, findsOneWidget);
+ expect(_ownsFocus(tester, _query), isTrue);
+ expect(
+ find.byKey(const ValueKey('new-harness-field-profile')),
+ findsOneWidget,
+ );
+ await openLaunchRow(tester, 'project');
+ final expected = _box(tester).options
+ .firstWhere(
+ (option) => !option.synthetic && option.project?.folder != null,
+ )
+ .project;
+ await key(tester, LogicalKeyboardKey.digit1, ctrl: true, alt: true);
+ expect(_chooser, findsNothing);
+ expect(_box(tester).project, expected);
+ expect(_box(tester).task, 'Keep task while applying direct shortcuts');
+ expect(workspace.starts, isEmpty);
+ },
+ );
+
+ journey(
+ 'machine shortcut from a project prompt keeps its nested return path',
+ (tester) async {
+ await _mount(
+ tester,
+ bindings: '''{"bindings":[
+ {"keys":"ctrl+alt+m","command":"creation.project_machine","when":"picker"}
+ ]}''',
+ );
+ await _new(tester);
+ await openLaunchRow(tester, 'project');
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-option-project:name')),
+ );
+ await tester.pump();
+ await tester.enterText(_query, 'keyboard-plans');
+ await key(tester, LogicalKeyboardKey.keyM, ctrl: true, alt: true);
+ expect(_box(tester).field, NewHarnessField.machine);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(_box(tester).field, NewHarnessField.projectName);
+ expect(_box(tester).query, 'keyboard-plans');
+ expect(_ownsFocus(tester, _query), isTrue);
+ },
+ );
+
+ journey('default Control-O browses the current machine without launching', (
+ tester,
+ ) async {
+ final app = createApp(connectionForTest: _DialogConnection.new);
+ seedMixedAgents(app);
+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
+ final map = MemoryKeymap();
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/openharness',
+ );
+ var browses = 0;
+ addTearDown(app.dispose);
+ addTearDown(map.dispose);
+ addTearDown(box.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: KeymapProvider(
+ keymap: map,
+ child: KeymapHost(
+ keymap: map,
+ enabled: () => true,
+ actions: const {},
+ child: NewHarnessForm(
+ controller: box,
+ desktop: true,
+ onClose: () {},
+ onCreated: () {},
+ onBrowse: () => browses++,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.enterText(_task, 'Browse without losing this task');
+ await key(tester, LogicalKeyboardKey.keyO, ctrl: true);
+ expect(browses, 1);
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(_chooser, findsOneWidget);
+ expect(_ownsFocus(tester, _query), isTrue);
+ expect(box.task, 'Browse without losing this task');
+ await key(tester, LogicalKeyboardKey.keyO, ctrl: true);
+ expect(browses, 2);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ for (final (door, field, draft) in [
+ ('project:name', NewHarnessField.projectName, 'keyboard-plans'),
+ ('project:repository', NewHarnessField.projectRepository, 'openai/codex'),
+ ]) {
+ for (final machine in ['m', 'studio']) {
+ journey(
+ '$field draft survives selecting ${machine == 'm' ? 'the same' : 'another'} machine where portable',
+ (tester) async {
+ final workspace = await _mount(
+ tester,
+ bindings: '{"bindings":[{"keys":"ctrl+alt+m","command":"creation.project_machine","when":"picker"}]}',
+ );
+ await _new(tester);
+ await tester.enterText(
+ _task,
+ 'Keep this task throughout the machine change',
+ );
+ await openLaunchRow(tester, 'project');
+ await tester.tap(find.byKey(ValueKey('new-harness-option-$door')));
+ await tester.pump();
+ await tester.enterText(_query, draft);
+ await key(tester, LogicalKeyboardKey.keyM, ctrl: true, alt: true);
+ expect(_box(tester).field, NewHarnessField.machine);
+ await tester.tap(find.byKey(ValueKey('new-harness-option-$machine')));
+ await tester.pumpAndSettle();
+ expect(_box(tester).machineId, machine);
+ expect(_box(tester).field, field);
+ expect(
+ _box(tester).query,
+ machine != 'm' && field == NewHarnessField.project ? '' : draft,
+ );
+ expect(_chooser, findsOneWidget);
+ expect(_ownsFocus(tester, _query), isTrue);
+ expect(
+ _box(tester).task,
+ 'Keep this task throughout the machine change',
+ );
+ expect(workspace.starts, isEmpty);
+ },
+ );
+ }
+ }
+
+ journey(
+ 'cancelling the remote folder browser preserves the repo and message',
+ (tester) async {
+ final workspace = await _mount(tester);
+ await _new(tester);
+ final box = _box(tester);
+ final originalProject = box.project;
+ await tester.enterText(
+ _task,
+ 'Keep this message while browsing remotely',
+ );
+ workspace.app.machineStates['m']!.localOnly = false;
+ await openLaunchRow(tester, 'project');
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-option-project:existing')),
+ );
+ await tester.pumpAndSettle();
+ final browser = find.byKey(
+ const ValueKey('desktop-remote-folder-dialog'),
+ );
+ expect(browser, findsOneWidget);
+ expect(_form, findsNothing);
+ await tester.enterText(
+ find.descendant(of: browser, matching: find.byType(TextField)),
+ '/work/review-draft',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(_form, findsOneWidget);
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.project, originalProject);
+ expect(box.task, 'Keep this message while browsing remotely');
+ expect(_ownsFocus(tester, _query), isTrue);
+ expect(workspace.folders.opened, 0);
+ expect(workspace.starts, isEmpty);
+ },
+ );
+
+ for (final owner in ['task', 'chooser']) {
+ journey('IME owns editing, dismissal, and native commands in the $owner', (
+ tester,
+ ) async {
+ final workspace = await _mount(tester, nativeMenus: true);
+ await _new(tester);
+ if (owner == 'chooser') await openLaunchRow(tester, 'agent');
+ final editor = owner == 'task' ? _task : _query;
+ await tester.tap(editor);
+ const composing = TextEditingValue(
+ text: '開発',
+ selection: TextSelection.collapsed(offset: 2),
+ composing: TextRange(start: 0, end: 2),
+ );
+ tester.testTextInput.updateEditingValue(composing);
+ await tester.pump();
+ final original = _box(tester);
+ for (final pressed in [
+ LogicalKeyboardKey.escape,
+ LogicalKeyboardKey.enter,
+ LogicalKeyboardKey.arrowDown,
+ LogicalKeyboardKey.tab,
+ ]) {
+ await key(tester, pressed);
+ }
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ for (final command in [
+ 'picker.cancel',
+ 'picker.add_here',
+ 'harnesses.list',
+ 'creation.agent',
+ 'creation.project_machine',
+ 'creation.project_new',
+ 'creation.task',
+ 'creation.options',
+ ]) {
+ await _nativeCommand(tester, command);
+ }
+ expect(_form, findsOneWidget);
+ expect(_box(tester), same(original));
+ expect(tester.widget<TextField>(editor).controller!.value, composing);
+ expect(_ownsFocus(tester, editor), isTrue);
+ expect(_search, findsNothing);
+ expect(workspace.starts, isEmpty);
+ if (owner == 'chooser') expect(_chooser, findsOneWidget);
+ });
+ }
+
+ journey(
+ 'pending Start rejects duplicate keyboard, native, and mouse starts',
+ (tester) async {
+ final workspace = await _mount(tester, nativeMenus: true);
+ await _new(tester);
+ await tester.enterText(_task, 'Start exactly once');
+ // Local-only identity supplies the default machine, but creation must
+ // use the fixture transport rather than the local folder preparer.
+ workspace.app.machineStates['m']!.localOnly = false;
+ final connection = workspace.connections['m']!;
+ final reply = connection.pendingStart = Completer<Map<String, dynamic>>();
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ final box = _box(tester);
+ expect(box.busy, isTrue);
+ expect(workspace.starts, hasLength(1));
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await _nativeCommand(tester, 'picker.add_here');
+ await _nativeCommand(tester, 'creation.project_machine');
+ expect(_chooser, findsNothing);
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-start')));
+ await tester.pump();
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyRepeatEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+ await tester.pump();
+ expect(workspace.starts, hasLength(1));
+ expect(workspace.starts.single['prompt'], 'Start exactly once');
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.tapAt(const Offset(10, 400));
+ await tester.pump();
+ expect(_form, findsOneWidget);
+ expect(_search, findsNothing);
+ reply.completeError(
+ const WsRequestFailure(
+ responseType: 'agent_create_result',
+ code: 'INVALID_ENGINE',
+ detail: 'Fixture launch declined.',
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(box.busy, isFalse);
+ expect(box.task, 'Start exactly once');
+ expect(box.error, isNotEmpty);
+ expect(_form, findsOneWidget);
+ },
+ );
+
+ journey('Cmd-P forward and reverse Tab cannot focus the dimmed workspace', (
+ tester,
+ ) async {
+ await _mount(tester, withTerminal: true);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ final panel = find.byType(DesktopSearchPanel);
+ for (final reverse in [false, true]) {
+ for (var i = 0; i < 28; i++) {
+ await key(tester, LogicalKeyboardKey.tab, shift: reverse);
+ expect(
+ _ownsFocus(tester, panel),
+ isTrue,
+ reason: 'Search traversal must remain in the active dialog.',
+ );
+ }
+ }
+ });
+
+ for (final nativeAccept in [false, true]) {
+ journey(
+ 'focused Cmd-P preview control owns ${nativeAccept ? 'native accept' : 'Return'}',
+ (tester) async {
+ final workspace = await _mount(
+ tester,
+ nativeMenus: nativeAccept,
+ withTerminal: true,
+ );
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.enterText(_search, 'login');
+ await tester.pump();
+ final panel = tester.widget<DesktopSearchPanel>(
+ find.byType(DesktopSearchPanel),
+ );
+ final selected = panel.search.selected?.id;
+ final previewVisible = panel.search.previewVisible;
+ await _tabTo(
+ tester,
+ find.byKey(const ValueKey('search-toggle-preview')),
+ );
+ if (nativeAccept) {
+ await _nativeCommand(tester, 'picker.accept');
+ } else {
+ await key(tester, LogicalKeyboardKey.enter);
+ }
+ expect(
+ _search,
+ findsOneWidget,
+ reason: 'A toolbar control must not open the highlighted harness.',
+ );
+ expect(panel.search.previewVisible, !previewVisible);
+ expect(panel.search.selected?.id, selected);
+ expect(panel.editing.text, 'login');
+ expect(workspace.input, isEmpty);
+ },
+ );
+ }
+
+ journey(
+ 'Return on Close search restores terminal focus without opening a result',
+ (tester) async {
+ final workspace = await _mount(tester, withTerminal: true);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.enterText(_search, 'login');
+ await _tabTo(tester, find.byTooltip('Close search'));
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(_search, findsNothing);
+ expect(
+ tester
+ .widget<TerminalView>(find.byType(TerminalView))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ expect(workspace.app.panes, hasLength(1));
+ expect(workspace.input, isEmpty);
+ },
+ );
+
+ for (final dismissal in ['Escape', 'outside click']) {
+ journey('Cmd-P returns focus to the terminal after $dismissal', (
+ tester,
+ ) async {
+ final workspace = await _mount(tester, withTerminal: true);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ expect(_search, findsOneWidget);
+ await tester.enterText(_search, 'login');
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(find.byType(SwarmSearchResults), findsOneWidget);
+ expect(workspace.input, isEmpty);
+ if (dismissal == 'Escape') {
+ await key(tester, LogicalKeyboardKey.escape);
+ } else {
+ await tester.tapAt(const Offset(10, 400));
+ await tester.pump();
+ }
+ expect(_search, findsNothing);
+ final view = tester.widget<TerminalView>(find.byType(TerminalView));
+ expect(view.focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(workspace.input.single.bytes, [27, 91, 68]);
+ });
+ }
+}
diff --git a/desktop/test/desktop_final_ux_test.dart b/desktop/test/desktop_final_ux_test.dart
new file mode 100644
index 000000000..818e0e1b1
--- /dev/null
+++ b/desktop/test/desktop_final_ux_test.dart
@@ -0,0 +1,217 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/widgets/desktop_search_panel.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'swarm_state_test.dart' show createApp;
+
+/// Independent final-review regressions. These exercise visible controls using
+/// keyboard and pointer input, without a daemon, user files, or native windows.
+void main() {
+ final renderDir = Platform.environment['DESKTOP_FINAL_UX_RENDER_DIR'];
+ setUpAll(() async {
+ if (renderDir != null) await loadPreviewFonts();
+ });
+ const inputKey = ValueKey('swarm-search-input');
+ final input = find.byKey(inputKey);
+
+ Future<void> capture(WidgetTester tester, String name) async {
+ if (renderDir == null) return;
+ await tester.runAsync(() async {
+ final boundary = tester.renderObject<RenderRepaintBoundary>(
+ find
+ .ancestor(
+ of: find.byType(DesktopSearchPanel),
+ matching: find.byType(RepaintBoundary),
+ )
+ .first,
+ );
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ final directory = Directory(renderDir)..createSync(recursive: true);
+ await File('${directory.path}/$name.png')
+ .writeAsBytes(data!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ Future<SwarmSearchController> mount(WidgetTester tester) async {
+ tester.view.physicalSize = const Size(440, 780);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final app = createApp();
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ selectOnEmptyQuery: false,
+ offersHarnessCreate: false,
+ );
+ final editor = TextEditingController();
+ final focus = FocusNode();
+ final map = MemoryKeymap();
+ addTearDown(app.dispose);
+ addTearDown(search.dispose);
+ addTearDown(editor.dispose);
+ addTearDown(focus.dispose);
+ addTearDown(map.dispose);
+ search.addListener(() {
+ if (editor.text != search.query) {
+ editor.value = TextEditingValue(
+ text: search.query,
+ selection: TextSelection.collapsed(offset: search.query.length),
+ );
+ }
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(1.6)),
+ child: child!,
+ ),
+ home: KeymapProvider(
+ keymap: map,
+ child: KeymapHost(
+ keymap: map,
+ enabled: () => true,
+ actions: const {},
+ child: Scaffold(
+ body: Padding(
+ padding: const EdgeInsets.all(20),
+ child: Center(
+ child: SizedBox(
+ height: 570,
+ child: SwarmSearchKeys(
+ desktop: true,
+ search: search,
+ editing: editor,
+ onChoose: (_) =>
+ fail('Scope navigation cannot open a result'),
+ onClose: () =>
+ fail('Scope navigation cannot close the dialog'),
+ onRefocus: focus.requestFocus,
+ child: DesktopSearchPanel(
+ search: search,
+ editing: editor,
+ focusNode: focus,
+ onChoose: (_) =>
+ fail('Scope navigation cannot open a result'),
+ onClose: () =>
+ fail('Scope navigation cannot close the dialog'),
+ onRefocus: focus.requestFocus,
+ previewBuilder: () => const SizedBox(),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump();
+ });
+ return search;
+ }
+
+ void expectScopeVisible(WidgetTester tester, String label) {
+ final selected = find.byKey(ValueKey('search-category-$label'));
+ final viewport = find
+ .ancestor(of: selected, matching: find.byType(SingleChildScrollView))
+ .first;
+ final visibleBounds = tester.getRect(viewport);
+ final selectedBounds = tester.getRect(selected);
+ expect(
+ selectedBounds.left,
+ greaterThanOrEqualTo(visibleBounds.left),
+ reason:
+ 'The selected $label scope must stay visible in a narrow window: '
+ '$selectedBounds inside $visibleBounds',
+ );
+ expect(selectedBounds.right, lessThanOrEqualTo(visibleBounds.right));
+ }
+
+ testWidgets(
+ 'keyboard scope changes reveal the selected segment when narrow',
+ (tester) async {
+ final search = await mount(tester);
+ for (var step = 0; step < 20; step++) {
+ await key(tester, LogicalKeyboardKey.tab);
+ if (tester
+ .widget<Focus>(find.byKey(const ValueKey('search-scopes')))
+ .focusNode!
+ .hasFocus) {
+ break;
+ }
+ }
+ for (final (label, _) in DesktopSearchPanel.categories.skip(1)) {
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await tester.pumpAndSettle();
+ expectScopeVisible(tester, label);
+ }
+ expect(search.isCommandMode, isTrue);
+ await capture(tester, 'keyboard-commands-narrow');
+ for (final (label, _) in DesktopSearchPanel.categories.reversed.skip(1)) {
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pumpAndSettle();
+ expectScopeVisible(tester, label);
+ }
+ expect(search.query, isEmpty);
+ await capture(tester, 'keyboard-all-narrow');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'typed prefixes reveal the matching scope without stealing focus',
+ (tester) async {
+ final search = await mount(tester);
+ for (final (label, prefix) in DesktopSearchPanel.categories.reversed) {
+ await tester.enterText(input, prefix);
+ await tester.pumpAndSettle();
+ expect(search.query, prefix);
+ expectScopeVisible(tester, label);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ if (prefix == '>') await capture(tester, 'typed-commands-narrow');
+ }
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'resizing the palette keeps its active scope and editor visible',
+ (tester) async {
+ await mount(tester);
+ tester.view.physicalSize = const Size(1200, 780);
+ await tester.pumpAndSettle();
+ await tester.enterText(input, '* release');
+ await tester.pumpAndSettle();
+ tester.view.physicalSize = const Size(440, 780);
+ await tester.pumpAndSettle();
+ expectScopeVisible(tester, 'Store');
+ expect(tester.widget<TextField>(input).controller!.text, '* release');
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ expect(tester.takeException(), isNull);
+ },
+ );
+}
diff --git a/desktop/test/desktop_guidance_layout_test.dart b/desktop/test/desktop_guidance_layout_test.dart
new file mode 100644
index 000000000..442f385d6
--- /dev/null
+++ b/desktop/test/desktop_guidance_layout_test.dart
@@ -0,0 +1,236 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/sharing/shared_harness_bar.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/state/workspace_learning.dart';
+import 'package:harness/widgets/workspace_quick_start.dart';
+import 'package:harness/widgets/workspace_start_guide.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap;
+import 'support/real_fonts.dart';
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ if (Platform.isMacOS &&
+ Platform.environment['GUIDANCE_RENDER_DIR'] != null) {
+ final font = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(font))).load();
+ }
+ // The widget engine has no CoreText fallback for keyboard symbols.
+ final symbols = ByteData.sublistView(
+ await File('/System/Library/Fonts/Apple Symbols.ttf').readAsBytes(),
+ );
+ for (final family in ['Arial', 'Courier New']) {
+ await (FontLoader(family)..addFont(Future.value(symbols))).load();
+ }
+ }
+ await (FontLoader(
+ 'MaterialIcons',
+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
+ });
+
+ Future<void> capture(WidgetTester tester, String name) async {
+ final directory = Platform.environment['GUIDANCE_RENDER_DIR'];
+ if (directory == null) return;
+ final boundary = tester.renderObject<RenderRepaintBoundary>(
+ find.byKey(const ValueKey('guidance-preview')),
+ );
+ await tester.runAsync(() async {
+ final image = await boundary.toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ Future<void> mount(
+ WidgetTester tester,
+ Widget child, {
+ required Brightness brightness,
+ required Size size,
+ required double scale,
+ }) async {
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ debugShowCheckedModeBanner: false,
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: RepaintBoundary(
+ key: const ValueKey('guidance-preview'),
+ child: Scaffold(body: child),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ for (final brightness in Brightness.values) {
+ for (final layout in [
+ (size: const Size(1200, 760), scale: 1.0),
+ (size: const Size(390, 620), scale: 2.0),
+ ]) {
+ final name = '${brightness.name}-${layout.size.width.toInt()}';
+ testWidgets('observer header $name fits and preserves actions', (
+ tester,
+ ) async {
+ final calls = <String>[];
+ var comments = false, viewer = false;
+ await mount(
+ tester,
+ StatefulBuilder(
+ builder: (context, setState) => SharedHarnessBar(
+ name: 'Climate dashboard — onboarding review',
+ detail: 'Morgan · MacBook Pro',
+ status: SharedPaneStatus.ended,
+ commentsSelected: comments,
+ viewerSelected: viewer,
+ onSelectViewer: (value) => setState(() {
+ viewer = value;
+ calls.add('viewer:$value');
+ }),
+ onToggleComments: () => setState(() {
+ comments = !comments;
+ calls.add('comments:$comments');
+ }),
+ onRetry: () => calls.add('retry'),
+ onClose: () => calls.add('close'),
+ ),
+ ),
+ brightness: brightness,
+ size: layout.size,
+ scale: layout.scale,
+ );
+ expect(calls, isEmpty);
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'observer-$name');
+ await tester.tap(find.text('Retry'));
+ await tester.tap(find.text('Viewer'));
+ await tester.tap(find.text('Comments'));
+ await tester.pumpAndSettle();
+ expect(find.text('Watch'), findsOneWidget);
+ Focus.of(tester.element(find.text('Watch'))).requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.space);
+ await tester.pumpAndSettle();
+ expect(find.text('Comments'), findsOneWidget);
+ await tester.tap(find.byTooltip('Close shared harness'));
+ expect(calls, [
+ 'retry',
+ 'viewer:true',
+ 'comments:true',
+ 'comments:false',
+ 'close',
+ ]);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('quick start $name keeps steps and keyboard activation', (
+ tester,
+ ) async {
+ final map = MemoryKeymap()
+ ..apply(
+ '{"bindings":[{"keys":"cmd+t","command":null},{"keys":"cmd+y","command":"swarm.new"}]}',
+ );
+ final learning = WorkspaceLearning()..start();
+ addTearDown(map.dispose);
+ addTearDown(learning.dispose);
+ final calls = <String>[];
+ await mount(
+ tester,
+ KeymapProvider(
+ keymap: map,
+ child: ListenableBuilder(
+ listenable: learning,
+ builder: (context, _) => WorkspaceQuickStart(
+ learning: learning,
+ onCommand: calls.add,
+ onPractice: () => calls.add('practice'),
+ ),
+ ),
+ ),
+ brightness: brightness,
+ size: layout.size,
+ scale: layout.scale,
+ );
+ final action = find.byKey(const ValueKey('quick-start-action'));
+ expect(calls, isEmpty);
+ expect(find.text('⌘Y Try it'), findsOneWidget);
+ await capture(tester, 'tour-$name');
+ await tester.tap(action);
+ expect(learning.completed, isEmpty);
+ learning.observe(agents: 1, zoomed: false);
+ await tester.pumpAndSettle();
+ await tester.tap(action);
+ learning.observe(agents: 2, zoomed: false);
+ await tester.pumpAndSettle();
+ await tester.tap(action);
+ learning.observe(agents: 2, zoomed: true);
+ await tester.pumpAndSettle();
+ await tester.tap(action);
+ learning.commandSearchOpened();
+ await tester.pumpAndSettle();
+ expect(find.text('Quick start · Complete'), findsOneWidget);
+ Focus.of(tester.element(find.text('Keyboard practice'))).requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.space);
+ await tester.pumpAndSettle();
+ expect(calls, [
+ 'swarm.new',
+ 'agent.open',
+ 'pane.zoom',
+ 'navigation.commands',
+ 'practice',
+ ]);
+ await tester.tap(find.byKey(const ValueKey('quick-start-pause')));
+ expect(learning.active, isFalse);
+ expect(learning.finished, isTrue);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('guide $name keeps annotations and scrollable shortcuts', (
+ tester,
+ ) async {
+ var opened = 0;
+ await mount(
+ tester,
+ WorkspaceStartGuide(onShortcuts: () => opened++),
+ brightness: brightness,
+ size: layout.size,
+ scale: layout.scale,
+ );
+ expect(opened, 0);
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'guide-$name');
+ final shortcuts = find.byKey(const ValueKey('workspace-all-shortcuts'));
+ await tester.ensureVisible(shortcuts);
+ await tester.pumpAndSettle();
+ await capture(tester, 'guide-actions-$name');
+ await tester.tap(shortcuts);
+ expect(opened, 1);
+ expect(tester.takeException(), isNull);
+ });
+ }
+ }
+}
diff --git a/desktop/test/desktop_history_dialog_test.dart b/desktop/test/desktop_history_dialog_test.dart
new file mode 100644
index 000000000..aa4723606
--- /dev/null
+++ b/desktop/test/desktop_history_dialog_test.dart
@@ -0,0 +1,362 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/search_result_text.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'keymap_host_test.dart' show key;
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show MemoryStore, createApp;
+
+const _channel = MethodChannel('harness/swarm_tabs');
+final _historyField = find.byWidgetPredicate(
+ (widget) =>
+ widget is TextField && widget.decoration?.hintText == 'Search history',
+);
+final _closeIcon = find.descendant(
+ of: find.byType(DesktopDialogHeader),
+ matching: find.byIcon(AppIcons.close),
+);
+final _renderDir = Platform.environment['DESKTOP_HISTORY_RENDER_DIR'];
+
+class _HistoryWorkspace {
+ _HistoryWorkspace() {
+ app.machineStates['m']!
+ ..nodeOnline = true
+ ..agents = const [
+ Agent(
+ id: 'a0',
+ name: 'Prototype review',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ Agent(
+ id: 'a1',
+ name: 'Release preparation',
+ engine: 'claude',
+ terminalAvailable: true,
+ ),
+ ];
+ firstId = app.adoptSessionForTest(terminal('a0', firstInput)).id;
+ secondId = app.adoptSessionForTest(terminal('a1', secondInput)).id;
+ }
+
+ final app = createApp();
+ final projects = SwarmProjectStore(storage: MemoryStore());
+ final firstInput = <TerminalBinaryFrame>[];
+ final secondInput = <TerminalBinaryFrame>[];
+ final picture = GlobalKey();
+ late final int firstId, secondId;
+ Future<void>? _dialogDone;
+
+ SwarmSearchController search(WidgetTester tester) => tester
+ .widget<SwarmSearchKeys>(
+ find.ancestor(
+ of: _historyField,
+ matching: find.byType(SwarmSearchKeys),
+ ),
+ )
+ .search!;
+
+ Future<void> open(WidgetTester tester) async {
+ final done = Completer<void>();
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ _channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('showHistory'),
+ ),
+ (_) => done.complete(),
+ );
+ _dialogDone = done.future;
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(_historyField, findsOneWidget);
+ expect(tester.widget<TextField>(_historyField).focusNode!.hasFocus, isTrue);
+ }
+
+ Future<void> closed(WidgetTester tester) async {
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ await _dialogDone;
+ expect(_historyField, findsNothing);
+ }
+}
+
+Future<_HistoryWorkspace> _mount(
+ WidgetTester tester, {
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ Size size = const Size(880, 560),
+}) async {
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ final oldEntry = newHarnessOpensInBox;
+ grid.AppTheme.brightness.value = brightness;
+ newHarnessOpensInBox = true;
+ addTearDown(() {
+ grid.AppTheme.brightness.value = oldBrightness;
+ newHarnessOpensInBox = oldEntry;
+ });
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(_channel, (_) async => true);
+ addTearDown(() => messenger.setMockMethodCallHandler(_channel, null));
+ final fixture = _HistoryWorkspace();
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox());
+ fixture.projects.dispose();
+ fixture.app.dispose();
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid
+ .buildAppTheme(brightness: brightness)
+ .copyWith(platform: TargetPlatform.macOS),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: RepaintBoundary(key: fixture.picture, child: child!),
+ ),
+ home: SwarmScreen(
+ notifier: fixture.app,
+ nativeTabs: true,
+ projectStore: fixture.projects,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ fixture.app.focusPane(fixture.firstId);
+ await tester.pump();
+ fixture.app.focusPane(fixture.secondId);
+ fixture.app.focusedPane!.session!.focusInput();
+ await tester.pump();
+ expect(fixture.app.focusedPaneId, fixture.secondId);
+ return fixture;
+}
+
+Future<void> _capture(
+ WidgetTester tester,
+ _HistoryWorkspace fixture,
+ String name,
+) async {
+ if (_renderDir == null) return;
+ debugDisableShadows = false;
+ try {
+ await tester.pump();
+ await tester.runAsync(() async {
+ final boundary =
+ fixture.picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ Directory(_renderDir!).createSync(recursive: true);
+ await File('$_renderDir/$name.png')
+ .writeAsBytes(data!.buffer.asUint8List());
+ image.dispose();
+ });
+ } finally {
+ debugDisableShadows = true;
+ }
+}
+
+double _contrast(Color ink, Color fill) {
+ final foreground = Color.alphaBlend(ink, fill).computeLuminance();
+ final background = fill.computeLuminance();
+ return foreground > background
+ ? (foreground + .05) / (background + .05)
+ : (background + .05) / (foreground + .05);
+}
+
+void main() {
+ setUpAll(() async {
+ if (_renderDir != null) await loadPreviewFonts();
+ });
+
+ testWidgets('native History owns keyboard input and restores its pane', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ final target = fixture.app.activeSwarmId;
+ await fixture.open(tester);
+ final search = fixture.search(tester);
+ final selected = search.selected!.id;
+ expect(search.supportsPreview, isFalse);
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ expect(search.hasPreview, isFalse);
+ expect(search.selected!.id, selected);
+ expect(tester.widget<TextField>(_historyField).focusNode!.hasFocus, isTrue);
+
+ // The field and visible Close control form one compact traversal loop.
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(Focus.of(tester.element(_closeIcon)).hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(tester.widget<TextField>(_historyField).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(Focus.of(tester.element(_closeIcon)).hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(tester.widget<TextField>(_historyField).focusNode!.hasFocus, isTrue);
+ await tester.enterText(_historyField, 'Prototype review');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await fixture.closed(tester);
+ expect(fixture.app.activeSwarmId, target);
+ expect(fixture.app.focusedPaneId, fixture.firstId);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(fixture.firstInput.single.bytes, [27, 91, 68]);
+ expect(fixture.secondInput, isEmpty);
+
+ await fixture.open(tester);
+ expect(tester.widget<TextField>(_historyField).controller!.text, isEmpty);
+ await key(tester, LogicalKeyboardKey.tab);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await fixture.closed(tester);
+ expect(fixture.app.focusedPaneId, fixture.firstId);
+
+ await fixture.open(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await fixture.closed(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(fixture.firstInput.last.bytes, [27, 91, 67]);
+ expect(fixture.firstInput, hasLength(2));
+ expect(fixture.secondInput, isEmpty);
+ });
+
+ testWidgets(
+ 'History composition keeps navigation and dismissal in the editor',
+ (tester) async {
+ final fixture = await _mount(tester);
+ await fixture.open(tester);
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 're',
+ selection: TextSelection.collapsed(offset: 2),
+ composing: TextRange(start: 0, end: 2),
+ ),
+ );
+ await tester.pump();
+ expect(fixture.search(tester).rows.length, greaterThan(1));
+ final selected = fixture.search(tester).selected!.id;
+ for (final key in [
+ LogicalKeyboardKey.arrowDown,
+ LogicalKeyboardKey.enter,
+ LogicalKeyboardKey.escape,
+ ]) {
+ // The fake editor can commit preedit while handling a key. Restore the
+ // active range that the platform IME would send for each event.
+ tester
+ .widget<TextField>(_historyField)
+ .controller!
+ .value = const TextEditingValue(
+ text: 're',
+ selection: TextSelection.collapsed(offset: 2),
+ composing: TextRange(start: 0, end: 2),
+ );
+ await tester.sendKeyEvent(key);
+ await tester.pump();
+ expect(_historyField, findsOneWidget);
+ expect(fixture.search(tester).selected!.id, selected);
+ }
+ expect(fixture.firstInput, isEmpty);
+ expect(fixture.secondInput, isEmpty);
+ expect(fixture.app.focusedPaneId, fixture.secondId);
+ // Explicit pointer dismissal is still available while composing.
+ await tester.tap(find.byTooltip('Close'));
+ await fixture.closed(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(fixture.secondInput.single.bytes, [27, 91, 68]);
+ },
+ );
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets(
+ 'live History ${brightness.name} at ${scale}x stays readable',
+ (tester) async {
+ final size = scale == 1 ? const Size(880, 560) : const Size(440, 420);
+ final fixture = await _mount(
+ tester,
+ brightness: brightness,
+ scale: scale,
+ size: size,
+ );
+ await fixture.open(tester);
+ final surface = find.byType(DesktopDialogSurface);
+ expect(surface, findsOneWidget);
+ final bounds = tester.getRect(surface);
+ expect(bounds.left, greaterThanOrEqualTo(20));
+ expect(bounds.right, lessThanOrEqualTo(size.width - 20));
+ expect(bounds.bottom, lessThanOrEqualTo(size.height - 20));
+ final fieldBounds = tester.getRect(_historyField);
+ expect(bounds.contains(fieldBounds.topLeft), isTrue);
+ expect(bounds.contains(fieldBounds.bottomRight), isTrue);
+ final context = tester.widget<Text>(find.text('This window'));
+ expect(
+ _contrast(context.style!.color!, DesktopChrome.surface),
+ greaterThanOrEqualTo(4.5),
+ );
+ final search = fixture.search(tester);
+ final selectedId = search.selected!.id;
+ final selected = find.byKey(
+ ValueKey('swarm-search-line:$selectedId'),
+ );
+ expect(selected, findsOneWidget);
+ final fill = tester.widget<Material>(selected).color!;
+ final label = tester.widget<SearchResultText>(
+ find
+ .descendant(
+ of: selected,
+ matching: find.byType(SearchResultText),
+ )
+ .first,
+ );
+ expect(
+ _contrast(label.style.color!, fill),
+ greaterThanOrEqualTo(4.5),
+ );
+ expect(tester.getRect(selected).top, greaterThan(fieldBounds.bottom));
+ expect(tester.getRect(selected).bottom, lessThan(bounds.bottom));
+ await _capture(tester, fixture, 'history-${brightness.name}-$scale');
+ expect(tester.takeException(), isNull);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ expect(search.selected!.id, isNot(selectedId));
+ await tester.pump();
+ final next = find.byKey(
+ ValueKey('swarm-search-line:${search.selected!.id}'),
+ );
+ final viewport = tester.getRect(
+ find.byKey(const ValueKey('swarm-search-result-list')),
+ );
+ expect(tester.getRect(next).top, greaterThanOrEqualTo(viewport.top));
+ expect(
+ tester.getRect(next).bottom,
+ lessThanOrEqualTo(viewport.bottom),
+ );
+ expect(tester.getRect(_historyField), fieldBounds);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await fixture.closed(tester);
+ },
+ );
+ }
+ }
+}
diff --git a/desktop/test/desktop_new_harness_edge_test.dart b/desktop/test/desktop_new_harness_edge_test.dart
new file mode 100644
index 000000000..15be565d1
--- /dev/null
+++ b/desktop/test/desktop_new_harness_edge_test.dart
@@ -0,0 +1,648 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/core/first_task.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/core/repository_clone.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/pane_arrangement.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+
+const _toolId = 'autonomous/review-tool';
+
+DshEntry _tool({bool installed = false, String id = _toolId}) => DshEntry(
+ id: id,
+ name: id == _toolId ? 'Review Tool' : 'Tool ${id.split('/').last}',
+ engine: 'codex',
+ engines: const ['codex', 'claude'],
+ description: 'A development environment',
+ installed: installed,
+);
+
+class _App extends AppNotifier {
+ _App()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ ) {
+ final state = MachineState(
+ const Machine(
+ machineId: 'machine',
+ name: 'Studio Mac',
+ authMode: MachineAuthMode.remote,
+ ),
+ )..localOnly = true;
+ state.engines.replace(const [
+ EngineAvailability(
+ engine: 'codex',
+ installed: true,
+ supportsCodexHome: true,
+ ),
+ EngineAvailability(engine: 'claude', installed: true),
+ ]);
+ state.dsh.replace([_tool()]);
+ machineStates['machine'] = state;
+ }
+
+ final installs = <String>[];
+ final launches = <Map<String, Object?>>[];
+ Completer<String?>? pendingInstall;
+
+ @override
+ Future<Map<String, dynamic>> readGitProject(
+ String machineId,
+ String path, {
+ bool refresh = false,
+ }) async => {'isGit': false};
+
+ @override
+ Future<void> probeEngines(String machineId, {bool force = false}) async {}
+
+ @override
+ Future<void> probeDsh(String machineId, {bool force = false}) async {}
+
+ @override
+ Future<Map<String, dynamic>> listCodexProfiles(
+ String machineId, {
+ Set<String> observedPaths = const {},
+ }) async => {
+ 'profiles': [
+ {'path': '/profiles/work', 'label': 'Work'},
+ ],
+ };
+
+ @override
+ Future<Map<String, dynamic>> listRemoteFolder(
+ String machineId,
+ String? path,
+ ) async => {'path': path ?? '/Users/dev', 'entries': []};
+
+ @override
+ Future<String?> installDsh(
+ String machineId,
+ String id, {
+ bool trustUnverified = false,
+ }) async {
+ installs.add(id);
+ final state = machineStates[machineId]!;
+ state.dsh.runs.remove(id);
+ narrate('clone');
+ final error = await (pendingInstall?.future ?? Future.value(null));
+ if (error == null) {
+ if (state.dsh.runs[id]?.done != true) narrate('done');
+ state.dsh.replace([_tool(installed: true)]);
+ } else {
+ state.dsh.failInstall(id, error);
+ }
+ notifyListeners();
+ return error;
+ }
+
+ void narrate(String phase, {String? line, String? code, DateTime? at}) {
+ machineStates['machine']!.dsh.applyInstall(
+ DshInstallProgress(id: _toolId, phase: phase, line: line, code: code),
+ now: at,
+ );
+ notifyListeners();
+ }
+
+ @override
+ Future<String?> createAgent(
+ String machineId, {
+ required String engine,
+ required String? folder,
+ bool bypassPermission = false,
+ String? permissionMode,
+ String? codexHome,
+ String? dsh,
+ GridModel? model,
+ String? prompt,
+ String? name,
+ String? agent,
+ ProjectFolderRequest? projectFolder,
+ String? swarmId,
+ PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
+ }) async {
+ launches.add({
+ 'engine': engine,
+ 'dsh': dsh,
+ 'prompt': prompt,
+ 'projectFolder': projectFolder,
+ });
+ return 'Synthetic launch boundary';
+ }
+}
+
+class _Fixture {
+ _Fixture(this.app, this.box, this.map);
+ final _App app;
+ final NewHarnessController box;
+ final MemoryKeymap map;
+ int closes = 0;
+}
+
+Future<_Fixture> _mount(
+ WidgetTester tester, {
+ String? harness,
+ String engine = 'codex',
+ bool withKeymap = true,
+ bool pendingInstall = false,
+ Size size = const Size(1000, 800),
+ double scale = 1,
+ List<DshEntry>? catalog,
+ NewHarnessDraft? draft,
+}) async {
+ final app = _App();
+ if (catalog != null) app.machineStates['machine']!.dsh.replace(catalog);
+ if (pendingInstall) app.pendingInstall = Completer<String?>();
+ final box = NewHarnessController(
+ app,
+ machineId: 'machine',
+ engine: engine,
+ harnessId: harness,
+ folder: '/work/repo',
+ draft: draft,
+ offersStore: true,
+ );
+ final map = MemoryKeymap();
+ final fixture = _Fixture(app, box, map);
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ addTearDown(map.dispose);
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final form = NewHarnessForm(
+ controller: box,
+ desktop: true,
+ onClose: () => fixture.closes++,
+ onCreated: () => fail('Synthetic fixture must not start a real session'),
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid
+ .buildAppTheme(brightness: Brightness.dark)
+ .copyWith(platform: TargetPlatform.macOS),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: withKeymap
+ ? KeymapProvider(
+ keymap: map,
+ child: KeymapHost(
+ keymap: map,
+ enabled: () => true,
+ actions: const {},
+ child: form,
+ ),
+ )
+ : form,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return fixture;
+}
+
+final _task = find.byKey(const ValueKey('new-harness-task'));
+final _query = find.byKey(const ValueKey('new-harness-query'));
+final _start = find.byKey(const ValueKey('new-harness-field-start'));
+final _install = find.byKey(const ValueKey('new-harness-install'));
+
+void main() {
+ testWidgets(
+ 'desktop setup narrates every stage before a single launch attempt',
+ (tester) async {
+ final fixture = await _mount(
+ tester,
+ harness: _toolId,
+ pendingInstall: true,
+ );
+ await tester.enterText(_task, 'Build the dashboard');
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await tester.pump();
+ expect(fixture.app.installs, [_toolId]);
+ expect(_install, findsOneWidget);
+ expect(find.text('Setting up Review Tool'), findsOneWidget);
+ expect(find.text('Download harness'), findsOneWidget);
+ expect(find.text('Set up tools'), findsOneWidget);
+ expect(find.text('Check requirements'), findsOneWidget);
+ expect(tester.widget<FilledButton>(_start).onPressed, isNull);
+ final began = fixture.box.installRun!.phases.first.at;
+ fixture.app.narrate(
+ 'setup',
+ line: 'Preparing the development environment',
+ at: began.add(const Duration(seconds: 75)),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('1:15'), findsOneWidget);
+ expect(
+ find.text('Preparing the development environment'),
+ findsOneWidget,
+ );
+ fixture.app.narrate(
+ 'doctor',
+ line: 'Checking the tools',
+ at: began.add(const Duration(seconds: 95)),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('Checking the tools'), findsOneWidget);
+ fixture.app.narrate('done', at: began.add(const Duration(seconds: 100)));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('Review Tool is ready'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(fixture.app.installs, hasLength(1));
+ fixture.app.pendingInstall!.complete(null);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ expect(fixture.app.launches.single['prompt'], 'Build the dashboard');
+ expect(_install, findsNothing);
+ expect(fixture.box.task, 'Build the dashboard');
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ for (final (code, detail, expected) in [
+ ('DSH_BUSY', 'Another install owns the lock', 'Wait for it to finish.'),
+ (
+ 'DOCTOR_FAILED',
+ 'miss uv',
+ 'curl -LsSf https://astral.sh/uv/install.sh | sh',
+ ),
+ ]) {
+ testWidgets('desktop $code remains readable and retry preserves the task', (
+ tester,
+ ) async {
+ final fixture = await _mount(
+ tester,
+ harness: _toolId,
+ pendingInstall: true,
+ size: const Size(500, 620),
+ scale: 1.3,
+ );
+ await tester.enterText(_task, 'Keep this task while setting up');
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await tester.pump();
+ fixture.app.narrate('setup');
+ fixture.app.narrate('failed', code: code);
+ fixture.app.pendingInstall!.complete(detail);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, isEmpty);
+ expect(find.text('Review Tool could not be installed'), findsOneWidget);
+ expect(find.text(expected), findsOneWidget);
+ expect(tester.widget<FilledButton>(_start).onPressed, isNotNull);
+ fixture.app.pendingInstall = Completer<String?>();
+ await tester.ensureVisible(_start);
+ await tester.tap(_start);
+ await tester.pump();
+ expect(fixture.app.installs, hasLength(2));
+ fixture.app.pendingInstall!.complete(null);
+ await tester.pumpAndSettle();
+ expect(
+ fixture.app.launches.single['prompt'],
+ 'Keep this task while setting up',
+ );
+ expect(tester.takeException(), isNull);
+ });
+ }
+
+ testWidgets(
+ 'oversized task explains the limit and becomes launchable after editing',
+ (tester) async {
+ final fixture = await _mount(tester);
+ await tester.enterText(_task, 'x' * (kFirstTaskMaxLength + 1));
+ await tester.pumpAndSettle();
+ expect(fixture.box.taskTooLong, isTrue);
+ expect(find.text('Your message is too long.'), findsOneWidget);
+ expect(fixture.box.error, contains('${kFirstTaskMaxLength + 1}'));
+ expect(tester.widget<FilledButton>(_start).onPressed, isNull);
+ await tester.enterText(_task, 'A short task');
+ await tester.pumpAndSettle();
+ expect(fixture.box.error, isNull);
+ expect(tester.widget<FilledButton>(_start).onPressed, isNotNull);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'standalone desktop composer submits on Return and closes with Escape',
+ (tester) async {
+ final fixture = await _mount(tester, withKeymap: false);
+ await tester.enterText(_task, 'A fallback keyboard task');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(1));
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await tester.pumpAndSettle();
+ expect(fixture.app.launches, hasLength(2));
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(fixture.closes, 1);
+ },
+ );
+
+ for (final withKeymap in [false, true]) {
+ testWidgets(
+ 'Repo machine keyboard traversal works with keymap=$withKeymap',
+ (tester) async {
+ final fixture = await _mount(tester, withKeymap: withKeymap);
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-field-project')),
+ );
+ await tester.pumpAndSettle();
+ final machine = find.byKey(const ValueKey('new-harness-repo-machine'));
+ bool queryFocused() =>
+ tester.widget<TextField>(_query).focusNode!.hasFocus;
+ expect(queryFocused(), isTrue);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(queryFocused(), isFalse);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(queryFocused(), isTrue);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(tester.widget<DesktopPill>(machine).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await tester.pumpAndSettle();
+ final choice = find.byKey(
+ const ValueKey('new-harness-machine-option-machine'),
+ );
+ expect(choice, findsOneWidget);
+ tester
+ .state<NewHarnessFormState>(find.byType(NewHarnessForm))
+ .dismissFromOutside();
+ await tester.pumpAndSettle();
+ expect(choice, findsNothing);
+ expect(_query, findsOneWidget);
+ // Repeated activation toggles the cascade without closing Repo.
+ await tester.tap(machine);
+ await tester.pumpAndSettle();
+ expect(choice, findsOneWidget);
+ tester.widget<DesktopPill>(machine).onPressed!();
+ await tester.pumpAndSettle();
+ expect(choice, findsNothing);
+ await key(tester, LogicalKeyboardKey.tab);
+ await tester.pumpAndSettle();
+ expect(_query, findsNothing);
+ expect(fixture.closes, 0);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+ }
+
+ testWidgets('Repo refuses a machine that vanished before a menu click', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ fixture.app.machineStates['other'] = MachineState(
+ const Machine(
+ machineId: 'other',
+ name: 'Other Mac',
+ authMode: MachineAuthMode.remote,
+ ),
+ )..nodeOnline = true;
+ fixture.app.notifyListeners();
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-project')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('new-harness-repo-machine')));
+ await tester.pumpAndSettle();
+ final choice = find.byKey(
+ const ValueKey('new-harness-machine-option-other'),
+ );
+ expect(choice, findsOneWidget);
+ fixture.app.machineStates.remove('other');
+ await tester.tap(choice);
+ await tester.pumpAndSettle();
+ expect(fixture.box.machineId, 'machine');
+ expect(fixture.box.error, 'This machine is no longer available.');
+ expect(fixture.app.launches, isEmpty);
+ });
+
+ testWidgets('Escape closes the chooser before the composer close button', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-project')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('new-harness-repo-machine')));
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('new-harness-machine-option-machine')),
+ findsOneWidget,
+ );
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ fixture.box.warn('Choose an installed agent to continue.');
+ await tester.pumpAndSettle();
+ expect(find.text('Choose an installed agent to continue.'), findsWidgets);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(fixture.box.field, NewHarnessField.projectMenu);
+ expect(_query, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_query, findsNothing);
+ expect(fixture.closes, 0);
+ await tester.tap(find.byKey(const ValueKey('new-harness-close')));
+ expect(fixture.closes, 1);
+ });
+
+ testWidgets('Change machine backs to the same nested folder prompt', (
+ tester,
+ ) async {
+ final fixture = await _mount(tester);
+ fixture.app.machineStates['other'] = MachineState(
+ const Machine(
+ machineId: 'other',
+ name: 'Other Mac',
+ authMode: MachineAuthMode.remote,
+ ),
+ )..localOnly = true;
+ fixture.app.notifyListeners();
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-project')));
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(
+ const ValueKey(
+ 'new-harness-option-${NewHarnessController.existingProjectId}',
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, '~developer');
+ await tester.pumpAndSettle();
+ final changeMachine = find.byKey(
+ const ValueKey(
+ 'new-harness-option-${NewHarnessController.changeMachineId}',
+ ),
+ );
+ final chooserBounds = tester.getRect(
+ find.byKey(const ValueKey('new-harness-chooser-surface')),
+ );
+ final rowBounds = tester.getRect(changeMachine);
+ expect(
+ rowBounds.bottom,
+ lessThanOrEqualTo(chooserBounds.bottom),
+ reason: 'Both folder actions must fit: $rowBounds in $chooserBounds.',
+ );
+ await tester.tap(changeMachine);
+ await tester.pumpAndSettle();
+ expect(fixture.box.field, NewHarnessField.machine);
+ await tester.tap(find.byKey(const ValueKey('new-harness-chooser-back')));
+ await tester.pumpAndSettle();
+ expect(fixture.box.field, NewHarnessField.project);
+ expect(fixture.closes, 0);
+ expect(fixture.app.launches, isEmpty);
+ });
+
+ testWidgets(
+ 'clicking the composer outside its chooser preserves the draft and dialog',
+ (tester) async {
+ final fixture = await _mount(tester);
+ await tester.enterText(_task, 'Keep my review notes');
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-project')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('new-harness-repo-machine')));
+ await tester.pumpAndSettle();
+ final surface = tester.getRect(
+ find.byKey(const ValueKey('new-harness-surface')),
+ );
+ final chooser = tester.getRect(
+ find.byKey(const ValueKey('new-harness-chooser-surface')),
+ );
+ final outside = surface.topLeft + const Offset(12, 12);
+ expect(chooser.contains(outside), isFalse);
+ await tester.tapAt(outside);
+ await tester.pumpAndSettle();
+ expect(_query, findsOneWidget);
+ await tester.tapAt(outside);
+ await tester.pumpAndSettle();
+ expect(_query, findsNothing);
+ expect(fixture.closes, 0);
+ expect(fixture.box.task, 'Keep my review notes');
+ expect(fixture.box.machineId, 'machine');
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'large desktop catalogs page through native rows without launching',
+ (tester) async {
+ final fixture = await _mount(
+ tester,
+ catalog: [for (var i = 0; i < 80; i++) _tool(id: 'autonomous/tool-$i')],
+ );
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-agent')));
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(fixture.box.cursor, greaterThan(0));
+ await key(tester, LogicalKeyboardKey.pageUp);
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'clone drafts carry the exact repository preparation into launch options',
+ (tester) async {
+ final repository = GitHubRepository.parse('openai/codex')!;
+ final fixture = await _mount(
+ tester,
+ draft: NewHarnessDraft(
+ machineId: 'machine',
+ engine: 'codex',
+ project: NewHarnessProject.clone(repository),
+ task: 'Review this repository',
+ permissionMode: 'full',
+ ),
+ );
+ expect(fixture.box.projectFolderRequest!.repository!.url, repository.url);
+ expect(fixture.box.task, 'Review this repository');
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'terminal selection keeps a task draft and explains its later return',
+ (tester) async {
+ final fixture = await _mount(tester);
+ await tester.enterText(_task, 'Keep this for an agent');
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-agent')));
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, 'terminal');
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-option-terminal')),
+ );
+ await tester.pumpAndSettle();
+ expect(fixture.box.engine, 'terminal');
+ expect(
+ find.text('Your task is kept when you switch agents.'),
+ findsOneWidget,
+ );
+ expect(tester.widget<TextField>(_task).readOnly, isTrue);
+ expect(_query, findsNothing);
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-agent')));
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, 'codex');
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('new-harness-option-codex')));
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(_task).controller!.text,
+ 'Keep this for an agent',
+ );
+ expect(tester.widget<TextField>(_task).readOnly, isFalse);
+ expect(fixture.app.launches, isEmpty);
+ },
+ );
+
+ testWidgets('direct profile chooser stays visible at enlarged text', (
+ tester,
+ ) async {
+ final fixture = await _mount(
+ tester,
+ size: const Size(760, 700),
+ scale: 1.5,
+ );
+ final profile = find.byKey(const ValueKey('new-harness-field-profile'));
+ await tester.ensureVisible(profile);
+ await tester.tap(profile);
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<Semantics>(find.byKey(const ValueKey('new-harness-choices')))
+ .properties
+ .label,
+ 'Codex profile',
+ );
+ expect(find.text('Codex profile'), findsNothing);
+ expect(
+ find.byKey(const ValueKey('new-harness-chooser-surface')).hitTestable(),
+ findsOneWidget,
+ );
+ expect(tester.takeException(), isNull);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(fixture.closes, 0);
+ });
+}
diff --git a/desktop/test/desktop_palette_layout_test.dart b/desktop/test/desktop_palette_layout_test.dart
new file mode 100644
index 000000000..cf2d99e86
--- /dev/null
+++ b/desktop/test/desktop_palette_layout_test.dart
@@ -0,0 +1,157 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/terminal_pane.dart';
+import 'package:harness/widgets/layout_palette.dart';
+import 'package:harness/widgets/move_pane_palette.dart';
+import 'package:harness/widgets/swarm_dialogs.dart';
+
+import 'support/real_fonts.dart';
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
+ if (Platform.isMacOS &&
+ Platform.environment['HARNESS_PALETTE_CAPTURE_DIR'] != null) {
+ final font = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(font))).load();
+ }
+ }
+ await (FontLoader(
+ 'MaterialIcons',
+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
+ });
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.7]) {
+ for (final surface in ['layout', 'move', 'rename']) {
+ final move = surface == 'move';
+ final rename = surface == 'rename';
+ testWidgets(
+ '$surface is readable and reachable in ${brightness.name} at $scale',
+ (tester) async {
+ final size = scale == 1
+ ? const Size(860, 620)
+ : const Size(420, 460);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);
+ final app = createApp();
+ final source = app.activeSwarmId;
+ app.panes.addAll([
+ for (var i = 0; i < 4; i++)
+ TerminalPane(id: i, machineId: 'm', agentId: 'a$i'),
+ ]);
+ for (var i = 0; i < 16; i++) {
+ app.newSwarm(name: 'Project ${i + 1} · workspace review');
+ }
+ app.selectSwarm(source);
+ app.focusPane(0);
+ final key = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: key,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(scale),
+ disableAnimations: true,
+ ),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => rename
+ ? showSwarmRenameDialog(context, 'Desktop')
+ : move
+ ? showMovePanePalette(context, app)
+ : showLayoutPalette(context, app),
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ if (move) {
+ // Wrapping the keyboard selection must reveal an offscreen row.
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await tester.pumpAndSettle();
+ final last = tester.getRect(find.text('New Tab'));
+ expect(last.top, greaterThan(0));
+ expect(last.bottom, lessThan(size.height));
+ }
+ final dismiss = rename
+ ? find.text('Cancel')
+ : find.byTooltip('Close');
+ final close = tester.getRect(dismiss);
+ expect(close.top, greaterThanOrEqualTo(24));
+ expect(close.bottom, lessThan(size.height - 24));
+ final directory =
+ Platform.environment['HARNESS_PALETTE_CAPTURE_DIR'];
+ if (directory != null) {
+ final previousShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ final boundary =
+ key.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ void repaint(RenderObject object) {
+ object.markNeedsPaint();
+ object.visitChildren(repaint);
+ }
+
+ repaint(boundary);
+ await tester.pump();
+ await tester.runAsync(() async {
+ final image = await boundary.toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$surface-${brightness.name}-$scale.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ debugDisableShadows = previousShadows;
+ repaint(boundary);
+ await tester.pump();
+ }
+ await tester.tap(dismiss);
+ await tester.pumpAndSettle();
+ expect(app.activeSwarmId, source);
+ expect(
+ app.panes.length,
+ 4,
+ reason: 'Reviewing must not change the workspace',
+ );
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+ }
+ }
+ }
+}
diff --git a/desktop/test/desktop_preview_compatibility_test.dart b/desktop/test/desktop_preview_compatibility_test.dart
new file mode 100644
index 000000000..dd546c906
--- /dev/null
+++ b/desktop/test/desktop_preview_compatibility_test.dart
@@ -0,0 +1,464 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/session_content_search.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/store/store_mark.dart';
+import 'package:harness/terminal/terminal_text.dart';
+import 'package:harness/terminal/terminal_theme.dart';
+import 'package:harness/terminal/terminal_theme_store.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/swarm_search_preview.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+
+import 'keymap_host_test.dart' show key;
+import 'session_search_rendering_test.dart' show TailConnection;
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_search_preview_test.dart' show seedPreviews;
+import 'swarm_state_test.dart' show createApp;
+
+class _ReviewPalette {
+ _ReviewPalette(this.search);
+
+ final SwarmSearchController search;
+ final editor = TextEditingController();
+ final focus = FocusNode();
+ final chosen = <SwarmSearchSelection>[];
+
+ void dispose() {
+ search.dispose();
+ editor.dispose();
+ focus.dispose();
+ }
+}
+
+const _inputKey = ValueKey('review-search-input');
+final _input = find.byKey(_inputKey);
+
+Future<_ReviewPalette> _mount(
+ WidgetTester tester,
+ SwarmSearchController search, {
+ bool desktop = false,
+ bool bios = false,
+ bool showPreview = true,
+}) async {
+ final fixture = _ReviewPalette(search);
+ addTearDown(fixture.dispose);
+ tester.view.physicalSize = const Size(1000, 780);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final content = SwarmSearchKeys(
+ search: search,
+ desktop: desktop,
+ editing: fixture.editor,
+ onChoose: fixture.chosen.add,
+ onClose: () {},
+ onRefocus: fixture.focus.requestFocus,
+ child: Column(
+ children: [
+ TextField(
+ key: _inputKey,
+ controller: fixture.editor,
+ focusNode: fixture.focus,
+ autofocus: true,
+ onChanged: search.setQuery,
+ ),
+ Expanded(
+ child: SwarmSearchResults(
+ search: search,
+ terminal: true,
+ bios: bios,
+ showPreview: showPreview,
+ onChoose: fixture.chosen.add,
+ onRefocus: fixture.focus.requestFocus,
+ ),
+ ),
+ ],
+ ),
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 620,
+ height: 720,
+ child: desktop ? DesktopChrome(child: content) : content,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump();
+ });
+ return fixture;
+}
+
+Future<void> _query(WidgetTester tester, String value) async {
+ await tester.enterText(_input, value);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pump(const Duration(milliseconds: 160));
+ await tester.pumpAndSettle();
+}
+
+void main() {
+ testWidgets(
+ 'terminal command preview keeps context and invokes only on Enter',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final command = SwarmDestination(
+ id: 'command:release.check',
+ commandId: 'release.check',
+ title: 'Check release',
+ detail: 'Inspect the release configuration',
+ shortcut: '⌘⇧R',
+ swarmId: null,
+ current: false,
+ );
+ final fixture = await _mount(
+ tester,
+ SwarmSearchController(
+ app,
+ const [],
+ activityFirst: true,
+ commands: () => [command],
+ ),
+ );
+ await _query(tester, '> release');
+ final preview = find.byType(SwarmSearchPreview);
+ expect(preview, findsOneWidget);
+ for (final text in [command.title, command.detail, command.shortcut!]) {
+ final label = find.descendant(of: preview, matching: find.text(text));
+ expect(label, findsOneWidget);
+ expect(
+ tester.widget<Text>(label).style!.fontFamily,
+ terminalContentStyle().fontFamily,
+ );
+ }
+ expect(fixture.chosen, isEmpty);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(fixture.chosen.single.destination.commandId, 'release.check');
+ expect(fixture.editor.text, '> release');
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'dated older content matches remain distinct from the latest turn',
+ (tester) async {
+ final earlier = DateTime.now().subtract(
+ const Duration(hours: 18, minutes: 5),
+ );
+ final connection = TailConnection(
+ {
+ 'retention cohorts': [
+ {
+ 'agentId': 'a7',
+ 'sessionId': 's7',
+ 'field': 'ask',
+ 'turn': 2,
+ 'at': earlier.millisecondsSinceEpoch,
+ 'snippet':
+ 'Compare ${kSnippetMarkOpen}retention$kSnippetMarkClose by cohort',
+ 'together': true,
+ 'score': .9,
+ },
+ ],
+ },
+ tail: (_) => {
+ 'rows': [
+ {
+ 'turn': 10,
+ 'at': DateTime.now().millisecondsSinceEpoch,
+ 'ask': 'Verify the latest report',
+ 'answer': 'Newest report verified.',
+ 'tools': '',
+ },
+ ],
+ 'hasMore': false,
+ 'total': 11,
+ },
+ );
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ const Agent(
+ id: 'a7',
+ sessionId: 's7',
+ name: 'Cohort report',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ ];
+ final fixture = await _mount(
+ tester,
+ SwarmSearchController(app, const [], adding: true, activityFirst: true),
+ );
+ await _query(tester, 'retention cohorts');
+ final preview = find.byType(SwarmSearchPreview);
+ expect(find.text('Matched earlier · 18h ago'), findsOneWidget);
+ expect(
+ find.descendant(
+ of: preview,
+ matching: find.textContaining(
+ 'Compare retention by cohort',
+ findRichText: true,
+ ),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.textContaining('Newest report verified.', findRichText: true),
+ findsOneWidget,
+ );
+ expect(fixture.search.selected!.agentId, 'a7');
+ expect(fixture.focus.hasFocus, isTrue);
+ expect(fixture.chosen, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'terminal preview explains an external conversation that is open elsewhere',
+ (tester) async {
+ final connection = TailConnection(
+ {
+ 'retention cohorts': [
+ {
+ 'agentId': '',
+ 'sessionId': 'external-session',
+ 'engine': 'codex',
+ 'field': 'ask',
+ 'snippet': 'Review retention cohorts',
+ 'score': .9,
+ 'external': {
+ 'title': 'External cohort report',
+ 'cwd': '/work/cohorts',
+ 'origin': 'codex-app',
+ 'open': true,
+ 'openIn': 'app',
+ },
+ },
+ ],
+ },
+ tail: (_) => {
+ 'rows': [],
+ 'hasMore': false,
+ 'external': {'open': true, 'openIn': 'app'},
+ },
+ );
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ addTearDown(app.dispose);
+ final fixture = await _mount(
+ tester,
+ SwarmSearchController(app, const [], adding: true, activityFirst: true),
+ );
+ await _query(tester, 'retention cohorts');
+ expect(fixture.search.selected!.external!.sessionId, 'external-session');
+ final warning = find.text(
+ 'Open in the Codex app. Close it there to open it here.',
+ );
+ expect(warning, findsOneWidget);
+ expect(
+ tester.widget<Text>(warning).style!.color,
+ terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ ).yellow,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(fixture.chosen, isEmpty);
+ expect(fixture.editor.text, 'retention cohorts');
+ expect(fixture.focus.hasFocus, isTrue);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ for (final bios in [false, true]) {
+ testWidgets('legacy empty results recover after editing (bios=$bios)', (
+ tester,
+ ) async {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final fixture = await _mount(
+ tester,
+ SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersHarnessCreate: false,
+ ),
+ bios: bios,
+ showPreview: false,
+ );
+ await _query(tester, 'unmatched-999999');
+ final message = find.text('No matching harnesses');
+ expect(message, findsOneWidget);
+ expect(fixture.search.selected, isNull);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(fixture.chosen, isEmpty);
+ await _query(tester, 'Agent 1');
+ expect(message, findsNothing);
+ expect(fixture.search.selected, isNotNull);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(fixture.chosen.single.destination.agentId, 'a1');
+ expect(tester.takeException(), isNull);
+ });
+ }
+
+ testWidgets(
+ 'bottom-up terminal results keep the preview above and keyboard scrolling independent',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await seedPreviews(app);
+ for (final agentId in ['a1', 'a2']) {
+ await app.handleEventForTest('m', {
+ 'type': 'turn_ended',
+ 'payload': {'agentId': agentId, 'sessionId': 'session-$agentId'},
+ });
+ }
+ final agent = app.machineStates['m']!.agents.first;
+ app.sessionPreviews.read(app.previewKey('m', agent))!.completedText =
+ List.generate(60, (i) => 'Explanation line $i').join('\n');
+ final fixture = await _mount(
+ tester,
+ SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ resultsFromBottom: true,
+ ),
+ );
+ await _query(tester, 'Checkout retries');
+ final preview = find.byType(SwarmSearchPreview);
+ final results = find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics && widget.properties.label == 'Search results',
+ );
+ expect(tester.getRect(results).top - tester.getRect(preview).bottom, 8);
+ final scrolling = tester
+ .state<ScrollableState>(
+ find
+ .descendant(of: preview, matching: find.byType(Scrollable))
+ .first,
+ )
+ .position;
+ final selected = fixture.search.selected!.id;
+ await key(tester, LogicalKeyboardKey.arrowDown, shift: true);
+ expect(scrolling.pixels, greaterThan(0));
+ expect(fixture.search.selected!.id, selected);
+ expect(fixture.editor.text, 'Checkout retries');
+ expect(fixture.focus.hasFocus, isTrue);
+ expect(fixture.chosen, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'desktop history gives the Store its own mark and activates its existing tab',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.openStore();
+ final storeId = app.activeSwarmId;
+ app.newSwarm(name: 'Work');
+ final history = SwarmNavigationHistory();
+ addTearDown(history.dispose);
+ app.selectSwarm(storeId);
+ history.record(app);
+ final fixture = await _mount(
+ tester,
+ SwarmSearchController(app, history.recent, history: history),
+ desktop: true,
+ showPreview: false,
+ );
+ await _query(tester, 'Harness Store');
+ expect(fixture.search.selected!.isStore, isTrue);
+ final row = find.byKey(ValueKey(swarmDestinationId(storeId)));
+ expect(
+ find.descendant(of: row, matching: find.byType(StoreMark)),
+ findsOneWidget,
+ );
+ await tester.tap(row);
+ await tester.pump();
+ expect(fixture.chosen.single.destination.swarmId, storeId);
+ expect(fixture.chosen.single.destination.isStore, isTrue);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'a full desktop tab explains recovery and a new tab can open a result',
+ (tester) async {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = app.machineStates['m']!.agents
+ .take(AppNotifier.maxPanes)
+ .toList();
+ for (var i = 0; i < AppNotifier.maxPanes; i++) {
+ app.adoptSessionForTest(terminal('a$i', []));
+ }
+ final fullTab = app.activeSwarm;
+ final full = await _mount(
+ tester,
+ SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersHarnessCreate: false,
+ ),
+ desktop: true,
+ showPreview: false,
+ );
+ expect(full.search.capacity, 0);
+ expect(full.search.rows, isEmpty);
+ expect(
+ find.text(
+ 'This tab is full (${AppNotifier.maxPanes} panes). Open a new tab to add more.',
+ ),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(full.chosen, isEmpty);
+ expect(fullTab.panes, hasLength(AppNotifier.maxPanes));
+
+ app.newSwarm(name: 'Another task');
+ final available = await _mount(
+ tester,
+ SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersHarnessCreate: false,
+ ),
+ desktop: true,
+ showPreview: false,
+ );
+ await _query(tester, 'Agent 0');
+ expect(available.search.capacity, AppNotifier.maxPanes);
+ expect(find.textContaining('This tab is full'), findsNothing);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(available.chosen.single.destination.agentId, 'a0');
+ expect(available.search.targetId, app.activeSwarmId);
+ expect(fullTab.panes, hasLength(AppNotifier.maxPanes));
+ expect(tester.takeException(), isNull);
+ },
+ );
+}
diff --git a/desktop/test/desktop_remote_folder_picker_test.dart b/desktop/test/desktop_remote_folder_picker_test.dart
new file mode 100644
index 000000000..4aac3fb70
--- /dev/null
+++ b/desktop/test/desktop_remote_folder_picker_test.dart
@@ -0,0 +1,688 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/remote_folder_picker.dart';
+import 'package:harness/widgets/swarm_dialogs.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+
+final _renderDir = Platform.environment['DESKTOP_REMOTE_FOLDER_RENDER_DIR'];
+final _picture = GlobalKey();
+
+Future<void> _capture(WidgetTester tester, String name) async {
+ if (_renderDir == null) return;
+ await tester.runAsync(() async {
+ final boundary =
+ _picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ Directory(_renderDir!).createSync(recursive: true);
+ await File('$_renderDir/$name.png')
+ .writeAsBytes(data!.buffer.asUint8List());
+ image.dispose();
+ });
+}
+
+class _Folders extends AppNotifier {
+ _Folders()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ ) {
+ machineStates['remote'] = MachineState(
+ const Machine(
+ machineId: 'remote',
+ name: 'Studio Mac',
+ authMode: MachineAuthMode.remote,
+ ),
+ );
+ }
+
+ final requests =
+ <
+ ({String machine, String? path, Completer<Map<String, dynamic>> reply})
+ >[];
+
+ @override
+ Future<Map<String, dynamic>> listRemoteFolder(
+ String machineId,
+ String? path,
+ ) {
+ final reply = Completer<Map<String, dynamic>>();
+ requests.add((machine: machineId, path: path, reply: reply));
+ return reply.future;
+ }
+}
+
+Map<String, dynamic> _listing(String path, [List<String> names = const []]) => {
+ 'path': path,
+ 'entries': [
+ for (final name in names) {'name': name, 'isDir': true},
+ ],
+};
+
+Future<void> _key(
+ WidgetTester tester,
+ LogicalKeyboardKey key, {
+ bool cmd = false,
+ bool ctrl = false,
+ bool shift = false,
+ bool alt = false,
+}) async {
+ final modifiers = [
+ if (cmd) LogicalKeyboardKey.metaLeft,
+ if (ctrl) LogicalKeyboardKey.controlLeft,
+ if (shift) LogicalKeyboardKey.shiftLeft,
+ if (alt) LogicalKeyboardKey.altLeft,
+ ];
+ for (final modifier in modifiers) {
+ await tester.sendKeyDownEvent(modifier);
+ }
+ await tester.sendKeyEvent(key);
+ for (final modifier in modifiers.reversed) {
+ await tester.sendKeyUpEvent(modifier);
+ }
+ await tester.pump();
+}
+
+Future<_Folders> _open(
+ WidgetTester tester, {
+ ValueChanged<String?>? onResult,
+ TargetPlatform platform = TargetPlatform.macOS,
+ Brightness brightness = Brightness.dark,
+ Size size = const Size(1100, 800),
+ double scale = 1,
+ String? initialPath,
+ bool unknownMachine = false,
+ bool desktop = true,
+ bool addProject = false,
+}) async {
+ final app = _Folders();
+ final callerFocus = FocusNode(debugLabel: 'remote-folder-caller');
+ addTearDown(callerFocus.dispose);
+ if (unknownMachine) app.machineStates.clear();
+ addTearDown(app.dispose);
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid
+ .buildAppTheme(brightness: brightness)
+ .copyWith(platform: platform),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: RepaintBoundary(key: _picture, child: child!),
+ ),
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ focusNode: callerFocus,
+ autofocus: true,
+ onPressed: () async {
+ if (addProject) {
+ final project = await showSwarmProjectDialog(context, app);
+ onResult?.call(project?.path);
+ return;
+ }
+ final result = await showRemoteFolderPicker(
+ context,
+ notifier: app,
+ machineId: 'remote',
+ initialPath: initialPath,
+ desktop: desktop,
+ // Desktop presentation must win over a legacy caller's flag.
+ terminal: true,
+ );
+ onResult?.call(result);
+ },
+ child: const Text('Browse remote'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Browse remote'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ if (addProject) {
+ await tester.ensureVisible(find.text('Choose folder'));
+ await tester.tap(find.text('Choose folder'));
+ await tester.pumpAndSettle();
+ }
+ return app;
+}
+
+TextField _path(WidgetTester tester) =>
+ tester.widget<TextField>(find.byKey(const Key('remote-folder-path')));
+
+FilledButton _select(WidgetTester tester) =>
+ tester.widget<FilledButton>(find.byKey(const Key('remote-folder-select')));
+
+void main() {
+ setUpAll(() async {
+ if (_renderDir != null) await loadPreviewFonts();
+ });
+ testWidgets('folder browser has native chrome and accessible path and rows', (
+ tester,
+ ) async {
+ final app = await _open(tester);
+ final semantics = tester.ensureSemantics();
+ expect(find.byType(DesktopDialogSurface), findsOneWidget);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(_path(tester).focusNode!.hasFocus, isTrue);
+ expect(find.bySemanticsLabel(RegExp('Folder path')), findsOneWidget);
+ expect(_select(tester).onPressed, isNull);
+ app.requests.single.reply.complete(
+ _listing('/Users/dev', ['code', 'notes']),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('On Studio Mac'), findsOneWidget);
+ expect(_select(tester).onPressed, isNotNull);
+ await _capture(tester, 'remote-folder-desktop');
+ final row = tester.getSemantics(find.bySemanticsLabel('code'));
+ expect(row.getSemanticsData().hasAction(ui.SemanticsAction.tap), isTrue);
+ tester
+ .renderObject(find.bySemanticsLabel('code'))
+ .owner!
+ .semanticsOwner!
+ .performAction(row.id, ui.SemanticsAction.tap);
+ await tester.pump();
+ expect(app.requests.last.path, '/Users/dev/code');
+ app.requests.last.reply.complete(_listing('/Users/dev/code'));
+ await tester.pumpAndSettle();
+ expect(find.text('No subfolders here.'), findsOneWidget);
+ expect(
+ app.requests.every((request) => request.machine == 'remote'),
+ isTrue,
+ );
+ semantics.dispose();
+ });
+
+ for (final platform in [TargetPlatform.macOS, TargetPlatform.linux]) {
+ testWidgets('keyboard paths, paging, parent and selection on $platform', (
+ tester,
+ ) async {
+ String? selected;
+ final app = await _open(
+ tester,
+ platform: platform,
+ onResult: (value) => selected = value,
+ );
+ final entries = [for (var i = 0; i < 100; i++) 'project-$i'];
+ app.requests.single.reply.complete(_listing('/Users/dev', entries));
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.arrowDown);
+ expect(FocusManager.instance.primaryFocus!.debugLabel, 'Remote folders');
+ await _key(tester, LogicalKeyboardKey.pageDown);
+ await _key(tester, LogicalKeyboardKey.pageUp);
+ await _key(tester, LogicalKeyboardKey.end);
+ expect(find.text('project-99').hitTestable(), findsOneWidget);
+ await _key(tester, LogicalKeyboardKey.home);
+ expect(find.text('project-0').hitTestable(), findsOneWidget);
+ await _key(tester, LogicalKeyboardKey.arrowDown);
+ await _key(tester, LogicalKeyboardKey.arrowRight);
+ expect(app.requests.last.path, '/Users/dev/project-1');
+ app.requests.last.reply.complete(
+ _listing('/Users/dev/project-1', ['src']),
+ );
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.arrowUp, alt: true);
+ expect(app.requests.last.path, '/Users/dev');
+ app.requests.last.reply.complete(_listing('/Users/dev', entries));
+ await tester.pumpAndSettle();
+ final mac = platform == TargetPlatform.macOS;
+ await _key(tester, LogicalKeyboardKey.keyL, cmd: mac, ctrl: !mac);
+ expect(_path(tester).focusNode!.hasFocus, isTrue);
+ expect(
+ _path(tester).controller!.selection,
+ const TextSelection(baseOffset: 0, extentOffset: 10),
+ );
+ await tester.enterText(
+ find.byKey(const Key('remote-folder-path')),
+ '/Users/dev/new',
+ );
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ expect(app.requests.last.path, '/Users/dev/new');
+ app.requests.last.reply.complete(_listing('/Users/dev/new'));
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.keyR, cmd: mac, ctrl: !mac);
+ expect(app.requests.last.path, '/Users/dev/new');
+ app.requests.last.reply.complete(_listing('/Users/dev/new'));
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.enter, cmd: mac, ctrl: !mac);
+ await tester.pumpAndSettle();
+ expect(selected, '/Users/dev/new');
+ expect(find.byType(DesktopDialogSurface), findsNothing);
+ });
+ }
+
+ testWidgets('Mac go-to-folder and Back/Home preserve the folder history', (
+ tester,
+ ) async {
+ final app = await _open(tester, initialPath: '/Users/dev/code');
+ app.requests.single.reply.complete(_listing('/Users/dev/code', ['src']));
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.arrowUp, cmd: true);
+ expect(app.requests.last.path, '/Users/dev');
+ app.requests.last.reply.complete(_listing('/Users/dev', ['code', 'notes']));
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.keyG, cmd: true, shift: true);
+ expect(_path(tester).focusNode!.hasFocus, isTrue);
+ await tester.tap(find.byKey(const Key('remote-folder-up')));
+ expect(app.requests.last.path, '/Users');
+ app.requests.last.reply.complete(_listing('/Users'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('remote-folder-home')));
+ expect(app.requests.last.path, isNull);
+ app.requests.last.reply.complete(_listing('/Users/dev'));
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets('held Enter cannot walk into another folder after a reply', (
+ tester,
+ ) async {
+ final app = await _open(tester);
+ app.requests.single.reply.complete(_listing('/Users/dev', ['code']));
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ app.requests.last.reply.complete(_listing('/Users/dev/code', ['src']));
+ await tester.pumpAndSettle();
+ await tester.sendKeyRepeatEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.enter);
+ expect(app.requests, hasLength(2));
+ });
+
+ testWidgets('composition retains Escape, navigation and modified Enter', (
+ tester,
+ ) async {
+ var closed = false;
+ final app = await _open(tester, onResult: (_) => closed = true);
+ app.requests.single.reply.complete(_listing('/Users/日本語', ['code']));
+ await tester.pumpAndSettle();
+ final value = TextEditingValue(
+ text: '/Users/日本語',
+ selection: const TextSelection.collapsed(offset: 10),
+ composing: const TextRange(start: 7, end: 10),
+ );
+ tester.testTextInput.updateEditingValue(value);
+ await tester.pump();
+ for (final key in [
+ LogicalKeyboardKey.arrowDown,
+ LogicalKeyboardKey.escape,
+ ]) {
+ await _key(tester, key);
+ }
+ await _key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await _key(tester, LogicalKeyboardKey.keyL, cmd: true);
+ await _key(tester, LogicalKeyboardKey.keyR, cmd: true);
+ expect(_path(tester).focusNode!.hasFocus, isTrue);
+ expect(_path(tester).controller!.value, value);
+ expect(closed, isFalse);
+ expect(app.requests, hasLength(1));
+ tester.testTextInput.updateEditingValue(
+ value.copyWith(composing: TextRange.empty),
+ );
+ await _key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(closed, isTrue);
+ });
+
+ testWidgets('typing and newer requests win over late replies', (
+ tester,
+ ) async {
+ final app = await _open(tester);
+ await tester.enterText(
+ find.byKey(const Key('remote-folder-path')),
+ '/Users/dev/new',
+ );
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ app.requests.last.reply.complete(_listing('/Users/dev/new', ['src']));
+ await tester.pumpAndSettle();
+ app.requests.first.reply.complete(_listing('/old', ['old']));
+ await tester.pumpAndSettle();
+ expect(_path(tester).controller!.text, '/Users/dev/new');
+ expect(find.text('old'), findsNothing);
+ await tester.tap(find.byKey(const Key('remote-folder-refresh')));
+ await tester.enterText(
+ find.byKey(const Key('remote-folder-path')),
+ '/draft',
+ );
+ app.requests.last.reply.complete(
+ _listing('/Users/dev/new', ['src', 'tests']),
+ );
+ await tester.pumpAndSettle();
+ expect(_path(tester).controller!.text, '/draft');
+ expect(_select(tester).onPressed, isNull);
+ expect(find.text('Showing /Users/dev/new'), findsOneWidget);
+ });
+
+ testWidgets(
+ 'request exceptions recover through Home and malformed listings stay safe',
+ (tester) async {
+ final app = await _open(tester);
+ app.requests.single.reply.completeError(StateError('connection closed'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ 'Couldn’t reach this machine. Check its connection and retry.',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('remote-folder-home')));
+ app.requests.last.reply.complete({'path': ''});
+ await tester.pumpAndSettle();
+ expect(_select(tester).onPressed, isNull);
+ await tester.tap(find.text('Retry'));
+ app.requests.last.reply.complete({
+ 'path': '/',
+ 'entries': [
+ {'name': 'Users', 'isDir': true},
+ {'name': 'file.txt', 'isDir': false},
+ {'name': ''},
+ {'name': 123},
+ 'malformed',
+ ],
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Users'), findsOneWidget);
+ expect(find.text('file.txt'), findsNothing);
+ expect(
+ tester
+ .widget<DesktopPill>(find.byKey(const Key('remote-folder-up')))
+ .onPressed,
+ isNull,
+ );
+ expect(_select(tester).onPressed, isNotNull);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'terminal callers keep their previous presentation and cancellation',
+ (tester) async {
+ String? result;
+ var closed = false;
+ final app = await _open(
+ tester,
+ desktop: false,
+ onResult: (value) {
+ closed = true;
+ result = value;
+ },
+ );
+ app.requests.single.reply.complete({
+ ..._listing('/home/dev', ['code']),
+ 'truncated': true,
+ });
+ await tester.pumpAndSettle();
+ expect(find.byType(AlertDialog), findsOneWidget);
+ expect(find.byType(DesktopDialogSurface), findsNothing);
+ expect(
+ find.text(
+ 'More folders are available. Enter their full path to open them.',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(closed, isTrue);
+ expect(result, isNull);
+ },
+ );
+
+ for (final error in [
+ 'FORBIDDEN',
+ 'PERMISSION_DENIED',
+ 'NOT_A_DIRECTORY',
+ 'NOT_FOUND',
+ 'INVALID_PATH',
+ 'UNREACHABLE',
+ 'UNKNOWN',
+ ]) {
+ testWidgets('$error offers a focused, repeat-safe Retry', (tester) async {
+ final app = await _open(tester, initialPath: '/Users/dev/missing');
+ app.requests.single.reply.complete({'error': error});
+ await tester.pumpAndSettle();
+ expect(_select(tester).onPressed, isNull);
+ expect(find.text('Retry'), findsOneWidget);
+ if (error == 'NOT_FOUND') await _capture(tester, 'remote-folder-error');
+ await tester.tap(find.text('Retry'));
+ await tester.tap(find.text('Retry'));
+ await tester.pump();
+ expect(app.requests, hasLength(2));
+ expect(_path(tester).focusNode!.hasFocus, isTrue);
+ expect(app.requests.last.path, '/Users/dev/missing');
+ app.requests.last.reply.complete(_listing('/Users/dev/missing'));
+ await tester.pumpAndSettle();
+ expect(find.text('Retry'), findsNothing);
+ expect(_select(tester).onPressed, isNotNull);
+ expect(tester.takeException(), isNull);
+ });
+ }
+
+ for (final dismissal in ['Cancel', 'Escape', 'backdrop']) {
+ testWidgets(
+ '$dismissal ignores a late response and restores caller focus',
+ (tester) async {
+ var closed = false;
+ String? selection;
+ final app = await _open(
+ tester,
+ onResult: (value) {
+ closed = true;
+ selection = value;
+ },
+ );
+ if (dismissal == 'Cancel') {
+ await tester.tap(find.text('Cancel'));
+ } else if (dismissal == 'Escape') {
+ await _key(tester, LogicalKeyboardKey.escape);
+ } else {
+ await tester.tapAt(const Offset(2, 2));
+ }
+ await tester.pumpAndSettle();
+ app.requests.single.reply.complete(_listing('/Users/dev', ['code']));
+ await tester.pumpAndSettle();
+ expect(closed, isTrue);
+ expect(selection, isNull);
+ expect(find.byType(DesktopDialogSurface), findsNothing);
+ expect(find.text('Browse remote').hitTestable(), findsOneWidget);
+ expect(
+ FocusManager.instance.primaryFocus!.debugLabel,
+ 'remote-folder-caller',
+ );
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
+ for (final brightness in Brightness.values) {
+ for (final desktop in [false, true]) {
+ testWidgets(
+ 'folder errors remain readable in ${brightness.name} desktop=$desktop',
+ (tester) async {
+ final app = await _open(
+ tester,
+ brightness: brightness,
+ desktop: desktop,
+ );
+ app.requests.single.reply.complete({'error': 'FORBIDDEN'});
+ await tester.pumpAndSettle();
+ final error = find.text(
+ 'Choose a folder inside your home directory on this machine.',
+ );
+ final foreground = tester.widget<Text>(error).style!.color!;
+ Color? background;
+ error.evaluate().single.visitAncestorElements((element) {
+ if (element.widget case Material(color: final color?)
+ when color.a == 1) {
+ background = color;
+ return false;
+ }
+ return true;
+ });
+ expect(background, isNotNull);
+ final fg = foreground.computeLuminance();
+ final bg = background!.computeLuminance();
+ final contrast = fg > bg
+ ? (fg + .05) / (bg + .05)
+ : (bg + .05) / (fg + .05);
+ expect(contrast, greaterThanOrEqualTo(4.5));
+ },
+ );
+ }
+
+ testWidgets(
+ 'Add project uses the desktop remote chooser with enlarged recovery in ${brightness.name}',
+ (tester) async {
+ String? projectPath;
+ final app = await _open(
+ tester,
+ brightness: brightness,
+ size: const Size(440, 560),
+ scale: 1.6,
+ addProject: true,
+ onResult: (path) => projectPath = path,
+ );
+ expect(
+ find.byKey(const ValueKey('desktop-remote-folder-dialog')),
+ findsOneWidget,
+ );
+ app.requests.single.reply.complete({'error': 'FORBIDDEN'});
+ await tester.pumpAndSettle();
+ final error = find.text(
+ 'Choose a folder inside your home directory on this machine.',
+ );
+ await _capture(tester, 'add-project-remote-${brightness.name}');
+ await tester.ensureVisible(error);
+ expect(error.hitTestable(), findsOneWidget);
+ await tester.ensureVisible(find.text('Retry'));
+ expect(find.text('Retry').hitTestable(), findsOneWidget);
+ expect(
+ tester.getBottomRight(error).dy,
+ lessThan(
+ tester.getTopLeft(find.byKey(const Key('remote-folder-select'))).dy,
+ ),
+ );
+ await tester.tap(find.text('Retry'));
+ await tester.pump();
+ app.requests.last.reply.complete(
+ _listing('/Users/dev/Project', ['src']),
+ );
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.arrowDown);
+ expect(_path(tester).focusNode!.hasFocus, isFalse);
+ await _key(tester, LogicalKeyboardKey.keyL, cmd: true);
+ expect(_path(tester).focusNode!.hasFocus, isTrue);
+ expect(
+ _path(tester).controller!.selection,
+ const TextSelection(baseOffset: 0, extentOffset: 18),
+ );
+ await _key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('desktop-remote-folder-dialog')),
+ findsNothing,
+ );
+ expect(
+ find.widgetWithText(OutlinedButton, '/Users/dev/Project'),
+ findsOneWidget,
+ );
+ await tester.tap(find.widgetWithText(FilledButton, 'Add project'));
+ await tester.pumpAndSettle();
+ expect(projectPath, '/Users/dev/Project');
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'narrow ${brightness.name} keeps enlarged errors and actions reachable',
+ (tester) async {
+ final app = await _open(
+ tester,
+ brightness: brightness,
+ size: const Size(440, 560),
+ scale: 1.6,
+ unknownMachine: true,
+ );
+ app.requests.single.reply.complete({'error': 'FORBIDDEN'});
+ await tester.pumpAndSettle();
+ await _capture(tester, 'remote-folder-narrow-${brightness.name}');
+ expect(find.text('On the remote machine'), findsOneWidget);
+ expect(find.text('Cancel').hitTestable(), findsOneWidget);
+ expect(
+ find.byKey(const Key('remote-folder-select')).hitTestable(),
+ findsOneWidget,
+ );
+ await tester.ensureVisible(find.text('Retry'));
+ await tester.tap(find.text('Retry'));
+ await tester.pump();
+ app.requests.last.reply.complete({
+ ..._listing('/Users/dev', [
+ 'a very long folder name with 日本語 and emoji 👩🏽‍💻',
+ ]),
+ 'truncated': true,
+ });
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ 'More folders are available. Enter their full path to open them.',
+ ),
+ findsOneWidget,
+ );
+ expect(_select(tester).onPressed, isNotNull);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
+ testWidgets(
+ 'Windows paths retain their remote separators and root boundary',
+ (tester) async {
+ String? selected;
+ final app = await _open(
+ tester,
+ initialPath: r'C:\Users\dev',
+ onResult: (value) => selected = value,
+ );
+ app.requests.single.reply.complete(_listing(r'C:\Users\dev', ['code']));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('code'));
+ expect(app.requests.last.path, r'C:\Users\dev\code');
+ app.requests.last.reply.complete(_listing(r'C:\Users\dev\code'));
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(app.requests.last.path, r'C:\Users\dev');
+ app.requests.last.reply.complete(_listing(r'C:\Users\dev', ['code']));
+ await tester.pumpAndSettle();
+ await _key(tester, LogicalKeyboardKey.enter);
+ app.requests.last.reply.complete(_listing(r'C:\Users\dev\code'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('remote-folder-select')));
+ await tester.pumpAndSettle();
+ expect(selected, r'C:\Users\dev\code');
+ },
+ );
+}
diff --git a/desktop/test/desktop_resource_forms_edge_test.dart b/desktop/test/desktop_resource_forms_edge_test.dart
new file mode 100644
index 000000000..02e4dc497
--- /dev/null
+++ b/desktop/test/desktop_resource_forms_edge_test.dart
@@ -0,0 +1,356 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/api_connections_controller.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/api_picker_form.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/machine_picker_form.dart';
+
+import 'keymap_host_test.dart' show key;
+import 'support/machine_api.dart';
+import 'support/password_cli.dart';
+
+const _connection = ApiConnection({
+ 'id': 'review-api',
+ 'provider': 'custom',
+ 'name': 'Review API',
+ 'baseUrl': 'https://review.example.test/v1',
+ 'keyEnv': 'REVIEW_API_KEY',
+ 'authHeader': 'Authorization',
+ 'authPrefix': 'Bearer',
+});
+
+class _App extends AppNotifier {
+ _App() : this._(PasswordCli());
+ _App._(this.passwords)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLink: passwords,
+ ) {
+ api = edits;
+ const machine = Machine(
+ machineId: 'm',
+ name: 'Studio Mac',
+ authMode: MachineAuthMode.remote,
+ );
+ machines = [machine];
+ machineStates['m'] = MachineState(machine)
+ ..localOnly = true
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected;
+ }
+
+ final PasswordCli passwords;
+ final edits = MachineApi();
+ final apiRequests = <Map<String, dynamic>>[];
+
+ @override
+ Future<Map<String, dynamic>> apiConnections(
+ String machineId,
+ Map<String, dynamic> payload, {
+ Duration timeout = const Duration(seconds: 10),
+ }) async {
+ apiRequests.add(payload);
+ return {
+ 'connections': payload['action'] == 'remove' ? [] : [_connection.data],
+ 'presets': [],
+ };
+ }
+}
+
+Future<void> _mount(
+ WidgetTester tester,
+ Widget form, {
+ FocusNode? query,
+ bool desktop = true,
+ Brightness brightness = Brightness.dark,
+}) async {
+ tester.view.physicalSize = const Size(500, 660);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: Padding(
+ padding: const EdgeInsets.all(16),
+ child: Column(
+ children: [
+ if (query != null)
+ TextField(
+ key: const ValueKey('resource-query'),
+ focusNode: query,
+ ),
+ Expanded(child: desktop ? DesktopChrome(child: form) : form),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+}
+
+Finder _machine(String id) => find.byKey(ValueKey('machine-form:$id'));
+Finder _api(String id) => find.byKey(ValueKey('api-form:$id'));
+Finder _apiInput(String id) => find.byKey(ValueKey('api-form-input:$id'));
+final _rename = find.byKey(const ValueKey('machine-rename-input'));
+TextField _field(WidgetTester tester, Finder finder) =>
+ tester.widget<TextField>(finder);
+bool _buttonFocused(WidgetTester tester, Finder finder) =>
+ switch (tester.widget(finder)) {
+ DesktopPill(:final focusNode) => focusNode!.hasFocus,
+ ButtonStyleButton(:final focusNode) => focusNode!.hasFocus,
+ _ => false,
+ };
+
+void main() {
+ for (final switchPane in [true, false]) {
+ testWidgets('native machine Tab boundaries preserve draft ($switchPane)', (
+ tester,
+ ) async {
+ final app = _App();
+ final query = FocusNode(debugLabel: 'Resource query');
+ final form = GlobalKey<MachinePickerFormState>();
+ final closed = <String?>[];
+ addTearDown(app.dispose);
+ addTearDown(query.dispose);
+ await _mount(
+ tester,
+ MachinePickerForm(
+ key: form,
+ app: app,
+ kind: MachinePickerFormKind.rename,
+ machineId: 'm',
+ onClose: closed.add,
+ onFocusChanged: (_) {},
+ onSwitchPane: switchPane ? query.requestFocus : null,
+ ),
+ query: switchPane ? query : null,
+ );
+ await tester.enterText(_rename, 'Build Mac');
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(_buttonFocused(tester, _machine('Save')), isTrue);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(_buttonFocused(tester, _machine('Cancel')), isTrue);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ switchPane
+ ? query.hasFocus
+ : _field(tester, _rename).focusNode!.hasFocus,
+ isTrue,
+ );
+ form.currentState!.focus();
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(
+ switchPane
+ ? query.hasFocus
+ : _buttonFocused(tester, _machine('Cancel')),
+ isTrue,
+ );
+ form.currentState!.focus();
+ await tester.pump();
+ expect(_field(tester, _rename).controller!.text, 'Build Mac');
+ expect(app.edits.renames, isEmpty);
+ expect(closed, isEmpty);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets(
+ 'native API Tab boundaries preserve masked draft ($switchPane)',
+ (tester) async {
+ final app = _App();
+ final controller = ApiConnectionsController(app, machineId: 'm')
+ ..loaded = true
+ ..connections = [_connection];
+ final query = FocusNode(debugLabel: 'Resource query');
+ final form = GlobalKey<ApiPickerFormState>();
+ addTearDown(app.dispose);
+ addTearDown(controller.dispose);
+ addTearDown(query.dispose);
+ await _mount(
+ tester,
+ ApiPickerForm(
+ key: form,
+ controller: controller,
+ connectionId: _connection.id,
+ onClose: (_) => fail('Traversal must not close the API editor'),
+ onFocusChanged: (_) {},
+ onSwitchPane: switchPane ? query.requestFocus : null,
+ ),
+ query: switchPane ? query : null,
+ brightness: switchPane ? Brightness.light : Brightness.dark,
+ );
+ await tester.enterText(_apiInput('key'), 'fixture-only-secret');
+ for (final id in ['visibility', 'options', 'cancel', 'save']) {
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(_buttonFocused(tester, _api(id)), isTrue);
+ }
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ switchPane
+ ? query.hasFocus
+ : _field(tester, _apiInput('name')).focusNode!.hasFocus,
+ isTrue,
+ );
+ form.currentState!.focus();
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(
+ switchPane ? query.hasFocus : _buttonFocused(tester, _api('save')),
+ isTrue,
+ );
+ form.currentState!.focus();
+ await tester.pump();
+ expect(
+ _field(tester, _apiInput('key')).controller!.text,
+ 'fixture-only-secret',
+ );
+ expect(_field(tester, _apiInput('key')).obscureText, isTrue);
+ expect(
+ controller.connections.single.data.containsKey('apiKey'),
+ isFalse,
+ );
+ expect(app.apiRequests, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
+ testWidgets('machine name validation recovers through readline editing', (
+ tester,
+ ) async {
+ final app = _App();
+ addTearDown(app.dispose);
+ await _mount(
+ tester,
+ MachinePickerForm(
+ app: app,
+ kind: MachinePickerFormKind.rename,
+ machineId: 'm',
+ onClose: (_) {},
+ onFocusChanged: (_) {},
+ ),
+ );
+ await tester.enterText(_rename, ' ');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(find.text('Enter a name.'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.keyU, ctrl: true);
+ expect(find.text('Enter a name.'), findsNothing);
+ await tester.enterText(_rename, 'Draft');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ expect(app.edits.renames, isEmpty);
+ await tester.tapAt(const Offset(2, 2));
+ await tester.pump();
+ expect(_field(tester, _rename).controller!.text, 'Draft');
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets(
+ 'native API deletion starts on Cancel and requires choosing Delete',
+ (tester) async {
+ final app = _App();
+ final controller = ApiConnectionsController(app, machineId: 'm')
+ ..loaded = true
+ ..connections = [_connection];
+ final closed = <String?>[];
+ addTearDown(app.dispose);
+ addTearDown(controller.dispose);
+ await _mount(
+ tester,
+ ApiPickerForm(
+ controller: controller,
+ connectionId: _connection.id,
+ removing: true,
+ onClose: closed.add,
+ onFocusChanged: (_) {},
+ ),
+ );
+ expect(_buttonFocused(tester, _api('cancel')), isTrue);
+ expect(
+ tester
+ .widget<FilledButton>(_api('delete'))
+ .style!
+ .backgroundColor!
+ .resolve({}),
+ Theme.of(tester.element(_api('delete'))).colorScheme.error,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(closed, [null]);
+ expect(app.apiRequests, isEmpty);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(_buttonFocused(tester, _api('delete')), isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.apiRequests, [
+ {'action': 'remove', 'id': _connection.id},
+ ]);
+ expect(closed, [null, '']);
+ },
+ );
+
+ for (final kind in [MachinePickerFormKind.app, MachinePickerFormKind.cli]) {
+ testWidgets(
+ 'legacy $kind setup keeps selectable installation instructions',
+ (tester) async {
+ final app = _App();
+ addTearDown(app.dispose);
+ await _mount(
+ tester,
+ MachinePickerForm(
+ app: app,
+ kind: kind,
+ machineId: 'm',
+ onClose: (_) {},
+ onFocusChanged: (_) {},
+ ),
+ desktop: false,
+ );
+ expect(find.byType(SelectableText), findsWidgets);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
+ testWidgets('legacy machine rename shows errors and one pending save', (
+ tester,
+ ) async {
+ final app = _App();
+ addTearDown(app.dispose);
+ await _mount(
+ tester,
+ MachinePickerForm(
+ app: app,
+ kind: MachinePickerFormKind.rename,
+ machineId: 'm',
+ onClose: (_) {},
+ onFocusChanged: (_) {},
+ ),
+ desktop: false,
+ );
+ await tester.enterText(_rename, '');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(find.text('Enter a name.'), findsOneWidget);
+ app.edits.renameReply = Completer<String?>();
+ await tester.enterText(_rename, 'New name');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(_field(tester, _rename).readOnly, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.edits.renames, [('m', 'New name')]);
+ app.edits.renameReply!.complete(null);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ });
+}
diff --git a/desktop/test/desktop_search_edges_test.dart b/desktop/test/desktop_search_edges_test.dart
new file mode 100644
index 000000000..a854f3b36
--- /dev/null
+++ b/desktop/test/desktop_search_edges_test.dart
@@ -0,0 +1,885 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/cli_link.dart';
+import 'package:harness/core/machine_resources.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/api_connections_controller.dart';
+import 'package:harness/models/local_model.dart';
+import 'package:harness/models/model_search_catalog.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/usage/models_menu_controller.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/api_picker_form.dart';
+import 'package:harness/widgets/machine_picker_form.dart';
+import 'package:harness/widgets/swarm_resource_preview.dart';
+
+import 'support/model_manager.dart';
+
+class _Usage extends ModelsMenuController {
+ @override
+ List<Map<String, Object?>> get rows => const [];
+}
+
+class _EdgeApp extends ModelManagerTestApp {
+ _EdgeApp() : super(ModelManagerConnection());
+
+ @override
+ String? machineListError;
+
+ int machineRetries = 0;
+ int resourceReads = 0;
+ Completer<void>? retryReply;
+ Completer<MachineResources?>? resourceReply;
+ final apiWrites = <Map<String, dynamic>>[];
+ final failingModelHosts = <String>{};
+ List<Map<String, dynamic>> savedApis = [];
+
+ @override
+ Future<Map<String, dynamic>> localModels(
+ String machineId, {
+ bool refresh = false,
+ }) {
+ if (failingModelHosts.contains(machineId)) {
+ throw StateError('Fixture model host unavailable');
+ }
+ return super.localModels(machineId, refresh: refresh);
+ }
+
+ @override
+ Future<void> retryMachines() async {
+ machineRetries++;
+ await retryReply?.future;
+ machineListError = null;
+ notifyListeners();
+ }
+
+ @override
+ Future<MachineResources?> readMachineResources(String machineId) async {
+ resourceReads++;
+ return resourceReply?.future ??
+ Future.value(const MachineResources(cpuPercent: 33));
+ }
+
+ @override
+ Future<RemotePasswordStatus> remotePasswordStatus() async =>
+ const RemotePasswordStatus(hasPassword: false);
+
+ @override
+ Future<Map<String, dynamic>> apiConnections(
+ String machineId,
+ Map<String, dynamic> payload, {
+ Duration timeout = const Duration(seconds: 10),
+ }) async {
+ apiWrites.add(Map.of(payload));
+ if (payload['action'] == 'save') {
+ final saved = Map<String, dynamic>.from(payload['connection'] as Map)
+ ..remove('apiKey')
+ ..['id'] = 'saved-api';
+ savedApis = [...savedApis, saved];
+ }
+ return {'connections': savedApis, 'presets': <Object>[]};
+ }
+}
+
+class _PreviewFixture {
+ _PreviewFixture({
+ required this.app,
+ required String query,
+ bool offersCreate = false,
+ bool preview = true,
+ bool selectOnEmpty = true,
+ }) {
+ catalog = ModelSearchCatalog(app.modelManager, usage, pollHosts: false);
+ search = SwarmSearchController(
+ app,
+ const [],
+ models: catalog,
+ adding: true,
+ activityFirst: true,
+ offersCreate: offersCreate,
+ previewInitiallyVisible: preview,
+ selectOnEmptyQuery: selectOnEmpty,
+ )..setQuery(query);
+ }
+
+ final _EdgeApp app;
+ final usage = _Usage();
+ late final ModelSearchCatalog catalog;
+ late final SwarmSearchController search;
+ final controls = SearchPreviewControls();
+ final queryFocus = FocusNode();
+ final choices = <SwarmSearchSelection>[];
+ var refocuses = 0;
+ var disposed = false;
+
+ void refocus() {
+ refocuses++;
+ queryFocus.requestFocus();
+ search.setManaging(false);
+ }
+
+ Widget widget({
+ bool desktop = true,
+ double width = 600,
+ SwarmSearchController? replacement,
+ Duration? resourcePollInterval,
+ }) {
+ final preview = SwarmResourcePreview(
+ search: replacement ?? search,
+ controls: controls,
+ onChoose: choices.add,
+ onRefocus: refocus,
+ onModalChanged: (_) {},
+ onCommands: () {},
+ resourcePollInterval: resourcePollInterval,
+ );
+ return MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: width,
+ child: Column(
+ children: [
+ TextField(
+ key: const ValueKey('edge-query'),
+ focusNode: queryFocus,
+ autofocus: true,
+ ),
+ Expanded(
+ child: desktop ? DesktopChrome(child: preview) : preview,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ void dispose() {
+ if (disposed) return;
+ disposed = true;
+ controls.dispose();
+ queryFocus.dispose();
+ search.dispose();
+ catalog.dispose();
+ usage.dispose();
+ app.dispose();
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test(
+ 'model status words follow operation progress and all pending states',
+ () {
+ final app = _EdgeApp();
+ final usage = _Usage();
+ final catalog = ModelSearchCatalog(
+ app.modelManager,
+ usage,
+ pollHosts: false,
+ );
+ addTearDown(app.dispose);
+ addTearDown(usage.dispose);
+ addTearDown(catalog.dispose);
+ final owner = app.modelManager;
+ const available = LocalModel(id: 'weights', name: 'Model');
+ const downloaded = LocalModel(
+ id: 'weights',
+ name: 'Model',
+ state: 'downloaded',
+ );
+ const running = LocalModel(
+ id: 'weights',
+ name: 'Model',
+ state: 'running',
+ );
+
+ for (final (model, label) in [
+ (available, 'Not downloaded'),
+ (downloaded, 'Downloaded'),
+ (running, 'Running'),
+ ]) {
+ expect(catalog.localStatus(model), label);
+ expect(catalog.localStatusWord(model), label);
+ }
+ owner.pendingId = 'weights';
+ for (final (download, start, label) in [
+ (true, true, 'Downloading'),
+ (false, true, 'Starting'),
+ (false, false, 'Stopping'),
+ ]) {
+ owner.pendingDownload = download;
+ owner.pendingStart = start;
+ expect(catalog.localStatus(available), label);
+ expect(catalog.localStatusWord(available), label);
+ }
+ owner.pendingId = null;
+ owner.pendingOperation = const LocalModelOperation(
+ id: 'download',
+ modelId: 'weights',
+ action: 'download',
+ stage: 'downloading',
+ phase: 'running',
+ progress: .42,
+ );
+ expect(catalog.localStatus(available), 'Downloading 42%');
+ expect(catalog.localStatusWord(available), 'Downloading');
+ owner.pendingOperation = const LocalModelOperation(
+ id: 'download',
+ modelId: 'weights',
+ action: 'download',
+ stage: 'downloading',
+ phase: 'failed',
+ error: 'Disk full',
+ );
+ expect(catalog.localStatus(available), 'Failed · try again');
+ expect(catalog.localStatusWord(available), 'Failed');
+ },
+ );
+
+ test('duplicate machine names keep stable model rows and removal revokes control', () async {
+ final app = _EdgeApp();
+ final usage = _Usage();
+ final catalog = ModelSearchCatalog(
+ app.modelManager,
+ usage,
+ pollHosts: false,
+ );
+ addTearDown(app.dispose);
+ addTearDown(usage.dispose);
+ addTearDown(catalog.dispose);
+ app.machineStates['other']!
+ ..machine = const Machine(
+ machineId: 'other',
+ name: 'This Mac',
+ authMode: MachineAuthMode.remote,
+ )
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ const weights = {
+ 'id': 'qwen.gguf',
+ 'name': 'Qwen weights',
+ 'state': 'downloaded',
+ 'canStart': true,
+ };
+ app.localInventory = {
+ 'models': [weights],
+ };
+ app.machineInventories['other'] = {
+ 'models': [weights],
+ };
+ catalog.setVisible(true);
+ await catalog.refresh();
+ final originalIds = catalog.rows.map((row) => row.id).toList();
+ expect(originalIds, [
+ 'model:local:qwen.gguf',
+ 'model:machine:other:qwen.gguf',
+ ]);
+ await catalog.refresh(force: true);
+ expect(catalog.rows.map((row) => row.id), originalIds);
+ app.machineStates.remove('other');
+ app.notifyListeners();
+ expect(
+ catalog.entries.values.where((entry) => entry.local != null),
+ hasLength(1),
+ );
+ expect(catalog.rows.single.id, originalIds.first);
+ expect(app.actions, isEmpty);
+ });
+
+ test(
+ 'served model IDs resolve inventory even when the display name differs',
+ () async {
+ final app = _EdgeApp();
+ final usage = _Usage();
+ final catalog = ModelSearchCatalog(
+ app.modelManager,
+ usage,
+ pollHosts: false,
+ );
+ addTearDown(app.dispose);
+ addTearDown(usage.dispose);
+ addTearDown(catalog.dispose);
+ app.localInventory = {
+ 'models': [
+ {
+ 'id': 'qwen.gguf',
+ 'name': 'Qwen weights',
+ 'state': 'running',
+ 'canStop': true,
+ },
+ ],
+ };
+ app.inventory = const GridModels(
+ gridName: 'home',
+ models: [GridModel(id: 'QWEN.GGUF', node: 'This Mac')],
+ );
+ await app.modelManager.refresh();
+ expect(catalog.entries, hasLength(1));
+ expect(catalog.entries.values.single.local!.id, 'qwen.gguf');
+ expect(catalog.entries.values.single.gridModel!.id, 'QWEN.GGUF');
+ },
+ );
+
+ Future<_PreviewFixture> mount(
+ WidgetTester tester, {
+ String query = '@This Mac',
+ _EdgeApp? app,
+ bool desktop = true,
+ double width = 600,
+ bool preview = true,
+ bool selectOnEmpty = true,
+ Duration? resourcePollInterval,
+ bool offersCreate = false,
+ }) async {
+ final seeded = app ?? _EdgeApp();
+ await seeded.modelManager.refresh();
+ final fixture = _PreviewFixture(
+ app: seeded,
+ query: query,
+ preview: preview,
+ selectOnEmpty: selectOnEmpty,
+ offersCreate: offersCreate,
+ );
+ addTearDown(fixture.dispose);
+ await tester.pumpWidget(
+ fixture.widget(
+ desktop: desktop,
+ width: width,
+ resourcePollInterval: resourcePollInterval,
+ ),
+ );
+ await tester.pumpAndSettle();
+ return fixture;
+ }
+
+ Future<void> invoke(
+ WidgetTester tester,
+ _PreviewFixture fixture,
+ String command,
+ ) async {
+ expect(fixture.controls.invoke(command), isTrue, reason: command);
+ await tester.pumpAndSettle();
+ }
+
+ for (final desktop in [true, false]) {
+ testWidgets(
+ 'empty preview scope links keep query focus and never launch ($desktop)',
+ (tester) async {
+ final fixture = await mount(
+ tester,
+ query: '',
+ desktop: desktop,
+ selectOnEmpty: false,
+ );
+ for (final prefix in ['@', '#', ':', '*', '>']) {
+ fixture.search.setQuery('');
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(ValueKey('swarm-search-scope:$prefix')));
+ await tester.pumpAndSettle();
+ expect(fixture.search.query, '$prefix ');
+ expect(fixture.queryFocus.hasFocus, isTrue);
+ expect(fixture.choices, isEmpty);
+ }
+ },
+ );
+
+ testWidgets(
+ 'retry preserves selected machine and joins a pending refresh ($desktop)',
+ (tester) async {
+ final app = _EdgeApp()..machineListError = 'Inventory timed out';
+ final pending = Completer<void>();
+ app.retryReply = pending;
+ final fixture = await mount(tester, app: app, desktop: desktop);
+ final selected = fixture.search.selected!.id;
+ final retry = find.byKey(
+ const ValueKey('resource-action:picker.refresh'),
+ );
+ expect(retry, findsOneWidget);
+ await tester.tap(retry);
+ await tester.pump();
+ expect(app.machineRetries, 1);
+ expect(find.text('Working…'), findsOneWidget);
+ fixture.controls.invoke('picker.refresh');
+ await tester.pump();
+ expect(app.machineRetries, 1);
+ expect(fixture.search.selected!.id, selected);
+ pending.complete();
+ await tester.pumpAndSettle();
+ expect(find.text('Working…'), findsNothing);
+ expect(find.text('Inventory timed out'), findsNothing);
+ expect(fixture.search.selected!.id, selected);
+ expect(app.resourceReads, greaterThan(0));
+ fixture.search.scrollPreview(1);
+ await tester.pump();
+ expect(fixture.search.selected!.id, selected);
+ },
+ );
+ }
+
+ testWidgets(
+ 'keyboard action focus restores a hidden preview and stays on one resource',
+ (tester) async {
+ final fixture = await mount(tester, preview: false);
+ expect(fixture.search.previewVisible, isFalse);
+ await invoke(tester, fixture, 'picker.focus_actions');
+ expect(fixture.search.previewVisible, isTrue);
+ expect(fixture.search.managing, isTrue);
+ final selected = fixture.search.selected!.id;
+ await invoke(tester, fixture, 'picker.next');
+ await invoke(tester, fixture, 'picker.previous');
+ expect(fixture.search.selected!.id, selected);
+ await invoke(tester, fixture, 'picker.cancel');
+ expect(fixture.queryFocus.hasFocus, isTrue);
+ expect(fixture.search.managing, isFalse);
+ },
+ );
+
+ testWidgets(
+ 'Return cannot act on a resource selected after its controls were focused',
+ (tester) async {
+ final fixture = await mount(tester);
+ await invoke(tester, fixture, 'picker.focus_actions');
+ fixture.search.setQuery('@Other computer');
+ expect(fixture.controls.invoke('picker.accept'), isTrue);
+ await tester.pumpAndSettle();
+ expect(find.byType(MachinePickerForm), findsNothing);
+ expect(fixture.queryFocus.hasFocus, isTrue);
+ expect(fixture.choices, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'rapid Return after selecting Add machine focuses its newly built controls',
+ (tester) async {
+ final fixture = await mount(tester, offersCreate: true);
+ fixture.search.setQuery('@');
+ final create = fixture.search.rows.indexWhere((row) => row.isCreate);
+ expect(create, isNonNegative);
+ fixture.search.move(create - fixture.search.cursor);
+ expect(fixture.controls.invoke('picker.accept'), isTrue);
+ await tester.pumpAndSettle();
+ expect(fixture.search.managing, isTrue);
+ await invoke(tester, fixture, 'picker.accept');
+ expect(find.byType(MachinePickerForm), findsOneWidget);
+ expect(find.text('Add machine · App'), findsOneWidget);
+ expect(fixture.app.connection.creations, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'a disabled model action accepts arrows without losing the selection',
+ (tester) async {
+ final fixture = await mount(tester, query: ':gemma');
+ await invoke(tester, fixture, 'picker.resource_toggle');
+ await invoke(tester, fixture, 'picker.focus_actions');
+ final selected = fixture.search.selected!.id;
+ await invoke(tester, fixture, 'picker.previous');
+ await invoke(tester, fixture, 'picker.next');
+ await invoke(tester, fixture, 'picker.accept');
+ expect(fixture.search.selected!.id, selected);
+ expect(fixture.choices, isEmpty);
+ expect(fixture.app.actions, isEmpty);
+ await invoke(tester, fixture, 'picker.cancel');
+ expect(fixture.queryFocus.hasFocus, isTrue);
+ },
+ );
+
+ testWidgets('a missing machine remains a read-only unavailable preview', (
+ tester,
+ ) async {
+ final fixture = await mount(tester);
+ fixture.app.machineStates.remove('m');
+ await tester.pumpWidget(fixture.widget());
+ await tester.pumpAndSettle();
+ expect(find.text('Unavailable'), findsOneWidget);
+ expect(fixture.controls.invoke('picker.accept'), isFalse);
+ expect(find.byType(MachinePickerForm), findsNothing);
+ expect(fixture.choices, isEmpty);
+ });
+
+ testWidgets(
+ 'create API from a filtered preview returns to its new saved row',
+ (tester) async {
+ final fixture = await mount(
+ tester,
+ query: ':missing',
+ offersCreate: true,
+ );
+ expect(fixture.search.selected!.isCreate, isTrue);
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.accept')),
+ );
+ await tester.pumpAndSettle();
+ expect(find.byType(ApiPickerForm), findsOneWidget);
+ fixture.refocus();
+ await tester.pump();
+ await invoke(tester, fixture, 'picker.focus_actions');
+ expect(fixture.queryFocus.hasFocus, isFalse);
+ await tester.tap(find.byKey(const ValueKey('api-form:provider:custom')));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:name')),
+ 'Saved API',
+ );
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:url')),
+ 'https://fixture.invalid/v1',
+ );
+ await tester.enterText(
+ find.byKey(const ValueKey('api-form-input:key')),
+ 'fixture-only-key',
+ );
+ await tester.tap(find.byKey(const ValueKey('api-form:save')));
+ await tester.pumpAndSettle();
+ expect(find.byType(ApiPickerForm), findsNothing);
+ expect(fixture.search.query, ':');
+ expect(fixture.search.selected!.modelId, 'model:api:saved-api');
+ expect(fixture.queryFocus.hasFocus, isTrue);
+ expect(
+ fixture.app.apiWrites.where((entry) => entry['action'] == 'save'),
+ hasLength(1),
+ );
+ },
+ );
+
+ testWidgets(
+ 'a create result returns one intent and keeps launch ownership outside the preview',
+ (tester) async {
+ final fixture = await mount(
+ tester,
+ query: 'New feature task',
+ offersCreate: true,
+ );
+ expect(fixture.search.selected!.isCreate, isTrue);
+ await tester.tap(
+ find.byKey(const ValueKey('resource-action:picker.accept')),
+ );
+ await tester.pumpAndSettle();
+ expect(fixture.choices, hasLength(1));
+ expect(fixture.choices.single.destination.isCreate, isTrue);
+ expect(fixture.app.connection.creations, isEmpty);
+ expect(fixture.queryFocus.hasFocus, isTrue);
+ },
+ );
+
+ testWidgets(
+ 'a native model discovery error is visible beside the retained model',
+ (tester) async {
+ final fixture = await mount(tester, query: ':gemma');
+ fixture.app.localReadFails = true;
+ await invoke(tester, fixture, 'picker.refresh');
+ final error = fixture.app.modelManager.error;
+ expect(error, isNotNull);
+ expect(find.text('Local models · $error'), findsOneWidget);
+ expect(fixture.search.selected!.modelId, 'model:local:gemma');
+ expect(fixture.choices, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'discovered models explain pending controls and keep the stable row when inventory arrives',
+ (tester) async {
+ final app = _EdgeApp()
+ ..localInventory = {'models': <Object>[]}
+ ..inventory = const GridModels(
+ gridName: 'home',
+ models: [GridModel(id: 'Discovery model', node: 'This Mac')],
+ );
+ final fixture = await mount(tester, app: app, query: ':Discovery model');
+ final selected = fixture.search.selected!.id;
+ final reply = Completer<Map<String, dynamic>>();
+ app.localReply = reply;
+ final pending = app.modelManager.refresh(force: true);
+ await tester.pump();
+ expect(find.text('Finding model controls…'), findsOneWidget);
+ reply.complete({
+ 'models': [
+ {
+ 'id': 'discovery',
+ 'name': 'Discovery model',
+ 'state': 'running',
+ 'canStop': true,
+ },
+ ],
+ });
+ await pending;
+ await tester.pumpAndSettle();
+ expect(find.text('Finding model controls…'), findsNothing);
+ expect(fixture.search.selected!.id, selected);
+ expect(fixture.catalog.entries.values.single.local!.id, 'discovery');
+ },
+ );
+
+ testWidgets('a remote model inventory error stays with its own host', (
+ tester,
+ ) async {
+ final app = _EdgeApp();
+ app.machineStates['other']!
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected;
+ app.machineInventories['other'] = {
+ 'models': [
+ {
+ 'id': 'remote',
+ 'name': 'Remote model',
+ 'state': 'downloaded',
+ 'canStart': true,
+ },
+ ],
+ };
+ final fixture = await mount(tester, app: app, query: ':');
+ fixture.catalog.setVisible(true);
+ await fixture.catalog.refresh();
+ fixture.search.setQuery(':Remote model');
+ await tester.pumpAndSettle();
+ final entry = fixture.catalog.entries[fixture.search.selected!.id]!;
+ app.failingModelHosts.add('other');
+ await entry.controller!.refresh(force: true);
+ await tester.pumpAndSettle();
+ expect(entry.controller!.error, 'Models are unavailable. Try again.');
+ expect(app.modelManager.error, isNull);
+ expect(find.text('Models are unavailable. Try again.'), findsOneWidget);
+ expect(fixture.search.selected!.id, entry.id);
+ expect(fixture.app.actions, isEmpty);
+ });
+
+ testWidgets(
+ 'changing selection closes machine edits before stale input can submit',
+ (tester) async {
+ final fixture = await mount(tester);
+ await invoke(tester, fixture, 'picker.resource_rename');
+ expect(find.byType(MachinePickerForm), findsOneWidget);
+ fixture.refocus();
+ await tester.pump();
+ await invoke(tester, fixture, 'picker.focus_actions');
+ expect(fixture.queryFocus.hasFocus, isFalse);
+ fixture.search.setQuery('@Other computer');
+ await tester.pumpAndSettle();
+ expect(find.byType(MachinePickerForm), findsNothing);
+ expect(fixture.queryFocus.hasFocus, isTrue);
+ expect(fixture.app.connection.creations, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'switching to another search controller detaches old selection callbacks',
+ (tester) async {
+ final fixture = await mount(tester);
+ final replacement = SwarmSearchController(
+ fixture.app,
+ const [],
+ adding: true,
+ )..setQuery('@Other computer');
+ addTearDown(replacement.dispose);
+ await tester.pumpWidget(fixture.widget(replacement: replacement));
+ await tester.pumpAndSettle();
+ await invoke(tester, fixture, 'picker.focus_actions');
+ expect(replacement.managing, isTrue);
+ final before = fixture.refocuses;
+ fixture.search.setQuery('@does-not-exist');
+ await tester.pumpAndSettle();
+ expect(fixture.refocuses, before);
+ expect(replacement.selected!.machineId, 'other');
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'machine metrics poll only while visible and join overlapping reads',
+ (tester) async {
+ final fixture = await mount(
+ tester,
+ resourcePollInterval: const Duration(seconds: 1),
+ );
+ final app = fixture.app;
+ final before = app.resourceReads;
+ final reply = Completer<MachineResources?>();
+ app.resourceReply = reply;
+ await tester.pump(const Duration(seconds: 1));
+ expect(app.resourceReads, before + 2);
+ await tester.pump(const Duration(seconds: 3));
+ expect(
+ app.resourceReads,
+ before + 2,
+ reason: 'A slow daemon must not accumulate overlapping requests',
+ );
+ reply.complete(null);
+ await tester.pump();
+ app.resourceReply = null;
+ app.foreground.value = false;
+ await tester.pump(const Duration(seconds: 2));
+ expect(app.resourceReads, before + 2);
+ app.foreground.value = true;
+ fixture.search.setQuery(':');
+ await tester.pump(const Duration(seconds: 2));
+ expect(
+ app.resourceReads,
+ before + 2,
+ reason: 'Model browsing should not poll machine telemetry',
+ );
+ fixture.search.setQuery('@');
+ await tester.pump();
+ final returned = app.resourceReads;
+ await tester.pump(const Duration(seconds: 1));
+ expect(app.resourceReads, returned + 2);
+ await tester.pumpWidget(const SizedBox());
+ final closed = app.resourceReads;
+ await tester.pump(const Duration(seconds: 5));
+ expect(app.resourceReads, closed);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ for (final window in [7200, 90]) {
+ testWidgets(
+ 'model preview explains oversized resting weights and usage window $window',
+ (tester) async {
+ final app = _EdgeApp();
+ app.localInventory = {
+ 'memoryBytes': 8 * 1024 * 1024 * 1024,
+ 'models': [
+ {
+ 'id': 'large',
+ 'name': 'Large model',
+ 'state': 'running',
+ 'canStop': true,
+ 'gridAsleep': true,
+ 'sizeBytes': 16 * 1024 * 1024 * 1024,
+ 'requests': 3,
+ 'windowSeconds': window,
+ },
+ ],
+ };
+ await mount(tester, app: app, query: ':Large model');
+ expect(
+ find.text('needs 16 GB · ${thisComputerName()} has 8.0 GB'),
+ findsOneWidget,
+ );
+ expect(find.text('Resting until your next message'), findsOneWidget);
+ expect(
+ find.text(window == 7200 ? '3 req / 2h' : '3 req / 2m'),
+ findsOneWidget,
+ );
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
+ testWidgets(
+ 'a model start keeps its progress and retry error on the selected preview',
+ (tester) async {
+ final app = _EdgeApp();
+ final reply = Completer<Map<String, dynamic>>();
+ app.actionReply = reply;
+ final fixture = await mount(tester, app: app, query: ':gemma');
+ fixture.search.setModelSelection('codex', app.inventory, machineId: 'm');
+ final selected = fixture.search.selected!;
+ expect(fixture.search.canStartModelForUse(selected), isTrue);
+ final start = fixture.search.startModelForUse(
+ selected,
+ stillCurrent: () => true,
+ );
+ await tester.pump();
+ expect(find.textContaining('Starting…'), findsOneWidget);
+ expect(fixture.search.selected!.id, selected.id);
+ const failure = {
+ 'id': 'start',
+ 'modelId': 'gemma',
+ 'action': 'start',
+ 'stage': 'starting',
+ 'phase': 'failed',
+ 'error': 'Not enough memory',
+ };
+ app.localInventory = {
+ 'models': [
+ {
+ 'id': 'gemma',
+ 'name': 'gemma-4-12B',
+ 'state': 'downloaded',
+ 'canStart': true,
+ 'operation': failure,
+ },
+ ],
+ };
+ reply.complete({'operation': failure});
+ await tester.pumpAndSettle();
+ expect(await start, isNull);
+ expect(fixture.search.modelUseError, 'Not enough memory');
+ expect(find.text('Not enough memory'), findsWidgets);
+ expect(fixture.search.selected!.id, selected.id);
+ expect(app.actions, hasLength(1));
+ expect(fixture.choices, isEmpty);
+ },
+ );
+
+ testWidgets('narrow API preview wraps labels and explains host ownership', (
+ tester,
+ ) async {
+ final app = _EdgeApp();
+ const api = ApiConnection({
+ 'id': 'edge-api',
+ 'name': 'Private API',
+ 'provider': 'custom',
+ 'baseUrl': 'https://example.invalid/v1',
+ 'authHeader': 'Authorization',
+ 'authPrefix': 'Bearer',
+ });
+ final fixture = await mount(tester, app: app, query: ':', width: 250);
+ app.modelManager.apis
+ ..connections = [api]
+ ..loaded = true;
+ app.modelManager.apis.models['edge-api'] = ApiModels(
+ models: [const ApiModel(id: 'reasoning', name: 'Reasoning model')],
+ );
+ app.modelManager.apis.notifyListeners();
+ fixture.search.setQuery(':reasoning');
+ fixture.search.move(1); // The API heading stays above its matching models.
+ fixture.search.setModelSelection(
+ 'codex',
+ app.inventory,
+ machineId: 'other',
+ );
+ await tester.pumpAndSettle();
+ expect(
+ fixture.search.selected?.modelId,
+ 'model:apimodel:edge-api:reasoning',
+ reason:
+ 'catalog=${fixture.catalog.entries.keys}; rows=${fixture.search.rows.map((row) => row.id)}',
+ );
+ expect(find.text('Reasoning model'), findsOneWidget);
+ expect(
+ find.textContaining('only the harnesses there can run on it'),
+ findsOneWidget,
+ );
+ expect(tester.takeException(), isNull);
+ fixture.search.setModelSelection(
+ 'terminal',
+ const GridModels(
+ gridName: 'home',
+ models: [],
+ localModelEngines: {'codex'},
+ ),
+ machineId: 'm',
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Not available to this harness'), findsOneWidget);
+ await invoke(tester, fixture, 'picker.resource_settings');
+ expect(find.byType(ApiPickerForm), findsOneWidget);
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('api-form-input:name')))
+ .controller!
+ .text,
+ 'Private API',
+ );
+ });
+}
diff --git a/desktop/test/desktop_search_polish_test.dart b/desktop/test/desktop_search_polish_test.dart
new file mode 100644
index 000000000..2cfdfc397
--- /dev/null
+++ b/desktop/test/desktop_search_polish_test.dart
@@ -0,0 +1,1310 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/models/api_connections_controller.dart';
+import 'package:harness/models/model_search_catalog.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/usage/models_menu_controller.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/desktop_search_panel.dart';
+import 'package:harness/widgets/api_picker_form.dart';
+import 'package:harness/widgets/machine_picker_form.dart';
+import 'package:harness/widgets/session_tail_view.dart';
+import 'package:harness/widgets/swarm_resource_preview.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/widgets/terminal_text_action.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' as configured;
+import 'resource_picker_test.dart' as resources;
+import 'session_search_rendering_test.dart' show TailConnection;
+import 'support/open_harness.dart';
+import 'support/mixed_agents.dart';
+import 'support/model_manager.dart';
+import 'swarm_state_test.dart' show createApp;
+
+class _Palette {
+ _Palette({AppNotifier? app, ModelSearchCatalog? models})
+ : app = app ?? createApp() {
+ if (app == null) seedMixedAgents(this.app);
+ search = SwarmSearchController(
+ this.app,
+ const [],
+ adding: true,
+ activityFirst: true,
+ models: models,
+ offersCreate: models != null,
+ commands: () => [
+ SwarmDestination(
+ id: 'command:agent.new',
+ title: 'New harness',
+ detail: 'Start a new harness',
+ commandId: 'agent.new',
+ shortcut: '⌘N',
+ swarmId: null,
+ current: false,
+ ),
+ ],
+ selectOnEmptyQuery: false,
+ offersHarnessCreate: false,
+ );
+ search.addListener(sync);
+ }
+
+ final AppNotifier app;
+ late final SwarmSearchController search;
+ final editor = TextEditingController();
+ final focus = FocusNode(debugLabel: 'Search fixture');
+ final map = MemoryKeymap();
+ final controls = SearchPreviewControls();
+ final chosen = <SwarmSearchSelection>[];
+ final picture = GlobalKey();
+ var closed = 0;
+
+ void sync() {
+ if (editor.text == search.query) return;
+ editor.value = TextEditingValue(
+ text: search.query,
+ selection: TextSelection.collapsed(offset: search.query.length),
+ );
+ }
+
+ void dispose() {
+ controls.dispose();
+ search.removeListener(sync);
+ search.dispose();
+ editor.dispose();
+ focus.dispose();
+ map.dispose();
+ app.dispose();
+ }
+
+ Widget widget({
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ SearchPreviewControls? previewControls,
+ Key? resourceKey,
+ }) => MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: KeymapProvider(
+ keymap: map,
+ child: KeymapHost(
+ keymap: map,
+ enabled: () => true,
+ actions: const {},
+ child: RepaintBoundary(
+ key: picture,
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Padding(
+ padding: const EdgeInsets.all(20),
+ child: Center(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: DesktopSearchPanel.maxWidth,
+ maxHeight: DesktopSearchPanel.maxHeight,
+ ),
+ child: SwarmSearchKeys(
+ desktop: true,
+ search: search,
+ editing: editor,
+ previewControls: previewControls ?? controls,
+ onChoose: chosen.add,
+ onClose: () => closed++,
+ onRefocus: focus.requestFocus,
+ child: DesktopSearchPanel(
+ search: search,
+ editing: editor,
+ focusNode: focus,
+ onChoose: chosen.add,
+ onClose: () => closed++,
+ onRefocus: focus.requestFocus,
+ previewBuilder: () => SwarmResourcePreview(
+ key: resourceKey,
+ search: search,
+ controls: previewControls ?? controls,
+ onChoose: chosen.add,
+ onRefocus: focus.requestFocus,
+ onModalChanged: (_) {},
+ onCommands: () => search.setQuery('>'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+}
+
+class _ReviewSubscriptions extends ModelsMenuController {
+ @override
+ List<Map<String, Object?>> get rows => const [
+ {
+ 'engine': 'codex',
+ 'title': 'OpenAI',
+ 'status': '71% remaining',
+ 'remainingPercent': 71.0,
+ 'details': ['Weekly usage · resets Friday'],
+ },
+ {
+ 'engine': 'claude',
+ 'title': 'Anthropic',
+ 'status': 'Not signed in',
+ 'details': ['Sign in to Claude on this computer.'],
+ },
+ ];
+}
+
+class _InventoryApp extends ModelManagerTestApp {
+ _InventoryApp() : super(ModelManagerConnection()) {
+ machines = [];
+ machineStates.clear();
+ }
+
+ @override
+ String? machineListError;
+
+ @override
+ bool get machinesRefreshing => _retry != null;
+
+ Completer<void>? _retry;
+ int retryCalls = 0;
+
+ @override
+ Future<void> retryMachines() async {
+ if (_retry != null) return _retry!.future;
+ retryCalls++;
+ final pending = _retry = Completer<void>();
+ notifyListeners();
+ await pending.future;
+ _retry = null;
+ machineListError = null;
+ notifyListeners();
+ }
+
+ void finishRetry() => _retry!.complete();
+}
+
+void main() {
+ final renderDir = Platform.environment['DESKTOP_SEARCH_RENDER_DIR'];
+ setUpAll(() async {
+ if (renderDir != null) await loadPreviewFonts();
+ });
+ const inputKey = ValueKey('swarm-search-input');
+ final input = find.byKey(inputKey);
+
+ Future<_Palette> mount(
+ WidgetTester tester, {
+ Size size = const Size(1120, 740),
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ AppNotifier? app,
+ ModelSearchCatalog? models,
+ }) async {
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final fixture = _Palette(app: app, models: models);
+ addTearDown(fixture.dispose);
+ await tester.pumpWidget(
+ fixture.widget(brightness: brightness, scale: scale),
+ );
+ await tester.pumpAndSettle();
+ return fixture;
+ }
+
+ Future<_Palette> mountModels(
+ WidgetTester tester, {
+ Size size = const Size(1440, 940),
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ int modelCount = 3,
+ }) async {
+ final app = ModelManagerTestApp(ModelManagerConnection());
+ app.machineStates.clear();
+ seedMixedAgents(app);
+ app.machineStates['m']!.localOnly = true;
+ app.localInventory = {
+ 'models': [
+ for (var i = 0; i < modelCount; i++)
+ {
+ 'id': 'review-model-$i',
+ 'name': i == 0 ? 'Qwen3.8-27B' : 'Gemma 4 ${i + 1}',
+ 'state': i == 0 ? 'running' : 'downloaded',
+ 'canStart': i != 0,
+ 'canStop': i == 0,
+ },
+ ],
+ };
+ app.inventory = const GridModels(
+ gridName: 'home',
+ models: [],
+ grids: [
+ GridSection(
+ name: 'Design team',
+ own: false,
+ models: [GridModel(id: 'Shared Qwen3.8', node: 'Studio')],
+ ),
+ ],
+ );
+ app.modelManager.apis
+ ..connections = [
+ const ApiConnection({
+ 'id': 'review-api',
+ 'provider': 'custom',
+ 'name': 'OpenRouter',
+ 'baseUrl': 'https://openrouter.ai/api/v1',
+ 'keyEnv': 'OPENROUTER_API_KEY',
+ }),
+ ]
+ ..loaded = true;
+ await app.modelManager.refresh();
+ final subscriptions = _ReviewSubscriptions();
+ final models = ModelSearchCatalog(
+ app.modelManager,
+ subscriptions,
+ pollHosts: false,
+ );
+ final palette = await mount(
+ tester,
+ app: app,
+ models: models,
+ size: size,
+ brightness: brightness,
+ scale: scale,
+ );
+ addTearDown(() {
+ models.dispose();
+ subscriptions.dispose();
+ });
+ return palette;
+ }
+
+ Future<void> capture(
+ WidgetTester tester,
+ _Palette palette,
+ String name,
+ ) async {
+ if (renderDir == null) return;
+ final previousShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ final boundary =
+ palette.picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final images = tester.widgetList<Image>(
+ find.descendant(
+ of: find.byKey(palette.picture),
+ matching: find.byType(Image),
+ ),
+ );
+ await tester.runAsync(() async {
+ await Future.wait([
+ for (final image in images)
+ precacheImage(image.image, palette.picture.currentContext!),
+ ]);
+ });
+ void repaint(RenderObject object) {
+ object.markNeedsPaint();
+ object.visitChildren(repaint);
+ }
+
+ repaint(boundary);
+ await tester.pump();
+ await tester.runAsync(() async {
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ final directory = Directory(renderDir)..createSync(recursive: true);
+ await File('${directory.path}/$name.png')
+ .writeAsBytes(data!.buffer.asUint8List());
+ image.dispose();
+ });
+ debugDisableShadows = previousShadows;
+ repaint(boundary);
+ await tester.pump();
+ }
+
+ test('preview activity says now below one minute and retains older ages', () {
+ final now = DateTime(2026, 9, 29, 12);
+ expect(sessionPreviewAge(now, now), 'now');
+ expect(
+ sessionPreviewAge(now.subtract(const Duration(seconds: 59)), now),
+ 'now',
+ );
+ expect(
+ sessionPreviewAge(now.subtract(const Duration(minutes: 1)), now),
+ '1m ago',
+ );
+ expect(
+ sessionPreviewAge(now.subtract(const Duration(hours: 2)), now),
+ '2h ago',
+ );
+ });
+
+ testWidgets('inventory loading settles without changing the empty catalog', (
+ tester,
+ ) async {
+ final app = _InventoryApp()..machinesLoading = true;
+ final palette = await mount(tester, app: app);
+ expect(palette.search.rows, isEmpty);
+ expect(find.text('Loading harnesses…'), findsOneWidget);
+ expect(find.textContaining('No harnesses yet'), findsNothing);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.chosen, isEmpty);
+
+ for (final (query, resource) in [('@', 'machines'), ('#', 'projects')]) {
+ palette.search.setQuery(query);
+ await tester.pumpAndSettle();
+ expect(find.text('Loading $resource…'), findsOneWidget);
+ expect(find.text('No matching $resource'), findsNothing);
+ }
+ palette.search.setQuery('>nothing matches');
+ await tester.pumpAndSettle();
+ expect(find.text('No matching commands'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('swarm-search-inventory-state')),
+ findsNothing,
+ );
+
+ palette.search.setQuery('');
+ await tester.pumpAndSettle();
+ app.machinesLoading = false;
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(find.text('Loading harnesses…'), findsNothing);
+ expect(find.textContaining('No harnesses yet'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ '${brightness.name} empty inventory failure retries once from the keyboard',
+ (tester) async {
+ final app = _InventoryApp();
+ final palette = await mount(
+ tester,
+ app: app,
+ brightness: brightness,
+ size: const Size(390, 520),
+ scale: 1.6,
+ );
+ const error =
+ 'The machine inventory could not be reached. Your existing '
+ 'harnesses will appear after the connection is restored.';
+ app.machineListError = error;
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(find.text('Couldn’t load your harnesses'), findsOneWidget);
+ expect(find.text(error), findsOneWidget);
+ expect(find.textContaining('No harnesses yet'), findsNothing);
+ await capture(tester, palette, 'inventory-error-${brightness.name}');
+ final retry = find.byKey(
+ const ValueKey('swarm-search-inventory-retry'),
+ );
+ await tester.ensureVisible(retry);
+ final button = find.descendant(
+ of: retry,
+ matching: find.byType(TextButton),
+ );
+ Focus.of(tester.element(find.text('Retry'))).requestFocus();
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.retryCalls, 1);
+ expect(find.text('Loading harnesses…'), findsOneWidget);
+ expect(tester.widget<TextButton>(button).onPressed, isNull);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.retryCalls, 1);
+ expect(palette.chosen, isEmpty);
+ app.finishRetry();
+ await tester.pumpAndSettle();
+ expect(find.textContaining('No harnesses yet'), findsOneWidget);
+ expect(find.text(error), findsNothing);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
+ testWidgets('loaded harnesses remain visible during inventory recovery', (
+ tester,
+ ) async {
+ final app = _InventoryApp();
+ seedMixedAgents(app);
+ final palette = await mount(tester, app: app);
+ final before = palette.search.rows.map((row) => row.id).toList();
+ expect(before, isNotEmpty);
+ app.machinesLoading = true;
+ app.machineListError = 'Inventory temporarily unavailable';
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(palette.search.rows.map((row) => row.id), before);
+ expect(
+ find.byKey(const ValueKey('swarm-search-result-list')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('swarm-search-inventory-state')),
+ findsNothing,
+ );
+ expect(tester.takeException(), isNull);
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final enlarged in [false, true]) {
+ testWidgets(
+ 'transcript preview is readable ${brightness.name} ${enlarged ? 'enlarged' : 'wide'}',
+ (tester) async {
+ const answer =
+ 'The account switcher now saves the current draft before changing profiles. '
+ 'Returning to the previous account restores the same tab, cursor position, '
+ 'and unsent text, so a quick identity check does not interrupt the task.\n\n'
+ 'I verified keyboard selection, reconnect recovery, and two browser sessions '
+ 'using the same project. The stale request is ignored after an account change, '
+ 'and a failed refresh keeps the last confirmed project visible.\n\n'
+ 'Changed: AccountSwitcher.tsx, draftStore.ts\n'
+ 'verify: pnpm test account-switcher\n'
+ 'Result: 18 checks passed; no duplicate draft writes.';
+ final now = DateTime.now();
+ final connection = TailConnection(
+ const {},
+ tail: (_) => {
+ 'rows': [
+ {
+ 'turn': 0,
+ 'at': now.millisecondsSinceEpoch,
+ 'ask': 'Preserve every draft when switching accounts.',
+ 'answer': answer,
+ 'tools': '',
+ },
+ ],
+ 'hasMore': false,
+ 'total': 1,
+ 'lastAsk': {
+ 'turn': 0,
+ 'at': now.millisecondsSinceEpoch,
+ 'ask': 'Preserve every draft when switching accounts.',
+ },
+ },
+ );
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ app.machineStates['m']!.agents = [
+ Agent(
+ id: 'account-switcher',
+ sessionId: 'account-switcher-session',
+ name: 'Account switcher draft recovery',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastActivityAt: now,
+ project: const AgentProject(
+ name: 'frontend-platform',
+ cwd: '/work/frontend-platform',
+ branch: 'feature/account-switcher',
+ ),
+ ),
+ ];
+ final palette = await mount(
+ tester,
+ app: app,
+ brightness: brightness,
+ size: const Size(1440, 940),
+ scale: enlarged ? 1.6 : 1,
+ );
+ await tester.enterText(input, 'Account switcher');
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpAndSettle();
+ final tail = find.byKey(
+ const ValueKey('session-tail:m:account-switcher-session'),
+ );
+ final text = find.text(answer, findRichText: true);
+ final viewport = tester.getRect(tail);
+ final answerRect = tester.getRect(text);
+ expect(viewport.width, greaterThan(600));
+ expect(answerRect.bottom, lessThanOrEqualTo(viewport.bottom));
+ if (!enlarged) {
+ expect(answerRect.top, greaterThanOrEqualTo(viewport.top));
+ final rendered = tester.widget<RichText>(text);
+ final measure = TextPainter(
+ text: rendered.text,
+ textScaler: rendered.textScaler,
+ textDirection: TextDirection.ltr,
+ )..layout(maxWidth: answerRect.width);
+ final currentLines = measure.computeLineMetrics().length;
+ measure.layout(maxWidth: (880 - 1) * .45 - 36);
+ final previousLines = measure.computeLineMetrics().length;
+ measure.dispose();
+ expect(currentLines, lessThan(previousLines));
+ if (renderDir != null) {
+ debugPrint(
+ 'Transcript review: ${answerRect.width.toStringAsFixed(0)}pt '
+ 'reading width, $currentLines lines; old panel360pt, '
+ '$previousLines lines.',
+ );
+ }
+ }
+ expect(
+ find.descendant(
+ of: find.byType(SwarmResourcePreview),
+ matching: find.text('now'),
+ ),
+ findsOneWidget,
+ );
+ expect(find.textContaining('0m ago'), findsNothing);
+ expect(tester.takeException(), isNull);
+ await capture(
+ tester,
+ palette,
+ 'transcript-${brightness.name}-${enlarged ? 'enlarged' : 'wide'}',
+ );
+ },
+ );
+ }
+ }
+
+ testWidgets('roomy palette gives the selected preview most of the width', (
+ tester,
+ ) async {
+ final palette = await mount(tester, size: const Size(1440, 940));
+ final panel = find.byKey(const ValueKey('swarm-search-results'));
+ final original = tester.getRect(panel);
+ final editor = tester.element(input);
+ expect(original.size, const Size(1120, 680));
+ await tester.enterText(input, 'login');
+ await tester.pumpAndSettle();
+ final preview = tester.getRect(find.byType(SwarmResourcePreview));
+ final results = tester.getRect(
+ find.byKey(const ValueKey('swarm-search-result-list')),
+ );
+ expect(preview.width, greaterThan(600));
+ expect(preview.width / (preview.width + results.width), closeTo(.56, .01));
+ for (final query in [
+ '@ M2',
+ '# openharness',
+ '* Robot',
+ '> new',
+ 'no-result',
+ ]) {
+ await tester.enterText(input, query);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpAndSettle();
+ expect(tester.getRect(panel), original);
+ expect(tester.element(input), same(editor));
+ }
+ expect(palette.chosen, isEmpty);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('model headings and group gaps are smaller than result rows', (
+ tester,
+ ) async {
+ final palette = await mountModels(tester);
+ await tester.enterText(input, ':');
+ await tester.pumpAndSettle();
+ final first = palette.search.rows.first;
+ final second = palette.search.rows[1];
+ final firstRect = tester.getRect(find.byKey(ValueKey(first.id)));
+ final secondRect = tester.getRect(find.byKey(ValueKey(second.id)));
+ final subscriptions = tester.getRect(
+ find.byKey(const ValueKey('model-section:Subscriptions')),
+ );
+ final apis = tester.getRect(
+ find.byKey(const ValueKey('model-section:APIs')),
+ );
+ expect(subscriptions.height, lessThan(firstRect.height));
+ expect(apis.top - secondRect.bottom, inInclusiveRange(8, 12));
+ expect(secondRect.top - firstRect.bottom, closeTo(4, .01));
+ final headingText = tester.getRect(
+ find.descendant(
+ of: find.byKey(const ValueKey('model-section:Subscriptions')),
+ matching: find.byType(Text),
+ ),
+ );
+ expect(headingText.left, closeTo(firstRect.left + 14, .01));
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('mixed model heights keep keyboard selections fully visible', (
+ tester,
+ ) async {
+ final palette = await mountModels(
+ tester,
+ size: const Size(1000, 720),
+ scale: 1.6,
+ modelCount: 24,
+ );
+ await tester.enterText(input, ':');
+ await tester.pumpAndSettle();
+ void expectSelectionVisible() {
+ final viewport = tester.getRect(
+ find.byKey(const ValueKey('swarm-search-result-list')),
+ );
+ final selected = tester.getRect(
+ find.byKey(ValueKey(palette.search.selected!.id)),
+ );
+ expect(selected.top, greaterThanOrEqualTo(viewport.top - .01));
+ expect(selected.bottom, lessThanOrEqualTo(viewport.bottom + .01));
+ }
+
+ for (var page = 0; page < 8; page++) {
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await tester.pumpAndSettle();
+ expectSelectionVisible();
+ }
+ expect(palette.search.cursor, palette.search.rows.length - 1);
+ for (var page = 0; page < 8; page++) {
+ await key(tester, LogicalKeyboardKey.pageUp);
+ await tester.pumpAndSettle();
+ expectSelectionVisible();
+ }
+ expect(palette.search.cursor, 0);
+ expect(palette.focus.hasFocus, isTrue);
+ expect(palette.chosen, isEmpty);
+ expect((palette.app as ModelManagerTestApp).actions, isEmpty);
+ expect(tester.takeException(), isNull);
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final layout in [
+ (name: 'wide', size: const Size(1440, 940), scale: 1.0),
+ (name: 'enlarged', size: const Size(1200, 900), scale: 1.6),
+ (name: 'narrow', size: const Size(440, 780), scale: 1.6),
+ ]) {
+ testWidgets('every search scope fits ${brightness.name} ${layout.name}', (
+ tester,
+ ) async {
+ final palette = await mountModels(
+ tester,
+ brightness: brightness,
+ size: layout.size,
+ scale: layout.scale,
+ );
+ final panel = find.byKey(const ValueKey('swarm-search-results'));
+ final original = tester.getRect(panel);
+ final editor = tester.element(input);
+ for (final (name, query) in [
+ ('harnesses', 'login'),
+ ('machines', '@'),
+ ('projects', '#'),
+ ('models', ':'),
+ ('store', '*'),
+ ('commands', '> new'),
+ ]) {
+ await tester.enterText(input, query);
+ await tester.pumpAndSettle();
+ expect(palette.search.rows, isNotEmpty, reason: name);
+ expect(tester.getRect(panel), original, reason: name);
+ expect(tester.element(input), same(editor), reason: name);
+ expect(tester.takeException(), isNull, reason: name);
+ await capture(
+ tester,
+ palette,
+ 'scope-$name-${brightness.name}-${layout.name}',
+ );
+ if (name == 'models') {
+ final preview = find.byType(SwarmResourcePreview);
+ expect(
+ find.descendant(of: preview, matching: find.text('Machine')),
+ findsNothing,
+ reason: 'A subscription is not a machine',
+ );
+ final local = palette.search.rows.indexWhere(
+ (row) => row.modelId == 'model:local:review-model-0',
+ );
+ expect(local, greaterThanOrEqualTo(0));
+ palette.search.move(local - palette.search.cursor);
+ await tester.pumpAndSettle();
+ final machineLabel = find.descendant(
+ of: preview,
+ matching: find.text('Machine'),
+ );
+ await tester.scrollUntilVisible(
+ machineLabel,
+ 100,
+ scrollable: find
+ .descendant(of: preview, matching: find.byType(Scrollable))
+ .first,
+ );
+ await tester.pumpAndSettle();
+ final labelRect = tester.getRect(machineLabel);
+ final machineValue = tester.getRect(
+ find.descendant(
+ of: preview,
+ matching: find.text(
+ '${thisComputerName()[0].toUpperCase()}${thisComputerName().substring(1)}',
+ ),
+ ),
+ );
+ expect(labelRect.height, lessThan(12 * layout.scale * 1.6));
+ if (layout.name == 'narrow') {
+ expect(labelRect.bottom, lessThan(machineValue.top));
+ } else {
+ expect(labelRect.top, closeTo(machineValue.top, .01));
+ expect(labelRect.right, lessThanOrEqualTo(machineValue.left));
+ }
+ expect(tester.takeException(), isNull);
+ await capture(
+ tester,
+ palette,
+ 'scope-model-detail-${brightness.name}-${layout.name}',
+ );
+ }
+ }
+ expect(palette.chosen, isEmpty);
+ expect((palette.app as ModelManagerTestApp).actions, isEmpty);
+ });
+ }
+ }
+
+ testWidgets(
+ 'native scopes put machines first and keep typed words and focus',
+ (tester) async {
+ final palette = await mount(tester);
+ expect(find.byType(DesktopPill), findsNWidgets(6));
+ expect(
+ find.byKey(const ValueKey('search-category-Harnesses')),
+ findsOneWidget,
+ );
+ expect(palette.search.hint, 'Search harnesses');
+ await tester.enterText(input, 'login');
+ for (final (label, prefix) in DesktopSearchPanel.categories) {
+ await tester.tap(find.byKey(ValueKey('search-category-$label')));
+ await tester.pumpAndSettle();
+ final exception = tester.takeException();
+ expect(exception, isNull, reason: 'Scope $label');
+ expect(palette.editor.text, prefix.isEmpty ? 'login' : '$prefix login');
+ expect(palette.focus.hasFocus, isTrue);
+ expect(palette.chosen, isEmpty);
+ expect(palette.closed, 0);
+ }
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets('clear search returns to the unselected root without closing', (
+ tester,
+ ) async {
+ final palette = await mount(tester);
+ expect(find.byKey(const ValueKey('search-clear-query')), findsNothing);
+ await tester.enterText(input, '@ M2');
+ await tester.pumpAndSettle();
+ expect(palette.search.selected, isNotNull);
+ await tester.tap(find.byKey(const ValueKey('search-clear-query')));
+ await tester.pumpAndSettle();
+ expect(palette.editor.text, isEmpty);
+ expect(palette.search.query, isEmpty);
+ expect(palette.search.selected, isNull);
+ expect(palette.search.showsTypeHints, isTrue);
+ expect(palette.focus.hasFocus, isTrue);
+ expect(palette.closed, 0);
+ expect(palette.chosen, isEmpty);
+ expect(find.byKey(const ValueKey('search-clear-query')), findsNothing);
+ });
+
+ testWidgets('empty Enter is inert and keyboard selection opens once', (
+ tester,
+ ) async {
+ final palette = await mount(tester);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.chosen, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ final chosenId = palette.search.selected!.id;
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.chosen, hasLength(1));
+ expect(palette.search.selected!.id, chosenId);
+ expect(palette.closed, 0);
+ });
+
+ testWidgets('composition owns arrows Enter and Escape', (tester) async {
+ final palette = await mount(tester);
+ await tester.enterText(input, 'login');
+ await tester.pumpAndSettle();
+ final selected = palette.search.selected!.id;
+ for (final logicalKey in [
+ LogicalKeyboardKey.arrowDown,
+ LogicalKeyboardKey.enter,
+ LogicalKeyboardKey.escape,
+ ]) {
+ // Flutter's fake input can commit preedit while processing a key. Each
+ // key starts with the active range that a platform IME would report.
+ palette.editor.value = const TextEditingValue(
+ text: 'login',
+ selection: TextSelection.collapsed(offset: 5),
+ composing: TextRange(start: 0, end: 5),
+ );
+ await key(tester, logicalKey);
+ expect(palette.search.selected!.id, selected);
+ expect(palette.chosen, isEmpty);
+ expect(palette.closed, 0);
+ expect(palette.editor.text, 'login');
+ }
+ });
+
+ testWidgets('machine controls keep the resource fixed and Escape returns', (
+ tester,
+ ) async {
+ final palette = await mount(tester);
+ await tester.enterText(input, '@ M2');
+ await tester.pumpAndSettle();
+ final selected = palette.search.selected!.id;
+ expect(find.byType(TerminalTextAction), findsNothing);
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.resource_rename')),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.search.managing, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(palette.search.selected!.id, selected);
+ expect(palette.search.managing, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(palette.search.managing, isFalse);
+ expect(palette.focus.hasFocus, isTrue);
+ expect(palette.editor.text, '@ M2');
+ expect(palette.closed, 0);
+ expect(palette.chosen, isEmpty);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('offline harnesses remain inspectable and cannot launch', (
+ tester,
+ ) async {
+ final palette = await mount(tester);
+ await tester.enterText(input, 'build-box');
+ await tester.pumpAndSettle();
+ final offline = palette.search.rows.indexWhere(
+ (row) => row.machineId == 'build' && row.agentId == 'login',
+ );
+ expect(offline, greaterThanOrEqualTo(0));
+ palette.search.move(offline - palette.search.cursor);
+ await tester.pumpAndSettle();
+ expect(palette.search.selected, isNotNull);
+ expect(
+ palette.search.sessionUnavailable(palette.search.selected),
+ 'Offline',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.chosen, isEmpty);
+ expect(palette.closed, 0);
+ expect(find.textContaining('Offline'), findsWidgets);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('preview toggle and commands preserve the same text editor', (
+ tester,
+ ) async {
+ final palette = await mount(tester);
+ final editorElement = tester.element(input);
+ await tester.enterText(input, 'login');
+ await tester.pumpAndSettle();
+ for (var i = 0; i < 2; i++) {
+ await tester.tap(find.byKey(const ValueKey('search-toggle-preview')));
+ await tester.pumpAndSettle();
+ expect(tester.element(input), same(editorElement));
+ expect(palette.focus.hasFocus, isTrue);
+ expect(palette.editor.text, 'login');
+ }
+ await tester.enterText(input, '> new');
+ await tester.pumpAndSettle();
+ expect(tester.element(input), same(editorElement));
+ expect(find.bySemanticsLabel('Command preview'), findsOneWidget);
+ expect(palette.chosen, isEmpty);
+ });
+
+ testWidgets('Return activates focused toolbar controls instead of a result', (
+ tester,
+ ) async {
+ final palette = await mount(tester);
+ await tester.enterText(input, 'login');
+ await tester.pumpAndSettle();
+ Future<void> focusButton(Key keyValue) async {
+ // Walk actual focus traversal instead of injecting a private FocusNode.
+ palette.focus.requestFocus();
+ for (var step = 0; step < 30; step++) {
+ await key(tester, LogicalKeyboardKey.tab);
+ final button = FocusManager.instance.primaryFocus?.context
+ ?.findAncestorWidgetOfExactType<IconButton>();
+ if (button?.key == keyValue) return;
+ }
+ fail('Toolbar control $keyValue was not keyboard reachable');
+ }
+
+ await focusButton(const ValueKey('search-toggle-preview'));
+ final visible = palette.search.previewVisible;
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.search.previewVisible, !visible);
+ expect(palette.chosen, isEmpty);
+ expect(palette.closed, 0);
+ await focusButton(const ValueKey('search-clear-query'));
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.editor.text, isEmpty);
+ expect(palette.chosen, isEmpty);
+ await focusButton(const ValueKey('search-close'));
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.closed, 1);
+ expect(palette.chosen, isEmpty);
+ });
+
+ testWidgets('focused scopes use arrows and Return returns to search', (
+ tester,
+ ) async {
+ final palette = await mount(tester);
+ var focusedScope = false;
+ for (var step = 0; step < 30; step++) {
+ await key(tester, LogicalKeyboardKey.tab);
+ focusedScope = tester
+ .widget<Focus>(find.byKey(const ValueKey('search-scopes')))
+ .focusNode!
+ .hasFocus;
+ if (focusedScope) break;
+ }
+ expect(focusedScope, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(palette.search.isMachineMode, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(palette.search.isProjectMode, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(palette.search.isMachineMode, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.focus.hasFocus, isTrue);
+ expect(palette.search.isMachineMode, isTrue);
+ expect(palette.chosen, isEmpty);
+ expect(palette.closed, 0);
+ });
+
+ testWidgets('standalone palette toolbar keeps normal keyboard traversal', (
+ tester,
+ ) async {
+ final palette = _Palette();
+ addTearDown(palette.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SwarmSearchKeys(
+ desktop: true,
+ search: palette.search,
+ editing: palette.editor,
+ onChoose: palette.chosen.add,
+ onClose: () => palette.closed++,
+ onRefocus: palette.focus.requestFocus,
+ child: DesktopSearchPanel(
+ search: palette.search,
+ editing: palette.editor,
+ focusNode: palette.focus,
+ onChoose: palette.chosen.add,
+ onClose: () => palette.closed++,
+ onRefocus: palette.focus.requestFocus,
+ previewBuilder: () => const SizedBox(),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.enterText(input, 'login');
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.editor.text, isEmpty);
+ expect(palette.focus.hasFocus, isTrue);
+ expect(palette.chosen, isEmpty);
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ final visible = palette.search.previewVisible;
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.search.previewVisible, !visible);
+ expect(palette.closed, 0);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets(
+ 'enlarged narrow preview keeps the latest turn under a long header',
+ (tester) async {
+ final connection = TailConnection(
+ const {},
+ tail: (_) => {
+ 'rows': [
+ {
+ 'turn': 0,
+ 'at': DateTime.now().millisecondsSinceEpoch,
+ 'ask': 'Verify the release',
+ 'answer': 'Newest verified answer',
+ 'tools': '',
+ },
+ ],
+ 'hasMore': false,
+ 'total': 1,
+ },
+ );
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ app.machineStates['m']!.agents = [
+ const Agent(
+ id: 'long-tail',
+ sessionId: 'long-tail-session',
+ name: 'Release investigation with a very long descriptive task name that wraps across several lines in a narrow window',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'a-project-with-a-long-directory-name',
+ cwd: '/work/projects/a-project-with-a-long-directory-name',
+ branch: 'feature/keep-the-latest-session-answer-visible',
+ ),
+ ),
+ ];
+ final palette = await mount(
+ tester,
+ app: app,
+ size: const Size(440, 780),
+ scale: 1.6,
+ );
+ await tester.enterText(input, 'Release investigation');
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpAndSettle();
+ final tail = find.byKey(
+ const ValueKey('session-tail:m:long-tail-session'),
+ );
+ expect(tail, findsOneWidget);
+ expect(tester.getSize(tail).height, greaterThan(45));
+ final answer = find.textContaining(
+ 'Newest verified answer',
+ findRichText: true,
+ );
+ expect(answer, findsOneWidget);
+ expect(tester.getRect(tail).overlaps(tester.getRect(answer)), isTrue);
+ expect(palette.focus.hasFocus, isTrue);
+ expect(tester.takeException(), isNull);
+ await capture(tester, palette, 'latest-tail-narrow-enlarged');
+ },
+ );
+
+ for (final brightness in Brightness.values) {
+ for (final narrow in [false, true]) {
+ testWidgets(
+ '${brightness.name} ${narrow ? 'narrow enlarged' : 'regular'} palette fits long names and empty matches',
+ (tester) async {
+ final palette = await mount(
+ tester,
+ brightness: brightness,
+ size: narrow ? const Size(440, 780) : const Size(1120, 740),
+ scale: narrow ? 1.6 : 1,
+ );
+ final machine = palette.app.machineStates['m']!;
+ machine.agents = [
+ const Agent(
+ id: 'very-long',
+ name: 'Fix 日本語 👩🏽‍💻 account switching and preserve every unsaved document while reconnecting the remote machine',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'a-project-with-a-very-long-name',
+ cwd: '/work/projects/a-project-with-a-very-long-name',
+ branch: 'feature/preserve-every-unsaved-document',
+ ),
+ ),
+ ];
+ palette.app.notifyListeners();
+ await tester.enterText(input, 'unsaved');
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await capture(
+ tester,
+ palette,
+ 'search-${brightness.name}-${narrow ? 'narrow' : 'regular'}',
+ );
+ await tester.enterText(input, '@ M2');
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await capture(
+ tester,
+ palette,
+ 'machines-${brightness.name}-${narrow ? 'narrow' : 'regular'}',
+ );
+ await tester.enterText(input, 'no-such-result-999999');
+ await tester.pump(const Duration(milliseconds: 350));
+ await tester.pumpAndSettle();
+ expect(palette.search.rows, isEmpty);
+ expect(find.text('No matching harnesses'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(palette.chosen, isEmpty);
+ },
+ );
+ }
+ }
+
+ testWidgets('replacement resource controls release the old dispatcher', (
+ tester,
+ ) async {
+ final palette = await mount(tester);
+ await tester.enterText(input, '@ M2');
+ await tester.pumpAndSettle();
+ final replacement = SearchPreviewControls();
+ addTearDown(replacement.dispose);
+ await tester.pumpWidget(palette.widget(previewControls: replacement));
+ await tester.pumpAndSettle();
+ expect(palette.controls.dispatch, isNull);
+ expect(palette.controls.commands, isNull);
+ expect(replacement.dispatch, isNotNull);
+ expect(replacement.invoke('picker.focus_actions'), isTrue);
+ await tester.pumpAndSettle();
+ expect(palette.search.managing, isTrue);
+ expect(palette.closed, 0);
+ });
+
+ testWidgets('disposing an old preview preserves the new keyboard owner', (
+ tester,
+ ) async {
+ final palette = await mount(tester);
+ await tester.enterText(input, '@ M2');
+ await tester.pumpAndSettle();
+ await tester.pumpWidget(
+ palette.widget(resourceKey: const ValueKey('new-preview')),
+ );
+ await tester.pumpAndSettle();
+ expect(palette.controls.commands, isNotNull);
+ expect(palette.controls.invoke('picker.focus_actions'), isTrue);
+ await tester.pumpAndSettle();
+ expect(palette.search.managing, isTrue);
+ expect(palette.closed, 0);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets(
+ 'reopened workspace palettes retain controls and Escape hierarchy',
+ (tester) async {
+ final app = await resources.fixture();
+ final map = MemoryKeymap();
+ var disposed = false;
+ addTearDown(() {
+ if (!disposed) app.dispose();
+ });
+ addTearDown(map.dispose);
+ await configured.mount(tester, app, map);
+ for (var cycle = 0; cycle < 3; cycle++) {
+ await openHarnessPicker(tester);
+ await tester.enterText(input, '@This Mac');
+ await tester.pumpAndSettle();
+ final search = resources.search(tester);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(search.managing, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(MachinePickerForm), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(MachinePickerForm), findsNothing);
+ expect(search.managing, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ expect(search.managing, isFalse);
+
+ await tester.enterText(input, ':deepseek');
+ await tester.pumpAndSettle();
+ final api = search.rows.indexWhere(
+ (row) => row.modelId == 'model:api:deepseek-api',
+ );
+ expect(api, greaterThanOrEqualTo(0));
+ search.move(api - search.cursor);
+ await tester.pumpAndSettle();
+ await resources.tabTo(
+ tester,
+ find.byKey(
+ const ValueKey('resource-action:picker.resource_settings'),
+ ),
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(ApiPickerForm), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(ApiPickerForm), findsNothing);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+
+ await tester.enterText(input, 'Checkout retries');
+ await tester.pumpAndSettle();
+ expect(search.selected!.agentId, 'a0');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(input, findsNothing);
+ expect(app.actions, isEmpty);
+ expect(tester.takeException(), isNull);
+ }
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ disposed = true;
+ },
+ );
+
+ testWidgets(
+ 'replacement result controllers own paging and reveal selection',
+ (tester) async {
+ final app = createApp(connected: true);
+ final first = SwarmSearchController(app, const [], adding: true);
+ final second = SwarmSearchController(app, const [], adding: true);
+ addTearDown(app.dispose);
+ addTearDown(first.dispose);
+ addTearDown(second.dispose);
+ Future<void> show(SwarmSearchController search) => tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: DesktopChrome(
+ child: SizedBox(
+ width: 600,
+ height: 300,
+ child: SwarmSearchResults(
+ search: search,
+ showPreview: false,
+ onChoose: (_) {},
+ onRefocus: () {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await show(first);
+ await tester.pumpAndSettle();
+ await show(second);
+ await tester.pumpAndSettle();
+ final starting = second.cursor;
+ second.pageResults(1);
+ await tester.pumpAndSettle();
+ expect(second.cursor, greaterThan(starting));
+ final selected = second.cursor;
+ first.pageResults(1);
+ await tester.pumpAndSettle();
+ expect(second.cursor, selected);
+ expect(tester.takeException(), isNull);
+ },
+ );
+}
diff --git a/desktop/test/desktop_task_palette_test.dart b/desktop/test/desktop_task_palette_test.dart
new file mode 100644
index 000000000..0f496aa1e
--- /dev/null
+++ b/desktop/test/desktop_task_palette_test.dart
@@ -0,0 +1,233 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/widgets/task_palette.dart';
+
+import 'support/real_fonts.dart';
+
+class _App extends AppNotifier {
+ _App()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ final routed = <String>[];
+ final sent = <(String, String, String)>[];
+ final reply = Completer<RouteAnswer?>();
+ @override
+ Future<RouteAnswer?> routeTask(String text) {
+ routed.add(text);
+ return reply.future;
+ }
+
+ @override
+ Future<String?> sendRoutedTask(
+ String agentId,
+ String machineId,
+ String text,
+ ) async {
+ sent.add((agentId, machineId, text));
+ return null;
+ }
+}
+
+RouteAnswer choices() => RouteAnswer(
+ agentId: 'a0',
+ machineId: 'm0',
+ name: 'Desktop design',
+ confidence: .6,
+ reason: 'Several agents are working on this project.',
+ weighed: 8,
+ machines: 2,
+ candidates: [
+ for (var i = 0; i < 8; i++)
+ RouteCandidate(
+ agentId: 'a$i',
+ machineId: 'm${i % 2}',
+ name: 'Desktop design ${i + 1}',
+ machine: i.isEven ? 'This Mac' : 'Studio',
+ recent: 'Polishing the welcome experience',
+ engine: i.isEven ? 'codex' : 'claude',
+ confidence: i == 0 ? .6 : .4,
+ ),
+ ],
+);
+
+void main() {
+ setUpAll(loadRealFonts);
+ for (final choosing in [false, true]) {
+ for (final key in [LogicalKeyboardKey.enter, LogicalKeyboardKey.escape]) {
+ testWidgets(
+ 'composition owns ${key.keyLabel} while ${choosing ? 'choosing an agent' : 'typing a task'}',
+ (tester) async {
+ final app = _App();
+ try {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showTaskPalette(context, app),
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ final field = find.byType(TextField);
+ if (choosing) {
+ await tester.enterText(field, 'Review the desktop');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ app.reply.complete(choices());
+ await tester.pumpAndSettle();
+ }
+ const composing = TextEditingValue(
+ text: 'しごと',
+ selection: TextSelection.collapsed(offset: 3),
+ composing: TextRange(start: 0, end: 3),
+ );
+ tester.testTextInput.updateEditingValue(composing);
+ await tester.pump();
+ await tester.sendKeyEvent(key);
+ await tester.pump();
+ expect(app.routed, choosing ? ['Review the desktop'] : isEmpty);
+ expect(app.sent, isEmpty);
+ expect(field, findsOneWidget);
+ expect(
+ tester.widget<TextField>(field).controller!.value,
+ composing,
+ );
+
+ tester.testTextInput.updateEditingValue(
+ composing.copyWith(composing: TextRange.empty),
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(key);
+ await tester.pump();
+ if (key == LogicalKeyboardKey.escape) {
+ await tester.pumpAndSettle();
+ expect(field, findsNothing);
+ } else if (choosing) {
+ expect(app.sent, [('a0', 'm0', 'しごと')]);
+ } else {
+ expect(app.routed, ['しごと']);
+ app.reply.complete(choices());
+ await tester.pumpAndSettle();
+ }
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 1));
+ app.dispose();
+ }
+ },
+ );
+ }
+ }
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.7]) {
+ testWidgets(
+ 'task routing fits ${brightness.name} at $scale and keeps selection in view',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = scale == 1
+ ? const Size(900, 700)
+ : const Size(420, 480);
+ addTearDown(tester.view.reset);
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final app = _App();
+ final picture = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: picture,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showTaskPalette(context, app),
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ final field = find.byType(TextField);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await tester.enterText(field, 'Polish the desktop');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.routed, ['Polish the desktop']);
+ expect(app.sent, isEmpty);
+ app.reply.complete(choices());
+ await tester.pumpAndSettle();
+ expect(find.byType(EngineMark), findsNWidgets(8));
+ expect(find.byType(DesktopDialogSurface), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ final directory = Platform.environment['HARNESS_TASK_CAPTURE_DIR'];
+ if (directory != null) {
+ final previousShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ final boundary =
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ void repaint(RenderObject object) {
+ object.markNeedsPaint();
+ object.visitChildren(repaint);
+ }
+
+ repaint(boundary);
+ await tester.pump();
+ await tester.runAsync(() async {
+ final image = await boundary.toImage();
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(directory).create(recursive: true);
+ await File('$directory/task-${brightness.name}-$scale.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ debugDisableShadows = previousShadows;
+ }
+ for (var i = 0; i < 7; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ }
+ expect(find.text('Desktop design 8').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(field, findsNothing);
+ expect(app.sent, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+ }
+ }
+}
diff --git a/desktop/test/desktop_welcome_composer_test.dart b/desktop/test/desktop_welcome_composer_test.dart
new file mode 100644
index 000000000..4cfa9b9e3
--- /dev/null
+++ b/desktop/test/desktop_welcome_composer_test.dart
@@ -0,0 +1,591 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/appearance_prefs_store.dart';
+import 'package:harness/shared/theme/prompt_style.dart';
+import 'package:harness/shared/theme/status_line_style.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/widgets/status_line.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/harness_customize_pane.dart';
+import 'package:harness/shared/widgets/app_dialog.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' show mount, native, nativeChannel;
+import 'support/mixed_agents.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show MemoryStore, createApp;
+
+class _DelayedPreferences extends MemoryStore {
+ final loaded = Completer<String?>();
+
+ @override
+ Future<String?> read(String key) =>
+ key == 'new_agent_engine' ? loaded.future : super.read(key);
+}
+
+class _Connection extends WsConn {
+ _Connection(String machine)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: machine,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final starts = <Map<String, dynamic>>[];
+ Completer<Map<String, dynamic>>? pending;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async => switch (type) {
+ 'engines_probe' => {
+ 'engines': [
+ {'engine': 'codex', 'installed': true},
+ {'engine': 'claude', 'installed': true},
+ ],
+ },
+ 'dsh_list' => {'dsh': []},
+ 'fs_list_dir' => {'path': payload['path'] ?? '/work', 'entries': []},
+ 'agent_create' => _create(payload),
+ _ => {},
+ };
+ Future<Map<String, dynamic>> _create(Map<String, dynamic> payload) {
+ starts.add(Map.of(payload));
+ pending = Completer<Map<String, dynamic>>();
+ return pending!.future;
+ }
+
+ void complete() => pending!.complete({
+ 'creationId': starts.last['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'created',
+ 'name': 'Created harness',
+ 'engine': 'codex',
+ 'project': {'cwd': '/work/openharness'},
+ },
+ });
+}
+
+void main() {
+ late AppNotifier app;
+ late MemoryKeymap map;
+ late _Connection connection;
+ final updates = <Map<dynamic, dynamic>>[];
+ final picture = GlobalKey();
+ setUpAll(loadPreviewFonts);
+ final form = find.byType(NewHarnessForm);
+ final task = find.byKey(const ValueKey('new-harness-task'));
+ NewHarnessController box(WidgetTester tester) =>
+ tester.widget<NewHarnessForm>(form).controller;
+
+ Future<void> capture(WidgetTester tester, String name) async {
+ final directory = Platform.environment['WELCOME_COMPOSER_RENDER_DIR'];
+ if (directory == null) return;
+ await tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage();
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ Future<void> setup(
+ WidgetTester tester, {
+ bool withPane = false,
+ bool mac = false,
+ MemoryStore? storage,
+ }) async {
+ final old = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = old);
+ connection = _Connection('m');
+ app = createApp(store: storage, connectionForTest: (_) => connection);
+ map = MemoryKeymap();
+ seedMixedAgents(app);
+ app.machineStates['m']!.localOnly = true;
+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
+ if (storage is! _DelayedPreferences) {
+ await app.agentPreference.remember('codex');
+ }
+ await app.projectHistory.select('m', '/work/openharness');
+ if (withPane) app.adoptSessionForTest(terminal('a0', []));
+ if (mac) {
+ updates.clear();
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ (call) async {
+ if (call.method == 'update') updates.add(call.arguments as Map);
+ return null;
+ },
+ );
+ }
+ await mount(tester, app, map, native: mac);
+ await tester.pumpAndSettle();
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ null,
+ );
+ });
+ }
+
+ testWidgets(
+ 'empty tab embeds the shared composer and typing keeps its numbers',
+ (tester) async {
+ await setup(tester);
+ expect(tester.widget<NewHarnessForm>(form).embedded, isTrue);
+ expect(find.byKey(const ValueKey('welcome-sessions')), findsNothing);
+ expect(find.byKey(const ValueKey('workspace-status-bar')), findsNothing);
+ expect(find.byKey(const ValueKey('new-harness-close')), findsNothing);
+ expect(find.byKey(const ValueKey('new-harness-dismiss')), findsNothing);
+ expect(tester.widget<TextField>(task).focusNode!.hasFocus, isTrue);
+ final original = box(tester);
+ await tester.enterText(task, '123 work on this');
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ await tester.pumpAndSettle();
+ expect(box(tester), same(original));
+ expect(box(tester).task, '123 work on this');
+ expect(connection.starts, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.tapAt(const Offset(50, 180));
+ await tester.pumpAndSettle();
+ expect(form, findsOneWidget);
+ expect(box(tester).task, '123 work on this');
+ },
+ );
+
+ testWidgets('Cmd-P round trip restores the tab draft and chosen options', (
+ tester,
+ ) async {
+ await setup(tester);
+ await tester.enterText(task, 'Keep my page draft');
+ box(tester).setFolder('/work/selected');
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.pumpAndSettle();
+ expect(form, findsNothing);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'different search',
+ );
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ await tester.pumpAndSettle();
+ expect(box(tester).task, 'Keep my page draft');
+ expect(box(tester).project.folder, '/work/selected');
+ expect(tester.widget<TextField>(task).focusNode!.hasFocus, isTrue);
+ expect(connection.starts, isEmpty);
+ });
+
+ testWidgets('each new tab keeps its own draft after switching', (
+ tester,
+ ) async {
+ await setup(tester);
+ final first = app.activeSwarmId;
+ await tester.enterText(task, 'First draft');
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pumpAndSettle();
+ final second = app.activeSwarmId;
+ expect(second, isNot(first));
+ expect(box(tester).task, isEmpty);
+ await tester.enterText(task, 'Second draft');
+ app.selectSwarm(first);
+ await tester.pumpAndSettle();
+ expect(box(tester).task, 'First draft');
+ app.selectSwarm(second);
+ await tester.pumpAndSettle();
+ expect(box(tester).task, 'Second draft');
+ expect(connection.starts, isEmpty);
+ });
+
+ testWidgets('switching tabs while defaults load still opens the new page', (
+ tester,
+ ) async {
+ final storage = _DelayedPreferences();
+ await setup(tester, storage: storage);
+ expect(form, findsNothing);
+ expect(find.text('Harness anything'), findsOneWidget);
+ expect(find.text('Preparing your harness…'), findsOneWidget);
+ expect(find.text('Choose a machine'), findsNothing);
+ app.newSwarm(name: 'Second draft');
+ await tester.pumpAndSettle();
+ final target = app.activeSwarmId;
+ storage.loaded.complete('codex');
+ await tester.pumpAndSettle();
+ expect(form, findsOneWidget);
+ expect(find.text('Preparing your harness…'), findsNothing);
+ expect(box(tester).swarmId, target);
+ expect(tester.widget<TextField>(task).focusNode!.hasFocus, isTrue);
+ expect(connection.starts, isEmpty);
+ });
+
+ testWidgets(
+ 'page launches once into its own tab and blocks another start while pending',
+ (tester) async {
+ await setup(tester);
+ final tab = app.activeSwarmId;
+ final tabs = app.swarms.length;
+ await tester.enterText(task, 'Build the page');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(connection.starts, hasLength(1));
+ expect(connection.starts.single['prompt'], 'Build the page');
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.activeSwarmId, tab);
+ expect(connection.starts, hasLength(1));
+ connection.complete();
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.activeSwarmId, tab);
+ expect(app.swarms, hasLength(tabs));
+ expect(app.panes.single.agentId, 'created');
+ expect(form, findsNothing);
+ },
+ );
+
+ testWidgets('Escape from search restores the embedded draft', (tester) async {
+ await setup(tester);
+ await tester.enterText(task, 'Back from search');
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(box(tester).task, 'Back from search');
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final (size, scale) in [
+ (const Size(1280, 800), 1.0),
+ (const Size(640, 540), 1.6),
+ ]) {
+ testWidgets('welcome with recents fits $brightness at $size and $scale', (
+ tester,
+ ) async {
+ await setup(tester);
+ final oldAppearance = appearancePrefsStore.value;
+ addTearDown(() => appearancePrefsStore.value = oldAppearance);
+ appearancePrefsStore.value = oldAppearance.copyWith(
+ prompt: const PromptPrefs(statusStyle: StatusLineStyle.spaceship),
+ );
+ app.machineStates['m']!.agents = [
+ for (final (index, name) in [
+ 'Polish the desktop composer',
+ 'Explore the machine picker',
+ 'Improve notifications',
+ 'Build a shader preview',
+ 'Continue the research',
+ 'Review the release notes',
+ 'Older session seven',
+ 'Older session eight',
+ 'Older session nine',
+ ].indexed)
+ Agent(
+ id: 'recent-$index',
+ name: name,
+ engine: index.isEven ? 'codex' : 'claude',
+ terminalAvailable: true,
+ lastOpenedAt: DateTime.now().subtract(
+ Duration(minutes: index * 23),
+ ),
+ project: const AgentProject(
+ name: 'openharness',
+ cwd: '/work/openharness',
+ branch: 'experiment/friendly-desktop',
+ ),
+ ),
+ ];
+ tester.view.physicalSize = size;
+ final previous = grid.AppTheme.brightness.value;
+ final previousPalette = grid.AppTheme.palette.value;
+ grid.AppTheme.palette.value = grid.AppTheme.paletteFor(brightness);
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() {
+ grid.AppTheme.brightness.value = previous;
+ grid.AppTheme.palette.value = previousPalette;
+ });
+ final preview = MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => KeymapProvider(
+ keymap: map,
+ child: MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: RepaintBoundary(key: picture, child: child!),
+ ),
+ ),
+ home: SwarmScreen(
+ key: const ValueKey('welcome-render'),
+ notifier: app,
+ nativeTabs: false,
+ ),
+ );
+ await tester.pumpWidget(preview);
+ await tester.pumpAndSettle();
+ final tabInk = tester.widget<Text>(find.text('New Tab')).style!.color!;
+ final tabContrast =
+ (tabInk.computeLuminance() + .05) /
+ (grid.AppPalette.swarmWelcome.computeLuminance() + .05);
+ expect(
+ tabContrast >= 1 ? tabContrast : 1 / tabContrast,
+ greaterThanOrEqualTo(4.5),
+ reason: 'Tab names remain readable beside either app appearance.',
+ );
+ expect(find.text('Recent harnesses'), findsOneWidget);
+ final recent = find.byKey(const ValueKey('welcome-sessions'));
+ expect(
+ find.descendant(of: recent, matching: find.byType(EngineMark)),
+ findsNWidgets(6),
+ );
+ expect(
+ find.descendant(of: recent, matching: find.byType(ColorFiltered)),
+ findsNothing,
+ );
+ expect(find.text('Older session seven'), findsNothing);
+ expect(find.text('now'), findsOneWidget);
+ expect(find.text('0m'), findsNothing);
+ expect(
+ tester.getRect(recent).top,
+ greaterThanOrEqualTo(
+ tester
+ .getRect(
+ find.byKey(const ValueKey('new-harness-field-approvals')),
+ )
+ .bottom +
+ 56,
+ ),
+ );
+ final surface = tester.getRect(
+ find.byKey(const ValueKey('new-harness-surface')),
+ );
+ expect(surface.width, lessThanOrEqualTo(680));
+ expect(surface.center.dx, closeTo(size.width / 2, 1));
+ expect(tester.takeException(), isNull);
+ await capture(
+ tester,
+ 'welcome-${brightness.name}-${size.width.toInt()}',
+ );
+ await tester.ensureVisible(find.text('Continue the research'));
+ expect(
+ find.text('Continue the research').hitTestable(),
+ findsOneWidget,
+ );
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('new-harness-field-project')),
+ );
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-field-project')),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('new-harness-chooser-surface')),
+ findsOneWidget,
+ );
+ await tester.tapAt(Offset(2, size.height / 2));
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('new-harness-chooser-surface')),
+ findsNothing,
+ );
+ expect(connection.starts, isEmpty);
+ if (scale == 1) {
+ app.machineStates['m']!.agents = [];
+ await tester.pumpWidget(const SizedBox());
+ await tester.pumpWidget(preview);
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('welcome-sessions')), findsNothing);
+ expect(
+ find.byKey(const ValueKey('workspace-status-bar')),
+ findsNothing,
+ );
+ expect(tester.widget<TextField>(task).focusNode!.hasFocus, isTrue);
+ await capture(tester, 'welcome-empty-${brightness.name}');
+ }
+ });
+ }
+ }
+
+ testWidgets(
+ 'native footer stays hidden on an empty tab and returns with work',
+ (tester) async {
+ await setup(tester, mac: true);
+ expect(updates.last['footerCovered'], isTrue);
+ expect(find.byKey(const ValueKey('workspace-status-bar')), findsNothing);
+ app.adoptSessionForTest(terminal('a0', []));
+ app.notifyListeners();
+ await tester.pumpAndSettle();
+ expect(updates.last['footerCovered'], isFalse);
+ expect(
+ find.byKey(const ValueKey('workspace-status-bar')),
+ findsOneWidget,
+ );
+ },
+ );
+
+ testWidgets(
+ 'recent context keeps customized fields and wording in one neutral ink',
+ (tester) async {
+ await setup(tester, withPane: true);
+ final prefs = appearancePrefsStore.value;
+ addTearDown(() => appearancePrefsStore.value = prefs);
+ app.newSwarm();
+ await tester.pumpAndSettle();
+ appearancePrefsStore.value = prefs.copyWith(
+ prompt: const PromptPrefs(statusStyle: StatusLineStyle.spaceship),
+ );
+ await tester.pumpAndSettle();
+ final recent = find.byKey(const ValueKey('welcome-sessions'));
+ final line = find.descendant(
+ of: recent,
+ matching: find.byType(StatusLine),
+ );
+ expect(line, findsOneWidget);
+ expect(
+ tester.widget<StatusLine>(line).parts.text,
+ 'M2 in openharness on feature/login-redirect',
+ );
+ for (final style in StatusLineStyle.values) {
+ appearancePrefsStore.value = prefs.copyWith(
+ prompt: PromptPrefs(statusStyle: style, color: true),
+ );
+ await tester.pumpAndSettle();
+ final paragraph = tester.renderObject<RenderParagraph>(
+ find.descendant(of: line, matching: find.byType(RichText)),
+ );
+ expect(paragraph.text.toPlainText(), contains('openharness'));
+ paragraph.text.visitChildren((span) {
+ if (span is TextSpan && (span.text?.isNotEmpty ?? false)) {
+ expect(span.style?.color, DesktopChrome.muted);
+ expect(span.style?.backgroundColor, isNull);
+ }
+ return true;
+ });
+ expect(tester.takeException(), isNull);
+ }
+ appearancePrefsStore.value = prefs.copyWith(
+ prompt: const PromptPrefs(
+ statusStyle: StatusLineStyle.pastelPowerline,
+ color: false,
+ machine: false,
+ branch: false,
+ ),
+ );
+ await tester.pumpAndSettle();
+ final configured = tester.widget<StatusLine>(line);
+ expect(configured.parts.style, StatusLineStyle.pastelPowerline);
+ expect(configured.color, isFalse);
+ expect(configured.parts.text, 'openharness');
+ expect(connection.starts, isEmpty);
+ },
+ );
+
+ testWidgets('native footer is covered for popup and restored on close', (
+ tester,
+ ) async {
+ await setup(tester, withPane: true, mac: true);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ await tester.pumpAndSettle();
+ expect(tester.widget<NewHarnessForm>(form).embedded, isFalse);
+ final creationVeil = tester
+ .widget<ColoredBox>(
+ find.descendant(
+ of: find.byType(DesktopDialogBackdrop),
+ matching: find.byType(ColoredBox),
+ ),
+ )
+ .color;
+ expect(creationVeil, grid.AppDesktop.darkVeil);
+ expect(updates.last['footerCovered'], isTrue);
+ await tester.tap(find.byKey(const ValueKey('new-harness-close')));
+ await tester.pumpAndSettle();
+ expect(updates.last['footerCovered'], isFalse);
+ expect(form, findsNothing);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.pumpAndSettle();
+ expect(updates.last['footerCovered'], isTrue);
+ expect(
+ tester
+ .widget<ColoredBox>(
+ find.descendant(
+ of: find.byType(DesktopDialogBackdrop),
+ matching: find.byType(ColoredBox),
+ ),
+ )
+ .color,
+ creationVeil,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(updates.last['footerCovered'], isFalse);
+ });
+
+ testWidgets('customization previews a passive footer only while current', (
+ tester,
+ ) async {
+ await setup(tester, withPane: true, mac: true);
+ final opening = native(tester, 'customize');
+ await tester.pumpAndSettle();
+ expect(find.byType(HarnessCustomizePane), findsOneWidget);
+ expect(updates.last['footerCovered'], isFalse);
+ expect(updates.last['footerPassive'], isTrue);
+ expect(updates.last['enabled'], isFalse);
+
+ unawaited(
+ showAppDialog<void>(
+ context: tester.element(find.byType(HarnessCustomizePane)),
+ builder: (context) => AlertDialog(
+ title: const Text('Nested task'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close nested task'),
+ ),
+ ],
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(updates.last['footerCovered'], isTrue);
+ expect(updates.last['footerPassive'], isFalse);
+ expect(updates.last['enabled'], isFalse);
+ await tester.tap(find.text('Close nested task'));
+ await tester.pumpAndSettle();
+ expect(updates.last['footerCovered'], isFalse);
+ expect(updates.last['footerPassive'], isTrue);
+
+ await tester.tap(find.byKey(const ValueKey('harness-customize-close')));
+ await tester.pumpAndSettle();
+ await opening;
+ expect(updates.last['footerCovered'], isFalse);
+ expect(updates.last['footerPassive'], isFalse);
+ expect(updates.last['enabled'], isTrue);
+ expect(connection.starts, isEmpty);
+ });
+}
diff --git a/desktop/test/desktop_workspace_tab_test.dart b/desktop/test/desktop_workspace_tab_test.dart
new file mode 100644
index 000000000..da157f3ac
--- /dev/null
+++ b/desktop/test/desktop_workspace_tab_test.dart
@@ -0,0 +1,346 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/desktop_workspace_tab.dart';
+
+import 'support/real_fonts.dart';
+
+typedef _Tab = ({String name, String? hint, bool working});
+
+const _eightTabs = <_Tab>[
+ (name: 'New Tab', hint: '⌘1', working: false),
+ (name: 'Desktop', hint: '⌘2', working: true),
+ (name: 'Docs', hint: '⌘3', working: false),
+ (name: 'Web', hint: '⌘4', working: false),
+ (name: 'Notes', hint: '⌘5', working: false),
+ (name: 'API', hint: '⌘6', working: false),
+ (name: 'Tests', hint: '⌘7', working: false),
+ (name: 'Release', hint: '⌘8', working: false),
+];
+
+Widget _host(
+ ValueNotifier<bool> hints, {
+ List<_Tab> tabs = _eightTabs,
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ GlobalKey? boundary,
+ VoidCallback? onSelect,
+ VoidCallback? onClose,
+ VoidCallback? onRename,
+ bool enabled = true,
+}) => RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ themeAnimationDuration: Duration.zero,
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Align(
+ alignment: Alignment.topLeft,
+ child: ColoredBox(
+ color: grid.AppPalette.swarmTabBar,
+ child: SizedBox(
+ height: scale == 1 ? 40 : 54,
+ child: Row(
+ children: [
+ const SizedBox(width: 8),
+ Expanded(
+ child: SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ child: Row(
+ children: [
+ for (final tab in tabs)
+ Builder(
+ builder: (context) => SizedBox(
+ width: DesktopWorkspaceTab.widthOf(
+ context,
+ tab.name,
+ shortcutHint: tab.hint,
+ hasActivity: tab.working,
+ ),
+ child: DesktopWorkspaceTab(
+ id: tab.name,
+ label: tab.name,
+ selected: tab.name == 'Desktop',
+ shortcutHint: tab.hint,
+ showShortcuts: hints,
+ onSelect: enabled ? (onSelect ?? () {}) : null,
+ onClose: enabled ? (onClose ?? () {}) : null,
+ onRename: onRename,
+ activityLabel: tab.working ? 'Working' : null,
+ activity: tab.working
+ ? SizedBox(
+ key: ValueKey('status:${tab.name}'),
+ width: 16,
+ child: Text(
+ '⠋',
+ textAlign: TextAlign.center,
+ textScaler: TextScaler.noScaling,
+ style:
+ grid.AppType.mono(
+ color: const Color(0xff64d2ff),
+ ).copyWith(
+ fontFamilyFallback: const [
+ 'Apple Symbols',
+ ],
+ ),
+ ),
+ )
+ : null,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(width: 152),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+);
+
+Future<void> _capture(
+ WidgetTester tester,
+ GlobalKey boundary,
+ String name,
+) async {
+ final directory = Platform.environment['HARNESS_WORKSPACE_TAB_CAPTURE_DIR'];
+ if (directory == null) return;
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage();
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+}
+
+Finder _label(String name) => find.byKey(ValueKey('tab-label:$name'));
+Finder _hint(String name) => find.byKey(ValueKey('tab-shortcut:$name'));
+Finder _close(String name) => find.byKey(ValueKey('tab-close:$name'));
+Finder _tab(String name) => find.byWidgetPredicate(
+ (widget) => widget is DesktopWorkspaceTab && widget.id == name,
+);
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ if (Platform.isMacOS) {
+ final sans = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in [grid.AppType.sansFamily, 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sans))).load();
+ }
+ await (FontLoader('Apple Symbols')..addFont(
+ Future.value(
+ ByteData.sublistView(
+ await File('/System/Library/Fonts/Apple Symbols.ttf')
+ .readAsBytes(),
+ ),
+ ),
+ ))
+ .load();
+ }
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
+ });
+
+ tearDown(() => grid.AppTheme.brightness.value = Brightness.dark);
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets('centered ${brightness.name} tabs at $scale text scale', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 100);
+ addTearDown(tester.view.reset);
+ grid.AppTheme.brightness.value = brightness;
+ final hints = ValueNotifier(false);
+ addTearDown(hints.dispose);
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ _host(
+ hints,
+ brightness: brightness,
+ scale: scale,
+ boundary: boundary,
+ ),
+ );
+ expect(tester.takeException(), isNull);
+ if (scale == 1) {
+ final scroll = tester.state<ScrollableState>(find.byType(Scrollable));
+ expect(scroll.position.maxScrollExtent, 0);
+ }
+ expect(
+ tester.getCenter(_label('New Tab')).dx,
+ closeTo(tester.getCenter(_tab('New Tab')).dx, .01),
+ );
+ final title = tester.getRect(_label('Desktop'));
+ final tabBounds = tester.getRect(_tab('Desktop'));
+ final mark = find.byKey(const ValueKey('status:Desktop'));
+ expect(mark, findsOneWidget);
+ expect(_close('Desktop').hitTestable(), findsNothing);
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: const Offset(1260, 90));
+ await tester.pump();
+ await _capture(tester, boundary, 'tabs-${brightness.name}-$scale-rest');
+ await mouse.moveTo(title.center);
+ await tester.pumpAndSettle();
+ expect(_close('Desktop').hitTestable(), findsOneWidget);
+ expect(tester.getRect(_label('Desktop')), title);
+ final icon = tester.widget<Icon>(
+ find.descendant(of: _close('Desktop'), matching: find.byType(Icon)),
+ );
+ expect(icon.icon, AppIcons.close);
+ expect(icon.size, 12);
+ expect(tester.getSize(_close('Desktop')), const Size(32, 32));
+ await _capture(
+ tester,
+ boundary,
+ 'tabs-${brightness.name}-$scale-hover',
+ );
+ hints.value = true;
+ await tester.pump();
+ expect(mark, findsNothing);
+ expect(_hint('Desktop'), findsOneWidget);
+ expect(_close('Desktop').hitTestable(), findsOneWidget);
+ expect(tester.getRect(_label('Desktop')), title);
+ expect(tester.getRect(_tab('Desktop')), tabBounds);
+ final shortcut = tester.getRect(_hint('Desktop'));
+ expect(shortcut.left - title.right, closeTo(6, .5));
+ expect(
+ shortcut.right,
+ lessThanOrEqualTo(tester.getRect(_close('Desktop')).left),
+ );
+ expect(
+ (title.left + shortcut.right) / 2,
+ closeTo(tabBounds.center.dx, .5),
+ );
+ await _capture(
+ tester,
+ boundary,
+ 'tabs-${brightness.name}-$scale-command',
+ );
+ await mouse.removePointer();
+ hints.value = false;
+ await tester.pump();
+ expect(mark, findsOneWidget);
+ expect(tester.getRect(_label('Desktop')), title);
+ expect(_close('Desktop').hitTestable(), findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+ }
+ }
+
+ testWidgets(
+ 'resolved remaps replace status and preserve purposeful actions',
+ (tester) async {
+ final semantics = tester.ensureSemantics();
+ final hints = ValueNotifier(false);
+ var selections = 0, closes = 0, renames = 0;
+ try {
+ await tester.pumpWidget(
+ _host(
+ hints,
+ tabs: const [(name: 'Desktop', hint: '⌃⌥⌘R', working: true)],
+ onSelect: () => selections++,
+ onClose: () => closes++,
+ onRename: () => renames++,
+ ),
+ );
+ final title = tester.getRect(_label('Desktop'));
+ final status = find.bySemanticsLabel('Desktop, Working');
+ expect(status, findsOneWidget);
+ expect(
+ tester
+ .getSemantics(status)
+ .getSemanticsData()
+ .flagsCollection
+ .isButton,
+ isTrue,
+ );
+ hints.value = true;
+ await tester.pump();
+ expect(find.text('⌃⌥⌘R'), findsOneWidget);
+ expect(find.text('⌘1'), findsNothing);
+ expect(tester.getRect(_label('Desktop')), title);
+ expect(status, findsOneWidget);
+ Focus.of(tester.element(_label('Desktop'))).requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ expect(selections, 1);
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: title.center);
+ await tester.pump();
+ await tester.tap(_close('Desktop'));
+ await tester.pump();
+ expect(closes, 1);
+ expect(selections, 1);
+ await tester.tap(_label('Desktop'));
+ await tester.pump(const Duration(milliseconds: 80));
+ await tester.tap(_label('Desktop'));
+ await tester.pumpAndSettle();
+ expect(renames, 1);
+ await mouse.removePointer();
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ semantics.dispose();
+ hints.dispose();
+ }
+ },
+ );
+
+ testWidgets('unbound and disabled tabs advertise no shortcut', (
+ tester,
+ ) async {
+ final hints = ValueNotifier(true);
+ addTearDown(hints.dispose);
+ await tester.pumpWidget(
+ _host(hints, tabs: const [(name: 'Notes', hint: null, working: true)]),
+ );
+ expect(_hint('Notes'), findsNothing);
+ expect(find.byKey(const ValueKey('status:Notes')), findsOneWidget);
+ await tester.pumpWidget(
+ _host(
+ hints,
+ tabs: const [(name: 'Notes', hint: '⌘2', working: true)],
+ enabled: false,
+ ),
+ );
+ expect(_hint('Notes'), findsNothing);
+ expect(find.byKey(const ValueKey('status:Notes')), findsOneWidget);
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: tester.getCenter(_label('Notes')));
+ await tester.pump();
+ expect(_close('Notes').hitTestable(), findsNothing);
+ await mouse.removePointer();
+ });
+}
diff --git a/desktop/test/dsh_install_panel_test.dart b/desktop/test/dsh_install_panel_test.dart
index ba71b3abd..4119e0f9f 100644
--- a/desktop/test/dsh_install_panel_test.dart
+++ b/desktop/test/dsh_install_panel_test.dart
@@ -2,6 +2,8 @@
// three steps with the line each is on, the tail of the log, how long each step
// took, and — when it fails — the machine's own `miss` line as a sentence with
// the command that fixes it.
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/dsh_catalog.dart';
@@ -71,8 +73,8 @@ _Mark _markOf(WidgetTester tester, String name) {
.widgetList<Icon>(find.descendant(of: row, matching: find.byType(Icon)))
.map((i) => i.icon)
.toList();
- if (icons.contains(Icons.check)) return _Mark.done;
- if (icons.contains(Icons.priority_high)) return _Mark.failed;
+ if (icons.contains(AppIcons.check)) return _Mark.done;
+ if (icons.contains(AppIcons.circleAlert)) return _Mark.failed;
return _Mark.pending;
}
diff --git a/desktop/test/entry_surfaces_render_test.dart b/desktop/test/entry_surfaces_render_test.dart
index 6a26f4da4..a4c426751 100644
--- a/desktop/test/entry_surfaces_render_test.dart
+++ b/desktop/test/entry_surfaces_render_test.dart
@@ -66,9 +66,9 @@ void main() {
rootBundle.load('packages/lucide_icons_flutter/assets/lucide.ttf'),
))
.load();
- await (FontLoader('packages/lucide_icons_flutter/Lucide300')..addFont(
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
rootBundle.load(
- 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w300.ttf',
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
),
))
.load();
diff --git a/desktop/test/environment_preflight_screen_test.dart b/desktop/test/environment_preflight_screen_test.dart
index 40ca647b3..c6d18de25 100644
--- a/desktop/test/environment_preflight_screen_test.dart
+++ b/desktop/test/environment_preflight_screen_test.dart
@@ -1,19 +1,31 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/bootstrap/environment_provisioner.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/widgets/environment_preflight_screen.dart';
-import 'package:harness/widgets/terminal_progress.dart';
-Widget host(EnvironmentReadiness readiness, {bool reduceMotion = false}) =>
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- builder: (context, child) => MediaQuery(
- data: MediaQuery.of(context).copyWith(disableAnimations: reduceMotion),
- child: child!,
+Widget host(
+ EnvironmentReadiness readiness, {
+ bool reduceMotion = false,
+ Brightness brightness = Brightness.dark,
+ double textScale = 1,
+}) {
+ grid.AppTheme.brightness.value = brightness;
+ return MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ disableAnimations: reduceMotion,
+ textScaler: TextScaler.linear(textScale),
),
- home: EnvironmentPreflightScreen(readiness: readiness),
- );
+ child: child!,
+ ),
+ home: grid.BrightnessScope(
+ child: EnvironmentPreflightScreen(readiness: readiness),
+ ),
+ );
+}
void main() {
testWidgets('the initial computer check respects Reduce Motion', (
@@ -24,7 +36,8 @@ void main() {
);
await tester.pump(const Duration(milliseconds: 300));
expect(find.byType(CircularProgressIndicator), findsNothing);
- expect(find.byType(TerminalProgressLine), findsOneWidget);
+ expect(find.byType(LinearProgressIndicator), findsOneWidget);
+ expect(find.text('0 of 3 checks finished'), findsOneWidget);
expect(tester.binding.hasScheduledFrame, isFalse);
});
@@ -46,7 +59,8 @@ void main() {
.isLiveRegion,
isTrue,
);
- expect(find.text(r'$ harness doctor'), findsOneWidget);
+ expect(find.text('Checking this computer'), findsOneWidget);
+ expect(find.bySemanticsLabel('Harness CLI\nWaiting'), findsOneWidget);
await tester.pumpWidget(
host(
EnvironmentReadiness(
@@ -61,15 +75,10 @@ void main() {
);
await tester.pump();
expect(
- find.text('all checks passed · opening your workspace'),
+ find.text('All checks passed. Opening your workspace…'),
findsOneWidget,
);
- // The prompt line is the same in both states; what changes is the line
- // under the bar.
- expect(
- find.text('read-only: nothing is installed by this check'),
- findsNothing,
- );
+ expect(find.text("This check doesn't install anything."), findsNothing);
expect(
tester
.getSemantics(status)
@@ -82,4 +91,112 @@ void main() {
semantics.dispose();
}
});
+
+ testWidgets('finished checks include failures without claiming readiness', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ host(
+ const EnvironmentReadiness(
+ steps: {
+ EnvironmentStep.clipboard: EnvironmentStepStatus.notApplicable,
+ EnvironmentStep.harness: EnvironmentStepStatus.failed,
+ EnvironmentStep.tmux: EnvironmentStepStatus.running,
+ },
+ ),
+ ),
+ );
+ expect(find.text('Not needed'), findsOneWidget);
+ expect(find.text('Check failed'), findsOneWidget);
+ expect(find.text('Checking…'), findsOneWidget);
+ expect(find.text('2 of 3 checks finished'), findsOneWidget);
+ expect(
+ tester
+ .widget<LinearProgressIndicator>(find.byType(LinearProgressIndicator))
+ .value,
+ 2 / 3,
+ );
+ expect(find.text('Your computer is ready'), findsNothing);
+
+ await tester.pumpWidget(
+ host(
+ EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ ),
+ ),
+ );
+ expect(find.text('3 of 3 checks finished'), findsOneWidget);
+ expect(
+ find.text('Your computer is ready'),
+ findsNothing,
+ reason: 'the provisioner must publish its final ready phase',
+ );
+ });
+
+ testWidgets('unknown progress stays unnumbered and respects Reduce Motion', (
+ tester,
+ ) async {
+ await tester.pumpWidget(host(const EnvironmentReadiness(steps: {})));
+ expect(
+ tester
+ .widget<LinearProgressIndicator>(find.byType(LinearProgressIndicator))
+ .value,
+ isNull,
+ );
+ await tester.pumpWidget(
+ host(const EnvironmentReadiness(steps: {}), reduceMotion: true),
+ );
+ await tester.pumpAndSettle(
+ const Duration(milliseconds: 50),
+ EnginePhase.sendSemanticsUpdate,
+ const Duration(seconds: 1),
+ );
+ expect(find.byIcon(AppIcons.hourglass), findsOneWidget);
+ expect(find.text('Waiting for checks…'), findsOneWidget);
+ expect(find.byType(LinearProgressIndicator), findsNothing);
+ expect(tester.binding.hasScheduledFrame, isFalse);
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'readiness fits a narrow ${brightness.name} window with large text',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(360, 360);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ host(
+ const EnvironmentReadiness(
+ steps: {
+ EnvironmentStep.clipboard: EnvironmentStepStatus.notApplicable,
+ EnvironmentStep.harness: EnvironmentStepStatus.unavailable,
+ EnvironmentStep.tmux: EnvironmentStepStatus.needsTerminal,
+ },
+ ),
+ brightness: brightness,
+ textScale: 1.6,
+ reduceMotion: true,
+ ),
+ );
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ expect(find.text('Unavailable'), findsOneWidget);
+ expect(find.text('Needs Terminal'), findsOneWidget);
+ await tester.ensureVisible(
+ find.text("This check doesn't install anything."),
+ );
+ expect(
+ find.text("This check doesn't install anything.").hitTestable(),
+ findsOneWidget,
+ );
+ expect(
+ tester.widget<Text>(find.text('Harness CLI')).style?.fontFamily,
+ grid.AppType.sansFamily,
+ );
+ },
+ );
+ }
}
diff --git a/desktop/test/environment_setup_screen_test.dart b/desktop/test/environment_setup_screen_test.dart
index 5c083362c..23788d1d5 100644
--- a/desktop/test/environment_setup_screen_test.dart
+++ b/desktop/test/environment_setup_screen_test.dart
@@ -8,6 +8,7 @@ import 'package:harness/auth/cli_login.dart';
import 'package:harness/bootstrap/environment_provisioner.dart';
import 'package:harness/core/config.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/color_palette.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/widgets/environment_setup_screen.dart';
@@ -68,6 +69,7 @@ Future<void> _mount(
WidgetTester tester,
AppNotifier app, {
double textScale = 1,
+ Brightness brightness = Brightness.dark,
}) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(880, 560);
@@ -75,7 +77,7 @@ Future<void> _mount(
await tester.pumpWidget(
MaterialApp(
theme: grid
- .buildAppTheme(brightness: Brightness.dark)
+ .buildAppTheme(brightness: brightness)
.copyWith(platform: TargetPlatform.macOS),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context).copyWith(
@@ -106,7 +108,108 @@ AppNotifier _app(SetupProvisioner provisioner) =>
..status = AppStatus.preparingEnvironment
..environmentReadiness = setupReview;
+void _expectReadableText(WidgetTester tester, Finder finder) {
+ final text = tester.widget<Text>(finder);
+ final foreground = text.style!.color!;
+ Color? background;
+ tester.element(finder).visitAncestorElements((element) {
+ final widget = element.widget;
+ if (widget case DecoratedBox(
+ decoration: BoxDecoration(color: final color?),
+ )) {
+ background = color;
+ return false;
+ }
+ return true;
+ });
+ expect(
+ background,
+ isNotNull,
+ reason: 'Measure against the painted setup surface.',
+ );
+ final fg = foreground.computeLuminance();
+ final bg = background!.computeLuminance();
+ final ratio = fg > bg ? (fg + .05) / (bg + .05) : (bg + .05) / (fg + .05);
+ expect(
+ ratio,
+ greaterThanOrEqualTo(4.5),
+ reason: '${text.data} must remain readable.',
+ );
+}
+
void main() {
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'setup details and recovery text have readable contrast in ${brightness.name}',
+ (tester) async {
+ final previousBrightness = grid.AppTheme.brightness.value;
+ final previousPalette = grid.AppTheme.palette.value;
+ addTearDown(() {
+ grid.AppTheme.brightness.value = previousBrightness;
+ grid.AppTheme.palette.value = previousPalette;
+ });
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method == 'Clipboard.setData') {
+ throw PlatformException(code: 'clipboard_unavailable');
+ }
+ return null;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ null,
+ ),
+ );
+ for (final palette in HarnessPalette.values) {
+ grid.AppTheme.brightness.value = brightness;
+ grid.AppTheme.palette.value = palette;
+ final provisioner = SetupProvisioner();
+ final app = _app(provisioner);
+ try {
+ await _mount(tester, app, brightness: brightness);
+ for (final item in setupReview.plan) {
+ _expectReadableText(tester, find.text(item.detail));
+ }
+ app.environmentReadiness = setupReview.copyWith(
+ phase: EnvironmentSetupPhase.failed,
+ output: const ['Synthetic setup diagnostic'],
+ );
+ app.notifyListeners();
+ await tester.pump();
+ _expectReadableText(
+ tester,
+ find.textContaining('Required for every harness'),
+ );
+ _expectReadableText(
+ tester,
+ find.text('~/.harness/runtime · harness version'),
+ );
+ for (var i = 0; i < find.text('Missing').evaluate().length; i++) {
+ _expectReadableText(tester, find.text('Missing').at(i));
+ }
+ await tester.ensureVisible(find.text('Copy diagnostics'));
+ await tester.tap(find.text('Copy diagnostics'));
+ await tester.pump();
+ final error = find.text(
+ 'Could not copy. Select the text to copy it, or try again.',
+ );
+ expect(error.hitTestable(), findsOneWidget);
+ _expectReadableText(tester, error);
+ expect(find.text('Retry').hitTestable(), findsOneWidget);
+ expect(provisioner.attempts, isEmpty);
+ expect(tester.takeException(), isNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ }
+ }
+ },
+ );
+ }
+
testWidgets('Retry after a launch check failure only checks the computer', (
tester,
) async {
diff --git a/desktop/test/export_logs_dialog_test.dart b/desktop/test/export_logs_dialog_test.dart
new file mode 100644
index 000000000..535279bde
--- /dev/null
+++ b/desktop/test/export_logs_dialog_test.dart
@@ -0,0 +1,245 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/logging/log_export.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/desktop_prompt_surface.dart';
+import 'package:harness/widgets/export_logs_dialog.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/real_fonts.dart';
+
+const _error =
+ 'Could not create the log archive.\nThe destination folder is not writable:\n'
+ '/Users/review/Library/Application Support/Harness/Diagnostic Reports\n'
+ 'Choose a writable destination, check available disk space, and try again.';
+const _missingPath =
+ '/private/tmp/does-not-exist-harness-review/harness-logs-2026-09-29T16-18-43-924Z.zip';
+
+void main() {
+ final output = Platform.environment['SECONDARY_DIALOG_RENDER_DIR'];
+ setUpAll(() async {
+ await loadRealFonts();
+ if (output != null) await loadPreviewFonts();
+ });
+
+ Future<GlobalKey> open(
+ WidgetTester tester, {
+ required Future<LogExportResult> Function() export,
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ }) async {
+ tester.view.physicalSize = const Size(880, 560);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final picture = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: picture,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showExportLogsDialog(context, export: export),
+ child: const Text('Export fixture'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Export fixture'));
+ await tester.pump();
+ return picture;
+ }
+
+ Future<void> capture(
+ WidgetTester tester,
+ GlobalKey picture,
+ String name,
+ ) async {
+ if (output == null) return;
+ final previous = debugDisableShadows;
+ debugDisableShadows = false;
+ try {
+ for (final render in tester.allRenderObjects) {
+ render.markNeedsPaint();
+ }
+ await tester.pump();
+ await tester.runAsync(() async {
+ final image =
+ await (picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(output).create(recursive: true);
+ await File('$output/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ } finally {
+ debugDisableShadows = previous;
+ }
+ }
+
+ testWidgets('pending export runs once and keeps its existing close guard', (
+ tester,
+ ) async {
+ final pending = Completer<LogExportResult>();
+ var calls = 0;
+ final picture = await open(
+ tester,
+ export: () {
+ calls++;
+ return pending.future;
+ },
+ );
+ expect(find.text('Exporting logs…'), findsOneWidget);
+ expect(find.textContaining('Secrets are stripped first.'), findsOneWidget);
+ expect(find.text('Close'), findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.tapAt(const Offset(10, 10));
+ await tester.pump();
+ expect(calls, 1);
+ expect(find.byType(DesktopPromptSurface), findsOneWidget);
+ await capture(tester, picture, 'export-pending');
+ pending.complete(const LogExportResult(error: 'The CLI did not answer.'));
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(DesktopPromptSurface), findsNothing);
+ expect(calls, 1);
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets(
+ 'export failure keeps Close visible ${brightness.name} $scale',
+ (tester) async {
+ final picture = await open(
+ tester,
+ export: () async => const LogExportResult(error: _error),
+ brightness: brightness,
+ scale: scale,
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ expect(
+ tester.widget<SelectableText>(find.byType(SelectableText)).data,
+ _error,
+ );
+ final close = find.widgetWithText(FilledButton, 'Close');
+ expect(close.hitTestable(), findsOneWidget);
+ final before = tester.getRect(close);
+ expect(before.bottom, lessThanOrEqualTo(540));
+ final scrollbar = tester.widget<Scrollbar>(
+ find
+ .descendant(
+ of: find.byType(DesktopPromptScrollBody),
+ matching: find.byType(Scrollbar),
+ )
+ .first,
+ );
+ expect(scrollbar.thumbVisibility, isTrue);
+ await capture(
+ tester,
+ picture,
+ 'export-error-${brightness.name}-$scale',
+ );
+ if (scale == 2) {
+ expect(
+ scrollbar.controller!.position.maxScrollExtent,
+ greaterThan(0),
+ );
+ await tester.drag(
+ find.byType(DesktopPromptScrollBody),
+ const Offset(0, -260),
+ );
+ await tester.pumpAndSettle();
+ expect(scrollbar.controller!.offset, greaterThan(0));
+ expect(tester.getRect(close), before);
+ await capture(
+ tester,
+ picture,
+ 'export-error-${brightness.name}-$scale-scrolled',
+ );
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(DesktopPromptSurface), findsNothing);
+ },
+ );
+
+ testWidgets(
+ 'export success actions grow and traverse ${brightness.name} $scale',
+ (tester) async {
+ expect(
+ File(_missingPath).existsSync(),
+ isFalse,
+ reason: 'Never reveal a real file from this fixture.',
+ );
+ final picture = await open(
+ tester,
+ export: () async => const LogExportResult(path: _missingPath),
+ brightness: brightness,
+ scale: scale,
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Logs exported'), findsOneWidget);
+ expect(
+ find.textContaining('It holds no credentials.'),
+ findsOneWidget,
+ );
+ final close = find.widgetWithText(FilledButton, 'Close');
+ final reveal = find.widgetWithText(TextButton, 'Show in Finder');
+ for (final (button, text) in [
+ (close, 'Close'),
+ (reveal, 'Show in Finder'),
+ ]) {
+ expect(button.hitTestable(), findsOneWidget);
+ final label = tester.getRect(find.text(text));
+ final bounds = tester.getRect(button);
+ expect(label.top - bounds.top, greaterThanOrEqualTo(6));
+ expect(bounds.bottom - label.bottom, greaterThanOrEqualTo(6));
+ }
+ await capture(
+ tester,
+ picture,
+ 'export-success-${brightness.name}-$scale',
+ );
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.pump();
+ expect(
+ Focus.of(tester.element(find.text('Show in Finder'))).hasFocus,
+ isTrue,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(Focus.of(tester.element(find.text('Close'))).hasFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(DesktopPromptSurface), findsNothing);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+ }
+}
diff --git a/desktop/test/fixtures/status_bar_before_daemons.json b/desktop/test/fixtures/status_bar_before_daemons.json
index f00f3cae8..f6b07f44d 100644
--- a/desktop/test/fixtures/status_bar_before_daemons.json
+++ b/desktop/test/fixtures/status_bar_before_daemons.json
@@ -15,31 +15,31 @@
[
13.0,
0.0,
- 78.0,
+ 104.0,
40.0
],
[
- 90.0,
+ 117.0,
6.0,
39.0,
28.0
],
[
- 142.0,
+ 169.0,
6.0,
52.0,
28.0
],
[
- 194.0,
+ 221.0,
6.0,
52.0,
28.0
],
[
- 246.0,
+ 273.0,
6.0,
- 221.0,
+ 194.0,
28.0
],
[
@@ -87,19 +87,13 @@
37.5
],
[
- -39.0,
+ -13.0,
0.0,
130.0,
40.0
],
[
- 91.0,
- 0.0,
- 130.0,
- 40.0
- ],
- [
- 221.0,
+ 117.0,
0.0,
130.0,
40.0
diff --git a/desktop/test/fork_keyboard_test.dart b/desktop/test/fork_keyboard_test.dart
index 707d8c353..e918f82b1 100644
--- a/desktop/test/fork_keyboard_test.dart
+++ b/desktop/test/fork_keyboard_test.dart
@@ -149,7 +149,7 @@ void main() {
const WsRequestTimeout('agent_fork'),
);
await tester.pumpAndSettle();
- expect(find.text('enter check status'), findsOneWidget);
+ expect(find.text('Check status'), findsOneWidget);
expect(field(tester, _task).readOnly, isTrue);
await key(tester, LogicalKeyboardKey.escape);
await open(tester);
@@ -235,7 +235,7 @@ void main() {
'''{"bindings":[{"keys":"f4","command":"picker.cancel","when":"picker"}]}''',
);
await tester.pump();
- expect(find.text('F4 close'), findsOneWidget);
+ expect(find.byTooltip('Close · F4'), findsOneWidget);
await key(tester, LogicalKeyboardKey.f4);
await tester.pumpAndSettle();
expect(_task, findsNothing);
@@ -281,13 +281,13 @@ void main() {
await mount(tester, size: const Size(480, 360), scale: 1.7);
await open(tester);
expect(field(tester, _task).focusNode!.hasPrimaryFocus, isTrue);
- expect(find.text('esc close').hitTestable(), findsOneWidget);
+ expect(find.text('Cancel').hitTestable(), findsOneWidget);
await key(tester, LogicalKeyboardKey.enter);
connection.forkReplies.single.completeError(
const WsRequestTimeout('agent_fork'),
);
await tester.pumpAndSettle();
- expect(find.text('esc close').hitTestable(), findsOneWidget);
+ expect(find.text('Close').hitTestable(), findsOneWidget);
expect(find.text('Fork may already exist.').hitTestable(), findsOneWidget);
expect(tester.takeException(), isNull);
await key(tester, LogicalKeyboardKey.escape);
diff --git a/desktop/test/friendly_desktop_test.dart b/desktop/test/friendly_desktop_test.dart
new file mode 100644
index 000000000..1d30fccc0
--- /dev/null
+++ b/desktop/test/friendly_desktop_test.dart
@@ -0,0 +1,403 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/widgets/desktop_search_panel.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'support/mixed_agents.dart';
+import 'swarm_state_test.dart' show createApp;
+
+class _Daemon extends WsConn {
+ _Daemon()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final requests = <(String, Map<String, dynamic>)>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ requests.add((type, payload));
+ if (type == 'engines_probe') {
+ return {
+ 'engines': [
+ {'engine': 'codex', 'installed': true},
+ {'engine': 'claude', 'installed': true},
+ ],
+ };
+ }
+ if (type == 'git_project_info') {
+ return {
+ 'isGit': true,
+ 'branch': 'main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ {'ref': 'refs/heads/feature', 'name': 'feature'},
+ ],
+ };
+ }
+ if (type == 'fs_list_dir') return {'path': '/work', 'entries': []};
+ if (type == 'agent_create') {
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'failed',
+ 'error': 'Fixture stops at the launch boundary',
+ };
+ }
+ return {};
+ }
+}
+
+void main() {
+ final renderDir = Platform.environment['FRIENDLY_UI_RENDER_DIR'];
+ setUpAll(() async {
+ if (renderDir != null) await loadPreviewFonts();
+ });
+ final picture = GlobalKey();
+
+ AppNotifier fixture(_Daemon daemon) {
+ final app = createApp(connectionForTest: (_) => daemon);
+ seedMixedAgents(app);
+ app.machineStates['m']!.engines.replace(const [
+ EngineAvailability(engine: 'codex', installed: true),
+ EngineAvailability(engine: 'claude', installed: true),
+ ]);
+ addTearDown(app.dispose);
+ return app;
+ }
+
+ Future<void> host(
+ WidgetTester tester,
+ Widget child,
+ MemoryKeymap map, {
+ Size size = const Size(1200, 800),
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ }) async {
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: KeymapProvider(
+ keymap: map,
+ child: KeymapHost(
+ keymap: map,
+ enabled: () => true,
+ actions: const {},
+ child: RepaintBoundary(
+ key: picture,
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Padding(padding: const EdgeInsets.all(24), child: child),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> capture(WidgetTester tester, String name) async {
+ if (renderDir == null) return;
+ await tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ final directory = Directory(renderDir)..createSync(recursive: true);
+ await File('${directory.path}/$name.png')
+ .writeAsBytes(data!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ Future<(NewHarnessController, _Daemon, MemoryKeymap)> composer(
+ WidgetTester tester, {
+ Size size = const Size(1200, 800),
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ VoidCallback? close,
+ }) async {
+ final daemon = _Daemon();
+ final app = fixture(daemon);
+ final controller = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/openharness',
+ );
+ final map = MemoryKeymap();
+ addTearDown(controller.dispose);
+ addTearDown(map.dispose);
+ await host(
+ tester,
+ NewHarnessForm(
+ controller: controller,
+ desktop: true,
+ onClose: close ?? () {},
+ onCreated: () {},
+ ),
+ map,
+ size: size,
+ brightness: brightness,
+ scale: scale,
+ );
+ return (controller, daemon, map);
+ }
+
+ testWidgets('task survives project and agent choices without launching', (
+ tester,
+ ) async {
+ final (box, daemon, _) = await composer(tester);
+ const task =
+ 'Make keyboard navigation feel natural.\nKeep the terminal fast.';
+ final field = find.byKey(const ValueKey('new-harness-task'));
+ await tester.enterText(field, task);
+ await tester.pump();
+ await capture(tester, 'new-harness-dark');
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-project')));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('new-harness-query')),
+ 'robotics',
+ );
+ await tester.pumpAndSettle();
+ expect(box.task, task);
+ await capture(tester, 'new-harness-project-chooser');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(tester.widget<TextField>(field).controller!.text, task);
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-agent')));
+ await tester.pumpAndSettle();
+ await capture(tester, 'new-harness-agent-chooser');
+ await tester.tap(find.byKey(const ValueKey('new-harness-option-claude')));
+ await tester.pumpAndSettle();
+ expect(box.engine, 'claude');
+ expect(box.task, task);
+ expect(
+ daemon.requests.where((request) => request.$1 == 'agent_create'),
+ isEmpty,
+ );
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets(
+ 'Shift-Enter edits, remapped start submits once, IME never submits',
+ (tester) async {
+ final (box, daemon, map) = await composer(tester);
+ final field = find.byKey(const ValueKey('new-harness-task'));
+ await tester.enterText(field, 'Review the release');
+ await key(tester, LogicalKeyboardKey.enter, shift: true);
+ expect(
+ daemon.requests.where((request) => request.$1 == 'agent_create'),
+ isEmpty,
+ );
+ final editor = tester.widget<TextField>(field).controller!;
+ editor.value = const TextEditingValue(
+ text: '日本語',
+ composing: TextRange(start: 0, end: 3),
+ selection: TextSelection.collapsed(offset: 3),
+ );
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(
+ daemon.requests.where((request) => request.$1 == 'agent_create'),
+ isEmpty,
+ );
+ editor.value = const TextEditingValue(
+ text: 'Review the release',
+ selection: TextSelection.collapsed(offset: 18),
+ );
+ box.setTask(editor.text);
+ map.apply(
+ '{"bindings":[{"keys":"cmd+shift+enter","command":"picker.add_here","when":"picker"},{"keys":"cmd+enter","command":null,"when":"picker"}]}',
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(
+ daemon.requests.where((request) => request.$1 == 'agent_create'),
+ isEmpty,
+ );
+ expect(box.requiredChoice, isNull);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true, shift: true);
+ await tester.pumpAndSettle();
+ expect(
+ daemon.requests.where((request) => request.$1 == 'agent_create'),
+ hasLength(1),
+ );
+ },
+ );
+
+ testWidgets('default Cmd-Enter sends the task and selected configuration', (
+ tester,
+ ) async {
+ final (box, daemon, _) = await composer(tester);
+ await tester.enterText(
+ find.byKey(const ValueKey('new-harness-task')),
+ 'Review the release',
+ );
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await tester.pumpAndSettle();
+ final starts = daemon.requests.where(
+ (request) => request.$1 == 'agent_create',
+ );
+ expect(starts, hasLength(1));
+ expect(starts.single.$2['prompt'], 'Review the release');
+ expect(starts.single.$2['engine'], 'codex');
+ expect(box.busy, isFalse);
+ expect(box.task, 'Review the release');
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'composer and chooser fit narrow ${brightness.name} with enlarged text',
+ (tester) async {
+ final (box, _, _) = await composer(
+ tester,
+ size: const Size(470, 820),
+ brightness: brightness,
+ scale: 1.5,
+ );
+ const task =
+ 'A long project brief that stays editable when the window is narrow.';
+ await tester.enterText(
+ find.byKey(const ValueKey('new-harness-task')),
+ task,
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'new-harness-narrow-${brightness.name}');
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('new-harness-field-project')),
+ );
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-field-project')),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'new-harness-chooser-narrow-${brightness.name}');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.task, task);
+ },
+ );
+ }
+
+ testWidgets(
+ 'palette filters keep query, arrows select, Enter opens exactly once',
+ (tester) async {
+ final app = fixture(_Daemon());
+ final search = SwarmSearchController(
+ app,
+ [],
+ adding: true,
+ activityFirst: true,
+ selectOnEmptyQuery: false,
+ offersHarnessCreate: false,
+ );
+ final editing = TextEditingController();
+ final focus = FocusNode();
+ final map = MemoryKeymap();
+ final chosen = <SwarmSearchSelection>[];
+ void sync() {
+ if (editing.text != search.query) {
+ editing.value = TextEditingValue(
+ text: search.query,
+ selection: TextSelection.collapsed(offset: search.query.length),
+ );
+ }
+ }
+
+ search.addListener(sync);
+ addTearDown(search.dispose);
+ addTearDown(editing.dispose);
+ addTearDown(focus.dispose);
+ addTearDown(map.dispose);
+ await host(
+ tester,
+ Center(
+ child: SizedBox(
+ width: 960,
+ height: 570,
+ child: SwarmSearchKeys(
+ search: search,
+ editing: editing,
+ onChoose: chosen.add,
+ onClose: () {},
+ onRefocus: focus.requestFocus,
+ child: DesktopSearchPanel(
+ search: search,
+ editing: editing,
+ focusNode: focus,
+ onChoose: chosen.add,
+ onClose: () {},
+ onRefocus: focus.requestFocus,
+ previewBuilder: () => const Text('Resource details'),
+ ),
+ ),
+ ),
+ ),
+ map,
+ );
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ expect(search.showsTypeHints, isTrue);
+ expect(find.text('Resource details'), findsNothing);
+ await tester.enterText(input, 'login');
+ await tester.pumpAndSettle();
+ expect(find.text('Resource details'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('search-toggle-preview')));
+ await tester.pumpAndSettle();
+ expect(search.previewVisible, isFalse);
+ await capture(tester, 'command-palette-dark');
+ await tester.tap(find.byKey(const ValueKey('search-category-Projects')));
+ await tester.pumpAndSettle();
+ expect(search.isProjectMode, isTrue);
+ expect(editing.text, '# login');
+ expect(chosen, isEmpty);
+ await tester.tap(find.byKey(const ValueKey('search-category-Harnesses')));
+ await tester.pumpAndSettle();
+ expect(editing.text, 'login');
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(search.selected, isNotNull);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(chosen, hasLength(1));
+ // The pointer's tooltip exit delay is unrelated to search completion.
+ await tester.pump(const Duration(milliseconds: 350));
+ expect(tester.takeException(), isNull);
+ },
+ );
+}
diff --git a/desktop/test/grid_model_picker_test.dart b/desktop/test/grid_model_picker_test.dart
index 16c02cf73..7c8e308d5 100644
--- a/desktop/test/grid_model_picker_test.dart
+++ b/desktop/test/grid_model_picker_test.dart
@@ -2,10 +2,10 @@ import 'dart:async';
// The pane header's model picker: two sections, the way back always offered, and a marked row that
// says where the agent actually is.
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
-import 'package:harness/widgets/box_chrome.dart';
import 'package:harness/shared/theme/workspace_bar_style.dart';
import 'package:harness/widgets/transient_menus.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -347,8 +347,8 @@ void main() {
// The two sections this picker has, and NOT the API section the window's own Models menu
// carries — this control cannot put an agent on an API provider, so offering one would be a
// choice that goes nowhere.
- expect(find.text('SUBSCRIPTION'), findsOneWidget);
- expect(find.text('ON YOUR MACHINES'), findsOneWidget);
+ expect(find.text('Subscription'), findsOneWidget);
+ expect(find.text('On your machines'), findsOneWidget);
expect(find.text('API'), findsNothing);
// A picker that can only move an agent ONTO a grid is a one-way door, so the engine's own login
@@ -432,8 +432,10 @@ void main() {
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
- expect(find.text('SUBSCRIPTION'), findsOneWidget);
- final bounds = tester.getRect(find.byType(TerminalBox));
+ expect(find.text('Subscription'), findsOneWidget);
+ final bounds = tester.getRect(
+ find.byKey(const ValueKey('pane-menu-surface')),
+ );
expect(bounds.left, greaterThanOrEqualTo(8));
expect(bounds.right, lessThanOrEqualTo(372));
expect(bounds.bottom, lessThanOrEqualTo(292));
@@ -442,13 +444,13 @@ void main() {
// keyboard contract that survived the panel.
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(find.text('SUBSCRIPTION'), findsNothing);
+ expect(find.text('Subscription'), findsNothing);
expect(trigger.hasFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
dismissTransientMenus();
await tester.pumpAndSettle();
- expect(find.text('SUBSCRIPTION'), findsNothing);
+ expect(find.text('Subscription'), findsNothing);
expect(ownLogin, 0);
expect(manage, 0);
});
@@ -566,7 +568,7 @@ void main() {
expect(find.text('Qwen3.5-4B'), findsOneWidget);
expect(find.text('LFM2.5-8B'), findsOneWidget);
// Still one menu, redrawn — not a second one over the first.
- expect(find.text('ON YOUR MACHINES'), findsOneWidget);
+ expect(find.text('On your machines'), findsOneWidget);
});
testWidgets('shared model changes refresh the open picker', (tester) async {
@@ -593,7 +595,7 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('Old model'), findsNothing);
expect(find.text('New model'), findsOneWidget);
- expect(find.text('SHARED · TEAM'), findsOneWidget);
+ expect(find.text('Shared · Team'), findsOneWidget);
});
testWidgets(
@@ -628,16 +630,16 @@ void main() {
);
await open(tester, onSelected: (m) => picked = m);
- expect(find.text('ON YOUR MACHINES'), findsOneWidget);
- expect(find.text('SHARED · AUTONOMOUS.AI'), findsOneWidget);
+ expect(find.text('On your machines'), findsOneWidget);
+ expect(find.text('Shared · autonomous.ai'), findsOneWidget);
// The grid's name is folded INTO its heading now, not hung on a line beneath it —
// where it read as an entry of the same kind as the models under it.
expect(find.text('Qwen3.5-4B'), findsOneWidget);
expect(find.text('DeepSeek-V4-Flash'), findsOneWidget);
// Own first: Local sits above the shared grids.
expect(
- tester.getTopLeft(find.text('ON YOUR MACHINES')).dy <
- tester.getTopLeft(find.text('SHARED · AUTONOMOUS.AI')).dy,
+ tester.getTopLeft(find.text('On your machines')).dy <
+ tester.getTopLeft(find.text('Shared · autonomous.ai')).dy,
isTrue,
);
// The grid's name is folded INTO its heading now rather than hung on a line beneath it,
@@ -660,7 +662,9 @@ void main() {
tester,
) async {
await open(tester);
- final width = tester.getSize(find.byType(Material).last).width;
+ final width = tester
+ .getSize(find.byKey(const ValueKey('pane-menu-surface')))
+ .width;
expect(
width,
greaterThanOrEqualTo(340),
@@ -685,7 +689,9 @@ void main() {
],
);
await open(tester);
- final width = tester.getSize(find.byType(Material).last).width;
+ final width = tester
+ .getSize(find.byKey(const ValueKey('pane-menu-surface')))
+ .width;
expect(
width,
greaterThan(340),
@@ -735,13 +741,13 @@ void main() {
);
await tester.tap(find.byType(GridModelPicker));
await tester.pumpAndSettle();
- expect(find.text('SUBSCRIPTION'), findsOneWidget);
+ expect(find.text('Subscription'), findsOneWidget);
await tester.tap(find.text('underneath'));
await tester.pumpAndSettle();
expect(
- find.text('SUBSCRIPTION'),
+ find.text('Subscription'),
findsNothing,
reason: 'the menu closes',
);
@@ -883,23 +889,25 @@ void main() {
final inkWell = tester.widget<InkWell>(
find.ancestor(of: find.text(row), matching: find.byType(InkWell)).first,
);
- expect(inkWell.mouseCursor, SystemMouseCursors.click, reason: row);
- // BOTH annotations, because the innermost one under the pointer is what decides: InkWell
- // installs a MouseRegion of its own, so an ancestor asking for a hand does not settle it.
- //
- // ⚠️ Counted, not read off `.first`. The nearest MouseRegion ancestor of a row IS the one
- // InkWell made, so asserting on it twice looked like two checks and was one — the wrapper
- // could be set to `basic` and this test still passed. Two carrying it is what proves both.
- final asking = tester
- .widgetList<MouseRegion>(
- find.ancestor(
- of: find.text(row),
- matching: find.byType(MouseRegion),
- ),
- )
- .where((region) => region.cursor == SystemMouseCursors.click)
- .length;
- expect(asking, greaterThanOrEqualTo(2), reason: row);
+ expect(
+ WidgetStateProperty.resolveAs<MouseCursor?>(inkWell.mouseCursor, {
+ WidgetState.hovered,
+ }),
+ SystemMouseCursors.click,
+ reason: row,
+ );
+ // The shared action now owns its cursor through the actual TextButton;
+ // a second, redundant MouseRegion is no longer part of the row contract.
+ final button = tester.widget<TextButton>(
+ find
+ .ancestor(of: find.text(row), matching: find.byType(TextButton))
+ .first,
+ );
+ expect(
+ button.style!.mouseCursor!.resolve({WidgetState.hovered}),
+ SystemMouseCursors.click,
+ reason: row,
+ );
}
// ⚠️ This asserts the widgets' contract, NOT the cursor the OS draws. Reading that back through
@@ -1155,18 +1163,14 @@ void main() {
// ── which row is the current one ─────────────────────────────────────────────────────────────
//
- // The mark is the fill and its accent border, and nothing else: the tick it used to carry sat
- // beside the quota figure and crowded it, and was taken out on request. Hover paints a fill too,
- // but never the border, which is what keeps the two apart. What is asked here is which ROW gets
- // the mark, and that a screen reader is told which one it is.
+ // A reserved check column identifies the saved choice independently of the
+ // blue pointer/keyboard highlight. It must agree with screen-reader selection.
ModelPickerRow rowFor(WidgetTester tester, String title) => tester
.widgetList<ModelPickerRow>(find.byType(ModelPickerRow))
.firstWhere((r) => r.title == title);
- testWidgets('exactly one row is marked, with no tick beside it', (
- tester,
- ) async {
+ testWidgets('exactly one row has the saved-choice checkmark', (tester) async {
build(
models: [
{'id': 'Qwen-Test', 'node': 'macbook'},
@@ -1178,7 +1182,14 @@ void main() {
expect(rowFor(tester, 'Qwen-Test').selected, isTrue);
expect(rowFor(tester, 'DeepSeek-Test').selected, isFalse);
expect(rowFor(tester, 'Anthropic').selected, isFalse);
- expect(find.byIcon(Icons.check), findsNothing);
+ expect(find.byIcon(AppIcons.check), findsOneWidget);
+ expect(
+ find.descendant(
+ of: find.byWidget(rowFor(tester, 'Qwen-Test')),
+ matching: find.byIcon(AppIcons.check),
+ ),
+ findsOneWidget,
+ );
expect(
// `.last`: the header control names the current model too.
tester.getSemantics(find.text('Qwen-Test').last),
@@ -1202,7 +1213,14 @@ void main() {
expect(rowFor(tester, 'Anthropic').selected, isTrue);
expect(rowFor(tester, 'Qwen-Test').selected, isFalse);
- expect(find.byIcon(Icons.check), findsNothing);
+ expect(find.byIcon(AppIcons.check), findsOneWidget);
+ expect(
+ find.descendant(
+ of: find.byWidget(rowFor(tester, 'Anthropic')),
+ matching: find.byIcon(AppIcons.check),
+ ),
+ findsOneWidget,
+ );
});
// ── the selection has to land before the machine confirms it ──────────────────────────────────
diff --git a/desktop/test/harness_command_bar_test.dart b/desktop/test/harness_command_bar_test.dart
index 22d64922b..8bae76ff2 100644
--- a/desktop/test/harness_command_bar_test.dart
+++ b/desktop/test/harness_command_bar_test.dart
@@ -431,8 +431,11 @@ void main() {
findsOneWidget,
);
expect(
- FocusManager.instance.primaryFocus?.debugLabel,
- 'new-harness-form',
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('new-harness-task')))
+ .focusNode!
+ .hasFocus,
+ isTrue,
);
// Opening the experimental prompt saves this draft and removes its dock.
await chord(tester, LogicalKeyboardKey.keyJ, shift: true);
diff --git a/desktop/test/harness_comments_test.dart b/desktop/test/harness_comments_test.dart
index 0ef1f9d5d..8d4037d82 100644
--- a/desktop/test/harness_comments_test.dart
+++ b/desktop/test/harness_comments_test.dart
@@ -1,21 +1,86 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/sharing/harness_comments.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'support/real_fonts.dart';
+
void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ if (Platform.isMacOS &&
+ Platform.environment['HARNESS_COMMENTS_CAPTURE_DIR'] != null) {
+ final font = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(font))).load();
+ }
+ }
+ await (FontLoader(
+ 'MaterialIcons',
+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
+ });
+
Future<void> show(
WidgetTester tester,
CommentAction manage, {
VoidCallback? signIn,
- }) => tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: Scaffold(
- body: HarnessComments(manage: manage, onSignIn: signIn),
+ Brightness brightness = Brightness.dark,
+ Size size = const Size(460, 560),
+ double scale = 1,
+ Widget? headerAction,
+ }) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: RepaintBoundary(
+ key: const ValueKey('comments-preview'),
+ child: Scaffold(
+ body: HarnessComments(
+ manage: manage,
+ onSignIn: signIn,
+ headerAction: headerAction,
+ ),
+ ),
+ ),
),
- ),
- );
+ );
+ }
+
+ Future<void> capture(WidgetTester tester, String name) async {
+ final directory = Platform.environment['HARNESS_COMMENTS_CAPTURE_DIR'];
+ if (directory == null) return;
+ final boundary = tester.renderObject<RenderRepaintBoundary>(
+ find.byKey(const ValueKey('comments-preview')),
+ );
+ await tester.runAsync(() async {
+ final image = await boundary.toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
testWidgets('public guests can read and sign in but cannot post', (
tester,
@@ -39,8 +104,8 @@ void main() {
await tester.pump();
expect(find.text('Looks good 👋'), findsOneWidget);
expect(find.byType(TextField), findsNothing);
- expect(find.text('[ Remove ]'), findsNothing);
- await tester.tap(find.text('[ Sign in to comment ]'));
+ expect(find.widgetWithText(TextButton, 'Remove'), findsNothing);
+ await tester.tap(find.widgetWithText(TextButton, 'Sign in to comment'));
expect(signIns, 1);
await tester.pumpWidget(const SizedBox());
});
@@ -76,14 +141,14 @@ void main() {
'Hello team',
);
await tester.pump();
- await tester.tap(find.text('[ Comment ]'));
+ await tester.tap(find.byKey(const ValueKey('comment-post')));
await tester.pump();
expect(find.textContaining('Your draft is saved'), findsOneWidget);
expect(
tester.widget<TextField>(find.byType(TextField)).controller!.text,
'Hello team',
);
- await tester.tap(find.text('[ Comment ]'));
+ await tester.tap(find.byKey(const ValueKey('comment-post')));
await tester.pump();
expect(requests, hasLength(2));
expect(requests[0]['id'], requests[1]['id']);
@@ -92,11 +157,148 @@ void main() {
tester.widget<TextField>(find.byType(TextField)).controller!.text,
isEmpty,
);
- await tester.tap(find.text('[ Remove ]'));
+ await tester.tap(find.widgetWithText(TextButton, 'Remove'));
await tester.pump();
expect(find.text('Hello team'), findsNothing);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
},
);
+
+ testWidgets(
+ 'pending post keeps its draft and blocks edits, removal and polling',
+ (tester) async {
+ final result = Completer<Map<String, dynamic>>();
+ final actions = <String>[];
+ const existing = {
+ 'id': 'existing',
+ 'authorName': 'Morgan',
+ 'text': 'Please review the current changes.',
+ 'canDelete': true,
+ };
+ await show(tester, (action, payload) async {
+ actions.add(action);
+ if (action == 'comment_post') return result.future;
+ return {
+ 'canComment': true,
+ 'comments': [existing],
+ };
+ });
+ await tester.pump();
+ await tester.enterText(
+ find.byKey(const Key('comment-input')),
+ 'Reviewing now',
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('comment-post')));
+ await tester.pump();
+ expect(tester.widget<TextField>(find.byType(TextField)).readOnly, isTrue);
+ expect(
+ tester
+ .widget<FilledButton>(find.byKey(const ValueKey('comment-post')))
+ .onPressed,
+ isNull,
+ );
+ expect(
+ tester
+ .widget<TextButton>(find.widgetWithText(TextButton, 'Remove'))
+ .onPressed,
+ isNull,
+ );
+ await tester.pump(const Duration(seconds: 5));
+ expect(actions, ['comments', 'comment_post']);
+ expect(
+ tester.widget<TextField>(find.byType(TextField)).controller!.text,
+ 'Reviewing now',
+ );
+ await capture(tester, 'pending-dark');
+ result.complete({
+ 'canComment': true,
+ 'comments': [existing],
+ });
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(find.byType(TextField)).readOnly,
+ isFalse,
+ );
+ expect(
+ tester.widget<TextField>(find.byType(TextField)).controller!.text,
+ isEmpty,
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets('comments remain usable ${brightness.name} at $scale text', (
+ tester,
+ ) async {
+ final comments = [
+ {
+ 'id': 'one',
+ 'authorName': 'Morgan Rivera · Product and frontend engineering',
+ 'createdAt': '2026-09-29T14:06:00Z',
+ 'text': 'The new layout makes the next step clear. Can we keep the explanation beside the approval choice?',
+ 'canDelete': true,
+ },
+ {
+ 'id': 'two',
+ 'authorName': 'Alex Chen',
+ 'createdAt': '2026-09-29T14:12:00Z',
+ 'text': 'Yes. I’m checking the narrow window and larger text next.',
+ 'canDelete': false,
+ },
+ ];
+ await show(
+ tester,
+ (_, _) async => {'canComment': true, 'comments': comments},
+ brightness: brightness,
+ scale: scale,
+ size: scale == 1 ? const Size(460, 560) : const Size(320, 360),
+ headerAction: TextButton(onPressed: () {}, child: const Text('Back')),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Comments (2)'), findsOneWidget);
+ expect(find.text('Back'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'discussion-${brightness.name}-$scale');
+ await tester.enterText(
+ find.byKey(const Key('comment-input')),
+ 'A draft\nwith a second line\nand one more.',
+ );
+ await tester.pumpAndSettle();
+ final post = find.byKey(const ValueKey('comment-post'));
+ await tester.ensureVisible(post);
+ await tester.pumpAndSettle();
+ expect(post.hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'composer-${brightness.name}-$scale');
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+ }
+
+ testWidgets(
+ 'failed initial read shows a scrollable error without an empty claim',
+ (tester) async {
+ await show(
+ tester,
+ (_, _) async => throw StateError('offline'),
+ scale: 2,
+ size: const Size(320, 360),
+ signIn: () {},
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Comments are unavailable.'), findsOneWidget);
+ expect(find.text('Start the conversation.'), findsNothing);
+ final signIn = find.widgetWithText(TextButton, 'Sign in to comment');
+ await tester.ensureVisible(signIn);
+ await tester.pumpAndSettle();
+ expect(signIn.hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'unavailable-dark-2.0');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
}
diff --git a/desktop/test/harness_customize_test.dart b/desktop/test/harness_customize_test.dart
index 025bb8cbc..ca746a9c5 100644
--- a/desktop/test/harness_customize_test.dart
+++ b/desktop/test/harness_customize_test.dart
@@ -23,6 +23,7 @@ import 'package:harness/terminal/terminal_font_store.dart';
import 'package:harness/terminal/terminal_theme.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/widgets/harness_customize_pane.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'package:xterm/xterm.dart';
import 'support/real_fonts.dart';
@@ -67,15 +68,29 @@ Future<void> _capture(WidgetTester tester, GlobalKey key, String name) async {
void main() {
setUpAll(() async {
- await loadRealFonts();
- if (Platform.isMacOS &&
- Platform.environment.containsKey('HARNESS_CUSTOMIZE_CAPTURE_DIR')) {
+ if (Platform.isMacOS) {
+ final sans = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in [grid.AppType.sansFamily, 'SF Pro Text', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sans))).load();
+ }
final bytes = ByteData.sublistView(
await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
);
for (final family in ['SF Mono', '.AppleSystemUIFontMonospaced']) {
await (FontLoader(family)..addFont(Future.value(bytes))).load();
}
+ await (FontLoader('Menlo')..addFont(
+ Future.value(
+ ByteData.sublistView(
+ await File('/System/Library/Fonts/Menlo.ttc').readAsBytes(),
+ ),
+ ),
+ ))
+ .load();
+ } else {
+ await loadRealFonts();
}
await (FontLoader(
'MaterialIcons',
@@ -206,6 +221,222 @@ void main() {
},
);
+ for (final (name, brightness, scheme, size, scale) in [
+ (
+ 'dark',
+ Brightness.dark,
+ TerminalThemeChoice.matchApp,
+ const Size(440, 760),
+ 1.0,
+ ),
+ (
+ 'light',
+ Brightness.light,
+ TerminalThemeChoice.matchApp,
+ const Size(440, 760),
+ 1.0,
+ ),
+ (
+ 'light-tango',
+ Brightness.light,
+ TerminalThemeChoice.tango,
+ const Size(440, 760),
+ 1.0,
+ ),
+ (
+ 'dark-scaled',
+ Brightness.dark,
+ TerminalThemeChoice.tango,
+ const Size(360, 560),
+ 1.7,
+ ),
+ (
+ 'light-scaled',
+ Brightness.light,
+ TerminalThemeChoice.tango,
+ const Size(360, 560),
+ 1.7,
+ ),
+ ]) {
+ testWidgets('desktop status choices and previews stay usable: $name', (
+ tester,
+ ) async {
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ final oldPalette = grid.AppTheme.palette.value;
+ final oldScheme = terminalThemeStore.value;
+ final oldFont = terminalFontStore.value;
+ addTearDown(() {
+ grid.AppTheme.brightness.value = oldBrightness;
+ grid.AppTheme.palette.value = oldPalette;
+ terminalThemeStore.value = oldScheme;
+ terminalFontStore.value = oldFont;
+ });
+ grid.AppTheme.brightness.value = brightness;
+ grid.AppTheme.palette.value = HarnessPalette.graphite;
+ terminalThemeStore.value = scheme;
+ terminalFontStore.value = const TerminalStyle(
+ fontFamily: 'Menlo',
+ fontSize: 14,
+ );
+ final store = AppearancePrefsStore(storage: _Storage());
+ addTearDown(store.dispose);
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => grid.BrightnessScope(
+ child: MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(scale),
+ highContrast: scale > 1,
+ disableAnimations: scale > 1,
+ ),
+ child: child!,
+ ),
+ ),
+ home: Scaffold(
+ body: RepaintBoundary(
+ key: boundary,
+ child: HarnessCustomizePane(store: store, onClose: () {}),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final selected = find.byKey(const ValueKey('prompt-style-standard'));
+ final other = find.byKey(const ValueKey('prompt-style-robbyrussell'));
+ final otherLabel = find.descendant(
+ of: other,
+ matching: find.text('Robbyrussell'),
+ );
+ final beforeStyle = tester.widget<Text>(otherLabel).style!;
+ final beforeHeader = tester.getSize(find.text('Customize Harness'));
+ expect(beforeStyle.fontFamily, grid.AppType.sansFamily);
+ expect(
+ beforeStyle.color,
+ grid.AppPalette.textPrimary,
+ reason: 'App labels follow the app appearance with any terminal theme',
+ );
+ await _capture(tester, boundary, 'desktop-$name-catalog');
+
+ // Terminal zoom changes its samples, without resizing the UI typography.
+ terminalFontStore.value = terminalFontStore.value.copyWith(fontSize: 24);
+ await tester.pumpAndSettle();
+ expect(tester.widget<Text>(otherLabel).style, beforeStyle);
+ expect(tester.getSize(find.text('Customize Harness')), beforeHeader);
+ final sample = find.byKey(const ValueKey('prompt-example-standard'));
+ final sampleText = tester.widget<Text>(
+ find.descendant(of: sample, matching: find.byType(Text)),
+ );
+ expect(sampleText.style!.fontFamily, 'Menlo');
+ expect(sampleText.style!.fontSize, 24);
+ expect(
+ tester
+ .widget<RichText>(
+ find.descendant(of: sample, matching: find.byType(RichText)),
+ )
+ .text
+ .style!
+ .fontWeight,
+ FontWeight.normal,
+ reason: 'A selected button must not make terminal output semibold',
+ );
+ expect(
+ MediaQuery.textScalerOf(tester.element(sample)),
+ TextScaler.noScaling,
+ );
+ final well = find.descendant(
+ of: find.byKey(const ValueKey('prompt-example-well-standard')),
+ matching: find.byType(DecoratedBox),
+ );
+ expect(
+ (tester.widget<DecoratedBox>(well).decoration as BoxDecoration).color,
+ terminalThemeFor(HarnessPalette.graphite, scheme).background,
+ );
+
+ await tester.ensureVisible(other);
+ Focus.of(tester.element(otherLabel)).requestFocus();
+ await tester.pumpAndSettle();
+ expect(store.value.prompt.statusStyle, StatusLineStyle.standard);
+ final semantics = tester.ensureSemantics();
+ try {
+ await tester.pump();
+ final chosen = tester.getSemantics(selected).getSemanticsData();
+ final focused = tester.getSemantics(other).getSemanticsData();
+ expect(chosen.flagsCollection.isSelected, ui.Tristate.isTrue);
+ expect(focused.flagsCollection.isSelected, ui.Tristate.isFalse);
+ expect(focused.label, 'Robbyrussell');
+ expect(focused.hasAction(ui.SemanticsAction.tap), isTrue);
+ } finally {
+ semantics.dispose();
+ }
+ final button = tester.widget<TextButton>(
+ find.descendant(of: other, matching: find.byType(TextButton)),
+ );
+ expect(
+ button.style!.side!.resolve({WidgetState.focused})!.color,
+ DesktopChrome.accent,
+ );
+ await _capture(tester, boundary, 'desktop-$name-focus-large-terminal');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(store.value.prompt.statusStyle, StatusLineStyle.robbyrussell);
+
+ final powerline = find.byKey(const ValueKey('prompt-style-agnoster'));
+ await tester.ensureVisible(powerline);
+ await tester.tap(powerline);
+ await tester.pumpAndSettle();
+ expect(store.value.prompt.statusStyle, StatusLineStyle.agnoster);
+ await _capture(tester, boundary, 'desktop-$name-powerline');
+
+ final reset = find.byKey(const ValueKey('prompt-reset'));
+ await tester.ensureVisible(reset);
+ await tester.pumpAndSettle();
+ final branchLabel = find.descendant(
+ of: find.byKey(const ValueKey('prompt-branch')),
+ matching: find.text('Branch'),
+ );
+ Focus.of(tester.element(branchLabel)).requestFocus();
+ await tester.pumpAndSettle();
+ await _capture(tester, boundary, 'desktop-$name-fields');
+ final toggleSemantics = tester.ensureSemantics();
+ try {
+ for (final field in ['machine', 'project', 'branch', 'color']) {
+ final toggle = find.byKey(ValueKey('prompt-$field'));
+ await tester.ensureVisible(toggle);
+ await tester.tap(toggle);
+ await tester.pumpAndSettle();
+ final node = tester.getSemantics(toggle).getSemanticsData();
+ expect(node.flagsCollection.isChecked, ui.CheckedState.isFalse);
+ expect(node.hasAction(ui.SemanticsAction.tap), isTrue);
+ }
+ } finally {
+ toggleSemantics.dispose();
+ }
+ expect(store.value.prompt.machine, isFalse);
+ expect(store.value.prompt.project, isFalse);
+ expect(store.value.prompt.branch, isFalse);
+ expect(store.value.prompt.color, isFalse);
+ expect(
+ tester
+ .widget<StatusLine>(find.byKey(const ValueKey('prompt-preview')))
+ .parts
+ .segments,
+ isEmpty,
+ );
+ await tester.ensureVisible(reset);
+ await tester.tap(reset);
+ await tester.pumpAndSettle();
+ expect(store.value.prompt, const PromptPrefs());
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
for (final entry in ['command search', 'native menu', 'Settings']) {
testWidgets(
'$entry opens customization beside the visible terminal and Escape returns typing',
diff --git a/desktop/test/harness_picker_entry_test.dart b/desktop/test/harness_picker_entry_test.dart
index 5218a3f1d..041fa7e0e 100644
--- a/desktop/test/harness_picker_entry_test.dart
+++ b/desktop/test/harness_picker_entry_test.dart
@@ -1,3 +1,4 @@
+import 'support/launch_menu.dart';
import 'support/open_harness.dart';
import 'dart:io';
@@ -147,10 +148,7 @@ void main() {
findsOneWidget,
);
await capture('creation');
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
+ await openLaunchRow(tester, 'agent');
await capture('creation-options');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
diff --git a/desktop/test/harness_placement_test.dart b/desktop/test/harness_placement_test.dart
index 0aad1c97a..4c1630b8c 100644
--- a/desktop/test/harness_placement_test.dart
+++ b/desktop/test/harness_placement_test.dart
@@ -3,6 +3,7 @@ import 'support/launch_menu.dart';
import 'dart:async';
+import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -22,6 +23,21 @@ import 'swarm_screen_test.dart' show terminal;
import 'swarm_screen_test.dart' as workspace;
import 'swarm_state_test.dart' show createApp;
+class _SelectedFolder extends FileSelectorPlatform {
+ _SelectedFolder(this.path);
+ final String path;
+ int opened = 0;
+
+ @override
+ Future<String?> getDirectoryPath({
+ String? initialDirectory,
+ String? confirmButtonText,
+ }) async {
+ opened++;
+ return path;
+ }
+}
+
class _Connection extends WsConn {
_Connection({this.profiles = const []})
: super(
@@ -268,10 +284,17 @@ void main() {
box = tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
- expect(box.task, isEmpty);
- expect(box.mode, 'auto');
- expect(box.profileLabel, isNot('Work'));
- expect(box.project.repository, isNull);
+ expect(
+ box.task,
+ ' Review before changing anything\nKeep the patch small ',
+ );
+ expect(box.mode, 'readOnly');
+ expect(box.profileLabel, profile);
+ expect(
+ box.project.repository?.url,
+ 'https://github.com/acme/terminal-tools.git',
+ );
+ expect(app.projectHistory.selected('m'), '/work/source');
expect(connection.requests, isEmpty);
await tester.pumpWidget(const SizedBox());
return;
@@ -357,7 +380,7 @@ void main() {
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(box.task, 'Keep this first task');
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await chord(tester, LogicalKeyboardKey.enter);
await tester.pump();
expect(connection.requests, hasLength(2));
expect(connection.requests.last.type, 'agent_create_status');
@@ -397,12 +420,21 @@ void main() {
final app = createApp(connectionForTest: (_) => connection);
addTearDown(app.dispose);
app.machineStates['m']!.nodeOnline = true;
+ final folderPicker = _SelectedFolder(projectQuery);
+ if (projectQuery.startsWith('/')) {
+ final previousPicker = FileSelectorPlatform.instance;
+ FileSelectorPlatform.instance = folderPicker;
+ addTearDown(() => FileSelectorPlatform.instance = previousPicker);
+ }
app.adoptSessionForTest(terminal('a0', []));
final original = app.activeSwarm;
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyT);
await chord(tester, LogicalKeyboardKey.keyN);
await tester.pump();
+ if (projectQuery.startsWith('/')) {
+ app.machineStates['m']!.localOnly = true;
+ }
final input = find.byKey(const ValueKey('new-harness-query'));
tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
@@ -423,12 +455,18 @@ void main() {
),
);
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- await tester.enterText(input, projectQuery);
- await tester.pump(const Duration(milliseconds: 250));
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
+ if (projectQuery.startsWith('/')) {
+ await tester.pumpAndSettle();
+ expect(folderPicker.opened, 1);
+ // Only the folder picker uses the local fixture. Launch still goes
+ // through the fake daemon used by every placement assertion below.
+ app.machineStates['m']!.localOnly = false;
+ } else {
+ await tester.enterText(input, projectQuery);
+ await tester.pump(const Duration(milliseconds: 250));
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ }
await openLaunchRow(tester, 'mode');
await tester.tap(
find.byKey(const ValueKey('new-harness-option-readOnly')),
@@ -756,7 +794,7 @@ void main() {
expect(box.placement, HarnessPlacement.currentTab);
box.setFolder('/work/project');
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await chord(tester, LogicalKeyboardKey.enter);
await tester.pump();
expect(box.busy, isTrue);
expect(
@@ -811,7 +849,7 @@ void main() {
expect(box.checking, isTrue);
await keepsPendingBox();
expect(connection.requests, hasLength(1));
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await chord(tester, LogicalKeyboardKey.enter);
await tester.pump();
expect(connection.requests.last.type, 'agent_create_status');
connection.created();
@@ -828,7 +866,7 @@ void main() {
);
testWidgets(
- 'a dismissed pending creation resumes its receipt even without a task',
+ 'switching tabs preserves a pending creation receipt even without a task',
(tester) async {
newHarnessOpensInBox = true;
addTearDown(() => newHarnessOpensInBox = false);
@@ -847,18 +885,17 @@ void main() {
.controller
.setFolder('/work/project');
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await chord(tester, LogicalKeyboardKey.enter);
await tester.pump();
final request = connection.requests.single;
expect(request.payload.containsKey('prompt'), isFalse);
request.reply.completeError(const WsRequestTimeout('agent_create'));
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- expect(find.byType(NewHarnessForm), findsOneWidget);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
+ final pendingTab = app.activeSwarmId;
+ app.selectSwarm(original.id);
+ await tester.pumpAndSettle();
expect(find.byType(NewHarnessForm), findsNothing);
+ app.selectSwarm(pendingTab);
await chord(tester, LogicalKeyboardKey.keyN);
await tester.pump();
final box = tester
@@ -867,18 +904,15 @@ void main() {
expect(box.task, isEmpty);
expect(box.checking, isTrue);
expect(find.text('pending harness'), findsNothing);
- expect(
- find.textContaining('Check status', findRichText: true),
- findsOneWidget,
- );
- // The restored "Escape again" warning keeps its meaning; it must not
- // require another invisible acknowledgement before closing.
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
+ expect(find.text('Check status'), findsOneWidget);
+ // Leaving the page again retains the same receipt, even with no task.
+ app.selectSwarm(original.id);
+ await tester.pumpAndSettle();
expect(find.byType(NewHarnessForm), findsNothing);
+ app.selectSwarm(pendingTab);
await chord(tester, LogicalKeyboardKey.keyN);
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await chord(tester, LogicalKeyboardKey.enter);
await tester.pump();
expect(connection.requests, hasLength(2));
expect(connection.requests.last.type, 'agent_create_status');
@@ -970,9 +1004,12 @@ void main() {
await tester.pump();
expect(app.swarms.length, placement == HarnessPlacement.newTab ? 2 : 1);
expect(app.swarms, contains(original));
- // The creation box was opened from a search editor that is now gone.
- // Returning focus to that detached editor would disable shortcuts.
- expect(find.byType(NewHarnessForm), findsNothing);
+ // Escape dismisses the modal and retains the draft. An empty tab keeps
+ // its embedded composer; either entry can open search afterward.
+ expect(
+ find.byType(NewHarnessForm),
+ placement == HarnessPlacement.newTab ? findsOneWidget : findsNothing,
+ );
await chord(tester, LogicalKeyboardKey.keyP);
expect(
find.byKey(const ValueKey('swarm-search-input')),
diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dart
index 066bc7ce4..74da227a4 100644
--- a/desktop/test/harness_session_manager_test.dart
+++ b/desktop/test/harness_session_manager_test.dart
@@ -2,12 +2,13 @@ import 'support/workspace_tools.dart';
import 'dart:async';
import 'dart:io';
-import 'dart:ui' show SemanticsAction;
+import 'dart:ui' show PointerDeviceKind, SemanticsAction;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
import 'package:harness/state/harness_sessions.dart';
import 'package:harness/state/pending_question.dart';
@@ -18,6 +19,7 @@ import 'package:harness/ws/ws_conn.dart';
import 'box_render_preview_test.dart' show loadPreviewFonts;
import 'keymap_host_test.dart' show key;
import 'support/restart_connection.dart';
+import 'support/real_fonts.dart';
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
@@ -48,6 +50,8 @@ const _paused = Agent(
);
void main() {
+ setUpAll(loadRealFonts);
+
late AppNotifier app;
late RestartConnection connection;
setUp(() {
@@ -247,6 +251,46 @@ void main() {
expect(tester.takeException(), isNull);
});
+ testWidgets('recent harness ages show and say now, including clock skew', (
+ tester,
+ ) async {
+ final now = DateTime.now();
+ app.machineStates['m']!.agents = [
+ for (final (id, age) in [
+ ('recent', const Duration(seconds: 30)),
+ ('future', const Duration(minutes: -4)),
+ ])
+ Agent(
+ id: id,
+ name: '$id harness',
+ engine: _running.engine,
+ sessionId: '$id-conversation',
+ terminalAvailable: true,
+ project: _project,
+ lastActivityAt: now.subtract(age),
+ ),
+ ];
+ for (final id in ['recent', 'future']) {
+ app.rememberOpenedHarness('m', id);
+ }
+ await open(tester);
+ for (final agentId in ['recent', 'future']) {
+ final id = agentDestinationId('m', agentId);
+ expect(
+ tester.widget<Text>(find.byKey(ValueKey('session-age:$id'))).data,
+ '· now',
+ );
+ final spoken = tester
+ .widget<Semantics>(find.byKey(ValueKey('session-open:$id')))
+ .properties
+ .value!;
+ expect(spoken, contains('Last used now'));
+ expect(spoken, isNot(contains('0m')));
+ expect(spoken, isNot(contains('now ago')));
+ }
+ expect(tester.takeException(), isNull);
+ });
+
testWidgets(
'displays remote cached tokens beneath context and leaves missing usage empty',
(tester) async {
@@ -959,6 +1003,20 @@ void main() {
nativeClick();
await tester.pumpAndSettle();
expect(find.byType(HarnessSessionManager), findsOneWidget);
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('session-search')))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('session-search')))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
expect(updates.last['sessionsOpen'], isTrue);
expect(updates.last['runningSessions'], 1);
nativeClick();
@@ -1023,6 +1081,172 @@ void main() {
});
final renderDir = Platform.environment['SESSION_MANAGER_RENDER_DIR'];
+ for (final brightness in Brightness.values) {
+ testWidgets('desktop inventory focus and feedback in ${brightness.name}', (
+ tester,
+ ) async {
+ if (renderDir != null) await tester.runAsync(loadPreviewFonts);
+ final previousBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ app.machineStates['m']!.blockedAgents['a0'] = question('a0');
+ app.machineStates['m']!.agents[0] = Agent.fromJson({
+ 'id': 'a0',
+ 'name': _running.name,
+ 'engine': _running.engine,
+ 'sessionId': 'fixture-conversation',
+ 'terminal': {'available': true},
+ 'project': {
+ 'name': _project.name,
+ 'cwd': _project.cwd,
+ 'branch': _project.branch,
+ },
+ 'tokenUsage': {'totalTokens': 123456},
+ 'outputStats': {
+ 'linesAdded': 124,
+ 'linesRemoved': 38,
+ 'pullRequestsCreated': 2,
+ },
+ });
+ final opening = <String>[];
+ final field = find.byKey(const ValueKey('session-search'));
+ final opener = find.byKey(
+ ValueKey('session-open:${agentDestinationId('m', 'a0')}'),
+ );
+ for (final (size, scale) in [
+ (const Size(880, 560), 1.0),
+ (const Size(420, 480), 1.7),
+ ]) {
+ tester.view.physicalSize = size;
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topCenter,
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: SizedBox(
+ width: 640,
+ child: HarnessSessionManager(
+ key: ValueKey((brightness, scale)),
+ app: app,
+ recent: const [],
+ onClose: () {},
+ onOpen: (row) async {
+ opening.add(row.id);
+ throw StateError('Synthetic open failure');
+ },
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> capture(String state) async {
+ expect(tester.takeException(), isNull);
+ if (renderDir == null) return;
+ final oldShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ try {
+ await tester.runAsync(() async {
+ await Future.wait(
+ find
+ .byType(Image)
+ .evaluate()
+ .map(
+ (element) => precacheImage(
+ (element.widget as Image).image,
+ element,
+ ),
+ ),
+ );
+ });
+ for (final object in tester.allRenderObjects) {
+ object.markNeedsPaint();
+ }
+ await tester.pump();
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(
+ Uri.file(
+ '$renderDir/inventory-$state-${brightness.name}-$scale.png',
+ ),
+ ),
+ );
+ } finally {
+ debugDisableShadows = oldShadows;
+ }
+ }
+
+ final editor = tester.widget<TextField>(field);
+ expect(editor.focusNode!.hasFocus, isTrue);
+ expect(find.byTooltip('Close').hitTestable(), findsOneWidget);
+ await capture('list');
+ await tester.enterText(field, 'Font');
+ editor.controller!.value = const TextEditingValue(
+ text: 'Font',
+ selection: TextSelection.collapsed(offset: 4),
+ composing: TextRange(start: 0, end: 4),
+ );
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: Offset.zero);
+ await mouse.moveTo(tester.getCenter(opener));
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(field).controller,
+ same(editor.controller),
+ );
+ expect(editor.focusNode!.hasFocus, isTrue);
+ expect(
+ editor.controller!.value.composing,
+ const TextRange(start: 0, end: 4),
+ );
+ expect(tester.widget<Semantics>(opener).properties.selected, isTrue);
+ await capture('active');
+ await mouse.removePointer();
+ editor.controller!.value = const TextEditingValue(
+ text: 'Font',
+ selection: TextSelection.collapsed(offset: 4),
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(opening.last, agentDestinationId('m', 'a0'));
+ await tester.tap(find.byTooltip('Clear search'));
+ await tester.pumpAndSettle();
+ const failure = 'Could not open this harness. Try again.';
+ final error = tester.widget<Text>(find.text(failure)).style!.color!;
+ final foreground = error.computeLuminance();
+ final background = grid.AppMenu.fill.computeLuminance();
+ final contrast = foreground > background
+ ? (foreground + .05) / (background + .05)
+ : (background + .05) / (foreground + .05);
+ expect(contrast, greaterThanOrEqualTo(4.5));
+ await capture('error');
+ final questions = find.byKey(
+ const ValueKey('session-filter:needsInput'),
+ );
+ await tester.ensureVisible(questions);
+ await tester.tap(questions);
+ await tester.pumpAndSettle();
+ expect(find.text('Use the shared cache?'), findsOneWidget);
+ await capture('needs-input');
+ expect(connection.requests, isEmpty);
+ expect(connection.stops, isEmpty);
+ }
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
testWidgets(
'render session manager for visual review',
skip: renderDir == null,
diff --git a/desktop/test/harness_session_picker_test.dart b/desktop/test/harness_session_picker_test.dart
index d665789ba..fa5384abd 100644
--- a/desktop/test/harness_session_picker_test.dart
+++ b/desktop/test/harness_session_picker_test.dart
@@ -185,7 +185,10 @@ void main() {
await tester.pumpAndSettle();
expect(app.stateOf('m')!.agents.first.isStopped, isTrue);
expect(resourceSearch(tester).selected?.agentId, 'a0');
- expect(find.text('Resume & open'), findsNothing);
+ expect(
+ find.byKey(const ValueKey('resource-action:picker.accept')),
+ findsOneWidget,
+ );
final panes = app.panes.map((pane) => pane.id).toList();
expect(
tester.widget<TextField>(resourceField).focusNode!.hasFocus,
diff --git a/desktop/test/harness_start_page_test.dart b/desktop/test/harness_start_page_test.dart
index 055fb3629..f6ea4a986 100644
--- a/desktop/test/harness_start_page_test.dart
+++ b/desktop/test/harness_start_page_test.dart
@@ -203,7 +203,7 @@ void main() {
});
testWidgets(
- 'over a picture, Customize keeps its terminal text action and restores focus',
+ 'over a picture, Customize keeps its shared capsule action and restores focus',
(tester) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(1280, 800);
@@ -232,7 +232,10 @@ void main() {
await tester.pump();
final button = find.byKey(const ValueKey('harness-customize-button'));
expect(tester.widget(button), isA<TerminalTextAction>());
- expect(find.text('[ Customize Harness ]'), findsOneWidget);
+ expect(
+ find.widgetWithText(TextButton, 'Customize Harness'),
+ findsOneWidget,
+ );
expect(
find.descendant(of: button, matching: find.byType(Icon)),
findsNothing,
diff --git a/desktop/test/harness_store_entry_test.dart b/desktop/test/harness_store_entry_test.dart
index cd8baa340..69f900485 100644
--- a/desktop/test/harness_store_entry_test.dart
+++ b/desktop/test/harness_store_entry_test.dart
@@ -150,53 +150,55 @@ void main() {
);
}
- testWidgets('fresh creation after browsing uses successful launch defaults', (
- tester,
- ) async {
- newHarnessOpensInBox = true;
- addTearDown(() => newHarnessOpensInBox = false);
- final app = createApp();
- app.machineStates['m']!.localOnly = true;
- app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
- await app.agentPreference.remember('codex');
- await app.projectHistory.select('m', '/work/saved');
- final map = MemoryKeymap();
- addTearDown(app.dispose);
- addTearDown(map.dispose);
- final pane = app.adoptSessionForTest(terminal('a0', []));
- final work = app.activeSwarm;
- await configured.mount(tester, app, map);
- await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ testWidgets(
+ 'returning from Store restores the creation draft and selected project',
+ (tester) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final app = createApp();
+ app.machineStates['m']!.localOnly = true;
+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
+ await app.agentPreference.remember('codex');
+ await app.projectHistory.select('m', '/work/saved');
+ final map = MemoryKeymap();
+ addTearDown(app.dispose);
+ addTearDown(map.dispose);
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final work = app.activeSwarm;
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- final box = tester
- .widget<NewHarnessForm>(find.byType(NewHarnessForm))
- .controller;
- box.setFolder('/work/project');
- await tester.pump();
- box.task = 'Finish the login feature';
- await tester.pump();
- final draft = box.draft;
- await openLaunchRow(tester, 'harness');
- await typeHarnessQuery(tester, 'a harness not in this catalog');
- await tester.pump();
- expect(box.selected?.id, NewHarnessController.storeId);
- expect(find.text('Browse Harness Store'), findsOneWidget);
- await acceptSetupOrSearch(tester);
- expect(app.activeSwarm.isStore, isTrue);
- expect(find.byType(NewHarnessForm), findsNothing);
- expect(work.panes.single, same(pane));
- app.selectSwarm(work.id);
- await tester.pump();
- await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- final resumed = tester
- .widget<NewHarnessForm>(find.byType(NewHarnessForm))
- .controller;
- expect(resumed.task, '');
- expect(resumed.engine, draft.engine);
- expect(resumed.machineId, draft.machineId);
- expect(resumed.project.folder, '/work/saved');
- await key(tester, LogicalKeyboardKey.escape);
- expect(tester.takeException(), isNull);
- await tester.pumpWidget(const SizedBox());
- });
+ final box = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
+ box.setFolder('/work/project');
+ await tester.pump();
+ box.task = 'Finish the login feature';
+ await tester.pump();
+ final draft = box.draft;
+ await openLaunchRow(tester, 'harness');
+ await typeHarnessQuery(tester, 'a harness not in this catalog');
+ await tester.pump();
+ expect(box.selected?.id, NewHarnessController.storeId);
+ expect(find.text('Browse Harness Store'), findsOneWidget);
+ await acceptSetupOrSearch(tester);
+ expect(app.activeSwarm.isStore, isTrue);
+ expect(find.byType(NewHarnessForm), findsNothing);
+ expect(work.panes.single, same(pane));
+ app.selectSwarm(work.id);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final resumed = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
+ expect(resumed.task, draft.task);
+ expect(resumed.engine, draft.engine);
+ expect(resumed.machineId, draft.machineId);
+ expect(resumed.project.folder, draft.project.folder);
+ expect(app.projectHistory.selected('m'), '/work/project');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
}
diff --git a/desktop/test/harness_titles_test.dart b/desktop/test/harness_titles_test.dart
index 2b5c73146..4ca23cc56 100644
--- a/desktop/test/harness_titles_test.dart
+++ b/desktop/test/harness_titles_test.dart
@@ -87,9 +87,36 @@ void main() {
test('a tab saved as Untitled Tab restores as New Tab', () {
expect(Swarm.normalizeName('Untitled Tab'), Swarm.defaultName);
- expect(Swarm.defaultName, 'New Swarm');
+ expect(Swarm.defaultName, 'New Tab');
});
+ test('legacy New Swarm becomes New Tab while custom titles stay exact', () {
+ expect(Swarm(id: 'legacy', name: 'New Swarm').name, 'New Tab');
+ for (final title in ['New Swarm', 'New swarm', '1: Release planning']) {
+ final tab = Swarm(id: 'custom', name: title, nameIsCustom: true);
+ expect(tab.name, title);
+ expect(tab.nameIsCustom, isTrue);
+ }
+ });
+
+ test(
+ 'a saved custom New Swarm title survives restore and opening work',
+ () async {
+ final store = MemoryStore();
+ final original = createApp(store: store);
+ original.renameSwarm(original.activeSwarmId, 'New Swarm');
+ await original.flushPaneLayout();
+ original.dispose();
+ final restored = createApp(store: store);
+ addTearDown(restored.dispose);
+ await restored.restorePaneLayoutForTest();
+ expect(restored.activeSwarm.name, 'New Swarm');
+ expect(restored.activeSwarm.nameIsCustom, isTrue);
+ await restored.addAgentToSwarm('m', 'a0');
+ expect(restored.activeSwarm.name, 'New Swarm');
+ },
+ );
+
test('tab follows its first harness until an explicit rename, including after restore', () async {
final store = MemoryStore();
final app = createApp(store: store);
@@ -102,7 +129,7 @@ void main() {
),
];
await app.addAgentToSwarm('m', 'a0');
- expect(app.activeSwarm.name, 'New Swarm');
+ expect(app.activeSwarm.name, 'New Tab');
expect(app.activeSwarm.nameIsCustom, isFalse);
await sessionTitle(app, 'Review API changes');
expect(app.activeSwarm.name, 'Review API changes');
diff --git a/desktop/test/keyboard_practice_test.dart b/desktop/test/keyboard_practice_test.dart
index 7bd8ac884..ef688f8b0 100644
--- a/desktop/test/keyboard_practice_test.dart
+++ b/desktop/test/keyboard_practice_test.dart
@@ -128,13 +128,13 @@ void main() {
await configured.mount(tester, app, map);
await command(tester, 'Keyboard practice');
expect(filter, findsOneWidget);
- await openLesson(tester, 'New Swarm');
+ await openLesson(tester, 'New Tab');
await key(tester, LogicalKeyboardKey.keyW, cmd: true);
- expect(find.textContaining('That is Close Swarm'), findsOneWidget);
+ expect(find.textContaining('That is Close Tab'), findsOneWidget);
expect(app.swarms, [original]);
expect(original.panes, panes);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
- expect(find.text('[x] New Swarm'), findsOneWidget);
+ expect(find.byKey(const ValueKey('practice-completed')), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
await openLesson(tester, 'Stop Harness');
await tester.enterText(
@@ -142,7 +142,7 @@ void main() {
'Stop Harness',
);
await key(tester, LogicalKeyboardKey.enter);
- expect(find.text('[x] Stop Harness'), findsOneWidget);
+ expect(find.byKey(const ValueKey('practice-completed')), findsOneWidget);
expect(app.swarms, [original]);
expect(original.panes, panes);
expect(input, isEmpty);
@@ -166,22 +166,22 @@ void main() {
'''{"bindings":[{"keys":"cmd+t","command":null},{"keys":"ctrl+x ctrl+t","command":"swarm.new"}]}''',
);
await tester.pumpWidget(MaterialApp(home: KeyboardPractice(keymap: map)));
- await openLesson(tester, 'New Swarm');
+ await openLesson(tester, 'New Tab');
expect(find.text('Press ctrl-X ctrl-T'), findsOneWidget);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
- expect(find.text('[x] New Swarm'), findsNothing);
+ expect(find.byKey(const ValueKey('practice-completed')), findsNothing);
await key(tester, LogicalKeyboardKey.keyX, ctrl: true);
await key(tester, LogicalKeyboardKey.keyT, ctrl: true);
- expect(find.text('[x] New Swarm'), findsOneWidget);
+ expect(find.byKey(const ValueKey('practice-completed')), findsOneWidget);
map.apply('''{"bindings":[{"keys":"cmd+t","command":null}]}''');
await tester.pump();
expect(find.byKey(const ValueKey('practice-command')), findsOneWidget);
await tester.enterText(
find.byKey(const ValueKey('practice-command')),
- 'New Swarm',
+ 'New Tab',
);
await key(tester, LogicalKeyboardKey.enter);
- expect(find.text('[x] New Swarm'), findsOneWidget);
+ expect(find.byKey(const ValueKey('practice-completed')), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
@@ -191,12 +191,12 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: KeyboardPractice()));
await openLesson(tester, 'Close search');
await key(tester, LogicalKeyboardKey.escape);
- expect(find.text('[x] Close search'), findsOneWidget);
+ expect(find.byKey(const ValueKey('practice-completed')), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
expect(filter, findsOneWidget);
await openLesson(tester, 'Erase the previous word');
await key(tester, LogicalKeyboardKey.keyW, ctrl: true);
- expect(find.text('[x] Erase the previous word'), findsOneWidget);
+ expect(find.byKey(const ValueKey('practice-completed')), findsOneWidget);
await tester.pumpWidget(const SizedBox());
});
@@ -213,7 +213,7 @@ void main() {
home: KeyboardPractice(keymap: map, storage: storage),
),
);
- await openLesson(tester, 'New Swarm');
+ await openLesson(tester, 'New Tab');
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
storage.pending!.complete(jsonEncode([earlier.id]));
await tester.pumpAndSettle();
@@ -235,7 +235,7 @@ void main() {
'practice buttons activate from the keyboard in both lesson contexts',
(tester) async {
await tester.pumpWidget(const MaterialApp(home: KeyboardPractice()));
- for (final query in ['New Swarm', 'Next result']) {
+ for (final query in ['New Tab', 'Next result']) {
await openLesson(tester, query);
final buttonText = find.descendant(
of: find.byKey(const ValueKey('practice-back')),
@@ -321,85 +321,183 @@ void main() {
},
);
- for (final (size, scale) in [
- (const Size(1000, 800), 1.0),
- (const Size(480, 420), 1.7),
+ for (final (size, scale, brightness) in [
+ (const Size(1000, 800), 1.0, Brightness.dark),
+ (const Size(1000, 800), 1.0, Brightness.light),
+ (const Size(480, 420), 1.7, Brightness.dark),
+ (const Size(480, 420), 1.7, Brightness.light),
]) {
- testWidgets('practice stays readable at $size and $scale text', (
- tester,
- ) async {
- await tester.runAsync(loadRealFonts);
- tester.view.physicalSize = size;
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- final boundary = GlobalKey();
- final storage = LearningMemoryStore();
- final map = MemoryKeymap();
- addTearDown(map.dispose);
- map.apply('''{"version":1,"bindings":[
+ testWidgets(
+ 'practice stays readable at $size and $scale text in $brightness',
+ (tester) async {
+ await tester.runAsync(() async {
+ if (Platform.isMacOS) {
+ final sans = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in [grid.AppType.sansFamily, 'SF Pro Text']) {
+ await (FontLoader(family)..addFont(Future.value(sans))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'SF Mono']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ await (FontLoader('Menlo')..addFont(
+ Future.value(
+ ByteData.sublistView(
+ await File('/System/Library/Fonts/Menlo.ttc')
+ .readAsBytes(),
+ ),
+ ),
+ ))
+ .load();
+ } else {
+ await loadRealFonts();
+ }
+ await (FontLoader('MaterialIcons')
+ ..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf')))
+ .load();
+ });
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final savedBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = savedBrightness);
+ final boundary = GlobalKey();
+ final storage = LearningMemoryStore();
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ map.apply('''{"version":1,"bindings":[
{"keys":"alt+j","command":"picker.page_down","when":"picker"},
{"keys":"alt+k","command":"picker.page_up","when":"picker"}
]}''');
- await tester.pumpWidget(
- MaterialApp(
- theme: ThemeData.dark(),
- builder: (context, child) => MediaQuery(
- data: MediaQuery.of(context)
- .copyWith(textScaler: TextScaler.linear(scale)),
- child: child!,
- ),
- home: RepaintBoundary(
- key: boundary,
- child: KeyboardPractice(storage: storage, keymap: map),
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(scale),
+ highContrast: brightness == Brightness.light && scale > 1,
+ disableAnimations: scale > 1,
+ ),
+ child: child!,
+ ),
+ home: RepaintBoundary(
+ key: boundary,
+ child: KeyboardPractice(storage: storage, keymap: map),
+ ),
),
- ),
- );
- await tester.pumpAndSettle();
- expect(tester.takeException(), isNull);
- Future<void> snap(String name) =>
- capture(tester, boundary, '$name-${size.width.toInt()}');
-
- await snap('practice-list');
- await openLesson(tester, 'New Swarm');
- await snap('practice-key');
- await key(tester, LogicalKeyboardKey.keyT, cmd: true);
- await tester.pumpAndSettle();
- expect(tester.takeException(), isNull);
- await snap('practice-result');
- if (size.width < 500) {
- final details = tester.widget<SingleChildScrollView>(
- find.byType(SingleChildScrollView),
);
- final scrolling = details.controller!;
- expect(scrolling.position.maxScrollExtent, greaterThan(0));
- await key(tester, LogicalKeyboardKey.pageDown);
- expect(scrolling.offset, greaterThan(0));
- await snap('practice-read');
- await key(tester, LogicalKeyboardKey.pageUp);
- expect(scrolling.offset, 0);
- await key(tester, LogicalKeyboardKey.pageDown);
- await key(tester, LogicalKeyboardKey.escape);
- await openLesson(tester, 'New Pane');
- expect(scrolling.offset, 0);
- await key(tester, LogicalKeyboardKey.escape);
- await openLesson(tester, 'Next result');
- await key(tester, LogicalKeyboardKey.arrowDown);
await tester.pumpAndSettle();
- final cell = terminalCellSizeOf(
- tester.element(find.byType(KeyboardPractice)),
+ expect(tester.takeException(), isNull);
+ final semantics = tester.ensureSemantics();
+ try {
+ await tester.pump();
+ final first = keyboardLessons(map).first;
+ final node = tester
+ .getSemantics(
+ find.byKey(
+ ValueKey('practice-${first.context.name}-${first.command}'),
+ ),
+ )
+ .getSemanticsData();
+ expect(node.label, '${first.label}, ${first.keys}');
+ expect(node.value, 'Not practiced');
+ expect(node.hasAction(ui.SemanticsAction.tap), isTrue);
+ } finally {
+ semantics.dispose();
+ }
+ Future<void> snap(String name) => capture(
+ tester,
+ boundary,
+ '$name-${brightness.name}-${size.width.toInt()}',
);
- await key(tester, LogicalKeyboardKey.arrowDown, shift: true);
- expect(scrolling.offset, closeTo(cell.height, .01));
- await key(tester, LogicalKeyboardKey.arrowUp, shift: true);
- expect(scrolling.offset, 0);
- await key(tester, LogicalKeyboardKey.keyJ, alt: true);
- expect(scrolling.offset, greaterThan(cell.height));
- await key(tester, LogicalKeyboardKey.keyK, alt: true);
- expect(scrolling.offset, 0);
- }
- expect(storage.values.values.any((v) => v.contains('swarm.new')), isTrue);
- await tester.pumpWidget(const SizedBox());
- });
+
+ await snap('practice-list');
+ await openLesson(tester, 'New Tab');
+ await snap('practice-key');
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await snap('practice-result');
+ if (size.width < 500) {
+ final details = tester.widget<SingleChildScrollView>(
+ find.byType(SingleChildScrollView),
+ );
+ final scrolling = details.controller!;
+ expect(scrolling.position.maxScrollExtent, greaterThan(0));
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(scrolling.offset, greaterThan(0));
+ await snap('practice-read');
+ await key(tester, LogicalKeyboardKey.pageUp);
+ expect(scrolling.offset, 0);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await key(tester, LogicalKeyboardKey.escape);
+ await openLesson(tester, 'New Pane');
+ expect(scrolling.offset, 0);
+ await key(tester, LogicalKeyboardKey.escape);
+ await openLesson(tester, 'Next result');
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ final cell = terminalCellSizeOf(
+ tester.element(find.byType(KeyboardPractice)),
+ );
+ await key(tester, LogicalKeyboardKey.arrowDown, shift: true);
+ expect(scrolling.offset, closeTo(cell.height, .01));
+ await key(tester, LogicalKeyboardKey.arrowUp, shift: true);
+ expect(scrolling.offset, 0);
+ await key(tester, LogicalKeyboardKey.keyJ, alt: true);
+ expect(scrolling.offset, greaterThan(cell.height));
+ await key(tester, LogicalKeyboardKey.keyK, alt: true);
+ expect(scrolling.offset, 0);
+ }
+ expect(
+ storage.values.values.any((v) => v.contains('swarm.new')),
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ for (final command in [
+ 'agent.new',
+ 'creation.project',
+ 'creation.project_existing',
+ 'creation.project_browse',
+ 'creation.project_recent_1',
+ 'creation.task',
+ 'creation.options',
+ 'picker.more_options',
+ ]) {
+ final label = harnessCommandById[command]!.label;
+ await openLesson(tester, label);
+ switch (command) {
+ case 'agent.new':
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ case 'creation.project_browse':
+ await key(tester, LogicalKeyboardKey.keyO, ctrl: true);
+ case 'picker.more_options':
+ await key(tester, LogicalKeyboardKey.period, cmd: true);
+ default:
+ await tester.enterText(
+ find.byKey(const ValueKey('practice-command')),
+ label,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ }
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('practice-completed')),
+ findsOneWidget,
+ );
+ expect(find.text(label), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(filter, findsOneWidget);
+ }
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
}
testWidgets(
diff --git a/desktop/test/keymap_runtime_test.dart b/desktop/test/keymap_runtime_test.dart
index b5552249e..78ca29c06 100644
--- a/desktop/test/keymap_runtime_test.dart
+++ b/desktop/test/keymap_runtime_test.dart
@@ -95,7 +95,7 @@ Future<void> tabToResult(WidgetTester tester, {String? id}) async {
void main() {
testWidgets(
- 'New Harness remapped navigation works in both fields and choices',
+ 'New Harness uses Tab for controls and remapped navigation in choices',
(tester) async {
final previousEntry = newHarnessOpensInBox;
newHarnessOpensInBox = true;
@@ -119,18 +119,7 @@ void main() {
final box = tester
.widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
- bool selected(String row) =>
- tester
- .widget<Semantics>(find.byKey(ValueKey('new-harness-field-$row')))
- .properties
- .selected ==
- true;
- await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
- expect(selected('agent'), isTrue);
- await key(tester, LogicalKeyboardKey.keyK, ctrl: true);
- expect(selected('start'), isTrue);
- await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
- await key(tester, LogicalKeyboardKey.enter);
+ await openLaunchRow(tester, 'agent');
expect(box.field, NewHarnessField.harness);
final cursor = box.cursor;
final engine = box.engine;
@@ -139,21 +128,37 @@ void main() {
await key(tester, LogicalKeyboardKey.keyK, ctrl: true);
expect(box.cursor, cursor);
expect(box.engine, engine);
- // Remapped Tab switches panes without walking rows or applying a choice.
+ // Remapped reverse Tab leaves choices without applying the highlight.
await key(tester, LogicalKeyboardKey.keyH, ctrl: true);
expect(harnessChoicesActive(tester), isFalse);
- expect(selected('agent'), isTrue);
expect(box.engine, engine);
- await key(tester, LogicalKeyboardKey.keyL, ctrl: true);
+ await openLaunchRow(tester, 'agent');
expect(harnessChoicesActive(tester), isTrue);
expect(box.engine, engine);
await key(tester, LogicalKeyboardKey.escape);
- await focusLaunchRow(tester, 'advanced');
- final expanded = box.advancedOpen;
- await key(tester, LogicalKeyboardKey.arrowRight);
- expect(box.advancedOpen, !expanded);
- await key(tester, LogicalKeyboardKey.arrowLeft);
- expect(box.advancedOpen, expanded);
+ await focusLaunchRow(tester, 'model');
+ final model = box.modelLabel;
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.model);
+ expect(harnessChoicesActive(tester), isTrue);
+ // Model is now a direct control. Remapped forward Tab dismisses its
+ // chooser and continues to Approvals without changing the model.
+ await key(tester, LogicalKeyboardKey.keyL, ctrl: true);
+ expect(harnessChoicesActive(tester), isFalse);
+ expect(box.modelLabel, model);
+ var approvalsFocused = false;
+ FocusManager.instance.primaryFocus?.context?.visitAncestorElements((e) {
+ approvalsFocused =
+ e.widget.key == const ValueKey('new-harness-field-approvals');
+ return !approvalsFocused;
+ });
+ expect(approvalsFocused, isTrue);
+ await focusLaunchRow(tester, 'model');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(harnessChoicesActive(tester), isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(harnessChoicesActive(tester), isFalse);
+ expect(box.modelLabel, model);
expect(app.panes, isEmpty);
await tester.pumpWidget(const SizedBox());
},
diff --git a/desktop/test/launch_preferences_test.dart b/desktop/test/launch_preferences_test.dart
new file mode 100644
index 000000000..652a6ccd3
--- /dev/null
+++ b/desktop/test/launch_preferences_test.dart
@@ -0,0 +1,1058 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/agent_preference.dart';
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/core/git_worktree.dart';
+import 'package:harness/core/permission_modes.dart';
+import 'package:harness/core/project_history.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/mixed_agents.dart';
+import 'swarm_state_test.dart' show MemoryStore, createApp;
+
+const _agentKey = 'new_harness_preferences_v1';
+const _projectKey = 'new_agent_projects_v1';
+
+class _Store extends MemoryStore {
+ final pendingReads = <String, Completer<String?>>{};
+ final writes = <(String, String)>[];
+ bool failWrites = false;
+
+ @override
+ Future<String?> read(String key) =>
+ pendingReads[key]?.future ?? super.read(key);
+
+ @override
+ Future<void> write(String key, String value) async {
+ writes.add((key, value));
+ if (failWrites) throw StateError('Fixture storage unavailable');
+ await super.write(key, value);
+ }
+}
+
+const _git = <String, dynamic>{
+ 'isGit': true,
+ 'branch': 'feature',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ {'ref': 'refs/heads/feature', 'name': 'feature'},
+ ],
+};
+
+class _Connection extends WsConn {
+ _Connection(String machine)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: machine,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final creates = <Map<String, dynamic>>[];
+ final gitAnswers = <String, Map<String, dynamic>>{};
+ Map<String, dynamic>? failure;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ switch (type) {
+ case 'engines_probe':
+ return {
+ 'engines': [
+ for (final engine in kEnginePermissionModes.keys)
+ {'engine': engine, 'installed': true},
+ ],
+ };
+ case 'dsh_list':
+ return {'dsh': []};
+ case 'fs_list_dir':
+ return {'path': '/home/user', 'entries': []};
+ case 'git_project_info':
+ return gitAnswers[payload['path']] ??
+ (payload['path'] == '/plain' ? {'isGit': false} : _git);
+ case 'codex_profiles_list':
+ return {'profiles': []};
+ case 'agent_create':
+ creates.add(Map.of(payload));
+ if (failure != null) {
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'failed',
+ ...failure!,
+ };
+ }
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'created-${creates.length}',
+ 'name': 'Created',
+ 'engine': payload['engine'],
+ 'terminalAvailable': true,
+ 'project': {
+ 'name': 'repo',
+ 'cwd': payload['cwd'] ?? '/worktrees/repo/new-task',
+ },
+ },
+ };
+ default:
+ return {};
+ }
+ }
+}
+
+class _Fixture {
+ _Fixture({MemoryStore? storage, bool machines = false}) {
+ app = createApp(
+ store: storage,
+ connectionForTest: (id) =>
+ connections.putIfAbsent(id, () => _Connection(id)),
+ connected: true,
+ );
+ if (machines) seedMixedAgents(app);
+ addTearDown(app.dispose);
+ }
+
+ late final AppNotifier app;
+ final connections = <String, _Connection>{};
+
+ NewHarnessController open({
+ String machine = 'm',
+ String? engine = 'codex',
+ String folder = '/repo',
+ NewHarnessDraft? draft,
+ bool desktop = false,
+ }) {
+ final box = NewHarnessController(
+ app,
+ machineId: machine,
+ engine: engine,
+ folder: folder,
+ draft: draft,
+ );
+ box.useDesktopChoices(desktop);
+ addTearDown(box.dispose);
+ return box;
+ }
+}
+
+Future<void> _settle() => Future<void>.delayed(Duration.zero);
+
+void _mode(NewHarnessController box, String mode) {
+ box.focusField(NewHarnessField.mode);
+ expect(box.field, NewHarnessField.mode);
+ box.accept(box.options.singleWhere((row) => row.id == mode));
+}
+
+void _engine(NewHarnessController box, String engine) {
+ box.focusField(NewHarnessField.agent);
+ box.accept(box.options.singleWhere((row) => row.id == engine));
+ expect(box.engine, engine);
+}
+
+void _machine(NewHarnessController box, String machine) {
+ box.focusField(NewHarnessField.machine);
+ box.accept(box.options.singleWhere((row) => row.id == machine));
+ expect(box.machineId, machine);
+}
+
+String _storedModes(Map<String, Object?> modes) =>
+ jsonEncode({'engine': 'codex', 'permissionsByEngine': modes});
+
+String _storedWorktrees(Map<String, Map<String, Object?>> machines) =>
+ jsonEncode({
+ for (final entry in machines.entries)
+ entry.key: {'worktrees': entry.value},
+ });
+
+void main() {
+ test(
+ 'explicit agent defaults persist without inventing a recent launch',
+ () async {
+ final storage = _Store();
+ final preferences = AgentPreference(storage);
+ await preferences.remember('grok');
+ await preferences.selectLaunch('claude', harnessId: 'autonomous/blender');
+ await preferences.selectLaunch('codex', harnessId: 'autonomous/blender');
+ final restored = AgentPreference(storage);
+ await restored.load();
+ expect(restored.harness, 'autonomous/blender');
+ expect(restored.value, 'codex');
+ expect(restored.engineFor('autonomous/blender'), 'codex');
+ expect(restored.recentChoices, ['grok']);
+ await restored.selectLaunch('claude');
+ expect(restored.harness, isNull);
+ expect(restored.engineFor(null), 'claude');
+ expect(restored.engineFor('autonomous/blender'), 'codex');
+ },
+ );
+
+ test('desktop remembers selected agent and repo before launching', () async {
+ final storage = _Store();
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open(desktop: true);
+ await _settle();
+ _engine(box, 'claude');
+ box.setFolder('/chosen/project');
+ await _settle();
+ expect(fixture.app.agentPreference.value, 'claude');
+ expect(fixture.app.projectHistory.selected('m'), '/chosen/project');
+ expect(fixture.connections.values.expand((c) => c.creates), isEmpty);
+ final next = fixture.open(engine: null, desktop: true);
+ await _settle();
+ expect(next.engine, 'claude');
+ });
+
+ test(
+ 'desktop defaults to main with saved worktree off and sends that branch',
+ () async {
+ final fixture = _Fixture();
+ await fixture.app.projectHistory.selectWorktree('m', '/repo', false);
+ final box = fixture.open(desktop: true);
+ await _settle();
+ expect(box.worktree, isFalse);
+ expect(box.branchRef, 'refs/heads/main');
+ expect(box.projectFolderRequest!.branchRef, 'refs/heads/main');
+ box.focusField(NewHarnessField.branch);
+ box.accept(
+ box.options.singleWhere((row) => row.id == 'refs/heads/feature'),
+ );
+ final restored = fixture.open(draft: box.draft, desktop: true);
+ final fresh = fixture.open(desktop: true);
+ await _settle();
+ expect(restored.branchRef, 'refs/heads/feature');
+ expect(fresh.branchRef, 'refs/heads/main');
+ expect(await fresh.create(), NewHarnessOutcome.created);
+ expect(
+ fixture.connections['m']!.creates.single['branchRef'],
+ 'refs/heads/main',
+ );
+ },
+ );
+
+ test('desktop does not substitute a remote or different branch for missing local main', () async {
+ final fixture = _Fixture();
+ await fixture.app.projectHistory.selectWorktree('m', '/repo', false);
+ final connection = fixture.connections.putIfAbsent(
+ 'm',
+ () => _Connection('m'),
+ );
+ connection.gitAnswers['/repo'] = {
+ ..._git,
+ 'branches': [
+ {'ref': 'refs/heads/feature', 'name': 'feature'},
+ {
+ 'ref': 'refs/remotes/origin/main',
+ 'name': 'origin/main',
+ 'remote': true,
+ },
+ ],
+ };
+ final box = fixture.open(desktop: true);
+ await _settle();
+ expect(box.branchRef, isNull);
+ expect(box.requiredChoice?.field, NewHarnessField.branch);
+ expect(box.branchLabel, 'main · unavailable');
+ box.toggleWorktree();
+ expect(box.branchRef, 'refs/remotes/origin/main');
+ });
+
+ test(
+ 'launch recency interleaves harnesses and agents across reloads',
+ () async {
+ final storage = _Store();
+ final preferences = AgentPreference(storage);
+ await preferences.remember('grok');
+ await preferences.remember('codex', harnessId: 'autonomous/blender');
+ await preferences.remember('cursor');
+ await preferences.remember('codex', harnessId: 'autonomous/rdkit');
+ await preferences.remember('grok');
+ final restored = AgentPreference(storage);
+ await restored.load();
+ expect(restored.recentChoices, [
+ 'grok',
+ 'autonomous/rdkit',
+ 'cursor',
+ 'autonomous/blender',
+ ]);
+ expect(restored.recentChoices, isNot(contains('codex')));
+ expect(restored.engineFor('autonomous/rdkit'), 'codex');
+ },
+ );
+
+ test('old launch history migrates with the last used choice first', () async {
+ final storage = _Store()
+ ..values[_agentKey] = jsonEncode({
+ 'engine': 'cursor',
+ 'harness': null,
+ 'agents': ['cursor', 'codex'],
+ 'harnesses': ['autonomous/blender'],
+ });
+ final preferences = AgentPreference(storage);
+ await preferences.load();
+ expect(preferences.recentChoices, [
+ 'cursor',
+ 'autonomous/blender',
+ 'codex',
+ ]);
+ await preferences.remember('grok');
+ final restored = AgentPreference(storage);
+ await restored.load();
+ expect(restored.recentChoices, [
+ 'grok',
+ 'cursor',
+ 'autonomous/blender',
+ 'codex',
+ ]);
+ });
+
+ test(
+ 'desktop keeps every coding agent above recent specialized harnesses',
+ () async {
+ final fixture = _Fixture();
+ final box = fixture.open();
+ await _settle();
+ const featured = [
+ 'autonomous/blender',
+ 'autonomous/circuitjs',
+ 'autonomous/godogen',
+ 'autonomous/mujoco',
+ 'autonomous/rdkit',
+ 'autonomous/strudel',
+ 'autonomous/typst',
+ ];
+ fixture.app.machineStates['m']!.dsh.replace([
+ for (final id in [...featured, 'autonomous/manim'])
+ DshEntry(id: id, name: id, engine: 'codex'),
+ ]);
+ box.useDesktopChoices(true);
+ box.focusField(NewHarnessField.harness);
+ const leading = [
+ 'claude',
+ 'codex',
+ 'cursor',
+ 'copilot',
+ 'grok',
+ 'opencode',
+ ];
+ final engines = allEngines.map((engine) => engine.id).toSet();
+ final initial = box.options.map((option) => option.id).toList();
+ expect(initial.take(leading.length), leading);
+ expect(initial.take(engines.length).toSet(), engines);
+ expect(initial.skip(engines.length).take(featured.length), featured);
+ expect(initial.last, kTerminalEngine);
+ await fixture.app.agentPreference.remember(
+ 'codex',
+ harnessId: 'autonomous/rdkit',
+ );
+ await fixture.app.agentPreference.remember('cursor');
+ await fixture.app.agentPreference.remember(
+ 'codex',
+ harnessId: 'removed/tool',
+ );
+ box.focusField(NewHarnessField.launch);
+ box.focusField(NewHarnessField.harness);
+ final ids = box.options.map((o) => o.id).toList();
+ expect(ids.take(engines.length), initial.take(engines.length));
+ expect(ids.skip(engines.length).take(featured.length), [
+ 'autonomous/rdkit',
+ ...featured.where((id) => id != 'autonomous/rdkit'),
+ ]);
+ expect(ids.toSet().length, ids.length);
+ expect(ids, isNot(contains('removed/tool')));
+ expect(ids, contains('autonomous/manim'));
+ expect(ids.last, kTerminalEngine);
+ // A search for a specialized harness still brings that match to the top.
+ box.setQuery('rdkit');
+ expect(box.options.first.id, 'autonomous/rdkit');
+ box.setQuery('');
+ expect(box.options.map((option) => option.id), ids);
+ },
+ );
+
+ group('approval preference storage', () {
+ test(
+ 'each engine keeps its last explicit supported mode across reloads',
+ () async {
+ final storage = _Store();
+ final preferences = AgentPreference(storage);
+ await preferences.remember('claude', harnessId: 'studio/agent');
+ await preferences.setAdvanced(true);
+ final expected = <String, String>{};
+ for (final entry in kEnginePermissionModes.entries) {
+ for (final mode in entry.value) {
+ await preferences.selectPermissionMode(entry.key, mode.id);
+ expected[entry.key] = mode.id;
+ final reloaded = AgentPreference(storage);
+ await reloaded.load();
+ for (final choice in expected.entries) {
+ expect(reloaded.permissionModeFor(choice.key), choice.value);
+ }
+ expect(reloaded.value, 'claude');
+ expect(reloaded.harness, 'studio/agent');
+ expect(reloaded.recent, ['claude']);
+ expect(reloaded.engineFor('studio/agent'), 'claude');
+ expect(reloaded.advancedOpen, isTrue);
+ }
+ }
+ },
+ );
+
+ test(
+ 'malformed and unsupported stored modes never become approvals',
+ () async {
+ for (final raw in [
+ 'not json',
+ '[]',
+ '{"permissionsByEngine":[]}',
+ _storedModes({
+ 'codex': 'plan',
+ 'claude': 'readOnly',
+ 'cursor': 'full',
+ 'opencode': true,
+ 'terminal': 'full',
+ 'retired': 'full',
+ }),
+ ]) {
+ final storage = _Store()..values[_agentKey] = raw;
+ final preferences = AgentPreference(storage);
+ await preferences.load();
+ for (final engine in [
+ ...kEnginePermissionModes.keys,
+ 'terminal',
+ 'retired',
+ ]) {
+ expect(preferences.permissionModeFor(engine), isNull, reason: raw);
+ }
+ }
+ final storage = _Store()
+ ..values[_agentKey] = _storedModes({
+ 'codex': 'ask',
+ 'claude': 'plan',
+ });
+ final preferences = AgentPreference(storage);
+ await preferences.load();
+ await preferences.selectPermissionMode('codex', 'plan');
+ await preferences.selectPermissionMode('terminal', 'full');
+ expect(preferences.permissionModeFor('codex'), 'ask');
+ expect(preferences.permissionModeFor('claude'), 'plan');
+ expect(storage.writes, isEmpty);
+ },
+ );
+
+ test(
+ 'new explicit modes win over a delayed read and serialize in order',
+ () async {
+ final read = Completer<String?>();
+ final storage = _Store()..pendingReads[_agentKey] = read;
+ final preferences = AgentPreference(storage);
+ final loading = preferences.load();
+ final first = preferences.selectPermissionMode('codex', 'readOnly');
+ final other = preferences.selectPermissionMode('claude', 'plan');
+ final last = preferences.selectPermissionMode('codex', 'ask');
+ read.complete(_storedModes({'codex': 'full', 'claude': 'auto'}));
+ await Future.wait([loading, first, other, last]);
+ expect(preferences.permissionModeFor('codex'), 'ask');
+ expect(preferences.permissionModeFor('claude'), 'plan');
+ storage.pendingReads.clear();
+ final reloaded = AgentPreference(storage);
+ await reloaded.load();
+ expect(reloaded.permissionModeFor('codex'), 'ask');
+ expect(reloaded.permissionModeFor('claude'), 'plan');
+ },
+ );
+
+ test(
+ 'unavailable storage leaves explicit choices usable in this session',
+ () async {
+ for (final storage in <_Store?>[null, _Store()..failWrites = true]) {
+ final preferences = AgentPreference(storage);
+ await preferences.selectPermissionMode('codex', 'readOnly');
+ await preferences.selectPermissionMode('claude', 'plan');
+ expect(preferences.permissionModeFor('codex'), 'readOnly');
+ expect(preferences.permissionModeFor('claude'), 'plan');
+ }
+ },
+ );
+ });
+
+ group('worktree preference storage', () {
+ test('choices are isolated by machine and path without changing project history', () async {
+ final storage = _Store();
+ final history = ProjectHistory(storage);
+ await history.select('m', '/selected');
+ await history.selectWorktree('m', '/repo', false);
+ await history.selectWorktree('m', '/other', true);
+ await history.selectWorktree('studio', '/repo', true);
+ final reloaded = ProjectHistory(storage);
+ await reloaded.load();
+ expect(reloaded.worktreeFor('m', '/repo'), isFalse);
+ expect(reloaded.worktreeFor('m', '/other'), isTrue);
+ expect(reloaded.worktreeFor('studio', '/repo'), isTrue);
+ expect(reloaded.worktreeFor('studio', '/other'), isNull);
+ expect(reloaded.worktreeFor('m', '/repo-extra'), isNull);
+ expect(reloaded.selected('m'), '/selected');
+ expect(reloaded.recent('m'), ['/selected']);
+ expect(reloaded.hasSelection('studio'), isFalse);
+ expect(reloaded.recent('studio'), isEmpty);
+ });
+
+ test(
+ 'corrupt values and invalid paths cannot create remembered toggles',
+ () async {
+ final invalidPaths = [
+ 'relative',
+ '',
+ '/bad\npath',
+ '/bad\u0000path',
+ '/${'x' * 4096}',
+ ];
+ final storage = _Store()
+ ..values[_projectKey] = _storedWorktrees({
+ 'm': {
+ '/repo': false,
+ '/other': true,
+ '/wrong-string': 'false',
+ '/wrong-int': 0,
+ for (final path in invalidPaths) path: true,
+ },
+ });
+ final history = ProjectHistory(storage);
+ await history.load();
+ for (final path in [...invalidPaths, '/wrong-string', '/wrong-int']) {
+ expect(history.worktreeFor('m', path), isNull);
+ }
+ for (final path in invalidPaths) {
+ await history.selectWorktree('m', path, false);
+ }
+ expect(history.worktreeFor('m', '/repo'), isFalse);
+ expect(history.worktreeFor('m', '/other'), isTrue);
+ expect(storage.writes, isEmpty);
+ for (final raw in ['broken', '[]', '{"m":{"worktrees":[]}}']) {
+ final broken = ProjectHistory(_Store()..values[_projectKey] = raw);
+ await broken.load();
+ expect(broken.worktreeFor('m', '/repo'), isNull);
+ await broken.selectWorktree('m', '/repo', false);
+ expect(broken.worktreeFor('m', '/repo'), isFalse);
+ }
+ },
+ );
+
+ test('rapid choices made during a slow read preserve the latest value and other projects', () async {
+ final read = Completer<String?>();
+ final storage = _Store()..pendingReads[_projectKey] = read;
+ final history = ProjectHistory(storage);
+ final first = history.selectWorktree('m', '/repo', false);
+ final second = history.selectWorktree('m', '/repo', true);
+ final last = history.selectWorktree('m', '/repo', false);
+ read.complete(
+ _storedWorktrees({
+ 'm': {'/repo': true, '/other': false},
+ 'studio': {'/repo': true},
+ }),
+ );
+ await Future.wait([first, second, last]);
+ storage.pendingReads.clear();
+ final reloaded = ProjectHistory(storage);
+ await reloaded.load();
+ expect(reloaded.worktreeFor('m', '/repo'), isFalse);
+ expect(reloaded.worktreeFor('m', '/other'), isFalse);
+ expect(reloaded.worktreeFor('studio', '/repo'), isTrue);
+ });
+
+ test(
+ 'bounded history retains the most recently changed projects',
+ () async {
+ final storage = _Store();
+ final history = ProjectHistory(storage);
+ for (var i = 0; i < 40; i++) {
+ await history.selectWorktree('m', '/repo-$i', false);
+ }
+ await history.selectWorktree('m', '/repo-0', true);
+ await history.selectWorktree('m', '/repo-40', true);
+ final reloaded = ProjectHistory(storage);
+ await reloaded.load();
+ expect(reloaded.worktreeFor('m', '/repo-0'), isTrue);
+ expect(reloaded.worktreeFor('m', '/repo-1'), isNull);
+ expect(reloaded.worktreeFor('m', '/repo-2'), isFalse);
+ expect(reloaded.worktreeFor('m', '/repo-40'), isTrue);
+ },
+ );
+
+ test('storage failures do not undo the visible worktree choice', () async {
+ for (final storage in <_Store?>[null, _Store()..failWrites = true]) {
+ final history = ProjectHistory(storage);
+ await history.selectWorktree('m', '/repo', false);
+ expect(history.worktreeFor('m', '/repo'), isFalse);
+ await history.selectWorktree('m', '/repo', true);
+ expect(history.worktreeFor('m', '/repo'), isTrue);
+ }
+ });
+ });
+
+ group('launch preference behavior', () {
+ test(
+ 'browsing and cancelling approvals does not remember a hovered mode',
+ () async {
+ final storage = _Store()
+ ..values[_agentKey] = _storedModes({
+ 'codex': 'readOnly',
+ 'claude': 'plan',
+ });
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open();
+ await _settle();
+ expect(box.mode, 'readOnly');
+ box.focusField(NewHarnessField.mode);
+ box.setQuery('full');
+ expect(box.selected!.id, 'full');
+ box.back();
+ expect(box.mode, 'readOnly');
+ expect(
+ fixture.app.agentPreference.permissionModeFor('codex'),
+ 'readOnly',
+ );
+ expect(storage.writes.where((write) => write.$1 == _agentKey), isEmpty);
+ _mode(box, 'ask');
+ await _settle();
+ expect(fixture.connections['m']!.creates, isEmpty);
+ final reloaded = AgentPreference(storage);
+ await reloaded.load();
+ expect(reloaded.permissionModeFor('codex'), 'ask');
+ expect(reloaded.permissionModeFor('claude'), 'plan');
+ expect(
+ reloaded.value,
+ 'codex',
+ reason: 'A permission choice does not count as a launch.',
+ );
+ },
+ );
+
+ test('switching engines restores independent approval modes, including after Terminal', () async {
+ final storage = _Store()
+ ..values[_agentKey] = _storedModes({
+ 'codex': 'readOnly',
+ 'claude': 'plan',
+ });
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open();
+ await _settle();
+ expect(box.mode, 'readOnly');
+ _engine(box, 'claude');
+ expect(box.mode, 'plan');
+ _mode(box, 'acceptEdits');
+ _engine(box, 'codex');
+ expect(box.mode, 'readOnly');
+ _mode(box, 'ask');
+ _engine(box, 'terminal');
+ expect(box.hasModes, isFalse);
+ _engine(box, 'claude');
+ expect(box.mode, 'acceptEdits');
+ _engine(box, 'codex');
+ expect(box.mode, 'ask');
+ await _settle();
+ final next = fixture.open(engine: 'claude');
+ await _settle();
+ expect(next.mode, 'acceptEdits');
+ expect(fixture.app.agentPreference.permissionModeFor('terminal'), isNull);
+ });
+
+ test(
+ 'previewed agent approvals stay separate until explicitly accepted',
+ () async {
+ final storage = _Store()
+ ..values[_agentKey] = _storedModes({
+ 'codex': 'readOnly',
+ 'claude': 'plan',
+ });
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open();
+ await _settle();
+ expect(
+ box
+ .agentSettingsFor('claude')
+ .singleWhere(
+ (row) => row.id == NewHarnessController.permissionsId,
+ )
+ .detail,
+ 'Plan first',
+ );
+ box.focusField(NewHarnessField.agent);
+ box.openAgentSetting('claude', NewHarnessController.permissionsId);
+ expect(box.selected!.id, 'plan');
+ box.setQuery('skip all');
+ expect(box.selected!.id, 'full');
+ box.back();
+ expect(box.engine, 'codex');
+ expect(box.mode, 'readOnly');
+ box.openAgentSetting('claude', NewHarnessController.permissionsId);
+ box.accept(box.options.singleWhere((row) => row.id == 'acceptEdits'));
+ await _settle();
+ expect(box.engine, 'claude');
+ expect(box.mode, 'acceptEdits');
+ expect(
+ fixture.app.agentPreference.permissionModeFor('claude'),
+ 'acceptEdits',
+ );
+ expect(
+ fixture.app.agentPreference.permissionModeFor('codex'),
+ 'readOnly',
+ );
+ expect(fixture.connections['m']!.creates, isEmpty);
+ },
+ );
+
+ test('unsupported remembered modes use the engine default and never cross engines', () async {
+ final storage = _Store()
+ ..values[_agentKey] = _storedModes({
+ 'codex': 'plan',
+ 'claude': 'readOnly',
+ });
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open();
+ await _settle();
+ expect(box.mode, kDefaultPermissionMode);
+ _engine(box, 'claude');
+ expect(box.mode, kDefaultPermissionMode);
+ expect(fixture.app.agentPreference.permissionModeFor('codex'), isNull);
+ expect(fixture.app.agentPreference.permissionModeFor('claude'), isNull);
+ });
+
+ test('late approval reads update the form but cannot replace a new explicit choice', () async {
+ for (final chooseBeforeRead in [false, true]) {
+ final read = Completer<String?>();
+ final storage = _Store()..pendingReads[_agentKey] = read;
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open();
+ await _settle();
+ if (chooseBeforeRead) _mode(box, 'readOnly');
+ final observed = <String>[];
+ box.addListener(() => observed.add(box.mode));
+ read.complete(_storedModes({'codex': 'full', 'claude': 'plan'}));
+ await _settle();
+ final expected = chooseBeforeRead ? 'readOnly' : 'full';
+ expect(box.mode, expected);
+ expect(observed, contains(expected));
+ expect(
+ fixture.app.agentPreference.permissionModeFor('codex'),
+ expected,
+ );
+ }
+ });
+
+ test(
+ 'late worktree reads repaint and preserve a toggle made during loading',
+ () async {
+ for (final chooseBeforeRead in [false, true]) {
+ final read = Completer<String?>();
+ final storage = _Store()..pendingReads[_projectKey] = read;
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open();
+ await _settle();
+ expect(box.worktree, isTrue);
+ if (chooseBeforeRead) box.toggleWorktree();
+ final observed = <bool>[];
+ box.addListener(() => observed.add(box.worktree));
+ read.complete(
+ _storedWorktrees({
+ 'm': {'/repo': chooseBeforeRead},
+ }),
+ );
+ await _settle();
+ expect(box.worktree, isFalse);
+ expect(observed, contains(false));
+ expect(fixture.app.projectHistory.worktreeFor('m', '/repo'), isFalse);
+ expect(box.branchRef, 'refs/heads/feature');
+ }
+ },
+ );
+
+ test('worktree follows the selected machine and project and remembers cancelled edits', () async {
+ final storage = _Store();
+ final fixture = _Fixture(storage: storage, machines: true);
+ final box = fixture.open();
+ await _settle();
+ box.toggleWorktree();
+ expect(box.worktree, isFalse);
+ await _settle();
+ box.setFolder('/other');
+ await _settle();
+ expect(box.worktree, isTrue);
+ box.setFolder('/repo');
+ await _settle();
+ expect(box.worktree, isFalse);
+ _machine(box, 'studio');
+ box.setFolder('/repo');
+ await _settle();
+ expect(
+ box.worktree,
+ isTrue,
+ reason: 'The same path belongs to a different host.',
+ );
+ box.toggleWorktree();
+ box.toggleWorktree();
+ await _settle();
+ _machine(box, 'm');
+ await _settle();
+ expect(box.project.folder, '/repo');
+ expect(box.worktree, isFalse);
+ final next = fixture.open();
+ await _settle();
+ expect(next.worktree, isFalse);
+ expect(
+ fixture.connections.values.expand((conn) => conn.creates),
+ isEmpty,
+ );
+ final reloaded = ProjectHistory(storage);
+ await reloaded.load();
+ expect(reloaded.worktreeFor('m', '/repo'), isFalse);
+ expect(reloaded.worktreeFor('studio', '/repo'), isTrue);
+ expect(reloaded.hasSelection('m'), isFalse);
+ });
+
+ test('a draft keeps its reviewed approvals and worktree over later remembered defaults', () async {
+ final storage = _Store()
+ ..values[_agentKey] = _storedModes({'codex': 'readOnly'})
+ ..values[_projectKey] = _storedWorktrees({
+ 'm': {'/repo': false},
+ });
+ final fixture = _Fixture(storage: storage);
+ final original = fixture.open();
+ await _settle();
+ final draft = original.draft;
+ final reviewedRequest = original.projectFolderRequest!.payload;
+ expect(draft.permissionMode, 'readOnly');
+ expect(draft.worktree, isFalse);
+ expect(draft.projectFolderRequest!.payload, reviewedRequest);
+ await fixture.app.agentPreference.selectPermissionMode('codex', 'full');
+ await fixture.app.projectHistory.selectWorktree('m', '/repo', true);
+ final restored = fixture.open(draft: draft);
+ await _settle();
+ expect(restored.mode, 'readOnly');
+ expect(restored.worktree, isFalse);
+ expect(restored.projectFolderRequest!.payload, reviewedRequest);
+ final fresh = fixture.open();
+ await _settle();
+ expect(fresh.mode, 'full');
+ expect(fresh.worktree, isTrue);
+ });
+
+ test(
+ 'explicit draft values win even when preference reads finish afterwards',
+ () async {
+ final agentRead = Completer<String?>();
+ final projectRead = Completer<String?>();
+ final storage = _Store()
+ ..pendingReads[_agentKey] = agentRead
+ ..pendingReads[_projectKey] = projectRead;
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open(
+ draft: NewHarnessDraft(
+ machineId: 'm',
+ engine: 'codex',
+ project: const NewHarnessProject.folder('/repo'),
+ task: 'Review without making changes',
+ permissionMode: 'readOnly',
+ worktree: true,
+ gitProject: GitProjectInfo.fromJson(_git),
+ ),
+ );
+ agentRead.complete(_storedModes({'codex': 'full'}));
+ projectRead.complete(
+ _storedWorktrees({
+ 'm': {'/repo': false},
+ }),
+ );
+ await _settle();
+ expect(box.mode, 'readOnly');
+ expect(box.worktree, isTrue);
+ expect(box.task, 'Review without making changes');
+ expect(box.projectFolderRequest!.payload['projectSource'], 'worktree');
+ },
+ );
+
+ test('launching a restored draft does not redefine last explicit approval or worktree choices', () async {
+ final storage = _Store()
+ ..values[_agentKey] = _storedModes({'codex': 'ask'})
+ ..values[_projectKey] = _storedWorktrees({
+ 'm': {'/repo': true},
+ });
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open(
+ draft: NewHarnessDraft(
+ machineId: 'm',
+ engine: 'codex',
+ project: const NewHarnessProject.folder('/repo'),
+ task: '',
+ permissionMode: 'readOnly',
+ worktree: false,
+ gitProject: GitProjectInfo.fromJson(_git),
+ ),
+ );
+ await _settle();
+ expect(await box.create(), NewHarnessOutcome.created);
+ await _settle();
+ final payload = fixture.connections['m']!.creates.single;
+ expect(payload['permissionMode'], 'readOnly');
+ expect(payload['projectSource'], 'branch');
+ final preferences = AgentPreference(storage);
+ final history = ProjectHistory(storage);
+ await Future.wait([preferences.load(), history.load()]);
+ expect(preferences.permissionModeFor('codex'), 'ask');
+ expect(history.worktreeFor('m', '/repo'), isTrue);
+ });
+
+ test(
+ 'non-Git and Terminal cannot overwrite the remembered project toggle',
+ () async {
+ final storage = _Store()
+ ..values[_projectKey] = _storedWorktrees({
+ 'm': {'/repo': false},
+ });
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open();
+ await _settle();
+ _engine(box, 'terminal');
+ await _settle();
+ expect(box.canUseWorktree, isFalse);
+ box.toggleWorktree();
+ _engine(box, 'codex');
+ await _settle();
+ expect(box.worktree, isFalse);
+ box.setFolder('/plain');
+ await _settle();
+ expect(box.canUseWorktree, isFalse);
+ box.toggleWorktree();
+ expect(fixture.app.projectHistory.worktreeFor('m', '/plain'), isNull);
+ expect(fixture.app.projectHistory.worktreeFor('m', '/repo'), isFalse);
+ expect(
+ storage.writes.where((write) => write.$1 == _projectKey),
+ isEmpty,
+ );
+ },
+ );
+
+ for (final worktree in [false, true]) {
+ test(
+ 'reload sends exact remembered approvals and worktree=$worktree at launch',
+ () async {
+ final storage = _Store();
+ await AgentPreference(storage)
+ .selectPermissionMode('codex', 'readOnly');
+ await ProjectHistory(storage).selectWorktree('m', '/repo', worktree);
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open();
+ await _settle();
+ expect(box.mode, 'readOnly');
+ expect(box.worktree, worktree);
+ final request = box.projectFolderRequest!.payload;
+ expect(
+ request,
+ worktree
+ ? {
+ 'projectSource': 'worktree',
+ 'gitSource': '/repo',
+ 'branchRef': 'refs/heads/main',
+ 'branchName': box.placeholder,
+ 'branchMode': 'placeholder',
+ }
+ : {
+ 'projectSource': 'branch',
+ 'gitSource': '/repo',
+ 'branchRef': 'refs/heads/feature',
+ },
+ );
+ expect(await box.create(), NewHarnessOutcome.created);
+ final payload = fixture.connections['m']!.creates.single;
+ expect(payload, containsPair('engine', 'codex'));
+ expect(payload, containsPair('permissionMode', 'readOnly'));
+ expect(payload, containsPair('bypassPermission', false));
+ expect({...payload}..remove('creationId'), {
+ 'engine': 'codex',
+ ...request,
+ 'bypassPermission': false,
+ 'permissionMode': 'readOnly',
+ });
+ },
+ );
+ }
+
+ test('linked worktree entry uses the main project preference and current main branch', () async {
+ final storage = _Store()
+ ..values[_projectKey] = _storedWorktrees({
+ 'm': {'/repo': false},
+ });
+ final fixture = _Fixture(storage: storage);
+ final connection = fixture.connections.putIfAbsent(
+ 'm',
+ () => _Connection('m'),
+ );
+ connection.gitAnswers['/worktrees/repo/task'] = {
+ ..._git,
+ 'branch': 'task',
+ 'mainFolder': '/repo',
+ 'mainBranch': 'feature',
+ };
+ final box = fixture.open(folder: '/worktrees/repo/task');
+ await _settle();
+ expect(box.project.folder, '/repo');
+ expect(box.worktree, isFalse);
+ expect(box.branchRef, 'refs/heads/feature');
+ expect(box.projectFolderRequest!.payload, {
+ 'projectSource': 'branch',
+ 'gitSource': '/repo',
+ 'branchRef': 'refs/heads/feature',
+ });
+ box.toggleWorktree();
+ await _settle();
+ expect(fixture.app.projectHistory.worktreeFor('m', '/repo'), isTrue);
+ expect(
+ fixture.app.projectHistory.worktreeFor('m', '/worktrees/repo/task'),
+ isNull,
+ );
+ });
+
+ test('failed worktree preparation retry does not persist its automatic worktree-off state', () async {
+ final storage = _Store();
+ await ProjectHistory(storage).selectWorktree('m', '/repo', true);
+ final fixture = _Fixture(storage: storage);
+ final connection = fixture.connections.putIfAbsent(
+ 'm',
+ () => _Connection('m'),
+ );
+ connection.gitAnswers['/worktrees/repo/task'] = {
+ ..._git,
+ 'branch': 'task',
+ 'mainFolder': '/repo',
+ 'mainBranch': 'feature',
+ };
+ connection.failure = {
+ 'preparedFolder': '/worktrees/repo/task',
+ 'failure': {'code': 'TMUX_UNAVAILABLE'},
+ };
+ final box = fixture.open();
+ await _settle();
+ expect(await box.create(), NewHarnessOutcome.failed);
+ await _settle();
+ expect(box.project.folder, '/repo');
+ expect(box.worktree, isFalse);
+ expect(box.branchRef, 'refs/heads/task');
+ expect(fixture.app.projectHistory.worktreeFor('m', '/repo'), isTrue);
+ final fresh = fixture.open();
+ await _settle();
+ expect(fresh.worktree, isTrue);
+ expect(fresh.branchRef, 'refs/heads/main');
+ });
+ });
+}
diff --git a/desktop/test/layout_palette_render_test.dart b/desktop/test/layout_palette_render_test.dart
index c6125977c..4f4adfe76 100644
--- a/desktop/test/layout_palette_render_test.dart
+++ b/desktop/test/layout_palette_render_test.dart
@@ -82,7 +82,7 @@ void main() {
Rect card(PanePreset preset) => tester.getRect(
find.ancestor(
of: find.text(preset.label),
- matching: find.byType(Container),
+ matching: find.byType(TextButton),
),
);
for (final preset in choices) {
diff --git a/desktop/test/layout_palette_test.dart b/desktop/test/layout_palette_test.dart
index c4735454e..a84829f10 100644
--- a/desktop/test/layout_palette_test.dart
+++ b/desktop/test/layout_palette_test.dart
@@ -119,7 +119,7 @@ void main() {
tester.getRect(
find.ancestor(
of: find.text(choice.label),
- matching: find.byType(Container),
+ matching: find.byType(TextButton),
),
),
];
diff --git a/desktop/test/link_another_machine_test.dart b/desktop/test/link_another_machine_test.dart
index 5c1260748..d38bf941e 100644
--- a/desktop/test/link_another_machine_test.dart
+++ b/desktop/test/link_another_machine_test.dart
@@ -171,7 +171,7 @@ void main() {
expect(find.text('build-box is linked.'), findsOneWidget);
expect(
find.text(
- 'Already linked. Open its harnesses from New Swarm or New Pane.',
+ 'Already linked. Open its harnesses from New Tab or New Pane.',
),
findsOneWidget,
);
diff --git a/desktop/test/link_machine_dialog_widget_test.dart b/desktop/test/link_machine_dialog_widget_test.dart
index 582cc2f95..a6afce9bf 100644
--- a/desktop/test/link_machine_dialog_widget_test.dart
+++ b/desktop/test/link_machine_dialog_widget_test.dart
@@ -92,7 +92,7 @@ void main() {
cliLink: cliLink ?? PasswordCli(),
);
- testWidgets('shows the terminal password form when no password is set', (
+ testWidgets('shows the password form when no password is set', (
tester,
) async {
final appNotifier = notifier();
@@ -443,7 +443,7 @@ void main() {
await enterPassword(tester);
expect(cli.passwords, ['fixture password']);
expect(tester.takeException(), isNull);
- expect(find.text('esc close').hitTestable(), findsOneWidget);
+ expect(find.text('Close').hitTestable(), findsOneWidget);
},
);
@@ -471,9 +471,7 @@ void main() {
await key(tester, LogicalKeyboardKey.escape);
expect(field(tester, passwordKey).focusNode!.hasFocus, isTrue);
expect(
- find.textContaining(
- RegExp('f8 confirm password', caseSensitive: false),
- ),
+ find.byTooltip(RegExp('Confirm password · f8', caseSensitive: false)),
findsOneWidget,
);
await key(tester, LogicalKeyboardKey.f8);
@@ -499,7 +497,7 @@ void main() {
);
await tester.pump();
expect(
- find.textContaining(RegExp('f4 close', caseSensitive: false)),
+ find.byTooltip(RegExp('Close · f4', caseSensitive: false)),
findsOneWidget,
);
await key(tester, LogicalKeyboardKey.f4);
diff --git a/desktop/test/link_machine_widget_test.dart b/desktop/test/link_machine_widget_test.dart
index 526f627f7..7a8eec597 100644
--- a/desktop/test/link_machine_widget_test.dart
+++ b/desktop/test/link_machine_widget_test.dart
@@ -362,7 +362,7 @@ void main() {
findsOneWidget,
);
expect(find.text('Remote password for remote-mac'), findsOneWidget);
- expect(find.text('enter link machine'), findsOneWidget);
+ expect(find.text('Link machine'), findsOneWidget);
expect(
find.text(
'Your previous harness will reconnect automatically after linking.',
@@ -376,7 +376,7 @@ void main() {
expect(find.text('Machine ID: remote-1'), findsOneWidget);
// The close key guide remains clickable as well as keyboard accessible.
- expect(find.text('esc close'), findsOneWidget);
+ expect(find.text('Close'), findsOneWidget);
notifier.dispose();
});
@@ -396,7 +396,7 @@ void main() {
);
expect(notifier.isLinkPromptDismissed(machine.machineId), isFalse);
- await tester.tap(find.text('esc close'));
+ await tester.tap(find.text('Close'));
await tester.pump();
expect(notifier.isLinkPromptDismissed(machine.machineId), isTrue);
notifier.dispose();
@@ -427,7 +427,7 @@ void main() {
find.byKey(const Key('remote-password-connect-field')),
'correct horse battery staple',
);
- await tester.tap(find.text('enter link machine'));
+ await tester.tap(find.text('Link machine'));
await tester.pumpAndSettle();
expect(connectedPassword, 'correct horse battery staple');
@@ -459,7 +459,7 @@ void main() {
find.byKey(const Key('remote-password-connect-field')),
'wrong-password',
);
- await tester.tap(find.text('enter link machine'));
+ await tester.tap(find.text('Link machine'));
await tester.pumpAndSettle();
expect(find.text('Incorrect password'), findsOneWidget);
diff --git a/desktop/test/local_model_picker_test.dart b/desktop/test/local_model_picker_test.dart
index 55efa0a2b..b22b6b307 100644
--- a/desktop/test/local_model_picker_test.dart
+++ b/desktop/test/local_model_picker_test.dart
@@ -11,6 +11,7 @@ import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/widgets/swarm_resource_preview.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'package:harness/widgets/swarm_switcher.dart';
import 'package:harness/ws/local_cli_discovery.dart';
@@ -266,6 +267,8 @@ void main() {
expect(picker.modelSection(running), ModelSearchSection.local);
expect(picker.modelSection(downloaded), ModelSearchSection.local);
expect(picker.modelSection(download), ModelSearchSection.catalog);
+ picker.move(picker.rows.indexOf(download) - picker.cursor);
+ await tester.pumpAndSettle();
expect(
find.text('Get for ${thisComputerName()} · 64 GB'),
findsOneWidget,
@@ -281,15 +284,12 @@ void main() {
expect(_statusColor(tester, downloaded), isNot(_live));
expect(_status(tester, download), 'Get');
expect(_statusColor(tester, download), isNot(_live));
- expect(
- _statusColor(tester, download),
- _statusColor(tester, downloaded),
- );
+ expect(_statusColor(tester, download), DesktopChrome.selectionDetail);
// Size, then speed — measured while it runs, else the catalog's estimate for this machine.
- expect(_facts(tester, running), ' 25 GB 21 tok/s');
- expect(_facts(tester, download), '5.6 GB ~10 tok/s');
- expect(_facts(tester, downloaded), '7.3 GB ');
+ expect(_facts(tester, running), '25 GB · 21 tok/s');
+ expect(_facts(tester, download), '5.6 GB · ~10 tok/s');
+ expect(_facts(tester, downloaded), '7.3 GB');
// Every row's columns line up: the size, the speed and the word start where the next row's do.
final rightEdges = {
for (final row in [running, downloaded, download])
@@ -321,7 +321,7 @@ void main() {
final picker = await _open(tester, app);
final running = _row(picker, 'Qwen3.6-35B-A3B');
expect(_status(tester, running), SwarmSearchController.inUseWord);
- expect(_statusColor(tester, running), _live);
+ expect(_statusColor(tester, running), DesktopChrome.selectionDetail);
// Cmd-I opens on the model the harness is on.
expect(picker.selected!.id, running.id);
expect(_inPreview('Running · this harness is on it'), findsOneWidget);
@@ -438,7 +438,10 @@ void main() {
expect(picker.usingLabel, 'Downloading 42%…');
expect(find.textContaining('Downloading 42%…'), findsOneWidget);
expect(_status(tester, _row(picker, 'Qwen3.5-9B')), 'Downloading');
- expect(_statusColor(tester, _row(picker, 'Qwen3.5-9B')), _live);
+ expect(
+ _statusColor(tester, _row(picker, 'Qwen3.5-9B')),
+ DesktopChrome.selectionDetail,
+ );
// A longer word does not push its row's columns out of line with a row that says Use.
double factsLeft(String title) => tester
.getTopLeft(
diff --git a/desktop/test/login_screen_test.dart b/desktop/test/login_screen_test.dart
index f11014d73..678715156 100644
--- a/desktop/test/login_screen_test.dart
+++ b/desktop/test/login_screen_test.dart
@@ -81,7 +81,7 @@ void main() {
expect(find.text('Your agents, wherever they run'), findsOneWidget);
expect(find.text('Sign in'), findsOneWidget);
expect(find.byType(LoginFleetMap), findsOneWidget);
- // The real mark, from the bundle — `Icons.memory` used to stand here and
+ // The real mark, from the bundle — `AppIcons.cpu` used to stand here and
// appeared nowhere else in the app.
final logo = tester.widget<Image>(
find.byWidgetPredicate(
diff --git a/desktop/test/machines_manager_keyboard_test.dart b/desktop/test/machines_manager_keyboard_test.dart
index ae693d6a4..86cda5b22 100644
--- a/desktop/test/machines_manager_keyboard_test.dart
+++ b/desktop/test/machines_manager_keyboard_test.dart
@@ -366,10 +366,7 @@ void main() {
{"keys":"f4","command":"picker.cancel","when":"picker"}
]}''');
await tester.pump();
- expect(
- find.textContaining(RegExp('f10 save', caseSensitive: false)),
- findsOneWidget,
- );
+ expect(find.byTooltip('Save · F10'), findsOneWidget);
await key(tester, LogicalKeyboardKey.enter);
expect(app.edits.renames, isEmpty);
await key(tester, LogicalKeyboardKey.f10);
@@ -403,7 +400,7 @@ void main() {
expect(tester.takeException(), isNull);
await _typeOpen(tester, 'rename');
expect(_rename.hitTestable(), findsOneWidget);
- expect(find.text('esc close').hitTestable(), findsOneWidget);
+ expect(find.text('Cancel').hitTestable(), findsOneWidget);
expect(tester.takeException(), isNull);
},
);
diff --git a/desktop/test/machines_manager_test.dart b/desktop/test/machines_manager_test.dart
index 9d0bac97b..ab4d7f7e8 100644
--- a/desktop/test/machines_manager_test.dart
+++ b/desktop/test/machines_manager_test.dart
@@ -73,7 +73,9 @@ void main() {
}
expect(resourceField, findsOneWidget);
expect(resourceSearch(tester).selected, isNull);
- await tester.tap(find.byKey(const ValueKey('swarm-search-scope:@')));
+ await tester.tap(
+ find.byKey(const ValueKey('search-category-Machines')),
+ );
await tester.pumpAndSettle();
expect(resourceScope('@'), findsOneWidget);
expect(find.byKey(const ValueKey('machines-panel')), findsNothing);
@@ -93,7 +95,7 @@ void main() {
await tester.enterText(resourceField, '');
await tester.pump();
- await tester.tap(find.byKey(const ValueKey('swarm-search-scope::')));
+ await tester.tap(find.byKey(const ValueKey('search-category-Models')));
await tester.pumpAndSettle();
expect(resourceScope(':'), findsOneWidget);
expect(find.byType(ModelsPanel), findsNothing);
@@ -337,7 +339,7 @@ void main() {
expect(resourceScope('@'), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(find.byKey(const ValueKey('swarm-search-button')), findsNothing);
+ expect(resourceField, findsNothing);
await openWorkspaceTool(tester, 'machines');
await tester.pumpAndSettle();
expect(resourceScope('@'), findsOneWidget);
@@ -388,6 +390,10 @@ void main() {
await key(tester, LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
expect(resourceSearch(tester).selected!.machineId, 'm');
+ // Tab advances through native controls; Escape returns to search.
+ expect(resourceSearch(tester).managing, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
expect(resourceSearch(tester).managing, isFalse);
expect(search.focusNode!.hasFocus, isTrue);
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/machines_panel_test.dart b/desktop/test/machines_panel_test.dart
index 0c24671ea..f0b7397a6 100644
--- a/desktop/test/machines_panel_test.dart
+++ b/desktop/test/machines_panel_test.dart
@@ -5,6 +5,7 @@ import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
@@ -22,7 +23,6 @@ import 'package:harness/shortcuts/app_keymap.dart';
import 'package:harness/shortcuts/keymap_host.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/widgets/machines_panel.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'keymap_host_test.dart' show MemoryKeymap, key;
import 'support/password_cli.dart';
@@ -310,8 +310,8 @@ void main() {
expect(find.textContaining('Available'), findsNothing);
expect(find.text('Offline'), findsNothing);
expect(find.textContaining('—'), findsNothing);
- expect(find.byIcon(LucideIcons.ellipsis), findsNothing);
- expect(find.byIcon(LucideIcons.monitorOff), findsNWidgets(2));
+ expect(find.byIcon(AppIcons.ellipsis), findsNothing);
+ expect(find.byIcon(AppIcons.monitorOff), findsNWidgets(2));
expect(find.text('Connect'), findsOneWidget);
expect(find.byKey(const ValueKey('machine-stats-rig')), findsNothing);
expect(find.text('0 harnesses'), findsOneWidget);
@@ -659,7 +659,7 @@ void main() {
app.add('remote', 'Mac mini', online: false);
await mount(tester);
expect(find.textContaining('Offline'), findsNothing);
- expect(find.byIcon(LucideIcons.monitorOff), findsOneWidget);
+ expect(find.byIcon(AppIcons.monitorOff), findsOneWidget);
expect(
find.byTooltip('Open Harness on Mac mini to bring it online.'),
findsOneWidget,
@@ -762,7 +762,7 @@ void main() {
await tester.pumpAndSettle();
final stats = find.byKey(const ValueKey('machine-stats-remote'));
expect(stats, findsNothing);
- expect(find.byIcon(LucideIcons.monitorOff), findsOneWidget);
+ expect(find.byIcon(AppIcons.monitorOff), findsOneWidget);
expect(find.text('Offline'), findsNothing);
app.resourceValues['remote'] = const MachineResources(cpuPercent: 7);
app.stateOf('remote')!.nodeOnline = true;
diff --git a/desktop/test/model_picker_chrome_test.dart b/desktop/test/model_picker_chrome_test.dart
index 9f11c71de..da1250e6f 100644
--- a/desktop/test/model_picker_chrome_test.dart
+++ b/desktop/test/model_picker_chrome_test.dart
@@ -1,5 +1,7 @@
// Where the model picker's furniture sits: the figures and the one button end on the edges the eye
// looks for them at, rather than wherever a flex split happened to leave them.
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/widgets/model_picker_chrome.dart';
@@ -14,7 +16,7 @@ Widget _frame(Widget child, {double width = kModelPickerWidth}) => MaterialApp(
);
void main() {
- testWidgets('the quota column ends where the meter under it ends', (
+ testWidgets('quota and saved-choice columns share stable right edges', (
tester,
) async {
// ⚠️ REGRESSION. The column was Flexible beside an Expanded title, which split the row in half
@@ -37,9 +39,10 @@ void main() {
);
final meter = tester.getRect(find.byType(LinearProgressIndicator));
- expect(tester.getRect(find.text('43% left')).right, meter.right);
- expect(tester.getRect(find.text('Healthy')).right, meter.right);
- expect(find.byIcon(Icons.check), findsNothing);
+ final check = tester.getRect(find.byIcon(AppIcons.check));
+ expect(check.right, meter.right);
+ expect(tester.getRect(find.text('43% left')).right, check.left - 8);
+ expect(tester.getRect(find.text('Healthy')).right, check.left - 8);
});
testWidgets('the footer button ends on the panel edge, not mid-row', (
diff --git a/desktop/test/models_panel_test.dart b/desktop/test/models_panel_test.dart
index ed1e5c8b7..4924c4fdc 100644
--- a/desktop/test/models_panel_test.dart
+++ b/desktop/test/models_panel_test.dart
@@ -5,11 +5,11 @@ import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/core/models.dart';
import 'package:harness/models/model_manager_controller.dart';
import 'package:harness/models/models_panel.dart';
@@ -290,9 +290,9 @@ void main() {
find.descendant(
of: control,
matching: find.byIcon(switch (state) {
- 'running' => LucideIcons.pause,
- 'downloaded' => LucideIcons.play,
- _ => LucideIcons.download,
+ 'running' => AppIcons.pause,
+ 'downloaded' => AppIcons.play,
+ _ => AppIcons.download,
}),
),
findsOneWidget,
@@ -311,7 +311,7 @@ void main() {
expect(
find.descendant(
of: find.byKey(const ValueKey('model-action-gemma')),
- matching: find.byIcon(LucideIcons.play),
+ matching: find.byIcon(AppIcons.play),
),
findsOneWidget,
);
@@ -561,7 +561,7 @@ void main() {
);
}
if (scenario == 'ready') {
- expect(find.byIcon(LucideIcons.pause), findsOneWidget);
+ expect(find.byIcon(AppIcons.pause), findsOneWidget);
expect(
find.text('16.2 GB · 17.6 tok/s · 42 requests / 24h'),
findsOneWidget,
@@ -699,7 +699,8 @@ void main() {
await tester.pump();
expect(find.text('Qwen3.8-27B'), findsWidgets);
expect(resourceSearch(tester).isModelMode, isTrue);
- expect(tester.getSize(resourceScope(':')).height, greaterThan(620));
+ expect(tester.getSize(resourceScope(':')).height, greaterThan(300));
+ expect(tester.getRect(resourceScope(':')).top, greaterThan(24));
expect(tester.getRect(resourceScope(':')).bottom, lessThan(760));
tester.view.physicalSize = const Size(1200, 480);
await tester.pump();
@@ -732,7 +733,7 @@ void main() {
final panel = tester.getRect(resourceScope(':'));
expect(panel.right, lessThanOrEqualTo(1200));
expect(panel.top, greaterThan(0));
- expect(panel.width, greaterThan(1000));
+ expect(panel.width, 1120);
expect(find.byType(Dialog), findsNothing);
expect(resourceSearch(tester).isModelMode, isTrue);
// The top-5 catalog model stays visible without pressing "Get models".
diff --git a/desktop/test/move_pane_palette_test.dart b/desktop/test/move_pane_palette_test.dart
index 888f4e14d..721e2c70b 100644
--- a/desktop/test/move_pane_palette_test.dart
+++ b/desktop/test/move_pane_palette_test.dart
@@ -55,7 +55,7 @@ void main() {
expect(find.text('Second'), findsOneWidget);
expect(find.text('Third'), findsOneWidget);
- expect(find.text('New Swarm'), findsOneWidget);
+ expect(find.text('New Tab'), findsOneWidget);
expect(
find.byKey(const ValueKey('move-pane-destination-2')),
findsOneWidget,
@@ -148,7 +148,7 @@ void main() {
final (app, source) = await _open(tester);
final before = app.swarms.length;
- await tester.tap(find.text('New Swarm'));
+ await tester.tap(find.text('New Tab'));
await tester.pumpAndSettle();
expect(app.swarms.length, before + 1);
diff --git a/desktop/test/new_agent_project_picker_test.dart b/desktop/test/new_agent_project_picker_test.dart
index 603b0a594..705e25fb4 100644
--- a/desktop/test/new_agent_project_picker_test.dart
+++ b/desktop/test/new_agent_project_picker_test.dart
@@ -335,7 +335,7 @@ void main() {
},
);
- testWidgets('keyboard focus never looks like a second project selection', (
+ testWidgets('keyboard focus preserves the single project selection', (
tester,
) async {
await mount(tester);
@@ -372,7 +372,16 @@ void main() {
);
expect(
((container.decoration! as BoxDecoration).border! as Border).top.color,
- Colors.transparent,
+ isNot(Colors.transparent),
+ );
+ expect(tester.widget<AppChoiceTile>(newTile).selected, isTrue);
+ expect(tester.widget<AppSelectField<String>>(recentTile).selected, isFalse);
+ expect(
+ ((container.decoration! as BoxDecoration).border! as Border).top.color,
+ isNot(
+ tester.widget<TextButton>(newButton).style!.side!.resolve({})!.color,
+ ),
+ reason: 'Keyboard focus has its own rim, separate from the saved choice',
);
});
diff --git a/desktop/test/new_harness_accessibility_test.dart b/desktop/test/new_harness_accessibility_test.dart
index 6467ec6f5..00a2b1f60 100644
--- a/desktop/test/new_harness_accessibility_test.dart
+++ b/desktop/test/new_harness_accessibility_test.dart
@@ -60,9 +60,13 @@ void main() {
.controller;
expect(box.engine, 'claude');
expect(harnessChoicesActive(tester), isFalse);
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(box.field, NewHarnessField.harness);
- await key(tester, LogicalKeyboardKey.arrowDown);
+ // A choice returns to its originating accessible control.
+ final agentButton = find.descendant(
+ of: find.byKey(const ValueKey('new-harness-field-agent')),
+ matching: find.byType(TextButton),
+ );
+ expect(tester.widget<TextButton>(agentButton).focusNode!.hasFocus, isTrue);
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-project')));
expect(box.field, NewHarnessField.projectMenu);
expect(input, isEmpty);
semantics.dispose();
diff --git a/desktop/test/new_harness_box_test.dart b/desktop/test/new_harness_box_test.dart
index f5a357c3f..df9f4df75 100644
--- a/desktop/test/new_harness_box_test.dart
+++ b/desktop/test/new_harness_box_test.dart
@@ -537,7 +537,7 @@ void main() {
},
);
- testWidgets('⌘N opens the box over live panes, and Escape closes it', (
+ testWidgets('⌘N focuses the prompt over live panes and Escape dismisses it', (
tester,
) async {
newHarnessOpensInBox = true;
@@ -561,7 +561,14 @@ void main() {
expect(frame.center.dx, tester.view.physicalSize.width / 2);
expect(frame.bottom, lessThan(tester.view.physicalSize.height));
expect(find.byKey(const ValueKey('new-harness-input')), findsNothing);
- expect(FocusManager.instance.primaryFocus!.debugLabel, 'new-harness-form');
+ expect(find.byKey(const ValueKey('new-harness-task')), findsOneWidget);
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('new-harness-task')))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.byKey(const ValueKey('new-harness-form')), findsNothing);
diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dart
index d1971f3e5..8807a0c8e 100644
--- a/desktop/test/new_harness_entry_rules_test.dart
+++ b/desktop/test/new_harness_entry_rules_test.dart
@@ -11,7 +11,10 @@ import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
import 'package:harness/store/store_screen.dart';
+import 'package:harness/widgets/desktop_search_panel.dart';
import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_search_input.dart';
import 'package:harness/ws/ws_conn.dart';
@@ -157,12 +160,13 @@ void main() {
}
Future<void> dismiss(WidgetTester tester) async {
- for (
- var i = 0;
- i < 4 && find.byType(NewHarnessForm).evaluate().isNotEmpty;
- i++
- ) {
- await key(tester, LogicalKeyboardKey.escape);
+ await tester.tap(find.byKey(const ValueKey('new-harness-close')));
+ await tester.pumpAndSettle();
+ if (find.byType(NewHarnessForm).evaluate().isNotEmpty &&
+ box(tester).checking) {
+ expect(box(tester).error, contains('Close again'));
+ await tester.tap(find.byKey(const ValueKey('new-harness-close')));
+ await tester.pumpAndSettle();
}
expect(find.byType(NewHarnessForm), findsNothing);
}
@@ -261,6 +265,30 @@ void main() {
}
}
+ testWidgets(
+ 'a Store example replaces an ordinary draft for the same product',
+ (tester) async {
+ await mount(tester);
+ await product(tester, 'autonomous/workshop');
+ await nameProject(tester, 'interrupted-workshop');
+ box(tester).setTask('Keep exploring this earlier idea');
+ await dismiss(tester);
+
+ await product(
+ tester,
+ 'autonomous/workshop',
+ task: 'Build a reading nook',
+ );
+ expect(box(tester).task, 'Build a reading nook');
+ expect(box(tester).harnessId, 'autonomous/workshop');
+ expect(box(tester).project.generated, isNotNull);
+ expect(box(tester).project.name, isNot('interrupted-workshop'));
+ expect(connections.values.expand((c) => c.starts), isEmpty);
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
testWidgets(
'Store machine choices have separate drafts and override edited defaults',
(tester) async {
@@ -518,7 +546,81 @@ void main() {
});
testWidgets(
- 'Cmd-N uses local saved defaults regardless of the focused pane',
+ 'explicit creation from search uses its requested task over an ordinary draft',
+ (tester) async {
+ await mount(tester, store: false);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ await nameProject(tester, 'interrupted-review');
+ box(tester).setTask('Explore the earlier idea');
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(search, 'Build the new idea');
+ final panel = tester.widget<DesktopSearchPanel>(
+ find.byType(DesktopSearchPanel),
+ );
+ // The creation action carries an explicit task, independently of Cmd-N
+ // switching between the search palette and an interrupted composer.
+ panel.onChoose(
+ SwarmSearchSelection(
+ SwarmDestination(
+ id: kSwarmCreateRowId,
+ title: 'New harness',
+ detail: 'Build the new idea',
+ swarmId: null,
+ current: false,
+ isCreate: true,
+ task: 'Build the new idea',
+ ),
+ SwarmSearchAction.open,
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(box(tester).task, 'Build the new idea');
+ expect(box(tester).project.folder, '/work/openharness');
+ expect(box(tester).project.name, isNull);
+ expect(box(tester).engine, 'codex');
+ expect(box(tester).placement, HarnessPlacement.currentTab);
+ expect(connections.values.expand((c) => c.starts), isEmpty);
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('Cmd-N restores an uncertain start after editing search', (
+ tester,
+ ) async {
+ await mount(tester, store: false);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final original = box(tester)..setTask('Review this exact request');
+ final starting = original.create();
+ await tester.pump();
+ final connection = connections['m']!;
+ expect(connection.starts, hasLength(1));
+ connection.replies.single.completeError(
+ const WsRequestTimeout('agent_create'),
+ );
+ expect(await starting, NewHarnessOutcome.failed);
+ await tester.pump();
+ expect(original.checking, isTrue);
+ final receipt = original.draft.attempt;
+ await dismiss(tester);
+
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Something else to look up',
+ );
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ expect(box(tester).checking, isTrue);
+ expect(box(tester).task, 'Review this exact request');
+ expect(box(tester).draft.attempt, same(receipt));
+ expect(connection.starts, hasLength(1));
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'Cmd-N keeps drafts with their source pane and uses defaults in another',
(tester) async {
await mount(tester, store: false);
final first = app.focusedPane!;
@@ -543,8 +645,8 @@ void main() {
await tester.pump();
await key(tester, shortcut, cmd: true);
expect(box(tester).engine, 'codex');
- expect(box(tester).project.folder, '/work/openharness');
- expect(box(tester).task, isEmpty);
+ expect(box(tester).project.name, 'keyboard-review');
+ expect(box(tester).task, 'Review this project');
expect(connections.values.expand((c) => c.starts), isEmpty);
await dismiss(tester);
await tester.pumpWidget(const SizedBox());
@@ -553,7 +655,7 @@ void main() {
);
testWidgets(
- 'fresh Cmd-N keeps successful defaults and discards canceled edits',
+ 'reopened Cmd-N restores reviewed edits and starts in the current tab',
(tester) async {
await mount(tester, store: false);
final origin = app.activeSwarm;
@@ -574,17 +676,23 @@ void main() {
await acceptSetupOrSearch(tester);
expect(find.byType(NewHarnessForm), findsNothing);
expect(connections.values.expand((c) => c.starts), isEmpty);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Find a different existing harness',
+ );
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
draft = box(tester);
- expect(draft.task, isEmpty);
- expect(draft.project.folder, '/work/openharness');
+ expect(draft.task, 'Check keyboard focus');
+ expect(draft.project.name, 'keyboard-review');
expect(draft.placement, HarnessPlacement.currentTab);
+ // Keep the launch on the fake daemon; no local project is created.
+ app.machineStates['m']!.localOnly = false;
await acceptSetupOrSearch(tester);
final connection = connections['m']!;
expect(connection.starts, hasLength(1));
expect(connection.starts.single['engine'], 'codex');
- expect(connection.starts.single['cwd'], '/work/openharness');
- expect(connection.starts.single['prompt'], isNull);
+ expect(connection.starts.single['projectName'], 'keyboard-review');
+ expect(connection.starts.single['prompt'], 'Check keyboard focus');
expect(connection.starts.single['dsh'], isNull);
connection.created();
await tester.pump();
diff --git a/desktop/test/new_harness_git_test.dart b/desktop/test/new_harness_git_test.dart
index 0b869e16c..88218580a 100644
--- a/desktop/test/new_harness_git_test.dart
+++ b/desktop/test/new_harness_git_test.dart
@@ -563,8 +563,8 @@ void main() {
await settle();
expect(
box.worktree,
- true,
- reason: 'Each Git project starts with Worktree on.',
+ false,
+ reason: 'Returning to a project restores its last worktree choice.',
);
expect(box.branchRef, 'refs/heads/main');
});
diff --git a/desktop/test/new_harness_install_pane_test.dart b/desktop/test/new_harness_install_pane_test.dart
index 20fbde866..9c7b0e901 100644
--- a/desktop/test/new_harness_install_pane_test.dart
+++ b/desktop/test/new_harness_install_pane_test.dart
@@ -200,6 +200,7 @@ void main() {
WidgetTester tester,
_Notifier notifier, {
double width = 900,
+ VoidCallback? onClose,
}) async {
final box = controller(notifier);
final keymap = MemoryKeymap();
@@ -219,7 +220,7 @@ void main() {
height: 520,
child: NewHarnessForm(
controller: box,
- onClose: () {},
+ onClose: onClose ?? () {},
onCreated: () {},
),
),
@@ -408,6 +409,31 @@ void main() {
});
group('installing on the way to start', () {
+ testWidgets('outside dismissal cannot abandon a running installation', (
+ tester,
+ ) async {
+ final notifier = await app();
+ notifier.pendingInstall = Completer<String?>();
+ var closes = 0;
+ final box = await mount(tester, notifier, onClose: () => closes++);
+ box.focusField(NewHarnessField.harness);
+ box.applyOption(box.options.firstWhere((o) => o.id == _circuit.id));
+ await tester.pump();
+ await startHarness(tester);
+ await tester.pump();
+ tester
+ .state<NewHarnessFormState>(find.byType(NewHarnessForm))
+ .dismissFromOutside();
+ await tester.pump();
+ expect(closes, 0);
+ expect(box.busy, isTrue);
+ expect(box.error, contains('Still working on it'));
+ expect(notifier.launches, isEmpty);
+ notifier.pendingInstall!.complete('Synthetic installation failure');
+ await tester.pumpAndSettle();
+ expect(box.busy, isFalse);
+ });
+
testWidgets('the right pane narrates the machine, step by step', (
tester,
) async {
diff --git a/desktop/test/notification_inbox_test.dart b/desktop/test/notification_inbox_test.dart
index c123de495..0be069d67 100644
--- a/desktop/test/notification_inbox_test.dart
+++ b/desktop/test/notification_inbox_test.dart
@@ -9,7 +9,9 @@ import 'package:harness/core/models.dart';
import 'package:harness/notify/alert_sounds.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/notification_inbox.dart';
+import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'package:harness/widgets/notification_inbox.dart';
import 'package:harness/widgets/workspace_notifications_button.dart';
@@ -17,7 +19,7 @@ import 'support/real_fonts.dart';
import 'swarm_attention_test.dart' show waitingQuestion;
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
-import 'workspace_activity_test.dart' show captureWorkspace;
+import 'workspace_activity_test.dart' as activity;
void main() {
final capture = Platform.environment['HARNESS_NOTIFICATION_CAPTURE_DIR'];
@@ -25,6 +27,26 @@ void main() {
final inbox = find.byKey(const ValueKey('notification-inbox'));
Finder row(String agent) => find.byKey(ValueKey('notification:m/$agent'));
+ Future<void> captureWorkspace(WidgetTester tester, String path) async {
+ final oldShadows = debugDisableShadows;
+ final view = tester.binding.renderViews.first;
+ void repaint(RenderObject object) {
+ object.markNeedsPaint();
+ object.visitChildren(repaint);
+ }
+
+ try {
+ debugDisableShadows = false;
+ repaint(view);
+ await tester.pumpAndSettle();
+ await activity.captureWorkspace(tester, path);
+ } finally {
+ debugDisableShadows = oldShadows;
+ repaint(view);
+ await tester.pump();
+ }
+ }
+
setUpAll(() async {
await (FontLoader('packages/lucide_icons_flutter/Lucide')..addFont(
rootBundle.load('packages/lucide_icons_flutter/assets/lucide.ttf'),
@@ -383,7 +405,13 @@ void main() {
await mount(tester, app);
await tester.tap(bell);
await tester.pumpAndSettle();
- expect(find.text('Notifications 9'), findsOneWidget);
+ expect(find.text('Notifications'), findsOneWidget);
+ expect(
+ find.descendant(of: inbox, matching: find.text('9')),
+ findsOneWidget,
+ );
+ expect(find.byTooltip('Close notifications'), findsOneWidget);
+ expect(tester.getSize(inbox).width, 440);
expect(find.byTooltip('Needs input'), findsWidgets);
expect(find.byTooltip('Failed'), findsWidgets);
expect(find.text('Test host openharness release-notes'), findsOneWidget);
@@ -417,4 +445,141 @@ void main() {
await tester.pumpWidget(const SizedBox());
app.dispose();
});
+
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'desktop inbox fits enlarged text and live states in ${brightness.name}',
+ (tester) async {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ final oldFont = terminalFontStore.value;
+ addTearDown(() {
+ grid.AppTheme.brightness.value = oldBrightness;
+ terminalFontStore.value = oldFont;
+ });
+ grid.AppTheme.brightness.value = brightness;
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(480, 420);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ addTearDown(tester.view.resetPhysicalSize);
+ final machine = app.stateOf('m')!;
+ machine.agents = const [
+ Agent(
+ id: 'a0',
+ name: 'Review the long onboarding flow for the product website',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'product-website',
+ cwd: '/work/product-website',
+ branch: 'onboarding-review',
+ ),
+ ),
+ Agent(
+ id: 'a1',
+ name: 'Choose a homepage direction',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'website',
+ cwd: '/work/website',
+ branch: 'new-home',
+ ),
+ ),
+ ];
+ app.agentUnread.mark('m', 'a0', AlertKind.done);
+ machine.blockedAgents['a1'] = waitingQuestion('a1');
+ app.agentUnread.mark('m', 'a1', AlertKind.needsYou);
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: const TextScaler.linear(1.6)),
+ child: child!,
+ ),
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => unawaited(
+ showNotificationInbox(
+ context,
+ app: app,
+ topInset: 40,
+ onOpen: (_) async => false,
+ ),
+ ),
+ child: const Text('Open inbox'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open inbox'));
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ expect(tester.getRect(inbox).right, 464);
+ expect(tester.getRect(inbox).top, 56);
+ expect(tester.getSize(inbox).width, 440);
+ expect(find.byType(DesktopDialogSurface), findsOneWidget);
+ expect(app.agentUnread.count, 2);
+ final title = tester.widget<Text>(
+ find.text('Choose a homepage direction'),
+ );
+ expect(title.style!.fontFamily, grid.AppType.sansFamily);
+ final header = tester.widget<Text>(find.text('Notifications'));
+ expect(header.style!.fontFamily, grid.AppType.sansFamily);
+ final before = tester.getSize(inbox);
+ final rowBefore = tester.getSize(row('a0'));
+ terminalFontStore.value = oldFont.copyWith(fontSize: 30);
+ await tester.pumpAndSettle();
+ expect(tester.getSize(inbox), before);
+ expect(tester.getSize(row('a0')), rowBefore);
+
+ if (capture != null) {
+ await tester.runAsync(
+ () => Directory(capture).create(recursive: true),
+ );
+ await captureWorkspace(
+ tester,
+ '$capture/desktop-notifications-${brightness.name}-enlarged.png',
+ );
+ }
+ await tester.tap(row('a0'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Could not open this harness. Try again.'),
+ findsOneWidget,
+ );
+ expect(app.agentUnread.count, 2);
+ expect(tester.takeException(), isNull);
+ if (capture != null) {
+ await captureWorkspace(
+ tester,
+ '$capture/desktop-notifications-${brightness.name}-error.png',
+ );
+ }
+ machine.blockedAgents.clear();
+ app.agentUnread.clearAll();
+ await tester.pumpAndSettle();
+ expect(find.text('No notifications'), findsOneWidget);
+ expect(
+ find.text('Could not open this harness. Try again.'),
+ findsNothing,
+ );
+ expect(find.byTooltip('Close notifications'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ if (capture != null) {
+ await captureWorkspace(
+ tester,
+ '$capture/desktop-notifications-${brightness.name}-empty.png',
+ );
+ }
+ await tester.tap(find.byTooltip('Close notifications'));
+ await tester.pumpAndSettle();
+ expect(inbox, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
}
diff --git a/desktop/test/open_picker_rendering_test.dart b/desktop/test/open_picker_rendering_test.dart
index 4c6b26487..5e37f1bf1 100644
--- a/desktop/test/open_picker_rendering_test.dart
+++ b/desktop/test/open_picker_rendering_test.dart
@@ -12,10 +12,10 @@ import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/widgets/search_result_text.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/engine_identity.dart';
import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_switcher.dart';
-import 'package:harness/widgets/engine_identity.dart';
-import 'package:harness/widgets/prompt_context.dart';
import 'package:xterm/xterm.dart';
import 'keymap_host_test.dart' show MemoryKeymap, key;
@@ -27,7 +27,7 @@ import 'swarm_state_test.dart' show createApp;
void main() {
testWidgets(
- 'terminal dialogs follow the live pane theme without losing focus',
+ 'desktop dialogs keep native controls and terminal previews through theme changes',
(tester) async {
final originalPalette = grid.AppTheme.palette.value;
final originalTheme = terminalThemeStore.value;
@@ -90,22 +90,23 @@ void main() {
find.descendant(of: input, matching: find.byType(EditableText)),
);
final panel = tester.widget<Material>(
- find.byKey(const ValueKey('swarm-search-results')),
- );
- expect(panel.color, pane.theme.background);
- expect(field.style!.color, pane.theme.foreground);
- expect(field.cursorColor, pane.theme.cursor);
- expect(editor.selectionColor, pane.theme.selection);
- final row = find.byKey(
- ValueKey('swarm-search-line:${search.selected!.id}'),
+ find
+ .descendant(
+ of: find.byKey(const ValueKey('swarm-search-results')),
+ matching: find.byType(Material),
+ )
+ .first,
);
- expect(tester.widget<Container>(row).color, pane.theme.selection);
- final cell = terminalCellSizeOf(tester.element(input));
- expect(tester.getSize(row).height, closeTo(cell.height, .01));
+ expect(panel.color, DesktopChrome.surface);
+ expect(field.style!.color, grid.AppPalette.textPrimary);
+ expect(field.cursorColor, grid.AppPalette.textPrimary);
expect(
- tester.getSize(find.byKey(ValueKey(search.selected!.id))).height,
- closeTo(cell.height, .01),
+ editor.selectionColor,
+ DefaultSelectionStyle.of(tester.element(input)).selectionColor,
);
+ final row = find.byKey(ValueKey(search.selected!.id));
+ expect(tester.widget<ListTile>(row).selected, isTrue);
+ expect(tester.getSize(row).height, greaterThan(40));
expect(field.cursorWidth, 2);
final rowTitles = tester.widgetList<SearchResultText>(
find.byWidgetPredicate(
@@ -119,29 +120,29 @@ void main() {
final row = search.rows.firstWhere((row) => row.title == title.text);
expect(
title.style.color,
- search.canSubmit(row)
- ? pane.theme.foreground
- : pane.theme.foreground.withValues(alpha: .28),
+ row.id == search.selected?.id
+ ? search.sessionUnavailable(row) == null
+ ? DesktopChrome.onSelection
+ : DesktopChrome.selectionDetail
+ : search.sessionUnavailable(row) == null
+ ? DesktopChrome.foreground
+ : DesktopChrome.muted,
);
}
- final previewText = tester.widgetList<Text>(
- find.descendant(
- of: find.byKey(const ValueKey('swarm-search-preview')),
- matching: find.byType(Text),
- ),
+ final previewText = find.descendant(
+ of: find.byKey(const ValueKey('swarm-search-preview')),
+ matching: find.byType(Text),
);
- expect(previewText, isNotEmpty);
- for (final style in [
- field.style!,
- ...rowTitles.map((text) => text.style),
- ...previewText.map((text) => text.style!),
- ]) {
- expect(style.fontFamily, pane.textStyle.fontFamily);
- expect(style.fontFamilyFallback, pane.textStyle.fontFamilyFallback);
- expect(style.fontSize, pane.textStyle.fontSize);
- expect(style.height, pane.textStyle.height);
- expect(style.letterSpacing, 0);
- expect(style.wordSpacing, 0);
+ expect(previewText, findsWidgets);
+ for (final element in previewText.evaluate()) {
+ final style = DefaultTextStyle.of(element).style
+ .merge((element.widget as Text).style);
+ expect(
+ style.fontFamily,
+ isIn([grid.AppType.sansFamily, grid.AppType.monoFamily]),
+ );
+ expect(style.fontSize, isIn([11.0, 12.0, 13.0, 15.0]));
+ expect(style.height ?? 1, inInclusiveRange(1.0, 1.6));
}
expect(search.selected!.id, selectedId);
expect(field.controller, same(controller));
@@ -176,13 +177,12 @@ void main() {
of: preview,
matching: find.text('Checkout retries'),
);
- final context = find.text('Test host:storefront (feat/safe-retries)');
+ final context = find.text('Test host · storefront · feat/safe-retries');
expect(context, findsOneWidget);
expect(find.descendant(of: preview, matching: context), findsOneWidget);
- final cell = terminalCellSizeOf(tester.element(input));
expect(
- tester.getTopLeft(context).dy - tester.getTopLeft(title).dy,
- closeTo(cell.height, .01),
+ tester.getTopLeft(context).dy,
+ greaterThan(tester.getBottomLeft(title).dy),
);
expect(
tester
@@ -193,18 +193,15 @@ void main() {
),
)
.map((text) => text.text),
- ['Checkout retries'],
+ contains('Checkout retries'),
);
expect(find.text('git: feat/safe-retries'), findsNothing);
await tester.enterText(input, 'Workspace sync');
await tester.pumpAndSettle();
final waiting = tester.widget<Text>(find.text('Needs your input'));
- expect(waiting.style!.fontSize, 18);
- expect(waiting.style!.height, 1.4);
- expect(
- waiting.style!.color,
- tester.widget<TerminalView>(find.byType(TerminalView)).theme.yellow,
- );
+ expect(waiting.style!.fontSize, 12);
+ expect(waiting.style!.height, 1.45);
+ expect(waiting.style!.color, grid.AppPalette.warn);
await key(tester, LogicalKeyboardKey.escape);
expect(find.byKey(const ValueKey('swarm-search-results')), findsNothing);
@@ -228,37 +225,26 @@ void main() {
expect(
tester
.widget<Material>(
- find.byKey(const ValueKey('new-harness-surface')),
+ find
+ .descendant(
+ of: find.byKey(
+ const ValueKey('new-harness-chooser-surface'),
+ ),
+ matching: find.byType(Material),
+ )
+ .first,
)
.color,
- pane.theme.background,
+ DesktopChrome.surface,
);
- expect(field.style!.color, pane.theme.foreground);
- expect(field.cursorColor, pane.theme.cursor);
- expect(editor.selectionColor, pane.theme.selection);
+ expect(field.style!.color, grid.AppPalette.textPrimary);
+ expect(field.cursorColor, grid.AppPalette.textPrimary);
expect(
- tester
- .widgetList<Container>(
- find.descendant(of: setup, matching: find.byType(Container)),
- )
- .where((container) => container.color == pane.theme.selection),
- hasLength(1),
+ editor.selectionColor,
+ DefaultSelectionStyle.of(tester.element(setupInput)).selectionColor,
);
- for (final style in [
- field.style!,
- ...tester
- .widgetList<Text>(
- find.descendant(of: setup, matching: find.byType(Text)),
- )
- .map((text) => text.style!),
- ]) {
- expect(style.fontFamily, pane.textStyle.fontFamily);
- expect(style.fontFamilyFallback, pane.textStyle.fontFamilyFallback);
- expect(style.fontSize, pane.textStyle.fontSize);
- expect(style.height, pane.textStyle.height);
- expect(style.letterSpacing, 0);
- expect(style.wordSpacing, 0);
- }
+ expect(field.style!.fontFamily, grid.AppType.body().fontFamily);
+ expect(field.style!.fontSize, 14);
expect(box.selected?.id, selectedOption);
expect(field.controller, same(setupController));
expect(setupController.value, setupEditing);
@@ -286,10 +272,17 @@ void main() {
await tester.pumpAndSettle();
expect(
tester
- .widget<Text>(find.byKey(const ValueKey('new-harness-status')))
+ .widget<Text>(
+ find.descendant(
+ of: find.byKey(const ValueKey('new-harness-chooser-surface')),
+ matching: find.byKey(const ValueKey('new-harness-status')),
+ ),
+ )
.style!
.color,
- tester.widget<TerminalView>(find.byType(TerminalView)).theme.red,
+ Theme.of(
+ tester.element(find.byKey(const ValueKey('new-harness-status'))),
+ ).colorScheme.error,
);
await tester.pumpWidget(const SizedBox());
app.dispose();
@@ -312,55 +305,24 @@ void main() {
of: results,
matching: find.byWidgetPredicate(
(widget) =>
- widget is InkWell &&
+ widget is ListTile &&
widget.key is ValueKey<String> &&
rowIds.contains((widget.key! as ValueKey<String>).value),
),
);
- final input = find.byKey(const ValueKey('swarm-search-input'));
- final cell = terminalCellSizeOf(tester.element(input));
- for (final row in rows.evaluate()) {
- final id = (row.widget.key! as ValueKey<String>).value;
- final line = find.byKey(ValueKey('swarm-search-line:$id'));
- expect(
- tester.getSize(line).height,
- closeTo(cell.height, .01),
- reason: 'Selection occupies exactly one terminal line.',
- );
- expect(
- tester.getSize(find.byKey(ValueKey(id))).height,
- closeTo(cell.height, .01),
- reason: 'The entire result occupies one line, with no spacer row.',
- );
- final title = find
- .descendant(of: line, matching: find.byType(Text))
- .first;
- expect(
- tester.getTopLeft(title).dx,
- closeTo(tester.getTopLeft(input).dx, .01),
- );
- }
final first = find.byKey(ValueKey(search.rows[0].id));
final second = find.byKey(ValueKey(search.rows[1].id));
+ final rowHeight =
+ tester.getTopLeft(second).dy - tester.getTopLeft(first).dy;
+ expect(rowHeight, greaterThanOrEqualTo(48));
+ expect(rows.evaluate(), isNotEmpty);
expect(
- tester.getTopLeft(second).dy - tester.getTopLeft(first).dy,
- closeTo(cell.height, .01),
+ find.descendant(of: results, matching: find.byType(EngineMark)),
+ findsWidgets,
);
- for (final type in [
- ListTile,
- Icon,
- Image,
- EngineMark,
- PromptContextView,
- ]) {
- expect(
- find.descendant(of: results, matching: find.byType(type)),
- findsNothing,
- );
- }
expect(search.rows.length, greaterThan(50));
final list = find.byKey(const ValueKey('swarm-search-result-list'));
- final capacity = (tester.getSize(list).height / cell.height).ceil();
+ final capacity = (tester.getSize(list).height / rowHeight).ceil();
expect(rows.evaluate().length, lessThanOrEqualTo(capacity + 2));
expect(rows.evaluate().length, lessThan(search.rows.length));
final visited = <String>{};
diff --git a/desktop/test/orchestrator_controls_test.dart b/desktop/test/orchestrator_controls_test.dart
index b38ac8b26..dc6f50e2a 100644
--- a/desktop/test/orchestrator_controls_test.dart
+++ b/desktop/test/orchestrator_controls_test.dart
@@ -6,6 +6,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/orchestrator/orchestrator_controller.dart';
import 'package:harness/orchestrator/orchestrator_launcher.dart';
import 'package:harness/orchestrator/orchestrator_workspace.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/pending_question.dart';
import 'package:harness/widgets/web_pane_panel.dart';
import 'package:harness/ws/ws_conn.dart';
@@ -43,6 +44,76 @@ void largeSurface(WidgetTester tester) {
}
void main() {
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'enlarged ${brightness.name} composer keeps Send visible and preserves its draft',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(880, 560);
+ addTearDown(tester.view.reset);
+ final previousBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);
+ final app = createApp();
+ final requests = <Map<String, dynamic>>[];
+ final model = OrchestratorController(
+ id: projectId,
+ request: (request) async {
+ requests.add(request);
+ return {'project': project()};
+ },
+ )..draft = 'Make the base wider.';
+ addTearDown(app.dispose);
+ addTearDown(model.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: const TextScaler.linear(2)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: OrchestratorWorkspace(
+ notifier: app,
+ machineId: 'm',
+ projectId: projectId,
+ controller: model,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final composer = find.byKey(const ValueKey('orchestrator-composer'));
+ final send = find.byTooltip('Send to director');
+ expect(
+ tester.widget<TextField>(composer).controller!.text,
+ model.draft,
+ );
+ expect(send.hitTestable(), findsOneWidget);
+ expect(
+ tester.getRect(send).right,
+ lessThanOrEqualTo(tester.getRect(composer).right),
+ );
+ expect(
+ tester.getRect(find.text('Shift ↵ for a new line')).right,
+ lessThan(tester.getRect(send).left),
+ );
+ expect(tester.takeException(), isNull);
+ await tester.tap(send);
+ await tester.pumpAndSettle();
+ final sent = requests.where(
+ (request) => request['action'] == 'message',
+ );
+ expect(sent.single['text'], 'Make the base wider.');
+ expect(model.draft, isEmpty);
+ expect(tester.widget<TextField>(composer).controller!.text, isEmpty);
+ expect(tester.widget<TextField>(composer).focusNode!.hasFocus, isTrue);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
test(
'refresh failures remain visible and a later refresh recovers',
() async {
diff --git a/desktop/test/orchestrator_review_render_test.dart b/desktop/test/orchestrator_review_render_test.dart
index c72c8d9e7..60b8662d1 100644
--- a/desktop/test/orchestrator_review_render_test.dart
+++ b/desktop/test/orchestrator_review_render_test.dart
@@ -47,8 +47,8 @@ void main() {
await (FontLoader(
'MaterialIcons',
)..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
- await (FontLoader('packages/lucide_icons_flutter/Lucide')..addFont(
- rootBundle.load('packages/lucide_icons_flutter/assets/lucide.ttf'),
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load('packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf'),
))
.load();
// Widget tests disable native font fallback. Supply symbol glyphs under
diff --git a/desktop/test/pane_machine_unknown_test.dart b/desktop/test/pane_machine_unknown_test.dart
index 9ea796284..ac91f5b65 100644
--- a/desktop/test/pane_machine_unknown_test.dart
+++ b/desktop/test/pane_machine_unknown_test.dart
@@ -3,10 +3,12 @@
// "Waiting for this machine to answer…" is only honest while there is something to wait FOR. When the
// machine LIST itself could not be read, the machine is not slow — it is unknown, and a spinner that
// never ends tells the user nothing and offers them nothing. This is the difference between those two.
+
import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
@@ -195,7 +197,7 @@ void main() {
find.text('Could not load machines. Retry to reconnect.'),
findsOneWidget,
);
- expect(find.byIcon(Icons.cloud_off), findsOneWidget);
+ expect(find.byIcon(AppIcons.cloudOff), findsOneWidget);
// And the button reaches the same reload the error strip's RETRY does.
expect(api.lists, hasLength(1));
@@ -213,7 +215,7 @@ void main() {
api.lists.single.completeError(ApiException('boom', status: 502));
await failed;
await _pump(tester, app);
- expect(find.byIcon(Icons.cloud_off), findsOneWidget);
+ expect(find.byIcon(AppIcons.cloudOff), findsOneWidget);
final ok = app.retryMachines();
await _untilRequested(tester, api, 2);
diff --git a/desktop/test/pane_menu_desktop_test.dart b/desktop/test/pane_menu_desktop_test.dart
new file mode 100644
index 000000000..e9f04f532
--- /dev/null
+++ b/desktop/test/pane_menu_desktop_test.dart
@@ -0,0 +1,498 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/terminal/terminal_search.dart';
+import 'package:harness/terminal/terminal_text.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/grid_model_picker.dart';
+import 'package:harness/widgets/model_picker_chrome.dart';
+import 'package:harness/widgets/resting_section.dart';
+import 'package:harness/widgets/terminal_find_bar.dart';
+import 'package:xterm/xterm.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/real_fonts.dart';
+import 'support/resting_models.dart';
+import 'swarm_state_test.dart' show createApp;
+
+const _captureKey = ValueKey('desktop-menu-preview');
+final _menu = find.byKey(const ValueKey('pane-menu-surface'));
+final _renderDir = Platform.environment['PANE_MENU_RENDER_DIR'];
+
+Widget _frame({
+ required Widget child,
+ double scale = 1,
+ bool highContrast = false,
+}) => RepaintBoundary(
+ key: _captureKey,
+ child: grid.BrightnessScope(
+ child: ValueListenableBuilder(
+ valueListenable: grid.AppTheme.brightness,
+ builder: (context, brightness, _) => MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(
+ brightness: brightness,
+ highContrast: highContrast,
+ ),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(scale),
+ highContrast: highContrast,
+ ),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topRight,
+ child: Padding(padding: const EdgeInsets.all(16), child: child),
+ ),
+ ),
+ ),
+ ),
+ ),
+);
+
+Future<void> _capture(WidgetTester tester, String name) async {
+ if (_renderDir == null) return;
+ final oldShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ try {
+ await tester.runAsync(
+ () => Future.wait([
+ for (final brand in ['openai', 'qwen', 'deepseek'])
+ precacheImage(
+ AssetImage('assets/model-icons/$brand.png'),
+ tester.element(find.byKey(_captureKey)),
+ ),
+ ]),
+ );
+ for (final object in tester.allRenderObjects) {
+ object.markNeedsPaint();
+ }
+ await tester.pump();
+ await expectLater(
+ find.byKey(_captureKey),
+ matchesGoldenFile(Uri.file('$_renderDir/$name.png')),
+ );
+ } finally {
+ debugDisableShadows = oldShadows;
+ for (final object in tester.allRenderObjects) {
+ object.markNeedsPaint();
+ }
+ await tester.pump();
+ }
+}
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ if (_renderDir != null) await loadPreviewFonts();
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final enlarged in [false, true]) {
+ final label = '${brightness.name}-${enlarged ? 'narrow-large' : 'wide'}';
+ testWidgets('desktop model menu remains usable $label', (tester) async {
+ final originalBrightness = grid.AppTheme.brightness.value;
+ final originalFont = terminalFontStore.value;
+ grid.AppTheme.brightness.value = brightness;
+ tester.view.devicePixelRatio = 1;
+ final size = enlarged ? const Size(380, 440) : const Size(900, 700);
+ tester.view.physicalSize = size;
+ addTearDown(() {
+ grid.AppTheme.brightness.value = originalBrightness;
+ terminalFontStore.value = originalFont;
+ tester.view.reset();
+ });
+
+ final daemon = RecordingDaemon(
+ modelsReply([
+ section(
+ 'home',
+ own: true,
+ models: [
+ row('Qwen3.5-4B', 'macbook-pro'),
+ row(
+ 'DeepSeek-V4-Flash',
+ 'mac-studio',
+ offlineMachine: 'Studio',
+ ),
+ ],
+ ),
+ section('Design team', state: 'asleep'),
+ ]),
+ );
+ final app = createApp(connectionForTest: (_) => daemon);
+ addTearDown(app.dispose);
+ final selections = <GridModel>[];
+ await tester.pumpWidget(
+ _frame(
+ scale: enlarged ? 1.7 : 1,
+ highContrast: enlarged,
+ child: GridModelPicker(
+ notifier: app,
+ machineId: 'm',
+ engineLabel: 'codex',
+ currentModel: 'Qwen3.5-4B',
+ onSelected: selections.add,
+ onRunLocalModel: () {},
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.tap(find.byType(GridModelPicker));
+ await tester.pumpAndSettle();
+
+ final bounds = tester.getRect(_menu);
+ expect(bounds.left, greaterThanOrEqualTo(8));
+ expect(bounds.top, greaterThanOrEqualTo(8));
+ expect(bounds.right, lessThanOrEqualTo(size.width - 8));
+ expect(bounds.bottom, lessThanOrEqualTo(size.height - 8));
+ expect(find.byType(ModelPickerSearch).hitTestable(), findsOneWidget);
+ expect(find.text('Local models').hitTestable(), findsOneWidget);
+ final footer = find.byType(ModelPickerFooter);
+ final footerAction = find.descendant(
+ of: footer,
+ matching: find.text('Local models'),
+ );
+ if (enlarged) {
+ expect(
+ tester.getTopLeft(footerAction).dy,
+ greaterThan(
+ tester.getBottomLeft(find.text('2 models available')).dy,
+ ),
+ );
+ }
+ final editor = find.descendant(
+ of: find.byType(ModelPickerSearch),
+ matching: find.byType(TextField),
+ );
+ final controller = tester.widget<TextField>(editor).controller!;
+ expect(
+ tester.widget<TextField>(editor).style!.fontFamily,
+ DesktopChrome.control().fontFamily,
+ );
+ expect(
+ MediaQuery.textScalerOf(tester.element(editor)).scale(10),
+ enlarged ? 17 : 10,
+ );
+ await _capture(tester, 'model-menu-$label');
+
+ // The saved model and keyboard target are separate: moving focus must
+ // not choose a model or add a second stop around a button.
+ final firstRow = find.byType(ModelPickerRow).first;
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ final firstFocus = FocusManager.instance.primaryFocus!;
+ expect(
+ firstFocus.context!
+ .findAncestorWidgetOfExactType<ModelPickerRow>()
+ ?.title,
+ tester.widget<ModelPickerRow>(firstRow).title,
+ );
+ expect(selections, isEmpty);
+ expect(
+ tester
+ .widgetList<ModelPickerRow>(find.byType(ModelPickerRow))
+ .where((row) => row.selected)
+ .single
+ .title,
+ 'Qwen3.5-4B',
+ );
+ await _capture(tester, 'model-menu-focus-$label');
+
+ final stops = <FocusNode>{firstFocus};
+ final labels = <String>['${firstFocus.debugLabel}: ${firstFocus.rect}'];
+ final controlCount =
+ find
+ .descendant(of: _menu, matching: find.byType(TextButton))
+ .evaluate()
+ .length +
+ 1; // Search is the only non-button stop.
+ for (var i = 0; i < controlCount; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pumpAndSettle();
+ final focused = FocusManager.instance.primaryFocus!;
+ labels.add('${focused.debugLabel}: ${focused.rect}');
+ if (i == controlCount - 1) {
+ expect(focused, same(firstFocus));
+ } else {
+ expect(stops.add(focused), isTrue, reason: labels.join('\n'));
+ }
+ }
+ expect(stops.length, controlCount);
+
+ final chosen = find.byWidgetPredicate(
+ (widget) => widget is ModelPickerRow && widget.selected,
+ );
+ Material chosenMaterial() => tester.widget<Material>(
+ find.descendant(of: chosen, matching: find.byType(Material)),
+ );
+ tester
+ .widget<EditableText>(
+ find.descendant(of: editor, matching: find.byType(EditableText)),
+ )
+ .focusNode
+ .requestFocus();
+ await tester.ensureVisible(chosen);
+ await tester.pumpAndSettle();
+ final savedShape = chosenMaterial().shape;
+ final savedBounds = tester.getRect(chosen);
+ expect(chosenMaterial().color, grid.AppSurface.accentWash);
+ expect(
+ find.descendant(of: chosen, matching: find.byIcon(AppIcons.check)),
+ findsOneWidget,
+ );
+ Focus.of(
+ tester.element(
+ find.descendant(of: chosen, matching: find.text('Qwen3.5-4B')),
+ ),
+ ).requestFocus();
+ await tester.pumpAndSettle();
+ expect(chosenMaterial().color, grid.AppDesktop.selection);
+ expect(chosenMaterial().shape, savedShape);
+ expect(tester.getRect(chosen), savedBounds);
+ expect(
+ tester
+ .widget<Icon>(
+ find.descendant(
+ of: chosen,
+ matching: find.byIcon(AppIcons.check),
+ ),
+ )
+ .color,
+ grid.AppDesktop.onSelection,
+ );
+
+ final wake = find.widgetWithText(TextButton, 'Show models');
+ await tester.ensureVisible(wake);
+ Focus.of(tester.element(find.text('Show models'))).requestFocus();
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<Material>(
+ find.descendant(of: wake, matching: find.byType(Material)),
+ )
+ .color,
+ grid.AppDesktop.selection,
+ );
+ for (final label in ['Show models', 'usually 15–40 s']) {
+ expect(
+ tester.widget<Text>(find.text(label)).style!.color,
+ grid.AppDesktop.onSelection,
+ );
+ }
+ expect(
+ tester
+ .widget<Icon>(
+ find.descendant(of: wake, matching: find.byIcon(AppIcons.eye)),
+ )
+ .color,
+ grid.AppDesktop.onSelection,
+ );
+ await _capture(tester, 'model-menu-wake-focus-$label');
+
+ await tester.enterText(editor, 'macbook');
+ await tester.pumpAndSettle();
+ const editing = TextEditingValue(
+ text: 'macbook',
+ selection: TextSelection.collapsed(offset: 7),
+ composing: TextRange(start: 0, end: 7),
+ );
+ controller.value = editing;
+ final filteredBounds = tester.getRect(_menu);
+ grid.AppTheme.brightness.value = brightness == Brightness.dark
+ ? Brightness.light
+ : Brightness.dark;
+ terminalFontStore.value = TerminalStyle(
+ fontSize: 22,
+ fontFamily: originalFont.fontFamily,
+ fontFamilyFallback: originalFont.fontFamilyFallback,
+ );
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(editor).controller, same(controller));
+ expect(controller.value, editing);
+ expect(tester.getRect(_menu), filteredBounds);
+ expect(tester.widget<Material>(_menu).color, grid.AppMenu.fill);
+ expect(
+ tester.widget<TextField>(editor).style!.fontSize,
+ DesktopChrome.control().fontSize,
+ );
+ expect(daemon.asks.every((ask) => ask['wake'] == null), isTrue);
+ expect(daemon.others, isEmpty);
+ expect(selections, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump();
+ });
+
+ testWidgets('offline switch keeps Cancel reachable $label', (
+ tester,
+ ) async {
+ final originalBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = enlarged
+ ? const Size(380, 360)
+ : const Size(900, 700);
+ addTearDown(() {
+ grid.AppTheme.brightness.value = originalBrightness;
+ tester.view.reset();
+ });
+ bool? result;
+ await tester.pumpWidget(
+ _frame(
+ scale: enlarged ? 1.7 : 1,
+ highContrast: enlarged,
+ child: Builder(
+ builder: (context) => TextButton(
+ onPressed: () async => result = await confirmSwitchAnyway(
+ context,
+ model: 'DeepSeek-V4-Flash',
+ offline: const GridModelUnavailable(
+ machine: 'Studio · remote development workstation',
+ ),
+ ),
+ child: const Text('Choose offline model'),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Choose offline model'));
+ await tester.pumpAndSettle();
+ expect(find.text('Cancel').hitTestable(), findsOneWidget);
+ expect(find.text('Switch').hitTestable(), findsOneWidget);
+ final cancel = find.widgetWithText(TextButton, 'Cancel');
+ expect(
+ tester.widget<TextButton>(cancel).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ await _capture(tester, 'offline-confirmation-$label');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(result, isFalse);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+ }
+
+ testWidgets('terminal Find stays fixed while desktop options scale', (
+ tester,
+ ) async {
+ final originalBrightness = grid.AppTheme.brightness.value;
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(380, 440);
+ addTearDown(() {
+ grid.AppTheme.brightness.value = originalBrightness;
+ tester.view.reset();
+ });
+ final terminal = Terminal()..resize(80, 4);
+ terminal.write('Marker\r\nmarker\r\n');
+ final search = TerminalSearch(terminal);
+ addTearDown(search.dispose);
+ await tester.runAsync(() async {
+ search.setQuery('marker');
+ await search.settled;
+ });
+ final bar = SizedBox(
+ width: 300,
+ child: TerminalFindBar(
+ search: search,
+ onQuery: (query, sensitive) =>
+ search.setQuery(query, caseSensitive: sensitive),
+ onStep: search.step,
+ onClose: () {},
+ onFocus: () {},
+ ),
+ );
+ final editor = find.byType(TextField);
+ Rect? initialBounds;
+ TextEditingController? initialController;
+ for (final brightness in Brightness.values) {
+ grid.AppTheme.brightness.value = brightness;
+ for (final scale in [1.0, 1.7]) {
+ await tester.pumpWidget(
+ _frame(child: bar, scale: scale, highContrast: scale > 1),
+ );
+ await tester.pumpAndSettle();
+ final controller = tester.widget<TextField>(editor).controller!;
+ initialBounds ??= tester.getRect(find.byType(TerminalFindBar));
+ initialController ??= controller;
+ expect(tester.getRect(find.byType(TerminalFindBar)), initialBounds);
+ expect(controller, same(initialController));
+ expect(controller.text, 'marker');
+ expect(MediaQuery.textScalerOf(tester.element(editor)).scale(10), 10);
+ expect(
+ tester.widget<TextField>(editor).style!.fontFamily,
+ terminalFontStore.value.fontFamily,
+ );
+ await tester.tap(find.byTooltip('Find options'));
+ await tester.pumpAndSettle();
+ expect(
+ MediaQuery.textScalerOf(tester.element(find.text('Match case')))
+ .scale(10),
+ scale * 10,
+ );
+ expect(
+ tester.widget<Text>(find.text('Match case')).style!.fontFamily,
+ DesktopChrome.control().fontFamily,
+ );
+ final menuBounds = tester.getRect(_menu);
+ expect(menuBounds.left, greaterThanOrEqualTo(8));
+ expect(menuBounds.right, lessThanOrEqualTo(372));
+ final matchCase = find.widgetWithText(TextButton, 'Match case');
+ expect(
+ tester
+ .widget<Material>(
+ find.descendant(of: matchCase, matching: find.byType(Material)),
+ )
+ .color,
+ grid.AppDesktop.selection,
+ );
+ expect(
+ tester.widget<Text>(find.text('Match case')).style!.color,
+ grid.AppDesktop.onSelection,
+ );
+ expect(
+ tester
+ .widget<Text>(
+ find.descendant(
+ of: matchCase,
+ matching: find.text(search.caseSensitive ? 'On' : 'Off'),
+ ),
+ )
+ .style!
+ .color,
+ grid.AppDesktop.onSelection,
+ );
+ if (search.caseSensitive) {
+ expect(
+ tester
+ .widget<Icon>(
+ find.descendant(
+ of: matchCase,
+ matching: find.byIcon(AppIcons.check),
+ ),
+ )
+ .color,
+ grid.AppDesktop.onSelection,
+ );
+ }
+ await _capture(tester, 'find-options-${brightness.name}-$scale');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(search.caseSensitive, scale == 1);
+ expect(controller.text, 'marker');
+ expect(tester.widget<TextField>(editor).focusNode!.hasFocus, isTrue);
+ expect(tester.takeException(), isNull);
+ }
+ }
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/pane_menu_row_test.dart b/desktop/test/pane_menu_row_test.dart
index 52193410a..b7e428522 100644
--- a/desktop/test/pane_menu_row_test.dart
+++ b/desktop/test/pane_menu_row_test.dart
@@ -1,12 +1,13 @@
-// `PaneMenuRow` and `paneMenuItem` on their own terms.
-//
-// These assertions used to live in `grid_model_picker_test`, because the model picker was the only
-// thing drawing these rows. It is not any more — it has its own panel — but the find bar and the
-// New Harness box still use them, and the two bugs pinned here were real: a hover the eye could
-// not tell from a selection, and trailing columns that landed at a different offset on every row.
+// The live action's active state and the retained legacy row's column geometry.
+// PaneMenuRow is no longer used by production menus.
+import 'dart:ui' as ui;
+
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/theme/app_theme.dart';
+import 'package:harness/widgets/model_picker_chrome.dart';
import 'package:harness/widgets/pane_menu.dart';
void main() {
@@ -29,28 +30,71 @@ void main() {
Widget item(Widget row) => paneMenuItem(onTap: () {}, child: row);
- testWidgets('hover has its own colour, and focus paints none', (tester) async {
- // Two rows looked equally chosen: one was SELECTED and the other was merely under the pointer
- // or holding focus, and all three states painted the same fill.
- await show(tester, [
- item(const PaneMenuRow(selected: true, title: 'chosen', status: 'here')),
- item(const PaneMenuRow(selected: false, title: 'other', status: 'there')),
- ]);
+ testWidgets(
+ 'active fill and saved checkmark stay distinct without moving the row',
+ (tester) async {
+ await show(tester, [
+ ModelPickerRow(
+ selected: true,
+ title: 'chosen',
+ subtitle: 'here',
+ onTap: () {},
+ ),
+ ModelPickerRow(
+ selected: false,
+ title: 'other',
+ subtitle: 'there',
+ onTap: () {},
+ ),
+ ]);
- for (final well in tester.widgetList<InkWell>(find.byType(InkWell))) {
- // Stated, not inherited: the Material default sat close enough to the selected fill to be
- // indistinguishable.
- expect(well.hoverColor, AppColors.rowHover);
- // An ink ripple is a THIRD fill on the same rectangle, and it lingers past the tap.
- expect(well.splashColor, Colors.transparent);
- expect(well.highlightColor, Colors.transparent);
- // Focus is a keyboard position, not a decision — and a menu focuses its first row as it
- // opens, so painting it lit a row before the pointer had moved.
- expect(well.focusColor, Colors.transparent);
- }
- expect(AppColors.rowHover, isNot(AppColors.selected));
- expect(AppColors.rowHover.a, lessThan(AppColors.selected.a));
- });
+ final chosen = find.widgetWithText(TextButton, 'chosen');
+ final other = find.widgetWithText(TextButton, 'other');
+ Material material(Finder row) => tester.widget<Material>(
+ find.descendant(of: row, matching: find.byType(Material)),
+ );
+ expect(material(chosen).color, grid.AppSurface.accentWash);
+ expect(material(other).color, Colors.transparent);
+ expect(
+ find.descendant(of: chosen, matching: find.byIcon(AppIcons.check)),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: other, matching: find.byIcon(AppIcons.check)),
+ findsNothing,
+ );
+ final before = tester.getRect(other);
+ final shape = material(other).shape;
+ final pointer = await tester.createGesture(
+ kind: ui.PointerDeviceKind.mouse,
+ );
+ await pointer.addPointer(location: const Offset(800, 600));
+ addTearDown(pointer.removePointer);
+ await pointer.moveTo(tester.getCenter(other));
+ await tester.pumpAndSettle();
+ expect(material(other).color, grid.AppDesktop.selection);
+ expect(
+ tester.widget<Text>(find.text('other')).style!.color,
+ grid.AppDesktop.onSelection,
+ );
+ expect(
+ tester.widget<Text>(find.text('there')).style!.color,
+ grid.AppDesktop.onSelection,
+ );
+ expect(material(chosen).color, grid.AppSurface.accentWash);
+ expect(material(other).shape, shape);
+ expect(tester.getRect(other), before);
+
+ await pointer.moveTo(const Offset(800, 600));
+ Focus.of(tester.element(find.text('other'))).requestFocus();
+ await tester.pumpAndSettle();
+ expect(material(other).color, grid.AppDesktop.selection);
+ expect(material(other).shape, shape);
+ expect(tester.getRect(other), before);
+ expect(find.byIcon(AppIcons.check), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ },
+ );
testWidgets('only the chosen row is filled', (tester) async {
await show(tester, [
@@ -74,40 +118,41 @@ void main() {
expect(fillOf('other')?.color, isNull);
});
- testWidgets('trailing metadata shares one right edge, whatever the row holds', (
- tester,
- ) async {
- // Every trailing field was a `Flexible`, whose flex is ONE — so a row's spare width was split
- // evenly between the title and each field beside it. A row with two fields put them a third
- // and two thirds across; a row with one put it halfway. Three columns, three offsets.
- await show(tester, [
- item(const PaneMenuRow(selected: false, title: 'one', status: 'a')),
- item(
- const PaneMenuRow(
- selected: false,
- title: 'two',
- status: 'firmware-engineer-daniel',
+ testWidgets(
+ 'trailing metadata shares one right edge, whatever the row holds',
+ (tester) async {
+ // Every trailing field was a `Flexible`, whose flex is ONE — so a row's spare width was split
+ // evenly between the title and each field beside it. A row with two fields put them a third
+ // and two thirds across; a row with one put it halfway. Three columns, three offsets.
+ await show(tester, [
+ item(const PaneMenuRow(selected: false, title: 'one', status: 'a')),
+ item(
+ const PaneMenuRow(
+ selected: false,
+ title: 'two',
+ status: 'firmware-engineer-daniel',
+ ),
),
- ),
- item(
- const PaneMenuRow(
- selected: false,
- title: 'three',
- detail: '7f0c59',
- status: '11% remaining',
+ item(
+ const PaneMenuRow(
+ selected: false,
+ title: 'three',
+ detail: '7f0c59',
+ status: '11% remaining',
+ ),
),
- ),
- ]);
+ ]);
- final edges = [
- tester.getRect(find.text('a')).right,
- tester.getRect(find.text('firmware-engineer-daniel')).right,
- tester.getRect(find.text('11% remaining')).right,
- ];
- for (final edge in edges) {
- expect((edge - edges.first).abs(), lessThan(0.5));
- }
- });
+ final edges = [
+ tester.getRect(find.text('a')).right,
+ tester.getRect(find.text('firmware-engineer-daniel')).right,
+ tester.getRect(find.text('11% remaining')).right,
+ ];
+ for (final edge in edges) {
+ expect((edge - edges.first).abs(), lessThan(0.5));
+ }
+ },
+ );
testWidgets('a long trailing field ellipsizes instead of eating the title', (
tester,
diff --git a/desktop/test/pane_model_status_test.dart b/desktop/test/pane_model_status_test.dart
index 5b859ac95..34f5463da 100644
--- a/desktop/test/pane_model_status_test.dart
+++ b/desktop/test/pane_model_status_test.dart
@@ -294,7 +294,7 @@ void main() {
await tester.tap(find.text('Pick another'));
await tester.pumpAndSettle();
// The pane's own model picker, open on its models.
- expect(find.text('SUBSCRIPTION'), findsOneWidget);
+ expect(find.text('Subscription'), findsOneWidget);
expect(find.text('Gemma-4-12B'), findsOneWidget);
},
);
diff --git a/desktop/test/pane_needs_link_test.dart b/desktop/test/pane_needs_link_test.dart
index d032ab830..da16b6c3e 100644
--- a/desktop/test/pane_needs_link_test.dart
+++ b/desktop/test/pane_needs_link_test.dart
@@ -153,7 +153,7 @@ void main() {
find.byKey(const Key('remote-password-connect-field')),
'correct horse battery staple',
);
- await tester.tap(find.text('enter link machine'));
+ await tester.tap(find.text('Link machine'));
await tester.pumpAndSettle();
expect(link.asked, ['correct horse battery staple']);
diff --git a/desktop/test/pane_tab_cleanup_test.dart b/desktop/test/pane_tab_cleanup_test.dart
index fbad67114..92d87dba5 100644
--- a/desktop/test/pane_tab_cleanup_test.dart
+++ b/desktop/test/pane_tab_cleanup_test.dart
@@ -12,7 +12,7 @@ import 'package:harness/state/swarm.dart';
import 'package:harness/state/terminal_pane.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/agent_drag.dart' show PaneCloseButton;
-import 'package:harness/widgets/workspace_bar_control.dart';
+import 'package:harness/widgets/desktop_workspace_tab.dart';
import 'package:harness/widgets/workspace_welcome.dart';
import 'package:xterm/xterm.dart' show TerminalView;
@@ -301,7 +301,7 @@ void main() {
if (native) 'pane menu',
if (native) 'viewer toggle',
'tab shortcut',
- if (native) 'tab strip close',
+ 'tab strip close',
]) {
testWidgets(
'closing by $road leaves the keyboard on the tab strip until Enter '
@@ -386,8 +386,23 @@ void main() {
});
case 'tab shortcut':
await chord(tester, LogicalKeyboardKey.keyW);
- case 'tab strip close':
+ case 'tab strip close' when native:
await nativeCommand(tester, 'close', {'id': closingTab.id});
+ case 'tab strip close':
+ final mouse = await tester.createGesture(
+ kind: PointerDeviceKind.mouse,
+ );
+ await mouse.addPointer(location: const Offset(1200, 700));
+ await mouse.moveTo(
+ tester.getCenter(find.byKey(ValueKey(closingTab.id))),
+ );
+ await tester.pump();
+ final close = find
+ .byKey(ValueKey('tab-close:${closingTab.id}'))
+ .hitTestable();
+ await tester.tap(close);
+ await mouse.removePointer();
+ await tester.pump();
}
expect(app.swarms, [keptTab]);
@@ -567,10 +582,10 @@ final arrowAndWord = [27, 91, 68, ...utf8.encode('next')];
Map<Object?, Object?> lastUpdate(List<MethodCall> calls) =>
calls.lastWhere((call) => call.method == 'update').arguments as Map;
-WorkspaceBarControl stripTab(WidgetTester tester, String id) =>
- tester.widget<WorkspaceBarControl>(
+DesktopWorkspaceTab stripTab(WidgetTester tester, String id) =>
+ tester.widget<DesktopWorkspaceTab>(
find.descendant(
of: find.byKey(ValueKey(id)),
- matching: find.byType(WorkspaceBarControl),
+ matching: find.byType(DesktopWorkspaceTab),
),
);
diff --git a/desktop/test/rename_keyboard_test.dart b/desktop/test/rename_keyboard_test.dart
index 0aafca1f4..41697e418 100644
--- a/desktop/test/rename_keyboard_test.dart
+++ b/desktop/test/rename_keyboard_test.dart
@@ -128,6 +128,37 @@ void main() {
},
);
+ testWidgets(
+ 'rename Tab traversal wraps between the field and visible actions',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await command(tester, 'rename agent');
+ expect(field(tester, _agent).focusNode!.hasPrimaryFocus, isTrue);
+
+ Future<void> tabTo(String label, {bool backwards = false}) async {
+ await key(tester, LogicalKeyboardKey.tab, shift: backwards);
+ expect(
+ Focus.of(tester.element(find.text(label))).hasPrimaryFocus,
+ isTrue,
+ reason: 'Tab should land on the visible $label button',
+ );
+ }
+
+ await tabTo('Cancel');
+ await tabTo('Save');
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(field(tester, _agent).focusNode!.hasPrimaryFocus, isTrue);
+ await tabTo('Save', backwards: true);
+ await tabTo('Cancel', backwards: true);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(field(tester, _agent).focusNode!.hasPrimaryFocus, isTrue);
+ expect(connection.renames, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
testWidgets(
'live custom rename keys, disabled defaults and composition keep ownership',
(tester) async {
@@ -142,7 +173,7 @@ void main() {
await mount(tester);
await key(tester, LogicalKeyboardKey.f2);
await tester.pumpAndSettle();
- expect(find.text('F8 save'), findsOneWidget);
+ expect(find.byTooltip('Save · F8'), findsOneWidget);
tester.testTextInput.enterText('Updated');
final editor = field(tester, _agent).controller!;
editor.value = editor.value.copyWith(
@@ -163,13 +194,13 @@ void main() {
{"keys":"f4","command":"picker.cancel","when":"picker"}
]}''');
await tester.pump();
- expect(find.text('F10 save'), findsOneWidget);
+ expect(find.byTooltip('Save · F10'), findsOneWidget);
await key(tester, LogicalKeyboardKey.f10);
connection.replies.single.complete({});
await tester.pumpAndSettle();
await command(tester, 'rename tab');
expect(field(tester, _tab).focusNode!.hasPrimaryFocus, isTrue);
- expect(find.text('F10 save'), findsOneWidget);
+ expect(find.byTooltip('Save · F10'), findsOneWidget);
tester.testTextInput.enterText('Named tab');
await key(tester, LogicalKeyboardKey.f10);
expect(app.activeSwarm.name, 'Named tab');
@@ -252,9 +283,10 @@ void main() {
await command(tester, 'rename agent');
tester.testTextInput.enterText('');
await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
expect(find.text('Name cannot be empty'), findsOneWidget);
expect(_agent.hitTestable(), findsOneWidget);
- expect(find.text('esc close').hitTestable(), findsOneWidget);
+ expect(find.text('Cancel').hitTestable(), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
},
diff --git a/desktop/test/resource_picker_test.dart b/desktop/test/resource_picker_test.dart
index 7158e62e9..daf6c3d7b 100644
--- a/desktop/test/resource_picker_test.dart
+++ b/desktop/test/resource_picker_test.dart
@@ -16,11 +16,11 @@ import 'package:harness/models/api_connections_controller.dart';
import 'package:harness/models/model_search_catalog.dart'
show ModelSearchSection;
import 'package:harness/widgets/api_picker_form.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/theme/color_palette.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/terminal/terminal_text.dart';
-import 'package:harness/terminal/terminal_theme.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/widgets/swarm_resource_preview.dart';
import 'package:harness/widgets/machine_picker_form.dart';
@@ -40,6 +40,25 @@ final field = find.byKey(const ValueKey('swarm-search-input'));
SwarmSearchController search(WidgetTester tester) =>
tester.widget<SwarmSearchResults>(find.byType(SwarmSearchResults)).search;
+Future<void> tabTo(
+ WidgetTester tester,
+ Finder target, {
+ bool backwards = false,
+}) async {
+ for (var attempt = 0; attempt < 40; attempt++) {
+ final targets = target.evaluate().toSet();
+ final focused = FocusManager.instance.primaryFocus?.context;
+ var contains = targets.contains(focused);
+ focused?.visitAncestorElements((element) {
+ if (targets.contains(element)) contains = true;
+ return !contains;
+ });
+ if (contains) return;
+ await key(tester, LogicalKeyboardKey.tab, shift: backwards);
+ }
+ fail('Tab could not reach $target');
+}
+
Future<ModelManagerTestApp> fixture({ModelManagerTestApp? provided}) async {
final app = provided ?? ModelManagerTestApp(ModelManagerConnection());
await seedPreviews(app);
@@ -298,7 +317,18 @@ void main() {
expect(origin.managing, isTrue);
await tester.enterText(password, 'fixture password');
await key(tester, LogicalKeyboardKey.tab);
- expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(
+ tester
+ .widget<TextButton>(
+ find.descendant(
+ of: find.byKey(const ValueKey('machine-form:Connect')),
+ matching: find.byType(TextButton),
+ ),
+ )
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
expect(origin.selected!.machineId, 'other');
expect(app.edits, isEmpty);
await key(tester, LogicalKeyboardKey.tab, shift: true);
@@ -399,15 +429,15 @@ void main() {
const ValueKey('swarm-search-resource-actions'),
);
expect(
- find.descendant(of: actions, matching: find.text('[ Password ]')),
+ find.descendant(of: actions, matching: find.text('Password')),
findsOneWidget,
);
expect(
- find.descendant(of: actions, matching: find.text('[ Rename ]')),
+ find.descendant(of: actions, matching: find.text('Rename')),
findsOneWidget,
);
expect(
- find.descendant(of: actions, matching: find.text('[ Actions… ]')),
+ find.descendant(of: actions, matching: find.text('Actions…')),
findsNothing,
);
await key(tester, LogicalKeyboardKey.enter);
@@ -439,7 +469,7 @@ void main() {
expect(controller.selected!.id, selectedId);
expect(controller.managing, isTrue);
await key(tester, LogicalKeyboardKey.tab);
- expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(button('picker.resource_settings').focusNode!.hasFocus, isTrue);
await key(tester, LogicalKeyboardKey.tab, shift: true);
expect(button('picker.resource_view').focusNode!.hasFocus, isTrue);
await key(tester, LogicalKeyboardKey.escape);
@@ -466,7 +496,10 @@ void main() {
findsNothing,
);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
- await key(tester, LogicalKeyboardKey.tab);
+ await tabTo(
+ tester,
+ find.byKey(const ValueKey('resource-action:picker.model_download')),
+ );
expect(controller.managing, isTrue);
expect(button('picker.model_download').focusNode!.hasFocus, isTrue);
expect(app.actions, isEmpty);
@@ -677,7 +710,7 @@ void main() {
await tester.enterText(field, ':Qwen3.8-27B');
await tester.pumpAndSettle();
final origin = search(tester);
- expect(find.text('Enter Get · Tab pane'), findsOneWidget);
+ expect(find.text('Enter Get · Tab controls'), findsOneWidget);
await key(tester, LogicalKeyboardKey.enter);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
expect(app.downloads, [(machine: 'm', model: 'qwen')]);
@@ -769,10 +802,24 @@ void main() {
'Get models',
'Shared with you',
]) {
- expect(
+ await tester.scrollUntilVisible(
find.byKey(ValueKey('model-section:$heading')),
- findsOneWidget,
+ 120,
+ scrollable: find.descendant(
+ of: find.byKey(const ValueKey('swarm-search-result-list')),
+ matching: find.byType(Scrollable),
+ ),
);
+ final section = find.byKey(ValueKey('model-section:$heading'));
+ await tester.scrollUntilVisible(
+ section,
+ 160,
+ scrollable: find.descendant(
+ of: find.byKey(const ValueKey('swarm-search-result-list')),
+ matching: find.byType(Scrollable),
+ ),
+ );
+ expect(section, findsOneWidget);
}
// Four catalog models all fit in the list, so nothing is folded behind "More models".
expect(
@@ -817,16 +864,17 @@ void main() {
.map((row) => '${row.id}: ${row.title}')
.join('\n'),
);
- expect(find.text('Enter Use · Tab pane'), findsOneWidget);
+ expect(find.text('Enter Use · Tab controls'), findsOneWidget);
expect(find.text('M2'), findsOneWidget);
- expect(find.text('15 GB'), findsOneWidget);
+ // The memory estimate is visible in both the row and its preview.
+ expect(find.text('15 GB'), findsNWidgets(2));
await capture(tester, 'remote-model-select');
final origin = search(tester);
- await key(tester, LogicalKeyboardKey.tab);
- expect(origin.managing, isTrue);
final stop = find.byKey(
const ValueKey('resource-action:picker.model_stop'),
);
+ await tabTo(tester, stop);
+ expect(origin.managing, isTrue);
final button = tester.widget<TextButton>(
find.descendant(of: stop, matching: find.byType(TextButton)),
);
@@ -862,10 +910,16 @@ void main() {
'Get models',
'Shared with you',
]) {
- expect(
- find.byKey(ValueKey('model-section:$heading')),
- findsOneWidget,
+ final section = find.byKey(ValueKey('model-section:$heading'));
+ await tester.scrollUntilVisible(
+ section,
+ 160,
+ scrollable: find.descendant(
+ of: find.byKey(const ValueKey('swarm-search-result-list')),
+ matching: find.byType(Scrollable),
+ ),
);
+ expect(section, findsOneWidget);
}
await capture(tester, 'model-sections');
await tester.enterText(field, ':gemma-4-12B');
@@ -979,7 +1033,7 @@ void main() {
expect(tester.widget<TextField>(field).controller!.text, isEmpty);
expect(tester.widget<TextField>(field).cursorWidth, 2);
expect(find.byKey(const ValueKey('swarm-search-prompt')), findsNothing);
- final hints = find.byKey(const ValueKey('swarm-search-type-hints'));
+ final hints = find.byKey(const ValueKey('search-category-Harnesses'));
expect(hints, findsOneWidget);
expect(search(tester).selected, isNull);
await key(tester, LogicalKeyboardKey.enter);
@@ -989,7 +1043,7 @@ void main() {
expect(search(tester).rows.any((row) => row.agentId != null), isTrue);
await tester.enterText(field, ':qwen');
await tester.pump();
- expect(hints, findsNothing);
+ expect(hints, findsOneWidget);
expect(search(tester).isModelMode, isTrue);
await key(tester, LogicalKeyboardKey.escape);
await key(tester, LogicalKeyboardKey.keyP, cmd: mac, ctrl: !mac);
@@ -1007,7 +1061,7 @@ void main() {
shift: true,
);
expect(search(tester).isCommandMode, isTrue);
- expect(hints, findsNothing);
+ expect(hints, findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
} finally {
await tester.pumpWidget(const SizedBox());
@@ -1022,7 +1076,7 @@ void main() {
);
testWidgets(
- 'empty search shows hints in the preview until a result is selected',
+ 'empty search keeps visible native scopes without selecting a result',
(tester) async {
final app = await fixture();
final originalFont = terminalFontStore.value;
@@ -1035,43 +1089,34 @@ void main() {
});
await mount(tester, app);
await key(tester, LogicalKeyboardKey.keyP, cmd: true);
- final hints = find.byKey(const ValueKey('swarm-search-type-hints'));
+ final harnesses = find.byKey(const ValueKey('search-category-Harnesses'));
final input = tester.widget<TextField>(field);
final inputPosition = tester.getTopLeft(field);
final listPosition = tester.getTopLeft(
find.byKey(const ValueKey('swarm-search-result-list')),
);
- const hintLabels = [
- '@ machines',
- '# projects',
- ': models',
- '* store',
- '> commands',
- ];
- expect(
- tester
- .widgetList<Text>(
- find.descendant(of: hints, matching: find.byType(Text)),
- )
- .map((text) => text.data),
- hintLabels,
- );
+ for (final category in [
+ 'Harnesses',
+ 'Machines',
+ 'Projects',
+ 'Models',
+ 'Store',
+ 'Commands',
+ ]) {
+ expect(
+ find.byKey(ValueKey('search-category-$category')),
+ findsOneWidget,
+ );
+ }
final controller = search(tester);
expect(controller.selected, isNull);
expect(controller.rows.any((row) => row.isCreate), isFalse);
- expect(find.text('New Harness'), findsNothing);
- expect(
- tester.getRect(hints).left,
- greaterThanOrEqualTo(
- tester
- .getRect(find.byKey(const ValueKey('swarm-search-result-list')))
- .right,
- ),
- );
+ expect(find.byType(SwarmResourcePreview), findsNothing);
+ expect(tester.getBottomLeft(harnesses).dy, lessThan(listPosition.dy));
for (final row in controller.rows) {
final line = find.byKey(ValueKey('swarm-search-line:${row.id}'));
if (line.evaluate().isNotEmpty) {
- expect(tester.widget<Container>(line).color, Colors.transparent);
+ expect(tester.widget<Material>(line).color, Colors.transparent);
}
}
app.machineStates['m']!.agents.add(
@@ -1084,19 +1129,19 @@ void main() {
app.notifyListeners();
await tester.pump();
expect(controller.selected, isNull);
- await capture(tester, 'empty-type-hints');
+ await capture(tester, 'empty-native-scopes');
await key(tester, LogicalKeyboardKey.arrowDown);
expect(controller.selected, controller.rows.first);
- expect(hints, findsNothing);
+ expect(find.byType(SwarmResourcePreview), findsOneWidget);
await key(tester, LogicalKeyboardKey.tab);
expect(controller.selected, controller.rows.first);
- expect(controller.managing, isTrue);
- await key(tester, LogicalKeyboardKey.escape);
+ expect(controller.managing, isFalse);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(input.focusNode!.hasFocus, isTrue);
await tester.enterText(field, 'search');
await tester.pump();
- expect(hints, findsNothing);
expect(controller.selected!.isCreate, isFalse);
expect(
controller.selected,
@@ -1118,16 +1163,16 @@ void main() {
await tester.enterText(field, '');
await tester.pump();
expect(controller.selected, isNull);
- expect(hints, findsOneWidget);
+ expect(find.byType(SwarmResourcePreview), findsNothing);
await key(tester, LogicalKeyboardKey.arrowUp);
expect(controller.selected, controller.rows.last);
for (final prefix in ['@', '#', ':', '*']) {
await tester.enterText(field, prefix);
await tester.pump();
- expect(hints, findsNothing);
+ expect(controller.showsTypeHints, isFalse);
expect(controller.selected!.isCreate, isFalse);
await key(tester, LogicalKeyboardKey.backspace);
- expect(hints, findsOneWidget);
+ expect(controller.showsTypeHints, isTrue);
expect(controller.selected, isNull);
}
@@ -1139,21 +1184,19 @@ void main() {
);
tester.view.physicalSize = const Size(480, 600);
await tester.pumpAndSettle();
- final compact = find
- .descendant(of: hints, matching: find.byType(Text))
- .first;
- final compactStyle = DefaultTextStyle.of(tester.element(compact)).style;
- expect(tester.widget<Text>(compact).data, hintLabels.first);
- expect(compactStyle.fontSize, 18);
- expect(
- compactStyle.color,
- terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- ).foreground.withValues(alpha: .54),
+ final compact = find.descendant(
+ of: harnesses,
+ matching: find.byType(Text),
);
+ final text = tester.widget<Text>(compact);
+ final style = DefaultTextStyle.of(tester.element(compact)).style
+ .merge(text.style);
+ expect(text.data, 'Harnesses');
+ expect(style.fontSize, grid.AppType.bodySize);
+ expect(style.fontFamily, grid.AppType.sansFamily);
+ expect(style.color, DesktopChrome.foreground);
expect(tester.takeException(), isNull);
- await capture(tester, 'narrow-type-hints');
+ await capture(tester, 'narrow-native-scopes');
await tester.pumpWidget(const SizedBox());
app.dispose();
},
@@ -1440,7 +1483,10 @@ void main() {
await key(tester, LogicalKeyboardKey.arrowDown, shift: true);
expect(
position().pixels,
- closeTo(terminalCellSizeOf(tester.element(field)).height, .01),
+ closeTo(
+ MediaQuery.textScalerOf(tester.element(field)).scale(13) * 1.5,
+ .01,
+ ),
);
await key(tester, LogicalKeyboardKey.arrowUp, shift: true);
await key(tester, LogicalKeyboardKey.arrowUp, shift: true);
@@ -1454,7 +1500,10 @@ void main() {
await key(tester, LogicalKeyboardKey.arrowDown, shift: true);
expect(
position().pixels,
- closeTo(terminalCellSizeOf(tester.element(field)).height, .01),
+ closeTo(
+ MediaQuery.textScalerOf(tester.element(field)).scale(13) * 1.5,
+ .01,
+ ),
);
controller.scrollPreview(10000);
await tester.pumpAndSettle();
@@ -1489,7 +1538,7 @@ void main() {
await tester.pump();
expect(controller.selected, isNull);
expect(
- find.byKey(const ValueKey('swarm-search-type-hints')),
+ find.byKey(const ValueKey('search-category-Harnesses')),
findsOneWidget,
);
controller.setQuery('*blender');
@@ -1526,7 +1575,13 @@ void main() {
expect(origin.managing, isTrue);
expect(origin.scopedMachineId, isNull);
expect(tester.getTopLeft(field), inputPosition);
- expect(find.text(origin.title), findsNothing);
+ expect(
+ find.descendant(
+ of: find.byType(SwarmResourcePreview),
+ matching: find.text(origin.title),
+ ),
+ findsNothing,
+ );
expect(find.byType(TextField), findsOneWidget);
expect(app.actions, isEmpty);
await capture(tester, 'machine-management');
@@ -1636,7 +1691,10 @@ void main() {
await key(tester, LogicalKeyboardKey.enter);
expect(controller.managing, isFalse);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
- await key(tester, LogicalKeyboardKey.tab);
+ await tabTo(
+ tester,
+ find.byKey(const ValueKey('resource-action:picker.resource_settings')),
+ );
expect(controller.managing, isTrue);
expect(find.byType(ApiPickerForm), findsNothing);
await key(tester, LogicalKeyboardKey.enter);
@@ -1653,28 +1711,21 @@ void main() {
expect(focused(find.byKey(const ValueKey('api-form-input:url'))), isTrue);
await key(tester, LogicalKeyboardKey.tab);
expect(focused(find.byKey(const ValueKey('api-form-input:key'))), isTrue);
- await key(tester, LogicalKeyboardKey.tab);
- expect(
- tester
- .widget<Focus>(
- find
- .descendant(
- of: find.byKey(const ValueKey('api-form:save')),
- matching: find.byType(Focus),
- )
- .first,
- )
- .focusNode!
- .hasFocus,
- isTrue,
- );
+ // The fixed action row follows the fields and visibility control.
+ final save = find.byKey(const ValueKey('api-form:save'));
+ for (var step = 0; step < 5; step++) {
+ await key(tester, LogicalKeyboardKey.tab);
+ if (tester.widget<FilledButton>(save).focusNode!.hasFocus) break;
+ }
+ expect(tester.widget<FilledButton>(save).focusNode!.hasFocus, isTrue);
+ expect(save.hitTestable(), findsOneWidget);
expect(controller.managing, isTrue);
- await key(tester, LogicalKeyboardKey.tab);
+ await tabTo(tester, field);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
expect(controller.managing, isFalse);
await key(tester, LogicalKeyboardKey.enter);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
- await key(tester, LogicalKeyboardKey.tab, shift: true);
+ await tabTo(tester, name, backwards: true);
expect(tester.widget<TextField>(name).focusNode!.hasFocus, isTrue);
expect(tester.widget<TextField>(name).controller!.text, 'Draft API');
await capture(tester, 'api-edit-inline');
@@ -1722,10 +1773,6 @@ void main() {
height: 1.4,
);
await tester.pumpAndSettle();
- final theme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
final previewText = find.descendant(
of: find.byType(SwarmResourcePreview),
matching: find.byType(Text),
@@ -1734,14 +1781,14 @@ void main() {
for (final element in previewText.evaluate()) {
final text = element.widget as Text;
final style = DefaultTextStyle.of(element).style.merge(text.style);
- expect(style.fontSize, 18);
- expect(style.height, 1.4);
+ expect(style.fontFamily, grid.AppType.sansFamily);
+ expect(style.fontSize, isIn([11.0, 12.0, 13.0, 14.0, 15.0]));
expect(
style.color,
isIn([
- theme.foreground,
- theme.foreground.withValues(alpha: .54),
- theme.foreground.withValues(alpha: .28),
+ DesktopChrome.foreground,
+ DesktopChrome.muted,
+ Theme.of(element).colorScheme.error,
]),
);
}
@@ -1762,21 +1809,19 @@ void main() {
grid.AppTheme.palette.value = HarnessPalette.midnight;
terminalFontStore.value = originalFont;
await tester.pumpAndSettle();
- final commandTheme = terminalThemeFor(
- grid.AppTheme.palette.value,
- terminalThemeStore.value,
- );
final line = find.byKey(ValueKey('swarm-search-line:$commandId'));
- final cell = terminalCellSizeOf(tester.element(commandField));
- expect(tester.getSize(line).height, closeTo(cell.height, .01));
- expect(tester.widget<Container>(line).color, commandTheme.selection);
+ expect(tester.getSize(line).height, greaterThanOrEqualTo(32));
+ expect(
+ tester.widget<Material>(line).color,
+ DesktopChrome.activeSelection,
+ );
expect(
tester
.widget<Dialog>(
find.byKey(const ValueKey('resource-command-picker')),
)
.backgroundColor,
- commandTheme.background,
+ DesktopChrome.surface,
);
expect(commandSearch.selected!.id, commandId);
expect(
@@ -1853,14 +1898,13 @@ void main() {
),
findsWidgets,
);
- final cell = terminalCellSizeOf(tester.element(field));
final visibleRows = [
for (final row in controller.rows)
if (find.byKey(ValueKey(row.id)).evaluate().isNotEmpty) row,
];
for (final row in visibleRows) {
final result = find.byKey(ValueKey(row.id));
- expect(tester.getSize(result).height, closeTo(cell.height, .01));
+ expect(tester.getSize(result).height, greaterThanOrEqualTo(44));
expect(
tester
.widgetList<SearchResultText>(
@@ -1870,20 +1914,25 @@ void main() {
),
)
.map((text) => text.text),
- row.isCreate ? isEmpty : [row.title],
+ contains(
+ row.isCreate && controller.isModelMode
+ ? 'Add API connection'
+ : controller.isModelDownloadsRow(row)
+ ? controller.modelDownloadsVisible
+ ? 'Hide catalog'
+ : 'Get models'
+ : row.title,
+ ),
);
}
for (var i = 1; i < visibleRows.length; i++) {
- final sectionBreak =
- controller.isModelMode &&
- controller.modelSection(visibleRows[i]) !=
- controller.modelSection(visibleRows[i - 1]);
expect(
- tester.getTopLeft(find.byKey(ValueKey(visibleRows[i].id))).dy -
- tester
- .getTopLeft(find.byKey(ValueKey(visibleRows[i - 1].id)))
- .dy,
- closeTo(cell.height * (sectionBreak ? 3 : 1), .01),
+ tester.getTopLeft(find.byKey(ValueKey(visibleRows[i].id))).dy,
+ greaterThanOrEqualTo(
+ tester
+ .getBottomLeft(find.byKey(ValueKey(visibleRows[i - 1].id)))
+ .dy,
+ ),
);
}
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
diff --git a/desktop/test/restart_keyboard_test.dart b/desktop/test/restart_keyboard_test.dart
index c8d812297..e7acbe562 100644
--- a/desktop/test/restart_keyboard_test.dart
+++ b/desktop/test/restart_keyboard_test.dart
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/widgets/desktop_prompt_surface.dart';
import 'package:harness/core/models.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
@@ -107,7 +108,7 @@ void main() {
});
await tester.pumpAndSettle();
expect(find.text('Wait for the other operation.'), findsOneWidget);
- expect(find.text('enter retry'), findsOneWidget);
+ expect(find.text('Retry'), findsOneWidget);
await key(tester, LogicalKeyboardKey.enter);
expect(connection.requests, hasLength(2));
connection.restartReplies.last.complete(restartReceipt(id()));
@@ -134,7 +135,7 @@ void main() {
await tester.pumpAndSettle();
await key(tester, LogicalKeyboardKey.escape);
await open(tester);
- expect(find.text('enter check status'), findsOneWidget);
+ expect(find.text('Check status'), findsOneWidget);
expect(connection.requests, hasLength(1));
await key(tester, LogicalKeyboardKey.enter);
connection.checkReplies.single.complete(
@@ -147,7 +148,7 @@ void main() {
),
findsOneWidget,
);
- expect(find.text('enter close'), findsOneWidget);
+ expect(find.text('Close'), findsOneWidget);
await key(tester, LogicalKeyboardKey.enter);
expect(connection.requests, hasLength(1));
await tester.pumpAndSettle();
@@ -155,6 +156,54 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
+ testWidgets(
+ 'restart details can be selected while Tab still reaches the visible actions',
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await open(tester);
+ final detail = List.generate(
+ 12,
+ (index) => 'Diagnostic ${index + 1}: wait for the other operation.',
+ ).join('\n');
+ connection.restartReplies.single.complete({
+ 'creationId': id(),
+ 'state': 'failed',
+ 'failure': {'code': 'AGENT_BUSY', 'detail': detail},
+ });
+ await tester.pumpAndSettle();
+ final message = find.text(detail);
+ final editor = tester.widget<EditableText>(message);
+ await tester.tap(
+ find.ancestor(of: message, matching: find.byType(DesktopPromptMessage)),
+ );
+ await key(tester, LogicalKeyboardKey.keyA, cmd: true);
+ expect(editor.focusNode.hasPrimaryFocus, isTrue);
+ expect(editor.controller.selection.textInside(detail), detail);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ Focus.of(tester.element(find.text('Close'))).hasPrimaryFocus,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ Focus.of(tester.element(find.text('Retry'))).hasPrimaryFocus,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ Focus.of(tester.element(find.text('Close'))).hasPrimaryFocus,
+ isTrue,
+ );
+ expect(connection.requests, hasLength(1));
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(_prompt, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
testWidgets(
'restarting again after uncertainty requires a separate keyboard confirmation',
(tester) async {
@@ -238,7 +287,7 @@ void main() {
{"keys":"f4","command":"picker.cancel","when":"picker"}
]}''');
await tester.pump();
- expect(find.text('F4 close'), findsOneWidget);
+ expect(find.byTooltip('Close · F4'), findsOneWidget);
await key(tester, LogicalKeyboardKey.f4);
await tester.pumpAndSettle();
expect(_prompt, findsNothing);
@@ -247,28 +296,29 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
- testWidgets('enlarged short window keeps uncertainty and Escape visible', (
- tester,
- ) async {
- app.adoptSessionForTest(terminal('a0', []));
- await mount(tester, size: const Size(480, 360), scale: 1.7);
- await open(tester);
- expect(find.text('esc close').hitTestable(), findsOneWidget);
- connection.restartReplies.single.completeError(
- const WsRequestTimeout('agent_restart'),
- );
- await tester.pumpAndSettle();
- expect(find.text('Restart not confirmed.').hitTestable(), findsOneWidget);
- expect(find.text('esc close').hitTestable(), findsOneWidget);
- await key(tester, LogicalKeyboardKey.tab);
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(find.text('esc back').hitTestable(), findsOneWidget);
- expect(tester.takeException(), isNull);
- await key(tester, LogicalKeyboardKey.escape);
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- expect(_prompt, findsNothing);
- await tester.pumpWidget(const SizedBox());
- });
+ testWidgets(
+ 'enlarged short window keeps uncertainty and close actions visible',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, size: const Size(480, 360), scale: 1.7);
+ await open(tester);
+ expect(find.text('Close').hitTestable(), findsOneWidget);
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Restart not confirmed.').hitTestable(), findsOneWidget);
+ expect(find.text('Close').hitTestable(), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Cancel').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_prompt, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
}
diff --git a/desktop/test/resting_model_picker_test.dart b/desktop/test/resting_model_picker_test.dart
index 6faca5ea9..ef06890c8 100644
--- a/desktop/test/resting_model_picker_test.dart
+++ b/desktop/test/resting_model_picker_test.dart
@@ -3,6 +3,7 @@
// row whose computers seem offline — and, with a daemon that sends none of it, the menu it always
// drew.
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
@@ -77,16 +78,16 @@ void main() {
expect(textsUnder(tester), [
'Qwen3.5-4B',
'Search models or machines',
- 'SUBSCRIPTION',
+ 'Subscription',
'Anthropic',
'Checking usage…',
- 'ON YOUR MACHINES',
+ 'On your machines',
'2',
'Qwen3.5-4B',
'macbook',
'LFM2.5-8B',
'studio · seems offline',
- 'SHARED · TEAM',
+ 'Shared · team',
'1',
'DeepSeek-V4-Flash',
'scholes-60001',
@@ -135,7 +136,7 @@ void main() {
);
// Under the heading, above the list it describes — and the list is still there to pick from.
expect(
- top(tester, find.text('ON YOUR MACHINES')) <
+ top(tester, find.text('On your machines')) <
top(tester, find.text(subtitle)),
isTrue,
);
@@ -156,7 +157,7 @@ void main() {
]);
await open(tester);
// A shared section that lists nothing is drawn while it has something to offer.
- expect(find.text('SHARED · TEAM'), findsOneWidget);
+ expect(find.text('Shared · team'), findsOneWidget);
expect(find.text('Show models'), findsOneWidget);
expect(find.text('usually 15–40 s'), findsOneWidget);
expect(saysGrid, findsNothing);
@@ -202,7 +203,7 @@ void main() {
section('team', state: 'asleep', lastKnownAge: 3600),
]);
await open(tester);
- expect(find.text('SHARED · TEAM'), findsOneWidget);
+ expect(find.text('Shared · team'), findsOneWidget);
expect(
find.text('Nobody was serving here when it went to sleep'),
findsOneWidget,
@@ -321,7 +322,11 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('Switch anyway?'), findsOneWidget);
expect(saysGrid, findsNothing);
- await tester.tap(find.text('Cancel'));
+ expect(
+ Focus.of(tester.element(find.text('Cancel'))).hasPrimaryFocus,
+ isTrue,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(find.text('Switch anyway?'), findsNothing);
expect(picked, isNull);
diff --git a/desktop/test/search_workspace_test.dart b/desktop/test/search_workspace_test.dart
index 2faed666d..568b63cb1 100644
--- a/desktop/test/search_workspace_test.dart
+++ b/desktop/test/search_workspace_test.dart
@@ -69,7 +69,7 @@ void main() {
findsNothing,
);
expect(
- find.byKey(const ValueKey('swarm-search-type-hints')),
+ find.byKey(const ValueKey('search-category-Harnesses')),
findsOneWidget,
);
await key(tester, LogicalKeyboardKey.escape);
diff --git a/desktop/test/session_search_rendering_test.dart b/desktop/test/session_search_rendering_test.dart
index c1ea59f19..1e42ab371 100644
--- a/desktop/test/session_search_rendering_test.dart
+++ b/desktop/test/session_search_rendering_test.dart
@@ -216,11 +216,6 @@ void main() {
);
final before = find.textContaining('answer 13', findRichText: true);
expect(newest, findsOneWidget);
- expect(before, findsOneWidget);
- expect(
- tester.getTopLeft(before).dy,
- lessThan(tester.getTopLeft(newest).dy),
- );
final listBox = tester.getRect(list);
expect(
tester.getBottomLeft(newest).dy,
@@ -231,10 +226,13 @@ void main() {
expect(find.textContaining('Matched earlier'), findsOneWidget);
// The searched words stand out in the turns.
final ask = tester.widget<RichText>(
- find.byWidgetPredicate(
- (widget) =>
- widget is RichText &&
- widget.text.toPlainText().contains('step 14 of the retention'),
+ find.descendant(
+ of: list,
+ matching: find.byWidgetPredicate(
+ (widget) =>
+ widget is RichText &&
+ widget.text.toPlainText().contains('step 14 of the retention'),
+ ),
),
);
final bold = <String>[];
@@ -262,12 +260,30 @@ void main() {
findsNothing,
);
- // The latest ask is in view, so nothing is pinned above the turns.
- expect(find.byKey(const ValueKey('preview-last-ask')), findsNothing);
+ // The long answer fills the viewport; the latest ask stays readable
+ // in the pinned header even while its original turn is above the fold.
+ expect(find.byKey(const ValueKey('preview-last-ask')), findsOneWidget);
// Shift-Up scrolls toward older turns, Shift-Down back.
final controller = tester.widget<ListView>(list).controller!;
expect(controller.position.pixels, 0);
+ // The latest long answer can fill the viewport. Reveal the preceding
+ // turn before checking order instead of depending on modal geometry.
+ await tester.scrollUntilVisible(
+ before,
+ 80,
+ scrollable: find.descendant(
+ of: list,
+ matching: find.byType(Scrollable),
+ ),
+ );
+ expect(before, findsOneWidget);
+ expect(
+ tester.getTopLeft(before).dy,
+ lessThan(tester.getTopLeft(newest).dy),
+ );
+ controller.jumpTo(0);
+ await tester.pump();
await key(tester, LogicalKeyboardKey.arrowUp, shift: true);
await tester.pump();
expect(controller.position.pixels, greaterThan(0));
@@ -289,8 +305,14 @@ void main() {
),
findsOneWidget,
);
- controller.jumpTo(controller.position.maxScrollExtent);
- await tester.pump();
+ await tester.scrollUntilVisible(
+ find.text('Start of conversation'),
+ 160,
+ scrollable: find.descendant(
+ of: list,
+ matching: find.byType(Scrollable),
+ ),
+ );
expect(
find.textContaining('answer 5', findRichText: true),
findsOneWidget,
diff --git a/desktop/test/session_work_dialog_test.dart b/desktop/test/session_work_dialog_test.dart
index 7ce13f5b6..538c9a03e 100644
--- a/desktop/test/session_work_dialog_test.dart
+++ b/desktop/test/session_work_dialog_test.dart
@@ -5,11 +5,14 @@ import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
+import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/theme/color_palette.dart';
+import 'package:harness/shared/theme/pull_request_icon.dart';
import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'package:harness/widgets/session_work_dialog.dart';
import 'package:xterm/xterm.dart' show TerminalStyle;
@@ -23,40 +26,49 @@ Future<void> captureDialog(
) async {
final output = Platform.environment['HARNESS_GIT_CONTEXT_CAPTURE_DIR'];
if (output == null) return;
- await tester.runAsync(() async {
- final render =
- boundary.currentContext!.findRenderObject()! as RenderRepaintBoundary;
- final picture = await render.toImage(pixelRatio: 1);
- final bytes = await picture.toByteData(format: ui.ImageByteFormat.png);
- await Directory(output).create(recursive: true);
- await File('$output/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
- picture.dispose();
- });
+ final oldShadows = debugDisableShadows;
+ void repaint(RenderObject object) {
+ object.markNeedsPaint();
+ object.visitChildren(repaint);
+ }
+
+ final render =
+ boundary.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ try {
+ debugDisableShadows = false;
+ repaint(render);
+ await tester.pumpAndSettle();
+ await tester.runAsync(() async {
+ final picture = await render.toImage(pixelRatio: 2);
+ final bytes = await picture.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(output).create(recursive: true);
+ await File('$output/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
+ picture.dispose();
+ });
+ } finally {
+ debugDisableShadows = oldShadows;
+ repaint(render);
+ await tester.pump();
+ }
}
void main() {
final capture = Platform.environment['HARNESS_GIT_CONTEXT_CAPTURE_DIR'];
setUpAll(() async {
- await loadRealFonts();
- // Optional local captures use the actual macOS terminal face. Portable
- // regression runs retain the shared metric-compatible test fonts.
- if (capture != null && Platform.isMacOS) {
- final bytes = await File('/System/Library/Fonts/SFNSMono.ttf')
- .readAsBytes();
- await (FontLoader(
- 'WorkDialogPreviewMono',
- )..addFont(Future.value(ByteData.sublistView(bytes)))).load();
- }
- });
- setUp(() {
- final old = terminalFontStore.value;
+ // Captures use the actual macOS system face. Portable regression runs
+ // retain the shared metric-compatible test fonts.
if (capture != null && Platform.isMacOS) {
- terminalFontStore.value = const TerminalStyle(
- fontFamily: 'WorkDialogPreviewMono',
- fontSize: 18,
- );
+ for (final (family, path) in [
+ ('.AppleSystemUIFont', '/System/Library/Fonts/SFNS.ttf'),
+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('Roboto', '/System/Library/Fonts/Supplemental/Arial.ttf'),
+ ]) {
+ final bytes = ByteData.sublistView(await File(path).readAsBytes());
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ } else {
+ await loadRealFonts();
}
- addTearDown(() => terminalFontStore.value = old);
});
testWidgets(
'PRs appear once and branches are a separate keyboard-accessible view',
@@ -147,6 +159,26 @@ void main() {
lessThan(360),
);
expect(find.text('Work location unknown'), findsNothing);
+ expect(find.byType(DesktopDialogSurface), findsOneWidget);
+ expect(
+ tester
+ .widget<Text>(find.text('Keep complete session previews'))
+ .style!
+ .fontFamily,
+ grid.AppType.sansFamily,
+ );
+ expect(
+ tester
+ .widgetList<SvgPicture>(find.byType(SvgPicture))
+ .map((icon) => (icon.bytesLoader as SvgAssetLoader).assetName),
+ [pullRequestIconAsset('Open'), pullRequestIconAsset('Merged')],
+ );
+ for (final state in ['Open', 'Merged']) {
+ expect(
+ tester.widget<Text>(find.text(state)).style!.color,
+ DesktopChrome.foreground,
+ );
+ }
await captureDialog(tester, boundary, 'pull-requests');
await tester.tap(
@@ -165,7 +197,12 @@ void main() {
expect(tester.takeException(), isNull);
await captureDialog(tester, boundary, 'branches');
tester
- .widget<TextButton>(find.byKey(const ValueKey('git-branches-tab')))
+ .widget<TextButton>(
+ find.descendant(
+ of: find.byKey(const ValueKey('git-branches-tab')),
+ matching: find.byType(TextButton),
+ ),
+ )
.focusNode!
.requestFocus();
await tester.pumpAndSettle();
@@ -243,11 +280,11 @@ void main() {
expect(find.text('Merged'), findsNWidgets(3));
expect(find.textContaining('completed'), findsNothing);
await captureDialog(tester, boundary, 'merged-pull-requests');
- await tester.tap(find.text('[ Load more ]'));
+ await tester.tap(find.widgetWithText(TextButton, 'Load more'));
await tester.pumpAndSettle();
expect(calls, [0, 4]);
expect(find.text('Merged'), findsNWidgets(3));
- expect(find.text('[ Load more ]'), findsNothing);
+ expect(find.widgetWithText(TextButton, 'Load more'), findsNothing);
expect(tester.takeException(), isNull);
},
);
@@ -295,6 +332,10 @@ void main() {
Focus.of(buttonContext).requestFocus();
await tester.pumpAndSettle();
final focus = FocusManager.instance.primaryFocus;
+ final rowRect = tester.getRect(target);
+ final dialogRect = tester.getRect(
+ find.byKey(const ValueKey('work-dialog-surface')),
+ );
final palette = grid.AppTheme.palette.value;
final theme = terminalThemeStore.value;
final font = terminalFontStore.value;
@@ -312,8 +353,122 @@ void main() {
await tester.pumpAndSettle();
expect(FocusManager.instance.primaryFocus, same(focus));
expect(target.hitTestable(), findsOneWidget);
+ expect(tester.getRect(target), rowRect);
+ expect(
+ tester.getRect(find.byKey(const ValueKey('work-dialog-surface'))),
+ dialogRect,
+ );
expect(find.textContaining('completed'), findsNothing);
expect(tester.takeException(), isNull);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(opened, [
+ Uri.parse('https://github.com/acme/app/pull/122'),
+ Uri.parse('https://github.com/acme/app/pull/122'),
+ ]);
+ },
+ );
+
+ testWidgets(
+ 'page keys scroll the active list, including overflowing branches',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(420, 420);
+ addTearDown(tester.view.reset);
+ final git = manyPrFixture();
+ (git['history']['branches'] as List).addAll(<Map<String, String>>[
+ for (var i = 0; i < 30; i++)
+ {
+ 'cwd': '/ship-hn',
+ 'remote': 'github.com/acme/app',
+ 'branch': 'feature/iteration-${i.toString().padLeft(2, '0')}',
+ 'at': '2026-09-27T13:00:00Z',
+ },
+ {
+ 'cwd': '/ship-hn',
+ 'remote': 'github.com/acme/app',
+ 'branch': 'z-last-branch',
+ 'at': '2026-09-27T13:00:00Z',
+ },
+ ]);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: const TextScaler.linear(1.6)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SessionWorkDialog(
+ agent: workAgent(git: git),
+ online: false,
+ read: (_) => throw StateError('Offline must not request data'),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ ScrollPosition position(String key) => tester
+ .state<ScrollableState>(
+ find.descendant(
+ of: find.byKey(ValueKey(key)),
+ matching: find.byType(Scrollable),
+ ),
+ )
+ .position;
+ final prs = position('git-prs-list');
+ expect(prs.maxScrollExtent, greaterThan(0));
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
+ await tester.pumpAndSettle();
+ expect(prs.pixels, greaterThan(0));
+ await tester.tap(find.byKey(const ValueKey('git-branches-tab')));
+ await tester.pumpAndSettle();
+ tester
+ .widget<DesktopPill>(find.byKey(const ValueKey('git-branches-tab')))
+ .focusNode!
+ .requestFocus();
+ await tester.pumpAndSettle();
+ final branches = position('git-branches-list');
+ expect(branches.maxScrollExtent, greaterThan(branches.viewportDimension));
+ expect(branches.pixels, 0);
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
+ await tester.pumpAndSettle();
+ expect(branches.pixels, greaterThan(0));
+ for (
+ var i = 0;
+ i < 60 && branches.pixels < branches.maxScrollExtent;
+ i++
+ ) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
+ await tester.pumpAndSettle();
+ }
+ expect(find.text('z-last-branch').hitTestable(), findsOneWidget);
+ for (var i = 0; i < 60 && branches.pixels > 0; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
+ await tester.pumpAndSettle();
+ }
+ expect(branches.pixels, 0);
+ expect(
+ find.text(git['current']['branch'] as String).hitTestable(),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const ValueKey('git-prs-tab')));
+ await tester.pumpAndSettle();
+ tester
+ .widget<DesktopPill>(find.byKey(const ValueKey('git-prs-tab')))
+ .focusNode!
+ .requestFocus();
+ await tester.pumpAndSettle();
+ final activePrs = position('git-prs-list');
+ final prOffset = activePrs.pixels;
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
+ await tester.pumpAndSettle();
+ expect(activePrs.pixels, greaterThan(prOffset));
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
+ await tester.pumpAndSettle();
+ expect(activePrs.pixels, closeTo(prOffset, .01));
+ expect(tester.takeException(), isNull);
},
);
@@ -357,66 +512,184 @@ void main() {
},
);
- for (final palette in [HarnessPalette.graphite, HarnessPalette.midnight]) {
- for (final size in [const Size(1000, 720), const Size(420, 680)]) {
- testWidgets(
- 'work details fit ${size.width} ${palette.name}, including enlarged text',
- (tester) async {
- tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = size;
- addTearDown(tester.view.reset);
- final old = grid.AppTheme.palette.value;
- grid.AppTheme.palette.value = palette;
- addTearDown(() => grid.AppTheme.palette.value = old);
- final boundary = GlobalKey();
- await tester.pumpWidget(
- grid.BrightnessScope(
- child: RepaintBoundary(
- key: boundary,
- child: MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- builder: (context, child) => MediaQuery(
- data: MediaQuery.of(context).copyWith(
- textScaler: TextScaler.linear(size.width < 500 ? 1.6 : 1),
+ for (final brightness in Brightness.values) {
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.midnight]) {
+ for (final size in [const Size(1000, 720), const Size(420, 680)]) {
+ testWidgets(
+ 'work details fit ${size.width} ${palette.name} ${brightness.name}, including enlarged text',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ final oldPalette = grid.AppTheme.palette.value;
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.palette.value = palette;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() {
+ grid.AppTheme.palette.value = oldPalette;
+ grid.AppTheme.brightness.value = oldBrightness;
+ });
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ grid.BrightnessScope(
+ child: RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(
+ size.width < 500 ? 1.6 : 1,
+ ),
+ ),
+ child: child!,
),
- child: child!,
- ),
- home: Scaffold(
- body: SessionWorkDialog(
- agent: workAgent(git: manyPrFixture()),
- online: false,
- read: (_) =>
- throw StateError('Offline must not request data'),
+ home: Scaffold(
+ body: SessionWorkDialog(
+ agent: workAgent(git: manyPrFixture()),
+ online: false,
+ read: (_) =>
+ throw StateError('Offline must not request data'),
+ ),
),
),
),
),
- ),
- );
- await tester.pumpAndSettle();
- expect(find.text('Offline'), findsOneWidget);
- expect(tester.takeException(), isNull);
- final output =
- Platform.environment['HARNESS_GIT_CONTEXT_CAPTURE_DIR'];
- if (output != null) {
- await tester.runAsync(() async {
- final render =
- boundary.currentContext!.findRenderObject()!
- as RenderRepaintBoundary;
- final picture = await render.toImage(pixelRatio: 1);
- final bytes = await picture.toByteData(
- format: ui.ImageByteFormat.png,
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Offline'), findsOneWidget);
+ expect(find.text('Pull requests (7)'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ final surface = tester.getRect(
+ find.byKey(const ValueKey('work-dialog-surface')),
+ );
+ expect(surface.left, greaterThanOrEqualTo(16));
+ expect(surface.right, lessThanOrEqualTo(size.width - 16));
+ expect(surface.top, greaterThanOrEqualTo(16));
+ expect(surface.bottom, lessThanOrEqualTo(size.height - 16));
+ final name =
+ 'work-${size.width.toInt()}-${palette.name}-${brightness.name}';
+ await captureDialog(tester, boundary, name);
+ if (size.width < 500 && palette == HarnessPalette.graphite) {
+ final last = find.byKey(
+ const ValueKey('work-pr-https://github.com/acme/app/pull/126'),
);
- await Directory(output).create(recursive: true);
- await File(
- '$output/work-${size.width.toInt()}-${palette.name}.png',
- ).writeAsBytes(bytes!.buffer.asUint8List());
- picture.dispose();
- });
- }
- },
- );
+ await tester.scrollUntilVisible(
+ last,
+ 100,
+ scrollable: find.descendant(
+ of: find.byKey(const ValueKey('git-prs-list')),
+ matching: find.byType(Scrollable),
+ ),
+ );
+ final rowContext = tester.element(
+ find.descendant(of: last, matching: find.byType(Row)).first,
+ );
+ Focus.of(rowContext).requestFocus();
+ await tester.pumpAndSettle();
+ expect(last.hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await captureDialog(tester, boundary, '$name-focused');
+ }
+ await tester.tap(find.byKey(const ValueKey('git-branches-tab')));
+ await tester.pumpAndSettle();
+ expect(find.text('Checked out'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await captureDialog(tester, boundary, '$name-branches');
+ },
+ );
+ }
}
+
+ testWidgets('work loading and errors stay readable in ${brightness.name}', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(420, 680);
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ final replies = [
+ Completer<Map<String, dynamic>>(),
+ Completer<Map<String, dynamic>>(),
+ ];
+ final offsets = <int>[];
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: const TextScaler.linear(1.6)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SessionWorkDialog(
+ agent: workAgent(),
+ read: (offset) {
+ offsets.add(offset);
+ return replies[offsets.length - 1].future;
+ },
+ open: (_) async => false,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Loading…'), findsOneWidget);
+ expect(
+ tester
+ .widget<TextButton>(find.widgetWithText(TextButton, 'Refreshing…'))
+ .onPressed,
+ isNull,
+ );
+ await captureDialog(tester, boundary, 'work-loading-${brightness.name}');
+ replies.first.complete({'status': 'unavailable'});
+ await tester.pumpAndSettle();
+ expect(find.text('No pull requests'), findsNothing);
+ expect(find.text('Work history is unavailable'), findsOneWidget);
+ expect(find.text('Pull requests (0)'), findsNothing);
+ expect(find.text('Could not refresh'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await captureDialog(
+ tester,
+ boundary,
+ 'work-empty-error-${brightness.name}',
+ );
+ await tester.tap(find.byKey(const ValueKey('git-branches-tab')));
+ await tester.pumpAndSettle();
+ expect(find.text('No branches'), findsNothing);
+ expect(find.text('Work history is unavailable'), findsOneWidget);
+ expect(find.text('Branches (0)'), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('git-prs-tab')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(TextButton, 'Refresh'));
+ await tester.pumpAndSettle();
+ final git = gitFixture();
+ replies.last.complete({'gitContext': git, 'history': git['history']});
+ await tester.pumpAndSettle();
+ expect(offsets, [0, 0]);
+ expect(find.text('Could not refresh'), findsNothing);
+ await tester.tap(
+ find.byKey(
+ const ValueKey('work-pr-https://github.com/acme/app/pull/12'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Could not open GitHub'), findsOneWidget);
+ expect(find.text('#12'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await captureDialog(
+ tester,
+ boundary,
+ 'work-open-error-${brightness.name}',
+ );
+ });
}
}
diff --git a/desktop/test/session_work_navigation_test.dart b/desktop/test/session_work_navigation_test.dart
index 2d5451a63..48195d9b7 100644
--- a/desktop/test/session_work_navigation_test.dart
+++ b/desktop/test/session_work_navigation_test.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/appearance_prefs_store.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/theme/prompt_style.dart';
import 'package:harness/shared/theme/status_line_style.dart';
import 'package:harness/state/workspace_status.dart';
@@ -78,6 +79,15 @@ void main() {
}
await tester.pumpAndSettle();
expect(find.byType(SessionWorkDialog), findsOneWidget);
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is ColoredBox &&
+ widget.color == grid.AppDesktop.darkVeil,
+ ),
+ findsOneWidget,
+ );
+ if (native) expect(updates.last['footerCovered'], isTrue);
expect(find.textContaining('/silent-beacon'), findsNothing);
expect(pane.session, same(session));
expect(input, isEmpty);
diff --git a/desktop/test/settings_review_render_test.dart b/desktop/test/settings_review_render_test.dart
index 50e2aeaca..de2bca7fe 100644
--- a/desktop/test/settings_review_render_test.dart
+++ b/desktop/test/settings_review_render_test.dart
@@ -56,8 +56,8 @@ void main() {
'packages/lucide_icons_flutter/assets/lucide.ttf',
),
(
- 'packages/lucide_icons_flutter/Lucide300',
- 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w300.ttf',
+ 'packages/lucide_icons_flutter/Lucide400',
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
),
]) {
await (FontLoader(family)..addFont(rootBundle.load(path))).load();
diff --git a/desktop/test/settings_screen_test.dart b/desktop/test/settings_screen_test.dart
index 07e916280..d923a96ae 100644
--- a/desktop/test/settings_screen_test.dart
+++ b/desktop/test/settings_screen_test.dart
@@ -7,6 +7,7 @@
// `HarnessFileStore` (the user's actual `~/.harness/desktop-app/state.json`).
// This only reads the store's untouched default.
import 'dart:async';
+import 'dart:ui' show SemanticsAction, Tristate;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -21,6 +22,8 @@ import 'package:harness/settings/settings_section.dart';
import 'package:harness/settings/experimental_features.dart';
import 'package:harness/settings/sections/shortcuts_section.dart';
import 'package:harness/shared/theme/app_theme.dart';
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/shared/layouts/widgets/sidebar_item.dart';
import 'package:harness/shortcuts/keyboard_practice.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/widgets/harness_customize_pane.dart';
@@ -124,6 +127,134 @@ void main() {
expect(tester.takeException(), isNull);
});
+ testWidgets('settings navigation announces and changes its selected section', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ await openSettings(tester);
+ Finder row(String label) => find.descendant(
+ of: find.byType(SettingsNav),
+ matching: find.widgetWithText(InkWell, label),
+ );
+ final usage = tester.getSemantics(row('Usage'));
+ final account = tester.getSemantics(row('Account'));
+ expect(usage.getSemanticsData().flagsCollection.isButton, isTrue);
+ expect(
+ usage.getSemanticsData().flagsCollection.isSelected,
+ Tristate.isTrue,
+ );
+ expect(
+ account.getSemanticsData().flagsCollection.isSelected,
+ Tristate.isFalse,
+ );
+ expect(account.getSemanticsData().hasAction(SemanticsAction.tap), isTrue);
+
+ // Assistive activation must take the same route as pointer/keyboard use.
+ tester
+ .renderObject(row('Account'))
+ .owner!
+ .semanticsOwner!
+ .performAction(account.id, SemanticsAction.tap);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<SettingsNav>(find.byType(SettingsNav)).section,
+ SettingsSection.account,
+ );
+ expect(
+ tester
+ .getSemantics(row('Account'))
+ .getSemanticsData()
+ .flagsCollection
+ .isSelected,
+ Tristate.isTrue,
+ );
+ expect(
+ tester
+ .getSemantics(row('Usage'))
+ .getSemanticsData()
+ .flagsCollection
+ .isSelected,
+ Tristate.isFalse,
+ );
+ } finally {
+ semantics.dispose();
+ }
+ });
+
+ testWidgets('shared sidebar semantics keep secondary actions independent', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ var opened = 0;
+ var closed = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: buildAppTheme(brightness: Brightness.light),
+ home: Scaffold(
+ body: SizedBox(
+ width: 260,
+ child: Column(
+ children: [
+ SidebarItem(
+ label: 'Workspace',
+ selected: true,
+ onTap: () => opened++,
+ trailingAlwaysVisible: true,
+ trailing: IconButton(
+ tooltip: 'Close workspace',
+ onPressed: () => closed++,
+ icon: const Icon(AppIcons.close),
+ ),
+ ),
+ SidebarItem(
+ label: 'Unavailable workspace',
+ enabled: false,
+ onTap: () => fail('Disabled rows must not activate'),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final primary = tester.getSemantics(find.text('Workspace'));
+ final secondary = tester.getSemantics(find.byTooltip('Close workspace'));
+ final disabled = tester.getSemantics(find.text('Unavailable workspace'));
+ expect(primary.getSemanticsData().flagsCollection.isButton, isTrue);
+ expect(
+ primary.getSemanticsData().flagsCollection.isSelected,
+ Tristate.isTrue,
+ );
+ expect(secondary.id, isNot(primary.id));
+ expect(secondary.getSemanticsData().flagsCollection.isButton, isTrue);
+ expect(
+ disabled.getSemanticsData().flagsCollection.isEnabled,
+ Tristate.isFalse,
+ );
+ expect(
+ disabled.getSemanticsData().hasAction(SemanticsAction.tap),
+ isFalse,
+ );
+ final owner = tester
+ .renderObject(find.text('Workspace'))
+ .owner!
+ .semanticsOwner!;
+ owner.performAction(secondary.id, SemanticsAction.tap);
+ await tester.pump();
+ expect(closed, 1);
+ expect(opened, 0);
+ owner.performAction(primary.id, SemanticsAction.tap);
+ await tester.pump();
+ expect(opened, 1);
+ expect(closed, 1);
+ } finally {
+ semantics.dispose();
+ }
+ });
+
testWidgets('About prints the running version', (tester) async {
await openSettings(tester);
diff --git a/desktop/test/setup_review_render_test.dart b/desktop/test/setup_review_render_test.dart
index 364d01e61..9ac5f5248 100644
--- a/desktop/test/setup_review_render_test.dart
+++ b/desktop/test/setup_review_render_test.dart
@@ -12,6 +12,7 @@ import 'package:harness/bootstrap/environment_provisioner.dart';
import 'package:harness/core/config.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/bootstrapping_screen.dart';
import 'package:harness/widgets/environment_preflight_screen.dart';
import 'package:harness/widgets/environment_setup_screen.dart';
@@ -30,9 +31,23 @@ class _NoInstall extends EnvironmentProvisioner {
void main() {
setUpAll(() async {
await loadRealFonts();
+ if (Platform.isMacOS) {
+ final bytes = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ }
await (FontLoader(
'MaterialIcons',
)..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
});
for (final brightness in Brightness.values) {
for (final scale in [1.0, 2.0]) {
@@ -132,8 +147,21 @@ void main() {
),
);
await tester.pump();
- expect(find.text(r'$ harness doctor').hitTestable(), findsOneWidget);
+ expect(
+ find.text('Checking this computer').hitTestable(),
+ findsOneWidget,
+ );
await capture('checking');
+ app.environmentReadiness = const EnvironmentReadiness(
+ steps: {
+ EnvironmentStep.clipboard: EnvironmentStepStatus.notApplicable,
+ EnvironmentStep.harness: EnvironmentStepStatus.running,
+ EnvironmentStep.tmux: EnvironmentStepStatus.ready,
+ },
+ );
+ app.notifyListeners();
+ await tester.pump();
+ await capture('checking-progress');
app.environmentReadiness = EnvironmentReadiness(
steps: {
for (final step in EnvironmentStep.values)
@@ -145,7 +173,7 @@ void main() {
await tester.pump();
await tester.pump();
expect(
- find.text('all checks passed · opening your workspace').hitTestable(),
+ find.text('All checks passed. Opening your workspace…').hitTestable(),
findsOneWidget,
);
await capture('ready');
@@ -189,6 +217,39 @@ void main() {
);
expect(find.text('Retry').hitTestable(), findsOneWidget);
await capture('copy-error');
+ final startupStatus = ValueNotifier('Starting local service…');
+ addTearDown(startupStatus.dispose);
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ disableAnimations: true,
+ textScaler: TextScaler.linear(scale),
+ ),
+ child: child!,
+ ),
+ home: ValueListenableBuilder(
+ valueListenable: startupStatus,
+ builder: (context, message, _) =>
+ BootstrappingScreen(statusMessage: message),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(
+ find.text('Opening your workspace').hitTestable(),
+ findsOneWidget,
+ );
+ await capture('startup');
+ startupStatus.value = 'Restoring your workspace…';
+ await tester.pump();
+ expect(find.text('Recent activity'), findsOneWidget);
+ await capture('startup-history');
await tester.pumpWidget(const SizedBox());
});
}
diff --git a/desktop/test/share_harness_test.dart b/desktop/test/share_harness_test.dart
index 482ef47c7..bcff2b755 100644
--- a/desktop/test/share_harness_test.dart
+++ b/desktop/test/share_harness_test.dart
@@ -14,8 +14,8 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/shortcuts/app_keymap.dart';
-import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
+import 'package:harness/terminal/terminal_text.dart' show terminalFontStore;
import 'package:xterm/xterm.dart' show TerminalStyle;
import 'support/real_fonts.dart';
@@ -43,19 +43,23 @@ class SharingApp extends AppNotifier {
void main() {
setUpAll(() async {
- // Native captures use real fonts; Chrome exercises the same cell layout
- // with the test font and does not read the host filesystem.
+ // Native captures use real fonts; Chrome uses its test font without
+ // reading the host filesystem.
if (kIsWeb) return;
+ await loadRealFonts();
if (Platform.isMacOS &&
Platform.environment['HARNESS_SHARE_SCREENSHOT'] != null) {
- final mono = ByteData.sublistView(
- await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ final sans = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
);
- await (FontLoader(
- '.AppleSystemUIFontMonospaced',
- )..addFont(Future.value(mono))).load();
- } else {
- await loadRealFonts();
+ for (final family in [
+ '.AppleSystemUIFont',
+ 'SF Pro Text',
+ 'Roboto',
+ 'Ubuntu Sans',
+ ]) {
+ await (FontLoader(family)..addFont(Future.value(sans))).load();
+ }
}
await (FontLoader(
'MaterialIcons',
@@ -66,16 +70,26 @@ void main() {
ShareAction manage, {
Size size = const Size(900, 800),
AppKeymap? keymap,
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
await tester.pumpWidget(
MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- builder: (context, child) => keymap == null
- ? child!
- : KeymapProvider(keymap: keymap, child: child!),
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: keymap == null
+ ? child!
+ : KeymapProvider(keymap: keymap, child: child!),
+ ),
home: RepaintBoundary(
key: const Key('sharing-preview'),
child: Scaffold(
@@ -127,7 +141,10 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
}
- await tester.tap(find.byKey(ValueKey('share-field-$name')));
+ final target = find.byKey(ValueKey('share-field-$name'));
+ await tester.ensureVisible(target);
+ await tester.pumpAndSettle();
+ await tester.tap(target);
await tester.pump();
}
@@ -146,6 +163,11 @@ void main() {
if (kIsWeb) return;
final output = Platform.environment['HARNESS_SHARE_SCREENSHOT'];
if (output == null) return;
+ final oldShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ for (final object in tester.allRenderObjects) {
+ object.markNeedsPaint();
+ }
await tester.pump(const Duration(milliseconds: 300));
var region = tester.getRect(
find.byKey(const ValueKey('share-form-surface')),
@@ -161,6 +183,11 @@ void main() {
await File('$output.$state.png').writeAsBytes(png!.buffer.asUint8List());
image.dispose();
});
+ debugDisableShadows = oldShadows;
+ for (final object in tester.allRenderObjects) {
+ object.markNeedsPaint();
+ }
+ await tester.pump();
}
testWidgets(
@@ -214,12 +241,9 @@ void main() {
.selected,
isTrue,
);
- final cell = terminalCellSizeOf(
- tester.element(find.byType(ShareHarnessDialog)),
- );
expect(
tester.getSize(find.byKey(const ValueKey('share-choice-1'))).height,
- closeTo(cell.height, .01),
+ greaterThanOrEqualTo(36),
);
await capture(tester, 'public-choice');
await key(tester, LogicalKeyboardKey.tab, shift: true);
@@ -248,7 +272,7 @@ void main() {
);
testWidgets(
- 'narrow form preserves email drafts across pane navigation, live font/theme changes and remaps',
+ 'narrow form preserves drafts and remaps while terminal font and theme changes leave its geometry intact',
(tester) async {
final map = MemoryKeymap()
..apply('''{"bindings":[
@@ -281,6 +305,7 @@ void main() {
0,
reason: 'unbound Enter stays unbound in an email editor',
);
+ final editorBefore = tester.getRect(find.byType(TextField));
terminalFontStore.value = TerminalStyle(
fontSize: 22,
fontFamily: originalFont.fontFamily,
@@ -293,7 +318,8 @@ void main() {
);
expect(tester.takeException(), isNull);
- await capture(tester, 'narrow-tango');
+ expect(tester.getRect(find.byType(TextField)), editorBefore);
+ await capture(tester, 'narrow-desktop');
await tester.tap(find.byKey(const ValueKey('share-back')));
await tester.pump();
expect(find.text('Copy link'), findsOneWidget);
@@ -364,6 +390,14 @@ void main() {
await field(tester, 'comments');
await tester.pumpAndSettle();
expect(find.text('Start the conversation.'), findsOneWidget);
+ expect(find.byKey(const ValueKey('comments-heading')), findsOneWidget);
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('share-choices-surface')),
+ matching: find.text('Comments'),
+ ),
+ findsOneWidget,
+ );
expect(calls, ['list', 'comments']);
await tester.enterText(find.byType(TextField), 'Please review this step.');
tester.view.physicalSize = const Size(900, 800);
@@ -376,7 +410,7 @@ void main() {
expect(calls, ['list', 'comments']);
await key(tester, LogicalKeyboardKey.escape);
expect(find.text('Copy link'), findsOneWidget);
- expect(find.text('[-]'), findsOneWidget);
+ expect(find.text('Hide'), findsOneWidget);
expect(find.text('Private'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
@@ -502,7 +536,8 @@ void main() {
await tester.tap(find.text('Share'));
await tester.pumpAndSettle();
expect(app.calls, [('machine', 'agent', 'list')]);
- expect(find.text('Share Climate dashboard'), findsOneWidget);
+ expect(find.text('Share harness'), findsOneWidget);
+ expect(find.text('Climate dashboard'), findsOneWidget);
await close(tester);
await tester.pumpAndSettle();
app.dispose();
@@ -719,6 +754,72 @@ void main() {
},
);
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.7]) {
+ testWidgets(
+ 'sharing keeps actions and email entry usable in ${brightness.name} at $scale',
+ (tester) async {
+ final changes = <String>[];
+ await show(
+ tester,
+ (action, payload) async {
+ if (action != 'list' && action != 'comments') changes.add(action);
+ return {
+ 'collaboration': true,
+ 'shares': [],
+ 'comments': [],
+ 'canComment': true,
+ };
+ },
+ brightness: brightness,
+ scale: scale,
+ size: scale == 1 ? const Size(1280, 800) : const Size(480, 360),
+ );
+ expect(find.text('Copy link').hitTestable(), findsOneWidget);
+ expect(find.text('Close').hitTestable(), findsOneWidget);
+ await capture(tester, 'desktop-${brightness.name}-$scale');
+ await field(tester, 'people');
+ await tester.enterText(
+ find.byType(TextField),
+ );
+ await tester.pumpAndSettle();
+ expect(find.byType(TextField).hitTestable(), findsOneWidget);
+ expect(find.text('Back').hitTestable(), findsOneWidget);
+ expect(changes, isEmpty);
+ await capture(tester, 'people-${brightness.name}-$scale');
+ await tester.tap(find.text('Back'));
+ await tester.pumpAndSettle();
+ expect(find.text('Copy link').hitTestable(), findsOneWidget);
+ await field(tester, 'options');
+ await field(tester, 'comments');
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const Key('comment-input')),
+ 'Please review the latest version.',
+ );
+ await tester.pumpAndSettle();
+ final post = find.byKey(const ValueKey('comment-post'));
+ await tester.ensureVisible(post);
+ await tester.pumpAndSettle();
+ expect(post.hitTestable(), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('comments-heading')),
+ findsOneWidget,
+ );
+ await capture(tester, 'comments-${brightness.name}-$scale');
+ await tester.tap(find.text('Back'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+ expect(find.byType(ShareHarnessDialog), findsNothing);
+ expect(changes, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+ }
+
testWidgets(
'a stale presence refresh cannot erase a newly saved invitation',
(tester) async {
diff --git a/desktop/test/share_toolbar_test.dart b/desktop/test/share_toolbar_test.dart
index 644ee0956..212fc6432 100644
--- a/desktop/test/share_toolbar_test.dart
+++ b/desktop/test/share_toolbar_test.dart
@@ -1,10 +1,10 @@
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/core/models.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/settings/experimental_features.dart';
@@ -54,6 +54,18 @@ class _SharingConnection extends WsConn {
void main() {
final button = find.byKey(const ValueKey('workspace-share-button'));
+ void expectSharedHarness(String name) {
+ final dialog = find.byType(ShareHarnessDialog);
+ expect(
+ find.descendant(of: dialog, matching: find.text('Share harness')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: dialog, matching: find.text(name)),
+ findsOneWidget,
+ );
+ }
+
late AppNotifier app;
late MemoryKeymap keymap;
late MemoryStore preferences;
@@ -62,7 +74,7 @@ void main() {
final input = <TerminalBinaryFrame>[];
// Initialize the icon library before the deep viewer build stack in Chrome.
- setUpAll(() => expect(LucideIcons.refreshCw.codePoint, greaterThan(0)));
+ setUpAll(() => expect(AppIcons.refreshCw.codePoint, greaterThan(0)));
setUp(() {
connection = _SharingConnection();
@@ -208,7 +220,7 @@ void main() {
);
await tester.tap(button);
await tester.pumpAndSettle();
- expect(find.text('Share Agent 0'), findsOneWidget);
+ expectSharedHarness('Agent 0');
expect(connection.shares, [('harness_share_list', 'a0')]);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
@@ -217,7 +229,7 @@ void main() {
await tester.pump();
await shareKey(tester);
await tester.pumpAndSettle();
- expect(find.text('Share Agent 1'), findsOneWidget);
+ expectSharedHarness('Agent 1');
await shareKey(tester);
await tester.pump();
expect(find.byType(ShareHarnessDialog), findsOneWidget);
@@ -282,7 +294,7 @@ void main() {
await tester.tap(button);
await tester.pumpAndSettle();
expect(connection.shares.single, ('harness_share_list', 'a0'));
- expect(find.text('Share Agent 0'), findsOneWidget);
+ expectSharedHarness('Agent 0');
await tester.pumpWidget(const SizedBox());
});
@@ -317,7 +329,7 @@ void main() {
expect(connection.shares, isEmpty);
await key(tester, LogicalKeyboardKey.f8);
await tester.pumpAndSettle();
- expect(find.text('Share Agent 0'), findsOneWidget);
+ expectSharedHarness('Agent 0');
await tester.pumpWidget(const SizedBox());
},
);
diff --git a/desktop/test/shared_agent_page_test.dart b/desktop/test/shared_agent_page_test.dart
index dad2e8ba8..ebc4335a5 100644
--- a/desktop/test/shared_agent_page_test.dart
+++ b/desktop/test/shared_agent_page_test.dart
@@ -1,7 +1,10 @@
import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
@@ -53,14 +56,35 @@ void main() {
app.dispose();
});
- Future<void> show(WidgetTester tester, {String? pinnedKey}) async {
+ Future<void> show(
+ WidgetTester tester, {
+ String? pinnedKey,
+ Brightness brightness = Brightness.dark,
+ Size size = const Size(800, 600),
+ double scale = 1,
+ }) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
await tester.pumpWidget(
MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: SharedAgentPage(
- app: app,
- dio: dio,
- location: SharedAgentLocation(id, pinnedKey, 'stag'),
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: RepaintBoundary(
+ key: const ValueKey('shared-access-preview'),
+ child: SharedAgentPage(
+ app: app,
+ dio: dio,
+ location: SharedAgentLocation(id, pinnedKey, 'stag'),
+ ),
),
),
);
@@ -73,6 +97,22 @@ void main() {
}
}
+ Future<void> capture(WidgetTester tester, String name) async {
+ final directory = Platform.environment['HARNESS_COMMENTS_CAPTURE_DIR'];
+ if (directory == null) return;
+ final boundary = tester.renderObject<RenderRepaintBoundary>(
+ find.byKey(const ValueKey('shared-access-preview')),
+ );
+ await tester.runAsync(() async {
+ final image = await boundary.toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
testWidgets('incomplete and changed owner identities never open a viewer', (
tester,
) async {
@@ -102,7 +142,7 @@ void main() {
find.textContaining('Sign in with an invited email'),
findsOneWidget,
);
- expect(find.text('[ Sign in ]'), findsOneWidget);
+ expect(find.widgetWithText(TextButton, 'Sign in'), findsOneWidget);
expect(find.byType(SharedHarnessPanel), findsNothing);
await tester.pumpWidget(const SizedBox());
status = 403;
@@ -138,4 +178,35 @@ void main() {
expect(tester.takeException(), isNull);
},
);
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets(
+ 'shared access remains readable ${brightness.name} at $scale text',
+ (tester) async {
+ status = 401;
+ await show(
+ tester,
+ pinnedKey: key,
+ brightness: brightness,
+ size: const Size(390, 360),
+ scale: scale,
+ );
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining('Sign in with an invited email'),
+ findsOneWidget,
+ );
+ final signIn = find.widgetWithText(TextButton, 'Sign in');
+ await tester.ensureVisible(signIn);
+ await tester.pumpAndSettle();
+ expect(signIn.hitTestable(), findsOneWidget);
+ expect(find.byType(SharedHarnessPanel), findsNothing);
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'private-access-${brightness.name}-$scale');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+ }
}
diff --git a/desktop/test/shared_harness_panel_test.dart b/desktop/test/shared_harness_panel_test.dart
index ba5931c23..a434fb060 100644
--- a/desktop/test/shared_harness_panel_test.dart
+++ b/desktop/test/shared_harness_panel_test.dart
@@ -216,7 +216,7 @@ void main() {
await settleNetwork(() => find.text('Live').evaluate().isNotEmpty);
expect(requests.first['payload'], containsPair('shareId', 'grant'));
expect(find.text('View only'), findsOneWidget);
- await tester.tap(find.text('[ Comments ]'));
+ await tester.tap(find.widgetWithText(TextButton, 'Comments'));
await settleNetwork(
() => find.byKey(const Key('comment-input')).evaluate().isNotEmpty,
);
@@ -224,9 +224,9 @@ void main() {
find.byKey(const Key('comment-input')),
'Keep this draft',
);
- await tester.tap(find.text('[ Watch ]'));
+ await tester.tap(find.widgetWithText(TextButton, 'Watch'));
await tester.pump();
- await tester.tap(find.text('[ Comments ]'));
+ await tester.tap(find.widgetWithText(TextButton, 'Comments'));
await tester.pump();
expect(
tester
@@ -235,7 +235,7 @@ void main() {
.text,
'Keep this draft',
);
- await tester.tap(find.text('[ Watch ]'));
+ await tester.tap(find.widgetWithText(TextButton, 'Watch'));
await tester.pump();
// Receiving the request on the server does not mean its reply has
// reached the UI yet. Wait for the response we are about to inspect.
diff --git a/desktop/test/shortcuts_browser_test.dart b/desktop/test/shortcuts_browser_test.dart
index 056463cb4..29b4b816c 100644
--- a/desktop/test/shortcuts_browser_test.dart
+++ b/desktop/test/shortcuts_browser_test.dart
@@ -1,75 +1,192 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shortcuts/app_keymap.dart';
import 'package:harness/shortcuts/keyboard_practice.dart';
import 'package:harness/shortcuts/shortcuts_browser.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/key_cap.dart';
+import 'package:harness/terminal/terminal_text.dart';
+import 'package:xterm/xterm.dart';
import 'keymap_host_test.dart' show key;
import 'support/real_fonts.dart';
void main() {
- for (final (size, scale) in [
- (const Size(1000, 700), 1.0),
- (const Size(480, 420), 1.8),
+ for (final (size, scale, brightness) in [
+ (const Size(1000, 700), 1.0, Brightness.dark),
+ (const Size(1000, 700), 1.0, Brightness.light),
+ (const Size(480, 420), 1.8, Brightness.dark),
+ (const Size(480, 420), 1.8, Brightness.light),
]) {
- testWidgets('lazy shortcuts keep keyboard paging visible at $size/$scale', (
- tester,
- ) async {
- await tester.runAsync(loadRealFonts);
- tester.view.physicalSize = size;
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- final map = AppKeymap();
- addTearDown(map.dispose);
- await tester.pumpWidget(
- MaterialApp(
- builder: (context, child) => MediaQuery(
- data: MediaQuery.of(context)
- .copyWith(textScaler: TextScaler.linear(scale)),
- child: child!,
- ),
- home: KeymapProvider(
- keymap: map,
- child: const Scaffold(body: ShortcutsBrowser(autofocus: true)),
+ testWidgets(
+ 'lazy shortcuts keep keyboard paging visible at $size/$scale/$brightness',
+ (tester) async {
+ await tester.runAsync(() async {
+ if (Platform.isMacOS) {
+ // Native key glyphs are absent from the cross-platform Arial
+ // fixture. Load the system face for these visual keycap reviews.
+ final sans = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in [grid.AppType.sansFamily, 'SF Pro Text']) {
+ await (FontLoader(family)..addFont(Future.value(sans))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'SF Mono']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ await (FontLoader('Menlo')..addFont(
+ Future.value(
+ ByteData.sublistView(
+ await File('/System/Library/Fonts/Menlo.ttc')
+ .readAsBytes(),
+ ),
+ ),
+ ))
+ .load();
+ } else {
+ await loadRealFonts();
+ }
+ await (FontLoader('MaterialIcons')
+ ..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf')))
+ .load();
+ });
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final savedBrightness = grid.AppTheme.brightness.value;
+ final savedFont = terminalFontStore.value;
+ addTearDown(() {
+ grid.AppTheme.brightness.value = savedBrightness;
+ terminalFontStore.value = savedFont;
+ });
+ grid.AppTheme.brightness.value = brightness;
+ terminalFontStore.value = const TerminalStyle(
+ fontSize: 24,
+ fontFamily: 'Courier New',
+ );
+ final map = AppKeymap();
+ final boundary = GlobalKey();
+ addTearDown(map.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(scale),
+ highContrast: brightness == Brightness.light && scale > 1,
+ disableAnimations: scale > 1,
+ ),
+ child: child!,
+ ),
+ home: KeymapProvider(
+ keymap: map,
+ child: RepaintBoundary(
+ key: boundary,
+ child: const Scaffold(body: ShortcutsBrowser(autofocus: true)),
+ ),
+ ),
),
- ),
- );
- await tester.pumpAndSettle();
- final rows = find.byWidgetPredicate(
- (widget) =>
- widget is Semantics &&
- widget.properties.label?.endsWith('Practice shortcut') == true,
- );
- expect(rows.evaluate().length, lessThan(keyboardLessons(map).length));
- final selected = find.byWidgetPredicate(
- (widget) => widget is Semantics && widget.properties.selected == true,
- );
- // Cross every group in both directions, including rows not built yet.
- for (final direction in [
- LogicalKeyboardKey.pageDown,
- LogicalKeyboardKey.pageUp,
- ]) {
- for (var page = 0; page < 20; page++) {
- await key(tester, direction);
- await tester.pumpAndSettle();
- expect(selected, findsOneWidget);
- final viewport = tester.getRect(find.byType(ListView));
- expect(viewport.contains(tester.getCenter(selected)), isTrue);
- expect(tester.takeException(), isNull);
+ );
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('shortcuts-search')))
+ .style!
+ .fontFamily,
+ grid.AppType.sansFamily,
+ );
+ for (final cap in tester.widgetList<KeyCap>(find.byType(KeyCap))) {
+ expect(cap.textStyle!.fontFamily, grid.AppType.sansFamily);
+ }
+ final title = find.text('Keyboard shortcuts').first;
+ final titleRect = tester.getRect(title);
+ terminalFontStore.value = const TerminalStyle(
+ fontSize: 10,
+ fontFamily: 'Menlo',
+ );
+ await tester.pump();
+ expect(tester.getRect(title), titleRect);
+ final captureDir =
+ Platform.environment['HARNESS_SHORTCUTS_CAPTURE_DIR'];
+ if (captureDir != null) {
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()
+ as RenderRepaintBoundary)
+ .toImage();
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ Directory(captureDir).createSync(recursive: true);
+ File(
+ '$captureDir/shortcuts-${brightness.name}-${size.width.toInt()}.png',
+ ).writeAsBytesSync(data!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ final rows = find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics &&
+ widget.properties.label?.endsWith('Practice shortcut') == true,
+ );
+ expect(rows.evaluate().length, lessThan(keyboardLessons(map).length));
+ final selected = find.byWidgetPredicate(
+ (widget) => widget is Semantics && widget.properties.selected == true,
+ );
+ // Cross every group in both directions, including rows not built yet.
+ for (final direction in [
+ LogicalKeyboardKey.pageDown,
+ LogicalKeyboardKey.pageUp,
+ ]) {
+ for (var page = 0; page < 20; page++) {
+ await key(tester, direction);
+ await tester.pumpAndSettle();
+ expect(selected, findsOneWidget);
+ final viewport = tester.getRect(find.byType(ListView));
+ expect(viewport.contains(tester.getCenter(selected)), isTrue);
+ expect(tester.takeException(), isNull);
+ }
+ }
+ await tester.enterText(
+ find.byKey(const ValueKey('shortcuts-search')),
+ 'clone',
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Clone Harness'), findsOneWidget);
+ final semantics = tester.ensureSemantics();
+ try {
+ await tester.pump();
+ final node = tester.getSemantics(rows).getSemanticsData();
+ expect(node.label, contains('Clone Harness'));
+ expect(node.hasAction(ui.SemanticsAction.tap), isTrue);
+ } finally {
+ semantics.dispose();
}
- }
- await tester.enterText(
- find.byKey(const ValueKey('shortcuts-search')),
- 'clone',
- );
- await tester.pumpAndSettle();
- expect(find.text('Clone Harness'), findsOneWidget);
- await key(tester, LogicalKeyboardKey.arrowDown);
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(find.byType(KeyboardPractice), findsOneWidget);
- await tester.pumpWidget(const SizedBox());
- });
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(KeyboardPractice), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('shortcuts-search')))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ await tester.tap(find.text('Clone Harness'));
+ await tester.pumpAndSettle();
+ expect(find.byType(KeyboardPractice), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
}
}
diff --git a/desktop/test/shortcuts_deck_test.dart b/desktop/test/shortcuts_deck_test.dart
index a83b394eb..e699de1a9 100644
--- a/desktop/test/shortcuts_deck_test.dart
+++ b/desktop/test/shortcuts_deck_test.dart
@@ -2,6 +2,8 @@
// What this guards is the reason the deck exists: the rows have to reflow into
// the width the pane actually has, instead of sitting in one 460px lane with
// the rest of the window empty.
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart';
@@ -243,7 +245,7 @@ void main() {
reason: 'The cap needs room for its full label and vertical padding.',
);
expect(
- tester.getSize(find.byIcon(Icons.keyboard_tab)).height,
+ tester.getSize(find.byIcon(AppIcons.arrowRightToLine)).height,
greaterThan(14),
reason: 'The Tab symbol should enlarge along with the letter keys.',
);
diff --git a/desktop/test/startup_test.dart b/desktop/test/startup_test.dart
index cde3d248b..bb4bda218 100644
--- a/desktop/test/startup_test.dart
+++ b/desktop/test/startup_test.dart
@@ -178,6 +178,8 @@ void main() {
'app_ui_font_size',
'app_color_palette',
'harness_start_background',
+ 'harness_custom_background',
+ 'harness_background_behind_harnesses',
'workspace_prompt_v1',
},
]);
diff --git a/desktop/test/status_line_test.dart b/desktop/test/status_line_test.dart
index fb3f10ce8..cb0e46052 100644
--- a/desktop/test/status_line_test.dart
+++ b/desktop/test/status_line_test.dart
@@ -111,6 +111,50 @@ void main() {
]);
});
+ test('recent status ink stays readable on desktop surfaces', () {
+ for (final surface in [Colors.white, const Color(0xFF181818)]) {
+ for (final style in StatusLineStyle.values) {
+ final parts = statusLineParts(
+ provider: '',
+ machine: 'M2',
+ project: 'app',
+ branch: 'main',
+ style: style,
+ );
+ for (final color in [true, false]) {
+ final original = statusLinePaintSegments(
+ parts,
+ darkTerminalTheme,
+ color: color,
+ );
+ final adapted = statusLinePaintSegments(
+ parts,
+ darkTerminalTheme,
+ color: color,
+ surfaceBackground: surface,
+ );
+ for (var i = 0; i < adapted.length; i++) {
+ final segment = adapted[i];
+ if (segment.background != null) {
+ expect(segment.toJson(), original[i].toJson());
+ continue;
+ }
+ final a = segment.foreground.computeLuminance();
+ final b = surface.computeLuminance();
+ final ratio = a > b ? (a + .05) / (b + .05) : (b + .05) / (a + .05);
+ expect(
+ ratio,
+ greaterThanOrEqualTo(4.5),
+ reason: '${style.name}, $color',
+ );
+ expect(segment.text, original[i].text);
+ expect(segment.branchSymbol, original[i].branchSymbol);
+ }
+ }
+ }
+ }
+ });
+
test(
'branch symbols follow real branches without changing searchable text',
() {
diff --git a/desktop/test/stop_keyboard_test.dart b/desktop/test/stop_keyboard_test.dart
index cb8dbbf4c..e013b4b08 100644
--- a/desktop/test/stop_keyboard_test.dart
+++ b/desktop/test/stop_keyboard_test.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
@@ -8,6 +9,7 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/desktop_prompt_surface.dart';
import 'keymap_host_test.dart' show key, MemoryKeymap;
import 'support/stop_connection.dart';
@@ -36,13 +38,17 @@ void main() {
WidgetTester tester, {
Size size = const Size(1280, 800),
double scale = 1,
+ Brightness brightness = Brightness.dark,
}) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = size;
addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
await tester.pumpWidget(
MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
+ theme: grid.buildAppTheme(brightness: brightness),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context)
.copyWith(textScaler: TextScaler.linear(scale)),
@@ -150,7 +156,7 @@ void main() {
]}''');
await mount(tester);
await open(tester, accept: LogicalKeyboardKey.f8);
- expect(find.text('F8 select'), findsOneWidget);
+ expect(find.byTooltip('Stop · F8'), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
expect(find.text('Stop Harness'), findsOneWidget);
await key(tester, LogicalKeyboardKey.f6);
@@ -161,7 +167,7 @@ void main() {
{"keys":"f4","command":"picker.cancel","when":"picker"}
]}''');
await tester.pump();
- expect(find.text('F4 close'), findsOneWidget);
+ expect(find.byTooltip('Close · F4'), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
expect(find.text('Stop Harness'), findsOneWidget);
await key(tester, LogicalKeyboardKey.f4);
@@ -191,7 +197,7 @@ void main() {
expect(find.text('Stop Terminal'), findsOneWidget);
expect(find.textContaining('End this shell'), findsOneWidget);
expect(find.text('Cancel').hitTestable(), findsOneWidget);
- expect(find.text('esc close').hitTestable(), findsOneWidget);
+ expect(find.text('Stop').hitTestable(), findsOneWidget);
final body = tester.widget<SingleChildScrollView>(
find.ancestor(
of: find.textContaining('End this shell'),
@@ -199,6 +205,25 @@ void main() {
),
);
expect(body.controller!.offset, 0);
+ // The scroll cue must be present before scrolling, with the same safe
+ // actions stationary below it. A hidden auto-scrollbar cannot be dragged.
+ final actionsBefore = tester.getRect(find.text('Cancel'));
+ final scrollbar = find.ancestor(
+ of: find.textContaining('End this shell'),
+ matching: find.byType(Scrollbar),
+ );
+ final thumb = tester.getRect(scrollbar).topRight + const Offset(-3, 8);
+ final drag = await tester.startGesture(
+ thumb,
+ kind: PointerDeviceKind.mouse,
+ );
+ await drag.moveBy(const Offset(0, 48));
+ await drag.up();
+ await tester.pumpAndSettle();
+ expect(body.controller!.offset, greaterThan(0));
+ expect(tester.getRect(find.text('Cancel')), actionsBefore);
+ expect(connection.stops, isEmpty);
+ body.controller!.jumpTo(0);
await key(tester, LogicalKeyboardKey.pageDown);
expect(body.controller!.offset, greaterThan(0));
expect(find.text('Cancel').hitTestable(), findsOneWidget);
@@ -247,6 +272,116 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'long stop errors remain readable and copyable above visible actions in ${brightness.name}',
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(
+ tester,
+ size: const Size(480, 360),
+ scale: 1.7,
+ brightness: brightness,
+ );
+ await open(tester);
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ final detail = List.generate(
+ 20,
+ (index) =>
+ 'Diagnostic ${index + 1}: reconnect to the machine and retry.',
+ ).join('\n');
+ connection.stopReplies.single.complete({
+ 'error': 'OFFLINE',
+ 'detail': detail,
+ });
+ await tester.pumpAndSettle();
+
+ final fullMessage = 'Stop failed: $detail';
+ final message = find.ancestor(
+ of: find.text(fullMessage),
+ matching: find.byType(DesktopPromptMessage),
+ );
+ final cancel = find.widgetWithText(TextButton, 'Cancel');
+ final stop = find.byKey(const Key('agent-stop-confirm'));
+ final cancelRect = tester.getRect(cancel);
+ final stopRect = tester.getRect(stop);
+ expect(message.hitTestable(), findsOneWidget);
+ expect(cancel.hitTestable(), findsOneWidget);
+ expect(stop.hitTestable(), findsOneWidget);
+ expect(cancelRect.bottom, lessThanOrEqualTo(340));
+ expect(stopRect.bottom, lessThanOrEqualTo(340));
+ expect(tester.takeException(), isNull);
+
+ // Error details must not add an invisible stop to the action cycle.
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ Focus.of(tester.element(find.text('Stop'))).hasPrimaryFocus,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ Focus.of(tester.element(find.text('Cancel'))).hasPrimaryFocus,
+ isTrue,
+ );
+
+ final scrollable = tester.state<ScrollableState>(
+ find.descendant(of: message, matching: find.byType(Scrollable)).first,
+ );
+ expect(scrollable.position.maxScrollExtent, greaterThan(0));
+ final errorScrollbar = find
+ .descendant(of: message, matching: find.byType(Scrollbar))
+ .first;
+ final thumb =
+ tester.getRect(errorScrollbar).topRight + const Offset(-3, 8);
+ final drag = await tester.startGesture(
+ thumb,
+ kind: PointerDeviceKind.mouse,
+ );
+ await drag.moveBy(const Offset(0, 20));
+ await drag.up();
+ await tester.pumpAndSettle();
+ expect(scrollable.position.pixels, greaterThan(0));
+ scrollable.position.jumpTo(0);
+ await tester.sendEventToBinding(
+ PointerScrollEvent(
+ position: tester.getCenter(message),
+ scrollDelta: const Offset(0, 200),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(scrollable.position.pixels, greaterThan(0));
+
+ String? copied;
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(SystemChannels.platform, (
+ call,
+ ) async {
+ if (call.method == 'Clipboard.setData') {
+ copied = (call.arguments as Map)['text'] as String;
+ }
+ return null;
+ });
+ addTearDown(
+ () =>
+ messenger.setMockMethodCallHandler(SystemChannels.platform, null),
+ );
+ await tester.tap(message);
+ await key(tester, LogicalKeyboardKey.keyA, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyC, cmd: true);
+ expect(copied, fullMessage);
+ expect(tester.getRect(cancel), cancelRect);
+ expect(tester.getRect(stop), stopRect);
+ expect(connection.stops, hasLength(1));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.text('Stop Harness'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
testWidgets('an open confirmation cannot stop a newly replaced session', (
tester,
) async {
diff --git a/desktop/test/stopped_harness_test.dart b/desktop/test/stopped_harness_test.dart
index 8113f6baa..f78f58d38 100644
--- a/desktop/test/stopped_harness_test.dart
+++ b/desktop/test/stopped_harness_test.dart
@@ -432,7 +432,11 @@ void main() {
'Saved work',
);
await tester.pump();
- expect(find.widgetWithText(TextButton, 'Resume & open'), findsNothing);
+ // The preview offers the same action for pointer users; Return submits
+ // directly from search without first opening a confirmation dialog.
+ expect(find.widgetWithText(TextButton, 'Resume & open'), findsOneWidget);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(connection.types, isEmpty);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(connection.types, ['agent_resume']);
diff --git a/desktop/test/store_demo_dialog_test.dart b/desktop/test/store_demo_dialog_test.dart
new file mode 100644
index 000000000..9f90f28bb
--- /dev/null
+++ b/desktop/test/store_demo_dialog_test.dart
@@ -0,0 +1,139 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/store/store_demo_dialog.dart';
+import 'package:webview_flutter/webview_flutter.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/real_fonts.dart';
+
+void main() {
+ final output = Platform.environment['SECONDARY_DIALOG_RENDER_DIR'];
+ setUpAll(() async {
+ await loadRealFonts();
+ if (output != null) await loadPreviewFonts();
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets('recording shares the modal veil ${brightness.name} $scale', (
+ tester,
+ ) async {
+ expect(
+ WebViewPlatform.instance,
+ isNull,
+ reason: 'This fixture never loads media or starts a native player.',
+ );
+ tester.view.physicalSize = const Size(880, 560);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final picture = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: picture,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showStoreDemo(
+ context,
+ entry: const DshEntry(
+ id: 'review/blender',
+ name: 'Blender',
+ engine: 'claude',
+ ),
+ example: const StoreExample(
+ prompt: 'Synthetic review only',
+ video: 'https://fixture.invalid/recording.mp4',
+ caption:
+ 'Real Blender session · shape a ribbon lamp '
+ 'and keep named design variants',
+ ),
+ ),
+ child: const Text('Watch fixture'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Watch fixture'));
+ await tester.pump();
+ final dialog = find.byType(StoreDemoDialog);
+ final route = ModalRoute.of(tester.element(dialog))!;
+ expect(route.animation!.isCompleted, isTrue);
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is ColoredBox &&
+ widget.color == grid.AppDesktop.veil(brightness),
+ ),
+ findsOneWidget,
+ );
+ expect(route.barrierColor, Colors.transparent);
+ expect(find.text('Blender · Recorded run'), findsOneWidget);
+ expect(find.text('Open recording').hitTestable(), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('store-demo-browser')).hitTestable(),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('store-demo-close')).hitTestable(),
+ findsOneWidget,
+ );
+ expect(tester.takeException(), isNull);
+ if (output != null) {
+ final previousShadows = debugDisableShadows;
+ debugDisableShadows = false;
+ try {
+ for (final render in tester.allRenderObjects) {
+ render.markNeedsPaint();
+ }
+ await tester.pump();
+ await tester.runAsync(() async {
+ final image =
+ await (picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(output).create(recursive: true);
+ await File(
+ '$output/store-recording-${brightness.name}-$scale.png',
+ ).writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ } finally {
+ debugDisableShadows = previousShadows;
+ }
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(dialog, findsNothing);
+ await tester.tap(find.text('Watch fixture'));
+ await tester.pump();
+ await tester.tapAt(const Offset(4, 4));
+ await tester.pumpAndSettle();
+ expect(dialog, findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+ }
+ }
+}
diff --git a/desktop/test/store_open_draft_test.dart b/desktop/test/store_open_draft_test.dart
index 4585a27fd..f8940148d 100644
--- a/desktop/test/store_open_draft_test.dart
+++ b/desktop/test/store_open_draft_test.dart
@@ -109,7 +109,7 @@ void main() {
app.newSwarm(name: 'Other work');
app.openStore();
final storeTab = app.activeSwarm;
- app.newSwarm(); // an empty New Swarm of the person's own, left open behind the store
+ app.newSwarm(); // an empty New Tab of the person's own, left open behind the store
final emptyTab = app.activeSwarm;
expect(emptyTab.isEmptyStarter, isTrue);
app.selectSwarm(storeTab.id);
@@ -147,7 +147,7 @@ void main() {
expect(
app.activeSwarm,
same(emptyTab),
- reason: 'in the empty New Swarm the window already had',
+ reason: 'in the empty New Tab the window already had',
);
expect(app.swarms.length, tabsBefore, reason: 'no second empty tab');
@@ -166,7 +166,7 @@ void main() {
expect(
app.swarms,
contains(emptyTab),
- reason: 'the person\'s own New Swarm stays',
+ reason: 'the person\'s own New Tab stays',
);
expect(
find.byKey(const ValueKey('store-page:autonomous/marp')),
diff --git a/desktop/test/store_page_test.dart b/desktop/test/store_page_test.dart
index 513b24db1..58eff2627 100644
--- a/desktop/test/store_page_test.dart
+++ b/desktop/test/store_page_test.dart
@@ -7,12 +7,13 @@ import 'support/agent_picker.dart';
// page, and a store whose control plane has no ratings routes at all (404).
import 'dart:async';
+import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/shared/widgets/app_rating_star.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness/api/api_client.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
@@ -1065,7 +1066,7 @@ void main() {
matching: find.byType(Row),
)
.first,
- matching: find.byIcon(LucideIcons.arrowUpRight300),
+ matching: find.byIcon(AppIcons.arrowUpRight),
),
findsNothing,
);
@@ -1171,7 +1172,7 @@ void main() {
find
.descendant(
of: _key('store-review-stars'),
- matching: find.byType(Icon),
+ matching: find.byType(AppRatingStar),
)
.last,
);
diff --git a/desktop/test/store_screen_test.dart b/desktop/test/store_screen_test.dart
index 1a8e61c75..6f5ffa8ff 100644
--- a/desktop/test/store_screen_test.dart
+++ b/desktop/test/store_screen_test.dart
@@ -689,11 +689,14 @@ void main() {
reason: 'no stars, no post',
);
// The fourth star.
- final stars = find.descendant(
+ final fourthStar = find.descendant(
of: find.byKey(const ValueKey('store-review-stars')),
- matching: find.byType(Icon),
+ matching: find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics && widget.properties.label == '4 stars',
+ ),
);
- await tester.tap(stars.at(3));
+ await tester.tap(fourthStar);
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey('store-review-title')),
diff --git a/desktop/test/support/launch_menu.dart b/desktop/test/support/launch_menu.dart
index 582f24036..d69c88fe0 100644
--- a/desktop/test/support/launch_menu.dart
+++ b/desktop/test/support/launch_menu.dart
@@ -52,6 +52,34 @@ Future<void> focusLaunchRow(WidgetTester tester, String name) async {
}.contains(target)) {
await openLaunchRow(tester, 'advanced');
}
+ final form = tester.widget<NewHarnessForm>(find.byType(NewHarnessForm));
+ if (form.desktop) {
+ bool focused() {
+ var within = false;
+ FocusManager.instance.primaryFocus?.context?.visitAncestorElements((e) {
+ if (e == tester.element(row)) within = true;
+ return !within;
+ });
+ return within;
+ }
+
+ final visited = <String?>[];
+ for (var i = 0; i < 32 && !focused(); i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ // Native frames can complete before the deferred focus restoration from
+ // opening the composer. Wait for that transition before the next key.
+ await tester.pumpAndSettle();
+ visited.add(FocusManager.instance.primaryFocus?.debugLabel);
+ }
+ expect(
+ focused(),
+ isTrue,
+ reason: '$target is reachable with Tab; visited $visited',
+ );
+ await tester.ensureVisible(row);
+ await tester.pumpAndSettle();
+ return;
+ }
for (var i = 0; i < 12; i++) {
if (tester.widget<Semantics>(row).properties.selected == true) break;
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
diff --git a/desktop/test/swarm_attention_picker_test.dart b/desktop/test/swarm_attention_picker_test.dart
index 749560589..21c600376 100644
--- a/desktop/test/swarm_attention_picker_test.dart
+++ b/desktop/test/swarm_attention_picker_test.dart
@@ -222,7 +222,7 @@ void main() {
final unavailable = find.byKey(
ValueKey(agentDestinationId('m', 'missing')),
);
- expect(tester.widget<InkWell>(unavailable).onTap, isNull);
+ expect(tester.widget<ListTile>(unavailable).onTap, isNull);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(attentionField, findsOneWidget);
diff --git a/desktop/test/swarm_history_test.dart b/desktop/test/swarm_history_test.dart
index df8c04f77..51cd00bdf 100644
--- a/desktop/test/swarm_history_test.dart
+++ b/desktop/test/swarm_history_test.dart
@@ -248,7 +248,10 @@ void main() {
// The mark a History row draws for the store, never the group grid.
Future<void> expectFlutterRow() async {
- await chord(tester, LogicalKeyboardKey.keyY);
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ await tester.enterText(jumpField, '> Show full history');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
final row = find.ancestor(
of: find.text(Swarm.storeName),
diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dart
index 185ef9016..6a75626ff 100644
--- a/desktop/test/swarm_interactions_test.dart
+++ b/desktop/test/swarm_interactions_test.dart
@@ -121,7 +121,7 @@ void main() {
await chord(tester, LogicalKeyboardKey.keyP, shift: true);
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
- '> New Swarm',
+ '> New Tab',
);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
@@ -226,7 +226,8 @@ void main() {
if (native) {
final tab = (updates.last['tabs'] as List).single as Map;
expect(tab['id'], office.id);
- expect(tab['label'], '1:office');
+ expect(tab['label'], 'office');
+ expect(tab['shortcutHint'], '⌘1');
} else {
expect(find.text('office'), findsOneWidget);
}
@@ -398,7 +399,7 @@ void main() {
expect(input.single.streamId, 'stream-a1');
expect(String.fromCharCodes(input.single.bytes), 'x');
await activate('rename', {'id': second});
- expect(find.text('Rename Swarm'), findsOneWidget);
+ expect(find.text('Rename Tab'), findsOneWidget);
final name = tester.widget<TextField>(find.byType(TextField));
expect(name.focusNode!.hasPrimaryFocus, isTrue);
tester.testTextInput.enterText('Keyboard work');
diff --git a/desktop/test/swarm_picker_activation_test.dart b/desktop/test/swarm_picker_activation_test.dart
index f78601009..aa341acb9 100644
--- a/desktop/test/swarm_picker_activation_test.dart
+++ b/desktop/test/swarm_picker_activation_test.dart
@@ -4,7 +4,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/terminal/terminal_binary.dart';
-import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'swarm_screen_test.dart' show mount, terminal;
@@ -27,8 +26,7 @@ void main() {
expect(find.byKey(const ValueKey('swarm-search-new-agent')), findsNothing);
final panelRect = tester.getRect(results);
final fieldRect = tester.getRect(field);
- final cell = terminalCellSizeOf(tester.element(field));
- expect(fieldRect.left - panelRect.left, closeTo(cell.width * 4, .01));
+ expect(fieldRect.left - panelRect.left, inInclusiveRange(40, 64));
expect(fieldRect.right, lessThanOrEqualTo(panelRect.right));
expect(fieldRect.width, greaterThan(panelRect.width / 2));
await chord(tester, LogicalKeyboardKey.keyN);
diff --git a/desktop/test/swarm_rename_dialog_test.dart b/desktop/test/swarm_rename_dialog_test.dart
index 73066b1ad..813484659 100644
--- a/desktop/test/swarm_rename_dialog_test.dart
+++ b/desktop/test/swarm_rename_dialog_test.dart
@@ -3,7 +3,6 @@ import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
-import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/widgets/swarm_dialogs.dart';
@@ -12,13 +11,21 @@ import 'support/real_fonts.dart';
void main() {
setUpAll(loadRealFonts);
- for (final scale in [1.0, 2.0]) {
+ for (final (brightness, scale) in [
+ (Brightness.dark, 1.0),
+ (Brightness.dark, 2.0),
+ (Brightness.light, 1.0),
+ (Brightness.light, 2.0),
+ ]) {
testWidgets(
- 'rename keeps keyboard ownership and rejects blank names at $scale',
+ 'rename keeps keyboard ownership and rejects blank names in ${brightness.name} at $scale',
(tester) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(640, 540);
addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
final boundaryKey = GlobalKey();
String? result;
var completions = 0;
@@ -27,7 +34,7 @@ void main() {
key: boundaryKey,
child: MaterialApp(
debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: Brightness.dark),
+ theme: grid.buildAppTheme(brightness: brightness),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context)
.copyWith(textScaler: TextScaler.linear(scale)),
@@ -68,7 +75,7 @@ void main() {
format: ui.ImageByteFormat.png,
);
await Directory(output).create(recursive: true);
- await File('$output/rename-$scale.png')
+ await File('$output/rename-${brightness.name}-$scale.png')
.writeAsBytes(bytes!.buffer.asUint8List());
image.dispose();
});
@@ -82,7 +89,7 @@ void main() {
expect(find.text('Name cannot be empty'), findsOneWidget);
expect(editor.focusNode!.hasPrimaryFocus, isTrue);
await tester.enterText(field, ' Search polish ');
- await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(result, 'Search polish');
expect(completions, 1);
@@ -91,7 +98,7 @@ void main() {
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'Unsaved name');
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(result, isNull);
expect(completions, 2);
diff --git a/desktop/test/swarm_resize_test.dart b/desktop/test/swarm_resize_test.dart
index ff209cf24..482a47166 100644
--- a/desktop/test/swarm_resize_test.dart
+++ b/desktop/test/swarm_resize_test.dart
@@ -1,8 +1,13 @@
import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/pane_resize_handle.dart';
@@ -11,6 +16,7 @@ import 'package:xterm/xterm.dart';
import 'swarm_interactions_test.dart' show chord;
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp, MemoryStore;
+import 'support/real_fonts.dart';
Future<void> mountWide(WidgetTester tester, AppNotifier app) async {
await mount(tester, app);
@@ -19,6 +25,108 @@ Future<void> mountWide(WidgetTester tester, AppNotifier app) async {
}
void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ if (Platform.isMacOS) {
+ final font = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in [grid.AppType.sansFamily, 'SF Pro Text', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(font))).load();
+ }
+ }
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets('resize help fits ${brightness.name} at $scale', (
+ tester,
+ ) async {
+ final size = scale == 1 ? const Size(1000, 640) : const Size(480, 360);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final frames = <TerminalBinaryFrame>[];
+ final left = app.adoptSessionForTest(terminal('a0', frames));
+ app.adoptSessionForTest(terminal('a1', frames));
+ final picture = GlobalKey();
+ try {
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: picture,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: SwarmScreen(notifier: app, nativeTabs: false),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ final before = tester.getSize(find.byKey(left.cellKey)).width;
+ app.beginPaneResize();
+ await tester.pump();
+ final hint = find.byKey(const ValueKey('pane-resize-hint'));
+ expect(hint, findsOneWidget);
+ expect(find.text('resize >'), findsNothing);
+ final bounds = tester.getRect(hint);
+ expect(bounds.left, greaterThanOrEqualTo(24));
+ expect(bounds.right, lessThanOrEqualTo(size.width - 24));
+ expect(bounds.top, greaterThanOrEqualTo(0));
+ expect(bounds.bottom, lessThanOrEqualTo(size.height - 24));
+ for (final label
+ in find
+ .descendant(of: hint, matching: find.byType(Text))
+ .evaluate()) {
+ final text = label.widget as Text;
+ expect(text.style!.fontFamily, grid.AppType.sansFamily);
+ final rect = tester.getRect(find.byWidget(text));
+ expect(bounds.contains(rect.topLeft), isTrue);
+ expect(bounds.contains(rect.bottomRight), isTrue);
+ }
+ expect(tester.takeException(), isNull);
+ await _captureResizeHelp(
+ tester,
+ picture,
+ '${brightness.name}-$scale',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
+ await tester.pump();
+ expect(
+ tester.getSize(find.byKey(left.cellKey)).width,
+ scale == 1 ? greaterThan(before) : greaterThanOrEqualTo(before),
+ reason: 'At minimum pane widths, resize remains clamped and owns the key.',
+ );
+ expect(frames, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(hint, findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(frames.single.bytes, [27, 91, 65]);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ grid.AppTheme.brightness.value = previous;
+ }
+ });
+ }
+ }
+
testWidgets(
'dragged proportions retain terminals, survive save/reopen and reset with the same preset',
(tester) async {
@@ -158,3 +266,37 @@ void main() {
},
);
}
+
+Future<void> _captureResizeHelp(
+ WidgetTester tester,
+ GlobalKey picture,
+ String name,
+) async {
+ final directory = Platform.environment['HARNESS_RESIZE_CAPTURE_DIR'];
+ if (directory == null) return;
+ final previousShadows = debugDisableShadows;
+ try {
+ debugDisableShadows = false;
+ for (final render in tester.allRenderObjects) {
+ render.markNeedsPaint();
+ }
+ await tester.pump();
+ await tester.runAsync(() async {
+ final image =
+ await (picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage();
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/resize-$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ } finally {
+ debugDisableShadows = previousShadows;
+ for (final render in tester.allRenderObjects) {
+ render.markNeedsPaint();
+ }
+ await tester.pump();
+ }
+}
diff --git a/desktop/test/swarm_saved_project_test.dart b/desktop/test/swarm_saved_project_test.dart
index 34a464aa2..3f9b32063 100644
--- a/desktop/test/swarm_saved_project_test.dart
+++ b/desktop/test/swarm_saved_project_test.dart
@@ -53,42 +53,56 @@ void main() {
},
);
- testWidgets('adding a project derives its name from the selected folder', (
- tester,
- ) async {
- final original = FileSelectorPlatform.instance;
- FileSelectorPlatform.instance = _Folders();
- addTearDown(() => FileSelectorPlatform.instance = original);
- final app = createApp();
- app.machineStates['m']!.localEndpoint = LocalCliEndpoint(
- computerId: 'local',
- wsUri: Uri.parse('ws://fixture.invalid'),
- protocolVersion: 1,
- terminalProtocolVersion: 3,
- );
- SavedSwarmProject? saved;
- await tester.pumpWidget(
- MaterialApp(
- home: Builder(
- builder: (context) => TextButton(
- onPressed: () async {
- saved = await showSwarmProjectDialog(context, app);
- },
- child: const Text('Open'),
+ for (final scale in [1.0, 2.0]) {
+ testWidgets(
+ 'adding a project derives its name from the selected folder at ${scale}x text',
+ (tester) async {
+ tester.view.physicalSize = const Size(640, 420);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final original = FileSelectorPlatform.instance;
+ FileSelectorPlatform.instance = _Folders();
+ addTearDown(() => FileSelectorPlatform.instance = original);
+ final app = createApp();
+ app.machineStates['m']!.localEndpoint = LocalCliEndpoint(
+ computerId: 'local',
+ wsUri: Uri.parse('ws://fixture.invalid'),
+ protocolVersion: 1,
+ terminalProtocolVersion: 3,
+ );
+ SavedSwarmProject? saved;
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Builder(
+ builder: (context) => TextButton(
+ onPressed: () async {
+ saved = await showSwarmProjectDialog(context, app);
+ },
+ child: const Text('Open'),
+ ),
+ ),
),
- ),
- ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ expect(find.byType(TextField), findsNothing);
+ await tester.ensureVisible(find.text('Choose folder'));
+ await tester.tap(find.text('Choose folder'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(FilledButton, 'Add project'));
+ await tester.pumpAndSettle();
+ expect(saved!.name, 'autonomous-harness');
+ expect(saved!.path, '/work/autonomous-harness/');
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
);
- await tester.tap(find.text('Open'));
- await tester.pumpAndSettle();
- expect(find.byType(TextField), findsNothing);
- await tester.tap(find.text('Choose folder'));
- await tester.pumpAndSettle();
- await tester.tap(find.widgetWithText(FilledButton, 'Add project'));
- await tester.pumpAndSettle();
- expect(saved!.name, 'autonomous-harness');
- expect(saved!.path, '/work/autonomous-harness/');
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- });
+ }
}
diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dart
index ac97f0ca2..b9c9179b2 100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@ -6,6 +6,7 @@ import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
+import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
@@ -87,7 +88,7 @@ TerminalSession terminal(String id, List<TerminalBinaryFrame> input) =>
void main() {
testWidgets(
- 'tabs omit close buttons and redundant hints; Command-W closes the active tab',
+ 'tabs show names, reveal hover close and Command hints, and preserve Command-W',
(tester) async {
final app = createApp();
final first = app.activeSwarm;
@@ -95,18 +96,40 @@ void main() {
app.newSwarm(name: 'Second tab');
final second = app.activeSwarm;
await mount(tester, app);
- expect(find.byKey(ValueKey('tab-close:${first.id}')), findsNothing);
- expect(find.byKey(ValueKey('tab-close:${second.id}')), findsNothing);
- final label = find.text('2:Second tab');
+ final close = find.byKey(ValueKey('tab-close:${second.id}'));
+ expect(close.hitTestable(), findsNothing);
+ final label = find.byKey(ValueKey('tab-label:${second.id}'));
final tab = find.byKey(ValueKey(second.id));
+ final nameBounds = tester.getRect(label);
+ expect(nameBounds.left, greaterThan(tester.getRect(tab).left));
+ expect(nameBounds.center.dx, closeTo(tester.getCenter(tab).dx, .01));
+ expect(find.text('2:Second tab'), findsNothing);
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: const Offset(1200, 700));
+ await mouse.moveTo(tester.getCenter(label));
+ await tester.pumpAndSettle();
+ expect(close.hitTestable(), findsOneWidget);
+ expect(tester.getRect(label), nameBounds);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ await tester.pump();
+ expect(find.text('⌘1'), findsOneWidget);
+ expect(find.text('⌘2'), findsOneWidget);
+ expect(close.hitTestable(), findsOneWidget);
+ final commandName = tester.getRect(label);
+ final commandHint = tester.getRect(find.text('⌘2'));
+ expect(commandHint.left - commandName.right, closeTo(6, .1));
expect(
- find.descendant(of: tab, matching: find.byType(Tooltip)),
- findsNothing,
- );
- expect(
- tester.getCenter(label).dx,
- closeTo(tester.getCenter(tab).dx, .01),
+ (commandName.left + commandHint.right) / 2,
+ closeTo(tester.getCenter(tab).dx, .1),
);
+ expect(commandName.size, nameBounds.size);
+ expect(app.activeSwarm, same(second));
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+ await tester.pump();
+ expect(close.hitTestable(), findsOneWidget);
+ await mouse.removePointer();
+ await tester.pump();
+ expect(close.hitTestable(), findsNothing);
Focus.of(tester.element(label)).requestFocus();
await tester.pumpAndSettle();
await chord(tester, LogicalKeyboardKey.keyW);
@@ -215,7 +238,7 @@ void main() {
isFalse,
);
} else {
- expect(find.text('1:store'), findsOneWidget);
+ expect(find.text('store'), findsOneWidget);
}
});
@@ -300,7 +323,7 @@ void main() {
expect(row['engine'], isNull);
expect(row['iconAsset'], isNull);
} else {
- expect(find.text('2:Leftovers'), findsOneWidget);
+ expect(find.text('Leftovers'), findsOneWidget);
}
final session = terminal('gone', []);
other.session = session;
@@ -311,7 +334,7 @@ void main() {
expect(row['engine'], 'codex');
expect(row['iconAsset'], 'assets/engine-icons/codex.png');
} else {
- expect(find.text('2:Leftovers again'), findsOneWidget);
+ expect(find.text('Leftovers again'), findsOneWidget);
}
tab.panes.removeWhere((pane) => pane.id == 900);
leftovers.panes.clear();
@@ -373,7 +396,7 @@ void main() {
final position = tester.state<ScrollableState>(strip).position;
position.jumpTo(position.maxScrollExtent);
await tester.pump();
- expect(find.text('42:store'), findsOneWidget);
+ expect(find.text('store'), findsOneWidget);
}
await tester.pumpWidget(const SizedBox());
app.dispose();
@@ -400,7 +423,7 @@ void main() {
final app = createApp();
final tab = app.activeSwarm;
await mount(tester, app, nativeTabs: native);
- expect(tab.name, 'New Swarm');
+ expect(tab.name, 'New Tab');
expect(
find.byKey(const ValueKey('harness-start-search')),
findsOneWidget,
@@ -427,14 +450,14 @@ void main() {
url: 'http://127.0.0.1:1/',
),
);
- app.renameSwarm(tab.id, 'New Swarm');
+ app.renameSwarm(tab.id, 'New Tab');
await tester.pump();
if (native) {
final row = (updates.last['tabs'] as List).single as Map;
expect(row['agentCount'], 1);
expect(row['engine'], 'codex');
} else {
- expect(find.text('New Swarm'), findsOneWidget);
+ expect(find.text('New Tab'), findsOneWidget);
expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsNothing);
}
tab.panes.removeWhere((pane) => pane.id == 900);
@@ -446,7 +469,7 @@ void main() {
expect(row['agentCount'], 2);
expect(row['engine'], isNull);
} else {
- expect(find.text('New Swarm'), findsOneWidget);
+ expect(find.text('New Tab'), findsOneWidget);
}
await app.closePane(app.panes.last.id);
@@ -457,7 +480,7 @@ void main() {
'codex',
);
} else {
- expect(find.text('New Swarm'), findsOneWidget);
+ expect(find.text('New Tab'), findsOneWidget);
expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsNothing);
}
expect(app.activeSwarm, same(tab));
diff --git a/desktop/test/swarm_search_preview_test.dart b/desktop/test/swarm_search_preview_test.dart
index 32eb7b14d..2bf3ba7f7 100644
--- a/desktop/test/swarm_search_preview_test.dart
+++ b/desktop/test/swarm_search_preview_test.dart
@@ -88,9 +88,9 @@ void main() {
rootBundle.load('packages/lucide_icons_flutter/assets/lucide.ttf'),
))
.load();
- await (FontLoader('packages/lucide_icons_flutter/Lucide300')..addFont(
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
rootBundle.load(
- 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w300.ttf',
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
),
))
.load();
@@ -451,7 +451,13 @@ void main() {
await page(pump: false);
expect(
previewPosition().pixels,
- closeTo(terminalCellSizeOf(tester.element(field)).height, .01),
+ closeTo(
+ inline
+ ? terminalCellSizeOf(tester.element(field)).height
+ : MediaQuery.textScalerOf(tester.element(field)).scale(13) *
+ 1.5,
+ .01,
+ ),
);
expect(search.selected!.id, selected);
expect(editor.controller.value, value);
diff --git a/desktop/test/swarm_search_render_test.dart b/desktop/test/swarm_search_render_test.dart
index b10015da8..ee652efb3 100644
--- a/desktop/test/swarm_search_render_test.dart
+++ b/desktop/test/swarm_search_render_test.dart
@@ -254,7 +254,7 @@ void main() {
)
.search!;
final previous = search.selected!.id;
- final visibleRows = find.byType(InkWell).evaluate().where((element) {
+ final visibleRows = find.byType(ListTile).evaluate().where((element) {
final key = element.widget.key;
return key is ValueKey<String> && key.value.startsWith('agent:');
}).toSet();
@@ -263,7 +263,7 @@ void main() {
var rows = 0;
debugOnRebuildDirtyWidget = (element, _) {
if (element.widget is TextField) fields++;
- if (element.widget is InkWell && visibleRows.contains(element)) rows++;
+ if (element.widget is ListTile && visibleRows.contains(element)) rows++;
};
try {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
@@ -278,10 +278,10 @@ void main() {
reason: 'Moving the highlight does not change the editor',
);
expect(rows, 2, reason: 'Only the old and new existing highlights changed');
- final selected = tester
- .element(find.byKey(ValueKey(search.selected!.id)))
- .findAncestorWidgetOfExactType<Semantics>()!;
- expect(selected.properties.selected, isTrue);
+ final selected = tester.widget<ListTile>(
+ find.byKey(ValueKey(search.selected!.id)),
+ );
+ expect(selected.selected, isTrue);
expect(find.byKey(const ValueKey('swarm-search-count')), findsNothing);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
expect(input, isEmpty);
@@ -300,14 +300,14 @@ void main() {
final field = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(field, 'Agent');
await tester.pump(const Duration(milliseconds: 200));
- final visibleRows = find.byType(InkWell).evaluate().where((element) {
+ final visibleRows = find.byType(ListTile).evaluate().where((element) {
final key = element.widget.key;
return key is ValueKey<String> && key.value.startsWith('agent:');
}).toSet();
expect(visibleRows, isNotEmpty);
var rowBuilds = 0;
debugOnRebuildDirtyWidget = (element, _) {
- if (element.widget is InkWell && visibleRows.contains(element)) {
+ if (element.widget is ListTile && visibleRows.contains(element)) {
rowBuilds++;
}
};
@@ -367,38 +367,17 @@ void main() {
.search!;
final row = find.byKey(ValueKey(search.selected!.id));
expect(find.byType(Checkbox), findsNothing);
- expect(
- tester
- .element(row)
- .findAncestorWidgetOfExactType<Semantics>()!
- .properties
- .selected,
- isTrue,
- );
+ expect(tester.widget<ListTile>(row).selected, isTrue);
final height = tester.getSize(row).height;
grid.AppTheme.palette.value = HarnessPalette.ember;
await tester.pump();
- expect(
- tester
- .element(row)
- .findAncestorWidgetOfExactType<Semantics>()!
- .properties
- .selected,
- isTrue,
- );
+ expect(tester.widget<ListTile>(row).selected, isTrue);
tester.platformDispatcher.textScaleFactorTestValue = 2;
await tester.pump();
expect(tester.getSize(row).height, greaterThan(height));
expect(tester.widget<TextField>(field).controller!.text, 'Agent');
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
- expect(
- tester
- .element(row)
- .findAncestorWidgetOfExactType<Semantics>()!
- .properties
- .selected,
- isTrue,
- );
+ expect(tester.widget<ListTile>(row).selected, isTrue);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
app.dispose();
@@ -423,14 +402,7 @@ void main() {
app.dismissError(); // Publish the sessions assembled through the test seam.
await tester.pump();
final row = find.byKey(ValueKey(agentDestinationId('m', 'a0')));
- expect(
- tester
- .element(row)
- .findAncestorWidgetOfExactType<Semantics>()!
- .properties
- .enabled,
- isTrue,
- );
+ expect(tester.widget<ListTile>(row).enabled, isTrue);
expect(
find.descendant(of: row, matching: find.text('Already added')),
findsNothing,
diff --git a/desktop/test/swarm_split_test.dart b/desktop/test/swarm_split_test.dart
index 630b5cd60..7163cd3b6 100644
--- a/desktop/test/swarm_split_test.dart
+++ b/desktop/test/swarm_split_test.dart
@@ -12,6 +12,7 @@ import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/state/pane_preset.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
import 'package:harness/ws/ws_conn.dart';
import 'package:xterm/xterm.dart';
@@ -653,7 +654,13 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(find.text('New Pane to the Right'), findsOneWidget);
- expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
+ expect(
+ tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search
+ .canAccept,
+ isTrue,
+ );
expect(find.byType(AlertDialog), findsNothing);
await chord(tester, LogicalKeyboardKey.keyN);
await tester.pump();
diff --git a/desktop/test/swarm_state_test.dart b/desktop/test/swarm_state_test.dart
index b21fe4b48..473a04773 100644
--- a/desktop/test/swarm_state_test.dart
+++ b/desktop/test/swarm_state_test.dart
@@ -131,6 +131,7 @@ void main() {
for (final legacy in [
'New swarm',
+ 'New Tab',
'New tab',
'New Tab',
'New Harness',
@@ -157,7 +158,7 @@ void main() {
final restored = createApp(store: store);
addTearDown(restored.dispose);
await restored.restorePaneLayoutForTest();
- expect(restored.activeSwarm.name, 'New Swarm');
+ expect(restored.activeSwarm.name, 'New Tab');
await restored.addAgentToSwarm('m', 'a0');
expect(restored.activeSwarm.name, 'Agent 0');
},
diff --git a/desktop/test/swarm_switcher_test.dart b/desktop/test/swarm_switcher_test.dart
index 5f4214a4f..560b0d578 100644
--- a/desktop/test/swarm_switcher_test.dart
+++ b/desktop/test/swarm_switcher_test.dart
@@ -37,7 +37,10 @@ void main() {
final pane = app.adoptSessionForTest(terminal('a0', frames));
final original = app.activeSwarm;
await mount(tester, app, nativeTabs: nativeTabs);
- expect(find.byKey(const ValueKey('swarm-search-button')), findsNothing);
+ expect(
+ find.byKey(const ValueKey('swarm-search-button')),
+ nativeTabs ? findsNothing : findsOneWidget,
+ );
expect(
harnessCommandById.containsKey('navigation.quick_open'),
isFalse,
diff --git a/desktop/test/system_notifications_test.dart b/desktop/test/system_notifications_test.dart
index 110406b77..da12f5ca7 100644
--- a/desktop/test/system_notifications_test.dart
+++ b/desktop/test/system_notifications_test.dart
@@ -3,6 +3,7 @@
// and how each platform's notifier is driven.
import 'dart:async';
import 'dart:io' show ProcessException, ProcessResult;
+import 'dart:ui' show SemanticsAction, Tristate;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -484,6 +485,44 @@ void main() {
),
);
+ testWidgets('each alert switch announces its own purpose and state', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ final os = _Recorder();
+ final system = SystemNotifications(
+ store: store(on: false),
+ notifier: os,
+ );
+ await pump(tester, system);
+ for (final (key, label) in [
+ ('settings-screen-alerts', 'On-screen alerts'),
+ ('settings-alert-sounds', 'Alert sounds'),
+ ('settings-desktop-notifications', 'Desktop notifications'),
+ ]) {
+ final toggle = find.byKey(Key(key));
+ final node = tester.getSemantics(toggle);
+ final before = node.getSemanticsData();
+ expect(before.label, label);
+ expect(before.flagsCollection.isToggled, Tristate.isFalse);
+ expect(before.hasAction(SemanticsAction.tap), isTrue);
+ tester
+ .renderObject(toggle)
+ .owner!
+ .semanticsOwner!
+ .performAction(node.id, SemanticsAction.tap);
+ await tester.pumpAndSettle();
+ final after = tester.getSemantics(toggle).getSemanticsData();
+ expect(after.label, label);
+ expect(after.flagsCollection.isToggled, Tristate.isTrue);
+ }
+ expect(os.authorizations, 1);
+ } finally {
+ semantics.dispose();
+ }
+ });
+
testWidgets('a switch that asks for permission when turned on', (
tester,
) async {
diff --git a/desktop/test/take_over_dialog_test.dart b/desktop/test/take_over_dialog_test.dart
index a274bc8c4..1449da430 100644
--- a/desktop/test/take_over_dialog_test.dart
+++ b/desktop/test/take_over_dialog_test.dart
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/widgets/take_over_dialog.dart';
void main() {
@@ -8,11 +9,26 @@ void main() {
required String engine,
required bool busy,
String? pick,
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ Size size = const Size(800, 600),
}) async {
TakeOver? chosen;
var answered = false;
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
await tester.pumpWidget(
MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
home: Builder(
builder: (context) => TextButton(
onPressed: () async {
@@ -83,4 +99,35 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('Move to Harness'), findsNothing);
});
+
+ for (final brightness in Brightness.values) {
+ testWidgets(
+ 'takeover keeps its safe default and visible choices in a short ${brightness.name} window',
+ (tester) async {
+ await ask(
+ tester,
+ engine: 'codex',
+ busy: true,
+ brightness: brightness,
+ scale: 1.7,
+ size: const Size(440, 360),
+ );
+ final wait = find.byKey(const Key('take-over-wait'));
+ expect(
+ tester.widget<FilledButton>(wait).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ expect(wait.hitTestable(), findsOneWidget);
+ expect(
+ find.byKey(const Key('take-over-now')).hitTestable(),
+ findsOneWidget,
+ );
+ expect(find.text('Cancel').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(find.text('Move to Harness'), findsNothing);
+ },
+ );
+ }
}
diff --git a/desktop/test/terminal_control_banner_test.dart b/desktop/test/terminal_control_banner_test.dart
index e66c8dc23..6001d7dab 100644
--- a/desktop/test/terminal_control_banner_test.dart
+++ b/desktop/test/terminal_control_banner_test.dart
@@ -1,3 +1,4 @@
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -228,7 +229,10 @@ void main() {
expect(banner, findsOneWidget);
expect(hint, findsOneWidget);
expect(
- find.descendant(of: banner, matching: find.byIcon(Icons.keyboard_return)),
+ find.descendant(
+ of: banner,
+ matching: find.byIcon(AppIcons.cornerDownLeft),
+ ),
findsOneWidget,
reason: 'the key is drawn on the button itself',
);
@@ -242,7 +246,7 @@ void main() {
tester,
notice: terminalNotice(
label: 'Offline',
- icon: Icons.cloud_off,
+ icon: AppIcons.cloudOff,
detail: 'Test host is offline.',
),
);
@@ -260,7 +264,7 @@ void main() {
tester,
notice: terminalNotice(
label: 'Not confirmed',
- icon: Icons.help_outline,
+ icon: AppIcons.circleHelp,
detail:
'The engine is still running here; the daemon has not confirmed '
'which conversation it reopened.',
@@ -276,7 +280,10 @@ void main() {
expect(button, findsOneWidget);
// ⏎ belongs to taking the stream back; this action has no chord behind it.
expect(
- find.descendant(of: button, matching: find.byIcon(Icons.keyboard_return)),
+ find.descendant(
+ of: button,
+ matching: find.byIcon(AppIcons.cornerDownLeft),
+ ),
findsNothing,
);
await tester.tap(button);
@@ -294,7 +301,7 @@ void main() {
tester,
notice: terminalNotice(
label: 'Link required',
- icon: Icons.link_off,
+ icon: AppIcons.unlink,
detail: 'Test host needs linking.',
actionLabel: 'Link',
onAction: () {},
@@ -313,7 +320,7 @@ void main() {
tester,
notice: terminalNotice(
label: 'Offline',
- icon: Icons.cloud_off,
+ icon: AppIcons.cloudOff,
detail: 'Test host is offline.',
),
);
@@ -330,7 +337,7 @@ void main() {
tester,
notice: terminalNotice(
label: 'Not confirmed',
- icon: Icons.help_outline,
+ icon: AppIcons.circleHelp,
detail: 'Still checking.',
banner: true,
actionLabel: 'Check again',
@@ -732,7 +739,7 @@ void main() {
tester,
notice: terminalNotice(
label: 'Offline',
- icon: Icons.cloud_off,
+ icon: AppIcons.cloudOff,
detail: 'Test host is offline.',
),
);
diff --git a/desktop/test/terminal_find_test.dart b/desktop/test/terminal_find_test.dart
index 8f3ad9aa4..7b0abc1a5 100644
--- a/desktop/test/terminal_find_test.dart
+++ b/desktop/test/terminal_find_test.dart
@@ -107,7 +107,9 @@ void main() {
app.adoptSessionForTest(session);
addTearDown(app.dispose);
await mount(tester, app);
- tester.view.physicalSize = const Size(600, 800);
+ // Terminal chrome ignores platform text scaling; a truly narrow pane
+ // offers compact actions, whose desktop popup still uses the larger type.
+ tester.view.physicalSize = const Size(340, 800);
tester.platformDispatcher.textScaleFactorTestValue = 1.7;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
await tester.pump();
diff --git a/desktop/test/terminal_panel_header_test.dart b/desktop/test/terminal_panel_header_test.dart
index d2ee8ba57..338fab05f 100644
--- a/desktop/test/terminal_panel_header_test.dart
+++ b/desktop/test/terminal_panel_header_test.dart
@@ -1,6 +1,8 @@
// The pane header's transport badge: which of the three paths carries this
// pane's bytes, drawn by shape as well as colour, and absent where there is no
// such choice to report.
+
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/auth_session.dart';
@@ -10,7 +12,6 @@ import 'package:harness/state/app_state.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/theme/app_theme.dart';
import 'package:harness/widgets/terminal_panel.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'support/real_fonts.dart';
@@ -154,17 +155,17 @@ void main() {
(tester) async {
final marks = {
'p2p': (
- icon: LucideIcons.link2,
+ icon: AppIcons.link2,
color: AppColors.success,
label: 'P2P · Direct peer connection',
),
'turn': (
- icon: LucideIcons.waypoints,
+ icon: AppIcons.waypoints,
color: AppColors.warning,
label: 'TURN · Via Cloudflare relay',
),
'relay': (
- icon: LucideIcons.server,
+ icon: AppIcons.server,
color: AppColors.mutedStrong,
label: 'WS · Via Harness WebSocket relay',
),
@@ -206,11 +207,7 @@ void main() {
expect(session.linkMode, isNull);
await pump(tester, session);
- for (final icon in [
- LucideIcons.link2,
- LucideIcons.waypoints,
- LucideIcons.server,
- ]) {
+ for (final icon in [AppIcons.link2, AppIcons.waypoints, AppIcons.server]) {
expect(find.byIcon(icon), findsNothing);
}
});
@@ -223,19 +220,19 @@ void main() {
session.linkMode = 'p2p';
await pump(tester, session);
- expect(find.byIcon(LucideIcons.link2), findsOneWidget);
- final position = tester.getCenter(find.byIcon(LucideIcons.link2));
+ expect(find.byIcon(AppIcons.link2), findsOneWidget);
+ final position = tester.getCenter(find.byIcon(AppIcons.link2));
session.linkMode = 'turn';
await pump(tester, session);
- expect(find.byIcon(LucideIcons.link2), findsNothing);
- expect(find.byIcon(LucideIcons.waypoints), findsOneWidget);
- expect(tester.getCenter(find.byIcon(LucideIcons.waypoints)), position);
+ expect(find.byIcon(AppIcons.link2), findsNothing);
+ expect(find.byIcon(AppIcons.waypoints), findsOneWidget);
+ expect(tester.getCenter(find.byIcon(AppIcons.waypoints)), position);
session.linkMode = 'relay';
await pump(tester, session);
- expect(find.byIcon(LucideIcons.waypoints), findsNothing);
- expect(find.byIcon(LucideIcons.server), findsOneWidget);
- expect(tester.getCenter(find.byIcon(LucideIcons.server)), position);
+ expect(find.byIcon(AppIcons.waypoints), findsNothing);
+ expect(find.byIcon(AppIcons.server), findsOneWidget);
+ expect(tester.getCenter(find.byIcon(AppIcons.server)), position);
});
// ── the harness verdict chip ─────────────────────────────────────────────
diff --git a/desktop/test/terminal_panel_presentation_test.dart b/desktop/test/terminal_panel_presentation_test.dart
index 1f5625acc..12bbfe427 100644
--- a/desktop/test/terminal_panel_presentation_test.dart
+++ b/desktop/test/terminal_panel_presentation_test.dart
@@ -1,5 +1,6 @@
import 'dart:ui' show PointerDeviceKind;
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
@@ -267,10 +268,10 @@ void main() {
);
expect(
find.byType(GridModelPicker),
- findsNothing,
- reason: 'The focused model is in the workspace status bar.',
+ findsOneWidget,
+ reason: 'The model belongs to its pane header.',
);
- expect(find.byTooltip('Close Pane').hitTestable(), findsNothing);
+ expect(find.byTooltip('Close Pane').hitTestable(), findsOneWidget);
for (final label in ['Zoom Pane', 'Stop Harness']) {
expect(find.byTooltip(label).hitTestable(), findsNothing);
}
@@ -356,7 +357,7 @@ void main() {
expect(tester.getSize(title).width, greaterThan(64));
expect(tester.takeException(), isNull);
final titleBefore = tester.getRect(title);
- expect(find.byType(GridModelPicker), findsNothing);
+ expect(find.byType(GridModelPicker), findsOneWidget);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: const Offset(1, 100));
await mouse.moveTo(tester.getCenter(title));
@@ -381,7 +382,7 @@ void main() {
expect(
tester
.widget<IconButton>(
- find.widgetWithIcon(IconButton, Icons.refresh),
+ find.widgetWithIcon(IconButton, AppIcons.refreshCw),
)
.onPressed,
isNotNull,
diff --git a/desktop/test/terminal_settings_section_test.dart b/desktop/test/terminal_settings_section_test.dart
index 2947ec139..9dadf2114 100644
--- a/desktop/test/terminal_settings_section_test.dart
+++ b/desktop/test/terminal_settings_section_test.dart
@@ -42,6 +42,28 @@ Widget _host({double textScale = 1.0}) => MaterialApp(
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
+ testWidgets('terminal selectors announce purpose independently of value', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ await tester.pumpWidget(_host());
+ await tester.pumpAndSettle();
+ final colors = tester
+ .getSemantics(find.bySemanticsLabel('Terminal colors'))
+ .getSemanticsData();
+ final font = tester
+ .getSemantics(find.bySemanticsLabel('Terminal font'))
+ .getSemanticsData();
+ expect(colors.label, 'Terminal colors');
+ expect(colors.value, terminalThemeStore.value.label);
+ expect(font.label, 'Terminal font');
+ expect(font.value, terminalFontStore.family.label);
+ } finally {
+ semantics.dispose();
+ }
+ });
+
testWidgets('the pane lays out with no overflow at the window minimum', (
tester,
) async {
diff --git a/desktop/test/terminal_ui_typography_test.dart b/desktop/test/terminal_ui_typography_test.dart
index e904f9c0f..470e2c1ba 100644
--- a/desktop/test/terminal_ui_typography_test.dart
+++ b/desktop/test/terminal_ui_typography_test.dart
@@ -1,3 +1,5 @@
+import 'package:harness/widgets/workspace_store_button.dart';
+
import 'dart:async';
import 'package:flutter/material.dart';
@@ -12,6 +14,8 @@ import 'package:harness/state/new_harness.dart';
import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/widgets/delete_agent_dialog.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/desktop_workspace_tab.dart';
import 'package:harness/widgets/harness_activity_mark.dart';
import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/pane_header_actions.dart';
@@ -61,8 +65,9 @@ void main() {
grid.AppType.titleSize,
grid.AppType.headingSize,
grid.AppType.bodySize,
- grid.AppType.monoLabelSize,
grid.AppType.captionSize,
+ DesktopChrome.heading().fontSize!,
+ DesktopChrome.text().fontSize!,
};
/// General UI and workspace bars keep their fixed scales during terminal zoom.
@@ -74,6 +79,7 @@ void main() {
InlineSpan span,
TextStyle inherited, {
bool workspaceBar = false,
+ bool desktopTab = false,
}) {
final style = inherited.merge(span.style);
if (span is TextSpan) {
@@ -85,7 +91,10 @@ void main() {
'LucideIcons',
].any((icon) => style.fontFamily?.contains(icon) == true)) {
checked++;
- if (workspaceBar) {
+ if (desktopTab) {
+ expect(style.fontSize, 13, reason: text);
+ expect(style.fontFamily, grid.AppType.sansFamily, reason: text);
+ } else if (workspaceBar) {
expect(style.fontSize, 13, reason: text);
expect(
style.fontFamily,
@@ -103,13 +112,18 @@ void main() {
}
}
for (final child in span.children ?? <InlineSpan>[]) {
- check(child, style, workspaceBar: workspaceBar);
+ check(
+ child,
+ style,
+ workspaceBar: workspaceBar,
+ desktopTab: desktopTab,
+ );
}
}
}
- // The welcome page stands where a terminal will and is set like one, so
- // it follows the terminal's size instead; see [checkWelcome].
+ // The welcome composer and search use the shared desktop type scale;
+ // their controls are checked separately below.
final welcome = find.byType(WorkspaceWelcome);
final setup = find.byWidgetPredicate(
(widget) =>
@@ -130,11 +144,19 @@ void main() {
check(
(element.widget as RichText).text,
const TextStyle(),
+ desktopTab:
+ (element.findAncestorWidgetOfExactType<DesktopWorkspaceTab>() !=
+ null &&
+ element.findAncestorWidgetOfExactType<ActivityMark>() ==
+ null) ||
+ element.findAncestorWidgetOfExactType<WorkspaceStoreButton>() !=
+ null,
workspaceBar: find
.descendant(
of: find.byWidgetPredicate(
(widget) =>
widget.key == const ValueKey('workspace-status-bar') ||
+ widget.key == const ValueKey('workspace-tab-bar') ||
widget.key == const ValueKey('terminal-pane-title') ||
widget.key == const ValueKey('viewer-pane-title') ||
widget is ActivityMark ||
@@ -146,9 +168,20 @@ void main() {
.isNotEmpty,
);
}
- for (final widget in tester.widgetList<EditableText>(
- find.byType(EditableText),
- )) {
+ for (final element in find.byType(EditableText).evaluate()) {
+ final widget = element.widget as EditableText;
+ if (element.findAncestorWidgetOfExactType<TextField>()?.key ==
+ const ValueKey('new-harness-task')) {
+ expect(widget.style.fontSize, 15);
+ expect(widget.style.fontFamily, grid.AppType.sansFamily);
+ continue;
+ }
+ if (element.findAncestorWidgetOfExactType<TextField>()?.key ==
+ const ValueKey('swarm-search-input')) {
+ expect(widget.style.fontSize, 17);
+ expect(widget.style.fontFamily, grid.AppType.sansFamily);
+ continue;
+ }
// A field is on the scale, or it types into the terminal and follows it.
expect({
...ramp,
@@ -160,14 +193,21 @@ void main() {
return sizes;
}
- /// The welcome page is terminal text: the terminal's face at its size.
+ /// The welcome page uses the same system-font composer at every terminal zoom.
void checkWelcome(WidgetTester tester) {
- final tagline = find.byKey(const ValueKey('welcome-tagline'));
- final line = tester.widget<Text>(tagline);
- final style = DefaultTextStyle.of(tester.element(tagline)).style
- .merge(line.style);
- expect(style.fontSize, terminalFontStore.size);
- expect(style.fontFamily, terminalFontStore.value.fontFamily);
+ expect(
+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).embedded,
+ isTrue,
+ );
+ final task = tester.widget<TextField>(
+ find.byKey(const ValueKey('new-harness-task')),
+ );
+ expect(task.style!.fontSize, 15);
+ expect(task.style!.fontFamily, grid.AppType.sansFamily);
+ expect(
+ tester.getSize(find.byKey(const ValueKey('new-harness-composer'))).width,
+ 680,
+ );
}
/// Zooming the terminal leaves every UI text where it was.
@@ -218,22 +258,22 @@ void main() {
selectFont(size);
final theme = grid.buildAppTheme(brightness: Brightness.dark);
final t = theme.textTheme;
- final mono = grid.AppType.monoFamily;
final sans = grid.AppType.sansFamily;
- // Headings, labels and what the user types are mono; prose is sans.
+ // App headings, controls and fields use the system face. Terminal and
+ // explicit code styles remain independent and are checked below.
final expected = {
- t.displayLarge: (grid.AppType.displaySize, mono),
- t.headlineSmall: (grid.AppType.titleSize, mono),
- t.titleLarge: (grid.AppType.titleSize, mono),
- t.titleMedium: (grid.AppType.headingSize, mono),
- t.titleSmall: (grid.AppType.bodySize, mono),
- t.labelLarge: (grid.AppType.bodySize, mono),
- t.labelSmall: (grid.AppType.monoMetaSize, mono),
+ t.displayLarge: (grid.AppType.displaySize, sans),
+ t.headlineSmall: (grid.AppType.titleSize, sans),
+ t.titleLarge: (grid.AppType.titleSize, sans),
+ t.titleMedium: (grid.AppType.headingSize, sans),
+ t.titleSmall: (grid.AppType.bodySize, sans),
+ t.labelLarge: (grid.AppType.bodySize, sans),
+ t.labelSmall: (grid.AppType.captionSize, sans),
t.bodyLarge: (grid.AppType.bodySize, sans),
t.bodyMedium: (grid.AppType.bodySize, sans),
t.bodySmall: (grid.AppType.bodySize, sans),
- grid.kFieldTextStyle: (grid.AppType.monoSize, mono),
- theme.dialogTheme.titleTextStyle: (grid.AppType.headingSize, mono),
+ grid.kFieldTextStyle: (grid.AppType.bodySize, sans),
+ theme.dialogTheme.titleTextStyle: (grid.AppType.headingSize, sans),
theme.dialogTheme.contentTextStyle: (grid.AppType.bodySize, sans),
theme.tooltipTheme.textStyle: (grid.AppType.captionSize, sans),
};
@@ -249,8 +289,6 @@ void main() {
test('mono takes the terminal face but not its size', () {
selectFont(22);
for (final (style, size) in [
- (grid.AppType.heading(), grid.AppType.headingSize),
- (grid.AppType.label(), grid.AppType.bodySize),
(grid.AppType.mono(), grid.AppType.monoSize),
(grid.AppType.monoLabel(), grid.AppType.monoLabelSize),
(grid.AppType.monoMeta(), grid.AppType.monoMetaSize),
@@ -263,7 +301,7 @@ void main() {
});
testWidgets(
- 'tabs, welcome, and setup screens follow terminal zoom while general UI keeps its scale',
+ 'welcome, native setup, and workspace chrome keep their scale during terminal zoom',
(tester) async {
final app = createApp();
app.machineStates['m']!.localOnly = true;
@@ -282,6 +320,7 @@ void main() {
expectSameSizes(before, checkText(tester));
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pumpAndSettle();
expect(find.byType(WorkspaceWelcome), findsOneWidget);
// Only the tab chrome is UI text here; the page itself is checked below.
checkText(tester, atLeast: 1);
@@ -298,42 +337,49 @@ void main() {
of: find.byKey(const ValueKey('new-harness-field-start')),
matching: find.text('New Harness'),
);
- expect(tester.widget<Text>(start).style!.fontSize, 18);
+ TextStyle startStyle() =>
+ DefaultTextStyle.of(tester.element(start)).style
+ .merge(tester.widget<Text>(start).style);
+ expect(startStyle().fontSize, 13);
+ expect(startStyle().fontFamily, grid.AppType.sansFamily);
selectFont(22);
await tester.pumpAndSettle();
expectSameSizes(box, checkText(tester, atLeast: 1));
- expect(tester.widget<Text>(start).style!.fontSize, 22);
+ expect(startStyle().fontSize, 13);
+ expect(startStyle().fontFamily, grid.AppType.sansFamily);
await key(tester, LogicalKeyboardKey.escape);
- for (final shortcut in [
- LogicalKeyboardKey.keyP,
- LogicalKeyboardKey.keyP,
- ]) {
- await key(tester, shortcut, cmd: true);
+ for (final terminalSize in [9.0, 18.0]) {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
final input = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(input, 'Agent');
await key(tester, LogicalKeyboardKey.arrowDown);
await tester.pumpAndSettle();
expect(find.byType(SwarmSearchPreview), findsOneWidget);
final search = checkText(tester, atLeast: 1);
- selectFont(
- shortcut == LogicalKeyboardKey.keyP ? 9 : 18,
- TerminalFontChoice.monaco,
- );
+ final resultSizes = {
+ for (final text in tester.widgetList<SearchResultText>(
+ find.byType(SearchResultText),
+ ))
+ text.text: text.style.fontSize,
+ };
+ selectFont(terminalSize, TerminalFontChoice.monaco);
await tester.pumpAndSettle();
expect(tester.widget<TextField>(input).controller!.text, 'Agent');
expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
expectSameSizes(search, checkText(tester, atLeast: 1));
+ expect(tester.widget<TextField>(input).style!.fontSize, 17);
expect(
- tester.widget<TextField>(input).style!.fontSize,
- terminalFontStore.size,
+ tester.widget<TextField>(input).style!.fontFamily,
+ grid.AppType.sansFamily,
);
for (final text in tester.widgetList<SearchResultText>(
find.byType(SearchResultText),
)) {
- expect(text.style.fontFamily, terminalFontStore.value.fontFamily);
- expect(text.style.fontSize, terminalFontStore.size);
- expect(text.style.height, terminalFontStore.value.height);
- expect(text.style.letterSpacing, 0);
+ expect(text.style.fontSize, resultSizes[text.text]);
+ expect([
+ grid.AppType.sansFamily,
+ grid.AppType.monoFamily,
+ ], contains(text.style.fontFamily));
}
await key(tester, LogicalKeyboardKey.escape);
}
@@ -387,7 +433,7 @@ void main() {
});
testWidgets(
- 'native tabs keep 13 pt platform monospace during terminal font changes',
+ 'native footer payload keeps its 13 pt status face during terminal font changes',
(tester) async {
final updates = <Map<dynamic, dynamic>>[];
const channel = MethodChannel('harness/swarm_tabs');
diff --git a/desktop/test/toolbar_onboarding_test.dart b/desktop/test/toolbar_onboarding_test.dart
index c935c2a10..e9db79013 100644
--- a/desktop/test/toolbar_onboarding_test.dart
+++ b/desktop/test/toolbar_onboarding_test.dart
@@ -118,7 +118,7 @@ void main() {
for (var completed = 0; completed <= 3; completed++) {
testWidgets(
- 'welcome has the same working actions with $completed saved steps',
+ 'welcome keeps the same composer and shortcuts with $completed saved steps',
(tester) async {
final storage = MemoryStore();
final previous = WorkspaceOnboarding(storage: storage);
@@ -142,43 +142,23 @@ void main() {
OnboardingStep.values.where(journey.completed),
OnboardingStep.values.take(completed),
);
- expect(find.text('Harness like a boss.'), findsOneWidget);
- expect(find.text('○'), findsNothing);
- expect(find.text('✓'), findsNothing);
- expect(find.byType(NewHarnessForm), findsNothing);
+ expect(find.byType(OnboardingCard), findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ expect(
+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).embedded,
+ isTrue,
+ );
expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
- for (final hint in ['⌘N', '⌘P', '⌘I', '⌘M', '⌘S']) {
- expect(find.text(hint), findsOneWidget);
- }
-
- final destinations = [
- 'agent.new',
- 'harnesses.list',
- 'models.list',
- 'machines.list',
- 'app.store',
- ];
- for (final command in destinations) {
- await tap(tester, find.byKey(ValueKey('welcome-$command')));
- switch (command) {
- case 'agent.new':
- expect(find.byType(NewHarnessForm), findsOneWidget);
- case 'harnesses.list':
- expect(resourceScope(''), findsOneWidget);
- case 'models.list':
- expect(resourceScope(':'), findsOneWidget);
- case 'machines.list':
- expect(resourceScope('@'), findsOneWidget);
- case 'app.store':
- expect(app.activeSwarm.isStore, isTrue);
- }
- if (command == 'app.store') {
- await key(tester, LogicalKeyboardKey.keyT, cmd: true);
- } else {
- await key(tester, LogicalKeyboardKey.escape);
- }
- await tester.pumpAndSettle();
- }
+ await tap(
+ tester,
+ find.byKey(const ValueKey('new-harness-field-project')),
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-chooser-surface')),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
for (final shortcut in [
LogicalKeyboardKey.keyN,
LogicalKeyboardKey.keyP,
@@ -225,7 +205,7 @@ void main() {
for (final native in [false, true]) {
testWidgets(
- 'welcome clicks and keyboard open real panels (native=$native)',
+ 'welcome controls and shortcuts open real panels (native=$native)',
(tester) async {
await mount(tester, native: native);
final models = resourceScope(':');
@@ -248,7 +228,7 @@ void main() {
await tester.pumpAndSettle();
}
- await tap(tester, find.byKey(const ValueKey('welcome-harnesses.list')));
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
expect(resourceScope(''), findsOneWidget);
await key(tester, LogicalKeyboardKey.keyM, cmd: true);
await tester.pumpAndSettle();
@@ -264,12 +244,21 @@ void main() {
expect(find.byType(NewHarnessForm), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- await tap(tester, find.byKey(const ValueKey('welcome-app.store')));
+ await key(tester, LogicalKeyboardKey.keyS, cmd: true);
expect(app.activeSwarm.isStore, isTrue);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
await tester.pumpAndSettle();
- await tap(tester, find.byKey(const ValueKey('welcome-agent.new')));
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
expect(find.byType(NewHarnessForm), findsOneWidget);
+ await tap(
+ tester,
+ find.byKey(const ValueKey('new-harness-field-project')),
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-chooser-surface')),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
expect(OnboardingStep.values.any(journey.completed), isFalse);
expect(app.actions, isEmpty);
expect(tester.takeException(), isNull);
@@ -327,17 +316,17 @@ void main() {
modelsAvailable: true,
);
await tester.pumpAndSettle();
- expect(find.text('✓'), findsNothing);
- expect(find.text('Harness like a boss.'), findsOneWidget);
+ expect(find.byType(OnboardingCard), findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
await tester.pumpAndSettle();
- expect(find.text('Harness like a boss.'), findsOneWidget);
- expect(find.text('✓'), findsNothing);
- await tap(tester, find.byKey(const ValueKey('welcome-harnesses.list')));
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ expect(find.byType(OnboardingCard), findsNothing);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
expect(resourceScope(''), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- await tap(tester, find.byKey(const ValueKey('welcome-app.store')));
+ await key(tester, LogicalKeyboardKey.keyS, cmd: true);
expect(app.activeSwarm.isStore, isTrue);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
await tester.pumpAndSettle();
@@ -526,7 +515,15 @@ void main() {
expect(find.byType(OnboardingCard), findsNothing);
await tester.enterText(resourceField, ':local');
await tester.pump();
- expect(find.text('Qwen3.8-27B'), findsOneWidget);
+ // The compact palette scrolls its catalog rather than filling the page.
+ await selectResource(tester, 'model:local:qwen');
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('model:local:qwen')),
+ matching: find.text('Qwen3.8-27B', findRichText: true),
+ ),
+ findsOneWidget,
+ );
expect(app.actions, isEmpty);
expect(journey.completed(OnboardingStep.models), isFalse);
expect(app.panes.single.agentId, 'work');
diff --git a/desktop/test/unavailable_harness_picker_test.dart b/desktop/test/unavailable_harness_picker_test.dart
index 33b55b7ad..6c5ca27e3 100644
--- a/desktop/test/unavailable_harness_picker_test.dart
+++ b/desktop/test/unavailable_harness_picker_test.dart
@@ -9,6 +9,7 @@ import 'package:harness/terminal/terminal_text.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/widgets/search_result_text.dart';
import 'package:harness/widgets/swarm_resource_preview.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'package:xterm/xterm.dart' show TerminalStyle;
import 'keymap_host_test.dart' show key;
@@ -195,9 +196,15 @@ void main() {
contains(label),
);
final title = tester.widget<SearchResultText>(
- find.descendant(of: row, matching: find.byType(SearchResultText)),
+ find.descendant(
+ of: row,
+ matching: find.byWidgetPredicate(
+ (w) =>
+ w is SearchResultText && w.text == controller.selected!.title,
+ ),
+ ),
);
- expect(title.style.color!.a, closeTo(.28, .01));
+ expect(title.style.color, DesktopChrome.selectionDetail);
expect(find.textContaining('No room'), findsNothing);
await key(tester, LogicalKeyboardKey.enter);
await key(tester, LogicalKeyboardKey.enter, cmd: true);
@@ -225,10 +232,7 @@ void main() {
terminalThemeStore.value = TerminalThemeChoice.tango;
await tester.pump();
expect(tester.takeException(), isNull);
- expect(
- tester.getSize(row).height,
- closeTo(terminalCellSizeOf(tester.element(field)).height, .01),
- );
+ expect(tester.getSize(row).height, greaterThanOrEqualTo(44));
await capture(tester, 'unavailable-sessions-narrow');
machine
..nodeOnline = true
diff --git a/desktop/test/usage_section_test.dart b/desktop/test/usage_section_test.dart
index 89483675e..2bcc6df2f 100644
--- a/desktop/test/usage_section_test.dart
+++ b/desktop/test/usage_section_test.dart
@@ -214,6 +214,32 @@ void main() {
},
);
+ testWidgets('usage selectors announce purpose as well as current scope', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ final controller = controllerWith(const {});
+ await controller.load();
+ await pumpUsage(tester, controller);
+ final provider = tester
+ .getSemantics(find.bySemanticsLabel('Usage provider'))
+ .getSemanticsData();
+ final range = tester
+ .getSemantics(find.bySemanticsLabel('Usage date range'))
+ .getSemanticsData();
+ expect(provider.label, 'Usage provider');
+ expect(provider.value, 'Overview');
+ expect(range.label, 'Usage date range');
+ expect(
+ range.value,
+ tester.widget<AppSelectField<UsageRange>>(_rangeField).value.label,
+ );
+ } finally {
+ semantics.dispose();
+ }
+ });
+
testWidgets('rests with nothing switched on, and offers the switches', (
tester,
) async {
diff --git a/desktop/test/welcome_entry_layout_test.dart b/desktop/test/welcome_entry_layout_test.dart
index 76de2fcc3..8bc75c5dd 100644
--- a/desktop/test/welcome_entry_layout_test.dart
+++ b/desktop/test/welcome_entry_layout_test.dart
@@ -8,6 +8,8 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/harness_start_page.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
import 'support/real_fonts.dart';
import 'swarm_state_test.dart' show createApp;
@@ -121,8 +123,9 @@ void main() {
// card follows it on the same row, never wrapped below it.
expect(storeRect.left, closeTo(fieldRect.left, 1));
expect(deviceRect.left, closeTo(storeRect.right + 16, 1));
- expect(deviceRect.bottom, closeTo(height - 80, 1));
- expect(storeRect.bottom, closeTo(height - 80, 1));
+ final pageRect = tester.getRect(find.byType(HarnessStartPage));
+ expect(deviceRect.bottom, closeTo(pageRect.bottom - 80, 1));
+ expect(storeRect.bottom, closeTo(pageRect.bottom - 80, 1));
expect(find.text('Meet the\nHarness device'), findsOneWidget);
expect(create.hitTestable(), findsOneWidget);
expect(open.hitTestable(), findsOneWidget);
@@ -152,7 +155,26 @@ void main() {
await tester.pump();
final results = find.byKey(const ValueKey('harness-start-results'));
expect(results, findsOneWidget);
- expect(tester.getRect(results).height, greaterThan(140));
+ // Even the shortest workspace keeps multiple complete choices visible
+ // above the fixed footer; the status bar consumes its own window space.
+ final choices = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search
+ .rows
+ .take(2)
+ .toList();
+ expect(choices, hasLength(2));
+ for (final choice in choices) {
+ final rowRect = tester.getRect(find.byKey(ValueKey(choice.id)));
+ expect(
+ rowRect.top,
+ greaterThanOrEqualTo(tester.getRect(results).top),
+ );
+ expect(
+ rowRect.bottom,
+ lessThanOrEqualTo(tester.getRect(results).bottom),
+ );
+ }
expect(tester.getRect(results).width, tester.getRect(field).width);
expect(tester.getRect(field).left, closeTo(fieldRect.left, 1));
expect(tester.getRect(field).right, closeTo(fieldRect.right, 1));
diff --git a/desktop/test/welcome_sessions_test.dart b/desktop/test/welcome_sessions_test.dart
index 3a3f59881..fe9359b1f 100644
--- a/desktop/test/welcome_sessions_test.dart
+++ b/desktop/test/welcome_sessions_test.dart
@@ -311,7 +311,7 @@ void main() {
);
testWidgets(
- 'in the workspace an empty tab keys the list, and gets it back after Cmd-P',
+ 'empty workspace keeps recent sessions available before connecting a local machine',
(tester) async {
newHarnessOpensInBox = true;
addTearDown(() => newHarnessOpensInBox = false);
@@ -319,21 +319,17 @@ void main() {
final app = sessions.app;
await mount(tester, app);
await tester.pump(const Duration(milliseconds: 50));
- String? focused() => FocusManager.instance.primaryFocus?.debugLabel;
expect(find.byKey(const ValueKey('welcome-sessions')), findsOneWidget);
- expect(focused(), 'Welcome sessions');
+ expect(find.text('Choose a machine'), findsOneWidget);
await key(tester, LogicalKeyboardKey.keyP, cmd: true);
await tester.pump(const Duration(milliseconds: 100));
- expect(focused(), isNot('Welcome sessions'));
+ expect(find.byKey(const ValueKey('swarm-search-input')), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
await tester.pump(const Duration(milliseconds: 100));
- expect(focused(), 'Welcome sessions');
+ expect(find.text('Choose a machine'), findsOneWidget);
- // 1 Command palette (a1), 2 NFC chat, 3 Deploy latest firmware (a2).
- await key(tester, LogicalKeyboardKey.arrowDown);
- await key(tester, LogicalKeyboardKey.arrowDown);
- await key(tester, LogicalKeyboardKey.enter);
+ await tester.tap(find.text('Deploy latest firmware'));
await tester.pump(const Duration(milliseconds: 100));
expect(app.panes.map((pane) => pane.agentId), ['a2']);
await tester.pumpWidget(const SizedBox());
@@ -394,7 +390,7 @@ void main() {
expect(find.text('Investigate Harness crash'), findsOneWidget);
expect(find.text('In the Codex app'), findsNothing);
- await key(tester, LogicalKeyboardKey.digit1);
+ await tester.tap(find.text('Investigate Harness crash'));
await tester.pump(const Duration(milliseconds: 100));
await tester.pump(const Duration(milliseconds: 100));
expect(
diff --git a/desktop/test/welcome_wallpaper_shortcuts_test.dart b/desktop/test/welcome_wallpaper_shortcuts_test.dart
index 3b9af75eb..c2183b0b1 100644
--- a/desktop/test/welcome_wallpaper_shortcuts_test.dart
+++ b/desktop/test/welcome_wallpaper_shortcuts_test.dart
@@ -14,7 +14,9 @@ import 'package:harness/shortcuts/app_keymap.dart';
import 'package:harness/shortcuts/keyboard_practice.dart';
import 'package:harness/shortcuts/shortcuts_browser.dart';
import 'package:harness/terminal/terminal_text.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'package:harness/widgets/shortcuts_sheet.dart';
+import 'package:harness/widgets/terminal_text_action.dart';
import 'package:harness/widgets/workspace_welcome.dart';
import 'package:xterm/xterm.dart';
@@ -112,7 +114,7 @@ void main() {
}
void expectUniformText(WidgetTester tester) {
- void check(InlineSpan span, TextStyle parent) {
+ void check(InlineSpan span, TextStyle parent, {bool capsule = false}) {
final style = parent.merge(span.style);
if (span is TextSpan) {
// Icon glyphs (Material's, and the app's Lucide set) are not type.
@@ -121,21 +123,34 @@ void main() {
(style.fontFamily?.startsWith('packages/lucide_icons_flutter/') ??
false);
if (span.text?.trim().isNotEmpty == true && !icon) {
- expect(style.fontSize, terminalFontStore.size, reason: span.text);
+ expect(
+ style.fontSize,
+ capsule ? 13 : terminalFontStore.size,
+ reason: span.text,
+ );
expect(
style.fontFamily,
- terminalFontStore.value.fontFamily,
+ capsule
+ ? DesktopChrome.text().fontFamily
+ : terminalFontStore.value.fontFamily,
reason: span.text,
);
}
for (final child in span.children ?? <InlineSpan>[]) {
- check(child, style);
+ check(child, style, capsule: capsule);
}
}
}
- for (final rich in tester.widgetList<RichText>(find.byType(RichText))) {
- check(rich.text, const TextStyle());
+ for (final rich in find.byType(RichText).evaluate()) {
+ // Workspace prose follows the terminal font; named actions deliberately
+ // use the shared desktop capsule typography, independent of terminal size.
+ check(
+ (rich.widget as RichText).text,
+ const TextStyle(),
+ capsule:
+ rich.findAncestorWidgetOfExactType<TerminalTextAction>() != null,
+ );
}
for (final input in tester.widgetList<EditableText>(
find.byType(EditableText),
@@ -146,6 +161,27 @@ void main() {
expect(tester.takeException(), isNull);
}
+ void expectShortcutTypography(WidgetTester tester) {
+ final browser = find.byType(ShortcutsBrowser);
+ for (final text in tester.widgetList<Text>(
+ find.descendant(of: browser, matching: find.byType(Text)),
+ )) {
+ if (text.style?.fontFamily != null) {
+ expect(
+ text.style!.fontFamily,
+ grid.AppType.sansFamily,
+ reason: text.data,
+ );
+ }
+ }
+ final input = tester.widget<TextField>(
+ find.byKey(const ValueKey('shortcuts-search')),
+ );
+ expect(input.style!.fontFamily, grid.AppType.sansFamily);
+ expect(input.style!.fontSize, 13);
+ expect(tester.takeException(), isNull);
+ }
+
testWidgets(
'wallpapers keep a centered welcome and the selected terminal type',
(tester) async {
@@ -261,11 +297,11 @@ void main() {
);
final search = find.byKey(const ValueKey('shortcuts-search'));
await capture(tester, 'shortcuts-dark');
- expectUniformText(tester);
+ expectShortcutTypography(tester);
await tester.enterText(search, 'clone');
await tester.pump();
expect(find.text('Clone Harness'), findsOneWidget);
- expect(find.text('New Swarm'), findsNothing);
+ expect(find.text('New Tab'), findsNothing);
await tester.enterText(search, 'unknown shortcut');
await tester.pump();
expect(find.textContaining('No shortcuts found'), findsOneWidget);
@@ -274,7 +310,7 @@ void main() {
);
await tester.enterText(search, 'cmd+y');
await tester.pump();
- expect(find.text('New Swarm'), findsOneWidget);
+ expect(find.text('New Tab'), findsOneWidget);
expect(find.text('Y'), findsOneWidget);
await key(tester, LogicalKeyboardKey.arrowDown);
await key(tester, LogicalKeyboardKey.enter);
@@ -282,7 +318,7 @@ void main() {
expect(find.byType(KeyboardPractice), findsOneWidget);
await key(tester, LogicalKeyboardKey.keyY, cmd: true);
await tester.pumpAndSettle();
- expect(find.text('[x] New Swarm'), findsOneWidget);
+ expect(find.byKey(const ValueKey('practice-completed')), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
@@ -292,7 +328,7 @@ void main() {
font(22);
tester.view.physicalSize = const Size(420, 740);
await tester.pumpAndSettle();
- expectUniformText(tester);
+ expectShortcutTypography(tester);
await capture(tester, 'shortcuts-narrow-large');
await tester.pumpWidget(const SizedBox());
},
@@ -314,7 +350,7 @@ void main() {
showShortcutsSheet(host);
await tester.pumpAndSettle();
expect(find.byType(ShortcutsBrowser), findsOneWidget);
- expectUniformText(tester);
+ expectShortcutTypography(tester);
// Dialog lives above the page's boundary; capture it directly when requested.
final output = Platform.environment['HARNESS_REFINEMENT_CAPTURE_DIR'];
if (output != null) {
diff --git a/desktop/test/workspace_activity_test.dart b/desktop/test/workspace_activity_test.dart
index f8348b830..e93f1da1b 100644
--- a/desktop/test/workspace_activity_test.dart
+++ b/desktop/test/workspace_activity_test.dart
@@ -9,6 +9,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/harness_activity.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
+import 'package:harness/widgets/desktop_workspace_tab.dart';
import 'package:harness/widgets/harness_activity_mark.dart';
import 'harness_activity_test.dart' show activityQuestion;
@@ -46,6 +47,14 @@ void main() {
} else {
await loadRealFonts();
}
+ if (capture != null) {
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
+ }
});
for (final native in [false, true]) {
@@ -177,7 +186,21 @@ void main() {
if (native) {
expect(nativeActivity(second.id)['mark'], isEmpty);
} else {
- expect(flutterState(second.id), HarnessActivity.idle);
+ expect(
+ find.byKey(ValueKey('tab-activity:${second.id}')),
+ findsNothing,
+ );
+ expect(
+ tester
+ .widget<DesktopWorkspaceTab>(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is DesktopWorkspaceTab && widget.id == second.id,
+ ),
+ )
+ .activityLabel,
+ HarnessActivity.idle.label,
+ );
}
// Narrow windows keep the symbol, shorten the name, and retain controls.
tester.view.physicalSize = const Size(640, 600);
diff --git a/desktop/test/workspace_machine_prompt_test.dart b/desktop/test/workspace_machine_prompt_test.dart
new file mode 100644
index 000000000..ef75d0b7f
--- /dev/null
+++ b/desktop/test/workspace_machine_prompt_test.dart
@@ -0,0 +1,238 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/workspace_machine_prompt.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/real_fonts.dart';
+
+void main() {
+ final output = Platform.environment['WELCOME_MACHINE_RENDER_DIR'];
+ setUpAll(() async {
+ await loadRealFonts();
+ if (output != null) await loadPreviewFonts();
+ });
+
+ Future<GlobalKey> mount(
+ WidgetTester tester, {
+ required Brightness brightness,
+ required double scale,
+ required ValueNotifier<bool> loading,
+ required VoidCallback onChoose,
+ ValueNotifier<bool>? preparing,
+ FocusNode? workspaceFocus,
+ }) async {
+ tester.view.physicalSize = const Size(880, 560);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final picture = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: picture,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid
+ .buildAppTheme(brightness: brightness)
+ .copyWith(platform: TargetPlatform.macOS),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(scale),
+ disableAnimations: true,
+ ),
+ child: child!,
+ ),
+ home: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Center(
+ child: SizedBox(
+ width: 680,
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(24),
+ child: Focus(
+ focusNode: workspaceFocus,
+ canRequestFocus: workspaceFocus != null,
+ skipTraversal: true,
+ child: ListenableBuilder(
+ listenable: Listenable.merge([loading, ?preparing]),
+ builder: (context, _) => WorkspaceMachinePrompt(
+ loading: loading.value,
+ preparing: preparing?.value ?? false,
+ onChoose: onChoose,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return picture;
+ }
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ for (final pending in [true, false]) {
+ testWidgets(
+ 'machine prompt remains actionable ${brightness.name} $scale '
+ '${pending ? "loading" : "empty"}',
+ (tester) async {
+ final loading = ValueNotifier(pending);
+ addTearDown(loading.dispose);
+ var choices = 0;
+ final picture = await mount(
+ tester,
+ brightness: brightness,
+ scale: scale,
+ loading: loading,
+ onChoose: () => choices++,
+ );
+ expect(tester.takeException(), isNull);
+ final heading = find.text('Harness anything');
+ final explanation = find.text(
+ pending
+ ? 'Finding your machines…'
+ : 'Choose a machine to start a new harness.',
+ );
+ final action = find.widgetWithText(
+ FilledButton,
+ 'Choose a machine',
+ );
+ final button = tester.getRect(action);
+ expect(action.hitTestable(), findsOneWidget);
+ expect(choices, 0);
+ expect(button.width, lessThan(400));
+ expect(button.bottom, lessThanOrEqualTo(536));
+ expect(
+ tester.getRect(heading).bottom,
+ lessThan(tester.getRect(explanation).top),
+ );
+ expect(tester.getRect(explanation).bottom, lessThan(button.top));
+ final label = tester.getRect(find.text('Choose a machine'));
+ expect(label.top - button.top, greaterThanOrEqualTo(6));
+ expect(button.bottom - label.bottom, greaterThanOrEqualTo(6));
+ for (final paragraph
+ in tester.allRenderObjects.whereType<RenderParagraph>()) {
+ expect(paragraph.didExceedMaxLines, isFalse);
+ }
+ if (output != null) {
+ await tester.runAsync(() async {
+ final image =
+ await (picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage();
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(output).create(recursive: true);
+ await File(
+ '$output/machine-${pending ? "loading" : "empty"}-'
+ '${brightness.name}-$scale.png',
+ ).writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ await tester.tap(action);
+ await tester.pump();
+ expect(choices, 1);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(
+ Focus.of(tester.element(find.text('Choose a machine'))).hasFocus,
+ isTrue,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(choices, 2);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+ }
+ }
+
+ testWidgets('inventory completion preserves the active action', (
+ tester,
+ ) async {
+ final loading = ValueNotifier(true);
+ addTearDown(loading.dispose);
+ var choices = 0;
+ await mount(
+ tester,
+ brightness: Brightness.dark,
+ scale: 2,
+ loading: loading,
+ onChoose: () => choices++,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ final action = find.widgetWithText(FilledButton, 'Choose a machine');
+ final control = tester.element(action);
+ final focus = Focus.of(tester.element(find.text('Choose a machine')));
+ expect(focus.hasFocus, isTrue);
+ loading.value = false;
+ await tester.pumpAndSettle();
+ expect(find.text('Finding your machines…'), findsNothing);
+ expect(
+ find.text('Choose a machine to start a new harness.'),
+ findsOneWidget,
+ );
+ expect(tester.element(action), same(control));
+ expect(focus.hasFocus, isTrue);
+ expect(choices, 0);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(choices, 1);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('preparing handoff leaves focus with the workspace', (
+ tester,
+ ) async {
+ final loading = ValueNotifier(true);
+ final preparing = ValueNotifier(true);
+ final workspaceFocus = FocusNode();
+ addTearDown(loading.dispose);
+ addTearDown(preparing.dispose);
+ addTearDown(workspaceFocus.dispose);
+ var choices = 0;
+ await mount(
+ tester,
+ brightness: Brightness.dark,
+ scale: 2,
+ loading: loading,
+ preparing: preparing,
+ workspaceFocus: workspaceFocus,
+ onChoose: () => choices++,
+ );
+ workspaceFocus.requestFocus();
+ await tester.pump();
+ expect(workspaceFocus.hasPrimaryFocus, isTrue);
+ expect(find.text('Harness anything'), findsOneWidget);
+ expect(find.text('Preparing your harness…'), findsOneWidget);
+ expect(find.text('Finding your machines…'), findsNothing);
+ expect(find.byType(FilledButton), findsNothing);
+ preparing.value = false;
+ await tester.pumpAndSettle();
+ expect(find.text('Preparing your harness…'), findsNothing);
+ expect(find.text('Finding your machines…'), findsOneWidget);
+ expect(find.byType(FilledButton).hitTestable(), findsOneWidget);
+ expect(workspaceFocus.hasPrimaryFocus, isTrue);
+ preparing.value = true;
+ await tester.pumpAndSettle();
+ expect(find.byType(FilledButton), findsNothing);
+ expect(workspaceFocus.hasPrimaryFocus, isTrue);
+ expect(choices, 0);
+ expect(tester.takeException(), isNull);
+ });
+}
diff --git a/desktop/test/workspace_pull_request_label_test.dart b/desktop/test/workspace_pull_request_label_test.dart
index 3d48ec251..b4586e36c 100644
--- a/desktop/test/workspace_pull_request_label_test.dart
+++ b/desktop/test/workspace_pull_request_label_test.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/color_palette.dart';
import 'package:harness/shared/theme/pull_request_icon.dart';
import 'package:harness/shared/theme/status_line_style.dart';
import 'package:harness/terminal/terminal_theme.dart';
@@ -32,6 +33,36 @@ void main() {
}
expect(colors.length, 4);
}
+ final originalPalette = grid.AppTheme.palette.value;
+ addTearDown(() => grid.AppTheme.palette.value = originalPalette);
+ for (final brightness in Brightness.values) {
+ grid.AppTheme.palette.value = brightness == Brightness.light
+ ? HarnessPalette.paper
+ : HarnessPalette.graphite;
+ final surface = grid.AppTheme.as(
+ brightness,
+ () => grid.AppPalette.cardBg,
+ );
+ for (final state in ['Open', 'Merged', 'Closed', 'Draft']) {
+ final color = pullRequestIconColor(
+ state,
+ null,
+ brightness: brightness,
+ );
+ expect(
+ pullRequestIconColor(
+ state,
+ tangoTerminalTheme,
+ brightness: brightness,
+ ),
+ color,
+ );
+ final a = color.computeLuminance();
+ final b = surface.computeLuminance();
+ final ratio = a > b ? (a + .05) / (b + .05) : (b + .05) / (a + .05);
+ expect(ratio, greaterThanOrEqualTo(4.5));
+ }
+ }
},
);
diff --git a/desktop/test/workspace_start_guide_test.dart b/desktop/test/workspace_start_guide_test.dart
index bdefc9a70..c0477cf9d 100644
--- a/desktop/test/workspace_start_guide_test.dart
+++ b/desktop/test/workspace_start_guide_test.dart
@@ -166,7 +166,6 @@ void main() {
),
);
await tester.pumpAndSettle();
- await key(tester, LogicalKeyboardKey.enter);
await typeHarnessQuery(tester, 'first-project');
await key(tester, LogicalKeyboardKey.enter);
}
@@ -186,14 +185,11 @@ void main() {
addTearDown(app.dispose);
addTearDown(journey.dispose);
await _mount(tester, app, onboarding: journey);
- expect(find.text('Harness like a boss.'), findsOneWidget);
- expect(find.text('○'), findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(app.panes, isEmpty);
if (keyboard) {
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- } else {
- await tester.tap(find.byKey(const ValueKey('welcome-agent.new')));
}
await tester.pumpAndSettle();
expect(find.byType(NewHarnessForm), findsOneWidget);
@@ -237,7 +233,7 @@ void main() {
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
await tester.pumpAndSettle();
expect(find.byType(WorkspaceWelcome), findsOneWidget);
- expect(find.text('Harness like a boss.'), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
for (final mark in ['✓', '○']) {
expect(
find.descendant(
@@ -268,7 +264,7 @@ void main() {
await chooseProject(tester);
await startHarness(tester);
await tester.pump();
- expect(find.text('Starting harness…'), findsOneWidget);
+ expect(find.text('Starting…'), findsOneWidget);
await tester.tap(start);
await key(tester, LogicalKeyboardKey.enter);
expect(app.launches, hasLength(1));
@@ -286,14 +282,21 @@ void main() {
final project = app.launches.single.project;
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ // Search can temporarily replace the page without discarding the retry.
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
expect(find.byType(NewHarnessForm), findsNothing);
- expect(find.text('Harness like a boss.'), findsOneWidget);
- expect(find.text('○'), findsNothing);
-
- await tester.tap(find.byKey(const ValueKey('welcome-agent.new')));
+ await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
app.creation = null;
- await chooseProject(tester);
+ expect(
+ tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller
+ .projectFolderRequest
+ ?.name,
+ project?.name,
+ );
await tester.tap(start);
await tester.pumpAndSettle();
expect(app.launches, hasLength(2));
@@ -305,7 +308,7 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
- testWidgets('welcome and New Tab stay quiet until an action is chosen', (
+ testWidgets('welcome and New Tab never launch until the form is submitted', (
tester,
) async {
final app = _FirstApp();
@@ -313,17 +316,17 @@ void main() {
await _mount(tester, app);
final search = find.byKey(const ValueKey('swarm-search-input'));
expect(find.byType(WorkspaceWelcome), findsOneWidget);
- expect(find.text('Harness like a boss.'), findsOneWidget);
- expect(find.byType(NewHarnessForm), findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(search, findsNothing);
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
expect(find.byType(NewHarnessForm), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
- expect(find.byType(NewHarnessForm), findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pumpAndSettle();
final tab = app.activeSwarmId;
expect(find.byType(WorkspaceWelcome), findsOneWidget);
- expect(find.text('Harness like a boss.'), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(search, findsNothing);
await openHarnessPicker(tester);
await tester.pump();
@@ -331,12 +334,12 @@ void main() {
await key(tester, LogicalKeyboardKey.escape);
expect(app.activeSwarmId, tab);
expect(search, findsNothing);
- await tester.tap(find.byKey(const ValueKey('welcome-agent.new')));
- await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ await tester.pumpAndSettle();
expect(find.byType(NewHarnessForm), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
expect(app.activeSwarmId, tab);
- expect(find.byType(NewHarnessForm), findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(app.launches, isEmpty);
await tester.pumpWidget(const SizedBox());
});
@@ -460,38 +463,40 @@ void main() {
expect(app.swarms, [first, second, welcome]);
expect(app.allPanes, [pane, other]);
expect(find.byType(WorkspaceWelcome).hitTestable(), findsOneWidget);
- expect(find.byType(NewHarnessForm), findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
await openHarnessPicker(tester);
expect(
find.byKey(const ValueKey('swarm-search-input')),
findsOneWidget,
);
- void expectGuideFixed(Finder dock) {
- final drawing = tester.getRect(
- find.byKey(const ValueKey('workspace-welcome-text')).last,
- );
+ void expectPageFits(Finder dock) {
+ final drawing = tester.getRect(find.byType(WorkspaceWelcome).last);
expect(drawing.top, greaterThanOrEqualTo(0));
expect(
- drawing.center,
- tester.getRect(find.byType(WorkspaceWelcome).last).center,
+ drawing.bottom,
+ lessThanOrEqualTo(tester.view.physicalSize.height),
);
expect(dock, findsOneWidget);
expect(tester.takeException(), isNull);
}
final searchDock = find.byKey(const ValueKey('swarm-search-results'));
- expectGuideFixed(searchDock);
+ expectPageFits(searchDock);
tester.view.physicalSize = const Size(960, 640);
await tester.pump();
- expectGuideFixed(searchDock);
+ expectPageFits(searchDock);
expect(tester.state<TerminalViewState>(view), same(renderer));
expect(app.launches, isEmpty);
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
await tester.pump(const Duration(milliseconds: 150));
expect(find.byType(NewHarnessForm), findsOneWidget);
- expectGuideFixed(find.byKey(const ValueKey('new-harness-form')));
+ expectPageFits(find.byKey(const ValueKey('new-harness-form')));
+ expect(
+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).embedded,
+ isTrue,
+ );
await key(tester, LogicalKeyboardKey.escape);
await tester.pump();
await key(tester, LogicalKeyboardKey.keyW, cmd: true);
@@ -582,7 +587,7 @@ void main() {
),
);
expect(tester.takeException(), isNull);
- final tab = find.text('⌘Y New Swarm');
+ final tab = find.text('⌘Y New Tab');
expect(tab, findsOneWidget);
await tester.tap(tab);
expect(
@@ -599,61 +604,63 @@ void main() {
},
);
- testWidgets('welcome text and wallpaper stay fixed when either dock opens', (
- tester,
- ) async {
- final app = _FirstApp();
- addTearDown(app.dispose);
- app.machineStates['m']!.agents = [
- Agent(id: 'saved', name: 'Robot arm', engine: 'claude'),
- ];
- await _mount(tester, app);
- await key(tester, LogicalKeyboardKey.keyT, cmd: true);
- await tester.pumpAndSettle();
- final page = find.byType(WorkspaceWelcome).last;
- final tagline = find.byKey(const ValueKey('workspace-welcome-text')).last;
- final textRect = tester.getRect(tagline);
- final wallpaper = find.byKey(const ValueKey('welcome-wallpaper')).last;
- final wallpaperRect = tester.getRect(wallpaper);
- void expectCentered() {
- expect(tester.getRect(tagline), textRect);
- expect(tester.getRect(wallpaper), wallpaperRect);
- expect(tester.getCenter(tagline), tester.getRect(page).center);
- expect(
- find.descendant(of: page, matching: find.byType(Image)),
- findsNothing,
- );
- }
+ testWidgets(
+ 'legacy welcome text and wallpaper stay fixed when either dock opens',
+ (tester) async {
+ newHarnessOpensInBox = false;
+ final app = _FirstApp();
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ Agent(id: 'saved', name: 'Robot arm', engine: 'claude'),
+ ];
+ await _mount(tester, app);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pumpAndSettle();
+ final page = find.byType(WorkspaceWelcome).last;
+ final tagline = find.byKey(const ValueKey('workspace-welcome-text')).last;
+ final textRect = tester.getRect(tagline);
+ final wallpaper = find.byKey(const ValueKey('welcome-wallpaper')).last;
+ final wallpaperRect = tester.getRect(wallpaper);
+ void expectCentered() {
+ expect(tester.getRect(tagline), textRect);
+ expect(tester.getRect(wallpaper), wallpaperRect);
+ expect(tester.getCenter(tagline), tester.getRect(page).center);
+ expect(
+ find.descendant(of: page, matching: find.byType(Image)),
+ findsNothing,
+ );
+ }
- expectCentered();
+ expectCentered();
- final search = find.byKey(const ValueKey('swarm-search-input'));
- expect(search, findsNothing);
- await openHarnessPicker(tester);
- await tester.enterText(search, 'nothing matches');
- await tester.pumpAndSettle();
- expectCentered();
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ expect(search, findsNothing);
+ await openHarnessPicker(tester);
+ await tester.enterText(search, 'nothing matches');
+ await tester.pumpAndSettle();
+ expectCentered();
- await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- await tester.pumpAndSettle();
- expect(find.byType(NewHarnessForm), findsOneWidget);
- expectCentered();
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- expectCentered();
- await tester.tap(find.byKey(const ValueKey('welcome-customize')));
- await tester.pumpAndSettle();
- expect(find.byType(HarnessCustomizePane), findsOneWidget);
- await tester.tap(find.byKey(const ValueKey('customize-wallpaper')));
- await tester.pumpAndSettle();
- expect(find.byType(WallpaperSection), findsOneWidget);
- expectCentered();
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- expect(find.byType(HarnessCustomizePane), findsNothing);
- expectCentered();
- await tester.pumpWidget(const SizedBox());
- });
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ await tester.pumpAndSettle();
+ expect(find.byType(AlertDialog), findsOneWidget);
+ expectCentered();
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expectCentered();
+ await tester.tap(find.byKey(const ValueKey('welcome-customize')));
+ await tester.pumpAndSettle();
+ expect(find.byType(HarnessCustomizePane), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('customize-wallpaper')));
+ await tester.pumpAndSettle();
+ expect(find.byType(WallpaperSection), findsOneWidget);
+ expectCentered();
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(HarnessCustomizePane), findsNothing);
+ expectCentered();
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
final output = Platform.environment['GUIDE_RENDER_DIR'];
testWidgets('render first entry guide', skip: output == null, (tester) async {
diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dart
index 41081df21..6dedbd6e3 100644
--- a/desktop/test/workspace_status_test.dart
+++ b/desktop/test/workspace_status_test.dart
@@ -3,6 +3,7 @@ import 'dart:async';
import 'dart:ui' as ui;
import 'dart:convert';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
@@ -12,12 +13,15 @@ import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/shared/theme/appearance_prefs_store.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/shared/theme/workspace_bar_style.dart';
+import 'package:harness/shared/theme/color_palette.dart';
import 'package:harness/shared/theme/prompt_style.dart';
import 'package:harness/shared/theme/status_line_style.dart';
import 'package:harness/state/swarm.dart';
import 'package:harness/state/terminal_pane.dart';
import 'package:harness/state/workspace_status.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/usage/models_menu_controller.dart';
+import 'package:harness/widgets/workspace_subscription_usage.dart';
import 'package:harness/terminal/terminal_text.dart';
import 'package:xterm/xterm.dart' show TerminalStyle;
import 'package:harness/widgets/grid_model_picker.dart';
@@ -34,6 +38,31 @@ import 'swarm_state_test.dart' show createApp, MemoryStore;
import 'swarm_screen_test.dart' show mount, terminal;
import 'support/real_fonts.dart';
+class _FooterSubscriptions extends ModelsMenuController {
+ List<Map<String, Object?>> values = [];
+ @override
+ List<Map<String, Object?>> get rows => values;
+ @override
+ Future<void> refresh() async {}
+ void update(List<Map<String, Object?>> value) {
+ values = value;
+ notifyListeners();
+ }
+}
+
+Map<String, Object?> subscription(
+ String engine,
+ String account,
+ num? remaining, {
+ String? status,
+}) => {
+ 'engine': engine,
+ 'account': account,
+ 'remainingPercent': remaining,
+ 'status': status ?? '$remaining% remaining',
+ 'details': ['Weekly limit'],
+};
+
class _PRConnection extends WsConn {
_PRConnection()
: super(
@@ -114,8 +143,10 @@ void main() {
if (Platform.environment['HARNESS_WORKSPACE_CONTROLS_CAPTURE_DIR'] !=
null) {
await loadRealFonts();
- await (FontLoader('packages/lucide_icons_flutter/Lucide')..addFont(
- rootBundle.load('packages/lucide_icons_flutter/assets/lucide.ttf'),
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
))
.load();
if (Platform.isMacOS) {
@@ -139,39 +170,16 @@ void main() {
});
for (final native in [false, true]) {
testWidgets(
- 'shared model selector follows focus and rejects stale actions (native=$native)',
+ 'pane model opens shared picker for its harness (native=$native)',
(tester) async {
final updates = <Map>[];
const channel = MethodChannel('harness/swarm_tabs');
- const codec = StandardMethodCodec();
final messenger = tester.binding.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'update') updates.add(call.arguments as Map);
return true;
});
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
- Future<void> activate(int paneId, String agentId) async {
- final done = Completer<void>();
- messenger.handlePlatformMessage(
- channel.name,
- codec.encodeMethodCall(
- MethodCall('focusedModel', {
- 'paneId': paneId,
- 'agentId': agentId,
- }),
- ),
- (bytes) {
- codec.decodeEnvelope(bytes!);
- done.complete();
- },
- );
- for (var i = 0; i < 8 && !done.isCompleted; i++) {
- await tester.pump();
- }
- expect(done.isCompleted, isTrue);
- await done.future;
- }
-
final connection = _PaneModelConnection();
final app = createApp(connectionForTest: (_) => connection);
addTearDown(app.dispose);
@@ -195,37 +203,43 @@ void main() {
final second = app.adoptSessionForTest(terminal('a1', []));
await mount(tester, app, nativeTabs: native);
final selectors = find.byType(GridModelPicker);
- expect(selectors, findsOneWidget);
+ Finder selector(String agent) =>
+ find.byKey(ValueKey(('pane-model', 'm', agent)));
+ expect(selectors, findsNWidgets(2));
+ expect(find.text('GPT-6 Astra'), findsOneWidget);
+ expect(find.text('Fable'), findsOneWidget);
+ expect(find.textContaining('High'), findsNothing);
expect(
- find.descendant(of: find.byType(TerminalPanel), matching: selectors),
+ find.descendant(
+ of: find.byKey(const ValueKey('workspace-status-bar')),
+ matching: selectors,
+ ),
findsNothing,
);
- if (native) {
- expect(updates.last['focusedModel']['text'], 'GPT-6 Astra · High');
- } else {
- expect(find.text('GPT-6 Astra · High'), findsOneWidget);
- expect(find.text('Fable'), findsNothing);
- await captureControls(tester, 'focused-model');
- expect(
- find.descendant(
- of: find.byKey(const ValueKey('workspace-status-bar')),
- matching: selectors,
- ),
- findsOneWidget,
- );
+ if (native) expect(updates.last['focusedModel'], isNull);
+ for (final width in [1280.0, 720.0]) {
+ tester.view.physicalSize = Size(width, 800);
+ await tester.pump();
+ for (final pane in [first, second]) {
+ final close = find.descendant(
+ of: find.byKey(pane.cellKey),
+ matching: find.byType(PaneCloseButton),
+ );
+ expect(close.hitTestable(), findsOneWidget);
+ final modelRect = tester.getRect(selector(pane.agentId!));
+ final closeRect = tester.getRect(close);
+ expect(modelRect.right, lessThanOrEqualTo(closeRect.left));
+ expect(modelRect.center.dy, closeTo(closeRect.center.dy, .1));
+ }
+ expect(tester.takeException(), isNull);
+ if (!native) await captureControls(tester, 'pane-model-$width');
}
- app.focusPane(first.id);
+ tester.view.physicalSize = const Size(1280, 800);
await tester.pump();
- if (native) {
- expect(updates.last['focusedModel']['text'], 'Fable · High');
- await activate(second.id, 'a1');
- expect(find.text('Local-Test-Model'), findsNothing);
- await activate(first.id, 'a0');
- } else {
- expect(find.text('GPT-6 Astra · High'), findsNothing);
- await tester.tap(selectors);
- }
+ expect(app.focusedPane, same(second));
+ await tester.tap(selector('a0'));
await tester.pumpAndSettle();
+ expect(app.focusedPane, same(first));
final modelSearch = find.byKey(const ValueKey('swarm-search-input'));
expect(modelSearch, findsOneWidget);
expect(tester.widget<TextField>(modelSearch).controller!.text, ':');
@@ -236,14 +250,9 @@ void main() {
expect(connection.retargets.single['agentId'], 'a0');
expect(connection.retargets.single['gridModel'], 'Local-Test-Model');
expect(app.panes, containsAll([first, second]));
- final stale = tester.widget<GridModelPicker>(selectors).onUseOwnLogin!;
- if (native) {
- await activate(first.id, 'a0');
- } else {
- await tester.tap(selectors);
- }
+
+ await tester.tap(selector('a0'));
await tester.pumpAndSettle();
- expect(modelSearch, findsOneWidget);
app.focusPane(second.id);
await tester.pumpAndSettle();
if (modelSearch.evaluate().isNotEmpty) {
@@ -255,24 +264,17 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
}
- // Dismissing the picker restores its originating pane. Move again
- // before checking that a callback captured for that pane is stale.
- app.focusPane(second.id);
+ final stale = tester.widget<GridModelPicker>(selector('a0')).onOpen!;
+ app.closePane(first.id);
await tester.pump();
stale();
await tester.pump();
+ expect(modelSearch, findsNothing);
expect(connection.retargets, hasLength(1));
app.machineStates['m']!.nodeOnline = false;
- app.focusPane(first.id);
+ app.focusPane(second.id, reveal: true);
await tester.pump();
- app.focusPane(second.id);
- await tester.pump();
- expect(tester.widget<GridModelPicker>(selectors).enabled, isFalse);
- if (native) {
- expect(updates.last['focusedModel']['interactive'], isFalse);
- await activate(second.id, 'a1');
- }
- expect(find.text('Local-Test-Model'), findsNothing);
+ expect(tester.widget<GridModelPicker>(selector('a1')).enabled, isFalse);
app.newSwarm();
await tester.pump();
expect(selectors, findsNothing);
@@ -282,7 +284,184 @@ void main() {
);
}
- testWidgets('hover close belongs to its pane and reserves title space', (
+ test(
+ 'footer distinguishes exhausted, unknown and separate subscriptions',
+ () {
+ expect(
+ WorkspaceSubscriptionUsage.fromRows([
+ subscription('claude', 'aaaaaa', 0),
+ subscription('codex', 'bbbbbb', 50),
+ ]).text,
+ 'Claude 0% Codex 50%',
+ );
+ final all = WorkspaceSubscriptionUsage.fromRows([
+ subscription('claude', 'aaaaaa', 0),
+ subscription('claude', 'cccccc', .3, status: '<1% remaining'),
+ subscription('codex', 'bbbbbb', null, status: 'Usage unavailable'),
+ ]);
+ expect(all.text, 'Claude aaaaaa 0% Claude cccccc <1% Codex —');
+ expect(all.detail, contains('Codex (bbbbbb): Usage unavailable'));
+ expect(all.segments.map((part) => part.tone), [
+ WorkspaceUsageTone.normal,
+ WorkspaceUsageTone.exhausted,
+ WorkspaceUsageTone.normal,
+ WorkspaceUsageTone.low,
+ WorkspaceUsageTone.normal,
+ WorkspaceUsageTone.normal,
+ ]);
+ expect(all.detail, contains('Weekly limit'));
+ expect(
+ WorkspaceSubscriptionUsage.fromRows([
+ subscription('claude', '', null, status: 'Not signed in'),
+ ]).text,
+ 'Subscriptions',
+ );
+ },
+ );
+
+ test('only low and exhausted percentages carry readable warning ink', () {
+ final oldBrightness = grid.AppTheme.brightness.value;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ final usage = WorkspaceSubscriptionUsage.fromRows([
+ subscription('claude', '', 0),
+ subscription('codex', '', 20),
+ subscription('other', '', 21),
+ ]);
+ for (final brightness in Brightness.values) {
+ grid.AppTheme.brightness.value = brightness;
+ for (final palette in HarnessPalette.values) {
+ final parts = usage.paintSegments(
+ foreground: palette.foreground,
+ surface: palette.workspace,
+ );
+ expect(parts[1].foreground, isNot(palette.foreground));
+ expect(parts[3].foreground, isNot(palette.foreground));
+ for (final index in [0, 2, 4, 5]) {
+ expect(parts[index].foreground, palette.foreground);
+ }
+ for (final part in parts) {
+ final ink = part.foreground.computeLuminance();
+ final ground = palette.workspace.computeLuminance();
+ expect(
+ ink > ground
+ ? (ink + .05) / (ground + .05)
+ : (ground + .05) / (ink + .05),
+ greaterThanOrEqualTo(4.5),
+ );
+ }
+ }
+ }
+ });
+
+ for (final native in [false, true]) {
+ testWidgets(
+ 'footer usage updates and opens subscriptions (native=$native)',
+ (tester) async {
+ final updates = <Map>[];
+ const channel = MethodChannel('harness/swarm_tabs');
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(channel, (call) async {
+ if (call.method == 'update') updates.add(call.arguments as Map);
+ return true;
+ });
+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
+ final subscriptions = _FooterSubscriptions()
+ ..values = [
+ subscription('claude', 'aaaaaa', 0),
+ subscription('codex', 'bbbbbb', 13),
+ ];
+ final app = createApp();
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ addTearDown(app.dispose);
+ addTearDown(subscriptions.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: native,
+ modelsMenu: subscriptions,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ const label = 'Claude 0% Codex 13%';
+ if (native) {
+ expect(updates.last['subscriptionUsage']['text'], label);
+ final parts = updates.last['subscriptionUsage']['segments'] as List;
+ expect(parts.map((part) => part['text']), [
+ 'Claude ',
+ '0%',
+ ' Codex ',
+ '13%',
+ ]);
+ expect(parts[0]['foreground'], parts[2]['foreground']);
+ expect(parts[1]['foreground'], isNot(parts[0]['foreground']));
+ expect(parts[3]['foreground'], isNot(parts[0]['foreground']));
+ expect(
+ updates.last['subscriptionUsage']['detail'],
+ contains('remaining'),
+ );
+ } else {
+ expect(find.text(label), findsOneWidget);
+ final usage = find.byKey(
+ const ValueKey('workspace-subscription-usage'),
+ );
+ final context = find.byKey(const ValueKey('workspace-pane-context'));
+ expect(
+ tester.getRect(usage).right,
+ lessThan(tester.getRect(context).left),
+ );
+ await captureControls(tester, 'subscription-usage-footer');
+ for (final width in [480.0, 640.0]) {
+ tester.view.physicalSize = Size(width, 800);
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ expect(
+ tester.getRect(usage).right,
+ lessThan(tester.getRect(context).left),
+ );
+ }
+ tester.view.physicalSize = const Size(1280, 800);
+ }
+ subscriptions.update([subscription('codex', 'bbbbbb', 27)]);
+ await tester.pump();
+ if (native) {
+ expect(updates.last['subscriptionUsage']['text'], 'Codex 27%');
+ final done = Completer<void>();
+ messenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('subscriptions'),
+ ),
+ (_) => done.complete(),
+ );
+ await tester.pumpAndSettle();
+ await done.future;
+ } else {
+ expect(find.text('Codex 27%'), findsOneWidget);
+ await tester.tap(
+ find.byKey(const ValueKey('workspace-subscription-usage')),
+ );
+ await tester.pumpAndSettle();
+ }
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ expect(
+ tester.widget<TextField>(search).controller!.text,
+ ':subscription',
+ );
+ expect(app.focusedPane, same(pane));
+ expect(app.panes, [pane]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets('visible close belongs to its pane without moving the title', (
tester,
) async {
final app = createApp();
@@ -296,35 +475,38 @@ void main() {
];
final close = find.byType(PaneCloseButton);
expect(close, findsNWidgets(2));
- expect(close.hitTestable(), findsNothing);
+ expect(close.hitTestable(), findsNWidgets(2));
+ final restingIcon = tester.widget<Icon>(
+ find.descendant(of: close.first, matching: find.byIcon(AppIcons.close)),
+ );
+ expect(restingIcon.size, AppIcons.closeSize);
+ expect(restingIcon.color!.a, .45);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
await mouse.moveTo(tester.getCenter(titles.first));
await tester.pump();
- expect(close.hitTestable(), findsOneWidget);
+ expect(close.hitTestable(), findsNWidgets(2));
for (var i = 0; i < 2; i++) {
expect(tester.getRect(titles.at(i)), titleRects[i]);
}
- await mouse.moveTo(tester.getCenter(close.hitTestable()));
+ await mouse.moveTo(tester.getCenter(close.first));
await tester.pump();
- final closeText = find.descendant(
- of: close.hitTestable(),
- matching: find.text('x'),
+ final closeIcon = find.descendant(
+ of: close.first,
+ matching: find.byIcon(AppIcons.close),
);
- expect(tester.widget<Text>(closeText).style?.fontWeight, FontWeight.bold);
+ expect(tester.widget<Icon>(closeIcon).color!.a, 1);
+ expect(tester.widget<Icon>(closeIcon).size, AppIcons.closeSize);
expect(
- find.descendant(
- of: close.hitTestable(),
- matching: find.byType(ColoredBox),
- ),
+ find.descendant(of: close.first, matching: find.byType(ColoredBox)),
findsNothing,
);
for (var i = 0; i < 2; i++) {
expect(tester.getRect(titles.at(i)), titleRects[i]);
}
await tester.pump(const Duration(milliseconds: 100));
- await captureControls(tester, 'pane-hover-close');
- await tester.tap(close.hitTestable());
+ await captureControls(tester, 'pane-visible-close');
+ await tester.tap(close.first);
await tester.pump();
expect(find.byKey(first.cellKey), findsNothing);
expect(app.panes, [second]);
@@ -542,7 +724,7 @@ void main() {
if (native) {
expect(
((updates.last['tabs'] as List).single as Map)['label'],
- '1:Release',
+ 'Release',
);
} else {
expect(find.text('Release'), findsOneWidget);
@@ -951,8 +1133,8 @@ void main() {
app.adoptSessionForTest(terminal('a1', []));
await mount(tester, app);
expect(find.text('code'), findsNWidgets(2));
- expect(find.text('1:'), findsOneWidget);
- expect(find.text('2:'), findsOneWidget);
+ expect(find.text('1:'), findsNothing);
+ expect(find.text('2:'), findsNothing);
final context = find.byKey(const ValueKey('workspace-pane-context'));
expect(
tester.getRect(context).top,
@@ -973,10 +1155,27 @@ void main() {
for (final element in barControls.evaluate()) {
final control = element.widget as WorkspaceBarControl;
final rect = tester.getRect(find.byWidget(control));
- expect(
- rect.height,
- control.selectedBackground == null ? 28 : tester.getSize(bar).height,
- );
+ if (control.label == 'Harness Store') {
+ final label = find.descendant(
+ of: find.byWidget(control),
+ matching: find.text('Harness Store'),
+ );
+ expect(
+ tester.widget<Text>(label).style!.fontFamily,
+ grid.AppType.sansFamily,
+ );
+ expect(
+ rect.height,
+ greaterThanOrEqualTo(tester.getSize(label).height + 12),
+ );
+ } else {
+ expect(
+ rect.height,
+ control.selectedBackground == null
+ ? 28
+ : tester.getSize(bar).height,
+ );
+ }
if (control.selected == true) {
final fill = find.descendant(
of: find.byWidget(control),
@@ -992,7 +1191,7 @@ void main() {
}
expect(
tester.getSize(secondTab).width,
- lessThan(workspaceBarCellSizeOf(tester.element(secondTab)).width * 12),
+ lessThanOrEqualTo(160 + grid.AppDesktop.tabCloseInset * 2),
reason: 'short tab labels keep their compact width in a roomy window',
);
expect(find.byKey(const ValueKey('swarm-search-button')), findsOneWidget);
@@ -1005,7 +1204,7 @@ void main() {
of: find.byType(TerminalPanel),
matching: find.byType(GridModelPicker),
),
- findsNothing,
+ findsWidgets,
);
await tester.tap(find.byKey(ValueKey(first.id)));
await tester.pump(const Duration(milliseconds: 350));
@@ -1028,6 +1227,49 @@ void main() {
}
}
await captureControls(tester, 'workspace-bottom-bar');
+ final workspace = tester.widget<SwarmScreen>(find.byType(SwarmScreen));
+ for (final scale in [1.0, 2.0]) {
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: workspace,
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ final store = find.byKey(const ValueKey('swarm-store-button'));
+ expect(
+ MediaQuery.textScalerOf(tester.element(store)).scale(13),
+ 13 * scale,
+ );
+ final label = find.descendant(
+ of: store,
+ matching: find.text('Harness Store'),
+ );
+ expect(
+ tester.renderObject<RenderParagraph>(label).didExceedMaxLines,
+ isFalse,
+ );
+ expect(
+ tester.getSize(store).height,
+ greaterThanOrEqualTo(tester.getSize(label).height + 12),
+ );
+ expect(
+ tester.widget<Text>(label).style!.fontFamily,
+ grid.AppType.sansFamily,
+ );
+ expect(tester.takeException(), isNull);
+ await captureControls(
+ tester,
+ 'store-navigation-$scale',
+ height: tester.getSize(bar).height,
+ );
+ }
await tester.pump(const Duration(milliseconds: 100));
await tester.pumpWidget(const SizedBox());
},
@@ -1055,7 +1297,8 @@ void main() {
app.adoptSessionForTest(terminal('a1', []));
await mount(tester, app, nativeTabs: true);
final tab = (updates.last['tabs'] as List).single as Map;
- expect(tab['label'], '1:code');
+ expect(tab['label'], 'code');
+ expect(tab['shortcutHint'], '⌘1');
expect((updates.last['focusedContext'] as Map)['text'], 'Test host');
expect(updates.last['barStyle'], containsPair('family', isA<String>()));
final originalPrefs = appearancePrefsStore.value;
@@ -1079,7 +1322,7 @@ void main() {
app.newSwarm();
await tester.pump();
expect(updates.last['focusedContext'], isNull);
- expect(((updates.last['tabs'] as List).last as Map)['label'], '2:new');
+ expect(((updates.last['tabs'] as List).last as Map)['label'], 'New Tab');
await tester.pumpWidget(const SizedBox());
},
);
diff --git a/desktop/test/workspace_welcome_test.dart b/desktop/test/workspace_welcome_test.dart
index 77b6c3f78..03cd0e0a4 100644
--- a/desktop/test/workspace_welcome_test.dart
+++ b/desktop/test/workspace_welcome_test.dart
@@ -171,7 +171,10 @@ void main() {
final contrast =
(hintInk.computeLuminance() + .05) /
(grid.AppPalette.swarmField.computeLuminance() + .05);
- expect(contrast, greaterThanOrEqualTo(4.5));
+ expect(
+ contrast >= 1 ? contrast : 1 / contrast,
+ greaterThanOrEqualTo(4.5),
+ );
for (final command in [
'agent.new',
'harnesses.list',
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 520cb86dc..36734d629 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -109,9 +109,9 @@ private extension SwarmTabButton {
let width = preferredWidth
let displayedWidth = frame.width
let rect = activityRect
- try checkTitlebar(label.string == "1:desktop" && activitySpace == cellWidth * 2,
+ try checkTitlebar(label.string == "desktop" && activitySpace >= activityRect.width + 6,
"Activity measures its gap and cell separately from the tab name")
- try checkTitlebar(rect.minX > ("1:desktop" as NSString).size(withAttributes: [.font: labelFont]).width,
+ try checkTitlebar(rect.minX >= titleRect.maxX + 6,
"The native activity follows the complete tab name")
var pictures = Set<Data>()
for frame in 0..<10 {
@@ -128,8 +128,8 @@ private extension SwarmTabButton {
for (mark, label) in states {
activity = SwarmTabActivity(payload(mark, label))
layoutSubtreeIfNeeded()
- try checkTitlebar(preferredWidth == width && activityRect == rect,
- "\(label) occupies the same reserved cell")
+ try checkTitlebar(preferredWidth == width && (mark.isEmpty || activityRect == rect),
+ "\(label) preserves tab width and visible marks share their inline cell")
try checkTitlebar(toolTip == label && selectButton.accessibilityHelp() == label,
"\(label) has readable hover and accessibility descriptions")
for narrow in [CGFloat(28), CGFloat(56), width, displayedWidth] {
@@ -158,11 +158,11 @@ private extension SwarmTabButton {
}
func checkShortNamesFit() throws {
- for name in ["1:desktop", "2:device", "3:swarm", "4:daemons", "5:web", "6:tui", "7:mobile"] {
+ for name in ["desktop", "device", "swarm", "daemons", "web", "tui", "mobile"] {
displayLabel = name
activity = SwarmTabActivity(["mark": "", "label": "Idle", "color": Int64(0xff999999)])
frame.size.width = preferredWidth
- let available = activityRect.minX - cellWidth - contentRect.minX
+ let available = titleRect.width
try checkTitlebar(available >= max(label.size().width, emphasizedLabel.size().width),
"\(name) fits at its preferred width in both weights without a false ellipsis")
}
@@ -300,17 +300,17 @@ private extension SwarmTabButton {
frame = NSRect(x: 0, y: 0, width: 160, height: 40)
contentCenterY = 20
name = "office"
- displayLabel = "2:office"
+ displayLabel = "office"
layoutSubtreeIfNeeded()
try checkTitlebar(toolTip == nil, "A fully visible tab name has no repeating tooltip")
- displayLabel = "2:code"
+ displayLabel = "code"
layoutSubtreeIfNeeded()
try checkTitlebar(toolTip == "office", "A different underlying tab name remains available")
name = "code"
layoutSubtreeIfNeeded()
try checkTitlebar(toolTip == nil, "Renaming a tab clears a redundant tooltip immediately")
name = "a-very-long-project-name"
- displayLabel = "2:\(name)"
+ displayLabel = name
layoutSubtreeIfNeeded()
try checkTitlebar(toolTip == displayLabel, "An ellipsized tab reveals its full label")
frame.size.width = 400
@@ -318,25 +318,35 @@ private extension SwarmTabButton {
layoutSubtreeIfNeeded()
try checkTitlebar(toolTip == nil, "Widening a tab removes a now-redundant tooltip")
- let symbol = SwarmStatusSymbolButton(frame: NSRect(x: 0, y: 0, width: 32, height: 28))
- symbol.title = "+"
+ let symbol = SwarmPlainIconButton(frame: NSRect(x: 0, y: 0, width: 32, height: 28))
+ symbol.image = HarnessControlSymbols.image("plus")
let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],
timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!
let symbolResting = symbol.renderedPixels()
symbol.mouseEntered(with: hover)
try checkTitlebar(symbol.renderedPixels() != symbolResting &&
symbol.renderedBitmap().colorAt(x: 1, y: 1)!.alphaComponent == 0,
- "Symbols become bold on hover without adding a background")
+ "Symbols emphasize their ink on hover without changing weight or adding a background")
+ shortcutHint = "⌘2"
+ activity = SwarmTabActivity(["mark": "⠋", "label": "Working", "color": Int64(0xff64d2ff)])
+ layoutSubtreeIfNeeded()
let width = preferredWidth
let resting = renderedPixels()
mouseEntered(with: hover)
let hovered = renderedBitmap()
- let filledRows = (0..<hovered.pixelsHigh).filter { hovered.colorAt(x: 1, y: $0)!.alphaComponent > 0 }
- try checkTitlebar(filledRows.isEmpty && renderedPixels() != resting,
- "Tabs become bold on hover without adding a background")
- try checkTitlebar(preferredWidth == width &&
- NSFontManager.shared.traits(of: emphasizedLabel.attribute(.font, at: 0, effectiveRange: nil) as! NSFont).contains(.boldFontMask),
- "Hover uses a bold font while preserving the tab width")
+ try checkTitlebar(hovered.colorAt(x: 20, y: 12)!.alphaComponent > 0 && renderedPixels() != resting,
+ "Hover quietly marks the tab surface")
+ try checkTitlebar(preferredWidth == width && !closeButton.isHidden && drawnFont == labelFont,
+ "Hover reveals the right close button without changing tab width or type")
+ let titleBeforeHint = titleRect, closeBeforeHint = closeButton.frame
+ showsShortcutHint = true
+ layoutSubtreeIfNeeded()
+ try checkTitlebar(displaysShortcut && !closeButton.isHidden && renderedPixels() != Data(bytes: hovered.bitmapData!, count: hovered.bytesPerRow * hovered.pixelsHigh),
+ "Holding Command replaces status with its shortcut while keeping the hover close action")
+ try checkTitlebar(titleRect == titleBeforeHint && closeButton.frame == closeBeforeHint && preferredWidth == width,
+ "Command hints never move the title, close target or tab boundaries")
+ showsShortcutHint = false
+ try checkTitlebar(!closeButton.isHidden, "Releasing Command keeps the hovered close action")
mouseExited(with: hover)
selectButton.highlight(true)
try checkTitlebar(renderedPixels() != resting, "Pressing a tab uses the same visible highlight")
@@ -348,13 +358,16 @@ private extension SwarmTabButton {
selected = true
let active = renderedBitmap()
let selectedRows = (0..<active.pixelsHigh).filter { active.colorAt(x: 1, y: $0)!.alphaComponent > 0 }
- try checkTitlebar(selectedRows.count == Int(bounds.height) && active.colorAt(x: 1, y: 20)!.alphaComponent == 1,
- "Selected tabs fill the full bar height")
+ try checkTitlebar(selectedRows.count > 0 && selectedRows.count < 8 &&
+ active.colorAt(x: 1, y: 20)!.alphaComponent == 0 &&
+ active.colorAt(x: 20, y: 20)!.alphaComponent == 1 &&
+ active.colorAt(x: 20, y: 0)!.alphaComponent == 0,
+ "The selected tab has upper curves, lower outward shoulders and a clear top inset")
mouseExited(with: hover)
for argb in [Int64(0xff282828), Int64(0xfff0f2f5)] {
palette = SwarmNativePalette(["workspace": argb])
let background = palette.workspace
- let pixel = renderedBitmap().colorAt(x: 1, y: 1)!.usingColorSpace(.sRGB)!
+ let pixel = renderedBitmap().colorAt(x: 20, y: Int(bounds.height) - 2)!.usingColorSpace(.sRGB)!
try checkTitlebar(abs(pixel.redComponent - background.redComponent) < 0.01 &&
abs(pixel.greenComponent - background.greenComponent) < 0.01 &&
abs(pixel.blueComponent - background.blueComponent) < 0.01,
@@ -362,6 +375,90 @@ private extension SwarmTabButton {
}
}
+ func checkHoverCloseAndShortcutHints() throws {
+ frame = NSRect(x: 0, y: 0, width: 240, height: 40)
+ contentCenterY = 20
+ name = "1: Release planning"
+ displayLabel = name
+ shortcutHint = "⌘2"
+ activity = SwarmTabActivity(["mark": "⠋", "label": "Working", "color": Int64(0xff64d2ff)])
+ layoutSubtreeIfNeeded()
+ let title = titleRect, close = closeButton.frame, width = preferredWidth
+ try checkTitlebar(closeButton.isHidden && !displaysShortcut,
+ "Resting tabs show neither a close icon nor a persistent shortcut")
+ var events: [String] = []
+ emit = { method, _ in events.append(method) }
+ let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],
+ timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!
+ mouseEntered(with: hover)
+ try checkTitlebar(!closeButton.isHidden && closeButton.frame.minX > title.maxX &&
+ closeButton.frame.size == NSSize(width: 32, height: 32),
+ "A hovered tab exposes a separate 32pt close target on the right")
+ try checkTitlebar(accessibilityChildren()?.count == 2 && closeButton.accessibilityLabel() == "Close 1: Release planning",
+ "The hover close button has the exact custom title as its accessible purpose")
+ let closeBitmap = closeButton.renderedBitmap()
+ let closeInk = (0..<closeBitmap.pixelsWide).flatMap { x in
+ (0..<closeBitmap.pixelsHigh).compactMap { y -> NSPoint? in
+ (closeBitmap.colorAt(x: x, y: y)?.alphaComponent ?? 0) > 0.1
+ ? NSPoint(x: x, y: y) : nil
+ }
+ }
+ let inkWidth = (closeInk.map(\.x).max() ?? 0) - (closeInk.map(\.x).min() ?? 0) + 1
+ let inkHeight = (closeInk.map(\.y).max() ?? 0) - (closeInk.map(\.y).min() ?? 0) + 1
+ try checkTitlebar(!closeInk.isEmpty && inkWidth <= 7 && inkHeight <= 7,
+ "The tab close paints a tiny regular cross inside its unchanged 32pt target")
+ closeButton.performClick(nil)
+ try checkTitlebar(events == ["close"], "Clicking the close control closes once without selecting the tab")
+ showsShortcutHint = true
+ try checkTitlebar(displaysShortcut && !closeButton.isHidden && shortcutLabel?.string == "⌘2",
+ "Command reveals the supplied shortcut beside the name without hiding hover close")
+ try checkTitlebar(indicatorRect.minX == titleRect.maxX + 6 &&
+ indicatorRect.maxX <= closeButton.frame.minX,
+ "The inline Command hint stays outside the close action's entire hit target")
+ let commandBitmap = renderedBitmap()
+ let hasActivityInk = (0..<commandBitmap.pixelsWide).contains { x in
+ (0..<commandBitmap.pixelsHigh).contains { y in
+ guard let pixel = commandBitmap.colorAt(x: x, y: y)?.usingColorSpace(.sRGB),
+ pixel.alphaComponent > 0.2 else { return false }
+ return pixel.blueComponent - pixel.redComponent > 0.15 &&
+ pixel.greenComponent - pixel.redComponent > 0.1
+ }
+ }
+ try checkTitlebar(!hasActivityInk && selectButton.accessibilityHelp() == "Working",
+ "Command hides the visual activity mark while retaining its accessible status")
+ try checkTitlebar(titleRect == title && closeButton.frame == close && preferredWidth == width,
+ "Modifier changes preserve every tab and title boundary")
+ mouseExited(with: hover)
+ try checkTitlebar(displaysShortcut && closeButton.isHidden,
+ "Command hints remain visible without pointer hover")
+ showsShortcutHint = false
+ try checkTitlebar(closeButton.isHidden && accessibilityChildren()?.count == 1,
+ "Releasing Command returns an unhovered tab to its quiet state")
+ shortcutHint = "⌃⌥⌘R"
+ layoutSubtreeIfNeeded()
+ showsShortcutHint = true
+ try checkTitlebar(shortcutLabel?.string == "⌃⌥⌘R" && indicatorRect.width >= shortcutLabel!.size().width,
+ "A remapped shortcut remains exact and fits its inline status position")
+ shortcutHint = nil
+ try checkTitlebar(!displaysShortcut, "Unbound and unnumbered tabs invent no shortcut hint")
+ actionsEnabled = false
+ mouseEntered(with: hover)
+ closeButton.performClick(nil)
+ try checkTitlebar(closeButton.isHidden && events == ["close"], "A modal disables and hides the hover close action")
+ emit = nil
+ }
+
+ func drawWithHoverControl() {
+ draw(bounds)
+ guard !closeButton.isHidden else { return }
+ NSGraphicsContext.saveGraphicsState()
+ let transform = NSAffineTransform()
+ transform.translateX(by: closeButton.frame.minX, yBy: closeButton.frame.minY)
+ transform.concat()
+ closeButton.draw(closeButton.bounds)
+ NSGraphicsContext.restoreGraphicsState()
+ }
+
func checkDoubleClickIsolation() throws {
let parent = nextResponder
let originalEmit = emit
@@ -410,9 +507,17 @@ private extension SwarmTabButton {
func checkCenteredLabel() throws {
let paragraph = label.attribute(.paragraphStyle, at: 0, effectiveRange: nil) as? NSParagraphStyle
- try checkTitlebar(paragraph?.alignment == .center, "The tab label is centered")
- try checkTitlebar(selectButton.frame == bounds, "Selection spans the whole tab without a close slot")
- try checkTitlebar(subviews.count == 1, "Hover and keyboard focus never add a close button")
+ let group = activitySpace == 0 ? titleRect : titleRect.union(indicatorRect)
+ try checkTitlebar(paragraph?.alignment == .center && abs(group.midX - bounds.midX) < 0.01,
+ "The visible title and adjacent indicator form a centered group")
+ try checkTitlebar(selectButton.frame == bounds, "Selection and drag retain the whole tab target beneath its accessory")
+ try checkTitlebar(subviews.count == 2 && closeButton.frame.maxX == bounds.maxX - 8,
+ "The close action stays inset inside the tab's curved body")
+ }
+
+ func checkCompleteNameFits() throws {
+ try checkTitlebar(titleRect.width >= naturalTitleWidth,
+ "The eight-tab fixture keeps each ordinary name readable")
}
func clickBothActions() {
@@ -424,9 +529,8 @@ private extension SwarmTabButton {
private extension SwarmTabStrip {
/// Every frame the bar lays out, apart from the daemon's own.
func barFrames() -> [NSRect] {
- [scroll.frame, document.frame, newButton.frame, contextButton.frame, focusedModelButton.frame,
- pullRequestButton.frame, searchButton.frame, notificationsButton.frame, storeButton.frame,
- shareButton.frame, voiceLabel.frame] + tabs.map { $0.frame }
+ [scroll.frame, document.frame, newButton.frame, contextButton.frame, subscriptionUsageButton.frame,
+ pullRequestButton.frame] + tabs.map { $0.frame }
}
/// Daemons off: no key, or `visible: false`, lays out exactly the bar from
@@ -438,7 +542,7 @@ private extension SwarmTabStrip {
let base: [String: Any] = ["enabled": true, "activeId": "off-3",
"tabs": (0..<7).map { ["id": "off-\($0)", "name": "Off \($0)", "label": "\($0 + 1):code"] },
"focusedContext": ["text": "Codex M2:project (main)", "canSelectModel": true],
- "focusedModel": ["text": "gpt-5", "paneId": 3, "agentId": "a1"],
+ "subscriptionUsage": ["text": "gpt-5", "paneId": 3, "agentId": "a1"],
"pullRequest": ["text": "PR #298 · Merged", "url": "https://github.com/acme/repo/pull/298"]]
daemonMayAppear = { true }
for width in [480.0, 720.0, 1024.0, 1440.0, 1920.0] {
@@ -621,6 +725,7 @@ private extension SwarmTabStrip {
species.flatMap { id in ["baby", "young", "adult"].map { "\(id)_\($0)_idle_0" } }
let bar = SwarmTabStrip(frame: NSRect(x: 0, y: 0, width: 900, height: 40))
bar.daemonMayAppear = { true }
+ bar.statusBar.frame = NSRect(x: 0, y: 0, width: 900, height: 40)
bar.daemonArt = art
bar.storeButton.image = SwarmHistoryIcons(assetURL: { asset in
assets.appendingPathComponent(String(asset.dropFirst("assets/".count)))
@@ -641,10 +746,10 @@ private extension SwarmTabStrip {
state["daemon"] = ["visible": true, "glyph": "[oo]", "art": "assets/daemon-art/slot/\(stage).png"]
bar.update(state)
try checkTitlebar(bar.daemonButton.art != nil && bar.daemonButton.frame.width == 44 &&
- bar.daemonButton.frame.minX == bar.storeButton.frame.maxX,
- "\(stage) is illustrated after Store on the \(light ? "light" : "dark") native bar")
+ bar.daemonButton.superview === bar.statusBar && bar.daemonButton.frame.minX == bar.subscriptionUsageButton.frame.maxX,
+ "\(stage) is illustrated in the footer on the \(light ? "light" : "dark") native bar")
pictures.insert(bar.daemonButton.renderedPixels())
- let bitmap = bar.renderedTree(background: bar.palette.tabBar)
+ let bitmap = bar.statusBar.renderedTree(background: bar.palette.workspace)
if stage == "egg_first_p0_0" || stage.hasSuffix("idle_0") {
var top = bitmap.pixelsHigh, bottom = -1
for y in 0..<bitmap.pixelsHigh {
@@ -683,7 +788,7 @@ private extension SwarmTabStrip {
var state: [String: Any] = ["enabled": true, "activeId": "pet-11",
"tabs": (0..<12).map { ["id": "pet-\($0)", "name": "Pet \($0)", "label": "\($0 + 1):code"] },
"focusedContext": ["text": "Codex M2:project (main)", "canSelectModel": true],
- "focusedModel": ["text": "gpt-5", "paneId": 3, "agentId": "a1"],
+ "subscriptionUsage": ["text": "gpt-5", "paneId": 3, "agentId": "a1"],
"pullRequest": ["text": "PR #298 · Merged", "url": "https://github.com/acme/repo/pull/298"],
"daemon": daemon]
update(state)
@@ -706,41 +811,35 @@ private extension SwarmTabStrip {
setFrameSize(NSSize(width: width, height: originalSize.height))
update(state)
try checkTitlebar(daemonButton.glyph == glyph, "Every nest stage and drop 1 sprite is drawn as sent")
- try checkTitlebar(daemonButton.font == tabs[0].labelFont,
+ try checkTitlebar(daemonButton.font == contextButton.font,
"The daemon shares the workspace bar font at \(size)pt")
try checkTitlebar(daemonButton.frame.maxX <= bounds.width &&
- daemonButton.frame.minX == storeButton.frame.maxX &&
+ daemonButton.frame.maxX <= contextButton.frame.minX &&
contextButton.frame.maxX <= pullRequestButton.frame.minX &&
- contextButton.superview === statusBar && daemonButton.superview === self &&
+ contextButton.superview === statusBar && daemonButton.superview === statusBar &&
newButton.frame.maxX < searchButton.frame.minX,
"Footer controls and top navigation do not overlap at \(width)px / \(size)pt")
try checkTitlebar(daemonButton.frame.width == 44,
- "Every growth stage keeps a 44pt top slot at \(size)pt")
+ "Every growth stage keeps a 44pt footer slot at \(size)pt")
try checkActiveVisible()
}
}
}
let tab = tabs[0]
- try checkTitlebar(storeButton.frame.maxX == daemonButton.frame.minX &&
- daemonButton.frame.midY == bounds.midY &&
- daemonButton.frame.maxX == bounds.width - ceil(workspaceBarTextWidth("m", font: daemonButton.font!)),
- "The daemon is last after Store, centered in the top bar with its outer gutter")
- let footerFrames = [contextButton.frame, pullRequestButton.frame, focusedModelButton.frame,
- shareButton.frame, voiceLabel.frame]
- updateDaemon([:])
- try checkTitlebar(footerFrames == [contextButton.frame, pullRequestButton.frame, focusedModelButton.frame,
- shareButton.frame, voiceLabel.frame], "Showing or hiding the top creature cannot change footer geometry")
- updateDaemon(daemon)
+ try checkTitlebar(daemonButton.frame.maxX <= contextButton.frame.minX &&
+ daemonButton.frame.height == subscriptionUsageButton.frame.height &&
+ daemonButton.frame.midY == subscriptionUsageButton.frame.midY,
+ "The daemon precedes focused context and shares the controls' height and inner gutters")
scroll.contentView.scroll(to: .zero)
let scrollFrame = scroll.frame, visible = scroll.documentVisibleRect
let documentFrame = document.frame, daemonFrame = daemonButton.frame
let contextFrame = contextButton.frame, prFrame = pullRequestButton.frame
- let modelFrame = focusedModelButton.frame
+ let modelFrame = subscriptionUsageButton.frame
func unmoved() -> Bool {
tabs[0] === tab && scroll.frame == scrollFrame && scroll.documentVisibleRect == visible &&
document.frame == documentFrame && daemonButton.frame == daemonFrame &&
contextButton.frame == contextFrame && pullRequestButton.frame == prFrame &&
- focusedModelButton.frame == modelFrame
+ subscriptionUsageButton.frame == modelFrame
}
for glyph in eggs + sprites + ["\\[=|=]/", "|[=|=]|", "/[=|=]\\", "-[=|=]-", "[==] |"] {
daemon["glyph"] = glyph
@@ -805,12 +904,12 @@ private extension SwarmTabStrip {
voiceLabel.color == statusColor(0xffd7af5f, fallback: .clear) &&
voiceLabel.accessibilityLabel() == voiceLabel.text && voiceLabel.accessibilityRole() == .staticText,
"The daemon's line shows in the message colour")
- try checkTitlebar(contextButton.isHidden && pullRequestButton.isHidden && !focusedModelButton.isHidden,
- "Its line replaces the left context while the model stays available on the right")
+ try checkTitlebar(contextButton.isHidden && pullRequestButton.isHidden && !subscriptionUsageButton.isHidden,
+ "Its line replaces the right context while subscription usage stays available on the left")
try checkTitlebar(unmoved(), "Speaking moves no tab, status control or the slot")
- try checkTitlebar(voiceLabel.frame.maxX < focusedModelButton.frame.minX &&
- voiceLabel.frame.minX == ceil(("m" as NSString).size(withAttributes: [.font: daemonButton.font!]).width),
- "The line keeps the footer's context area while the daemon lives in the top bar")
+ try checkTitlebar(voiceLabel.frame.minX >= daemonButton.frame.maxX &&
+ voiceLabel.frame.maxX <= statusBar.bounds.width,
+ "The line spans the status area after the slot")
let voicePixels = voiceLabel.renderedPixels()
daemon["voice"] = String(repeating: "a very long line ", count: 40)
updateDaemon(daemon)
@@ -818,7 +917,7 @@ private extension SwarmTabStrip {
"A long line truncates in place")
state["daemon"] = daemon
update(state)
- try checkTitlebar(contextButton.isHidden && pullRequestButton.isHidden && !focusedModelButton.isHidden && !voiceLabel.isHidden,
+ try checkTitlebar(contextButton.isHidden && pullRequestButton.isHidden && !subscriptionUsageButton.isHidden && !voiceLabel.isHidden,
"A workspace update while it speaks keeps the message line")
try checkTitlebar(unmoved(), "A workspace update while it speaks lays out as if the status were shown")
// The pair brain's line, exactly as sent, keys first: each offered key in
@@ -894,7 +993,7 @@ private extension SwarmTabStrip {
daemon["voice"] = nil
updateDaemon(daemon)
try checkTitlebar(voiceLabel.isHidden && !contextButton.isHidden && !pullRequestButton.isHidden &&
- !focusedModelButton.isHidden && unmoved(),
+ !subscriptionUsageButton.isHidden && unmoved(),
"Silence restores the status exactly where it was")
// The ten cells as Flutter drew them and the grue's patch. No count labels.
daemon["glyph"] = "[o o]"
@@ -939,13 +1038,13 @@ private extension SwarmTabStrip {
updateDaemon(daemon)
state["daemon"] = daemon
state["pullRequest"] = nil
- state["focusedModel"] = nil
+ state["subscriptionUsage"] = nil
update(state)
daemon["voice"] = "pip: pong."
updateDaemon(daemon)
daemon["voice"] = ""
updateDaemon(daemon)
- try checkTitlebar(pullRequestButton.isHidden && focusedModelButton.isHidden && !contextButton.isHidden,
+ try checkTitlebar(pullRequestButton.isHidden && subscriptionUsageButton.isHidden && !contextButton.isHidden,
"Silence restores only what the status holds")
state["enabled"] = false
update(state)
@@ -1025,7 +1124,7 @@ private extension SwarmTabStrip {
try checkTitlebar(!shareButton.isHidden && shareButton.isEnabled &&
shareButton.frame.width == shareButton.preferredWidth &&
shareButton.frame.maxX <= bounds.width &&
- contextButton.frame.maxX < shareButton.frame.minX &&
+ shareButton.frame.maxX <= contextButton.frame.minX &&
shareButton.superview === statusBar,
"Share stays in the footer without overlapping context at width \(width)")
update(hidden)
@@ -1084,14 +1183,14 @@ private extension SwarmTabStrip {
"activeId": "font-tab", "enabled": true,
"barStyle": ["family": ".AppleSystemUIFontMonospaced", "size": 13.0,
"foreground": Int64(0xffd0d0d0), "selection": Int64(0xff444444)]])
- try checkTitlebar(tabs[0].labelFont == NSFont.monospacedSystemFont(ofSize: 13, weight: .regular),
- "Numbered tabs use 13 pt SF Mono regular")
- try checkTitlebar(tabs[0].drawnFont == tabs[1].drawnFont && contextButton.font == tabs[0].labelFont,
- "Active tabs, inactive tabs, and pane context share one font")
+ try checkTitlebar(tabs[0].labelFont == NSFont.systemFont(ofSize: 13, weight: .regular),
+ "Tabs use 13 pt regular system UI type")
+ try checkTitlebar(tabs[0].drawnFont == tabs[1].drawnFont && contextButton.font != tabs[0].labelFont,
+ "Tab navigation is independent of the chosen status-line font")
for control in [newButton, storeButton] {
- try checkTitlebar(control.font == contextButton.font && control.frame.midY == bounds.midY &&
+ try checkTitlebar(control.font == tabs[0].labelFont && control.frame.midY == bounds.midY &&
contextButton.frame.midY == statusBar.bounds.midY,
- "Top actions and footer context share a font and center within their own rows")
+ "Navigation uses system type and each control centers within its own row")
}
try checkTitlebar(tabs[0].frame.width == tabs[0].preferredWidth &&
tabs[1].frame.width == tabs[1].preferredWidth &&
@@ -1101,6 +1200,113 @@ private extension SwarmTabStrip {
}
+ func checkTabPresentationAndCapture() throws {
+ setFrameSize(NSSize(width: 900, height: 40))
+ let rows: [[String: Any]] = [
+ ["id": "new", "name": "New Tab", "label": "New Tab", "shortcutHint": "⌘1"],
+ ["id": "work", "name": "Desktop", "label": "Desktop", "shortcutHint": "⌘2",
+ "activity": ["mark": "⠋", "label": "Working", "working": true, "color": Int64(0xff64d2ff)]],
+ ["id": "custom", "name": "1: Release planning", "label": "1: Release planning", "shortcutHint": "⌃⌥⌘R"],
+ ["id": "unbound", "name": "Notes", "label": "Notes", "shortcutHint": NSNull()],
+ ]
+ update(["enabled": true, "activeId": "work", "tabs": rows])
+ try checkTitlebar(tabs.map(\.displayLabel) == ["New Tab", "Desktop", "1: Release planning", "Notes"],
+ "Clean labels preserve numeric-looking custom names and omit generated prefixes")
+ try checkTitlebar(tabs.map(\.shortcutHint) == ["⌘1", "⌘2", "⌃⌥⌘R", nil],
+ "Native tab hints preserve effective remaps and intentionally unbound shortcuts")
+ let initial = tabs.map(\.frame)
+ var statusChanged: [String: Any] = ["enabled": true, "activeId": "work", "tabs": rows,
+ "barStyle": ["family": "Menlo", "size": 28.0, "foreground": Int64(0xffdddddd)]]
+ update(statusChanged)
+ try checkTitlebar(tabs.map(\.frame) == initial && tabs.allSatisfy { $0.labelFont.pointSize == 13 },
+ "A large custom status font cannot resize system-font tab navigation")
+ statusChanged["barStyle"] = ["family": "Menlo", "size": 13.0, "foreground": Int64(0xffdddddd)]
+ let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],
+ timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!
+ for (name, values) in [
+ ("dark", ["workspace": Int64(0xff282828), "tabBar": Int64(0xff1c1c1c)]),
+ ("light", ["workspace": Int64(0xfff0f2f5), "tabBar": Int64(0xffe4e6e9)]),
+ ] {
+ statusChanged["palette"] = values
+ update(statusChanged)
+ let ink = tabs[0].foreground.usingColorSpace(.sRGB)!
+ try checkTitlebar(name == "light" ? ink.redComponent < 0.2 : ink.redComponent > 0.8,
+ "Tab labels remain readable on the UI surface with an independently chosen status foreground")
+ setShortcutHintsVisible(false)
+ try captureTabPresentation("native-tabs-\(name)-rest")
+ tabs[1].mouseEntered(with: hover)
+ try captureTabPresentation("native-tabs-\(name)-hover")
+ setShortcutHintsVisible(true)
+ try checkTitlebar(tabs.allSatisfy(\.showsShortcutHint) && tabs.map(\.frame) == initial,
+ "Holding Command reveals hints across the strip without moving tabs")
+ try captureTabPresentation("native-tabs-\(name)-command")
+ tabs[1].mouseExited(with: hover)
+ setShortcutHintsVisible(false)
+ }
+ update(["enabled": false, "activeId": "work", "tabs": rows])
+ setShortcutHintsVisible(true)
+ try checkTitlebar(tabs.allSatisfy { !$0.showsShortcutHint }, "Disabled native navigation never advertises active shortcuts")
+ setShortcutHintsVisible(false)
+ let crowdedNames = ["New Tab", "Desktop", "Docs", "Web", "Notes", "API", "Tests", "Release"]
+ let crowdedRows: [[String: Any]] = crowdedNames.enumerated().map { index, name in
+ ["id": "dense-\(index)", "name": name, "label": name, "shortcutHint": "⌘\(index + 1)",
+ "activity": ["mark": index == 1 ? "⠋" : "", "label": index == 1 ? "Working" : "Idle",
+ "color": Int64(0xff64d2ff)]]
+ }
+ setFrameSize(NSSize(width: 1440, height: 40))
+ for (name, values) in [
+ ("dark", ["workspace": Int64(0xff282828), "tabBar": Int64(0xff1c1c1c)]),
+ ("light", ["workspace": Int64(0xfff0f2f5), "tabBar": Int64(0xffe4e6e9)]),
+ ] {
+ update(["enabled": true, "activeId": "dense-1", "tabs": crowdedRows, "palette": values])
+ try captureTabPresentation("native-tabs-eight-\(name)-rest")
+ try checkTitlebar(tabs.last!.frame.maxX <= scroll.bounds.width,
+ "Eight ordinary tab names with inset close targets fit a 1440pt strip: \(tabs.last!.frame.maxX) in \(scroll.bounds.width)")
+ for tab in tabs {
+ try tab.checkCenteredLabel()
+ try tab.checkCompleteNameFits()
+ }
+ setShortcutHintsVisible(true)
+ try captureTabPresentation("native-tabs-eight-\(name)-command")
+ tabs[1].mouseEntered(with: hover)
+ try captureTabPresentation("native-tabs-eight-\(name)-command-hover")
+ tabs[1].mouseExited(with: hover)
+ setShortcutHintsVisible(false)
+ }
+ }
+
+ func captureTabPresentation(_ name: String) throws {
+ guard let directory = ProcessInfo.processInfo.environment["HARNESS_TAB_CAPTURE_DIR"] else { return }
+ let height = Int(bounds.height) + 40
+ let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(bounds.width), pixelsHigh: height,
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap)
+ palette.tabBar.setFill()
+ NSRect(x: 0, y: 0, width: bounds.width, height: CGFloat(height)).fill()
+ palette.workspace.setFill()
+ NSRect(x: 0, y: 0, width: bounds.width, height: 40).fill()
+ for tab in tabs {
+ NSGraphicsContext.saveGraphicsState()
+ let transform = NSAffineTransform()
+ transform.translateX(by: scroll.frame.minX + tab.frame.minX, yBy: 40)
+ transform.concat()
+ tab.drawWithHoverControl()
+ NSGraphicsContext.restoreGraphicsState()
+ }
+ NSGraphicsContext.saveGraphicsState()
+ let transform = NSAffineTransform()
+ transform.translateX(by: newButton.frame.minX, yBy: newButton.frame.minY + 40)
+ transform.concat()
+ newButton.draw(newButton.bounds)
+ NSGraphicsContext.restoreGraphicsState()
+ NSGraphicsContext.restoreGraphicsState()
+ let destination = URL(fileURLWithPath: directory)
+ try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
+ try bitmap.representation(using: .png, properties: [:])!.write(to: destination.appendingPathComponent(name + ".png"))
+ }
+
func checkStartupPalette(_ expected: SwarmNativePalette) throws {
try checkTitlebar(palette == expected, "Startup uses the saved workspace palette")
try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled,
@@ -1237,39 +1443,39 @@ private extension SwarmTabStrip {
}
try checkTitlebar(clickedFields.map { $0.0 } == ["machine", "project", "branch"] &&
clickedFields.allSatisfy { $0.1 == 7 }, "Each context action preserves field and pane identity")
- linked["focusedModel"] = ["text": "Fable", "paneId": 7, "agentId": "a0", "interactive": true,
- "detail": "Switch model · Subscription or local models",
- "segments": [["text": "Fable", "foreground": Int64(0xffdddddd)]]]
- var modelClicks: [(Int, String)] = []
- emit = { method, args in
- if method == "focusedModel", let args = args as? [String: Any],
- let pane = args["paneId"] as? Int, let agent = args["agentId"] as? String {
- modelClicks.append((pane, agent))
- }
+ linked["subscriptionUsage"] = ["text": "Claude 0% Codex 13%", "interactive": true,
+ "detail": "Remaining subscription usage",
+ "segments": [["text": "Claude ", "foreground": Int64(0xffdddddd)],
+ ["text": "0%", "foreground": Int64(0xffff6b6b)],
+ ["text": " Codex ", "foreground": Int64(0xffdddddd)],
+ ["text": "13%", "foreground": Int64(0xffffc857)]]]
+ var usageClicks = 0
+ emit = { method, _ in
+ if method == "subscriptions" { usageClicks += 1 }
}
update(linked)
- try checkTitlebar(!focusedModelButton.isHidden && focusedModelButton.isEnabled,
- "Focused model has its own enabled status control")
- try checkTitlebar(focusedModelButton.frame.minX > pullRequestButton.frame.maxX &&
- focusedModelButton.frame.height == contextButton.frame.height &&
- focusedModelButton.frame.maxX <= statusBar.bounds.width,
- "Model sits on the right of the footer opposite machine/repo/branch/PR")
- try checkTitlebar(focusedModelButton.toolTip == "Switch model · Subscription or local models",
- "Model hint explains switching without repeating the visible name")
- let modelResting = focusedModelButton.renderedPixels()
- focusedModelButton.mouseEntered(with: pointer)
- try checkTitlebar(focusedModelButton.renderedPixels() != modelResting &&
- focusedModelButton.renderedBitmap().colorAt(x: 1, y: 1)!.alphaComponent == 0,
- "Model uses bold hover feedback without a background well")
- focusedModelButton.mouseExited(with: pointer)
- focusedModelButton.performClick(nil)
- try checkTitlebar(modelClicks.count == 1 && modelClicks[0].0 == 7 && modelClicks[0].1 == "a0",
- "Model actions carry the focused pane and agent identity")
+ try checkTitlebar(!subscriptionUsageButton.isHidden && subscriptionUsageButton.isEnabled,
+ "Subscription usage has its own enabled status control")
+ try checkTitlebar(subscriptionUsageButton.frame.maxX < contextButton.frame.minX &&
+ subscriptionUsageButton.frame.height == contextButton.frame.height &&
+ subscriptionUsageButton.frame.maxX <= statusBar.bounds.width,
+ "Usage sits on the left opposite machine/repo/branch/PR")
+ try checkTitlebar(subscriptionUsageButton.toolTip == "Remaining subscription usage",
+ "Usage hint explains that percentages are remaining")
+ let usageResting = subscriptionUsageButton.renderedPixels()
+ subscriptionUsageButton.mouseEntered(with: pointer)
+ try checkTitlebar(subscriptionUsageButton.renderedPixels() != usageResting &&
+ subscriptionUsageButton.renderedBitmap().colorAt(x: 1, y: 1)!.alphaComponent == 0,
+ "Usage uses hover feedback without a background well")
+ subscriptionUsageButton.mouseExited(with: pointer)
+ subscriptionUsageButton.performClick(nil)
+ try checkTitlebar(usageClicks == 1,
+ "Usage opens subscriptions without a pane or retarget action")
linked["enabled"] = false
update(linked)
- focusedModelButton.performClick(nil)
- try checkTitlebar(!focusedModelButton.isEnabled && modelClicks.count == 1,
- "Disabled model controls cannot switch a harness")
+ subscriptionUsageButton.performClick(nil)
+ try checkTitlebar(!subscriptionUsageButton.isEnabled && usageClicks == 1,
+ "Disabled usage controls cannot dispatch")
linked["enabled"] = false
update(linked)
for control in contextButton.fieldButtons {
@@ -1285,23 +1491,48 @@ private extension SwarmTabStrip {
update(state(rows, active: "swarm-11"))
try checkTitlebar(pullRequestButton.actionURL == nil && pullRequestButton.accessibilityValue() as? String == "",
"Changing to a pane without a PR clears the old link and state")
+ var covered = state(rows, active: "swarm-11")
+ covered["footerCovered"] = true
+ update(covered)
+ try checkTitlebar(statusBar.isHidden,
+ "Flutter's modal backdrop covers the native footer too")
+ try checkTitlebar(accessibilityChildren()?.contains(where: { $0 as? NSView === statusBar }) == false,
+ "The covered footer is removed from the native accessibility tree")
+ covered["footerCovered"] = false
+ update(covered)
+ try checkTitlebar(!statusBar.isHidden,
+ "Closing the modal restores the native footer")
+ try checkTitlebar(accessibilityChildren()?.contains(where: { $0 as? NSView === statusBar }) == true,
+ "Closing the modal restores the footer's accessibility controls")
+ covered["footerPassive"] = true
+ covered["enabled"] = false
+ update(covered)
+ try checkTitlebar(!statusBar.isHidden,
+ "Status customization keeps the footer visible as a passive preview")
+ try checkTitlebar(accessibilityChildren()?.contains(where: { $0 as? NSView === statusBar }) == false,
+ "A passive footer is excluded from modal accessibility traversal")
+ try checkTitlebar(!subscriptionUsageButton.isEnabled && !pullRequestButton.isEnabled,
+ "Passive footer controls cannot activate underlying commands")
+ covered["footerPassive"] = false
+ covered["enabled"] = true
+ update(covered)
try checkTitlebar(contextButton.nextBackground == nil, "A missing PR clears the joined background")
try checkTitlebar(contextButton.fieldButtons.isEmpty, "Leaving a context clears its former link controls")
try tabs[0].checkDoubleClickIsolation()
- try checkTitlebar(tabs.count == 24 && newButton.isEnabled, "All overflow tabs and New Swarm remain available")
+ try checkTitlebar(tabs.count == 24 && newButton.isEnabled, "All overflow tabs and New Tab remain available")
try checkTitlebar(scroll.frame.maxX <= newButton.frame.minX &&
newButton.frame.maxX < searchButton.frame.minX, "Tabs precede the search, bell and Store controls")
- try checkTitlebar(tabs[0].frame.width < 120 && tabs[0].displayLabel == "1:code",
- "Overflow tabs keep a readable minimum width and their numbered names")
- try checkTitlebar(subviews.count == 6 && statusBar.subviews.count == 5 && pullRequestButton.isHidden && focusedModelButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,
+ try checkTitlebar(tabs[0].frame.width < 136 && tabs[0].displayLabel == "code",
+ "Overflow tabs keep readable names without persistent number prefixes")
+ try checkTitlebar(subviews.count == 5 && statusBar.subviews.count == 6 && pullRequestButton.isHidden && subscriptionUsageButton.isHidden && daemonButton.isHidden && voiceLabel.isHidden && shareButton.isHidden,
"Navigation lives in the titlebar and focused context lives in the footer")
let controls = [newButton]
- for (control, symbol) in zip(controls, ["+"]) {
- try checkTitlebar(control.image == nil && control.title == symbol && !control.isBordered,
- "Management controls are plain terminal text without a resting button well")
- try checkTitlebar(control.frame.height >= 28 && control.frame.width > workspaceBarTextWidth(symbol, font: barFont),
- "The new-tab control keeps the shared click height and padding around its text")
- try checkTitlebar(control.accessibilityLabel() == "New Swarm" && control.toolTip?.contains("New Swarm") == true,
+ for control in controls {
+ try checkTitlebar(control.image != nil && control.title.isEmpty && !control.isBordered,
+ "Management controls use the regular outline family without a resting button well")
+ try checkTitlebar(control.frame.height >= 28 && control.frame.width > HarnessControlSymbols.size,
+ "The new-tab control keeps the shared click height and padding around its icon")
+ try checkTitlebar(control.accessibilityLabel() == "New Tab" && control.toolTip?.contains("New Tab") == true,
"Every symbol explains its action through a tooltip and accessible name")
let resting = control.renderedPixels()
let event = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],
@@ -1352,10 +1583,10 @@ private extension SwarmTabStrip {
try checkTitlebar(accessibleTabs.map(\.swarmId) == tabs.map(\.swarmId), "Accessible order follows visual order")
try checkActiveVisible()
update(state([["id": "swarm-0", "name": "Custom name", "label": "1:blender"]], active: "swarm-0"))
- try checkTitlebar(tabs[0] === original && original.displayLabel == "1:blender",
+ try checkTitlebar(tabs[0] === original && original.displayLabel == "blender",
"Type changes update the existing tab without renaming its saved workspace")
try original.checkAccessibility(expectedName: "Custom name", active: true)
- try checkTitlebar(newButton.toolTip == "New Swarm ⌘T", "New Swarm retains its keyboard hint")
+ try checkTitlebar(newButton.toolTip == "New Tab ⌘T", "New Tab retains its keyboard hint")
events.removeAll()
contextButton.performClick(nil)
newButton.performClick(nil)
@@ -1383,7 +1614,11 @@ private extension SwarmTabStrip {
update(["enabled": true, "activeId": "keyboard-23",
"tabs": (0..<24).map { ["id": "keyboard-\($0)", "name": "Keyboard \($0)"] }])
let tab = tabs[0]
+ let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],
+ timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!
+ tab.mouseEntered(with: hover)
let buttons = tab.accessibilityChildren()!.compactMap { $0 as? NSButton }
+ try checkTitlebar(buttons.count == 2, "Hover exposes selection and close to native accessibility")
for button in buttons {
try checkTitlebar(window.makeFirstResponder(button), "An enabled tab action accepts keyboard focus")
try tab.checkCenteredLabel()
@@ -1402,6 +1637,7 @@ private extension SwarmTabStrip {
try tab.checkCenteredLabel()
try checkTitlebar(messenger.calls.count == before + 1, "Each native tab activation sends one action")
}
+ tab.mouseExited(with: hover)
tab.attention = true
try checkTitlebar(buttons[0].accessibilityHelp()?.contains("Needs your input") == true,
"The attention dot has an accessible description")
@@ -1419,13 +1655,13 @@ private extension SwarmTabStrip {
stale.clickBothActions()
try checkTitlebar(messenger.calls.count == beforeStale, "A removed tab's retained controls cannot dispatch actions")
let unfocusedNew = newButton.renderedPixels()
- try checkTitlebar(window.makeFirstResponder(newButton), "New swarm accepts keyboard focus")
+ try checkTitlebar(window.makeFirstResponder(newButton), "New Tab accepts keyboard focus")
try checkTitlebar(newButton.hasKeyboardFocus && newButton.renderedPixels() != unfocusedNew,
"Keyboard focus gives the new-tab symbol the same bold emphasis as hover")
newButton.performClick(nil)
messenger.finishNextReply()
try checkTitlebar(window.firstResponder === window.contentInput && messenger.calls.last?.method == "new",
- "New swarm returns keyboard ownership to the workspace")
+ "New Tab returns keyboard ownership to the workspace")
updateDaemon(["visible": true, "glyph": "\\_O_/"])
try checkTitlebar(window.makeFirstResponder(daemonButton), "The daemon accepts keyboard focus")
daemonButton.performClick(nil)
@@ -1434,8 +1670,6 @@ private extension SwarmTabStrip {
messenger.finishNextReply()
try checkTitlebar(window.firstResponder === window.contentInput && messenger.calls.last?.method == "daemon",
"The daemon panel receives the next keystroke")
- let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],
- timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!
let beforeLook = messenger.calls.count, pendingReplies = messenger.replies.count
daemonButton.mouseEntered(with: hover)
daemonButton.mouseExited(with: hover)
@@ -1530,7 +1764,7 @@ private extension SwarmTabStrip {
"The native fixture can write its isolated drag pasteboard")
info.draggingLocation = document.convert(NSPoint(x: tabs[2].frame.midX + 1, y: 20), to: nil)
try checkTitlebar(draggingEntered(info) == .move && draggingUpdated(info) == .move,
- "An owned tab can move within the visible tab area")
+ "An owned tab can move within the visible tab area: \(scroll.frame), \(scroll.documentVisibleRect), \(info.draggingLocation)")
try checkTitlebar(performDragOperation(info) && moves.last?["index"] as? Int == 2,
"Moving right accounts for removing the source tab first")
moves.removeAll()
@@ -1546,7 +1780,7 @@ private extension SwarmTabStrip {
try checkTitlebar(moves.isEmpty, "Rejected drag emits no reorder")
}
info.draggingLocation = convert(NSPoint(x: newButton.frame.midX, y: 20), to: nil)
- try rejected("New Swarm is not a tab drop target")
+ try rejected("New Tab is not a tab drop target")
info.draggingLocation = document.convert(NSPoint(x: tabs[0].frame.midX, y: 20), to: nil)
info.draggingSource = SwarmTabButton(id: "drag-3")
try rejected("A foreign tab with a matching ID cannot reorder this strip")
@@ -1669,10 +1903,10 @@ private extension SwarmTitlebar {
"The menu yields the remapped search shortcut to Flutter")
try checkTitlebar(!main.performKeyEquivalent(with: open), "Menu equivalents defer before input dispatch")
setKeymap(defaults)
- try checkTitlebar(strip.newButton.toolTip == "New Swarm ⌘T", "Keymap reload restores the current New Swarm hint")
- try checkTitlebar(strip.newButton.accessibilityLabel() == "New Swarm", "The plus announces New Swarm")
+ try checkTitlebar(strip.newButton.toolTip == "New Tab ⌘T", "Keymap reload restores the current New Tab hint")
+ try checkTitlebar(strip.newButton.accessibilityLabel() == "New Tab", "The plus announces New Tab")
try checkTitlebar(main.defersToInput(event("n", 45, .command)) && main.defersToInput(event("t", 17, .command)),
- "Command-N and Command-T reach creation and New Swarm")
+ "Command-N and Command-T reach creation and New Tab")
try checkTitlebar(main.defersToInput(event("p", 35, .command)), "Command-P reaches Harnesses")
try checkTitlebar(main.defersToInput(event("p", 35, [.command, .shift])), "Command-Shift-P reaches commands")
try checkTitlebar(main.defersToInput(event("o", 31, .command)), "Command-O reaches the project picker")
@@ -1867,19 +2101,19 @@ private extension SwarmTitlebar {
}
try checkTitlebar(agent.items.filter { !$0.isSeparatorItem }.allSatisfy { $0.image != nil && $0.toolTip == nil },
"Every File action has a native icon and no hover hint")
- try checkTitlebar(agent.items.contains { $0.title == "Rename Swarm" && $0.representedObject as? String == "renameActive" }, "Rename Swarm preserves its command")
+ try checkTitlebar(agent.items.contains { $0.title == "Rename Tab" && $0.representedObject as? String == "renameActive" }, "Rename Tab preserves its command")
let movePane = agent.items.first(where: { $0.representedObject as? String == "movePaneToTab" })!
- try checkTitlebar(movePane.title == "Move Pane to Swarm" && movePane.keyEquivalent == "m" && movePane.keyEquivalentModifierMask == [.command, .shift],
- "Move Pane to Swarm advertises Command-Shift-M")
+ try checkTitlebar(movePane.title == "Move Pane to Tab" && movePane.keyEquivalent == "m" && movePane.keyEquivalentModifierMask == [.command, .shift],
+ "Move Pane to Tab advertises Command-Shift-M")
actionsEnabled = true
canFind = false
- try checkTitlebar(!validateMenuItem(movePane), "Move Pane to Swarm needs a focused pane")
+ try checkTitlebar(!validateMenuItem(movePane), "Move Pane to Tab needs a focused pane")
canFind = true
- try checkTitlebar(validateMenuItem(movePane), "Move Pane to Swarm is available with a focused pane")
- try checkTitlebar(agent.items.contains { $0.title == "Close Swarm" && $0.representedObject as? String == "closeActive" }, "Close Swarm preserves its command")
+ try checkTitlebar(validateMenuItem(movePane), "Move Pane to Tab is available with a focused pane")
+ try checkTitlebar(agent.items.contains { $0.title == "Close Tab" && $0.representedObject as? String == "closeActive" }, "Close Tab preserves its command")
let closeTabShortcut = agent.items.first { $0.representedObject as? String == "closeActive" }!
let closePaneShortcut = agent.items.first { $0.representedObject as? String == "closePane" }!
- try checkTitlebar(closeTabShortcut.keyEquivalent == "w" && closeTabShortcut.keyEquivalentModifierMask == [.command], "Close Swarm defaults to Command-W")
+ try checkTitlebar(closeTabShortcut.keyEquivalent == "w" && closeTabShortcut.keyEquivalentModifierMask == [.command], "Close Tab defaults to Command-W")
try checkTitlebar(closePaneShortcut.keyEquivalent == "w" && closePaneShortcut.keyEquivalentModifierMask == [.command, .shift], "Close Pane defaults to Command-Shift-W")
let commands = edit.submenu!.items.first(where: { $0.representedObject as? String == "commands" })!
try checkTitlebar(commands.keyEquivalent == "p" && commands.keyEquivalentModifierMask == [.command, .shift], "Command search keeps its native menu owner")
@@ -1887,7 +2121,7 @@ private extension SwarmTitlebar {
try checkTitlebar(harnesses.keyEquivalent == "p" && harnesses.keyEquivalentModifierMask == [.command],
"Command-P keeps harness search; commands use Command-Shift-P")
try checkTitlebar(edit.submenu!.items.allSatisfy { $0.representedObject as? String != "jump" }, "Edit has no Navigate action")
- try checkTitlebar(agent.items.contains { $0.title == "New Swarm" && $0.keyEquivalent == "t" && $0.representedObject as? String == "new" }, "New Swarm opens the chooser with Command-T")
+ try checkTitlebar(agent.items.contains { $0.title == "New Tab" && $0.keyEquivalent == "t" && $0.representedObject as? String == "new" }, "New Tab opens the chooser with Command-T")
let reopen = historyMenu.items.first(where: { $0.representedObject as? String == "reopen" })!
actionsEnabled = true
canReopen = false
@@ -1896,11 +2130,11 @@ private extension SwarmTitlebar {
try checkTitlebar(validateMenuItem(reopen), "Closed-Swarm recovery becomes available")
let closePane = agent.items.first(where: { $0.representedObject as? String == "closePane" })!
canClosePane = false
- try checkTitlebar(!validateMenuItem(closePane), "Remove Agent is disabled in New swarm")
+ try checkTitlebar(!validateMenuItem(closePane), "Remove Agent is disabled in New Tab")
canClosePane = true
try checkTitlebar(validateMenuItem(closePane), "Remove Agent is enabled for a focused pane")
let create = agent.items.first(where: { $0.representedObject as? String == "new" })!
- try checkTitlebar(validateMenuItem(create), "Native New Swarm remains available without the retired tab capacity")
+ try checkTitlebar(validateMenuItem(create), "Native New Tab remains available without the retired tab capacity")
let machineRows: [[String: Any]] = [
["id": "office", "name": "iMac – Office", "status": "Online", "presence": "Online", "local": true, "agentCount": 2,
"agents": [["id": "one", "title": "App work", "engine": "codex", "canOpen": true],
@@ -1926,7 +2160,7 @@ private extension SwarmTitlebar {
}
recentRows.append(["id": "swarm:recent", "title": "Recent Swarm", "swarm": true])
let closedRows: [[String: Any]] = (0..<14).map {
- ["id": "closed-\($0)", "title": "Closed Swarm \($0)", "detail": "3 agents", "swarm": true, "canReopen": true]
+ ["id": "closed-\($0)", "title": "Closed Tab \($0)", "detail": "3 agents", "swarm": true, "canReopen": true]
}
updateHistory(recentRows, closed: closedRows)
menuWillOpen(historyMenu)
@@ -2208,6 +2442,8 @@ do {
try strip.checkShareAction()
try strip.checkNotifications()
try strip.checkActivityMarks()
+ try SwarmTabButton(id: "close-shortcuts").checkHoverCloseAndShortcutHints()
+ try strip.checkTabPresentationAndCapture()
try SwarmTabButton(id: "hover-fixture").checkHoverStyleAndTooltips()
try strip.checkDaemon()
try strip.checkDaemonOff()