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 New and Open Harness pickers with terminal typography (#282)

Dee0c177a852a39
diff --git a/.github/assets/pickers/new-harness.png b/.github/assets/pickers/new-harness.png
new file mode 100644
index 000000000..4aaabee1d
Binary files /dev/null and b/.github/assets/pickers/new-harness.png differ
diff --git a/.github/assets/pickers/open-harness.png b/.github/assets/pickers/open-harness.png
new file mode 100644
index 000000000..2c0e3167f
Binary files /dev/null and b/.github/assets/pickers/open-harness.png differ
diff --git a/desktop/design/bios-setup-screen-handoff.md b/desktop/design/bios-setup-screen-handoff.md
new file mode 100644
index 000000000..b13b6a227
--- /dev/null
+++ b/desktop/design/bios-setup-screen-handoff.md
@@ -0,0 +1,294 @@
+# New Harness setup and minimal Open Harness picker — handoff
+
+Branch: `feat/centered-new-harness-palette`. Updated 2026-09-23.
+
+## Latest review direction
+
+The user reviewed the first BIOS version of ⌘O and explicitly asked to remove
+`Harness:` labels, brackets and all arrow instructions, pointing to fzf in Vim:
+"clean, minimal but functional. less is better". **This supersedes the BIOS
+presentation requirements for Open Harness below.** The first simplification
+was too sparse; the user then requested machine, repository, branch and last
+activity, and asked that New Harness look different from session names.
+
+The final ⌘O list has a plain title and subdued highlight, a small engine mark,
+a machine/repository/branch line, and elapsed activity at the right.
+New Harness is a plus-marked action separated from sessions by a rule.
+The next review removed the match count entirely and asked for typography
+and spacing identical to the terminal. Titles, metadata, activity, input and
+preview now use the renderer's selected face, size and line height, with no
+inherited UI tracking. Secondary details and their glyphs are muted gray,
+without the repository/branch accent colors. The preview stays available.
+The subsequent review found the rows too crowded. Sessions now have 12 px
+above and below their two text lines and a 4 px title/context gap, with wider
+horizontal insets. The preview uses 24 px margins and section separation;
+terminal font metrics remain unchanged.
+The latest review asked why the visible ages were out of order. ⌘O now sorts
+by the displayed last-activity timestamp, newest first, rather than by opening
+history. Filtering retains that order, and catalog updates retain the selected
+session. Unknown timestamps follow dated sessions; visit history only breaks
+ties. Search remains at the top.
+
+The user approved ⌘O's UI/UX and asked to carry its typography, spacing and
+colors to ⌘N. Creation shares its terminal font metrics, muted labels,
+generous padding and subdued selection. The subsequent review asked for
+less unused space: ⌘N now has its own 960 × 480 frame, growing by up to 25%
+with larger terminal text and clamping to the window. Fields and choices
+use a 55:45 split while retaining their row spacing. Field values have no
+brackets or punctuation; the start action has a plus mark and accent.
+The arrow legend and More options / F2 footer are gone, including the
+hard-coded F2 shortcut. The existing remappable Cmd+. advanced-form action
+remains available. Wide windows keep fields and choices side by side;
+narrow windows give the active list full width with a back action. Search
+stays above its scrolling choices. Field/value clicks work alongside the
+existing keyboard contract.
+The next refinement makes project, machine, branch and approval choices a
+single line. Machines show their names; only the local machine has a muted **This machine**
+note. Folder paths and branch metadata remain searchable without being
+printed below every choice. Profile appears only for the selected agent when
+it uses Codex profiles; merely browsing other agents does not move the fields.
+Field navigation skips the hidden Profile row in both directions.
+
+The latest review adds icons to Clone Repository, Open Folder, and New Project.
+Open Folder leads to the short Folder path prompt with a Browse Folder action.
+GitHub URL and Project name prompts are short too. Pasting works with Cmd-V or
+Ctrl-V, and accepted paths, URLs, and names return to Project. Delayed clipboard
+replies cannot overwrite a different field or newly typed input. Backspace
+removes a complete Unicode character. The idle right pane has no highlight;
+the active list keeps its keyboard highlight. The cursor sits beside its hint
+without an extra space. Pending Git discovery does not flash a false non-Git
+message. Unavailable choices explain why they cannot be used.
+This supersedes the historical BIOS presentation described below.
+
+## Latest verification and native review
+
+See [picker-verification.md](picker-verification.md) for scenario coverage,
+measured line coverage, native observations, artifacts and remaining limits.
+The user has requested PR creation and merge after verification.
+
+Integrated current main `306cbfdd` and checked the resulting branch:
+
+- Full desktop suite: **3,116 passed, 12 skipped, 17 failed**. All 17 failures
+ reproduce on main (48 passing cases in those same six files); no loader
+ failures or additional failed test names.
+- Affected randomized runs: **260 passed** at each of seeds 924 and 925,
+ **51 Cmd-P checks passed** at seed 926, **284 passed** at seed 927, and
+ **295 passed** after final integration at seed 928.
+- **Nine native macOS fixtures passed** after integration, using an isolated
+ test bundle with fake transports. Models now opens its overview without
+ launching the pending product, matching current main.
+- Full analysis matches main's 15 existing findings. Final fixture analysis
+ reports no issues; changed Dart files are formatted.
+- The optional render walkthrough passed and generated 133 synthetic images.
+- New Harness form coverage is **97.6%**; controller coverage is **93.7%**.
+ This is not 100% coverage or a zero-bug guarantee.
+- On-demand CLI CI failures also reproduce on main; this branch has no CLI or
+ workflow changes. Details and run links are in the verification record.
+- Normal macOS build 9 succeeded (`harness-picker-review-build-9.log`).
+
+The repeat audit added 37 regressions covering composition, native command
+routing, folder-browser failures, first-key editing, delayed clipboard replies,
+Git/install failure and retry, duplicate creation, disposal, command handoff
+and unmatched command searches. Cmd-O branch widths use measured content,
+including inherited text styles, so a branch uses the available row space.
+
+Computer use confirmed the field/action alignment, scrolling, single-line
+choices, each agent's approval options, conditional Profile, machine labels,
+Worktree activation, project prompt acceptance, and Cmd-P execution and
+cancellation. An approved real plain Terminal was started in `/private/tmp`,
+verified with `pwd`, then exited. Physical Cmd-V and IME delivery remain
+unverified by the automation; native context-menu paste worked. Live credential
+profile actions were blocked by review and are covered only by fake fixtures.
+
+The latest quit/restart was blocked by approval review because an active
+conversation had unconfirmed saved state. The existing review process remains
+open, and build 9 is ready for its next restart. Native fixtures instead ran
+as Harness Picker Verification in an isolated copy; that process has exited.
+Earlier cleanup also closed an existing Office Untitled Tab. Its requested
+restoration remains incomplete after review blocked identifying/reopening the
+matching session; the verification record preserves the details.
+
+## Why this exists
+
+The team said the bottom command dock was "too hard to use": every answer was
+a trip into a sub-list and back. The replacement is a **BIOS setup utility** —
+one screen holding every answer, changed where it stands, keyboard only.
+
+That reference was chosen deliberately and researched. What separates a BIOS
+screen from an ncurses dialog is that **the screen is the chrome**: values sit
+bracketed at a fixed column, the selection is inverse video rather than a
+marker glyph, the key legend never moves, and nothing is a button. `dialog`,
+`whiptail` and `menuconfig` read as TUI rather than BIOS precisely because
+they are a centred rounded box with a drop shadow and `<Select> <Exit>`.
+
+Three earlier designs were rejected, and the reasons still apply:
+
+- **A unified fuzzy list** where Return means "start" on one row and "set" on
+ another. Same key, two verbs, one surface. This is Spotlight behaviour, not
+ fzf behaviour.
+- **A shell-style command line** (`claude ~/code/foo -b main -w`). It looks
+ like a shell, so it inherits a contract it cannot honour — people reach for
+ `Ctrl-R`, `!$`, globs, history. k9s users filed exactly that request against
+ its `:` prompt. Positional grammar also cannot work here: branch candidates
+ depend on which project is selected, so `-b main` cannot be typed before the
+ project resolves.
+- **Phoenix's `-`/`+` for changing values.** Folder and branch names are full
+ of hyphens; a screen that swallows one to nudge a value is broken for the
+ thing people type most. `PgUp`/`PgDn` keep the convention instead.
+
+## The key model (do not quietly change this)
+
+| Key | On the items | With the list live |
+| --- | --- | --- |
+| `↑↓` | move between rows | move within the list |
+| `←→` | change the focused value in place | — |
+| `↵` | **Pick from List** — hand the arrows to the right column | take the value |
+| `Esc` | close | back to the items |
+| `Tab` | walk the rows | walk the list |
+| typing | fuzzy search the focused row | narrow further |
+
+Two rules hold it together:
+
+1. **Only `New Harness` starts an agent.** Return on a value row never
+ launches. This was an explicit request after a stray Return started work.
+2. **The selection bar marks which column has the keys.** The 12% white fill is
+ where the arrows are. The idle right pane has no fill; the left field stays
+ faintly marked while its list is active. The idle column's text greys out too. A test
+ counts the active bars and asserts there is never more than one.
+
+`Tab` is handled explicitly because unhandled it runs Flutter's focus
+traversal, which moves focus *out* of the form and leaves it deaf to every
+later key. That looked like a freeze and took a while to find.
+
+## Files
+
+| File | What it holds |
+| --- | --- |
+| `lib/widgets/new_harness_form.dart` | The whole ⌘N screen. New. |
+| `lib/state/new_harness.dart` | `stepValues()` and `applyOption()` added; rest untouched. |
+| `lib/screens/swarm_screen.dart` | Mounts the form; ⌘O overlay geometry and scrim. |
+| `lib/widgets/swarm_switcher.dart` | ⌘O results/preview split. |
+| `lib/widgets/box_chrome.dart` | Shared UI styles stay fixed; terminal surfaces opt into `terminalTextStyle`. |
+| `test/new_harness_form_test.dart` | 32 tests, all key paths. New. |
+
+### The one controller subtlety
+
+`stepValues()` returns a field's values in a **stable** order. The displayed
+list re-ranks the chosen row to the front, so stepping through *that* by index
+walks in circles — right always took the second row, left always wrapped to
+the last. The form captures a wheel on focus and steps through that instead.
+
+Synthetic rows are not all the same thing. `Clone`, `Open Folder`,
+`New Project` and `Change Machine` are **doors**: they open a prompt or the
+system chooser. `Create branch x` is synthetic too and is a genuine **answer**.
+`_doors` names them explicitly; inferring from `synthetic` broke branch
+creation.
+
+## Implemented in this pass
+
+- Deleted the unused `NewHarnessBox` and `CommandDock`; migrated launch tests
+ and benchmarks to the real setup form, explicit field selection and launch.
+- Connected advanced options, Store, profile linking and folder browsing to
+ the form. Fixed initial parent notification during build, prompt Escape,
+ focus return after browsing, busy/pending dismissal, and scrolling to the
+ selected field at large text sizes. Creation errors are visible live regions.
+- Added flat activity ordering for ⌘O, retaining command, group and split ordering.
+ The old handoff pointed at `rankSwarmLocations`, but the live ⌘O path uses
+ the placement/add catalog. `activityFirst` applies the ordering there;
+ the navigation-only path remains unchanged. Controller coverage verifies
+ activity order while filtering, discovery refreshes and live preview matches,
+ while ordinary search retains relevance ranking.
+- Simplified ⌘O after user review: no type labels, brackets or persistent key
+ legend. Titles have a compact identity line and elapsed activity; New Harness
+ is a distinct plus action. A block cursor and preview remain; the match
+ count was removed in the latest review.
+ Cached rows retain search emphasis and full accessible context. Tab stays
+ inside the list; narrow windows prioritize results over the preview.
+ Activity comes from the catalog agent's `lastActivityAt` and refreshes once
+ a minute while the picker is open; missing timestamps remain blank.
+- Restored fixed shared dialog typography. New Harness, Open Harness and its
+ preview opt into the terminal font/size. The remote folder browser opened
+ from New Harness opts in too; the OS folder chooser remains native.
+
+## Verification and review
+
+A normal macOS debug app is built from `lib/main.dart` at
+`desktop/build/macos/Build/Products/Debug/Harness.app`. The user authorized
+restarting the live app with this branch build; existing tabs were restored.
+At that earlier review stage, commit/push/merge had not yet been requested;
+the latest instruction authorizes the PR and merge after verification.
+
+Production Dart analysis reports no issues. The final full run reported 21
+failures: 17 pre-existing CLI daemon/sign-out/expiry/environment failures,
+plus four picker assertions affected by the last visual simplification.
+Those four were corrected and their files rerun successfully: 12 layout,
+keyboard and capture checks, and 5 catalog/metadata checks passed. The full
+run is `/private/tmp/harness-minimal-verification.jsonl`; follow-up results
+are `/private/tmp/harness-minimal-layout-tests.jsonl` and
+`/private/tmp/harness-minimal-catalog-tests.jsonl`. The earlier targeted run
+also passed all 114 keyboard, rendering, accessibility and MRU tests before
+the final visual simplification. No failing tests were disabled.
+
+The subsequent context/activity refinement is verified separately in
+`/private/tmp/harness-context-tests.jsonl` and
+`/private/tmp/harness-context-action-test.jsonl`. Real-font snapshots cover
+normal and narrow windows and enlarged text in `/private/tmp/harness-context-review/`.
+The latest typography/count/color refinement passed all 79 affected checks in
+`/private/tmp/harness-neutral-tests.jsonl` and has captures in
+`/private/tmp/harness-neutral-review/`. Build evidence is
+`/private/tmp/harness-neutral-build.log`; production analysis is
+`/private/tmp/harness-neutral-analysis.txt`.
+The spacing follow-up passed all 47 affected checks in
+`/private/tmp/harness-spacing-tests.jsonl`, with normal/narrow/enlarged-font
+captures in `/private/tmp/harness-spacing-review/`. Its debug build succeeded
+(`/private/tmp/harness-spacing-build.log`), and production analysis reports
+no issues (`/private/tmp/harness-spacing-analysis.txt`). `git diff --check` passes.
+The activity-order correction passed all 54 affected checks in
+`/private/tmp/harness-activity-sort-tests.jsonl`. The review build and production
+analysis succeeded (`/private/tmp/harness-activity-sort-build.log` and
+`/private/tmp/harness-activity-sort-analysis.txt`).
+Native review confirms ascending displayed ages (0m, 0m, 0m, 9m, 1h, 1h, 2h…).
+That activity-sort review ran alongside `/Applications/Harness.app`; automatic
+approval review blocked quitting that separate installed instance, so it was
+left running.
+
+The ⌘N styling pass is captured at normal/narrow widths and 2× text in
+`/private/tmp/harness-new-style-review/`. The affected form, keyboard, layout,
+accessibility, project/profile and placement checks passed after updating
+assertions for plain values and explicit choice focus. Results are in
+`/private/tmp/harness-new-style-tests.jsonl` (initial run),
+`/private/tmp/harness-new-style-followup-tests.jsonl` (remaining files), and
+`/private/tmp/harness-new-style-project-tests.jsonl` (final project assertions).
+Production analysis has no issues (`/private/tmp/harness-new-style-analysis.txt`)
+and the debug build succeeded (`/private/tmp/harness-new-style-build.log`).
+The branch review app has been restarted with the matching ⌘N presentation.
+
+The compact ⌘N follow-up passed 47 affected checks in
+`/private/tmp/harness-compact-new-tests.jsonl`, with normal/narrow/enlarged-font
+captures in `/private/tmp/harness-compact-new-review/`. Production analysis
+has no issues (`/private/tmp/harness-compact-new-analysis.txt`) and the debug
+build succeeded (`/private/tmp/harness-compact-new-build.log`). After the user
+confirmed the restart, the branch app was reopened with the rebuilt executable.
+Native review confirms the compact frame, preserved field spacing and removed
+More options / F2 footer. The app is left on ⌘N for review.
+
+The single-line choices and conditional Profile pass completed 66 affected
+checks (`/private/tmp/harness-single-line-tests.jsonl`), including changing
+agents without moving fields while browsing and skipping the hidden Profile
+row during keyboard navigation. Normal and enlarged-text captures are in
+`/private/tmp/harness-single-line-review/`. Production analysis has no issues
+(`/private/tmp/harness-single-line-analysis.txt`) and the macOS debug build
+succeeded (`/private/tmp/harness-single-line-build.log`).
+The branch app was restarted under the user's review-build authorization.
+Native review confirms single-line projects, machine names with inline Remote
+notes, and no Profile row for Claude Code. ⌘N is open on Machine for review.
+
+## Two process notes that cost real time
+
+- **Write the widget test before rebuilding.** Every bug the user found by
+ hand — arrows not stepping, search looking broken, the list not moving — was
+ reachable from a test that sends real key events. The first such test caught
+ six failures in one run, three of which had already been reported.
+- **Scripted `str.replace` edits must assert their anchor.** Three silently
+ matched nothing after an earlier edit moved the text, so changes were
+ reported that never reached the file, and the wrong code got debugged.
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
index eaeda38fe..6d2f2f9e9 100644
--- a/desktop/design/new-harness-entry-rules.md
+++ b/desktop/design/new-harness-entry-rules.md
@@ -5,11 +5,22 @@ 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 launch form starts with Agent, Machine, and Project, followed by Start
-Harness, which is selected initially. There is no heading, Task row, or Open In
-row. Cmd-O and Cmd-P pickers also omit their heading and result-count row.
+The launch form starts on Project, followed by Agent, Machine, Branch,
+Worktree, Approvals, and Profile when the chosen agent uses Codex profiles.
+The separate **+ New Harness** action submits the draft. There is no heading,
+Task row, or Open In row. Cmd-O and Cmd-P also omit headings and counts.
Tasks carried from search or Store examples remain part of the draft.
+Values and search use the terminal's selected font, size, and line height.
+The right pane previews choices without a selection highlight while the left
+has focus. Return or typing activates the list; accepting a value returns to
+its field. The three project actions have icons. Clone, folder path, and new
+project prompts return to Project after acceptance; only New Harness starts.
+Project, machine, branch, and approval options occupy one line. Only the local
+machine has a note, **This machine**. Approvals come from the chosen agent's
+supported modes, and Profile disappears for agents that do not use it.
+Narrow windows show the active list full-width with a back action.
+
| Entry | Initial values | Destination after a successful start |
| --- | --- | --- |
| Cmd-T, then Cmd-N | Previous pane's agent, machine, and project | The blank tab opened by Cmd-T |
@@ -32,9 +43,9 @@ while a pending start needs confirmation.
## Git projects
-Git projects show Branch, then Worktree. Worktree defaults to `[x]` for a
-repository with a commit; Enter, Space, or a click toggles `[x]` and `[ ]`.
-Folders without Git show neither row. Discovery runs on the selected machine
+Git projects enable Branch and Worktree. Worktree defaults to **Yes** for a
+repository with a commit; Enter, Left/Right, Page Up/Down, or a click toggles
+**Yes** and **No**. Folders without Git keep both rows visible but 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.
@@ -55,12 +66,12 @@ projects.
**Branch** starts on the default branch with Worktree on, and on the folder's
own branch with it off. It 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
-button reads **Start Harness** on every New Harness, whatever the rows say.
+New Harness is new work, and another agent's branch is one pick away. The start
+action reads **New Harness**, whatever the rows say.
The picker names local branches; a remote branch is listed only when no local
branch has its name.
-With `[x]`, **Branch** is what the new worktree works from. At Start a new
+With **Yes**, **Branch** is what the new worktree works from. At Start a new
branch starts from the newer of that branch and its upstream, fetched for at
most ten seconds: `main` behind `origin/main` starts from `origin/main`, and
`main` with commits of its own starts from `main`, so nothing is lost; offline,
@@ -85,7 +96,7 @@ 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 `[ ]`, **Branch** is the branch the folder itself is on; only local
+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.
Typing a name no branch has offers **Create branch**:
a new branch from the folder's branch, keeping its uncommitted changes.
@@ -94,8 +105,8 @@ also needs nothing uncommitted. No changes are forced,
stashed, or discarded. A selected subfolder follows into a new worktree only if
it exists in that commit.
-The picker tags branches `default`, `current`, `worktree` and `remote`, and
-leaves out branches Harness made (marked `branch.<name>.harness`, or named
+The picker displays branch names on one line; metadata such as `default`,
+`current`, `worktree`, and `remote` remains searchable. It leaves out branches Harness made (marked `branch.<name>.harness`, or named
`harness/…` by older builds) whose worktree is gone. The daemon removes a
worktree it finds in `~/harnesses/worktrees` only when no live or stopped
harness uses it, nothing is uncommitted, and it has been idle for a week; the
@@ -129,7 +140,7 @@ 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 Project
-prefills and selects the name so it can be replaced.
+opens the name prompt; accepting a name returns to the Project field.
Each machine retains its own project choice. A folder on one machine is never
silently reused on another. Generated folders use exclusive reservation and
@@ -139,7 +150,7 @@ never silently renamed, and existing files are never overwritten.
## Regression coverage
- `test/new_harness_git_test.dart`, `test/git_worktree_test.dart`, and
- `test/git_worktree_failures_test.dart`: Git defaults, hidden non-Git rows,
+ `test/git_worktree_failures_test.dart`: Git defaults, disabled non-Git rows,
keyboard/click toggles, branch search, branch resolution, stale
replies, retries, actual Git worktrees and branch safety, fetching,
tracking, `.worktreeinclude`, process deadlines, and bounded output.
diff --git a/desktop/design/picker-verification.md b/desktop/design/picker-verification.md
new file mode 100644
index 000000000..24c54daec
--- /dev/null
+++ b/desktop/design/picker-verification.md
@@ -0,0 +1,275 @@
+# Picker verification — 2026-09-23
+
+Scope: Cmd-N New Harness and Cmd-O Open Harness redesign, plus Cmd-P command
+execution, editing and focus regressions.
+This is a scenario audit, not a claim that every possible runtime state has
+been tested. Line coverage is measured separately from native UI testing.
+
+## Automated checks
+
+- Final full desktop suite: **3,116 passed, 12 skipped, 17 failed**. The failures
+ match the pre-existing CLI/auth/setup baseline; no new picker failure.
+- Cmd-P-focused shuffled run (seed 926): **51 passed**, including eight added
+ tests for pointer/keyboard handoff, unmatched queries, and native composition.
+- Final integrated affected run (seed 928): **295 passed**, including machine
+ entry into New Harness. Seed 927 passed 284. Earlier repeat
+ runs (seeds 924 and 925) each passed **260**.
+ Covers
+ creation, draft ownership, Git/worktrees, accessibility, keyboard routing,
+ mouse selection, both picker layouts, typography, previews and activity order.
+- Native macOS integration fixtures: **9 passed**. First workspace, Cmd-T/Cmd-O
+ creation, Store Open/Try, Models cancelling pending creation without a launch,
+ edited defaults and destination, and
+ immediate terminal input after creation, search/shared-view ownership, and
+ Machines pending edits. Fake transport and in-memory state;
+ these tests do not launch real agents or establish physical AppKit/IME input.
+- Full analysis matches current main exactly: **15 existing findings**, with no
+ new errors or warnings. Final changed integration/rendering fixtures report
+ no issues; all 53 changed Dart files passed the format check.
+- Normal macOS review build 9 succeeded after integration. The running review
+ app was left open because approval review blocked quitting an unconfirmed
+ conversation. Native tests ran in a separate test-only bundle, which exited.
+- The opt-in screenshot walkthrough passed and rendered **133 fixture images**.
+ It now uses the current fields, opens the advanced form for task editing,
+ follows immediate choice acceptance, and uses main's current Models and
+ Machines surfaces, including the Connection settings submenu.
+ PR images are synthetic: [New Harness](../../.github/assets/pickers/new-harness.png)
+ and [Open Harness](../../.github/assets/pickers/open-harness.png).
+- The branch-width follow-up passes **39 affected rendering/customization
+ checks**. Its new regression failed before the fix and verifies that long
+ branch text is actually painted in full across prompt styles and text scales.
+
+Coverage from the full suite (`flutter test --coverage`):
+
+| File | Covered lines | Coverage |
+| --- | ---: | ---: |
+| terminal/terminal_text.dart | 15 / 15 | 100.0% |
+| widgets/new_harness_form.dart | 526 / 539 | 97.6% |
+| state/new_harness.dart | 1,347 / 1,438 | 93.7% |
+| state/swarm_navigation.dart | 715 / 755 | 94.7% |
+| state/swarm_search.dart | 391 / 406 | 96.3% |
+| widgets/swarm_search_input.dart | 79 / 80 | 98.8% |
+| widgets/swarm_switcher.dart | 573 / 663 | 86.4% |
+| widgets/swarm_search_preview.dart | 284 / 303 | 93.7% |
+| widgets/prompt_context.dart | 170 / 172 | 98.8% |
+
+The form now uses a real Flutter text field, including its selection, composing
+region and block cursor. Native computer use checks the rendered input in
+addition to widget tests. This is not 100% line coverage or proof of every
+possible runtime state; manual unfocused-editing fallbacks and legacy paths
+remain uncovered. Clipboard error, empty, delayed, selection-change and
+dismissal cases are covered. Native IME behavior and physical keyboard paste are not
+established by injected Flutter key tests.
+
+## Repeat audit
+
+The additional 29 regressions found and verified fixes for:
+
+- **Input-method composition:** Cmd-N previously accepted an agent on Return,
+ erased the candidate on Escape, or moved the list on Tab/arrows while the
+ input method was still composing. Candidate keys now remain with the input
+ method. Tests cover Return, numpad Return, Escape, Tab, arrows and page keys,
+ followed by an actual commit and acceptance.
+- **Native command dispatch:** native workspace/menu and legacy search commands
+ could bypass the composition check. Both picker regions now protect the
+ active candidate before dispatch. This is tested through the native method
+ channel, separately from normal Flutter keyboard routing.
+- **Folder-browser exceptions:** a failed chooser callback escaped as an
+ unhandled asynchronous error. The prompt now displays a retryable error and
+ retains input focus. Late failure after dismissal has no stale effect.
+
+The repeat also covers the first printable key, clicking the query editor,
+delayed paste after a selection change, chooser cancellation/retry, Git
+discovery failure/retry, remote-branch refusal with Worktree off, disposal
+during Git discovery or installation, missing Store-harness installation,
+installation failure/retry, unavailable catalogs, duplicate starts and
+oversized carried tasks. Installation and creation tests use fake transports;
+they do not install products on the user's machines.
+
+The two pre-integration shuffled runs pass the same 260 tests, and the final
+integrated run passes 295. The final full run has exactly the
+same 17 failed test names as `harness-audit-final-tests-v3.jsonl`, with no added
+or resolved failures. Native creation fixtures also passed again. This is
+measured regression evidence, not a zero-bug or 100%-coverage claim.
+
+## Scenario coverage
+
+| Area | Scenarios |
+| --- | --- |
+| Project | History, full-path search despite single-line names, project action icons, new name with spaces, invalid/empty name, existing path with spaces, clone URL paste, validation, machine-specific history, browser callbacks, acceptance returns to fields |
+| Machine | Local-only note, remote names, offline/unlinked refusal, machine switch, stale replies, project isolation |
+| Agent | Every engine's controller options, saved draft, Store product entry, profile visibility changes, agent preview does not mutate launch defaults |
+| Approvals | Every Codex, Claude, Cursor and OpenCode value, launch payload contract with CLI, unsupported agents, no implicit launch |
+| Branch/worktree | Git/non-Git/pending/error states, existing/new/remote branches, worktree on/off, linked worktree, branch sanitization, no destructive switching, retries |
+| Profile | Default/named selection, link/refresh callbacks, machine ownership, unsupported agents, hidden row navigation |
+| Input | Arrows, Return/numpad Return, Tab/Shift-Tab, Page Up/Down, Escape levels, key repeats, Unicode backspace, Cmd-V/Ctrl-V, empty/error/delayed clipboard, focus retention |
+| Layout | Wide/narrow, enlarged text, selected item visibility, active/inactive columns, terminal font metrics, muted metadata, no result count or key legend |
+| Start | Explicit action only, failure/retry, lost-reply receipt, pending/busy state, exact destination, no duplicate agent, immediate terminal focus |
+| Commands | Pointer/Return execution, no-match navigation and recovery, availability rechecked before execution, Cmd-N handoff, terminal focus restored on cancellation, native command composition guards |
+| Open Harness | Activity order, unknown/tied timestamps, filtered and live results, preserved selection, preview, small windows, keyboard and pointer opening |
+
+## Baseline failures
+
+All 17 failures reproduce on current main (`306cbfdd`) in a detached checkout.
+The six affected files produce **48 passed and the same 17 failures**; no
+credentials or production connections are used. Artifact:
+`harness-picker-main-final-baseline.jsonl`. The failures are:
+
+- `workspace_account_lifecycle_test.dart`: 8 (sign-out, expiry, stale layout
+ replies and sign-in during cleanup).
+- `signout_recovery_test.dart`: 2.
+- `workspace_expiry_screen_test.dart`: 4 (both themes and text scales).
+- `local_cli_discovery_test.dart`: 1 (signed-out daemon supervision).
+- `environment_setup_screen_test.dart`: 1 (install/retry to sign-in).
+- `environment_recheck_timer_test.dart`: 1.
+
+They concern the local daemon/auth setup path, not picker selection or creation.
+The whole suite therefore remains red; this audit does not hide or relabel them.
+
+The on-demand Linux CLI CI is also red on main. The branch run
+[35938893689](https://github.com/autonomous-ai/openharness/actions/runs/35938893689)
+had five failures, all reproduced by the independent current-main run
+[35939411173](https://github.com/autonomous-ai/openharness/actions/runs/35939411173),
+which had seven failures (4,245 passed, 63 skipped). They concern shell job-control
+output, a file-watcher event, Grid process timeout, and Grid CLI discovery.
+The picker branch changes no CLI or workflow files relative to this main commit.
+
+## Reproduction
+
+From `desktop`, using Flutter 3.47.2:
+
+```sh
+flutter test --no-pub --coverage
+FLUTTER_TEST=1 flutter test -d macos --no-pub \
+ integration_test/native_workspace_e2e_test.dart \
+ --name 'native (first workspace|created|Store|Models|creation)'
+flutter build macos --debug --no-pub --target lib/main.dart
+```
+
+Detailed run artifacts are under `/private/tmp/harness-audit-*` on the review
+machine. Always rebuild `main.dart` after the native fixture replaces the app.
+
+Final integrated artifacts (main `306cbfdd`):
+
+- `harness-picker-final-full-fixed.jsonl`: 3,116 passed, 12 skipped, 17 failures;
+ no loader errors. Failure names match the main checkout exactly.
+- `harness-picker-final-shuffled.jsonl`: 295 passing affected tests, seed 928.
+- `harness-picker-cmdp-final.jsonl`: 51 passing command/focus checks, seed 926.
+- `harness-picker-main-final-baseline.jsonl`: 48 passed and the same 17 failures
+ on main in a detached worktree.
+- `harness-picker-native-final.jsonl`: nine native checks in the copied
+ Harness Picker Verification app with a unique bundle ID and fake transports.
+- `harness-picker-final-analysis.txt` and
+ `harness-picker-main-final-analysis.txt`: the same 15 findings on both trees.
+- `harness-picker-final-fixture-analysis.txt`: no issues in the last two edits.
+- `harness-picker-pr-render-final-4.jsonl`: passing optional render walkthrough;
+ 133 images in `/private/tmp/harness-picker-pr-images-final-4`.
+- `harness-picker-review-build-9.log`: successful normal macOS build.
+
+Earlier repeat artifacts:
+
+- `harness-picker-full-repeat.jsonl`: latest full suite and coverage.
+- `harness-picker-repeat-seed924.jsonl` and
+ `harness-picker-repeat-seed925.jsonl`: 260 passing checks per shuffle.
+- `harness-picker-native-repeat.jsonl`: seven passing native creation fixtures.
+- `harness-picker-repeat-analysis.txt`: no analyzer findings in the six latest
+ changed source/test files.
+- `harness-picker-edge-before.jsonl` and
+ `harness-picker-edge-before-browser.jsonl`: failing regressions before the
+ composition and browser-recovery fixes; `harness-picker-edge-fixed.jsonl`
+ records the 44 passing form scenarios afterward.
+- `harness-picker-review-build-7.log`: latest normal macOS build, restarted
+ for hands-on review. The project draft was restored after testing.
+- `harness-audit-final-tests-v3.jsonl`: final whole suite and coverage, including
+ the branch-width follow-up, before the repeat audit.
+- `harness-audit-final-random-tests.jsonl`: the randomized affected repeat.
+- `harness-audit-native-final-tests.jsonl`: seven native creation fixtures.
+- `harness-audit-analysis-final.txt`: no analysis issues in the changed input,
+ controller, scenario tests and rendering tests.
+- `harness-audit-review-build-5.log`: normal review app, including both prompt
+ alignments and the final native-test findings.
+- `harness-branch-space-tests-3.jsonl`: 39 passing branch-width, picker, header
+ and customization checks; `harness-branch-space-analysis.txt`: no issues.
+- `harness-audit-review-build-6.log`: normal app with the branch-width fix.
+ Native review confirms full visible branch names, including
+ `feat/centered-new-harness-palette`, in the available row space.
+
+## Computer-use review
+
+Used the actual macOS app through computer use, including pointer/accessible
+clicks, typing, scrolling, native menus and the native folder chooser.
+
+| Area | Observed result |
+| --- | --- |
+| Project actions | Clone, Open Folder and New Project have distinct icons. Typed paths, a public Git URL and a name with spaces return to the left fields after acceptance. No real repository was cloned. |
+| Clipboard | Native context-menu Copy/Paste round-tripped a public Git URL, and Return accepted it. Computer-use Cmd-V/Cmd-A attempts timed out or did not deliver the expected shortcut; physical keyboard paste remains unverified. |
+| Folder browser | Cancel returns to a usable path prompt; Open accepts the chosen existing folder and returns to the form. |
+| Project scrolling | Scrolled beyond the previous nine-option limit into later history entries. |
+| Machines | Clicked all seven available machine choices. Linked machines select; unlinked machines explain why. Only the local machine says This machine. After the final fix, selecting M2 clears the prior unlinked-machine warning. |
+| Agents | Clicked all 14 core coding-agent choices, plus Terminal. Confirmed conditional approvals/profile rows. Store products are covered as option types, not a claim that every product was installed or launched. |
+| Approvals | Clicked all five Claude, four Codex, two Cursor and two OpenCode draft choices. Retested that switching agents, or merely previewing another agent, does not expose another agent's approval values. Restored ordinary defaults; no agent was launched with altered permissions. |
+| Branch/worktree | Searched and selected an existing worktree branch as a draft. Checked Worktree in both directions with pointer, Return and, after the fix, accessible clicks. No checkout was performed. |
+| Store | Browse more harnesses opens the Store. Closed only the temporary Store test tab afterward. Store Open/Try and creation payloads also pass the isolated native fixtures. |
+| Open Harness | Searched existing sessions, inspected previews and the activity order, and opened New Harness through the plus action. Prompt, plus and engine marks share a column. |
+| Alignment | Both prompt layouts were inspected in the native review app. Widget tests measure Cmd-N text baselines and action-icon centers at normal and enlarged text, and Cmd-O prompt/leading-icon centers. |
+| Branch width | The rebuilt Cmd-O shows the complete branch names in the user's reported rows. All prompt styles and normal/enlarged text also pass measured overflow assertions. |
+| Real creation | With explicit permission, started a plain Terminal on M2 in `/private/tmp`, ran `pwd` and observed `/private/tmp`, then ran `exit`. No AI agent was started. The temporary test tab is gone. |
+
+The build-7 repeat confirmed typed `/private/tmp`, `hello moon`, and a public
+Git URL are accepted and leave the right-hand editor. Codex/Claude switching
+again exposed the correct four/five approval choices and conditional Profile;
+Worktree toggled both ways, M2 alone carried This machine, and Cmd-O filtering,
+keyboard selection, activity ordering and full branch names remained correct.
+The original project, Codex agent and Worktree setting were restored. No new
+agent or project directory was created in this repeat.
+
+Computer-use `paste` still timed out, and injected Cmd-A/Cmd-V did not reliably
+produce the intended selection/paste. Native editing-menu attempts did not
+resolve that ambiguity. Physical shortcuts therefore remain unverified; the
+earlier successful context-menu round trip is not evidence that those shortcuts
+work. The normal review app remains available for that check.
+
+Cmd-P computer-use review also confirmed filtering to Keyboard shortcuts,
+Return execution, Escape cancellation, recent-command ordering, and clicking
+New Harness to hand focus into the setup form. Cancelling that form left the
+existing workspace intact. The focused automated suite additionally verifies
+no stray terminal input, no implicit launch, and native composition guards.
+
+Findings fixed during the audit:
+
+- Hand-drawn input was replaced with a real text field so native text editing
+ and clipboard actions can work through the platform input connection.
+- Accepted project prompts now close the right-hand editor instead of leaving
+ the user stuck there; cancellation restores input focus.
+- The choices list can scroll beyond its first nine entries.
+- Agent preview state no longer supplies approval options for a different
+ selected agent.
+- A valid machine selection clears a prior unavailable-machine error.
+- Accessible field activation now has the same behavior as a pointer click,
+ including toggling Worktree.
+- Cmd-N search text shares the prompt baseline; both pickers align the prompt
+ with the action and session icons beneath it.
+- Metadata uses measured content widths instead of equal shares. A long branch
+ can use the room left by a short machine or repository name. Measurement also
+ includes inherited text styling; genuinely crowded lines still shorten the
+ repository before the branch. Tests inspect painted text overflow, not merely
+ whether the full string exists in a Text widget.
+
+Limitations and cleanup:
+
+- The latest review app restart was blocked by automatic approval review
+ because an active conversation had unconfirmed saved state. The app remains
+ open; build 9 is ready for the next restart. The separately identified native
+ fixture app exited after its successful tests.
+- Live profile selection/refresh/link actions were blocked by automatic
+ approval review because they may access credential files. Isolated profile
+ tests cover the callbacks, selection and machine ownership. No claim of a
+ completed live profile-link test is made.
+- An existing iMac–Office Untitled Tab with a Grid icon also disappeared during
+ test cleanup. The user authorized restoration. Automatic approval review
+ initially blocked it; the subsequent app restart cleared the in-memory
+ closed-tab history. The matching Office Grid session remains in Open Harness,
+ but review rejected opening it because it could not establish that it was the
+ same tab. Restoration remains incomplete; no existing session was deliberately
+ stopped or deleted. The temporary picker QA app was successfully quit after
+ explicit permission, and the final branch build is running.
diff --git a/desktop/integration_test/native_workspace_e2e_test.dart b/desktop/integration_test/native_workspace_e2e_test.dart
index c87f86d12..a8352780b 100644
--- a/desktop/integration_test/native_workspace_e2e_test.dart
+++ b/desktop/integration_test/native_workspace_e2e_test.dart
@@ -31,6 +31,7 @@ import 'package:harness/usage/ledger/usage_ledger_controller.dart';
import 'package:harness/usage/ledger/usage_report.dart';
import 'package:harness/usage/ledger/opencode_ledger_scanner.dart';
import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/models/models_panel.dart';
import 'package:harness/settings/settings_nav.dart';
import 'package:harness/settings/settings_screen.dart';
import 'package:harness/settings/settings_section.dart';
@@ -47,7 +48,7 @@ import 'package:harness/widgets/workspace_welcome.dart';
import 'package:harness/shortcuts/keyboard_practice.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/environment_setup_screen.dart';
import 'package:harness/widgets/terminal_find_bar.dart';
import 'package:harness/ws/ws_conn.dart';
@@ -913,19 +914,19 @@ void main() {
);
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 200));
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(find.byType(WorkspaceWelcome), findsOneWidget);
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
await tester.pump(const Duration(milliseconds: 200));
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.engine, 'codex');
expect(box.projectLabel, startsWith('~/harnesses/codex-'));
final proposedFolder = box.projectFolderRequest!.folderName;
expect(connection.creates, isEmpty);
expect(find.byType(WorkspaceWelcome), findsOneWidget);
- await key(tester, LogicalKeyboardKey.enter);
+ await startHarness(tester);
await tester.pump(const Duration(milliseconds: 200));
expect(connection.creates, hasLength(1));
expect(
@@ -933,7 +934,7 @@ void main() {
'/fixture/harnesses/$proposedFolder',
);
expect(connection.creates.single['engine'], 'codex');
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
await key(tester, LogicalKeyboardKey.keyS, cmd: true);
await tester.pump(const Duration(milliseconds: 100));
expect(app.activeSwarm.isStore, isTrue);
@@ -1344,18 +1345,18 @@ void main() {
expect(find.text('Check retargeted keyboard input'), findsWidgets);
expect(find.text('New Pane'), findsNothing);
await key(tester, LogicalKeyboardKey.enter);
- expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(
tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
.task,
'Check retargeted keyboard input',
);
- await key(tester, LogicalKeyboardKey.enter);
+ await startHarness(tester);
await tester.pump(const Duration(milliseconds: 200));
await tester.pump();
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.activeSwarm, same(destination));
expect(
app.activeSwarm,
@@ -1391,7 +1392,9 @@ void main() {
('Models', null),
]) {
testWidgets(
- 'native ${entry == 'Models' ? 'Models' : 'Store $entry'} switches products and focuses the started pane',
+ entry == 'Models'
+ ? 'native Models replaces pending creation with its overview without launching'
+ : 'native Store $entry switches products and focuses the started pane',
(tester) async {
const products = [
{
@@ -1433,8 +1436,9 @@ void main() {
),
);
await tester.pump(const Duration(milliseconds: 200));
- NewHarnessController prompt() =>
- tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;
+ NewHarnessController prompt() => tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
Future<void> open(String id, {String? task}) async {
await openStoreAgent(
tester.element(find.byType(StoreTab)),
@@ -1462,27 +1466,36 @@ void main() {
);
await tester.pump(const Duration(milliseconds: 200));
await reply.future;
- } else {
- await open('autonomous/blender', task: task);
+ expect(find.byType(NewHarnessForm), findsNothing);
+ expect(find.byType(ModelsPanel), findsOneWidget);
+ expect(connection.creates, isEmpty);
+ expect(app.activeSwarm, same(store));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.byType(ModelsPanel), findsNothing);
+ expect(connection.creates, isEmpty);
+ expect(originalInput, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ return;
}
- final product = entry == 'Models'
- ? AppNotifier.gridHarness
- : 'autonomous/blender';
- final prefix = entry == 'Models' ? 'grid' : 'blender';
+ await open('autonomous/blender', task: task);
+ const product = 'autonomous/blender';
+ const prefix = 'blender';
expect(prompt().engine, product);
expect(prompt().projectLabel, startsWith('~/harnesses/$prefix-'));
expect(prompt().task, task ?? '');
final folder = prompt().projectFolderRequest!.folderName;
expect(app.activeSwarm, same(store));
expect(connection.creates, isEmpty);
- await key(tester, LogicalKeyboardKey.enter);
+ await startHarness(tester);
await tester.pump(const Duration(milliseconds: 200));
await tester.pump();
expect(connection.creates, hasLength(1));
expect(connection.creates.single['dsh'], product);
expect(connection.creates.single['prompt'], task);
expect(connection.creates.single['cwd'], '/fixture/harnesses/$folder');
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.activeSwarm.isStore, isFalse);
final session = app.focusedPane!.session!;
final view = tester.widget<TerminalView>(
@@ -1531,84 +1544,73 @@ void main() {
);
await tester.pump(const Duration(milliseconds: 200));
- final line = find.byKey(const ValueKey('new-harness-input'));
NewHarnessController prompt() =>
- tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;
+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller;
+ const task = 'Refine terminal workspace; keep running sessions attached';
await key(tester, LogicalKeyboardKey.keyO, cmd: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ task,
+ );
await key(tester, LogicalKeyboardKey.enter);
await tester.pump(const Duration(milliseconds: 80));
expect(prompt().engine, 'codex');
expect(prompt().machineId, 'm');
expect(prompt().project.folder, '/work/openharness');
+ expect(prompt().task, task);
expect(app.swarms, [source]);
expect(app.activeSwarm, same(source));
- expect(prompt().field, NewHarnessField.launch);
- await key(tester, LogicalKeyboardKey.arrowDown);
- await key(tester, LogicalKeyboardKey.arrowDown);
- await key(tester, LogicalKeyboardKey.enter);
- expect(prompt().field, NewHarnessField.machine);
+ expect(prompt().field, NewHarnessField.projectMenu);
+
+ await openLaunchRow(tester, 'machine');
await key(tester, LogicalKeyboardKey.enter);
- expect(prompt().field, NewHarnessField.launch);
+ expect(prompt().machineId, 'm');
await openLaunchRow(tester, 'project');
- await tester.enterText(line, 'openharness');
+ await typeHarnessQuery(tester, 'openharness');
await key(tester, LogicalKeyboardKey.enter);
expect(prompt().project.folder, '/work/openharness');
- expect(prompt().field, NewHarnessField.launch);
- await openLegacyTaskEditor(tester);
- await tester.enterText(line, 'Refine terminal workspace');
- await key(tester, LogicalKeyboardKey.enter, alt: true);
- expect(
- tester.widget<TextField>(line).controller!.text,
- 'Refine terminal workspace\n',
- );
- const task = 'Refine terminal workspace\nKeep running sessions attached';
- await tester.enterText(line, task);
+
+ await openLaunchRow(tester, 'profile');
+ expect(prompt().field, NewHarnessField.profile);
await key(tester, LogicalKeyboardKey.escape);
await openLaunchRow(tester, 'agent');
- await tester.enterText(line, 'claude');
+ await typeHarnessQuery(tester, 'claude');
+ expect(prompt().engine, 'codex');
+ expect(
+ find.byKey(const ValueKey('new-harness-field-profile')),
+ findsOneWidget,
+ );
await key(tester, LogicalKeyboardKey.enter);
expect(prompt().engine, 'claude');
expect(prompt().task, task);
+ expect(
+ find.byKey(const ValueKey('new-harness-field-profile')),
+ findsNothing,
+ );
+
await openLaunchRow(tester, 'project');
- expect(prompt().field, NewHarnessField.projectMenu);
- await key(tester, LogicalKeyboardKey.arrowDown);
- await key(tester, LogicalKeyboardKey.arrowDown);
- await key(tester, LogicalKeyboardKey.enter);
- expect(prompt().field, NewHarnessField.project);
- expect(prompt().options.single.id, NewHarnessController.browseId);
- await key(tester, LogicalKeyboardKey.escape);
- await key(tester, LogicalKeyboardKey.enter);
- expect(prompt().field, NewHarnessField.launch);
- await openLaunchRow(tester, 'agent');
+ await typeHarnessQuery(tester, 'does-not-match-any-existing-project');
for (
var step = 0;
- prompt().selected?.id != 'codex' && step < 30;
+ prompt().selected?.id != NewHarnessController.existingProjectId &&
+ step < 8;
step++
) {
- await key(tester, LogicalKeyboardKey.arrowUp);
+ await key(tester, LogicalKeyboardKey.arrowDown);
}
- expect(prompt().selected?.id, 'codex');
- expect(prompt().engine, 'claude');
- await openAgentSetting(tester, 'codex', NewHarnessController.profileId);
- expect(prompt().field, NewHarnessField.profile);
- await key(tester, LogicalKeyboardKey.escape);
- await key(tester, LogicalKeyboardKey.escape);
- expect(prompt().engine, 'claude');
- await openLaunchRow(tester, 'agent');
- await openAgentSetting(
- tester,
- prompt().selected!.engine!,
- NewHarnessController.permissionsId,
- );
- expect(prompt().field, NewHarnessField.mode);
- await tester.enterText(line, 'Plan first');
+ expect(prompt().selected?.id, NewHarnessController.existingProjectId);
await key(tester, LogicalKeyboardKey.enter);
- expect(prompt().field, NewHarnessField.agent);
+ expect(prompt().field, NewHarnessField.project);
+ expect(prompt().options.single.id, NewHarnessController.browseId);
await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
+ expect(prompt().field, NewHarnessField.projectMenu);
+
+ await openLaunchRow(tester, 'approvals');
+ await typeHarnessQuery(tester, 'Plan first');
+ await key(tester, LogicalKeyboardKey.enter);
expect(prompt().mode, 'plan');
await key(tester, LogicalKeyboardKey.escape);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.swarms, [source]);
expect(
input,
@@ -1628,9 +1630,9 @@ void main() {
expect(prompt().mode, 'plan');
expect(prompt().task, task);
expect(prompt().project.folder, '/work/openharness');
- await key(tester, LogicalKeyboardKey.enter);
+ await startHarness(tester);
await tester.pump(const Duration(milliseconds: 200));
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.activeSwarm, same(source));
expect(source.panes.length, 2);
expect(source.panes.first, same(original));
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 16bbfccfe..e024fb212 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -1,3 +1,4 @@
+import 'dart:math' as math;
import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
@@ -33,6 +34,8 @@ import '../state/new_harness.dart';
import '../state/pane_arrangement.dart';
import '../terminal/terminal_viewport.dart';
import '../terminal/terminal_text.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
import '../usage/models_menu_controller.dart';
import '../state/swarm_catalog.dart';
import '../state/swarm_navigation.dart';
@@ -56,7 +59,7 @@ import '../widgets/fork_agent_dialog.dart';
import '../widgets/restart_agent_action.dart';
import '../widgets/new_agent_dialog.dart';
import '../widgets/box_chrome.dart';
-import '../widgets/new_harness_box.dart';
+import '../widgets/new_harness_form.dart';
import '../widgets/open_harness_intent.dart';
import '../widgets/pane_grid.dart';
import '../widgets/pane_minimize.dart';
@@ -1013,15 +1016,17 @@ class _SwarmScreenState extends State<SwarmScreen>
'restartAgent' => 'agent.restart',
_ => null,
};
- if (nativeCommand != null) {
+ if (nativeCommand != null || call.method == 'searchCommand') {
final focus = FocusManager.instance.primaryFocus?.context;
final region = focus == null ? null : KeymapRegion.of(focus);
+ // Native menu actions must leave an input-method candidate intact even
+ // when the focused picker delegates that command to the workspace.
+ if (region?.composing?.call() == true) return;
final action = region?.actions?[nativeCommand];
if (action != null) {
// Match keyboard dispatch: the focused picker owns its commands and
// closes its own results before opening creation. Bypassing it stacks
// another search or leaves the start-page dropdown under the dialog.
- if (region?.composing?.call() == true) return;
action();
if (call.method != 'keymapCommand') {
await WidgetsBinding.instance.endOfFrame;
@@ -1714,19 +1719,18 @@ class _SwarmScreenState extends State<SwarmScreen>
split: split,
placement: placement,
);
- final content = NewHarnessBox(
- docked: true,
+ final content = NewHarnessForm(
controller: box,
+ onCreated: () {
+ _closeNewHarness(restoreFocus: false, keepDraft: false);
+ unawaited(_focusCreatedPane());
+ },
onClose: () {
final target = box.swarmId ?? app.activeSwarmId;
_closeNewHarness();
app.cancelSwarmDraft(target);
},
- onCreated: () {
- _closeNewHarness(restoreFocus: false, keepDraft: false);
- unawaited(_focusCreatedPane());
- },
- onBrowse: () => unawaited(_browseForNewHarness(box)),
+ onBrowse: () => _browseForNewHarness(box),
onStore: _openStore,
onLinkProfile: () => unawaited(_linkProfileForNewHarness(box)),
onNeedsForm: () {
@@ -1757,6 +1761,7 @@ class _SwarmScreenState extends State<SwarmScreen>
listenable: box,
builder: (context, child) => LayoutBuilder(
builder: (context, constraints) {
+ final setupScale = terminalTextScaleOf(context).clamp(1.0, 1.25);
return Stack(
children: [
Positioned.fill(
@@ -1771,13 +1776,34 @@ class _SwarmScreenState extends State<SwarmScreen>
app.cancelSwarmDraft(target);
}
},
+ // The popup is the terminal's own colour, so the
+ // screen behind it is dimmed rather than competed
+ // with — that, and the light shadow, are what carry
+ // the separation a different fill used to.
+ child: ColoredBox(
+ color: Colors.black.withValues(alpha: .94),
+ ),
),
),
),
- CommandDock(
- topClearance: _native ? 0 : _tabBarHeight,
- expanded: box.field == NewHarnessField.projectMenu,
- child: content,
+ Positioned.fill(
+ top: _native ? 0 : _tabBarHeight,
+ child: Align(
+ alignment: const Alignment(0, -0.12),
+ // Sized for the setup fields rather than the session
+ // catalog, with some extra room for larger terminal text.
+ child: SizedBox(
+ width: math.min(
+ 960 * setupScale,
+ constraints.maxWidth - 48,
+ ),
+ height: math.min(
+ 480 * setupScale,
+ constraints.maxHeight - 88,
+ ),
+ child: content,
+ ),
+ ),
),
],
);
@@ -1824,6 +1850,7 @@ class _SwarmScreenState extends State<SwarmScreen>
notifier: app,
machineId: machineId,
initialPath: box.project.folder,
+ terminal: true,
);
if (mounted && identical(_newHarness, box) && box.machineId == machineId) {
if (path != null) box.setFolder(path);
@@ -2421,7 +2448,11 @@ class _SwarmScreenState extends State<SwarmScreen>
modes: _searchModes,
adding: adding,
offersCreate: adding,
- resultsFromBottom: true,
+ activityFirst: split == null && !query.startsWith('>'),
+ // The input leads now, so the results read downward from it. Left
+ // bottom-up, the list reversed itself and New Harness — first in the
+ // rows — landed visually last.
+ resultsFromBottom: false,
split: split,
placement:
placement ??
@@ -2565,95 +2596,149 @@ class _SwarmScreenState extends State<SwarmScreen>
// result rather than a cached, offscreen ListView row below the input.
Widget ordered(double order, Widget child) =>
FocusTraversalOrder(order: NumericFocusOrder(order), child: child);
- final panel = TerminalBox(
+ final panel = Material(
key: const ValueKey('swarm-search-results'),
- docked: true,
- child: FocusTraversalGroup(
- policy: OrderedTraversalPolicy(),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- 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),
- ],
- ),
- ),
- Flexible(
- child: ordered(
- 2,
- SwarmSearchResults(
+ elevation: 0,
+ color: terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ ).background,
+ surfaceTintColor: Colors.transparent,
+ child: DefaultTextStyle.merge(
+ style: terminalContentStyle(color: Colors.white),
+ 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,
- fitRows: true,
terminal: true,
- ),
- ),
- ),
- ordered(
- 1,
- Semantics(
- label: search.hint,
- child: ReadlineKeys(
- controller: _searchText,
- onChanged: search.setQuery,
- child: SwarmSearchInput(
- 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,
+ bios: true,
+ header: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (search.canGoBack || search.isGroupMode)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(18, 12, 18, 0),
+ child: Text(
+ search.title,
+ style: terminalContentStyle(color: kBoxFaint),
+ ),
+ ),
+ Semantics(
+ label: search.hint,
+ child: ReadlineKeys(
+ controller: _searchText,
+ onChanged: search.setQuery,
+ child: SwarmSearchInput(
+ inputKey: const ValueKey('swarm-search-input'),
+ controller: _searchText,
+ focusNode: _searchFocus,
+ search: search,
+ onClose: _dismissSearch,
+ onChanged: search.setQuery,
+ onOpen: _focusSearch,
+ height: 44 * terminalTextScaleOf(context),
+ terminal: true,
+ bios: true,
+ prompt: '>',
+ hintText: search.hint,
+ ),
+ ),
+ ),
+ ],
),
+ )
+ : Column(
+ children: [
+ 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(
+ 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,
+ ),
+ ),
+ ),
+ 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();
+ },
+ ),
+ ),
+ ],
),
- ),
- ),
- 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();
- },
- ),
- ),
- ],
),
),
);
@@ -2689,13 +2774,26 @@ class _SwarmScreenState extends State<SwarmScreen>
key: const ValueKey('swarm-search-dismiss'),
behavior: HitTestBehavior.opaque,
onTap: _dismissSearch,
+ child: ColoredBox(
+ color: Colors.black.withValues(alpha: .94),
+ ),
),
),
),
- CommandDock(
- expanded: true,
- topClearance: _native ? 0.0 : _tabBarHeight,
- child: contents,
+ 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.
+ child: SizedBox(
+ width: math.min(1480, constraints.maxWidth - 48),
+ height: math.min(760, constraints.maxHeight - 88),
+ child: contents,
+ ),
+ ),
),
],
);
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index e4c66fd2c..723c251c7 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -755,6 +755,7 @@ class NewHarnessController extends ChangeNotifier {
String get modeLabel =>
_modes.where((m) => m.id == mode).firstOrNull?.label ?? mode;
bool get riskyMode => _modes.any((m) => m.id == mode && m.risky);
+ bool get usesProfile => _base == 'codex';
bool get hasProfile => _baseOf(_settingsEngine) == 'codex';
bool get supportsProfiles =>
hasProfile && _machine?.engines['codex']?.supportsCodexHome == true;
@@ -798,6 +799,7 @@ class NewHarnessController extends ChangeNotifier {
_agentPreview = engine;
focusField(
setting == profileId ? NewHarnessField.profile : NewHarnessField.mode,
+ previewAgent: true,
);
}
@@ -913,9 +915,9 @@ class NewHarnessController extends ChangeNotifier {
NewHarnessField.agent => 'Choose an agent',
NewHarnessField.machine => 'Choose a machine',
NewHarnessField.branch => 'Search branches',
- NewHarnessField.project => 'Enter a folder path, or press Enter to browse',
- NewHarnessField.projectName => 'Type a project name',
- NewHarnessField.projectRepository => 'Paste a GitHub repository URL',
+ NewHarnessField.project => 'Folder path',
+ NewHarnessField.projectName => 'Project name',
+ NewHarnessField.projectRepository => 'GitHub URL',
NewHarnessField.mode => 'How much it may do without asking',
NewHarnessField.profile => 'Find a Codex profile',
};
@@ -925,8 +927,12 @@ class NewHarnessController extends ChangeNotifier {
({NewHarnessField field, String query, String? agentPreview}) _machineOrigin =
(field: NewHarnessField.launch, query: '', agentPreview: null);
- void focusField(NewHarnessField next) {
- if (locked || field == next || !_supportsField(next)) return;
+ void focusField(NewHarnessField next, {bool previewAgent = false}) {
+ if (locked) return;
+ // Form fields edit the saved agent. Only an explicit nested setting may
+ // use the agent currently being previewed in the choices list.
+ if (!previewAgent) _agentPreview = null;
+ if (field == next || !_supportsField(next)) return;
if (next == NewHarnessField.machine) {
_machineOrigin = (
field: field,
@@ -1049,6 +1055,44 @@ class NewHarnessController extends ChangeNotifier {
notifyListeners();
}
+ /// ← and → change the focused field's value where it stands, as a BIOS
+ /// settings screen does, rather than opening a list to choose from. Unlike
+ /// [accept] the line keeps its field, so the next arrow steps again, and
+ /// the rows the box adds for itself — Browse, New project, Permissions —
+ /// are skipped: they are doors, not values.
+ /// The values a field can be stepped through, in a stable order. The
+ /// displayed list is NOT that order: it re-ranks so the chosen row floats
+ /// to the front, which makes stepping by index walk in circles — right
+ /// always took the second row and left always wrapped to the last.
+ List<NewHarnessOption> stepValues() => [
+ for (final option in options)
+ if (!option.synthetic && option.enabled) option,
+ ];
+
+ /// Take [option] as this field's value without moving off the field.
+ /// Synthetic rows are allowed here even though [stepValues] leaves them
+ /// out: "Create branch x" is a real answer to the Branch row, it is only
+ /// not one the arrows should cycle onto.
+ void applyOption(NewHarnessOption option) {
+ if (locked || !option.enabled) return;
+ error = null;
+ _steered = true;
+ _apply(option);
+ _refresh();
+ }
+
+ /// Take what the field is highlighting as its value, where it stands.
+ /// Typing narrows a field and lands on a row; this is what makes that row
+ /// the answer, so the value on screen is always the one Return acts on.
+ void takeSelection() {
+ final option = selected;
+ if (locked || option == null || option.synthetic || !option.enabled) {
+ return;
+ }
+ _apply(option);
+ _refresh();
+ }
+
NewHarnessOption? get selected =>
cursor < 0 || cursor >= options.length ? null : options[cursor];
@@ -1109,7 +1153,7 @@ class NewHarnessController extends ChangeNotifier {
// For anyone who would rather point at a folder than type its path. It stays
// under whatever is typed: the way out must not vanish on the first key.
NewHarnessOption get _browse =>
- NewHarnessOption(id: browseId, synthetic: true, title: 'Open Folder');
+ NewHarnessOption(id: browseId, synthetic: true, title: 'Browse Folder');
NewHarnessOption get _changeMachine => NewHarnessOption(
id: changeMachineId,
@@ -1122,7 +1166,7 @@ class NewHarnessController extends ChangeNotifier {
const NewHarnessOption(
id: repositoryId,
synthetic: true,
- title: 'Clone GitHub Repository',
+ title: 'Clone Repository',
detail: 'Paste a GitHub repository URL',
),
const NewHarnessOption(
@@ -1145,11 +1189,11 @@ class NewHarnessController extends ChangeNotifier {
final option = row ?? selected;
if (locked || option?.id == storeId) return;
if (option?.id == permissionsId) {
- focusField(NewHarnessField.mode);
+ focusField(NewHarnessField.mode, previewAgent: true);
return;
}
if (option?.id == profileId) {
- focusField(NewHarnessField.profile);
+ focusField(NewHarnessField.profile, previewAgent: true);
return;
}
if (option?.id == refreshProfilesId) {
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 7325d41ed..3bbffef5f 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -248,6 +248,7 @@ class SwarmDestination {
this.detailBranchOffset,
this.terminalDetail,
this.promptContext,
+ this.lastActivityAt,
required this.swarmId,
required this.current,
this.machineId,
@@ -288,6 +289,7 @@ class SwarmDestination {
/// and machine before paths and branches, which are more likely to truncate.
final String? terminalDetail;
final PromptContext? promptContext;
+ final DateTime? lastActivityAt;
final String? swarmId, machineId, agentId, engine;
final String? closedId;
final String? commandId, shortcut;
@@ -674,6 +676,7 @@ class SwarmLocationCatalog {
agentId: pane.agentId,
previewKey: agent == null ? null : app.previewKey(pane.machineId, agent),
engine: engine,
+ lastActivityAt: agent?.lastActivityAt,
current: swarm.id == app.activeSwarmId && pane.id == app.focusedPaneId,
// The agent's own title first, ranked like the name: "board fab check"
// finds the agent whose work that is, not whichever recap mentions fab.
@@ -690,6 +693,34 @@ class SwarmLocationCatalog {
}
}
+/// Open Harness uses the same activity timestamp it shows beside each session.
+/// Undated rows come last; ties retain visit recency and search relevance.
+List<SwarmDestination> rankSwarmDestinationsByActivity(
+ List<SwarmDestination> all,
+ String query, {
+ List<String> recent = const [],
+ SessionPreviewStore? previews,
+}) {
+ final matches = rankSwarmDestinations(all, query, previews: previews);
+ final rank = {for (var i = 0; i < matches.length; i++) matches[i].id: i};
+ final visits = {for (var i = 0; i < recent.length; i++) recent[i]: i};
+ matches.sort((a, b) {
+ final aTime = a.lastActivityAt;
+ final bTime = b.lastActivityAt;
+ final activity = aTime == null
+ ? (bTime == null ? 0 : 1)
+ : bTime == null
+ ? -1
+ : bTime.compareTo(aTime);
+ if (activity != 0) return activity;
+ final visit = (visits[a.id] ?? recent.length).compareTo(
+ visits[b.id] ?? recent.length,
+ );
+ return visit != 0 ? visit : rank[a.id]!.compareTo(rank[b.id]!);
+ });
+ return matches;
+}
+
/// Each swarm is one selectable parent, followed by its matching agent views.
/// Keep the parent even when only an agent matches, so its destination is clear.
/// Order groups by their best match/previous place, and agents by match within it.
@@ -1212,6 +1243,7 @@ List<SwarmDestination> swarmDestinations(
agentId: agentId,
previewKey: row == null ? null : app.previewKey(machineId, row.$2),
engine: engine,
+ lastActivityAt: row?.$2.lastActivityAt,
current:
owner?.id == app.activeSwarmId && pane?.id == app.focusedPaneId,
// The agent's own title is ranked like its name (see titleFields):
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 44dfe6ca2..3455a817e 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -41,6 +41,7 @@ class SwarmSearchController extends ChangeNotifier {
this.modes,
this.adding = false,
this.navigating = false,
+ this.activityFirst = false,
this.commandsOnly = false,
this.offersCreate = false,
this.resultsFromBottom = false,
@@ -77,6 +78,10 @@ class SwarmSearchController extends ChangeNotifier {
final List<SwarmDestination> Function()? modes;
final bool adding;
final bool navigating;
+
+ /// Open Harness filters by latest activity; commands and splits keep relevance order.
+ final bool activityFirst;
+ bool get setupLayout => activityFirst && !isCommandMode && !isHelpMode;
final bool commandsOnly;
/// Whether the list ends in a row that makes a harness instead of finding
@@ -146,9 +151,7 @@ class SwarmSearchController extends ChangeNotifier {
rows.any((row) => !row.isCreate);
bool get hasPreview =>
- _previewVisible &&
- canPreview &&
- (!resultsFromBottom || selected?.isCreate != true);
+ _previewVisible && canPreview && selected?.isCreate != true;
void togglePreview() {
if (!supportsPreview) return;
@@ -402,8 +405,8 @@ class SwarmSearchController extends ChangeNotifier {
final previous = rows;
final previousSelection = selected?.id;
_filter(keepOrder: true);
- // Live text can add/remove a match, but never shuffle matching rows under
- // the keyboard or repaint the editor when the result set is unchanged.
+ // Live text can add/remove a match. Preserve selection and avoid repainting
+ // the editor when the result set is unchanged.
if (!listEquals(previous, rows) || previousSelection != selected?.id) {
notifyListeners();
}
@@ -433,6 +436,8 @@ class SwarmSearchController extends ChangeNotifier {
final availableCommands = isCommandMode
? commands?.call() ?? const <SwarmDestination>[]
: const <SwarmDestination>[];
+ final byActivity =
+ activityFirst && !navigating && !isCommandMode && !isGroupMode;
_commandIds = {for (final command in availableCommands) command.id};
final scopedMembers = _groupScope == null
? null
@@ -475,13 +480,20 @@ class SwarmSearchController extends ChangeNotifier {
recent: recent,
previews: app.sessionPreviews,
)
+ : byActivity
+ ? rankSwarmDestinationsByActivity(
+ candidates,
+ matchQuery,
+ recent: recent,
+ previews: app.sessionPreviews,
+ )
: rankSwarmDestinations(
candidates,
matchQuery,
recent: recent,
previews: history == null ? app.sessionPreviews : null,
);
- if (keepOrder && !navigating) {
+ if (keepOrder && !navigating && !byActivity) {
final remaining = {for (final row in rows) row.id: row};
rows = [
for (final row in previous) ?remaining.remove(row.id),
@@ -490,8 +502,9 @@ class SwarmSearchController extends ChangeNotifier {
}
// Keep the match order within each group, but put rows Return can open
// first. An already-added exact match must not bury the usable matches.
- // Location navigation retains its parent/child structure.
- if (!navigating && !isCommandMode) {
+ // Location navigation retains its parent/child structure; Open Harness
+ // retains its activity order, including unavailable sessions.
+ if (!navigating && !isCommandMode && !byActivity) {
final available = <SwarmDestination>[];
final unavailable = <SwarmDestination>[];
for (final row in rows) {
@@ -507,7 +520,14 @@ class SwarmSearchController extends ChangeNotifier {
for (final row in rows)
if (!row.isCreate) row,
];
- rows = resultsFromBottom || placement != null || query.trim().isEmpty
+ // Navigating (⌘O) always leads with New Harness: the list below it is
+ // ordered by latest activity, so the one thing that is never a
+ // result needs a fixed home rather than a place in that order.
+ rows =
+ resultsFromBottom ||
+ navigating ||
+ placement != null ||
+ query.trim().isEmpty
? [?create, ...found]
: [...found, ?create];
}
diff --git a/desktop/lib/terminal/terminal_text.dart b/desktop/lib/terminal/terminal_text.dart
index d33266b5d..ff0598696 100644
--- a/desktop/lib/terminal/terminal_text.dart
+++ b/desktop/lib/terminal/terminal_text.dart
@@ -26,6 +26,11 @@ TextStyle terminalTextStyle({
fontFeatures: fontFeatures,
);
+/// The renderer's exact font and line metrics, without inherited UI tracking.
+TextStyle terminalContentStyle({Color? color}) => terminalFontStore.value
+ .toTextStyle(color: color)
+ .copyWith(letterSpacing: 0, wordSpacing: 0);
+
/// Keeps retained widgets and open overlays on the same live typography.
class TerminalFontScope extends InheritedNotifier<TerminalFontStore> {
TerminalFontScope({super.key, required super.child})
diff --git a/desktop/lib/widgets/box_chrome.dart b/desktop/lib/widgets/box_chrome.dart
index ab43ff751..88b16c2bf 100644
--- a/desktop/lib/widgets/box_chrome.dart
+++ b/desktop/lib/widgets/box_chrome.dart
@@ -55,70 +55,14 @@ class TerminalTabBorder extends ShapeBorder {
void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {}
}
-/// A temporary command area attached to the workspace's bottom edge. Its
-/// overlay never changes the dimensions or scroll position of live terminals.
-class CommandDock extends StatelessWidget {
- const CommandDock({
- super.key,
- required this.child,
- this.topClearance = 0,
- this.expanded = false,
- });
- final Widget child;
- final double topClearance;
- final bool expanded;
-
- @override
- Widget build(BuildContext context) {
- return LayoutBuilder(
- builder: (context, constraints) {
- final available =
- (constraints.maxHeight - topClearance - 2 * kWorkspaceInset).clamp(
- 0.0,
- double.infinity,
- );
- final scale = grid.appTextScaleOf(context);
- // A shallow dock at ordinary sizes, with room for readable defaults and
- // key hints when accessibility text or a narrow window needs more rows.
- final minimum = constraints.maxWidth < 800 * scale ? 320.0 : 280.0;
- final maxHeight =
- (expanded
- ? 520.0 * scale
- : (available * .4).clamp(minimum * scale, 400.0 * scale))
- .clamp(0.0, available);
- return Align(
- alignment: Alignment.bottomCenter,
- child: Padding(
- padding: const EdgeInsets.fromLTRB(
- kWorkspaceInset,
- 0,
- kWorkspaceInset,
- kWorkspaceInset,
- ),
- child: ConstrainedBox(
- constraints: BoxConstraints(
- minWidth: (constraints.maxWidth - 2 * kWorkspaceInset).clamp(
- 0.0,
- double.infinity,
- ),
- maxHeight: maxHeight,
- ),
- child: FocusScope(child: child),
- ),
- ),
- );
- },
+/// Fixed UI typography for shared dialogs. Setup screens opt into the
+/// terminal's size explicitly so zoom does not resize unrelated controls.
+TextStyle boxMonoStyle({Color? color, FontWeight? weight, double? height}) =>
+ grid.AppType.mono(
+ height: height ?? 1.35,
+ color: color ?? Colors.white,
+ fontWeight: weight,
);
- }
-}
-
-/// Shared typography and frame for prompts that sit over the terminals: the
-/// terminal's face at [grid.AppType.monoSize], which ⌘+ and ⌘− leave alone.
-TextStyle boxMonoStyle({Color? color, FontWeight? weight}) => grid.AppType.mono(
- height: 1.35,
- color: color ?? Colors.white,
- fontWeight: weight,
-);
class TerminalBox extends StatelessWidget {
const TerminalBox({super.key, required this.child, this.docked = false});
diff --git a/desktop/lib/widgets/new_harness_box.dart b/desktop/lib/widgets/new_harness_box.dart
deleted file mode 100644
index bc8440a16..000000000
--- a/desktop/lib/widgets/new_harness_box.dart
+++ /dev/null
@@ -1,1654 +0,0 @@
-import 'dart:async';
-
-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/permission_modes.dart';
-import '../shared/theme/app_theme.dart' as grid;
-import '../shortcuts/app_keymap.dart';
-import '../shortcuts/keymap.dart';
-import '../state/new_harness.dart';
-import 'box_chrome.dart';
-import 'pane_menu.dart';
-import 'terminal_prompt.dart';
-
-enum _LaunchChoice { agent, machine, project, branch, worktree, create }
-
-/// A launch menu and focused completion prompts with shared arrow navigation.
-/// Create is selected initially; arrows and Enter edit a displayed default.
-class NewHarnessBox extends StatefulWidget {
- const NewHarnessBox({
- super.key,
- required this.controller,
- required this.onClose,
- required this.onCreated,
- required this.onNeedsForm,
- this.onBrowse,
- this.onStore,
- this.onLinkProfile,
- this.docked = false,
- });
- final NewHarnessController controller;
- final bool docked;
-
- /// Open the system's folder chooser (or another machine's browser) and hand
- /// the folder to the controller. Null hides nothing: the row then does nothing.
- final VoidCallback? onBrowse;
- final VoidCallback? onStore;
- final VoidCallback? onLinkProfile;
- final VoidCallback onClose;
- final VoidCallback onCreated;
-
- /// Open the full creation form for advanced options.
- final VoidCallback onNeedsForm;
-
- @override
- State<NewHarnessBox> createState() => _NewHarnessBoxState();
-}
-
-class _NewHarnessBoxState extends State<NewHarnessBox> {
- final _text = TextEditingController();
- final _focus = FocusNode(debugLabel: 'New harness argument');
- final _launchFocus = FocusNode(debugLabel: 'New harness launch');
- bool get _launching => box.field == NewHarnessField.launch;
- bool get _projectMenu => box.field == NewHarnessField.projectMenu;
- bool get _agentPicker => box.field == NewHarnessField.agent;
- bool get _machinePicker => box.field == NewHarnessField.machine;
- bool get _profilePicker => box.field == NewHarnessField.profile;
- bool get _reverseResults =>
- widget.docked || _projectMenu || _agentPicker || _profilePicker;
- int get _pinnedCount => _profilePicker && box.supportsProfiles ? 2 : 0;
- bool get _hasInput => !_launching;
- _LaunchChoice _launchChoice = _LaunchChoice.create;
- String get _agentSummary => [
- box.agentLabel,
- if (box.hasModes && box.mode != kDefaultPermissionMode) box.modeLabel,
- if (box.profileLabel case final profile?) 'profile $profile',
- ].join(' · ');
- List<_LaunchChoice> get _launchChoices => [
- _LaunchChoice.agent,
- _LaunchChoice.machine,
- _LaunchChoice.project,
- if (box.isGitProject) _LaunchChoice.branch,
- if (box.canUseWorktree || box.gitError != null) _LaunchChoice.worktree,
- _LaunchChoice.create,
- ];
- String get _launchCreateLabel => box.checking
- ? 'Check status'
- : box.needsProject
- ? 'Choose project'
- : box.createLabel;
-
- void _selectLaunchChoice(_LaunchChoice choice) {
- if (box.locked || _launchChoice == choice) return;
- setState(() => _launchChoice = choice);
- _announce();
- }
-
- void _activateLaunchChoice(_LaunchChoice choice) {
- if (box.busy || (box.locked && choice != _LaunchChoice.create)) return;
- switch (choice) {
- case _LaunchChoice.agent:
- box.focusField(NewHarnessField.agent);
- case _LaunchChoice.machine:
- box.focusField(NewHarnessField.machine);
- case _LaunchChoice.project:
- box.focusField(NewHarnessField.projectMenu);
- case _LaunchChoice.branch:
- box.focusField(NewHarnessField.branch);
- case _LaunchChoice.worktree:
- box.gitError != null ? box.retryGitProject() : box.toggleWorktree();
- case _LaunchChoice.create:
- unawaited(_finish(box.create()));
- }
- _requestFocus();
- }
-
- void _requestFocus() => (_hasInput ? _focus : _launchFocus).requestFocus();
- final _scroll = ScrollController();
- final _announcer = BoxAnnouncer();
- final _pointer = BoxPointerGate();
- double _rowHeight = 38;
- double _compactRowHeight = 28;
- int _revealed = -1;
- String? _revealedQuery;
- NewHarnessField? _announcedField;
- bool _announcementScheduled = false;
- bool _altHeld = false;
- String? _hoveredAgent;
- VoidCallback? _closeSettingsMenu;
- NewHarnessController get box => widget.controller;
-
- @override
- void initState() {
- super.initState();
- // A task carried in — a draft kept from the last Escape, or what was typed
- // in the search — is in the field from the first frame, caret at its end.
- _text.value = TextEditingValue(
- text: box.query,
- selection: TextSelection.collapsed(offset: box.query.length),
- );
- box.addListener(_changed);
- terminalFontStore.addListener(_fontChanged);
- HardwareKeyboard.instance.addHandler(_watchAlt);
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted) return;
- _requestFocus();
- _changed();
- });
- }
-
- @override
- void dispose() {
- _closeSettingsMenu?.call();
- HardwareKeyboard.instance.removeHandler(_watchAlt);
- box.removeListener(_changed);
- terminalFontStore.removeListener(_fontChanged);
- _text.dispose();
- _focus.dispose();
- _launchFocus.dispose();
- _scroll.dispose();
- super.dispose();
- }
-
- /// ⌥ held shows the digit each of the first nine rows answers to, the way the
- /// tab strip shows ⌘1–⌘9 while ⌘ is held. Never consumes the key.
- bool _watchAlt(KeyEvent event) {
- // Only where a digit picks a row: on the task ⌥ is word motion and
- // composed characters, and a panel rebuild for each would be for nothing.
- final held =
- HardwareKeyboard.instance.isAltPressed &&
- box.field != NewHarnessField.task &&
- box.options.isNotEmpty;
- if (held != _altHeld && mounted) setState(() => _altHeld = held);
- return false;
- }
-
- /// The keys this box prints, resolved when the keymap changes — not six
- /// linear scans of the picker bindings on every keystroke.
- Map<String, String> _pickerKeys = const {}, _projectKeys = const {};
- Map<String, String> get _keys => _projectMenu ? _projectKeys : _pickerKeys;
- static const _printed = {
- 'picker.previous': '↑',
- 'picker.next': '↓',
- 'picker.accept': '↵',
- 'picker.add_here': '⌘↵',
- 'picker.complete': '⇥',
- 'picker.complete_back': '⇧⇥',
- 'picker.more_options': '⌘.',
- 'picker.cancel': 'esc',
- 'creation.project_browse': 'ctrl-o',
- };
-
- @override
- void didChangeDependencies() {
- super.didChangeDependencies();
- Map<String, String> hints(KeymapContext scope) => {
- for (final entry in _printed.entries)
- entry.key: terminalPromptHint(
- context,
- entry.key,
- entry.value,
- contextKind: scope,
- ),
- };
- _pickerKeys = hints(KeymapContext.picker);
- _projectKeys = hints(KeymapContext.project);
- }
-
- /// Only rebuild when the arguments, results, or visible status change.
- Object? _shown;
- NewHarnessField? _focusedField;
- Object _visible() => (
- box.field,
- box.options,
- box.cursor,
- box.busy,
- box.checking,
- box.listing,
- box.status,
- box.error,
- box.task,
- box.worktree,
- box.canUseWorktree,
- box.checkingGit,
- box.gitError,
- box.branchRowLabel,
- box.createLabel,
- box.placement,
- box.query.trim().isEmpty,
- box.matchCount,
- box.total,
- (
- box.agentLabel,
- box.machineLabel,
- box.projectLocation,
- box.modeLabel,
- box.profileLabel,
- ),
- );
-
- void _changed() {
- if (!mounted) return;
- final editingName =
- _focusedField != box.field && box.field == NewHarnessField.projectName;
- if (_text.text != box.query) {
- _text.value = TextEditingValue(
- text: box.query,
- selection: editingName
- ? TextSelection(baseOffset: 0, extentOffset: box.query.length)
- : TextSelection.collapsed(offset: box.query.length),
- );
- }
- if (_focusedField != box.field) {
- _focusedField = box.field;
- if (_launching) _launchChoice = _LaunchChoice.create;
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) _requestFocus();
- });
- }
- if (box.locked || !_launchChoices.contains(_launchChoice)) {
- _launchChoice = _LaunchChoice.create;
- }
- final visible = _visible();
- if (visible != _shown) {
- _shown = visible;
- setState(() {});
- _announce();
- }
- }
-
- void _announce() {
- if (!_announcementScheduled) {
- _announcementScheduled = true;
- WidgetsBinding.instance.addPostFrameCallback((_) {
- _announcementScheduled = false;
- if (!mounted) return;
- final fieldChanged = _announcedField != box.field;
- if (_revealed != box.cursor ||
- fieldChanged ||
- _revealedQuery != box.query) {
- _reveal();
- }
- _revealed = box.cursor;
- _revealedQuery = box.query;
- _announcedField = box.field;
- final row = box.selected;
- // macOS does not announce liveRegion changes. Send the visible
- // message explicitly, ahead of the row, without moving the list.
- // Read at frame end so one update announces only its final state.
- _announcer.row(
- context,
- box.error ??
- box.status ??
- (_launching
- ? _launchChoice == _LaunchChoice.create
- ? _summaryText()
- : _launchChoice == _LaunchChoice.worktree
- ? 'Worktree ${box.worktree ? 'on' : 'off'}. Enter to toggle.'
- : '${_choiceTitle(_launchChoice)}. Enter to edit.'
- : box.field == NewHarnessField.task
- // No row to read here: read what Return will do instead.
- ? _summaryText()
- : row == null
- ? null
- : '${fieldChanged ? '${_fieldName(box.field)}. ' : ''}'
- '${row.title}${row.detail.isEmpty ? '' : ', ${row.detail}'}'
- '${box.isCurrent(row) ? ', current' : ''}'
- '${row.enabled ? '' : ', unavailable'}'),
- );
- });
- }
- }
-
- void _reveal() {
- if (!_scroll.hasClients || box.options.isEmpty) return;
- final start = _projectMenu ? 3 : _pinnedCount;
- if (box.cursor < start) return;
- final first = box.cursor;
- final top = box.options
- .skip(start)
- .take(first - start)
- .fold(0.0, (height, row) => height + _heightOf(row));
- final height = box.options
- .skip(first)
- .take(box.cursor - first + 1)
- .fold(0.0, (height, row) => height + _heightOf(row));
- final position = _scroll.position;
- final target =
- (top < position.pixels
- ? top
- : top + height > position.pixels + position.viewportDimension
- ? top + height - position.viewportDimension
- : position.pixels)
- .clamp(0.0, position.maxScrollExtent);
- if (target != position.pixels) _scroll.jumpTo(target);
- }
-
- double _heightOf(NewHarnessOption row) => _projectMenu
- ? _compactRowHeight
- : (box.field == NewHarnessField.project ||
- box.field == NewHarnessField.projectName) &&
- row.detail.isEmpty
- ? _compactRowHeight
- : _rowHeight;
-
- static String _fieldName(NewHarnessField field) => switch (field) {
- NewHarnessField.launch => 'New Harness',
- NewHarnessField.projectMenu => 'Project',
- NewHarnessField.projectName => 'Project name',
- NewHarnessField.projectRepository => 'GitHub repository',
- NewHarnessField.task => 'Task',
- NewHarnessField.mode => 'Permissions',
- NewHarnessField.profile => 'Codex profile',
- NewHarnessField.agent => 'Agent',
- NewHarnessField.machine => 'Machine',
- NewHarnessField.branch => 'Branch',
- NewHarnessField.project => 'Project',
- };
-
- /// What a launch row is called on screen.
- static String _choiceTitle(_LaunchChoice choice) =>
- '${choice.name[0].toUpperCase()}${choice.name.substring(1)}';
-
- bool get _composing =>
- _hasInput &&
- _text.value.composing.isValid &&
- !_text.value.composing.isCollapsed;
-
- Future<void> _finish(Future<NewHarnessOutcome> work) async {
- switch (await work) {
- case NewHarnessOutcome.created:
- widget.onCreated();
- case NewHarnessOutcome.failed:
- if (mounted) _requestFocus();
- }
- }
-
- bool _openingOptions = false;
- Future<void> _moreOptions() async {
- if (box.locked || _composing || _openingOptions) return;
- _openingOptions = true;
- try {
- await box.waitForGitProject();
- if (!mounted || box.locked) return;
- if (box.gitError != null) {
- box.warn(
- 'Could not check Git on ${box.machineLabel}. Retry Worktree before opening advanced options.',
- );
- return;
- }
- widget.onNeedsForm();
- } finally {
- _openingOptions = false;
- }
- }
-
- Future<void> _agentSettings(
- BuildContext anchor,
- NewHarnessOption agent,
- ) async {
- final engine = agent.engine;
- if (engine == null || box.locked) return;
- final settings = box.agentSettingsFor(engine);
- if (settings.isEmpty) return;
- _closeSettingsMenu?.call();
- final machine = box.machineId;
- final overlay = Overlay.of(anchor).context.findRenderObject()! as RenderBox;
- final button = anchor.findRenderObject()! as RenderBox;
- final position = button.localToGlobal(Offset.zero, ancestor: overlay);
- final setting = await showPaneMenu<String>(
- context: context,
- position: RelativeRect.fromRect(
- position & button.size,
- Offset.zero & overlay.size,
- ),
- minWidth: 270,
- maxWidth: 350,
- onOpen: (_, close) => _closeSettingsMenu = close,
- onClose: () => _closeSettingsMenu = null,
- children: (close) => [
- paneMenuHeader(agent.title),
- for (final setting in settings)
- paneMenuItem(
- onTap: () => close(setting.id),
- child: PaneMenuRow(
- key: ValueKey(setting.id),
- selected: false,
- title: setting.title,
- detail: setting.detail,
- ),
- ),
- ],
- );
- if (!mounted || machine != box.machineId || setting == null) return;
- box.openAgentSetting(engine, setting);
- _requestFocus();
- }
-
- void _editTask() {
- if (box.locked) return;
- if (box.takesTask) {
- box.focusField(NewHarnessField.task);
- } else {
- box.warn(
- 'Starting ${box.agentLabel} with a task is not supported yet. Enter it in the agent after launch.',
- );
- }
- }
-
- void _projectAction(String id) {
- if (box.locked) return;
- box.accept(box.options.firstWhere((row) => row.id == id));
- _requestFocus();
- }
-
- void _pickRecent(int number) {
- final recents = box.options.where((row) => !row.synthetic).toList();
- if (box.locked || number > recents.length) return;
- box.accept(recents[number - 1]);
- _requestFocus();
- }
-
- void _enter() {
- if (_composing || box.busy) return;
- if (_launching && !box.locked) {
- _activateLaunchChoice(_launchChoice);
- return;
- }
- if (box.selected?.id == NewHarnessController.linkProfileId && !box.locked) {
- widget.onLinkProfile?.call();
- return;
- }
- if (box.selected?.id == NewHarnessController.storeId && !box.locked) {
- widget.onStore?.call();
- return;
- }
- if (box.returnCreates) {
- unawaited(_finish(box.create()));
- } else if (box.selected?.id == NewHarnessController.browseId) {
- widget.onBrowse?.call();
- } else {
- box.accept();
- }
- _requestFocus();
- }
-
- void _createNow() {
- if (_composing || box.busy) return;
- if (box.selected?.id == NewHarnessController.linkProfileId && !box.locked) {
- widget.onLinkProfile?.call();
- return;
- }
- if (box.selected?.id == NewHarnessController.storeId && !box.locked) {
- widget.onStore?.call();
- return;
- }
- if (box.selected?.id == NewHarnessController.browseId && !box.locked) {
- widget.onBrowse?.call();
- return;
- }
- unawaited(_finish(box.createNow()));
- }
-
- /// Closing mid-create would throw away the attempt that exists to recover a
- /// lost reply, and leave a harness nobody is watching arrive.
- ///
- /// The same goes, once, for a create whose reply was lost: the first Escape
- /// says what is at stake, the second means it.
- void _cancel() {
- if (_composing) return;
- if (box.back()) return;
- if (box.requestDismiss()) widget.onClose();
- }
-
- /// Down, Up and the page keys: the highlight in a list, the caret in the
- /// task. The keymap consumes a key it matches whether or not anything
- /// handles it, so on the task — six lines with nothing to highlight — the
- /// arrows did nothing at all. There they are handed to the text field.
- void _vertical(int direction, {bool page = false}) {
- if (_launching) {
- final choices = _launchChoices;
- _selectLaunchChoice(
- page
- ? (direction < 0 ? choices.first : choices.last)
- : choices[(choices.indexOf(_launchChoice) + direction) %
- choices.length],
- );
- return;
- }
- if (box.field != NewHarnessField.task) {
- if (_reverseResults) {
- box.page(-direction, page ? _rowsPerPage : 1);
- } else {
- page ? box.page(direction, _rowsPerPage) : box.move(direction);
- }
- return;
- }
- final context = _focus.context;
- if (context == null) return;
- Actions.maybeInvoke(
- context,
- page
- ? ExtendSelectionVerticallyToAdjacentPageIntent(
- forward: direction > 0,
- collapseSelection: true,
- )
- : ExtendSelectionVerticallyToAdjacentLineIntent(
- forward: direction > 0,
- collapseSelection: true,
- ),
- );
- }
-
- void _tab(int step) {
- if (_composing || box.busy) return;
- box.complete(step);
- _requestFocus();
- }
-
- int get _rowsPerPage {
- if (!_scroll.hasClients) return 8;
- final height = _projectMenu ? _compactRowHeight : _rowHeight;
- return (_scroll.position.viewportDimension / height).floor().clamp(1, 50);
- }
-
- void _pick(int index) {
- if (index >= box.options.length || box.locked) return;
- if (box.options[index].id == NewHarnessController.linkProfileId) {
- widget.onLinkProfile?.call();
- return;
- }
- if (box.options[index].id == NewHarnessController.browseId) {
- widget.onBrowse?.call();
- return;
- }
- if (box.options[index].id == NewHarnessController.storeId) {
- widget.onStore?.call();
- return;
- }
- box.accept(box.options[index]);
- _requestFocus();
- }
-
- void _fontChanged() => setState(() {});
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final scale = MediaQuery.textScalerOf(context);
- _compactRowHeight = boxRowHeight(scale);
- _rowHeight =
- (box.field == NewHarnessField.project ||
- box.field == NewHarnessField.projectName ||
- box.field == NewHarnessField.projectRepository ||
- _projectMenu)
- ? scale.scale(grid.AppType.monoSize) * 1.35 +
- scale.scale(grid.AppType.monoSize) * 1.35 +
- 10
- : boxRowHeight(scale);
- final input = Semantics(
- label: '${_fieldName(box.field)}. ${box.hint}',
- child: ReadlineKeys(
- enabled: !box.locked,
- controller: _text,
- onChanged: box.setQuery,
- child: _input(),
- ),
- );
- final keys = <String, VoidCallback>{
- 'picker.accept': _enter,
- 'picker.add_here': _createNow,
- 'picker.next': () => _vertical(1),
- 'picker.previous': () => _vertical(-1),
- // No preview here to page, so the page keys page the list.
- 'picker.preview_page_down': () => _vertical(1, page: true),
- 'picker.preview_page_up': () => _vertical(-1, page: true),
- 'picker.cancel': _cancel,
- 'picker.complete': () => _tab(1),
- 'picker.complete_back': () => _tab(-1),
- 'picker.more_options': _moreOptions,
- if (_launching && !box.locked) ...{
- 'creation.agent': () => box.focusField(NewHarnessField.agent),
- 'creation.project': () => box.focusField(NewHarnessField.projectMenu),
- 'creation.task': _editTask,
- 'creation.options': _moreOptions,
- },
- if (_launching && !box.locked)
- 'creation.project_machine': () =>
- box.focusField(NewHarnessField.machine),
- if (_projectMenu && !box.locked) ...{
- 'creation.project_new': () =>
- _projectAction(NewHarnessController.newProjectId),
- 'creation.project_existing': () =>
- _projectAction(NewHarnessController.existingProjectId),
- 'creation.project_repository': () =>
- _projectAction(NewHarnessController.repositoryId),
- for (var recent = 1; recent <= 9; recent++)
- 'creation.project_recent_$recent': () => _pickRecent(recent),
- },
- if (box.field == NewHarnessField.project && !box.locked)
- 'creation.project_browse': () => widget.onBrowse?.call(),
- // Only where there are rows: on the task ⌥-digits are characters, and a
- // picker key nothing handles now falls through to the field.
- if (box.field != NewHarnessField.task && !_projectMenu)
- for (var row = 1; row <= 9; row++)
- 'picker.pick_$row': () => _pick(row - 1),
- };
- final panel = Semantics(
- scopesRoute: true,
- namesRoute: true,
- explicitChildNodes: true,
- label: box.checking
- ? 'Check agent creation'
- : box.placement == null
- ? 'New Harness'
- : box.createLabel,
- child: TerminalBox(
- key: const ValueKey('new-harness-box'),
- docked: widget.docked,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- _line(),
- if (!_launching &&
- _reverseResults &&
- box.field != NewHarnessField.task)
- Flexible(child: RepaintBoundary(child: _options())),
- // A long first task scrolls inside its editor after using the
- // available room; it never pushes the key guide out of the box.
- if (_hasInput)
- Flexible(
- // Field changes move the result list above this editor in a
- // dock. Keep its text-input connection and focus while it moves.
- key: const ValueKey('new-harness-editor-slot'),
- flex: box.field == NewHarnessField.task ? 1 : 0,
- child: input,
- ),
- // The rows churn on every keystroke; the shadow and the clip
- // around them should not be redrawn for it.
- if (!_launching &&
- !_reverseResults &&
- box.field != NewHarnessField.task)
- Flexible(child: RepaintBoundary(child: _options())),
- _footer(context),
- ],
- ),
- ),
- );
- final extra = CallbackShortcuts(
- bindings: {
- if (_launching)
- const SingleActivator(LogicalKeyboardKey.space): () {
- if (_launchChoice == _LaunchChoice.worktree) {
- _activateLaunchChoice(_LaunchChoice.worktree);
- }
- },
- // ⌥↵ is the pane's own chord for "break the line"; it is not a command.
- const SingleActivator(LogicalKeyboardKey.enter, alt: true): _newline,
- if (KeymapTheme.of(context) == null) ...{
- if (box.field == NewHarnessField.project && !box.locked)
- const SingleActivator(LogicalKeyboardKey.keyO, control: true): () =>
- widget.onBrowse?.call(),
- const SingleActivator(LogicalKeyboardKey.tab): () => _tab(1),
- const SingleActivator(LogicalKeyboardKey.tab, shift: true): () =>
- _tab(-1),
- const SingleActivator(LogicalKeyboardKey.period, meta: true):
- _moreOptions,
- // Only where there are rows: on the task ⌥-digits are characters.
- if (box.field != NewHarnessField.task && !_projectMenu)
- for (var digit = 0; digit < 9; digit++)
- SingleActivator(_digits[digit], alt: true): () => _pick(digit),
- const SingleActivator(LogicalKeyboardKey.enter): _enter,
- const SingleActivator(LogicalKeyboardKey.numpadEnter): _enter,
- const SingleActivator(LogicalKeyboardKey.enter, meta: true):
- _createNow,
- const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
- _vertical(1),
- const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
- _vertical(-1),
- const SingleActivator(LogicalKeyboardKey.keyN, control: true): () =>
- _vertical(1),
- const SingleActivator(LogicalKeyboardKey.keyP, control: true): () =>
- _vertical(-1),
- const SingleActivator(LogicalKeyboardKey.pageDown): () =>
- _vertical(1, page: true),
- const SingleActivator(LogicalKeyboardKey.pageUp): () =>
- _vertical(-1, page: true),
- const SingleActivator(LogicalKeyboardKey.escape): _cancel,
- const SingleActivator(LogicalKeyboardKey.keyC, control: true): () {
- if (!_composing) _cancel();
- },
- },
- },
- child: Focus(focusNode: _launchFocus, child: panel),
- );
- if (KeymapTheme.of(context) == null) return extra;
- return KeymapRegion(
- contextKind: _projectMenu ? KeymapContext.project : KeymapContext.picker,
- composing: () => _composing,
- actions: keys,
- child: Actions(
- actions: {
- DismissIntent: CallbackAction<DismissIntent>(onInvoke: (_) => null),
- },
- child: extra,
- ),
- );
- }
-
- static const _digits = [
- LogicalKeyboardKey.digit1,
- LogicalKeyboardKey.digit2,
- LogicalKeyboardKey.digit3,
- LogicalKeyboardKey.digit4,
- LogicalKeyboardKey.digit5,
- LogicalKeyboardKey.digit6,
- LogicalKeyboardKey.digit7,
- LogicalKeyboardKey.digit8,
- LogicalKeyboardKey.digit9,
- ];
-
- /// One field for every answer. On the task it grows to hold a real message —
- /// a first message can be two thousand characters, and a single 46px line
- /// showed forty of them — and ⌥↵ breaks the line, as it does in the panes.
- Widget _input() {
- final onTask = box.field == NewHarnessField.task;
- return TextField(
- key: const ValueKey('new-harness-input'),
- controller: _text,
- focusNode: _focus,
- onChanged: box.setQuery,
- readOnly: box.locked,
- minLines: 1,
- maxLines: onTask ? 6 : 1,
- keyboardType: onTask ? TextInputType.multiline : TextInputType.text,
- textInputAction: TextInputAction.none,
- style: boxMonoStyle(),
- cursorColor: grid.AppPalette.swarmAccent,
- decoration: InputDecoration(
- hintText: box.hint,
- hintStyle: boxMonoStyle(color: kBoxFaint),
- hintMaxLines: 1,
- // This is text on the first input line, not a vertically centered icon.
- // InputDecorator aligns a prefix to both the hint and editor baseline.
- floatingLabelBehavior: FloatingLabelBehavior.always,
- prefix: Text(
- '${switch (box.field) {
- NewHarnessField.projectName => 'Name',
- NewHarnessField.projectRepository => 'Repo',
- NewHarnessField.project => 'Folder',
- NewHarnessField.projectMenu => 'Project',
- NewHarnessField.mode => 'Permissions',
- _ => _fieldName(box.field),
- }.padRight(8)} ',
- style: boxMonoStyle(color: grid.AppPalette.swarmAccent),
- ),
- suffixIconConstraints: const BoxConstraints(minHeight: 38),
- suffixIcon: !onTask && box.query.trim().isNotEmpty && box.matchCount > 0
- ? Padding(
- padding: const EdgeInsets.only(right: 10),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Padding(
- padding: const EdgeInsets.only(right: 4),
- child: Text(
- '${box.matchCount}/${box.total}',
- key: const ValueKey('new-harness-count'),
- style: kBoxFaintStyle.copyWith(
- fontFeatures: const [FontFeature.tabularFigures()],
- ),
- ),
- ),
- ],
- ),
- )
- : null,
- // The box supplies the background; a filled M3 input adds another
- // horizontal inset that would move this label off the context column.
- filled: false,
- hoverColor: Colors.transparent,
- isDense: true,
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 14,
- vertical: 10,
- ),
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- ),
- );
- }
-
- /// ⌥↵ on the task: a new line in the message, not a harness.
- void _newline() {
- if (box.field != NewHarnessField.task || box.busy || _composing) return;
- final value = _text.value;
- final selection = value.selection.isValid
- ? value.selection
- : TextSelection.collapsed(offset: value.text.length);
- final text = value.text.replaceRange(selection.start, selection.end, '\n');
- _text.value = TextEditingValue(
- text: text,
- selection: TextSelection.collapsed(offset: selection.start + 1),
- );
- box.setQuery(text);
- }
-
- /// A compact command context, with names for every editable default.
- Widget _line() => _projectMenu
- ? Padding(
- padding: const EdgeInsets.fromLTRB(14, 8, 14, 4),
- child: Row(
- children: [
- Expanded(
- child: Text(
- 'Projects on ${box.machineLabel}',
- style: boxMonoStyle(color: kBoxFaint),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- TextButton(
- key: const ValueKey('new-harness-change-machine'),
- onPressed: box.locked
- ? null
- : () => box.focusField(NewHarnessField.machine),
- child: Text(
- 'Change Machine',
- style: boxMonoStyle(color: grid.AppPalette.swarmAccent),
- ),
- ),
- ],
- ),
- )
- : Padding(
- padding: const EdgeInsets.fromLTRB(6, 8, 6, 4),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (!_launching)
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8),
- child: Text(
- box.checking
- ? 'pending harness'
- : _agentPicker
- ? 'Choose an agent'
- : _machinePicker
- ? 'Choose a machine'
- : box.field == NewHarnessField.branch
- ? 'Choose a branch'
- : _profilePicker
- ? 'Codex profile on ${box.machineLabel}'
- : box.field == NewHarnessField.mode
- ? 'Permissions for ${box.agentSettingsLabel}'
- : 'New Harness',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ),
- if (!_agentPicker &&
- !_machinePicker &&
- box.field != NewHarnessField.branch) ...[
- if (!_launching) const SizedBox(height: 8),
- _segment(
- NewHarnessField.agent,
- _launching
- ? _agentSummary
- : box.field == NewHarnessField.mode || _profilePicker
- ? box.agentSettingsLabel
- : box.agentLabel,
- ),
- _segment(NewHarnessField.machine, box.machineLabel),
- _segment(NewHarnessField.project, switch (box.field) {
- NewHarnessField.project => 'Open Folder',
- NewHarnessField.projectName => 'New Project',
- NewHarnessField.projectRepository => 'GitHub Repository',
- _ => box.needsProject ? 'Choose a project' : box.projectLabel,
- }),
- ],
- if (_launching) ...[
- if (box.isGitProject)
- _segment(
- NewHarnessField.branch,
- box.branchRowLabel,
- tooltip: box.opensWorktree
- ? '${box.branchLabel} is checked out in a worktree of its own: the harness starts there, beside what is working in it.'
- : box.worktree
- ? 'What the worktree works from, brought up to date with its remote at Start. The default branch gets a new branch named after the session; another is checked out as it is. Type a name to create one.'
- : 'The branch the project folder is on.',
- ),
- if (box.isGitProject || box.checkingGit || box.gitError != null)
- _default(
- 'worktree',
- box.checkingGit
- ? 'Checking…'
- : box.gitError != null
- ? 'Retry'
- : box.worktree
- ? '[x]'
- : '[ ]',
- enabled: box.canUseWorktree || box.gitError != null,
- tooltip: box.gitError != null
- ? 'Could not check Git on ${box.machineLabel}. Retry.'
- : box.canUseWorktree
- ? 'Start in a new Git worktree: a folder of its own, so harnesses never share files. Uncommitted changes stay in the project folder.'
- : 'Choose an existing Git project to use a worktree.',
- onTap: () {
- _selectLaunchChoice(_LaunchChoice.worktree);
- _activateLaunchChoice(_LaunchChoice.worktree);
- },
- ),
- const SizedBox(height: 8),
- _default(
- 'create',
- _launchCreateLabel,
- action: true,
- onTap: () => _activateLaunchChoice(_LaunchChoice.create),
- ),
- ],
- ],
- ),
- );
-
- Widget _segment(
- NewHarnessField field,
- String label, {
- String? title,
- String? tooltip,
- }) => _default(
- field.name,
- label,
- title: title,
- tooltip: tooltip,
- active:
- box.field == field ||
- (field == NewHarnessField.project &&
- (_projectMenu ||
- box.field == NewHarnessField.projectName ||
- box.field == NewHarnessField.projectRepository)),
- risky: _launching && field == NewHarnessField.agent && box.riskyMode,
- onTap: () {
- box.focusField(
- field == NewHarnessField.project ? NewHarnessField.projectMenu : field,
- );
- _requestFocus();
- },
- );
-
- Widget _default(
- String name,
- String label, {
- required VoidCallback onTap,
- bool active = false,
- bool risky = false,
- bool action = false,
- bool enabled = true,
- String? tooltip,
- String? title,
- }) {
- final choice = _launching
- ? _LaunchChoice.values.where((item) => item.name == name).firstOrNull
- : null;
- final highlighted = choice != null && choice == _launchChoice;
- final disabled = !enabled || (name == 'create' ? box.busy : box.locked);
- final fieldLabel = title ?? '${name[0].toUpperCase()}${name.substring(1)}';
- final checkbox =
- name == 'worktree' && !box.checkingGit && box.gitError == null;
- return MouseRegion(
- onHover: (event) {
- if (!disabled && choice != null && _pointer.moved(event)) {
- _selectLaunchChoice(choice);
- }
- },
- child: Semantics(
- button: !checkbox,
- checked: checkbox ? box.worktree : null,
- enabled: !disabled,
- selected: highlighted || active,
- label: checkbox
- ? fieldLabel
- : action
- ? label
- : '$fieldLabel, $label',
- excludeSemantics: true,
- onTap: disabled ? null : onTap,
- child: BoxRowHighlight(
- terminal: true,
- highlighted: highlighted,
- accent: grid.AppPalette.swarmAccent,
- child: Tooltip(
- message: tooltip ?? label,
- child: InkWell(
- key: ValueKey('new-harness-field-$name'),
- onTap: disabled ? null : onTap,
- canRequestFocus: false,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
- child: Row(
- children: [
- if (!action)
- Text(
- '${fieldLabel.padRight(8)} ',
- style: boxMonoStyle(
- color: active
- ? grid.AppPalette.swarmAccent
- : kBoxFaint,
- ),
- ),
- Flexible(
- child: Text(
- label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(
- color: risky
- ? grid.AppPalette.warn
- : disabled
- ? kBoxFaint
- : Colors.white,
- weight: active || action
- ? FontWeight.w600
- : FontWeight.w400,
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- ),
- );
- }
-
- /// On the task there is nothing to pick: say, in one sentence, what Return
- /// will do — every answer on the line read back in words — so the person
- /// can check it at a glance and never has to trust what they cannot see.
- String _summaryText() => box.needsProject
- ? 'Choose a project before starting ${box.agentLabel}.'
- : 'Return starts ${box.agentLabel} on ${box.machineLabel} in '
- '${box.projectLabel}'
- '${box.gitSummary}'
- '${box.hasModes ? ', ${box.modeLabel.toLowerCase()}' : ''}'
- '${box.profileLabel == null ? '' : ', profile ${box.profileLabel}'}'
- '${box.task.trim().isEmpty ? '' : ', and sends what you typed as its first message'}.';
-
- Widget _projectChoices() {
- final recents = box.options.skip(3).toList();
- Widget row(int index) {
- final option = box.options[index];
- final highlighted = box.cursor == index;
- final folder = option.project?.folder;
- final title = Text(
- option.title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(color: option.enabled ? Colors.white : kBoxFaint),
- );
- return MouseRegion(
- onHover: (event) {
- if (_pointer.moved(event) && !highlighted) {
- box.move(index - box.cursor);
- }
- },
- child: Semantics(
- button: true,
- selected: highlighted,
- label: '${option.title}, ${option.detail}',
- child: BoxRowHighlight(
- terminal: true,
- highlighted: highlighted,
- accent: grid.AppPalette.swarmAccent,
- child: Tooltip(
- message: option.detail,
- child: InkWell(
- key: ValueKey(option.id),
- canRequestFocus: false,
- onTap: box.locked ? null : () => _pick(index),
- child: SizedBox(
- height: _compactRowHeight,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12),
- child: LayoutBuilder(
- builder: (context, constraints) => Row(
- children: [
- if (folder == null)
- Expanded(child: title)
- else
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: constraints.maxWidth * .4,
- ),
- child: title,
- ),
- if (folder != null) ...[
- const SizedBox(width: 12),
- Expanded(
- child: Text(
- box.tildePath(folder),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ),
- ],
- if (box.isCurrent(option))
- const Padding(
- padding: EdgeInsets.only(left: 8),
- child: Icon(
- LucideIcons.check,
- size: 13,
- color: kBoxFaint,
- ),
- ),
- if (highlighted)
- Padding(
- padding: const EdgeInsets.only(left: 8),
- child: Text(
- _keys['picker.accept'] ?? '↵',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- );
- }
-
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(12, 10, 12, 6),
- child: Text(
- box.query.trim().isNotEmpty
- ? recents.isEmpty
- ? 'No projects match “${box.query.trim()}”'
- : 'matches · ${recents.length}/${box.total}'
- : recents.isEmpty
- ? 'No recent projects'
- : 'recent · ${recents.length}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ),
- if (recents.isNotEmpty)
- Flexible(
- child: SizedBox(
- height: recents.length.clamp(0, 9) * _compactRowHeight,
- child: NotificationListener<ScrollMetricsNotification>(
- onNotification: (_) {
- // Keep the chosen project visible after resizing or
- // changing text size, even when its cursor hasn't moved.
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted && _projectMenu) _reveal();
- });
- return false;
- },
- child: ListView.builder(
- key: const ValueKey('new-harness-recent-projects'),
- controller: _scroll,
- reverse: true,
- itemCount: recents.length,
- itemExtent: _compactRowHeight,
- itemBuilder: (_, index) => row(index + 3),
- ),
- ),
- ),
- ),
- const SizedBox(height: 8),
- for (var i = 2; i >= 0; i--) row(i),
- ],
- ),
- );
- }
-
- Widget _options() {
- if (_launching || box.field == NewHarnessField.task) {
- return const SizedBox.shrink();
- }
- if (_projectMenu) return _projectChoices();
- if (box.field == NewHarnessField.projectRepository && box.options.isEmpty) {
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
- child: Align(
- alignment: Alignment.centerLeft,
- heightFactor: 1,
- child: Text(
- box.query.trim().isEmpty
- ? 'Clone to ${box.machineLabel}:~/harnesses/<repository>'
- : 'Paste a GitHub repository URL, or try openai/codex',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ),
- );
- }
- if (box.field == NewHarnessField.projectName && box.query.trim().isEmpty) {
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
- child: Align(
- alignment: Alignment.centerLeft,
- heightFactor: 1,
- child: Text(
- "${box.machineLabel}:~/harnesses/<name>",
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ),
- );
- }
- if (box.options.isEmpty) {
- final path = box.field == NewHarnessField.project && box.isPathQuery;
- return Center(
- heightFactor: 1,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
- child: Text(
- box.listing
- ? 'Reading the folder…'
- : _agentPicker
- ? 'No agents match “${box.query.trim()}”.'
- : path
- ? 'No folders here'
- // Typing a project's name into the agent field is the first
- // thing a new person does; say where they are and the way out.
- : 'Nothing matches “${box.query.trim()}” in '
- '${_fieldName(box.field)}. Escape goes back.',
- textAlign: TextAlign.center,
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ),
- );
- }
- if (_agentPicker && box.matchCount == 0) {
- return Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Flexible(
- child: SingleChildScrollView(
- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
- child: Text(
- 'No agents match “${box.query.trim()}”.',
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ),
- ),
- Flexible(child: _optionList()),
- ],
- );
- }
- if (_pinnedCount == 0) return _optionList();
- return Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Flexible(child: _optionList(start: _pinnedCount)),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- for (var i = _pinnedCount - 1; i >= 0; i--)
- SizedBox(
- height: _heightOf(box.options[i]),
- child: _optionRow(i),
- ),
- ],
- ),
- ),
- ],
- );
- }
-
- Widget _optionList({int start = 0}) {
- if (start == box.options.length) return const SizedBox.shrink();
- return LayoutBuilder(
- builder: (context, constraints) {
- final height = box.options
- .skip(start)
- .take(widget.docked ? 6 : 8)
- .fold(12.0, (height, row) => height + _heightOf(row));
- return Align(
- alignment: Alignment.topCenter,
- heightFactor: 1,
- child: SizedBox(
- height: height.clamp(0, constraints.maxHeight),
- child: Padding(
- padding: const EdgeInsets.symmetric(vertical: 6),
- child: ListView.builder(
- key: const ValueKey('new-harness-options'),
- controller: _scroll,
- reverse: _reverseResults,
- padding: const EdgeInsets.symmetric(horizontal: 6),
- itemExtentBuilder: (index, _) =>
- _heightOf(box.options[index + start]),
- itemCount: box.options.length - start,
- itemBuilder: (_, index) => _optionRow(index + start),
- ),
- ),
- ),
- );
- },
- );
- }
-
- Widget _optionRow(int index) {
- final accent = grid.AppPalette.swarmAccent;
- final option = box.options[index];
- final highlighted = index == box.cursor;
- final hasSettings =
- _agentPicker &&
- option.engine != null &&
- box.agentSettingsFor(option.engine!).isNotEmpty;
- final folder = option.project?.folder;
- final walkable =
- folder != null &&
- !option.synthetic &&
- box.field == NewHarnessField.project &&
- box.isPathQuery;
- return MouseRegion(
- onEnter: hasSettings
- ? (_) => setState(() => _hoveredAgent = option.id)
- : null,
- onExit: hasSettings
- ? (_) => setState(() {
- if (_hoveredAgent == option.id) _hoveredAgent = null;
- })
- : null,
- // The pointer moving onto a row, never a row moving under it.
- onHover: (event) {
- if (_pointer.moved(event) && box.cursor != index) {
- box.move(index - box.cursor);
- }
- },
- child: BoxRowHighlight(
- terminal: true,
- highlighted: highlighted,
- accent: accent,
- child: ListTile(
- key: ValueKey(option.id),
- dense: true,
- visualDensity: VisualDensity.compact,
- minVerticalPadding: 0,
- minTileHeight: _heightOf(option),
- enabled: !box.busy,
- hoverColor: Colors.transparent,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
- contentPadding: const EdgeInsets.only(left: 8, right: 6),
- title:
- (box.field == NewHarnessField.project ||
- box.field == NewHarnessField.projectName ||
- box.field == NewHarnessField.projectRepository ||
- _projectMenu)
- ? Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- option.title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(
- color: option.enabled ? Colors.white : kBoxFaint,
- ),
- ),
- if (option.detail.isNotEmpty)
- Text(
- option.detail,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(color: kBoxFaint),
- ),
- ],
- )
- : Row(
- children: [
- Flexible(
- flex: 3,
- child: Text(
- option.title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(
- color: option.risky
- ? grid.AppPalette.warn
- : option.enabled
- ? Colors.white
- : Colors.white54,
- ),
- ),
- ),
- if (option.detail.isNotEmpty) ...[
- const SizedBox(width: 10),
- Flexible(
- flex: 5,
- child: Text(
- option.detail,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: boxMonoStyle(
- color: option.risky
- ? grid.AppPalette.warn
- : kBoxFaint,
- ),
- ),
- ),
- ],
- ],
- ),
- trailing: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- // The answer the line already gives wears the check, as the
- // current folder and branch do in an editor's pickers.
- if (box.isCurrent(option))
- const Padding(
- padding: EdgeInsets.only(right: 10),
- child: Icon(LucideIcons.check, size: 15, color: kBoxFaint),
- ),
- if (_altHeld && index < 9)
- Padding(
- padding: const EdgeInsets.only(right: 8),
- child: Text('⌥${index + 1}', style: kBoxFaintStyle),
- ),
- if (walkable)
- // The mouse's Tab: go into the folder rather than take it.
- IconButton(
- tooltip: 'Open ${option.title}',
- visualDensity: VisualDensity.compact,
- iconSize: 16,
- color: Colors.white54,
- icon: const Icon(LucideIcons.chevronRight),
- onPressed: box.busy
- ? null
- : () {
- box.setQuery('${box.tildePath(folder)}/');
- _requestFocus();
- },
- ),
- if (highlighted && option.enabled)
- Text(
- _keys['picker.accept'] ?? '↵',
- key: const ValueKey('new-harness-row-action'),
- style: boxMonoStyle(color: kBoxFaint),
- ),
- if (_agentPicker)
- SizedBox(
- width: 28,
- height: 28,
- child: hasSettings
- ? Builder(
- builder: (anchor) => _AgentSettingsButton(
- key: ValueKey('new-harness-settings-${option.id}'),
- label: 'Settings for ${option.title}',
- visible: _hoveredAgent == option.id,
- onPressed: box.locked
- ? null
- : () => _agentSettings(anchor, option),
- ),
- )
- : null,
- ),
- ],
- ),
- onTap: () => _pick(index),
- ),
- ),
- );
- }
-
- /// Errors retain the available recovery keys. A pending receipt permits a
- /// status check or dismissal; it cannot edit choices or change forms.
- Widget _footer(BuildContext context) {
- String key(String command, String fallback) => _keys[command] ?? fallback;
- return BoxHintStrip(
- key: const ValueKey('new-harness-footer'),
- message:
- box.error ??
- (_profilePicker
- ? box.profileHelp ??
- (box.linkingProfile ? 'Linking profile…' : null)
- : null) ??
- box.status,
- isError: box.error != null,
- busy: box.busy || box.linkingProfile,
- hints: [
- if (box.field != NewHarnessField.task && !box.checking)
- BoxHint(
- '${key('picker.previous', '↑')}/${key('picker.next', '↓')}',
- 'select',
- ),
- BoxHint(
- key('picker.accept', '↵'),
- box.checking
- ? 'check status'
- : _projectMenu
- ? switch (box.selected?.id) {
- NewHarnessController.newProjectId => 'new project',
- NewHarnessController.existingProjectId => 'open folder',
- NewHarnessController.repositoryId => 'clone repository',
- _ => 'use project',
- }
- : _launching && _launchChoice != _LaunchChoice.create
- ? _launchChoice == _LaunchChoice.worktree
- ? 'toggle'
- : 'edit ${_launchChoice.name}'
- : _launching && box.needsProject
- ? 'choose project'
- : box.returnCreates
- ? 'start'
- : box.selected?.id == NewHarnessController.storeId
- ? 'open store'
- : box.selected?.id == NewHarnessController.permissionsId
- ? 'edit permissions'
- : box.selected?.id == NewHarnessController.profileId
- ? 'choose profile'
- : box.selected?.id == NewHarnessController.linkProfileId
- ? 'link profile folder'
- : box.selected?.id == NewHarnessController.refreshProfilesId
- ? 'refresh profiles'
- : _profilePicker
- ? 'use profile'
- : box.field == NewHarnessField.mode
- ? 'use permissions'
- : box.selected?.id == NewHarnessController.browseId
- ? 'open folder'
- : box.selected?.id == NewHarnessController.changeMachineId
- ? 'change machine'
- : box.selected?.id == NewHarnessController.newProjectId
- ? 'name project'
- : box.field == NewHarnessField.projectRepository
- ? 'use repository'
- : box.field == NewHarnessField.project ||
- box.field == NewHarnessField.projectName
- ? 'use project'
- : 'choose',
- onTap: _enter,
- ),
- if (_launching &&
- !box.checking &&
- _launchChoice != _LaunchChoice.create)
- BoxHint(key('picker.add_here', '⌘↵'), 'start', onTap: _createNow),
- if (!box.checking &&
- !_launching &&
- !_projectMenu &&
- box.field != NewHarnessField.task &&
- box.field != NewHarnessField.projectName &&
- box.field != NewHarnessField.projectRepository)
- BoxHint(
- key('picker.complete', '⇥'),
- box.isPathQuery ? 'complete path' : 'complete',
- onTap: () => _tab(1),
- ),
- if (!box.checking && box.field == NewHarnessField.project)
- BoxHint(
- key('creation.project_browse', 'ctrl-o'),
- 'browse folders',
- onTap: widget.onBrowse,
- ),
- BoxHint(
- key('picker.cancel', 'esc'),
- _launching || box.checking ? 'close' : 'back',
- onTap: _cancel,
- ),
- ],
- );
- }
-}
-
-/// Reserve the same hit target even when the icon is quiet, so rows never move.
-class _AgentSettingsButton extends StatefulWidget {
- const _AgentSettingsButton({
- super.key,
- required this.label,
- required this.visible,
- required this.onPressed,
- });
- final String label;
- final bool visible;
- final VoidCallback? onPressed;
-
- @override
- State<_AgentSettingsButton> createState() => _AgentSettingsButtonState();
-}
-
-class _AgentSettingsButtonState extends State<_AgentSettingsButton> {
- bool _focused = false;
-
- @override
- Widget build(BuildContext context) {
- return Focus(
- onFocusChange: (focused) => setState(() => _focused = focused),
- child: Opacity(
- opacity: widget.visible || _focused ? 1 : 0,
- alwaysIncludeSemantics: true,
- child: IconButton(
- tooltip: widget.label,
- onPressed: widget.onPressed,
- icon: const Icon(LucideIcons.settings, size: 14, color: kBoxFaint),
- style: IconButton.styleFrom(
- padding: EdgeInsets.zero,
- minimumSize: const Size(28, 28),
- maximumSize: const Size(28, 28),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- ),
- ),
- ),
- );
- }
-}
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
new file mode 100644
index 000000000..806f41a91
--- /dev/null
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -0,0 +1,1047 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.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 '../state/new_harness.dart';
+import 'box_chrome.dart';
+import 'engine_identity.dart';
+
+/// Every answer a new harness needs, on one screen, changed where it stands.
+///
+/// Shares Open Harness's terminal typography and quiet selection treatment.
+/// ↑↓ walk the fields; ←→ change their values. Return opens the focused
+/// field's choices, and only the explicit New Harness action starts an agent.
+/// Typing filters the choices without changing the current value.
+///
+/// Unavailable Git fields explain why they cannot be changed. Profile only
+/// appears for agents that use it.
+class NewHarnessForm extends StatefulWidget {
+ const NewHarnessForm({
+ super.key,
+ required this.controller,
+ required this.onClose,
+ required this.onCreated,
+ this.onBrowse,
+ this.onStore,
+ this.onLinkProfile,
+ this.onNeedsForm,
+ });
+
+ final NewHarnessController controller;
+ final VoidCallback onClose;
+ final VoidCallback onCreated;
+ final FutureOr<void> Function()? onBrowse;
+ final VoidCallback? onStore, onLinkProfile, onNeedsForm;
+
+ @override
+ State<NewHarnessForm> createState() => _NewHarnessFormState();
+}
+
+/// The items, in the order they are read. Project leads because it is what
+/// changes most; everything under it is usually already right.
+enum _Row {
+ project,
+ agent,
+ machine,
+ branch,
+ worktree,
+ approvals,
+ profile,
+ start,
+}
+
+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();
+ _Row _row = _Row.project;
+ final _itemKeys = {for (final row in _Row.values) row: GlobalKey()};
+ final _choiceKey = GlobalKey();
+
+ List<_Row> get _rows => [
+ for (final row in _Row.values)
+ if (row != _Row.profile || box.usesProfile) row,
+ ];
+
+ /// Whether the focused field's choices own the keyboard. Wide windows also
+ /// preview them while the fields are active.
+ bool _listOpen = false;
+
+ @override
+ void initState() {
+ super.initState();
+ box.addListener(_onBox);
+ // The pane colours can change under an open dialog; it wears them too.
+ terminalThemeStore.addListener(_onBox);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ if (box.checking) _row = _Row.start;
+ _syncField();
+ _focus.requestFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ box.removeListener(_onBox);
+ terminalThemeStore.removeListener(_onBox);
+ _inputFocus.dispose();
+ _queryText.dispose();
+ _focus.dispose();
+ super.dispose();
+ }
+
+ NewHarnessField? _observedField;
+ void _onBox() {
+ if (!mounted) return;
+ if (_queryText.text != box.query) {
+ _queryText.value = TextEditingValue(
+ text: box.query,
+ selection: TextSelection.collapsed(offset: box.query.length),
+ );
+ }
+ if (_observedField != box.field) {
+ _observedField = box.field;
+ final next = switch (box.field) {
+ NewHarnessField.agent => _Row.agent,
+ NewHarnessField.machine => _Row.machine,
+ NewHarnessField.branch => _Row.branch,
+ NewHarnessField.mode => _Row.approvals,
+ NewHarnessField.profile => _Row.profile,
+ NewHarnessField.projectMenu ||
+ NewHarnessField.project ||
+ NewHarnessField.projectName ||
+ NewHarnessField.projectRepository => _Row.project,
+ NewHarnessField.launch => _Row.start,
+ _ => _row,
+ };
+ if (next != _row) {
+ _row = next;
+ _listOpen = false;
+ _takeWheel();
+ }
+ }
+ setState(() {});
+ _revealRow();
+ }
+
+ void _focusEditor() {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ (_picking ? _inputFocus : _focus).requestFocus();
+ });
+ }
+
+ /// The field a row edits, or null where the row is its own answer.
+ static const _projectFields = {
+ NewHarnessField.projectMenu,
+ NewHarnessField.project,
+ NewHarnessField.projectName,
+ NewHarnessField.projectRepository,
+ };
+
+ NewHarnessField? _fieldOf(_Row row) => switch (row) {
+ _Row.project =>
+ _projectFields.contains(box.field)
+ ? box.field
+ : NewHarnessField.projectMenu,
+ _Row.agent => NewHarnessField.agent,
+ _Row.machine => NewHarnessField.machine,
+ _Row.branch => NewHarnessField.branch,
+ _Row.worktree => null,
+ _Row.approvals => NewHarnessField.mode,
+ _Row.profile => NewHarnessField.profile,
+ _Row.start => null,
+ };
+
+ /// Why a row cannot be changed, in the words the row will wear.
+ String? _blocked(_Row row) => switch (row) {
+ _Row.branch || _Row.worktree when box.checkingGit => '',
+ _Row.branch when box.gitError != null => box.gitError,
+ _Row.branch when !box.isGitProject => 'Not a Git repository',
+ _Row.worktree when box.gitError != null => box.gitError,
+ _Row.worktree when !box.canUseWorktree => 'Not a Git repository',
+ _Row.approvals when !box.hasModes => 'Not used by this agent',
+ _ => null,
+ };
+
+ String _label(_Row row) => switch (row) {
+ _Row.project => switch (box.field) {
+ NewHarnessField.projectName => 'New Project',
+ NewHarnessField.projectRepository => 'Repository',
+ NewHarnessField.project => 'Folder',
+ _ => 'Project',
+ },
+ _Row.agent => 'Agent',
+ _Row.machine => 'Machine',
+ _Row.branch => 'Branch',
+ _Row.worktree => 'Worktree',
+ _Row.approvals => 'Approvals',
+ _Row.profile => 'Profile',
+ _Row.start => 'New Harness',
+ };
+
+ /// What the row currently answers — or, while its list is open, what the
+ /// highlight would make it, so the row never disagrees with the list.
+ String _value(_Row row) => _valueOf(row);
+
+ String _valueOf(_Row row) => switch (row) {
+ _Row.project => box.projectLabel,
+ _Row.agent => box.agentLabel,
+ _Row.machine => box.machineLabel,
+ _Row.branch => box.branchRowLabel,
+ _Row.worktree => box.worktree ? 'Yes' : 'No',
+ _Row.approvals => box.modeLabel,
+ _Row.profile => box.profileLabel ?? 'Default',
+ _Row.start => '',
+ };
+
+ /// Focusing a row focuses the field it edits, so the controller's option
+ /// list — and therefore ← and → — is already the right one.
+ void _syncField() {
+ final field = _fieldOf(_row);
+ if (field == null) {
+ _wheel = const [];
+ return;
+ }
+ box.focusField(field);
+ _takeWheel();
+ }
+
+ void _moveRow(int delta) {
+ if (box.busy || box.linkingProfile) return;
+ final rows = _rows;
+ setState(() {
+ _row = rows[(rows.indexOf(_row) + delta) % rows.length];
+ _listOpen = false;
+ });
+ if (box.query.isNotEmpty) box.setQuery('');
+ _syncField();
+ _revealRow();
+ }
+
+ void _revealRow() {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ final context = _picking
+ ? _choiceKey.currentContext
+ : _itemKeys[_row]?.currentContext;
+ if (context == null) return;
+ final target = context.findRenderObject();
+ final viewport = Scrollable.maybeOf(context)?.context.findRenderObject();
+ if (target is! RenderBox ||
+ viewport is! RenderBox ||
+ !target.hasSize ||
+ !viewport.hasSize) {
+ return;
+ }
+ final top = target.localToGlobal(Offset.zero, ancestor: viewport).dy;
+ if (top < 0 || top + target.size.height > viewport.size.height) {
+ Scrollable.ensureVisible(context, alignment: top < 0 ? 0 : 1);
+ }
+ });
+ }
+
+ /// ← and → on a row that is its own answer flip it; everywhere else they
+ /// step the field's options and apply the new one where it stands.
+ /// The values this row steps through, captured when the row is focused.
+ /// The controller's displayed list re-ranks the chosen row to the front,
+ /// so stepping through THAT walks in circles; a wheel taken once does not
+ /// move under the arrows.
+ List<NewHarnessOption> _wheel = const [];
+ int _at = 0;
+
+ void _takeWheel() {
+ _wheel = box.stepValues();
+ _at = _wheel.indexWhere(box.isCurrent);
+ if (_at < 0) _at = 0;
+ }
+
+ void _stepValue(int delta) {
+ if (box.locked || _blocked(_row) != null) return;
+ if (_row == _Row.worktree) {
+ setState(box.toggleWorktree);
+ return;
+ }
+ if (_wheel.isEmpty) _takeWheel();
+ if (_wheel.isEmpty) return;
+ // Follow the value if something else moved it, then step from there.
+ final now = _wheel.indexWhere(box.isCurrent);
+ if (now >= 0) _at = now;
+ _at = (_at + delta) % _wheel.length;
+ box.applyOption(_wheel[_at]);
+ }
+
+ /// Folder paths, project names and repository URLs keep their prompt active
+ /// even before anything is typed.
+ static const _prompts = {
+ NewHarnessField.project,
+ NewHarnessField.projectName,
+ NewHarnessField.projectRepository,
+ };
+
+ bool get _picking =>
+ (_listOpen || box.query.isNotEmpty || _prompts.contains(box.field)) &&
+ _fieldOf(_row) != null &&
+ _blocked(_row) == null;
+
+ bool _isComposing() =>
+ _queryText.value.composing.isValid &&
+ !_queryText.value.composing.isCollapsed;
+
+ /// Typing filters the focused field's choices; Return commits the selection.
+ void _onTyped(String value) {
+ if (box.locked || _fieldOf(_row) == null || _blocked(_row) != null) return;
+ box.setQuery(value);
+ _focusEditor();
+ }
+
+ void _insertText(String text) {
+ if (box.locked || _fieldOf(_row) == null || _blocked(_row) != null) return;
+ final value = _queryText.value;
+ final selection = value.selection.isValid
+ ? value.selection
+ : TextSelection.collapsed(offset: value.text.length);
+ final next = value.text.replaceRange(selection.start, selection.end, text);
+ _queryText.value = TextEditingValue(
+ text: next,
+ selection: TextSelection.collapsed(offset: selection.start + text.length),
+ );
+ _onTyped(next);
+ }
+
+ Future<void> _pasteQuery() async {
+ if (box.locked || _fieldOf(_row) == null || _blocked(_row) != null) return;
+ final row = _row;
+ final field = box.field;
+ final query = box.query;
+ final selection = _queryText.selection;
+ bool stillEditing() =>
+ mounted &&
+ !box.locked &&
+ _row == row &&
+ box.field == field &&
+ box.query == query &&
+ _queryText.selection == selection;
+ try {
+ final data = await Clipboard.getData(Clipboard.kTextPlain);
+ if (!stillEditing() || data?.text?.isNotEmpty != true) return;
+ _insertText(data!.text!.replaceAll(RegExp(r'[\r\n]+'), ' '));
+ _revealRow();
+ } on PlatformException {
+ if (stillEditing()) box.warn('Could not paste. Try again.');
+ }
+ }
+
+ /// Walk the choices without changing the field's saved value.
+ void _stepMatch(int delta) {
+ // Move the highlight and nothing else. Taking each row as it is passed
+ // applies a project, which reselects its machine, which refreshes the
+ // list with a reset cursor — the highlight snapped home on every press.
+ // The doors ARE drawn, so the arrows land on them: a row you can see and
+ // cannot reach is worse than one that is not there.
+ setState(() => box.move(delta));
+ }
+
+ /// The rows that open something instead of answering the row. Being
+ /// synthetic is not enough to qualify — "Create branch x" is synthetic and
+ /// is an answer — so they are named.
+ static const _doors = {
+ NewHarnessController.browseId,
+ NewHarnessController.newProjectId,
+ NewHarnessController.repositoryId,
+ NewHarnessController.existingProjectId,
+ NewHarnessController.changeMachineId,
+ NewHarnessController.linkProfileId,
+ NewHarnessController.refreshProfilesId,
+ NewHarnessController.storeId,
+ };
+ bool _isDoor(NewHarnessOption option) => _doors.contains(option.id);
+
+ /// Clone, Open Folder and New Project are doors rather than values: they
+ /// open a prompt or the system chooser instead of answering the row.
+ void _openDoor(NewHarnessOption option) {
+ if (box.locked || !option.enabled) return;
+ box.setQuery('');
+ if (option.id == NewHarnessController.storeId) {
+ widget.onStore?.call();
+ return;
+ }
+ if (option.id == NewHarnessController.linkProfileId) {
+ widget.onLinkProfile?.call();
+ return;
+ }
+ if (option.id == NewHarnessController.refreshProfilesId) {
+ unawaited(box.refreshProfiles());
+ return;
+ }
+ if (option.id == NewHarnessController.changeMachineId) {
+ _selectRow(_Row.machine);
+ setState(() => _listOpen = true);
+ return;
+ }
+ if (option.id == NewHarnessController.browseId) {
+ unawaited(_browse());
+ return;
+ }
+ setState(() => box.accept(option));
+ }
+
+ Future<void> _browse() async {
+ final machineId = box.machineId;
+ try {
+ await widget.onBrowse?.call();
+ } on Exception {
+ if (mounted &&
+ box.machineId == machineId &&
+ box.field == NewHarnessField.project) {
+ box.warn('Could not browse folders. Try again.');
+ }
+ }
+ if (!mounted) return;
+ if (box.field == NewHarnessField.launch) _selectRow(_Row.project);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focusEditor();
+ });
+ WidgetsBinding.instance.scheduleFrame();
+ }
+
+ Future<void> _start() async {
+ if (box.busy) return;
+ switch (await box.create()) {
+ case NewHarnessOutcome.created:
+ widget.onCreated();
+ case NewHarnessOutcome.failed:
+ // The controller has said why on the line; keep the keys live.
+ if (mounted) _focus.requestFocus();
+ }
+ }
+
+ void _acceptChoice(NewHarnessOption option) {
+ if (box.locked) return;
+ if (!option.enabled) {
+ box.accept(option);
+ return;
+ }
+ if (_isDoor(option)) {
+ _openDoor(option);
+ } else {
+ final prompt = _prompts.contains(box.field);
+ box.applyOption(option);
+ box.setQuery('');
+ if (prompt) box.focusField(NewHarnessField.projectMenu);
+ setState(() => _listOpen = false);
+ }
+ _focusEditor();
+ _revealRow();
+ }
+
+ KeyEventResult _onKey(FocusNode node, KeyEvent event) {
+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
+ 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 (event.logicalKey == LogicalKeyboardKey.keyV &&
+ (HardwareKeyboard.instance.isMetaPressed ||
+ HardwareKeyboard.instance.isControlPressed)) {
+ if (event is KeyDownEvent) unawaited(_pasteQuery());
+ return KeyEventResult.handled;
+ }
+ switch (event.logicalKey) {
+ case LogicalKeyboardKey.tab:
+ // Tab is never let through. Unhandled, it runs Flutter's focus
+ // traversal, which moves focus OUT of this form and leaves it deaf
+ // to every later key — the screen looked frozen. Here it walks the
+ // rows, which is what a form's Tab is expected to do anyway.
+ _picking
+ ? _stepMatch(HardwareKeyboard.instance.isShiftPressed ? -1 : 1)
+ : _moveRow(HardwareKeyboard.instance.isShiftPressed ? -1 : 1);
+ case LogicalKeyboardKey.arrowDown:
+ // While the list is open it owns ↑↓, so the rows below do not move
+ // under a highlight the reader is using to choose.
+ _picking ? _stepMatch(1) : _moveRow(1);
+ case LogicalKeyboardKey.arrowUp:
+ _picking ? _stepMatch(-1) : _moveRow(-1);
+ case LogicalKeyboardKey.arrowRight:
+ case LogicalKeyboardKey.pageDown:
+ if (_picking && event.logicalKey == LogicalKeyboardKey.arrowRight) {
+ return KeyEventResult.ignored;
+ }
+ if (!_picking) _stepValue(1);
+ case LogicalKeyboardKey.arrowLeft:
+ case LogicalKeyboardKey.pageUp:
+ if (_picking && event.logicalKey == LogicalKeyboardKey.arrowLeft) {
+ return KeyEventResult.ignored;
+ }
+ if (!_picking) _stepValue(-1);
+ case LogicalKeyboardKey.enter:
+ case LogicalKeyboardKey.numpadEnter:
+ // Return chooses a value in the list; only the start row launches.
+ if (_picking) {
+ final option = box.selected;
+ if (option != null) {
+ _acceptChoice(option);
+ } else if (_prompts.contains(box.field)) {
+ box.accept();
+ } else {
+ box.warn('No values match this search.');
+ }
+ } else if (box.field == NewHarnessField.projectName ||
+ box.field == NewHarnessField.projectRepository) {
+ // A door's own prompt: Return finishes it rather than walking off.
+ box.accept();
+ } else if (_row == _Row.worktree && _blocked(_row) == null) {
+ setState(box.toggleWorktree);
+ } else if (_row != _Row.start) {
+ // Return opens the row's choices. It never starts an agent from a
+ // value row — only the button does that.
+ if (_blocked(_row) == null) setState(() => _listOpen = true);
+ } else if (box.query.isNotEmpty && box.matchCount == 0) {
+ // Return is never silent: nothing matched, so say so rather than
+ // starting with a value the search did not choose.
+ box.warn('Nothing matches "${box.query}".');
+ } else {
+ unawaited(_start());
+ }
+ case LogicalKeyboardKey.escape:
+ // A filter first, the screen second: Escape gives back the typed
+ // text before it closes anything, as vim's wildmenu does.
+ if (box.query.isNotEmpty) {
+ _onTyped('');
+ } else if (_prompts.contains(box.field)) {
+ setState(() {
+ _listOpen = false;
+ box.focusField(NewHarnessField.projectMenu);
+ });
+ } else if (_listOpen) {
+ setState(() => _listOpen = false);
+ } else {
+ if (box.requestDismiss()) widget.onClose();
+ }
+ case LogicalKeyboardKey.backspace:
+ if (_inputFocus.hasFocus) return KeyEventResult.ignored;
+ final query = box.query;
+ if (query.isEmpty) return KeyEventResult.ignored;
+ final selection = _queryText.selection;
+ if (!selection.isValid) return KeyEventResult.ignored;
+ if (selection.isCollapsed && selection.start > 0) {
+ final before = query.substring(0, selection.start);
+ _queryText.selection = TextSelection(
+ baseOffset: before.characters.skipLast(1).toString().length,
+ extentOffset: selection.end,
+ );
+ }
+ _insertText('');
+ default:
+ // A real text client owns native paste, selection, and composition.
+ // Only the first printable key on an idle field needs forwarding.
+ if (_inputFocus.hasFocus) return KeyEventResult.ignored;
+ // Typing narrows the highlighted item. There is no separate input to
+ // move to — the item is the input, which is what keeps this one
+ // screen. `-` and `+` are values, so they never reach here.
+ final typed = event.character;
+ if (typed == null || typed.isEmpty || typed.codeUnitAt(0) < 0x20) {
+ return KeyEventResult.ignored;
+ }
+ if (HardwareKeyboard.instance.isMetaPressed ||
+ HardwareKeyboard.instance.isControlPressed) {
+ return KeyEventResult.ignored;
+ }
+ _insertText(typed);
+ }
+ _focusEditor();
+ _revealRow();
+ return KeyEventResult.handled;
+ }
+
+ Color get _rule => Colors.white.withValues(alpha: .16);
+
+ Color get _popupFill => terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ ).background;
+
+ // Only the column that owns the keys carries Open Harness's full highlight.
+ Color get _activeFill => Colors.white.withValues(alpha: .12);
+ Color get _idleFill => Colors.white.withValues(alpha: .04);
+
+ /// One face, one size, everywhere on this screen — and it is the
+ /// TERMINAL's size, the one ⌘+ and ⌘− set, not the UI's fixed 13pt. A box
+ /// that stays small beside a zoomed terminal reads as another application.
+ TextStyle _ink([Color? color]) =>
+ terminalContentStyle(color: color ?? Colors.white);
+
+ /// Geometry follows the same size, so the columns keep their proportions.
+ double _scale = 1;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ TerminalFontScope.watch(context);
+ final scale = terminalTextScaleOf(context);
+ if (_scale != scale) {
+ _scale = scale;
+ _revealRow();
+ }
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: _isComposing,
+ actions: {
+ 'picker.more_options': () {
+ if (!box.locked && !box.checkingGit) widget.onNeedsForm?.call();
+ },
+ },
+ child: Focus(
+ key: const ValueKey('new-harness-form'),
+ focusNode: _focus,
+ onKeyEvent: _onKey,
+ child: Material(
+ elevation: 0,
+ color: _popupFill,
+ surfaceTintColor: Colors.transparent,
+ child: DefaultTextStyle.merge(
+ style: _ink(),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final wide = constraints.maxWidth >= 800 * _scale.clamp(1, 1.5);
+ if (!wide) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(
+ child: _picking ? _sidePane(compact: true) : _items(),
+ ),
+ if (!_picking &&
+ (box.error != null || box.status != null))
+ Padding(
+ padding: const EdgeInsets.all(24),
+ child: _status(),
+ ),
+ ],
+ );
+ }
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(flex: 55, child: _items()),
+ VerticalDivider(width: 1, thickness: 1, color: _rule),
+ Expanded(flex: 45, child: _sidePane()),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _items() => Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final row in _rows)
+ if (row == _Row.start) _buildButton() else _buildRow(row),
+ ],
+ ),
+ ),
+ );
+
+ /// The only action that starts an agent, distinct from the editable fields.
+ Widget _buildButton() {
+ final on = _row == _Row.start && !_picking;
+ return Semantics(
+ key: const ValueKey('new-harness-field-start'),
+ button: true,
+ selected: on,
+ enabled: !box.busy && !box.linkingProfile,
+ onTap: !box.busy && !box.linkingProfile ? _start : null,
+ child: Padding(
+ key: _itemKeys[_Row.start],
+ padding: const EdgeInsets.only(top: 24),
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ excludeFromSemantics: true,
+ onTap: !box.busy && !box.linkingProfile ? _start : null,
+ child: Container(
+ color: on ? _activeFill : Colors.transparent,
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
+ child: Row(
+ children: [
+ Icon(
+ box.checking ? LucideIcons.refreshCw300 : LucideIcons.plus300,
+ size: terminalFontStore.size * 1.25,
+ color: grid.AppPalette.swarmAccent,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ box.checking ? 'Check status' : 'New Harness',
+ style: _ink(grid.AppPalette.swarmAccent),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// Wide windows preview choices beside the fields. Narrow windows give the
+ /// active list the full width, with Escape returning to the same field.
+ Widget _sidePane({bool compact = false}) => Semantics(
+ key: const ValueKey('new-harness-choices'),
+ container: true,
+ focused: _picking,
+ label: '${_label(_row)} choices',
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (compact)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 16),
+ child: InkWell(
+ canRequestFocus: false,
+ onTap: () {
+ if (_prompts.contains(box.field)) {
+ box.focusField(NewHarnessField.projectMenu);
+ }
+ box.setQuery('');
+ setState(() => _listOpen = false);
+ _focus.requestFocus();
+ _revealRow();
+ },
+ child: Row(
+ children: [
+ Icon(
+ LucideIcons.chevronLeft300,
+ size: terminalFontStore.size,
+ color: kBoxFaint,
+ ),
+ const SizedBox(width: 8),
+ Text(_label(_row), style: _ink(kBoxFaint)),
+ ],
+ ),
+ ),
+ ),
+ if (_hasChoices) ...[
+ _searchBar(),
+ const SizedBox(height: 24),
+ Flexible(child: SingleChildScrollView(child: _matchPane())),
+ ],
+ if (box.error != null || box.status != null) ...[
+ const SizedBox(height: 24),
+ _status(),
+ ],
+ ],
+ ),
+ ),
+ );
+
+ Widget _status() => Semantics(
+ liveRegion: true,
+ child: Text(
+ box.error ?? box.status!,
+ key: const ValueKey('new-harness-status'),
+ style: _ink(box.error != null ? Colors.orangeAccent : kBoxFaint),
+ ),
+ );
+
+ /// Whether this row has anything to list. Worktree is a boolean and the
+ /// button is an action, so their columns stay empty rather than inventing
+ /// something to fill them.
+ bool get _hasChoices => _fieldOf(_row) != null && _blocked(_row) == null;
+
+ /// The choices, in the order the controller already ranks them: the three
+ /// doors first — New Project, Open Folder, Clone — then the recents and
+ /// matches under a gap. The highlight opens on the first real project, the
+ /// fourth row, so the doors are visible without being in the way.
+ Widget _matchPane() {
+ final shown = box.options;
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (shown.isEmpty && !_prompts.contains(box.field))
+ Text('No matches', style: _ink(kBoxFaint)),
+ for (var i = 0; i < shown.length; i++) ...[
+ _matchRow(shown[i]),
+ // One gap where the doors end and the projects begin.
+ if (shown[i].synthetic &&
+ i + 1 < shown.length &&
+ !shown[i + 1].synthetic)
+ const SizedBox(height: 8),
+ ],
+ ],
+ );
+ }
+
+ /// A prompt people can see, because "type to search" printed in a key
+ /// guide is a sentence nobody reads. fzf's `>` rather than a labelled box:
+ /// there is no second place for the caret to be, so it needs no border.
+ /// 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 => _prompts.contains(box.field)
+ ? box.hint
+ : 'Search ${_label(_row).toLowerCase()}';
+
+ Widget _searchBar() {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ SizedBox(
+ width: terminalFontStore.size * 1.25,
+ child: Text(
+ '>',
+ key: const ValueKey('new-harness-prompt'),
+ textAlign: TextAlign.center,
+ style: _ink(_picking ? Colors.white : kBoxFaint),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Actions(
+ actions: {
+ PasteTextIntent: CallbackAction<PasteTextIntent>(
+ onInvoke: (_) {
+ unawaited(_pasteQuery());
+ return null;
+ },
+ ),
+ },
+ child: TextField(
+ key: const ValueKey('new-harness-query'),
+ controller: _queryText,
+ focusNode: _inputFocus,
+ readOnly: box.locked,
+ showCursor: _picking,
+ style: _ink(Colors.white),
+ cursorColor: Colors.white70,
+ cursorWidth: terminalFontStore.size * .62,
+ cursorRadius: Radius.zero,
+ cursorOpacityAnimates: false,
+ autocorrect: false,
+ enableSuggestions: false,
+ onChanged: _onTyped,
+ onTap: () {
+ setState(() => _listOpen = true);
+ _revealRow();
+ },
+ onTapOutside: (_) {},
+ decoration: InputDecoration(
+ hintText: '${_picking ? ' ' : ''}$_promptHint',
+ hintStyle: _ink(kBoxFaint),
+ hintMaxLines: 1,
+ isDense: true,
+ isCollapsed: true,
+ constraints: const BoxConstraints(),
+ contentPadding: EdgeInsets.zero,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ filled: false,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _matchRow(NewHarnessOption option) {
+ final on = identical(option, box.selected);
+ final local =
+ box.field == NewHarnessField.machine &&
+ box.app.stateOf(option.id)?.isLocalMachine == true;
+ final actionIcon = switch (option.id) {
+ NewHarnessController.repositoryId => LucideIcons.gitBranch300,
+ NewHarnessController.existingProjectId ||
+ NewHarnessController.browseId => LucideIcons.folder300,
+ NewHarnessController.newProjectId => LucideIcons.plus300,
+ _ => null,
+ };
+ final showDetail =
+ (_row == _Row.agent || _row == _Row.profile) &&
+ option.detail.isNotEmpty &&
+ !_isDoor(option);
+ final title = Text(
+ option.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: _ink(
+ !_picking || !option.enabled
+ ? kBoxFaint
+ : option.synthetic
+ ? grid.AppPalette.swarmAccent
+ : on
+ ? Colors.white
+ : Colors.white70,
+ ),
+ );
+ return Semantics(
+ key: ValueKey('new-harness-option-${option.id}'),
+ selected: on,
+ enabled: option.enabled && !box.locked,
+ button: _isDoor(option),
+ child: InkWell(
+ canRequestFocus: false,
+ onTap: !box.locked ? () => _acceptChoice(option) : null,
+ child: Container(
+ key: on ? _choiceKey : null,
+ color: on && _picking ? _activeFill : Colors.transparent,
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (actionIcon != null) ...[
+ Icon(
+ actionIcon,
+ size: terminalFontStore.size * 1.25,
+ color: _picking ? grid.AppPalette.swarmAccent : kBoxFaint,
+ ),
+ const SizedBox(width: 12),
+ ] else if (option.engine != null) ...[
+ EngineMark(
+ engine: option.engine,
+ size: terminalFontStore.size * 1.25,
+ ),
+ const SizedBox(width: 12),
+ ],
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (local)
+ Row(
+ children: [
+ Expanded(child: title),
+ const SizedBox(width: 12),
+ Text(
+ 'This machine',
+ style: _ink(
+ kBoxFaint,
+ ).copyWith(fontSize: terminalFontStore.size * .85),
+ ),
+ ],
+ )
+ else
+ title,
+ if (showDetail) ...[
+ const SizedBox(height: 4),
+ Text(
+ option.detail,
+ style: _ink(kBoxFaint),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ void _selectRow(_Row row) {
+ if (box.locked) return;
+ setState(() {
+ _row = row;
+ _listOpen = false;
+ });
+ box.setQuery('');
+ _syncField();
+ _focus.requestFocus();
+ _focusEditor();
+ _revealRow();
+ }
+
+ void _activateRow(_Row row) {
+ _selectRow(row);
+ if (row == _Row.worktree) {
+ box.toggleWorktree();
+ } else {
+ setState(() => _listOpen = true);
+ }
+ _focusEditor();
+ _revealRow();
+ }
+
+ Widget _buildRow(_Row row) {
+ final highlighted = row == _row;
+ final blocked = _blocked(row);
+ final value = blocked ?? _value(row);
+ final ink = blocked != null || _picking
+ ? kBoxFaint
+ : highlighted
+ ? Colors.white
+ : Colors.white70;
+ return Semantics(
+ key: ValueKey('new-harness-field-${row.name}'),
+ label: '${_label(row)}, $value',
+ selected: highlighted,
+ enabled: blocked == null && !box.locked,
+ onTap: blocked == null && !box.locked ? () => _activateRow(row) : null,
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ excludeFromSemantics: true,
+ onTap: blocked == null && !box.locked ? () => _activateRow(row) : null,
+ child: Container(
+ key: _itemKeys[row],
+ color: highlighted
+ ? (_picking ? _idleFill : _activeFill)
+ : Colors.transparent,
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final label = Text(_label(row), style: _ink(kBoxFaint));
+ final content = Text(
+ value,
+ style: _ink(ink),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ );
+ if (constraints.maxWidth < 360 * _scale) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [label, const SizedBox(height: 4), content],
+ );
+ }
+ return Row(
+ children: [
+ SizedBox(width: 120 * _scale, child: label),
+ const SizedBox(width: 16),
+ Expanded(child: content),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/prompt_context.dart b/desktop/lib/widgets/prompt_context.dart
index 7deca1351..6dd0c2acb 100644
--- a/desktop/lib/widgets/prompt_context.dart
+++ b/desktop/lib/widgets/prompt_context.dart
@@ -19,12 +19,14 @@ class PromptContextView extends StatefulWidget {
this.prefs,
this.store,
this.matches = const [],
+ this.textStyle,
});
final PromptContext contextData;
final PromptPrefs? prefs;
final AppearancePrefsStore? store;
- double get size => grid.AppType.monoLabelSize;
+ final TextStyle? textStyle;
+ double get size => textStyle?.fontSize ?? grid.AppType.monoLabelSize;
final Iterable<SearchFieldMatch> matches;
@override
@@ -83,12 +85,14 @@ class _PromptContextViewState extends State<PromptContextView> {
);
}
- /// Breadcrumbs name places a person copies, so they are mono, one step
- /// under the terminal's own text.
- static TextStyle _style(Color tone) => grid.AppType.monoLabel(
- color: tone,
- fontWeight: FontWeight.w400,
- height: 1.35,
+ /// Callers can match the terminal while shared headers keep their UI scale.
+ TextStyle _style(Color tone) => DefaultTextStyle.of(context).style.merge(
+ widget.textStyle?.copyWith(color: widget.textStyle?.color ?? tone) ??
+ grid.AppType.monoLabel(
+ color: tone,
+ fontWeight: FontWeight.w400,
+ height: 1.35,
+ ),
);
Widget _line(PromptPrefs prefs, double maxWidth, TextScaler scaler) {
@@ -167,7 +171,9 @@ class _PromptContextViewState extends State<PromptContextView> {
child: Builder(
builder: (context) {
final part = segments[index];
- final tone = prefs.color ? part.color : Colors.white60;
+ final tone =
+ widget.textStyle?.color ??
+ (prefs.color ? part.color : Colors.white60);
final width = widths?[index];
final style = _style(tone);
// A folder cut short keeps both ends, the way editors
@@ -233,9 +239,9 @@ class _PromptContextViewState extends State<PromptContextView> {
/// Folders shorten in the middle; everything else at the end.
static bool _middle(String label) => label == 'Project' || label.isEmpty;
- /// How much of the line each segment's text gets when it does not all fit:
- /// the project gives way first, then the machine, and the branch last, each keeping a few characters; narrower than that, all
- /// alike. Null when everything fits.
+ /// Size each segment by its content, then shrink only when the whole line
+ /// does not fit. The project gives way first, then the machine, and the
+ /// branch last. Null only when the line has no width constraint.
List<double>? _fit(
List<
({String label, String value, String ascii, IconData? icon, Color color})
@@ -264,7 +270,9 @@ class _PromptContextViewState extends State<PromptContextView> {
chrome += powerline ? (index == 0 ? 6 : 12) + 12 : (index > 0 ? 12 : 0);
}
var excess = natural.fold(chrome, (sum, width) => sum + width) - maxWidth;
- if (excess <= 0) return null;
+ // Equal Flexible shares would truncate a long branch even when shorter
+ // machine/project labels leave enough room for the whole line.
+ if (excess <= 0) return natural;
final widths = [...natural];
final floor = _measure('mmmmmm…', style, scaler);
const order = ['', 'Project', 'Machine', 'Branch', 'Harness'];
@@ -331,8 +339,7 @@ class _PromptContextViewState extends State<PromptContextView> {
class _Clipped extends StatelessWidget {
const _Clipped({required this.clip, required this.child});
- /// Only with every segment at a fixed width; a line that fits is laid out
- /// as it always was.
+ /// Only bounded lines with measured segment widths can be safely clipped.
final bool clip;
final Widget child;
@override
@@ -349,8 +356,8 @@ class _Clipped extends StatelessWidget {
: child;
}
-/// A segment at the width [PromptContextView._fit] gave it, or sharing the
-/// line's width with the others when it did not give one.
+/// A segment at the width [PromptContextView._fit] gave it, or unconstrained
+/// when the surrounding line has no width limit.
class _Sized extends StatelessWidget {
const _Sized({required this.fixed, required this.child});
final bool fixed;
diff --git a/desktop/lib/widgets/remote_folder_picker.dart b/desktop/lib/widgets/remote_folder_picker.dart
index e041a46f9..c326764fe 100644
--- a/desktop/lib/widgets/remote_folder_picker.dart
+++ b/desktop/lib/widgets/remote_folder_picker.dart
@@ -1,5 +1,7 @@
import 'dart:math' as math;
+import '../terminal/terminal_text.dart';
+
import '../shared/widgets/labeled_field.dart';
import 'package:flutter/material.dart';
@@ -19,12 +21,30 @@ Future<String?> showRemoteFolderPicker(
required AppNotifier notifier,
required String machineId,
String? initialPath,
+ bool terminal = false,
}) => showAppDialog<String>(
context: context,
- builder: (context) => _RemoteFolderPickerDialog(
- notifier: notifier,
- machineId: machineId,
- initialPath: initialPath,
+ builder: (context) => ListenableBuilder(
+ listenable: terminalFontStore,
+ builder: (context, _) {
+ final theme = Theme.of(context);
+ return Theme(
+ data: terminal
+ ? theme.copyWith(
+ textTheme: theme.textTheme.apply(
+ fontSizeFactor:
+ terminalFontStore.size / grid.AppType.monoSize,
+ ),
+ )
+ : theme,
+ child: _RemoteFolderPickerDialog(
+ notifier: notifier,
+ machineId: machineId,
+ initialPath: initialPath,
+ terminal: terminal,
+ ),
+ );
+ },
),
);
@@ -33,11 +53,13 @@ class _RemoteFolderPickerDialog extends StatefulWidget {
required this.notifier,
required this.machineId,
this.initialPath,
+ this.terminal = false,
});
final AppNotifier notifier;
final String machineId;
final String? initialPath;
+ final bool terminal;
@override
State<_RemoteFolderPickerDialog> createState() =>
@@ -255,7 +277,16 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
final scale = MediaQuery.textScalerOf(context);
- _rowHeight = math.max(36, scale.scale(grid.AppType.bodySize) * 1.35 + 16);
+ _rowHeight = math.max(
+ 36,
+ scale.scale(
+ widget.terminal
+ ? terminalFontStore.size
+ : grid.AppType.bodySize,
+ ) *
+ 1.35 +
+ 16,
+ );
final listHeight =
(MediaQuery.sizeOf(context).height - 320 - scale.scale(50)).clamp(
120.0,
@@ -323,7 +354,10 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
- const FieldLabel('Folder path'),
+ if (widget.terminal)
+ Text('Folder path', style: terminalTextStyle())
+ else
+ const FieldLabel('Folder path'),
Focus(
onKeyEvent: (node, event) {
if (event is KeyDownEvent &&
@@ -347,9 +381,9 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
focusNode: _locationFocus,
autofocus: true,
// A path: typed and pasted, so set to be copied exactly.
- style: grid.AppType.mono(
- color: grid.AppPalette.textPrimary,
- ),
+ 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(
diff --git a/desktop/lib/widgets/swarm_search_input.dart b/desktop/lib/widgets/swarm_search_input.dart
index 262f26b43..b52791435 100644
--- a/desktop/lib/widgets/swarm_search_input.dart
+++ b/desktop/lib/widgets/swarm_search_input.dart
@@ -30,6 +30,7 @@ class SwarmSearchInput extends StatelessWidget {
this.height,
this.prompt,
this.terminal = false,
+ this.bios = false,
});
final Key inputKey;
@@ -54,12 +55,13 @@ class SwarmSearchInput extends StatelessWidget {
final double? height;
/// The typed text and the hint; the search glyph grows with it.
- double get fontSize => grid.AppType.monoSize;
+ double get fontSize => bios ? terminalFontStore.size : grid.AppType.monoSize;
final String? prompt;
/// Plain monospace input in a TerminalBox, without a decorative search glyph.
/// Mode prefixes belong to the editable buffer.
final bool terminal;
+ final bool bios;
@override
Widget build(BuildContext context) {
@@ -75,6 +77,9 @@ class SwarmSearchInput extends StatelessWidget {
Widget _buildInput(BuildContext context) {
final open = search != null;
final terminalStyle = terminal || prompt != null;
+ final style = bios
+ ? terminalContentStyle(color: Colors.white)
+ : boxMonoStyle();
final border = OutlineInputBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(rounded ? (prominent ? 32 : 28) : 12),
@@ -100,10 +105,11 @@ class SwarmSearchInput extends StatelessWidget {
onTapAlwaysCalled: true,
onTapOutside: onTapOutside == null ? null : (_) => onTapOutside!(),
onChanged: onChanged,
- style: terminalStyle
- ? boxMonoStyle()
- : grid.AppType.mono(color: Colors.white),
- cursorColor: grid.AppPalette.swarmAccent,
+ style: terminalStyle ? style : grid.AppType.mono(color: Colors.white),
+ cursorColor: bios ? Colors.white70 : grid.AppPalette.swarmAccent,
+ cursorWidth: bios ? terminalFontStore.size * .62 : 2,
+ cursorRadius: Radius.zero,
+ cursorOpacityAnimates: !bios,
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
hintText:
@@ -113,18 +119,30 @@ class SwarmSearchInput extends StatelessWidget {
? search!.hint
: hintText ?? search?.hint ?? kSwarmSearchHint,
hintStyle: terminalStyle
- ? boxMonoStyle(color: kBoxFaint)
+ ? style.copyWith(color: kBoxFaint)
: grid.AppType.mono(color: Colors.white60),
hintMaxLines: 1,
prefixIcon: prompt != null
? Padding(
- padding: const EdgeInsets.only(left: 14, right: 10),
+ padding: EdgeInsets.only(
+ left: bios ? 28 : 14,
+ right: bios ? 12 : 10,
+ ),
child: Center(
widthFactor: 1,
heightFactor: 1,
- child: Text(
- prompt!,
- style: boxMonoStyle(color: grid.AppPalette.swarmAccent),
+ child: SizedBox(
+ width: bios ? terminalFontStore.size * 1.25 : null,
+ child: Text(
+ prompt!,
+ key: const ValueKey('swarm-search-prompt'),
+ textAlign: TextAlign.center,
+ style: style.copyWith(
+ color: bios
+ ? Colors.white
+ : grid.AppPalette.swarmAccent,
+ ),
+ ),
),
),
)
diff --git a/desktop/lib/widgets/swarm_search_preview.dart b/desktop/lib/widgets/swarm_search_preview.dart
index edd917389..21357befd 100644
--- a/desktop/lib/widgets/swarm_search_preview.dart
+++ b/desktop/lib/widgets/swarm_search_preview.dart
@@ -182,7 +182,7 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
controller: _scroll,
padding: EdgeInsets.all(
widget.terminal
- ? 12
+ ? 24
: widget.compactHeader
? 16
: 24,
@@ -198,12 +198,19 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
Text(
row.title,
// The list leads the eye; this confirms it.
- style: AppType.monoLabel(
- fontWeight: FontWeight.w600,
- ),
+ style: widget.terminal
+ ? terminalContentStyle()
+ : AppType.monoLabel(
+ fontWeight: FontWeight.w600,
+ ),
),
const SizedBox(height: 6),
- Text(row.detail, style: _muted),
+ Text(
+ row.detail,
+ style: widget.terminal
+ ? terminalContentStyle(color: kBoxFaint)
+ : _muted,
+ ),
// Nothing exists yet behind the create row, so
// there is no session to be missing text from.
if (agents.isEmpty && !row.isCreate)
@@ -211,7 +218,11 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
padding: EdgeInsets.only(top: 24),
child: Text(
'No recent session text available.',
- style: _muted,
+ style: widget.terminal
+ ? terminalContentStyle(
+ color: kBoxFaint,
+ )
+ : _muted,
),
),
],
@@ -239,7 +250,7 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
controller: _scroll,
padding: EdgeInsets.all(
widget.terminal
- ? 12
+ ? 24
: widget.compactHeader
? 16
: 24,
@@ -282,9 +293,9 @@ class _AgentPreview extends StatelessWidget {
@override
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
- final muted = terminal ? boxMonoStyle(color: kBoxFaint) : _muted;
+ final muted = terminal ? terminalContentStyle(color: kBoxFaint) : _muted;
final body = terminal
- ? boxMonoStyle(color: const Color(0xffe1e1e4))
+ ? terminalContentStyle(color: const Color(0xffe1e1e4))
: _body;
Widget section(String label, String text, {int? maxLines}) =>
_Section(label, text, maxLines: maxLines, terminal: terminal);
@@ -333,14 +344,14 @@ class _AgentPreview extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (terminal) ...[
- Text(agent.displayName, style: boxMonoStyle(weight: FontWeight.w600)),
- const SizedBox(height: 4),
+ Text(agent.displayName, style: terminalContentStyle()),
+ const SizedBox(height: 8),
Text.rich(
TextSpan(
children: [
TextSpan(
text: '$state ',
- style: TextStyle(color: color),
+ style: const TextStyle(color: kBoxFaint),
),
TextSpan(
text:
@@ -375,7 +386,7 @@ class _AgentPreview extends StatelessWidget {
),
if (dense) ...[
const SizedBox(width: 10),
- Text(state, style: AppType.monoMeta(color: color)),
+ Text(state, style: boxMonoStyle(color: color)),
],
],
),
@@ -403,7 +414,7 @@ class _AgentPreview extends StatelessWidget {
color: color,
),
const SizedBox(width: 5),
- Text(state, style: AppType.monoMeta(color: color)),
+ Text(state, style: boxMonoStyle(color: color)),
],
),
),
@@ -438,7 +449,7 @@ class _AgentPreview extends StatelessWidget {
] else ...[
SizedBox(
height: terminal
- ? 8
+ ? 24
: dense
? 16
: 26,
@@ -471,7 +482,7 @@ class _AgentPreview extends StatelessWidget {
],
),
),
- SizedBox(height: terminal ? 14 : 24),
+ const SizedBox(height: 24),
],
if (working) ...[
if (request != null) section(requestLabel, request),
@@ -504,7 +515,7 @@ class _AgentPreview extends StatelessWidget {
),
for (final text in record!.earlierResponses)
Padding(
- padding: EdgeInsets.only(top: terminal ? 6 : 10),
+ padding: EdgeInsets.only(top: terminal ? 12 : 10),
child: Text(
_displayText(text),
maxLines: 4,
@@ -528,7 +539,7 @@ class _AgentPreview extends StatelessWidget {
if (project?.cwd case final cwd?) Text(cwd, style: muted),
if (project?.branch case final branch?)
Padding(
- padding: const EdgeInsets.only(top: 4),
+ padding: EdgeInsets.only(top: terminal ? 8 : 4),
child: Row(
children: [
const Icon(
@@ -543,7 +554,7 @@ class _AgentPreview extends StatelessWidget {
),
if (record?.receivedAt case final at?)
Padding(
- padding: const EdgeInsets.only(top: 8),
+ padding: EdgeInsets.only(top: terminal ? 12 : 8),
child: Text(
'${offline || record?.unavailable == true ? 'Saved text · ' : ''}Received ${TimeOfDay.fromDateTime(at).format(context)}',
style: muted,
@@ -564,20 +575,20 @@ class _Section extends StatelessWidget {
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
return Padding(
- padding: EdgeInsets.only(bottom: terminal ? 8 : 24),
+ padding: const EdgeInsets.only(bottom: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: terminal
- ? boxMonoStyle(color: kBoxFaint)
+ ? terminalContentStyle(color: kBoxFaint)
: _muted.copyWith(fontWeight: FontWeight.w500),
),
- SizedBox(height: terminal ? 4 : 7),
+ SizedBox(height: terminal ? 8 : 7),
Text(
_displayText(text),
- style: terminal ? boxMonoStyle() : _body,
+ style: terminal ? terminalContentStyle() : _body,
maxLines: maxLines,
overflow: maxLines == null ? null : TextOverflow.ellipsis,
),
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 892693bc3..2843a98cb 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'swarm_search_field.dart';
import 'package:flutter/material.dart';
@@ -17,6 +19,8 @@ import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
import '../state/swarm_navigation.dart';
import '../state/swarm_search.dart';
+import '../state/harness_sessions.dart' show harnessActivityAge;
+import '../shared/theme/prompt_style.dart';
import '../store/store_mark.dart';
import 'engine_identity.dart';
import 'swarm_icon.dart';
@@ -83,7 +87,7 @@ class _SwarmHistoryState extends State<_SwarmHistory> {
Spacer(),
Text(
'This session',
- style: grid.AppType.monoMeta(color: Colors.white54),
+ style: boxMonoStyle(color: Colors.white54),
),
],
),
@@ -195,10 +199,12 @@ class SwarmSearchKeys extends StatelessWidget {
'picker.cancel': dismiss,
// Tab is a picker command now (New Harness completes paths with
// it); a matched key is consumed, so here it still walks the focus.
- 'picker.complete': () =>
- FocusManager.instance.primaryFocus?.nextFocus(),
- 'picker.complete_back': () =>
- FocusManager.instance.primaryFocus?.previousFocus(),
+ 'picker.complete': () => search?.setupLayout == true
+ ? move(1)
+ : FocusManager.instance.primaryFocus?.nextFocus(),
+ 'picker.complete_back': () => search?.setupLayout == true
+ ? move(-1)
+ : FocusManager.instance.primaryFocus?.previousFocus(),
if (search != null)
for (var row = 1; row <= 9; row++)
'picker.pick_$row': () => run(() {
@@ -361,6 +367,8 @@ class SwarmSearchResults extends StatefulWidget {
this.sideBySideMinWidth = 800,
this.fitRows = false,
this.terminal = false,
+ this.bios = false,
+ this.header,
});
final SwarmSearchController search;
final ValueChanged<SwarmSearchSelection> onChoose;
@@ -371,6 +379,8 @@ class SwarmSearchResults extends StatefulWidget {
/// taken their actual heights, including larger text and warning messages.
final bool fitRows;
final bool terminal;
+ final bool bios;
+ final Widget? header;
@override
State<SwarmSearchResults> createState() => _SwarmSearchResultsState();
}
@@ -384,6 +394,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
final _announcer = BoxAnnouncer();
String? _announced;
final _scroll = ScrollController();
+ Timer? _activityClock;
final _resultsKey = GlobalKey();
double _rowHeight = 56;
bool _revealScheduled = false;
@@ -423,6 +434,11 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
@override
void initState() {
super.initState();
+ if (widget.bios) {
+ _activityClock = Timer.periodic(const Duration(minutes: 1), (_) {
+ if (mounted) setState(() {});
+ });
+ }
search.addListener(_changed);
terminalFontStore.addListener(_fontChanged);
_lastPage = search.resultPage.value;
@@ -521,6 +537,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
@override
void dispose() {
+ _activityClock?.cancel();
search.removeListener(_changed);
terminalFontStore.removeListener(_fontChanged);
search.resultPage.removeListener(_pageResults);
@@ -564,6 +581,15 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
terminal: widget.terminal,
stacked: stacked,
);
+ if (widget.bios) {
+ // Two terminal lines, a 4 px title/context gap, and 12 px above
+ // and below each session keep adjacent entries distinct.
+ _rowHeight =
+ scale.scale(terminalFontStore.size) *
+ terminalFontStore.value.height *
+ 2 +
+ 28;
+ }
final height = widget.fitRows
? _fittedHeight(
constraints,
@@ -588,6 +614,9 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
final highlighted = index == search.cursor;
final canSubmit = search.canSubmit(row);
final alreadyHere = search.alreadyHere(row);
+ final activityAge = widget.bios && row.lastActivityAt != null
+ ? harnessActivityAge(row.lastActivityAt, DateTime.now())
+ : null;
final presentation = (
row,
highlighted,
@@ -601,6 +630,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
acceptKey,
widget.terminal,
stacked,
+ activityAge,
);
final previous = _rowWidgets.remove(row.id);
if (previous?.presentation == presentation) {
@@ -629,12 +659,28 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
dense: true,
visualDensity: VisualDensity.compact,
minVerticalPadding: 0,
- horizontalTitleGap: 10,
+ horizontalTitleGap: widget.bios ? 12 : 10,
minLeadingWidth: 20,
- contentPadding: const EdgeInsets.symmetric(horizontal: 10),
+ contentPadding: EdgeInsets.symmetric(
+ horizontal: widget.bios ? 16 : 10,
+ ),
// The dock uses its full-row highlight for
// selection; prefixes only appear in the input.
- leading: widget.terminal
+ leading: widget.bios
+ ? row.isCreate
+ ? Icon(
+ LucideIcons.plus300,
+ size: terminalFontStore.size * 1.25,
+ color: grid.AppPalette.swarmAccent,
+ )
+ : row.agentId != null
+ ? EngineMark(
+ engine: row.engine,
+ size: terminalFontStore.size * 1.25,
+ enabled: canSubmit,
+ )
+ : null
+ : widget.terminal
? null
: Row(
mainAxisSize: MainAxisSize.min,
@@ -679,8 +725,13 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
row: row,
terminal: widget.terminal,
stacked: stacked,
+ bios: widget.bios,
+ highlighted: highlighted,
+ activityAge: activityAge,
),
- trailing: widget.terminal
+ trailing: widget.bios
+ ? null
+ : widget.terminal
? (highlighted
? Text(
acceptKey ?? '',
@@ -696,7 +747,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
: alreadyHere && search.placement == null
? Text(
'Already added',
- style: grid.AppType.monoMeta(color: Colors.white54),
+ style: boxMonoStyle(color: Colors.white54),
)
: highlighted
? ConstrainedBox(
@@ -722,7 +773,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
? null
: Text(
row.shortcut!,
- style: grid.AppType.monoMeta(color: Colors.white60),
+ style: boxMonoStyle(color: Colors.white60),
),
onTap: canSubmit ? () => _submit(row) : null,
);
@@ -737,12 +788,30 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
_focusResult(row.id);
}
},
- child: BoxRowHighlight(
- terminal: widget.terminal,
- highlighted: highlighted,
- accent: grid.AppPalette.swarmAccent,
- child: tile,
- ),
+ child: widget.bios
+ ? Material(
+ color: highlighted
+ ? Colors.white.withValues(alpha: .12)
+ : Colors.transparent,
+ child: row.isCreate
+ ? DecoratedBox(
+ decoration: BoxDecoration(
+ border: Border(
+ bottom: BorderSide(
+ color: Colors.white.withValues(alpha: .12),
+ ),
+ ),
+ ),
+ child: tile,
+ )
+ : tile,
+ )
+ : BoxRowHighlight(
+ terminal: widget.terminal,
+ highlighted: highlighted,
+ accent: grid.AppPalette.swarmAccent,
+ child: tile,
+ ),
),
);
if (_rowWidgets.length > 48) {
@@ -760,6 +829,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
label: 'Search results',
child: Column(
children: [
+ ?widget.header,
Expanded(
child: search.rows.isEmpty
? Center(
@@ -794,8 +864,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
policy: OrderedTraversalPolicy(),
child: ListView.builder(
key: const ValueKey('swarm-search-result-list'),
- padding: const EdgeInsets.symmetric(
- horizontal: 8,
+ padding: EdgeInsets.symmetric(
+ horizontal: widget.bios ? 12 : 8,
),
controller: _scroll,
// The dock only shows a few rows. Building the
@@ -851,7 +921,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
],
),
);
- final preview = search.hasPreview
+ final preview = search.hasPreview && (!widget.bios || sideBySide)
? SwarmSearchPreview(
key: const ValueKey('swarm-search-preview'),
search: search,
@@ -859,9 +929,10 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
terminal: widget.terminal,
)
: null;
- final content = preview == null
- ? results
- : sideBySide
+ // Side by side, the two columns keep their share whether or not
+ // there is anything to preview: a list that widened every time the
+ // preview went away made the rows move under the reader's eye.
+ final content = sideBySide && (widget.bios || preview != null)
? Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -875,9 +946,11 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
)
else
const SizedBox(width: 8),
- Expanded(flex: 4, child: preview),
+ Expanded(flex: 4, child: preview ?? const SizedBox()),
],
)
+ : preview == null
+ ? results
: search.resultsFromBottom
? Column(
children: [
@@ -955,12 +1028,18 @@ class _SearchRowContent extends StatefulWidget {
required this.row,
required this.terminal,
required this.stacked,
+ this.bios = false,
+ this.highlighted = false,
+ this.activityAge,
});
final SwarmSearchController search;
final SwarmDestination row;
final bool terminal;
final bool stacked;
+ final bool bios;
+ final bool highlighted;
+ final String? activityAge;
@override
State<_SearchRowContent> createState() => _SearchRowContentState();
@@ -1005,6 +1084,72 @@ class _SearchRowContentState extends State<_SearchRowContent> {
grid.AppTheme.watch(context);
final row = widget.row;
final matches = searchResultMatches(row, swarmQueryTerms(_query.$1));
+ if (widget.bios) {
+ final style = terminalContentStyle(
+ color: row.isCreate
+ ? grid.AppPalette.swarmAccent
+ : widget.highlighted
+ ? Colors.white
+ : Colors.white70,
+ );
+ final data = row.promptContext;
+ return Semantics(
+ label: row.isCreate
+ ? 'New Harness'
+ : '${row.title}\n${row.terminalDetail ?? row.detail}'
+ '${widget.activityAge == null ? '' : ', Last active ${widget.activityAge} ago'}',
+ excludeSemantics: true,
+ child: row.isCreate
+ ? Text('New Harness', style: style)
+ : Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: SearchResultText(
+ row.title,
+ matches: matches.where((match) => match.title),
+ style: style,
+ ),
+ ),
+ if (widget.activityAge case final age?) ...[
+ const SizedBox(width: 12),
+ Tooltip(
+ message:
+ 'Last active ${row.lastActivityAt!.toLocal()}',
+ child: Text(
+ age,
+ style: terminalContentStyle(color: Colors.white38),
+ ),
+ ),
+ ],
+ ],
+ ),
+ if (data != null || row.detail.isNotEmpty)
+ const SizedBox(height: 4),
+ if (data != null)
+ PromptContextView(
+ contextData: PromptContext(
+ machine: data.machine,
+ project: data.project,
+ branch: data.branch,
+ leading: data.leading,
+ ),
+ textStyle: terminalContentStyle(color: kBoxFaint),
+ matches: matches.where((match) => !match.title),
+ )
+ else if (row.detail.isNotEmpty)
+ SearchResultText(
+ row.detail,
+ matches: matches.where((match) => !match.title),
+ style: style.copyWith(color: kBoxFaint),
+ ),
+ ],
+ ),
+ );
+ }
final title = SearchResultText(
row.title,
matches: matches.where((match) => match.title),
@@ -1032,7 +1177,7 @@ class _SearchRowContentState extends State<_SearchRowContent> {
matches: matches.where((match) => !match.title),
style: widget.terminal
? boxMonoStyle(color: kBoxFaint)
- : grid.AppType.monoMeta(color: Colors.white54),
+ : boxMonoStyle(color: Colors.white54),
)
: null;
return widget.stacked
@@ -1093,10 +1238,7 @@ class SwarmSearchActionLabel extends StatelessWidget {
if (!compact) const SizedBox(width: 8),
if (_returnChord.hasMatch(hint)) ...[
if (hint.length > 1)
- Text(
- hint.substring(0, hint.length - 1),
- style: grid.AppType.monoMeta(),
- ),
+ Text(hint.substring(0, hint.length - 1), style: boxMonoStyle()),
const Icon(Icons.keyboard_return, size: 14),
] else
ConstrainedBox(
@@ -1105,7 +1247,7 @@ class SwarmSearchActionLabel extends StatelessWidget {
hint.replaceAll('↵', 'Return').replaceAll('⇥', 'Tab'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: grid.AppType.monoMeta(),
+ style: boxMonoStyle(),
),
),
],
@@ -1264,7 +1406,7 @@ class SwarmSearchCount extends StatelessWidget {
key: const ValueKey('swarm-search-count'),
style: terminal
? boxMonoStyle(color: kBoxFaint)
- : grid.AppType.monoMeta(color: Colors.white54),
+ : boxMonoStyle(color: Colors.white54),
),
);
},
diff --git a/desktop/test/benchmarks/common_actions_benchmark.dart b/desktop/test/benchmarks/common_actions_benchmark.dart
index 8d2f360be..8838fa62f 100644
--- a/desktop/test/benchmarks/common_actions_benchmark.dart
+++ b/desktop/test/benchmarks/common_actions_benchmark.dart
@@ -10,7 +10,7 @@ import 'package:harness/state/new_harness.dart';
import 'package:harness/settings/settings_screen.dart';
import 'package:harness/shortcuts/shortcuts_browser.dart';
import 'package:harness/terminal/terminal_binary.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import '../keymap_host_test.dart' show MemoryKeymap, key;
import '../keymap_runtime_test.dart' show mount;
@@ -51,7 +51,7 @@ void main() {
final elapsed = watch.elapsedMicroseconds;
if (i >= 0) times.add(elapsed);
if (name == 'cmd_n') {
- expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
} else if (name == 'cmd_o' || name == 'cmd_p') {
expect(
find.byKey(const ValueKey('swarm-search-input')),
diff --git a/desktop/test/benchmarks/primary_workflows_benchmark.dart b/desktop/test/benchmarks/primary_workflows_benchmark.dart
index 4086cc5e8..25ecb5501 100644
--- a/desktop/test/benchmarks/primary_workflows_benchmark.dart
+++ b/desktop/test/benchmarks/primary_workflows_benchmark.dart
@@ -12,7 +12,7 @@ import 'package:harness/core/models.dart';
import 'package:harness/state/new_harness.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/terminal_panel.dart';
import 'package:harness/ws/ws_conn.dart';
@@ -158,7 +158,7 @@ void main() {
// The rebuild instrumentation is reported separately from timings.
if (sample > 0) times.add(watch.elapsedMicroseconds);
if (name == 'cmd_n') {
- expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
} else if (name == 'cmd_o') {
expect(
find.byKey(const ValueKey('swarm-search-input')),
diff --git a/desktop/test/bios_navigation_test.dart b/desktop/test/bios_navigation_test.dart
new file mode 100644
index 000000000..40d126d00
--- /dev/null
+++ b/desktop/test/bios_navigation_test.dart
@@ -0,0 +1,160 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/state/harness_placement.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ testWidgets('Open Harness sorts by activity while filtering and refreshing', (
+ tester,
+ ) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ for (final (id, hour) in [
+ ('a1', 10),
+ ('a10', 12),
+ ('a11', 11),
+ ('a12', null),
+ ])
+ Agent(
+ id: id,
+ sessionId: 'session-$id',
+ name: 'Agent ${id.substring(1)}',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastActivityAt: hour == null ? null : DateTime.utc(2026, 9, 23, hour),
+ ),
+ ];
+ final recent = [
+ agentDestinationId('m', 'a1'),
+ agentDestinationId('m', 'a12'),
+ agentDestinationId('m', 'a10'),
+ ];
+ final search = SwarmSearchController(
+ app,
+ recent,
+ adding: true,
+ offersCreate: true,
+ activityFirst: true,
+ placement: HarnessPlacement.newTab,
+ );
+ addTearDown(search.dispose);
+ expect(search.setupLayout, isTrue);
+ expect(search.rows.first.isCreate, isTrue);
+ expect(search.rows.skip(1).map((row) => row.agentId), [
+ 'a10',
+ 'a11',
+ 'a1',
+ 'a12',
+ ]);
+ search.setQuery('Agent 1');
+ expect(
+ search.rows.where((row) => !row.isCreate).map((row) => row.agentId),
+ ['a10', 'a11', 'a1', 'a12'],
+ );
+
+ final ordinary = SwarmSearchController(app, recent, adding: true);
+ addTearDown(ordinary.dispose);
+ ordinary.setQuery('Agent 1');
+ expect(ordinary.setupLayout, isFalse);
+ expect(ordinary.rows.first.agentId, 'a1');
+
+ final selected = search.selected!.id;
+ await app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'a1',
+ 'sessionId': 'session-a1',
+ 'name': 'Agent 1',
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ 'updatedAt': '2026-09-23T12:00:30Z',
+ },
+ },
+ });
+ expect(search.rows.first.isCreate, isTrue);
+ expect(search.rows.skip(1).map((row) => row.agentId), [
+ 'a1',
+ 'a10',
+ 'a11',
+ 'a12',
+ ]);
+ expect(search.selected!.id, selected);
+
+ search.setQuery('retry-safe');
+ expect(search.rows.every((row) => row.isCreate), isTrue);
+ Future<void> response(String id) async {
+ await app.handleEventForTest('m', {
+ 'type': 'text_delta',
+ 'payload': {
+ 'agentId': id,
+ 'sessionId': 'session-$id',
+ 'content': 'The operation is now retry-safe.',
+ },
+ });
+ await tester.pump(const Duration(milliseconds: 80));
+ }
+
+ await response('a11');
+ search.move(1);
+ expect(search.selected!.agentId, 'a11');
+ await response('a1');
+ expect(search.rows.skip(1).map((row) => row.agentId), ['a1', 'a11']);
+ expect(search.selected!.agentId, 'a11');
+ search.setQuery('>');
+ expect(search.setupLayout, isFalse);
+ });
+
+ test(
+ 'activity ordering spans tabs with deterministic ties and missing times',
+ () {
+ SwarmDestination row(
+ String id,
+ String title,
+ String tab, {
+ DateTime? activity,
+ }) => SwarmDestination(
+ id: id,
+ title: title,
+ detail: '',
+ swarmId: tab,
+ current: tab == 'one',
+ lastActivityAt: activity,
+ );
+ final earlier = DateTime.utc(2026, 9, 23, 10);
+ final later = DateTime.utc(2026, 9, 23, 12);
+ final all = [
+ row('tab:one', 'First tab', 'one'),
+ row('one:a', 'Alpha harness', 'one', activity: earlier),
+ row('tab:two', 'Second tab', 'two'),
+ row('two:b', 'Beta harness', 'two', activity: later),
+ row('two:c', 'Gamma harness', 'two', activity: later),
+ ];
+ const recent = ['one:a', 'two:c', 'tab:two', 'tab:one'];
+ expect(
+ rankSwarmDestinationsByActivity(
+ all,
+ '',
+ recent: recent,
+ ).map((row) => row.id),
+ ['two:c', 'two:b', 'one:a', 'tab:two', 'tab:one'],
+ );
+ expect(
+ rankSwarmDestinationsByActivity(
+ all,
+ 'harness',
+ recent: recent,
+ ).map((row) => row.id),
+ ['two:c', 'two:b', 'one:a'],
+ );
+ expect(
+ rankSwarmDestinationsByActivity(all, 'missing', recent: recent),
+ isEmpty,
+ );
+ },
+ );
+}
diff --git a/desktop/test/box_flows_test.dart b/desktop/test/box_flows_test.dart
index c3df064b4..2f4afe141 100644
--- a/desktop/test/box_flows_test.dart
+++ b/desktop/test/box_flows_test.dart
@@ -1,16 +1,13 @@
-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';
-import 'package:harness/core/models.dart';
import 'package:harness/state/new_harness.dart';
-import 'package:harness/terminal/terminal_session.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'support/launch_menu.dart';
import 'support/mixed_agents.dart';
import 'swarm_interactions_test.dart' show chord;
import 'swarm_screen_test.dart' show mount, terminal;
@@ -25,75 +22,41 @@ class _CancelFolder extends FileSelectorPlatform {
}) => answer.future;
}
-/// The box, driven through the whole screen the way a person drives it: the
-/// flows where work could be lost or a key could quietly do nothing.
void main() {
- final line = find.byKey(const ValueKey('new-harness-input'));
- final box = find.byKey(const ValueKey('new-harness-box'));
-
setUp(() => newHarnessOpensInBox = true);
tearDown(() => newHarnessOpensInBox = false);
+ NewHarnessController box(WidgetTester tester) =>
+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller;
- Future<void> open(WidgetTester tester) async {
- final app = createApp();
- seedMixedAgents(app);
- app.adoptSessionForTest(terminal('a0', []));
- await app.addAgentToSwarm('m', 'a0');
- addTearDown(app.dispose);
- await mount(tester, app);
- }
-
- NewHarnessController creation(WidgetTester tester) =>
- tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;
-
- Future<void> editTask(WidgetTester tester) async {
- creation(tester).focusField(NewHarnessField.task);
- await tester.pump();
- }
-
- Future<void> close(WidgetTester tester) async {
- for (var i = 0; box.evaluate().isNotEmpty && i < 4; i++) {
+ testWidgets(
+ 'edited defaults and a carried task survive closing and reopening',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ app.adoptSessionForTest(terminal('a0', []));
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await openLaunchRow(tester, 'agent');
+ await typeHarnessQuery(tester, 'OpenCode');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ box(tester).task = 'Review this project';
+ box(tester).setFolder('/work/selected-before-task');
+ await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- }
- expect(box, findsNothing);
- }
-
- testWidgets('edited defaults survive Escape before a task is typed', (
- tester,
- ) async {
- final app = createApp();
- seedMixedAgents(app);
- app.adoptSessionForTest(terminal('a0', []));
- addTearDown(app.dispose);
- await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyN);
- final creation = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- creation.focusField(NewHarnessField.agent);
- await tester.pump();
- await tester.enterText(line, 'OpenCode');
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- creation.setFolder('/work/selected-before-task');
- await tester.pump();
- expect(creation.task, isEmpty);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await chord(tester, LogicalKeyboardKey.keyN);
- final restored = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- expect(restored.task, isEmpty);
- expect(restored.engine, 'opencode');
- expect(restored.project.folder, '/work/selected-before-task');
- expect(restored.field, NewHarnessField.launch);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpWidget(const SizedBox());
- });
+ await chord(tester, LogicalKeyboardKey.keyN);
+ expect(box(tester).task, 'Review this project');
+ expect(box(tester).engine, 'opencode');
+ expect(box(tester).project.folder, '/work/selected-before-task');
+ expect(app.panes, hasLength(1));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
- testWidgets('cancelling a folder browser returns to project input', (
+ testWidgets('cancelled native browsing returns the keys to the setup list', (
tester,
) async {
final app = createApp();
@@ -108,359 +71,63 @@ void main() {
addTearDown(() => FileSelectorPlatform.instance = previous);
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyN);
- final creation = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- creation.focusField(NewHarnessField.project);
- creation.move(
- creation.options.indexWhere(
+ await openLaunchRow(tester, 'project');
+ final controller = box(tester);
+ controller.move(
+ controller.options.indexWhere(
+ (row) => row.id == NewHarnessController.existingProjectId,
+ ) -
+ controller.cursor,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ controller.move(
+ controller.options.indexWhere(
(row) => row.id == NewHarnessController.browseId,
) -
- creation.cursor,
+ controller.cursor,
);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
FocusManager.instance.primaryFocus?.unfocus();
- await tester.pump();
picker.answer.complete(null);
await tester.pumpAndSettle();
- expect(creation.field, NewHarnessField.project);
- expect(tester.widget<TextField>(line).focusNode!.hasFocus, isTrue);
- await tester.enterText(line, 'payments processing');
- await tester.pump();
- expect(creation.query, 'payments processing');
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpWidget(const SizedBox());
- });
-
- testWidgets('Escape keeps what was typed for the next ⌘N', (tester) async {
- await open(tester);
- await chord(tester, LogicalKeyboardKey.keyN);
- await tester.pump();
- await editTask(tester);
- await tester.enterText(line, 'fix the flaky login test');
- await tester.pump();
- await close(tester);
- // Up to two thousand characters, and Escape is the most-pressed key here.
- await chord(tester, LogicalKeyboardKey.keyN);
- await tester.pump();
- expect(creation(tester).task, 'fix the flaky login test');
- await editTask(tester);
- expect(
- tester.widget<TextField>(line).controller!.text,
- 'fix the flaky login test',
- );
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await tester.pumpWidget(const SizedBox());
- });
-
- testWidgets('the arrows move the caret in a task of several lines', (
- tester,
- ) async {
- await open(tester);
- await chord(tester, LogicalKeyboardKey.keyN);
- await tester.pump();
- await editTask(tester);
- await tester.enterText(line, 'first line\nsecond line');
- await tester.pump();
- final field = tester.widget<TextField>(line);
- expect(field.maxLines, greaterThan(1));
- field.controller!.selection = const TextSelection.collapsed(offset: 22);
- await tester.pump();
- // Matched keys are consumed by the keymap whether or not anything handles
- // them, so on the task the arrows have to be handed to the text field.
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
- await tester.pump();
- expect(field.controller!.selection.baseOffset, lessThan(11));
- // Still the task, and nothing was made.
- expect(box, findsOneWidget);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
+ expect(FocusManager.instance.primaryFocus?.debugLabel, 'new-harness-query');
+ await typeHarnessQuery(tester, 'robotics');
+ expect(controller.query, 'robotics');
+ expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
});
- testWidgets('⌥↵ breaks the line in the task; it does not make the harness', (
- tester,
- ) async {
- await open(tester);
- await chord(tester, LogicalKeyboardKey.keyN);
- await tester.pump();
- await editTask(tester);
- await tester.enterText(line, 'one');
- await tester.pump();
- await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
- await tester.pump();
- expect(tester.widget<TextField>(line).controller!.text, 'one\n');
- expect(box, findsOneWidget);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await tester.pumpWidget(const SizedBox());
- });
-
- testWidgets('⌘N from the empty workspace picker keeps what was typed there', (
+ testWidgets('different source panes retain separate setup drafts', (
tester,
) async {
final app = createApp();
- app.machineStates['m']!.nodeOnline = true;
+ seedMixedAgents(app);
+ final first = app.adoptSessionForTest(terminal('a0', []));
+ await app.addAgentToSwarm('m', 'a1');
addTearDown(app.dispose);
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyT);
- await chord(tester, LogicalKeyboardKey.keyO);
- final start = find.byKey(const ValueKey('swarm-search-input'));
- await tester.tap(start);
- await tester.pump();
- await tester.enterText(start, 'write the docs');
+ app.focusPane(first.id);
await tester.pump();
- // ⌘N used to throw this away; only the create row kept it. (The page's
- // own New Harness button is hidden while its results are showing.)
await chord(tester, LogicalKeyboardKey.keyN);
- await tester.pump(const Duration(milliseconds: 200));
- expect(box, findsOneWidget);
- expect(creation(tester).task, 'write the docs');
- expect(creation(tester).field, NewHarnessField.launch);
- expect(creation(tester).project.generated, isNotNull);
+ box(tester).setFolder('/work/first-draft');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- await tester.pumpWidget(const SizedBox());
- });
-
- testWidgets('Tab completes an agent and Enter accepts it', (tester) async {
- await open(tester);
- await chord(tester, LogicalKeyboardKey.keyN);
- final controller = creation(tester);
- final previous = controller.engine;
- await openLaunchRow(tester, 'agent');
- await tester.pump();
- await tester.enterText(line, 'open');
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
- await tester.pump();
- expect(controller.query, 'OpenCode');
- expect(controller.engine, previous);
- expect(controller.field, NewHarnessField.agent);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ final other = app.panes.firstWhere((pane) => pane.agentId == 'a1');
+ app.focusPane(other.id);
await tester.pump();
- expect(controller.field, NewHarnessField.launch);
- expect(controller.engine, 'opencode');
- await close(tester);
- await tester.pumpWidget(const SizedBox());
- });
-
- testWidgets('a draft comes back once, not under every later ⌘N', (
- tester,
- ) async {
- await open(tester);
- Future<String> reopen() async {
- await chord(tester, LogicalKeyboardKey.keyN);
- await tester.pump();
- await editTask(tester);
- return tester.widget<TextField>(line).controller!.text;
- }
-
- expect(await reopen(), isEmpty);
- await tester.enterText(line, 'for the auth project');
+ await chord(tester, LogicalKeyboardKey.keyN);
+ expect(box(tester).project.folder, isNot('/work/first-draft'));
+ box(tester).setFolder('/work/second-draft');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- await close(tester);
- expect(await reopen(), 'for the auth project');
- // Cleared by hand and dismissed: it is gone, not resurrected.
- await tester.enterText(line, '');
+ app.focusPane(first.id);
await tester.pump();
- await close(tester);
- expect(await reopen(), isEmpty);
- await close(tester);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ expect(box(tester).project.folder, '/work/first-draft');
+ expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
});
-
- testWidgets(
- 'drafts stay with their source project and retain edited defaults',
- (tester) async {
- final app = createApp();
- addTearDown(app.dispose);
- seedMixedAgents(app);
- final auth = app.adoptSessionForTest(terminal('a0', []));
- final docs = app.adoptSessionForTest(terminal('a2', []));
- app.focusPane(auth.id);
- await mount(tester, app);
-
- Future<NewHarnessController> resume() async {
- await chord(tester, LogicalKeyboardKey.keyN);
- await editTask(tester);
- return tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- }
-
- Future<void> cancel() async {
- await close(tester);
- }
-
- var creation = await resume();
- await tester.enterText(
- line,
- ' Investigate the redirect\nDo not change code ',
- );
- await tester.pump();
- creation.focusField(NewHarnessField.mode);
- creation.accept(
- const NewHarnessOption(id: 'readOnly', title: 'Read only'),
- );
- creation.focusField(NewHarnessField.machine);
- creation.accept(
- const NewHarnessOption(id: 'studio', title: 'iMac · Office'),
- );
- creation.setFolder('/work/isolated-auth');
- creation.focusField(NewHarnessField.task);
- await tester.pump();
- await cancel();
-
- // Starting in another project must never put the auth task one Return
- // away from running there. That project keeps its own in-progress task.
- app.focusPane(docs.id);
- creation = await resume();
- expect(creation.task, isEmpty);
- expect(creation.machineId, 'm');
- expect(creation.project.folder, '/work/release-notes');
- await tester.enterText(line, 'Explain the release notes');
- await tester.pump();
- await cancel();
-
- app.focusPane(auth.id);
- creation = await resume();
- expect(creation.task, ' Investigate the redirect\nDo not change code ');
- expect(creation.engine, 'codex');
- expect(creation.machineId, 'studio');
- expect(creation.project.folder, '/work/isolated-auth');
- expect(creation.mode, 'readOnly');
- await cancel();
-
- app.focusPane(docs.id);
- creation = await resume();
- expect(creation.task, 'Explain the release notes');
- expect(creation.machineId, 'm');
- expect(creation.project.folder, '/work/release-notes');
- await cancel();
- await tester.pump(const Duration(milliseconds: 60));
- await tester.pumpWidget(const SizedBox());
- },
- );
-
- for (final otherMachine in [false, true]) {
- testWidgets(
- 'same-project drafts are isolated across ${otherMachine ? 'machines' : 'agents'}',
- (tester) async {
- final app = createApp();
- addTearDown(app.dispose);
- seedMixedAgents(app);
- final sourceAgent = app.machineStates['m']!.agents.first;
- final machineId = otherMachine ? 'studio' : 'm';
- final agentId = otherMachine ? sourceAgent.id : 'a1';
- app.machineStates[machineId]!.agents = [
- if (!otherMachine) sourceAgent,
- Agent(
- id: agentId,
- name: 'Another feature',
- engine: sourceAgent.engine,
- terminalAvailable: true,
- project: sourceAgent.project,
- ),
- ];
- final source = app.adoptSessionForTest(terminal(sourceAgent.id, []));
- final other = app.adoptSessionForTest(
- TerminalSession(
- machineId: machineId,
- agentId: agentId,
- agentName: 'Another feature',
- engineId: 'codex',
- send: (_, _) async => true,
- sendBinary: (_) async => true,
- )
- ..status = TerminalSessionStatus.controlling
- ..streamId = 'other-feature',
- );
- app.focusPane(source.id);
- await mount(tester, app);
- Future<NewHarnessController> resume() async {
- await chord(tester, LogicalKeyboardKey.keyN);
- await editTask(tester);
- return tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- }
-
- Future<void> cancel() async {
- await close(tester);
- }
-
- var creation = await resume();
- await tester.enterText(line, 'Inspect authentication');
- await tester.pump();
- creation.focusField(NewHarnessField.mode);
- creation.accept(
- const NewHarnessOption(id: 'readOnly', title: 'Read only'),
- );
- await cancel();
- app.focusPane(other.id);
- creation = await resume();
- expect(creation.task, isEmpty);
- expect(creation.machineId, machineId);
- await tester.enterText(line, 'Update feature documentation');
- await tester.pump();
- await cancel();
-
- app.focusPane(source.id);
- creation = await resume();
- expect(creation.task, 'Inspect authentication');
- expect(creation.mode, 'readOnly');
- await cancel();
- // Explicit text in search starts the requested task using the source's
- // defaults, without touching another context's draft.
- await chord(tester, LogicalKeyboardKey.keyT);
- await chord(tester, LogicalKeyboardKey.keyO);
- await tester.enterText(
- find.byKey(const ValueKey('swarm-search-input')),
- 'Implement a new redirect',
- );
- await tester.pump();
- creation = await resume();
- expect(creation.task, 'Implement a new redirect');
- expect(creation.mode, 'auto');
- expect(creation.machineId, 'm');
- expect(creation.project.folder, sourceAgent.project!.cwd);
- await cancel();
- await chord(tester, LogicalKeyboardKey.keyW);
- app.focusPane(other.id);
- expect((await resume()).task, 'Update feature documentation');
- await cancel();
- await tester.pump(const Duration(milliseconds: 60));
- await tester.pumpWidget(const SizedBox());
- },
- );
- }
-
- testWidgets(
- 'a list field chooses with Return and comes back to the launch menu',
- (tester) async {
- await open(tester);
- await chord(tester, LogicalKeyboardKey.keyN);
- await tester.pump();
- await openLaunchRow(tester, 'agent');
- await tester.pump();
- // The key guide keeps the same action while filtering choices.
- expect(find.textContaining('choose', findRichText: true), findsOneWidget);
- await tester.enterText(line, 'open');
- await tester.pump();
- expect(find.textContaining('choose', findRichText: true), findsOneWidget);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(box, findsOneWidget);
- expect(creation(tester).field, NewHarnessField.launch);
- expect(find.text('OpenCode'), findsWidgets);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await tester.pumpWidget(const SizedBox());
- },
- );
}
diff --git a/desktop/test/box_polish_test.dart b/desktop/test/box_polish_test.dart
index 60d50d6a4..e931cef79 100644
--- a/desktop/test/box_polish_test.dart
+++ b/desktop/test/box_polish_test.dart
@@ -1,399 +1,59 @@
-import 'dart:async';
-
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/new_harness.dart';
-import 'package:harness/state/swarm_search.dart';
-import 'package:harness/terminal/terminal_binary.dart';
-import 'package:harness/widgets/box_chrome.dart';
-import 'package:harness/widgets/new_harness_box.dart';
-import 'package:harness/widgets/swarm_switcher.dart';
-import 'package:harness/ws/ws_conn.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'support/launch_menu.dart';
+import 'support/mixed_agents.dart';
import 'swarm_interactions_test.dart' show chord;
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
-import 'keymap_host_test.dart' show key;
-
-class _PendingConnection extends WsConn {
- _PendingConnection()
- : super(
- wsBaseUrl: 'ws://fixture.invalid',
- autonomousEnv: 'test',
- machineId: 'm',
- accessTokenProvider: (_, _) async => '',
- onAuthFailure: (_) {},
- onEvent: (_) {},
- onStatus: (_) {},
- );
-
- final creation = Completer<Map<String, dynamic>>();
-
- @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},
- ],
- },
- 'dsh_list' => {'dsh': []},
- 'agent_create' => creation.future,
- _ => {},
- };
-}
void main() {
setUp(() => newHarnessOpensInBox = true);
tearDown(() => newHarnessOpensInBox = false);
testWidgets(
- 'dock stays aligned across search, creation, resizing and preview without changing pane geometry',
- (tester) async {
- final app = createApp();
- addTearDown(app.dispose);
- final pane = app.adoptSessionForTest(terminal('a0', []));
- await mount(tester, app);
- for (final size in [const Size(1280, 800), const Size(600, 540)]) {
- tester.view.physicalSize = size;
- await tester.pump();
- final before = tester.getRect(find.byKey(pane.cellKey));
- await chord(tester, LogicalKeyboardKey.keyO);
- void aligned(Finder panel) {
- final rect = tester.getRect(panel);
- expect(rect.left, before.left);
- expect(rect.right, before.right);
- expect(rect.bottom, before.bottom);
- expect(tester.getRect(find.byKey(pane.cellKey)), before);
- expect(tester.takeException(), isNull);
- }
-
- final search = find.byKey(const ValueKey('swarm-search-results'));
- aligned(search);
- final input = find.byKey(const ValueKey('swarm-search-input'));
- final y = tester.getRect(input).bottom;
- await tester.enterText(input, 'Agent 1');
- await tester.pump();
- aligned(search);
- expect(tester.getRect(input).bottom, closeTo(y, .001));
- await key(tester, LogicalKeyboardKey.slash, ctrl: true);
- aligned(search);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await chord(tester, LogicalKeyboardKey.keyN);
- final create = find.byKey(const ValueKey('new-harness-box'));
- aligned(create);
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
- await tester.pump();
- aligned(create);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- }
- await tester.pumpWidget(const SizedBox());
- },
- );
-
- testWidgets('all key hints stay visible as the prompt grows and wraps', (
- tester,
- ) async {
- final app = createApp();
- addTearDown(app.dispose);
- app.adoptSessionForTest(terminal('a69', []));
- await mount(tester, app);
- tester.view.physicalSize = const Size(600, 800);
- tester.platformDispatcher.textScaleFactorTestValue = 1.7;
- addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
- await tester.pump();
- await chord(tester, LogicalKeyboardKey.keyO);
-
- void checkGuide() {
- final guide = find.byType(BoxHintStrip);
- final bounds = tester.getRect(guide);
- final hints = find.descendant(of: guide, matching: find.byType(InkWell));
- expect(hints, findsWidgets);
- for (final hint in hints.evaluate()) {
- final rect = tester.getRect(find.byWidget(hint.widget));
- expect(bounds.contains(rect.topLeft), isTrue);
- expect(
- bounds.contains(rect.bottomRight - const Offset(.1, .1)),
- isTrue,
- );
- }
- expect(bounds.bottom, lessThan(800));
- expect(tester.takeException(), isNull);
- }
-
- checkGuide();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- checkGuide();
- final panel = find.byKey(const ValueKey('new-harness-box'));
- final creation = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- creation.focusField(NewHarnessField.task);
- await tester.pump();
- final originalHeight = tester.getSize(panel).height;
- await tester.enterText(
- find.byKey(const ValueKey('new-harness-input')),
- 'Fix the login flow\nKeep the session alive\nAdd regression coverage',
- );
- await tester.pump();
- expect(tester.getSize(panel).height, greaterThan(originalHeight));
- checkGuide();
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
- await tester.pump();
- checkGuide();
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpWidget(const SizedBox());
- });
-
- testWidgets(
- 'preview toggles without losing the query and Ctrl-C returns to the terminal',
+ 'setup errors remain visible and are live accessibility regions',
(tester) async {
final app = createApp();
+ seedMixedAgents(app);
+ app.adoptSessionForTest(terminal('a0', []));
addTearDown(app.dispose);
- final frames = <TerminalBinaryFrame>[];
- app.adoptSessionForTest(terminal('a69', frames));
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
- final field = find.byKey(const ValueKey('swarm-search-input'));
- final preview = find.byKey(const ValueKey('swarm-search-preview'));
- await tester.enterText(field, 'Agent 1');
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final box = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
+ box.warn('The selected folder is unavailable.');
await tester.pump();
- final search = tester
- .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
- .search;
- final editor = tester.widget<TextField>(field);
- final value = editor.controller!.value;
- final selected = search.selected;
- expect(preview, findsOneWidget);
- await key(tester, LogicalKeyboardKey.slash, ctrl: true);
- expect(preview, findsNothing);
- expect(editor.controller!.value, value);
- expect(search.selected, same(selected));
- expect(editor.focusNode!.hasPrimaryFocus, isTrue);
- await key(tester, LogicalKeyboardKey.slash, ctrl: true);
- expect(preview, findsOneWidget);
- expect(search.selected, same(selected));
- await key(tester, LogicalKeyboardKey.slash, ctrl: true);
- expect(preview, findsNothing);
- expect(search.selected, same(selected));
- // Without a preview, page keys navigate the result list, retaining input.
- final beforePage = search.cursor;
- await key(tester, LogicalKeyboardKey.pageUp);
- expect(search.cursor, greaterThan(beforePage));
- expect(editor.controller!.value, value);
- expect(editor.focusNode!.hasPrimaryFocus, isTrue);
- await key(tester, LogicalKeyboardKey.pageDown);
- expect(search.cursor, beforePage);
- await key(tester, LogicalKeyboardKey.keyC, ctrl: true);
- expect(field, findsNothing);
- expect(frames, isEmpty);
- await key(tester, LogicalKeyboardKey.keyC, ctrl: true);
- expect(frames.single.bytes, [3]);
- await tester.pumpWidget(const SizedBox());
- },
- );
-
- test('openable matches precede already-added exact matches', () async {
- final app = createApp();
- addTearDown(app.dispose);
- app.machineStates['m']!.agents = [
- for (final (id, name) in [
- ('a0', 'Auth'),
- ('a1', 'Auth service'),
- ('a2', 'Fix auth'),
- ])
- Agent(id: id, name: name, engine: 'codex', terminalAvailable: true),
- ];
- app.adoptSessionForTest(terminal('a0', []));
- final search = SwarmSearchController(
- app,
- const [],
- adding: true,
- offersCreate: true,
- );
- addTearDown(search.dispose);
- search.setQuery('auth');
- expect(search.rows.map((row) => row.agentId), ['a1', 'a2', 'a0', null]);
- expect(search.selected?.agentId, 'a1');
- expect(search.submit()?.destination.agentId, 'a1');
- expect(search.matchCount, 3);
-
- // An explicitly highlighted unavailable row stays selected on app updates.
- search.move(2);
- app.dismissError();
- expect(search.selected?.agentId, 'a0');
- expect(search.submit(), isNull);
- });
-
- testWidgets('held Tab completes without committing or changing the project', (
- tester,
- ) async {
- final app = createApp();
- addTearDown(app.dispose);
- app.adoptSessionForTest(terminal('a0', []));
- await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyN);
- final controller = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- controller.setFolder('/work/repo');
- controller.focusField(NewHarnessField.agent);
- await tester.pump();
- await tester.enterText(
- find.byKey(const ValueKey('new-harness-input')),
- 'open',
- );
- await tester.sendKeyDownEvent(LogicalKeyboardKey.tab);
- await tester.pump();
- expect(controller.engine, 'codex');
- expect(controller.query, 'OpenCode');
- for (var i = 0; i < 12; i++) {
- await tester.sendKeyRepeatEvent(LogicalKeyboardKey.tab);
+ final status = find.byKey(const ValueKey('new-harness-status'));
+ expect(find.text('The selected folder is unavailable.'), findsOneWidget);
+ final semantics = tester.widget<Semantics>(
+ find.ancestor(of: status, matching: find.byType(Semantics)).first,
+ );
+ expect(semantics.properties.liveRegion, isTrue);
+ await openLaunchRow(tester, 'agent');
+ await typeHarnessQuery(tester, 'Codex');
+ expect(find.text('The selected folder is unavailable.'), findsNothing);
+ box.warn('The selected folder is unavailable.');
await tester.pump();
- }
- await tester.sendKeyUpEvent(LogicalKeyboardKey.tab);
- expect(controller.engine, 'codex');
- expect(controller.query, 'OpenCode');
- expect(controller.machineId, 'm');
- expect(controller.project.folder, '/work/repo');
- expect(app.allPanes, hasLength(1));
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpWidget(const SizedBox());
- });
-
- testWidgets(
- 'box errors are announced, including the same error after editing',
- (tester) async {
- final app = createApp();
- addTearDown(app.dispose);
- app.adoptSessionForTest(terminal('a0', []));
- await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyN);
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ expect(status, findsOneWidget);
+ tester.view.physicalSize = const Size(600, 680);
+ addTearDown(tester.view.resetPhysicalSize);
await tester.pump();
- // Agent choices now offer the Store even when no agent matches. Use
- // the machine field to exercise an empty-choice error and announcement.
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ expect(status.hitTestable(), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- final input = find.byKey(const ValueKey('new-harness-input'));
- final controller = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- controller.focusField(NewHarnessField.machine);
+ // Clearing the filter clears its warning. Check the field view too.
+ box.warn('The selected folder is unavailable.');
await tester.pump();
- for (var i = 0; i < 2; i++) {
- await tester.enterText(input, 'zzqq');
- await tester.pump();
- tester.takeAnnouncements();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(controller.error, contains('Nothing matches'));
- expect(
- tester.takeAnnouncements(),
- contains(isAccessibilityAnnouncement(controller.error!)),
- );
- await tester.enterText(input, 'zzqqx');
- await tester.pump();
- }
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(status.hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
},
);
-
- testWidgets('creation status and a lost reply are announced', (tester) async {
- final connection = _PendingConnection();
- final app = createApp(connectionForTest: (_) => connection);
- addTearDown(app.dispose);
- app.adoptSessionForTest(terminal('a0', []));
- await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyN);
- final controller = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- controller.setFolder('/work/repo');
- await tester.pump();
- tester.takeAnnouncements();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(controller.busy, isTrue);
- expect(
- tester.takeAnnouncements(),
- contains(isAccessibilityAnnouncement('Starting harness…')),
- );
- connection.creation.completeError(const WsRequestTimeout('agent_create'));
- await tester.pump();
- expect(controller.checking, isTrue);
- expect(
- tester.takeAnnouncements(),
- contains(isAccessibilityAnnouncement(controller.error!)),
- );
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- expect(find.byType(NewHarnessBox), findsOneWidget);
- expect(
- tester.takeAnnouncements(),
- contains(isAccessibilityAnnouncement(controller.error!)),
- );
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpWidget(const SizedBox());
- });
-
- for (final (width, scale) in [(1280.0, 1.0), (760.0, 1.0), (600.0, 1.7)]) {
- testWidgets(
- 'search ends on a whole row at width $width and text scale $scale',
- (tester) async {
- final app = createApp();
- addTearDown(app.dispose);
- app.adoptSessionForTest(terminal('a69', []));
- await mount(tester, app);
- tester.view.physicalSize = Size(width, 800);
- tester.platformDispatcher.textScaleFactorTestValue = scale;
- addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
- await tester.pump();
- await chord(tester, LogicalKeyboardKey.keyO);
- final list = find.byKey(const ValueKey('swarm-search-result-list'));
- final row = find
- .descendant(of: list, matching: find.byType(ListTile))
- .first;
- final padding = tester.widget<ListView>(list).padding! as EdgeInsets;
- final visibleRows =
- (tester.getSize(list).height - padding.vertical) /
- tester.getSize(row).height;
- expect(visibleRows, closeTo(visibleRows.roundToDouble(), .001));
-
- // Creation stays outside the scrolling results, directly above input.
- await tester.enterText(
- find.byKey(const ValueKey('swarm-search-input')),
- 'zzqq',
- );
- await tester.pump();
- final onlyRow = find.descendant(
- of: list,
- matching: find.byType(ListTile),
- );
- expect(onlyRow, findsNothing);
- final create = find.widgetWithText(ListTile, 'New Harness');
- expect(create, findsOneWidget);
- expect(
- tester.getRect(create).bottom,
- lessThanOrEqualTo(
- tester
- .getRect(find.byKey(const ValueKey('swarm-search-input')))
- .top,
- ),
- );
- expect(tester.takeException(), isNull);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpWidget(const SizedBox());
- },
- );
- }
}
diff --git a/desktop/test/box_render_preview_test.dart b/desktop/test/box_render_preview_test.dart
index 835724f1e..3ec094033 100644
--- a/desktop/test/box_render_preview_test.dart
+++ b/desktop/test/box_render_preview_test.dart
@@ -18,7 +18,8 @@ import 'package:harness/auth/peer_link_client.dart';
import 'package:harness/core/config.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/pane_preset.dart';
-import 'package:harness/widgets/new_harness_box.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/ws/ws_conn.dart';
@@ -221,11 +222,10 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- final line = find.byKey(const ValueKey('new-harness-input'));
- final contextPicker = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- contextPicker.setFolder('/work/payments');
+ final line = find.byKey(const ValueKey('new-harness-query'));
+ NewHarnessController contextPicker() =>
+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller;
+ contextPicker().setFolder('/work/payments');
await app.projectHistory.select('m', '/work/payments');
app.machineStates['m']!.localProjects = {
for (final (index, name) in [
@@ -247,16 +247,17 @@ void main() {
await shot('06-launch-large-text');
tester.view.physicalSize = const Size(1280, 800);
tester.platformDispatcher.clearTextScaleFactorTestValue();
- await openLegacyTaskEditor(tester);
- await tester.pump();
- await type(line, '');
+ await chord(tester, LogicalKeyboardKey.period);
+ await tester.pumpAndSettle();
+ final taskField = find.byKey(const Key('new-agent-task'));
+ await type(taskField, '');
await shot('07-new-tab-task-empty');
- await type(line, 'Plan the launch\nInclude the product demo');
+ await type(taskField, 'Plan the launch\nInclude the product demo');
await shot('07-new-tab-task-multiline');
- await type(line, 'fix the flaky login test');
+ await type(taskField, 'fix the flaky login test');
await shot('07-new-tab-task-typed');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
+ await tester.pumpAndSettle();
await openLaunchRow(tester, 'agent');
await tester.pump();
await shot('08-new-agent');
@@ -264,7 +265,7 @@ void main() {
await key(tester, LogicalKeyboardKey.enter);
await openLaunchRow(tester, 'agent');
final previewAgent = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
for (
var step = 0;
@@ -278,6 +279,7 @@ void main() {
await shot('08-codex-highlighted-from-claude');
await type(line, 'co');
await shot('09-new-agent-filtered');
+ await key(tester, LogicalKeyboardKey.enter);
await openAgentSetting(
tester,
'codex',
@@ -291,8 +293,6 @@ void main() {
await shot('09-codex-profiles');
await type(line, 'Work');
await key(tester, LogicalKeyboardKey.enter);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
await shot('09-configured-agent');
await openLaunchRow(tester, 'project');
await tester.pump();
@@ -311,7 +311,10 @@ void main() {
'prototype',
'experiments',
]) {
- await app.projectHistory.select(contextPicker.machineId, '/work/$name');
+ await app.projectHistory.select(
+ contextPicker().machineId,
+ '/work/$name',
+ );
}
app.notifyListeners();
await tester.pump(const Duration(milliseconds: 200));
@@ -329,22 +332,30 @@ void main() {
await shot('10-project-filtered');
await type(line, 'no-matching-project');
await shot('10-project-no-matches');
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await openLaunchRow(tester, 'project');
+ await tester.tap(
+ find.byKey(
+ ValueKey(
+ 'new-harness-option-${NewHarnessController.existingProjectId}',
+ ),
+ ),
+ );
await tester.pump();
await shot('10-existing-project');
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await openLaunchRow(tester, 'project');
+ await tester.tap(
+ find.byKey(
+ ValueKey('new-harness-option-${NewHarnessController.repositoryId}'),
+ ),
+ );
await tester.pump();
await shot('10-github-empty');
await type(line, 'https://github.com/acme/payments');
await shot('10-github-repository');
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- contextPicker.accept(
- contextPicker.options.firstWhere(
- (row) => row.id == NewHarnessController.newProjectId,
+ await openLaunchRow(tester, 'project');
+ await tester.tap(
+ find.byKey(
+ ValueKey('new-harness-option-${NewHarnessController.newProjectId}'),
),
);
await tester.pump();
@@ -361,15 +372,15 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
}
- contextPicker.focusField(NewHarnessField.task);
- contextPicker.setQuery('');
- contextPicker.focusField(NewHarnessField.agent);
- contextPicker.accept(const NewHarnessOption(id: 'pi', title: 'Pi'));
+ contextPicker().focusField(NewHarnessField.task);
+ contextPicker().setQuery('');
+ contextPicker().focusField(NewHarnessField.agent);
+ contextPicker().accept(const NewHarnessOption(id: 'pi', title: 'Pi'));
await tester.pump();
await shot('12-pi-task-availability');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- expect(find.byKey(const ValueKey('new-harness-box')), findsNothing);
+ expect(find.byKey(const ValueKey('new-harness-form')), findsNothing);
await chord(tester, LogicalKeyboardKey.keyP);
await shot('13-command-open');
@@ -409,15 +420,15 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
final largeBox = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
largeBox.setFolder('/work/payments');
await shot('15-create-large-text');
- await openLegacyTaskEditor(tester);
- await tester.pump();
+ await chord(tester, LogicalKeyboardKey.period);
+ await tester.pumpAndSettle();
await shot('15-task-large-text');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
+ await tester.pumpAndSettle();
await openLaunchRow(tester, 'project');
await tester.pump();
await shot('15-project-menu-large-text');
@@ -430,7 +441,7 @@ void main() {
tester.view.physicalSize = const Size(1280, 800);
tester.platformDispatcher.clearTextScaleFactorTestValue();
final create = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
create.focusField(NewHarnessField.projectName);
create.setQuery('Super terminal');
@@ -464,7 +475,7 @@ void main() {
);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
await shot('21-returned-draft');
tester.view.physicalSize = const Size(600, 800);
tester.platformDispatcher.textScaleFactorTestValue = 1.7;
@@ -591,9 +602,7 @@ void main() {
await shot('35-pane-actions-narrow');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- Focus.of(tester.element(find.byIcon(Icons.tune).first)).requestFocus();
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.tap(find.byType(GridModelPicker).first);
await tester.pumpAndSettle();
await shot('36-model-menu-narrow');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
@@ -677,7 +686,7 @@ void main() {
await tester.pumpAndSettle();
await shot('40-link-machine');
await tester.enterText(
- find.byKey(const Key('remote-password-connect-field')),
+ find.byKey(const ValueKey('connect-password-studio-input')),
'fixture password',
);
await key(tester, LogicalKeyboardKey.enter);
@@ -704,30 +713,21 @@ void main() {
);
await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
- await shot('44-machine-chooser');
- final machineSearch = find.byKey(const Key('link-machine-search'));
- await tester.enterText(machineSearch, 'ssh');
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- await shot('45-machine-ssh-guide');
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- await tester.enterText(machineSearch, 'desktop');
- await key(tester, LogicalKeyboardKey.enter);
+ await shot('44-machines');
+ final addMachine = find.byKey(const ValueKey('add-machine'));
+ await tester.ensureVisible(addMachine);
+ await tester.tap(addMachine);
await tester.pumpAndSettle();
await shot('46-machine-desktop-guide');
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- await tester.enterText(machineSearch, 'zzzz');
- await shot('47-machine-no-match');
- await tester.enterText(machineSearch, 'ssh');
- await key(tester, LogicalKeyboardKey.enter);
+ final serverSetup = find.text('Set up a server…');
+ await tester.ensureVisible(serverSetup);
+ await tester.tap(serverSetup);
await tester.pumpAndSettle();
+ await shot('45-machine-ssh-guide');
tester.view.physicalSize = const Size(600, 420);
tester.platformDispatcher.textScaleFactorTestValue = 1.7;
await shot('48-machine-guide-small-large-text');
await key(tester, LogicalKeyboardKey.escape);
- await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
tester.view.physicalSize = const Size(1280, 800);
tester.platformDispatcher.clearTextScaleFactorTestValue();
@@ -738,8 +738,9 @@ void main() {
);
await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
- await tester.enterText(machineSearch, 'password');
- await key(tester, LogicalKeyboardKey.enter);
+ await tester.tap(find.byTooltip('Options for M2'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Connection settings…'));
await tester.pumpAndSettle();
await shot('49-own-password-prompt');
passwordCli.setReply = Completer<RemotePasswordSetResult>();
@@ -808,19 +809,29 @@ void main() {
await key(tester, LogicalKeyboardKey.keyP, cmd: true);
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
- '> machines manager',
+ '> machines',
);
await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
- final managerSearch = find.byKey(const Key('machines-manager-search'));
+ Future<void> machineOptions(String id) async {
+ final options = find.byTooltip(
+ 'Options for ${managerApp.stateOf(id)!.machine.displayName}',
+ );
+ await tester.ensureVisible(options);
+ await tester.tap(options);
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> machineAction(String id, String label) async {
+ await machineOptions(id);
+ await tester.tap(find.text(label));
+ await tester.pumpAndSettle();
+ }
+
await shot('57-machines-manager');
- await tester.enterText(managerSearch, 'office');
- await shot('58-machines-filtered');
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
+ await machineOptions('studio');
await shot('59-machine-actions');
- await tester.enterText(managerSearch, 'rename');
- await key(tester, LogicalKeyboardKey.enter);
+ await tester.tap(find.text('Rename'));
await tester.pumpAndSettle();
final renameInput = find.byKey(const Key('machine-rename-input'));
await shot('60-machine-rename');
@@ -836,34 +847,26 @@ void main() {
machineApi.renameReply = null;
await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
- await tester.enterText(managerSearch, 'delete');
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
+ await machineAction('studio', 'Remove from account…');
await shot('63-machine-delete');
machineApi.deleteFailure = ApiException(
'Could not reach your account. Try again.',
);
- await key(tester, LogicalKeyboardKey.tab);
- await key(tester, LogicalKeyboardKey.enter);
+ await tester.tap(find.byKey(const Key('machine-delete-confirm')));
await tester.pumpAndSettle();
await shot('64-machine-delete-error');
await key(tester, LogicalKeyboardKey.escape);
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- await tester.enterText(managerSearch, 'shared');
- await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
+ await tester.ensureVisible(
+ find.byKey(const ValueKey('machine-shared-fixture')),
+ );
await shot('65-shared-machine');
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- await tester.enterText(managerSearch, 'office');
- await key(tester, LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
tester.view.physicalSize = const Size(480, 360);
tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await tester.pumpAndSettle();
+ await machineOptions('studio');
await shot('66-machine-actions-small-large-text');
- await tester.enterText(managerSearch, 'rename');
- await key(tester, LogicalKeyboardKey.enter);
+ await tester.tap(find.text('Rename'));
await tester.pumpAndSettle();
await shot('67-machine-rename-small-large-text');
await key(tester, LogicalKeyboardKey.escape);
diff --git a/desktop/test/command_dock_interaction_test.dart b/desktop/test/command_dock_interaction_test.dart
index e1da73229..659fe2b8a 100644
--- a/desktop/test/command_dock_interaction_test.dart
+++ b/desktop/test/command_dock_interaction_test.dart
@@ -1,711 +1,156 @@
-import 'support/launch_menu.dart';
-
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/state/new_harness.dart';
-import 'package:harness/terminal/terminal_binary.dart';
-import 'package:harness/widgets/box_chrome.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/core/models.dart';
+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/box_chrome.dart' show kBoxFaint;
+import 'package:harness/terminal/terminal_text.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_switcher.dart';
import 'keymap_host_test.dart' show MemoryKeymap, key;
import 'keymap_runtime_test.dart' as configured;
-import 'swarm_screen_test.dart' show terminal;
+import 'support/launch_menu.dart';
import 'support/mixed_agents.dart';
+import 'swarm_screen_test.dart' show terminal;
import 'swarm_state_test.dart' show createApp;
void main() {
setUp(() => newHarnessOpensInBox = true);
tearDown(() => newHarnessOpensInBox = false);
- testWidgets(
- 'launch arrows edit the highlighted field without starting an agent',
- (tester) async {
- final app = createApp();
- seedMixedAgents(app);
- addTearDown(app.dispose);
- final map = MemoryKeymap();
- addTearDown(map.dispose);
- final frames = <TerminalBinaryFrame>[];
- app.adoptSessionForTest(terminal('a0', frames));
- await configured.mount(tester, app, map);
- await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- final original = (box.engine, box.machineId, box.project);
- final paneCount = app.activeSwarm.panes.length;
- void highlighted(String name) {
- final row = find.byKey(ValueKey('new-harness-field-$name'));
- expect(row.hitTestable(), findsOneWidget);
- final highlight = tester.widget<BoxRowHighlight>(
- find.ancestor(of: row, matching: find.byType(BoxRowHighlight)),
- );
- expect(highlight.highlighted, isTrue);
- expect(box.field, NewHarnessField.launch);
- }
-
- highlighted('create');
- for (final letter in [
- LogicalKeyboardKey.keyA,
- LogicalKeyboardKey.keyM,
- LogicalKeyboardKey.keyP,
- LogicalKeyboardKey.keyT,
- LogicalKeyboardKey.keyO,
- LogicalKeyboardKey.keyG,
- ]) {
- await key(tester, letter);
- highlighted('create');
- }
- // Down wraps from the bottom action into the arguments in visual order.
- for (final (steps, name, field) in [
- (1, 'agent', NewHarnessField.agent),
- (2, 'machine', NewHarnessField.machine),
- (3, 'project', NewHarnessField.projectMenu),
- ]) {
- for (var i = 0; i < steps; i++) {
- await key(tester, LogicalKeyboardKey.arrowDown);
- }
- highlighted(name);
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.field, field);
- await key(tester, LogicalKeyboardKey.escape);
- highlighted('create');
- }
- await key(tester, LogicalKeyboardKey.arrowUp);
- highlighted('worktree');
- await key(tester, LogicalKeyboardKey.arrowUp);
- highlighted('project');
- expect(
- find.byKey(const ValueKey('new-harness-field-options')),
- findsNothing,
- );
- await openLaunchRow(tester, 'agent');
- await openAgentSetting(
- tester,
- box.selected!.engine!,
- NewHarnessController.permissionsId,
- );
- expect(box.field, NewHarnessField.mode);
- expect(find.byKey(const Key('new-agent-task')), findsNothing);
- await tester.enterText(
- find.byKey(const ValueKey('new-harness-input')),
- 'ask',
- );
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.field, NewHarnessField.agent);
- expect(box.mode, 'ask');
- await key(tester, LogicalKeyboardKey.escape);
- highlighted('create');
- expect(find.textContaining('Ask first'), findsOneWidget);
- expect((box.engine, box.machineId, box.project), original);
- expect(app.activeSwarm.panes, hasLength(paneCount));
- expect(frames, isEmpty);
-
- // Navigation obeys the same live picker remaps as the child lists.
- map.apply('''{"bindings":[
- {"keys":"down","command":null,"when":"picker"},
- {"keys":"ctrl+j","command":"picker.next","when":"picker"}
- ]}''');
- await tester.pump();
- await key(tester, LogicalKeyboardKey.arrowDown);
- highlighted('create');
- await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
- highlighted('agent');
- await key(tester, LogicalKeyboardKey.arrowUp);
- highlighted('create');
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpWidget(const SizedBox());
- },
- );
-
- testWidgets(
- 'Machine returns to its source menu and project search stays on that machine',
- (tester) async {
- final app = createApp();
- seedMixedAgents(app);
- addTearDown(app.dispose);
- await app.projectHistory.select('studio', '/work/remote-project');
- final map = MemoryKeymap();
- addTearDown(map.dispose);
- final frames = <TerminalBinaryFrame>[];
- app.adoptSessionForTest(terminal('a0', frames));
- await configured.mount(tester, app, map);
- await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- final original = box.project;
- final input = find.byKey(const ValueKey('new-harness-input'));
- await openLegacyTaskEditor(tester);
- await tester.enterText(input, 'Inspect the project');
- await key(tester, LogicalKeyboardKey.escape);
- await openLaunchRow(tester, 'machine');
- await tester.enterText(input, 'Office');
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.field, NewHarnessField.launch);
- expect(box.machineId, 'm');
- expect(box.project, original);
- await openLaunchRow(tester, 'machine');
- await tester.enterText(input, 'Office');
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.field, NewHarnessField.launch);
- expect(box.machineId, 'studio');
- expect(box.needsProject, isTrue);
- await openLaunchRow(tester, 'project');
- final remoteRow = box.options.singleWhere(
- (row) => row.project?.folder == '/work/remote-project',
- );
- expect(find.text('remote-project').hitTestable(), findsOneWidget);
- await tester.enterText(input, 'remote-project');
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.field, NewHarnessField.launch);
- expect(box.project.folder, '/work/remote-project');
- await openLaunchRow(tester, 'machine');
- await tester.enterText(input, 'M2');
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.project, original);
- expect(box.task, 'Inspect the project');
- await openLaunchRow(tester, 'project');
- box.accept(remoteRow);
- expect(box.error, contains('machine has changed'));
- expect(box.machineId, 'm');
- map.apply('''{"bindings":[
- {"keys":"m","command":null,"when":"picker"},
- {"keys":"u","command":"creation.project_machine","when":"picker"},
- {"keys":"ctrl+r","command":"creation.project_recent_1","when":"project"}
- ]}''');
- await tester.pump();
- await tester.enterText(input, 'robotics');
- await key(tester, LogicalKeyboardKey.keyR, ctrl: true);
- expect(box.field, NewHarnessField.launch);
- expect(box.project.folder, '/work/robotics');
- await key(tester, LogicalKeyboardKey.keyM);
- expect(box.field, NewHarnessField.launch);
- await key(tester, LogicalKeyboardKey.keyU);
- expect(box.field, NewHarnessField.machine);
- await key(tester, LogicalKeyboardKey.escape);
- await openLaunchRow(tester, 'project');
- await tester.enterText(input, 'robotics');
- await key(tester, LogicalKeyboardKey.keyU);
- expect(box.field, NewHarnessField.projectMenu);
- await tester.tap(
- find.byKey(const ValueKey('new-harness-change-machine')),
- );
- await tester.pump();
- expect(box.field, NewHarnessField.machine);
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.field, NewHarnessField.projectMenu);
- expect(box.query, 'robotics');
- expect(frames, isEmpty);
- await tester.pumpWidget(const SizedBox());
- },
- );
-
- testWidgets(
- 'Project keeps its actions visible and scopes each prompt to its intent',
- (tester) async {
- final app = createApp();
- seedMixedAgents(app);
- addTearDown(app.dispose);
- for (var i = 0; i < 40; i++) {
- await app.projectHistory.select('m', '/work/project-$i');
- }
- await app.projectHistory.select('studio', '/work/office-only');
- final map = MemoryKeymap();
- addTearDown(map.dispose);
- final frames = <TerminalBinaryFrame>[];
- app.adoptSessionForTest(terminal('a0', frames));
- await configured.mount(tester, app, map);
- await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- final original = box.project;
- final input = find.byKey(const ValueKey('new-harness-input'));
- await openLaunchRow(tester, 'project');
- expect(box.field, NewHarnessField.projectMenu);
- expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
- for (final label in [
- 'New Project',
- 'Open Folder',
- 'Clone GitHub Repository',
- ]) {
- expect(find.text(label).hitTestable(), findsOneWidget);
- }
- expect(
- find.byKey(const ValueKey('new-harness-change-machine')).hitTestable(),
- findsOneWidget,
- );
- expect(box.options.where((row) => !row.synthetic), hasLength(43));
- expect(box.selected!.project, original);
- for (final shortcut in ['1', '9', 'n', 'o', 'g']) {
- expect(find.text(shortcut), findsNothing);
- }
- final openRow = find.byKey(
- const ValueKey(NewHarnessController.existingProjectId),
- );
- final newRow = find.byKey(
- const ValueKey(NewHarnessController.newProjectId),
- );
- final openBounds = tester.getRect(openRow);
- expect(tester.getRect(newRow).bottom, lessThanOrEqualTo(openBounds.top));
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(box.selected!.id, NewHarnessController.newProjectId);
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(box.selected!.id, NewHarnessController.existingProjectId);
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(box.selected!.id, NewHarnessController.repositoryId);
- final cloneRow = find.byKey(
- const ValueKey(NewHarnessController.repositoryId),
- );
- expect(
- tester.getRect(openRow).bottom,
- lessThanOrEqualTo(tester.getRect(cloneRow).top),
- );
- expect(
- tester.getRect(cloneRow).bottom,
- lessThanOrEqualTo(tester.getRect(input).top),
- );
- // Older recents scroll; project actions remain anchored beside the footer.
- for (var i = 0; i < 5; i++) {
- await key(tester, LogicalKeyboardKey.pageUp);
- }
- await tester.pump();
- expect(box.cursor, greaterThan(12));
- expect(
- find.byKey(ValueKey(box.selected!.id)).hitTestable(),
- findsOneWidget,
- );
- expect(tester.getRect(openRow), openBounds);
- final previousSize = tester.view.physicalSize;
- final selectedProject = box.selected!.id;
- tester.view.physicalSize = const Size(600, 680);
- tester.platformDispatcher.textScaleFactorTestValue = 1.7;
- addTearDown(tester.view.resetPhysicalSize);
- addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
- await tester.pumpAndSettle();
- expect(box.selected!.id, selectedProject);
- expect(
- find.byKey(ValueKey(selectedProject)).hitTestable(),
- findsOneWidget,
- );
- expect(openRow.hitTestable(), findsOneWidget);
- tester.view.physicalSize = previousSize;
- tester.platformDispatcher.clearTextScaleFactorTestValue();
- await tester.pumpAndSettle();
- // Letters and digits belong to the search, not hidden action shortcuts.
- for (final ordinary in [
- LogicalKeyboardKey.keyN,
- LogicalKeyboardKey.keyO,
- LogicalKeyboardKey.keyG,
- LogicalKeyboardKey.keyM,
- LogicalKeyboardKey.digit1,
- LogicalKeyboardKey.digit9,
- ]) {
- await key(tester, ordinary);
- expect(box.field, NewHarnessField.projectMenu);
- }
- await tester.enterText(input, 'nogm19');
- await tester.pump();
- expect(box.query, 'nogm19');
- expect(box.options, hasLength(3));
- expect(find.text('No projects match “nogm19”'), findsOneWidget);
- for (final label in [
- 'New Project',
- 'Open Folder',
- 'Clone GitHub Repository',
- ]) {
- expect(find.text(label).hitTestable(), findsOneWidget);
- }
- await tester.enterText(input, 'project-9');
- await tester.pump();
- expect(box.selected!.project!.folder, '/work/project-9');
- expect(
- find.byKey(ValueKey(box.selected!.id)).hitTestable(),
- findsOneWidget,
- );
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.project.folder, '/work/project-9');
- expect(box.field, NewHarnessField.launch);
- box.setFolder(original.folder!);
- await openLaunchRow(tester, 'project');
- expect(box.query, isEmpty);
- await tester.enterText(input, 'office-only');
- await tester.pump();
- expect(box.options.where((row) => !row.synthetic), isEmpty);
- expect(box.selected!.id, NewHarnessController.existingProjectId);
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.field, NewHarnessField.project);
- expect(box.options.single.id, NewHarnessController.browseId);
- await tester.enterText(input, 'new project');
- await tester.pump();
- expect(box.options.any((row) => row.id == 'project:new'), isFalse);
- expect(box.project, original);
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.query, 'office-only');
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(box.selected!.id, NewHarnessController.repositoryId);
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.field, NewHarnessField.projectRepository);
- await tester.enterText(input, 'https://example.com/owner/repo');
- await key(tester, LogicalKeyboardKey.enter, cmd: true);
- expect(box.error, contains('GitHub URL'));
- expect(box.project, original);
- await tester.enterText(input, 'acme/payments');
- await key(tester, LogicalKeyboardKey.keyM);
- expect(box.field, NewHarnessField.projectRepository);
- await key(tester, LogicalKeyboardKey.enter);
- expect(
- box.project.repository!.url,
- 'https://github.com/acme/payments.git',
- );
- expect(box.field, NewHarnessField.launch);
- await openLaunchRow(tester, 'machine');
- await tester.enterText(input, 'Office');
- await key(tester, LogicalKeyboardKey.enter);
- await openLaunchRow(tester, 'project');
- expect(box.machineId, 'studio');
- expect(
- box.options
- .where((row) => row.project != null)
- .every((row) => row.machineId == 'studio'),
- isTrue,
- );
- await tester.enterText(input, 'office-only');
- await tester.pump();
- expect(box.selected!.project!.folder, '/work/office-only');
- // Explicit custom bindings remain available without reserving search text.
- map.apply(
- '{"bindings":[{"keys":"ctrl+r","command":"creation.project_new","when":"project"}]}',
- );
- await tester.pump();
- await key(tester, LogicalKeyboardKey.keyR, ctrl: true);
- expect(box.field, NewHarnessField.projectName);
- await tester.enterText(input, 'payments processing');
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.project.name, 'payments processing');
- expect(
- box.projectLocation,
- 'iMac · Office:~/harnesses/payments-processing',
- );
- // The full form remains available through its compatibility shortcut.
- await key(tester, LogicalKeyboardKey.period, cmd: true);
- expect(find.byKey(const Key('new-agent-task')), findsOneWidget);
- await key(tester, LogicalKeyboardKey.escape);
- expect(frames, isEmpty);
- await tester.pump(const Duration(milliseconds: 200));
- await tester.pumpWidget(const SizedBox());
- },
- );
-
- testWidgets('Pi and Codex both use the compact launch form', (tester) async {
+ testWidgets('setup rows edit in place and only the launch action starts', (
+ tester,
+ ) async {
final app = createApp();
seedMixedAgents(app);
- addTearDown(app.dispose);
final map = MemoryKeymap();
+ addTearDown(app.dispose);
addTearDown(map.dispose);
app.adoptSessionForTest(terminal('a0', []));
await configured.mount(tester, app, map);
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
- final input = find.byKey(const ValueKey('new-harness-input'));
- for (final agent in ['pi', 'codex']) {
- await openLaunchRow(tester, 'agent');
- await tester.enterText(input, agent);
- box.accept(box.options.firstWhere((row) => row.id == agent));
- await tester.pump();
- expect(
- find.byKey(const ValueKey('new-harness-field-task')),
- findsNothing,
- );
- expect(
- find.byKey(const ValueKey('new-harness-field-placement')),
- findsNothing,
- );
- expect(find.text('Start Harness'), findsOneWidget);
- }
+ await openLaunchRow(tester, 'agent');
+ await typeHarnessQuery(tester, 'Claude Code');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.engine, 'claude');
+ expect(app.panes, hasLength(1));
+ await openLaunchRow(tester, 'approvals');
+ await typeHarnessQuery(tester, 'Ask first');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.mode, 'ask');
+ expect(app.panes, hasLength(1));
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.byType(NewHarnessForm), findsNothing);
+ expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
});
testWidgets(
- 'launch keys are remappable and remain text in an argument prompt',
+ 'session context and activity are visible beside a distinct create action',
(tester) async {
final app = createApp();
- seedMixedAgents(app);
- addTearDown(app.dispose);
final map = MemoryKeymap();
- addTearDown(map.dispose);
- map.apply(
- '{"bindings":[{"keys":"a","command":null,"when":"picker"},{"keys":"e","command":"creation.agent","when":"picker"}]}',
- );
- final frames = <TerminalBinaryFrame>[];
- app.adoptSessionForTest(terminal('a0', frames));
- await configured.mount(tester, app, map);
- await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- expect(box.field, NewHarnessField.launch);
- await key(tester, LogicalKeyboardKey.keyA);
- expect(box.field, NewHarnessField.launch);
- await key(tester, LogicalKeyboardKey.keyE);
- expect(box.field, NewHarnessField.agent);
- // The menu action must not steal letters while editing or searching.
- await key(tester, LogicalKeyboardKey.keyP);
- await key(tester, LogicalKeyboardKey.keyT);
- await key(tester, LogicalKeyboardKey.keyO);
- await key(tester, LogicalKeyboardKey.keyE);
- expect(box.field, NewHarnessField.agent);
- final input = find.byKey(const ValueKey('new-harness-input'));
- await tester.enterText(input, 'OpenCode');
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.engine, 'opencode');
- expect(box.field, NewHarnessField.launch);
- await openLegacyTaskEditor(tester);
- await tester.enterText(input, 'a project to open');
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.task, 'a project to open');
- expect(box.field, NewHarnessField.launch);
- await key(tester, LogicalKeyboardKey.escape);
- expect(find.byType(NewHarnessBox), findsNothing);
- expect(frames, isEmpty);
- await tester.pumpWidget(const SizedBox());
- },
- );
-
- for (final size in [const Size(1440, 1000), const Size(900, 560)]) {
- testWidgets('recent sessions fill the available dock at $size', (
- tester,
- ) async {
- final app = createApp();
addTearDown(app.dispose);
- final map = MemoryKeymap();
addTearDown(map.dispose);
- app.adoptSessionForTest(terminal('a69', []));
+ seedMixedAgents(app);
+ final previous = app.machineStates['m']!.agents.first;
+ app.machineStates['m']!.agents = [
+ Agent(
+ id: previous.id,
+ name: previous.name,
+ engine: previous.engine,
+ project: previous.project,
+ terminalAvailable: true,
+ lastActivityAt: DateTime.now().subtract(const Duration(minutes: 33)),
+ ),
+ ...app.machineStates['m']!.agents.skip(1),
+ ];
await configured.mount(tester, app, map);
- tester.view.physicalSize = size;
- await tester.pump();
await key(tester, LogicalKeyboardKey.keyO, cmd: true);
- final results = tester.widget<SwarmSearchResults>(
- find.byType(SwarmSearchResults),
- );
- final list = tester.getRect(
- find.byKey(const ValueKey('swarm-search-result-list')),
- );
- final visible = results.search.rows.where((row) {
- if (row.isCreate) return false;
- final finder = find.byKey(ValueKey(row.id));
- if (finder.evaluate().isEmpty) return false;
- final bounds = tester.getRect(finder);
- return bounds.top >= list.top - 1 && bounds.bottom <= list.bottom + 1;
- }).length;
- if (size.height >= 1000) {
- expect(visible, 10);
- } else {
- expect(visible, inInclusiveRange(1, 10));
+ final row = find.byKey(ValueKey(agentDestinationId('m', 'a0')));
+ expect(tester.widget<ListTile>(row).leading, isA<EngineMark>());
+ for (final value in [
+ 'M2',
+ 'openharness',
+ 'feature/login-redirect',
+ '33m',
+ ]) {
+ expect(
+ find.descendant(of: row, matching: find.text(value)),
+ findsOneWidget,
+ );
}
- expect(
- find.byKey(const ValueKey('swarm-search-input')).hitTestable(),
- findsOneWidget,
- );
- expect(
- find.byKey(const ValueKey('create:harness')).hitTestable(),
- findsOneWidget,
- );
- expect(
- find.byKey(const ValueKey('swarm-search-hints')).hitTestable(),
- findsOneWidget,
+ for (final label in ['M2', 'openharness', 'feature/login-redirect']) {
+ final text = tester.widget<Text>(
+ find.descendant(of: row, matching: find.text(label)),
+ );
+ expect(text.style!.fontFamily, terminalFontStore.value.fontFamily);
+ expect(text.style!.fontSize, terminalFontStore.size);
+ expect(text.style!.height, terminalFontStore.value.height);
+ expect(text.style!.color, kBoxFaint);
+ }
+ final create = tester.widget<ListTile>(
+ find.byKey(const ValueKey(kSwarmCreateRowId)),
);
+ expect(create.leading, isA<Icon>());
+ expect(find.text('Harness:'), findsNothing);
+ expect(find.byKey(const ValueKey('swarm-search-hints')), findsNothing);
expect(tester.takeException(), isNull);
- await tester.pump(const Duration(milliseconds: 100));
await tester.pumpWidget(const SizedBox());
- await tester.pump(const Duration(milliseconds: 100));
- });
- }
+ },
+ );
for (final size in [const Size(1280, 800), const Size(600, 700)]) {
testWidgets(
- 'dock pins creation beside its input while matches filter at $size',
+ 'Open Harness stays minimal and keeps its frame while filtering at $size',
(tester) async {
final app = createApp();
- addTearDown(app.dispose);
final map = MemoryKeymap();
+ addTearDown(app.dispose);
addTearDown(map.dispose);
- final frames = <TerminalBinaryFrame>[];
- final pane = app.adoptSessionForTest(terminal('a69', frames));
- app.renameSwarm(app.activeSwarmId, 'Feature work');
+ final pane = app.adoptSessionForTest(terminal('a0', []));
await configured.mount(tester, app, map);
tester.view.physicalSize = size;
await tester.pump();
final paneBounds = tester.getRect(find.byKey(pane.cellKey));
await key(tester, LogicalKeyboardKey.keyO, cmd: true);
+ final panel = find.byKey(const ValueKey('swarm-search-results'));
final input = find.byKey(const ValueKey('swarm-search-input'));
- final preview = find.byKey(const ValueKey('swarm-search-preview'));
- expect(find.text('· Feature work'), findsNothing);
- // The create row already explains itself; only real agents need preview.
- expect(preview, findsNothing);
- await tester.enterText(input, 'Agent 1');
- await tester.pump();
+ final count = find.byKey(const ValueKey('swarm-search-count'));
+ final bounds = tester.getRect(panel);
+ expect(tester.widget<TextField>(input).cursorWidth, greaterThan(2));
+ expect(find.text('>'), findsOneWidget);
+ expect(find.text('Harness:'), findsNothing);
+ expect(find.text('[ New Harness ]'), findsNothing);
+ expect(find.text('Select Item'), findsNothing);
+ expect(find.byKey(const ValueKey('swarm-search-hints')), findsNothing);
final search = tester
.widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
.search;
- final best = search.selected!;
- expect(best.agentId, 'a1');
- final bestRow = find.byKey(ValueKey(best.id));
- final queryBounds = tester.getRect(input);
- final matchBounds = tester.getRect(bestRow);
- final createRow = find.byKey(const ValueKey('create:harness'));
- final createBounds = tester.getRect(createRow);
- expect(queryBounds.top - createBounds.bottom, inInclusiveRange(0, 12));
- expect(matchBounds.bottom, lessThanOrEqualTo(createBounds.top + .001));
expect(search.rows.first.isCreate, isTrue);
- expect(search.rows.first.task, 'Agent 1');
- expect(preview, findsOneWidget);
- if (size.width < 800) {
- expect(
- tester.getRect(preview).bottom,
- lessThan(tester.getRect(bestRow).top),
- );
- } else {
- expect(tester.getRect(preview).left, greaterThan(matchBounds.right));
- expect(
- tester
- .getSize(find.byKey(const ValueKey('swarm-search-results')))
- .height,
- lessThan(size.height * .65),
- );
- }
- await key(tester, LogicalKeyboardKey.slash, ctrl: true);
- expect(preview, findsNothing);
- expect(search.selected, same(best));
- expect(
- tester.getRect(input),
- rectMoreOrLessEquals(queryBounds, epsilon: .001),
- );
- await key(tester, LogicalKeyboardKey.slash, ctrl: true);
- expect(preview, findsOneWidget);
- expect(
- tester.getRect(input),
- rectMoreOrLessEquals(queryBounds, epsilon: .001),
- );
- await key(tester, LogicalKeyboardKey.arrowUp);
- expect(search.cursor, 2);
- final selectedRow = find.byKey(ValueKey(search.selected!.id));
- expect(selectedRow.hitTestable(), findsOneWidget);
- if (bestRow.evaluate().isNotEmpty) {
- expect(
- tester.getRect(selectedRow).center.dy,
- lessThan(tester.getRect(bestRow).center.dy),
- );
- }
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(search.selected, same(best));
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(search.selected!.isCreate, isTrue);
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(
- search.selected!.isCreate,
- isTrue,
- reason: 'Do not wrap at the edge',
- );
- await key(tester, LogicalKeyboardKey.keyK, ctrl: true);
- expect(search.selected, same(best));
- await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
- expect(search.selected!.isCreate, isTrue);
- expect(
- tester.getRect(createRow),
- rectMoreOrLessEquals(createBounds, epsilon: .001),
- );
- await tester.drag(
- find.byKey(const ValueKey('swarm-search-result-list')),
- const Offset(0, 180),
- );
- await tester.pumpAndSettle();
- expect(
- tester.getRect(createRow),
- rectMoreOrLessEquals(createBounds, epsilon: .001),
- );
- await tester.enterText(input, '');
- await tester.pump();
- expect(
- tester.getRect(createRow),
- rectMoreOrLessEquals(createBounds, epsilon: .001),
- );
await key(tester, LogicalKeyboardKey.tab);
- expect(
- FocusManager.instance.primaryFocus?.context
- ?.findAncestorWidgetOfExactType<ListTile>()
- ?.key,
- const ValueKey('create:harness'),
- reason: 'Tab reaches the pinned action next to the query first',
- );
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ await tester.enterText(input, 'nothing-like-this');
+ await tester.pump();
+ expect(search.rows.single.isCreate, isTrue);
+ expect(tester.getRect(panel), bounds);
+ expect(count, findsNothing);
expect(tester.getRect(find.byKey(pane.cellKey)), paneBounds);
+ expect(find.text('New Harness'), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
- await key(tester, LogicalKeyboardKey.arrowLeft);
- expect(frames.single.bytes, [27, 91, 68]);
- await tester.pump(const Duration(milliseconds: 100));
+ expect(panel, findsNothing);
expect(tester.takeException(), isNull);
+ // Let the terminal's resize debounce settle before disposing the fixture.
+ await tester.pump(const Duration(milliseconds: 60));
await tester.pumpWidget(const SizedBox());
},
);
}
-
- testWidgets(
- 'creation choices follow spatial keys while task arrows edit text',
- (tester) async {
- final app = createApp();
- addTearDown(app.dispose);
- final map = MemoryKeymap();
- addTearDown(map.dispose);
- app.adoptSessionForTest(terminal('a0', []));
- await configured.mount(tester, app, map);
- await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- final input = find.byKey(const ValueKey('new-harness-input'));
- final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- box.setFolder("/work/project");
- box.focusField(NewHarnessField.task);
- await tester.pump();
- await tester.enterText(input, 'First line\nSecond line');
- await tester.pump();
- expect(box.task, 'First line\nSecond line');
- await key(tester, LogicalKeyboardKey.arrowUp);
- expect(box.task, 'First line\nSecond line');
- final editor = tester.widget<TextField>(input);
- expect(editor.controller!.selection.baseOffset, lessThan(11));
- await key(tester, LogicalKeyboardKey.escape);
- await openLaunchRow(tester, 'agent');
- expect(box.task, 'First line\nSecond line');
- await tester.enterText(input, 'c');
- await tester.pump();
- expect(box.options.length, greaterThan(1));
- expect(box.cursor, 0);
- final first = box.selected!;
- final order = box.options.map((row) => row.id).toList();
- final firstBounds = tester.getRect(find.byKey(ValueKey(first.id)));
- await key(tester, LogicalKeyboardKey.arrowUp);
- expect(box.cursor, 1);
- expect(box.options.map((row) => row.id), order);
- expect(tester.getRect(find.byKey(ValueKey(first.id))), firstBounds);
- expect(find.text('Permissions'), findsNothing);
- expect(find.text('Codex Profile'), findsNothing);
- expect(
- tester.getRect(find.byKey(ValueKey(box.selected!.id))).center.dy,
- lessThan(firstBounds.center.dy),
- );
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(box.selected!.id, first.id);
- expect(tester.getRect(find.byKey(ValueKey(first.id))), firstBounds);
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.field, NewHarnessField.launch);
- expect(box.task, 'First line\nSecond line');
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pumpWidget(const SizedBox());
- },
- );
}
diff --git a/desktop/test/harness_command_bar_test.dart b/desktop/test/harness_command_bar_test.dart
index 60daeb9b5..39d701023 100644
--- a/desktop/test/harness_command_bar_test.dart
+++ b/desktop/test/harness_command_bar_test.dart
@@ -14,7 +14,7 @@ import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/harness_command_bar.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:xterm/xterm.dart';
import 'support/real_fonts.dart';
@@ -413,34 +413,29 @@ void main() {
await tester.enterText(input, 'Plan the arm calibration');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pumpAndSettle();
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(input, findsNothing);
final prompt = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(prompt.machineId, 'm');
expect(prompt.engine, 'studio/arm');
expect(prompt.project.folder, isNull);
expect(prompt.task, 'Plan the arm calibration');
expect(prompt.field, NewHarnessField.projectMenu);
- expect(find.byKey(const ValueKey('new-harness-input')), findsOneWidget);
- await tester.tap(
- find.byKey(const ValueKey(NewHarnessController.newProjectId)),
+ expect(
+ find.byKey(const ValueKey('new-harness-field-project')),
+ findsOneWidget,
);
- await tester.pump();
- expect(prompt.field, NewHarnessField.projectName);
expect(
- tester
- .widget<TextField>(find.byKey(const ValueKey('new-harness-input')))
- .focusNode!
- .hasFocus,
- isTrue,
+ FocusManager.instance.primaryFocus?.debugLabel,
+ 'new-harness-form',
);
// Opening the experimental prompt saves this draft and removes its dock.
await chord(tester, LogicalKeyboardKey.keyJ, shift: true);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(input, findsOneWidget);
expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
expect(app.allPanes, hasLength(1));
diff --git a/desktop/test/harness_picker_entry_test.dart b/desktop/test/harness_picker_entry_test.dart
index 5d9e9582b..1b5db0cec 100644
--- a/desktop/test/harness_picker_entry_test.dart
+++ b/desktop/test/harness_picker_entry_test.dart
@@ -7,11 +7,12 @@ import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/state/swarm_search.dart';
+import 'package:harness/state/new_harness.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shortcuts/app_keymap.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/swarm_switcher.dart';
-import 'package:harness/shared/widgets/app_choice_picker.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'swarm_interactions_test.dart' show chord;
import 'swarm_screen_test.dart' show terminal;
@@ -20,6 +21,8 @@ import 'swarm_state_test.dart' show createApp;
import 'support/real_fonts.dart';
void main() {
+ setUp(() => newHarnessOpensInBox = true);
+ tearDown(() => newHarnessOpensInBox = false);
setUpAll(() async {
await loadRealFonts();
for (final (name, asset) in [
@@ -125,22 +128,27 @@ void main() {
expect(tester.widget<TextField>(field).controller, same(controller));
expect(
find.textContaining('Payment retries now reuse'),
- findsOneWidget,
+ size.width >= 848 ? findsOneWidget : findsNothing,
);
await capture('results');
await chord(tester, LogicalKeyboardKey.keyN);
await tester.pumpAndSettle();
expect(field, findsNothing);
expect(find.byType(SwarmSearchResults), findsNothing);
- expect(find.byType(AlertDialog), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(
- find.byKey(const ValueKey('create-agent-submit')),
+ find.byKey(const ValueKey('new-harness-field-project')),
findsOneWidget,
);
- expect(find.byType(AppChoicePicker<String>), findsWidgets);
await capture('creation');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await capture('creation-options');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.focusedPane, same(pane));
expect(frames, isEmpty);
expect(tester.takeException(), isNull);
diff --git a/desktop/test/harness_placement_test.dart b/desktop/test/harness_placement_test.dart
index 83693ae35..f67bf4743 100644
--- a/desktop/test/harness_placement_test.dart
+++ b/desktop/test/harness_placement_test.dart
@@ -1,3 +1,5 @@
+import 'support/launch_menu.dart';
+
import 'dart:async';
import 'package:flutter/material.dart';
@@ -11,7 +13,7 @@ import 'package:harness/state/new_harness.dart';
import 'package:harness/state/pane_preset.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/codex_profile_field.dart';
import 'package:harness/ws/ws_conn.dart';
@@ -179,7 +181,7 @@ void main() {
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyT);
await chord(tester, LogicalKeyboardKey.keyO);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
await chord(tester, LogicalKeyboardKey.period);
await tester.pumpAndSettle();
@@ -220,7 +222,7 @@ void main() {
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
var box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(
box.task,
@@ -232,17 +234,12 @@ void main() {
);
expect(box.mode, 'readOnly');
expect(box.profileLabel, profile);
- expect(
- find.descendant(
- of: find.byKey(const ValueKey('new-harness-field-agent')),
- matching: find.textContaining('Read only · profile $profile'),
- ),
- findsOneWidget,
- );
- expect(box.field, NewHarnessField.launch);
+ expect(find.text('Read only'), findsOneWidget);
+ expect(find.text(profile), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(
FocusManager.instance.primaryFocus!.debugLabel,
- 'New harness launch',
+ 'new-harness-form',
);
expect(connection.requests, isEmpty);
expect(app.swarms, contains(original));
@@ -263,7 +260,7 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.profileLabel, profile);
// A second Escape leaves creation entirely. Reopening from the same
@@ -278,14 +275,14 @@ void main() {
inPane ? LogicalKeyboardKey.keyO : LogicalKeyboardKey.keyT,
);
if (!inPane) await chord(tester, LogicalKeyboardKey.keyO);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.profileLabel, profile);
expect(box.placement, HarnessPlacement.currentTab);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
final request = connection.requests.single;
expect(request.payload['permissionMode'], 'readOnly');
@@ -315,7 +312,7 @@ void main() {
await chord(tester, LogicalKeyboardKey.keyN);
expect(
tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
.task,
isEmpty,
@@ -342,15 +339,15 @@ void main() {
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyT);
await chord(tester, LogicalKeyboardKey.keyO);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
final input = find.byKey(const ValueKey('new-harness-input'));
tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
.focusField(NewHarnessField.task);
await tester.pump();
- await tester.enterText(input, 'Keep this first task');
+ await typeHarnessQuery(tester, 'Keep this first task');
await chord(tester, LogicalKeyboardKey.period);
await tester.pumpAndSettle();
await chord(tester, LogicalKeyboardKey.enter);
@@ -360,16 +357,16 @@ void main() {
await tester.tapAt(const Offset(4, 650));
await tester.pump();
expect(find.byType(AlertDialog), findsOneWidget);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
request.reply.completeError(const WsRequestTimeout('agent_create'));
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.checking, isTrue);
- expect(box.field, NewHarnessField.launch);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(input, findsNothing);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyW);
@@ -379,7 +376,7 @@ void main() {
expect(box.task, 'Keep this first task');
expect(app.swarms, contains(original));
expect(app.swarms, hasLength(2));
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
expect(connection.requests, hasLength(2));
expect(connection.requests.last.type, 'agent_create_status');
@@ -425,37 +422,26 @@ void main() {
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyT);
await chord(tester, LogicalKeyboardKey.keyO);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- final input = find.byKey(const ValueKey('new-harness-input'));
- tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller
- .focusField(NewHarnessField.task);
- await tester.pump();
- await tester.enterText(
- input,
- 'Review the project before changing anything',
- );
- await tester.tap(
- find.byKey(const ValueKey('new-harness-field-project')),
- );
+ await acceptSetupOrSearch(tester);
await tester.pump();
- await tester.tap(
- find.byKey(
- ValueKey(
- projectQuery.startsWith('/')
- ? NewHarnessController.existingProjectId
- : projectQuery.contains('/')
- ? NewHarnessController.repositoryId
- : NewHarnessController.newProjectId,
- ),
- ),
+ final setup = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
+ setup.task = 'Review the project before changing anything';
+ await openLaunchRow(tester, 'project');
+ final door = projectQuery.startsWith('/')
+ ? NewHarnessController.existingProjectId
+ : projectQuery.contains('/')
+ ? NewHarnessController.repositoryId
+ : NewHarnessController.newProjectId;
+ setup.move(
+ setup.options.indexWhere((row) => row.id == door) - setup.cursor,
);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- await tester.enterText(input, projectQuery);
+ await typeHarnessQuery(tester, projectQuery);
await tester.pump(const Duration(milliseconds: 250));
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
await chord(tester, LogicalKeyboardKey.period);
await tester.pumpAndSettle();
@@ -466,12 +452,12 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.mode, 'readOnly');
await chord(tester, LogicalKeyboardKey.period);
await tester.pumpAndSettle();
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(find.text(detail), findsOneWidget);
final mode = find.byKey(const Key('new-agent-permission-mode'));
expect(
@@ -502,7 +488,7 @@ void main() {
await chord(tester, LogicalKeyboardKey.keyN);
expect(
tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
.task,
isEmpty,
@@ -772,16 +758,16 @@ void main() {
final search = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(search, 'fix the login regression');
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.task, 'fix the login regression');
expect(box.placement, HarnessPlacement.currentTab);
box.setFolder('/work/project');
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
expect(box.busy, isTrue);
expect(
@@ -790,7 +776,7 @@ void main() {
);
Future<void> keepsPendingBox() async {
- expect(box.field, NewHarnessField.launch);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(box.locked, isTrue);
final task = box.task;
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
@@ -809,7 +795,9 @@ void main() {
expect(search, findsNothing);
expect(find.byType(AlertDialog), findsNothing);
expect(
- tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller,
+ tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller,
same(box),
);
expect(app.swarms, contains(original));
@@ -818,7 +806,7 @@ void main() {
await tester.tapAt(const Offset(12, 650));
await tester.pump();
expect(
- tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller,
+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller,
same(box),
reason:
'Clicking outside must preserve an active or unresolved creation',
@@ -834,13 +822,13 @@ void main() {
expect(box.checking, isTrue);
await keepsPendingBox();
expect(connection.requests, hasLength(1));
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
expect(connection.requests.last.type, 'agent_create_status');
connection.created();
await tester.pump();
await tester.pump();
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.swarms, hasLength(2));
expect(app.activeSwarm.name, 'Made');
expect(app.panes.single.agentId, 'made');
@@ -864,14 +852,14 @@ void main() {
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyT);
await chord(tester, LogicalKeyboardKey.keyO);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
.setFolder('/work/project');
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
final request = connection.requests.single;
expect(request.payload.containsKey('prompt'), isFalse);
@@ -879,32 +867,29 @@ void main() {
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
await chord(tester, LogicalKeyboardKey.keyO);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.task, isEmpty);
expect(box.checking, isTrue);
expect(find.text('pending harness'), findsNothing);
- expect(
- find.textContaining('check status', findRichText: true),
- findsOneWidget,
- );
+ expect(find.text('Check status'), 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.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
await chord(tester, LogicalKeyboardKey.keyO);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
expect(connection.requests, hasLength(2));
expect(connection.requests.last.type, 'agent_create_status');
@@ -965,10 +950,10 @@ void main() {
await chord(tester, LogicalKeyboardKey.keyO);
}
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.pump();
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.placement, HarnessPlacement.currentTab);
expect(box.engine, 'codex');
@@ -1044,7 +1029,7 @@ void main() {
await tester.pump();
await tester.pump();
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(
box.engine,
diff --git a/desktop/test/harness_store_entry_test.dart b/desktop/test/harness_store_entry_test.dart
index f41f4f725..6c3ea02ad 100644
--- a/desktop/test/harness_store_entry_test.dart
+++ b/desktop/test/harness_store_entry_test.dart
@@ -8,7 +8,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/state/new_harness.dart';
import 'package:harness/terminal/terminal_binary.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_switcher.dart';
import 'package:xterm/xterm.dart';
@@ -94,7 +94,7 @@ void main() {
.widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
.search;
expect(search.selected?.commandId, 'app.store', reason: query);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
expect(app.activeSwarm.isStore, isTrue);
expect(app.swarms, hasLength(2));
expect(find.byType(SwarmSearchResults), findsNothing);
@@ -133,20 +133,20 @@ void main() {
);
await tester.pump();
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.engine, 'studio/arm');
expect(box.task, prompt ?? '');
expect(box.projectLabel, startsWith('~/harnesses/robot-studio-'));
expect(box.projectFolderRequest!.isGenerated, isTrue);
expect(box.placement, HarnessPlacement.newTab);
- expect(box.field, NewHarnessField.launch);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
expect(app.activeSwarm, same(store));
expect(app.swarms, hasLength(count));
await key(tester, LogicalKeyboardKey.escape);
expect(app.activeSwarm, same(store));
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
await tester.pumpWidget(const SizedBox());
},
);
@@ -165,31 +165,29 @@ void main() {
final work = app.activeSwarm;
await configured.mount(tester, app, map);
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- final input = find.byKey(const ValueKey('new-harness-input'));
+
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
box.setFolder('/work/project');
await tester.pump();
- await openLegacyTaskEditor(tester);
- await tester.enterText(input, 'Finish the login feature');
+ box.task = 'Finish the login feature';
await tester.pump();
final draft = box.draft;
- await key(tester, LogicalKeyboardKey.escape);
await openLaunchRow(tester, 'agent');
- await tester.enterText(input, 'a harness not in this catalog');
+ await typeHarnessQuery(tester, 'a harness not in this catalog');
await tester.pump();
expect(box.selected?.id, NewHarnessController.storeId);
expect(find.text('Browse more harnesses…'), findsOneWidget);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
expect(app.activeSwarm.isStore, isTrue);
- expect(find.byType(NewHarnessBox), findsNothing);
+ 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<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(resumed.task, draft.task);
expect(resumed.engine, draft.engine);
diff --git a/desktop/test/keymap_runtime_test.dart b/desktop/test/keymap_runtime_test.dart
index 3c0a1d0ad..1bd136a6c 100644
--- a/desktop/test/keymap_runtime_test.dart
+++ b/desktop/test/keymap_runtime_test.dart
@@ -10,10 +10,12 @@ import 'package:harness/shortcuts/app_keymap.dart';
import 'package:harness/shortcuts/keymap.dart';
import 'package:harness/shortcuts/shortcuts_browser.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
import 'package:harness/state/pane_preset.dart';
import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/agent_picker.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_switcher.dart';
import 'package:xterm/xterm.dart';
@@ -60,6 +62,23 @@ Future<void> native(WidgetTester tester, String method, [Object? arguments]) {
}
Future<void> tabToResult(WidgetTester tester, {String? id}) async {
+ final results = find.byType(SwarmSearchResults);
+ if (results.evaluate().isNotEmpty) {
+ final search = tester.widget<SwarmSearchResults>(results).search;
+ if (search.setupLayout) {
+ for (var i = 0; i < search.rows.length; i++) {
+ if (id == null
+ ? search.selected?.isCreate == false
+ : search.selected?.id == id) {
+ break;
+ }
+ await key(tester, LogicalKeyboardKey.tab);
+ }
+ if (id != null) expect(search.selected?.id, id);
+ return;
+ }
+ }
+
ListTile? focusedResult() => FocusManager.instance.primaryFocus?.context
?.findAncestorWidgetOfExactType<ListTile>();
bool reached() => id == null
@@ -72,6 +91,86 @@ Future<void> tabToResult(WidgetTester tester, {String? id}) async {
}
void main() {
+ for (final command in ['newAgent', 'commands']) {
+ testWidgets('native $command preserves composing New Harness input', (
+ tester,
+ ) async {
+ final previousEntry = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = previousEntry);
+ final map = MemoryKeymap();
+ final app = createApp();
+ addTearDown(map.dispose);
+ addTearDown(app.dispose);
+ await mount(tester, app, map, native: true);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final form = find.byType(NewHarnessForm);
+ final original = tester.widget<NewHarnessForm>(form).controller;
+ final field = find.byKey(const ValueKey('new-harness-query'));
+ await tester.tap(field);
+ const composing = TextEditingValue(
+ text: 'moon',
+ selection: TextSelection.collapsed(offset: 4),
+ composing: TextRange(start: 0, end: 4),
+ );
+ tester.testTextInput.updateEditingValue(composing);
+ await tester.pump();
+ final opening = native(tester, command);
+ await tester.pump();
+ await opening;
+ expect(form, findsOneWidget);
+ expect(tester.widget<NewHarnessForm>(form).controller, same(original));
+ expect(tester.widget<TextField>(field).controller!.value, composing);
+ expect(original.query, 'moon');
+ expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
+ expect(app.panes, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
+ for (final mode in ['O', 'P']) {
+ for (final command in ['next', 'previous', 'submit', 'add', 'close']) {
+ testWidgets(
+ 'native search $command respects an IME candidate in Cmd-$mode',
+ (tester) async {
+ final map = MemoryKeymap();
+ final app = createApp();
+ addTearDown(map.dispose);
+ addTearDown(app.dispose);
+ await mount(tester, app, map, native: true);
+ await key(
+ tester,
+ mode == 'O' ? LogicalKeyboardKey.keyO : LogicalKeyboardKey.keyP,
+ cmd: true,
+ );
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ final candidate = mode == 'O' ? 'Agent' : '> rename';
+ final composing = TextEditingValue(
+ text: candidate,
+ selection: TextSelection.collapsed(offset: candidate.length),
+ composing: TextRange(
+ start: mode == 'O' ? 0 : 2,
+ end: candidate.length,
+ ),
+ );
+ tester.testTextInput.updateEditingValue(composing);
+ await tester.pump();
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ final selected = search.selected;
+ final opening = native(tester, 'searchCommand', {'command': command});
+ await tester.pump();
+ await opening;
+ expect(field, findsOneWidget);
+ expect(search.selected, same(selected));
+ expect(tester.widget<TextField>(field).controller!.value, composing);
+ expect(app.panes, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+ }
for (final remapped in [false, true]) {
testWidgets(
'the configured Layout key cycles choices and returns to latest output (remapped=$remapped)',
@@ -401,10 +500,7 @@ void main() {
await key(tester, LogicalKeyboardKey.arrowDown);
expect(search.cursor, initial);
await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
- expect(
- search.cursor,
- inline ? (initial - 1) % search.rows.length : initial + 1,
- );
+ expect(search.cursor, (initial - 1) % search.rows.length);
await tester.enterText(input, 'Agent 0');
await tester.pump();
expect(
@@ -695,7 +791,7 @@ void main() {
final next =
search.rows[inline
? (search.cursor + 1) % search.rows.length
- : (search.cursor - 1).clamp(0, search.rows.length - 1)];
+ : (search.cursor + 1) % search.rows.length];
await key(tester, LogicalKeyboardKey.arrowDown);
expect(search.selected, same(secondRow));
await key(tester, LogicalKeyboardKey.keyG, ctrl: true);
diff --git a/desktop/test/machines_manager_test.dart b/desktop/test/machines_manager_test.dart
index cc82a79a7..f6d2d0241 100644
--- a/desktop/test/machines_manager_test.dart
+++ b/desktop/test/machines_manager_test.dart
@@ -10,7 +10,7 @@ import 'package:harness/models/local_model.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/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:xterm/xterm.dart';
@@ -375,7 +375,7 @@ void main() {
await tester.pumpAndSettle();
await tester.tap(find.text('New harness'));
await tester.pumpAndSettle();
- final box = tester.widget<NewHarnessBox>(find.byType(NewHarnessBox));
+ final box = tester.widget<NewHarnessForm>(find.byType(NewHarnessForm));
expect(box.controller.machineId, 'fresh');
expect(box.controller.placement, HarnessPlacement.currentTab);
expect(app.panes.single.machineId, 'm', reason: 'Existing work stays open');
diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dart
index 7727e12a2..cdec80734 100644
--- a/desktop/test/models_menu_test.dart
+++ b/desktop/test/models_menu_test.dart
@@ -18,7 +18,7 @@ import 'package:harness/usage/usage_accounts.dart';
import 'package:harness/usage/usage_controller.dart';
import 'package:harness/usage/usage_source.dart';
import 'package:harness/usage/usage_window.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'swarm_screen_test.dart' show terminal;
import 'swarm_state_test.dart' show createApp;
@@ -413,7 +413,7 @@ void main() {
final source = app.activeSwarm;
await openGridDoor(tester, app, machineId: machineId, command: command);
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.engine, harness);
expect(box.machineId, machineId ?? 'm');
@@ -423,7 +423,7 @@ void main() {
expect(app.swarms, [source]);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.swarms, [source]);
if (command == 'manageMachines') {
await key(tester, LogicalKeyboardKey.keyP, cmd: true);
@@ -435,7 +435,7 @@ void main() {
await key(tester, LogicalKeyboardKey.enter);
expect(
tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
.engine,
harness,
@@ -456,7 +456,7 @@ void main() {
final app = ModelManagerTestApp(connection);
await openGridDoor(tester, app, machineId: remote ? 'other' : null);
expect(find.byType(AgentPicker), findsNothing);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.activeSwarm.isStore, isFalse);
expect(app.allPanes, isEmpty);
expect(find.byType(ModelsPanel), findsOneWidget);
diff --git a/desktop/test/new_harness_accessibility_test.dart b/desktop/test/new_harness_accessibility_test.dart
index 5bc8ca983..b3b101fb0 100644
--- a/desktop/test/new_harness_accessibility_test.dart
+++ b/desktop/test/new_harness_accessibility_test.dart
@@ -5,11 +5,12 @@ import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/state/new_harness.dart';
import 'package:harness/terminal/terminal_binary.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'keymap_host_test.dart' show MemoryKeymap, key;
import 'keymap_runtime_test.dart' show mount;
import 'support/mixed_agents.dart';
+import 'support/launch_menu.dart' show harnessChoicesActive;
import 'swarm_screen_test.dart' show terminal;
import 'swarm_state_test.dart' show createApp;
@@ -36,10 +37,27 @@ void main() {
.performAction(row.id, SemanticsAction.tap);
await tester.pump();
expect(
- tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller.field,
+ tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller
+ .field,
NewHarnessField.agent,
);
expect(input, isEmpty);
+ // Pointer users can open the same choices and return to field navigation.
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-agent')));
+ await tester.pump();
+ expect(harnessChoicesActive(tester), isTrue);
+ await tester.tap(find.byKey(const ValueKey('new-harness-option-claude')));
+ await tester.pump();
+ final box = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
+ expect(box.engine, 'claude');
+ expect(harnessChoicesActive(tester), isFalse);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.field, NewHarnessField.machine);
+ expect(input, isEmpty);
semantics.dispose();
await tester.pumpWidget(const SizedBox());
app.dispose();
diff --git a/desktop/test/new_harness_agent_settings_test.dart b/desktop/test/new_harness_agent_settings_test.dart
index 6c60a88fc..7c5c261fd 100644
--- a/desktop/test/new_harness_agent_settings_test.dart
+++ b/desktop/test/new_harness_agent_settings_test.dart
@@ -5,7 +5,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/engine_availability.dart';
import 'package:harness/state/new_harness.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/ws/ws_conn.dart';
import 'keymap_host_test.dart' show MemoryKeymap, key;
@@ -97,7 +97,6 @@ class _Profiles extends WsConn {
void main() {
setUp(() => newHarnessOpensInBox = true);
tearDown(() => newHarnessOpensInBox = false);
- final input = find.byKey(const ValueKey('new-harness-input'));
void setting(NewHarnessController box, String id) {
if (id == NewHarnessController.permissionsId ||
@@ -108,108 +107,40 @@ void main() {
}
}
- testWidgets(
- 'agent settings use pickers and launch with the chosen profile and permissions',
- (tester) async {
- final connection = _Profiles('m');
- final app = createApp(connectionForTest: (_) => connection);
- seedMixedAgents(app);
- addTearDown(app.dispose);
- final map = MemoryKeymap();
- addTearDown(map.dispose);
- app.adoptSessionForTest(terminal('a0', []));
- await configured.mount(tester, app, map);
- await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- expect(
- find.byKey(const ValueKey('new-harness-field-options')),
- findsNothing,
- );
- await openLaunchRow(tester, 'agent');
- await tester.enterText(input, 'Claude Code');
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.engine, 'claude');
- await openLaunchRow(tester, 'agent');
- for (final name in ['agent', 'machine', 'project']) {
- expect(find.byKey(ValueKey('new-harness-field-$name')), findsNothing);
- }
- expect(find.text('Codex profile…'), findsNothing);
- // Move from a saved Claude selection to Codex without accepting it.
- for (var step = 0; box.selected?.id != 'codex' && step < 30; step++) {
- await key(tester, LogicalKeyboardKey.arrowUp);
- }
- expect(box.selected?.id, 'codex');
- expect(box.engine, 'claude');
- expect(find.text('Permissions'), findsNothing);
- expect(find.text('Codex Profile'), findsNothing);
- await openAgentSetting(tester, 'codex', NewHarnessController.profileId);
- expect(box.field, NewHarnessField.profile);
- expect(box.agentSettingsLabel, 'Codex');
- await tester.tap(find.byKey(const ValueKey('new-harness-field-machine')));
- await tester.pump();
- expect(box.field, NewHarnessField.machine);
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.field, NewHarnessField.profile);
- expect(box.agentSettingsLabel, 'Codex');
- expect(box.engine, 'claude');
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.selected?.id, 'codex');
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.engine, 'claude', reason: 'Escape keeps the saved agent');
- expect(box.draft.profile, isNull);
- await openLaunchRow(tester, 'agent');
- await tester.enterText(input, 'zzzz');
- await tester.pump();
- expect(find.text('No agents match “zzzz”.'), findsOneWidget);
- expect(box.selected?.id, NewHarnessController.storeId);
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.engine, 'claude');
- await openLaunchRow(tester, 'agent');
- await tester.enterText(input, 'Codex');
- await tester.pump();
- await openAgentSetting(
- tester,
- 'codex',
- NewHarnessController.permissionsId,
- );
- expect(box.field, NewHarnessField.mode);
- await tester.enterText(input, 'read only');
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.field, NewHarnessField.agent);
- expect(box.mode, 'readOnly');
- await openAgentSetting(tester, 'codex', NewHarnessController.profileId);
- expect(box.field, NewHarnessField.profile);
- expect(connection.lists, greaterThanOrEqualTo(1));
- expect(
- box.draft.profile,
- isNull,
- reason: 'Discovery never changes the account',
- );
- await tester.enterText(input, 'Work');
- await key(tester, LogicalKeyboardKey.enter);
- expect(box.field, NewHarnessField.agent);
- expect(box.draft.profile!.path, '/profiles/m/work');
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.field, NewHarnessField.launch);
- expect(find.text('Codex · Read only · profile Work'), findsOneWidget);
- await openLaunchRow(tester, 'machine');
- expect(find.text('Choose a machine').first, findsOneWidget);
- for (final name in ['agent', 'machine', 'project']) {
- expect(find.byKey(ValueKey('new-harness-field-$name')), findsNothing);
- }
- await key(tester, LogicalKeyboardKey.escape);
- expect(box.machineId, 'm');
- expect(box.draft.profile!.path, '/profiles/m/work');
- expect(connection.creates, isEmpty);
- await key(tester, LogicalKeyboardKey.enter);
- expect(connection.creates.single['codexHome'], '/profiles/m/work');
- expect(connection.creates.single['permissionMode'], 'readOnly');
- await tester.pumpWidget(const SizedBox());
- await tester.pump(const Duration(milliseconds: 200));
- },
- );
+ testWidgets('setup launches with the chosen profile and approvals', (
+ tester,
+ ) async {
+ final connection = _Profiles('m');
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final box = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
+ await openLaunchRow(tester, 'approvals');
+ await typeHarnessQuery(tester, 'read only');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.mode, 'readOnly');
+ await openLaunchRow(tester, 'profile');
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(connection.lists, greaterThanOrEqualTo(1));
+ expect(box.draft.profile, isNull);
+ await typeHarnessQuery(tester, 'Work');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.draft.profile!.path, '/profiles/m/work');
+ expect(connection.creates, isEmpty);
+ await startHarness(tester);
+ expect(connection.creates.single['codexHome'], '/profiles/m/work');
+ expect(connection.creates.single['permissionMode'], 'readOnly');
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 200));
+ });
testWidgets('profile discovery ignores replies from the previous machine', (
tester,
diff --git a/desktop/test/new_harness_box_test.dart b/desktop/test/new_harness_box_test.dart
index f234bc60a..46cca6b87 100644
--- a/desktop/test/new_harness_box_test.dart
+++ b/desktop/test/new_harness_box_test.dart
@@ -13,8 +13,7 @@ import 'package:harness/core/repository_clone.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/box_chrome.dart' show kWorkspaceInset;
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/ws/ws_conn.dart';
import 'package:path/path.dart' as p;
@@ -532,20 +531,17 @@ void main() {
await chord(tester, LogicalKeyboardKey.keyN);
await tester.pump();
expect(find.byType(AlertDialog), findsNothing);
- expect(find.byKey(const ValueKey('new-harness-box')), findsOneWidget);
- // Attached to the workspace's bottom edge, without dimming or resizing it.
- final dock = tester.getRect(find.byKey(const ValueKey('new-harness-box')));
- expect(dock.left, kWorkspaceInset);
- expect(dock.right, tester.view.physicalSize.width - kWorkspaceInset);
- expect(dock.bottom, tester.view.physicalSize.height - kWorkspaceInset);
- expect(find.byKey(const ValueKey('new-harness-input')), findsNothing);
- expect(
- FocusManager.instance.primaryFocus!.debugLabel,
- 'New harness launch',
+ expect(find.byKey(const ValueKey('new-harness-form')), findsOneWidget);
+ final frame = tester.getRect(
+ find.byKey(const ValueKey('new-harness-form')),
);
+ 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');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- expect(find.byKey(const ValueKey('new-harness-box')), findsNothing);
+ expect(find.byKey(const ValueKey('new-harness-form')), findsNothing);
await tester.pumpWidget(const SizedBox());
app.dispose();
});
@@ -793,7 +789,7 @@ void main() {
child: SizedBox(
width: 720,
height: 420,
- child: NewHarnessBox(
+ child: NewHarnessForm(
controller: box,
onClose: () => closed++,
onCreated: () {},
@@ -805,31 +801,17 @@ void main() {
),
);
await tester.pump();
- final input = find.byKey(const ValueKey('new-harness-input'));
- expect(box.field, NewHarnessField.launch);
- expect(input, findsNothing);
+ expect(box.field, NewHarnessField.projectMenu);
await openLaunchRow(tester, 'agent');
- await tester.pump();
- expect(box.field, NewHarnessField.agent);
- expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
- await tester.enterText(input, 'clau');
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
- await tester.pump();
- expect(box.query, 'Claude Code');
+ await typeHarnessQuery(tester, 'clau');
expect(box.engine, 'codex');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(box.engine, 'claude');
- expect(box.field, NewHarnessField.launch);
- await openLegacyTaskEditor(tester);
- await tester.pump();
- await tester.enterText(input, 'a project to test');
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- expect(box.field, NewHarnessField.launch);
- expect(box.task, 'a project to test');
+ expect(box.field, NewHarnessField.agent);
expect(closed, 0);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
expect(closed, 1);
await tester.pumpWidget(const SizedBox());
box.dispose();
diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dart
index 56c6cbec7..4375da0ce 100644
--- a/desktop/test/new_harness_entry_rules_test.dart
+++ b/desktop/test/new_harness_entry_rules_test.dart
@@ -1,3 +1,5 @@
+import 'support/launch_menu.dart';
+
import 'dart:async';
import 'package:flutter/material.dart';
@@ -9,7 +11,7 @@ import 'package:harness/state/app_state.dart';
import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/new_harness.dart';
import 'package:harness/store/store_screen.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_search_input.dart';
import 'package:harness/ws/ws_conn.dart';
@@ -97,9 +99,9 @@ void main() {
late AppNotifier app;
late MemoryKeymap map;
late Map<String, _Connection> connections;
- final input = find.byKey(const ValueKey('new-harness-input'));
+
NewHarnessController box(WidgetTester tester) =>
- tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;
+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller;
setUp(() {
newHarnessOpensInBox = true;
@@ -152,19 +154,19 @@ void main() {
Future<void> dismiss(WidgetTester tester) async {
for (
var i = 0;
- i < 4 && find.byType(NewHarnessBox).evaluate().isNotEmpty;
+ i < 4 && find.byType(NewHarnessForm).evaluate().isNotEmpty;
i++
) {
await key(tester, LogicalKeyboardKey.escape);
}
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
}
Future<void> nameProject(WidgetTester tester, String name) async {
box(tester).focusField(NewHarnessField.projectName);
await tester.pump();
- await tester.enterText(input, name);
- await key(tester, LogicalKeyboardKey.enter);
+ await typeHarnessQuery(tester, name);
+ await acceptSetupOrSearch(tester);
}
for (final shortcut in [LogicalKeyboardKey.keyN, LogicalKeyboardKey.keyO]) {
@@ -175,7 +177,7 @@ void main() {
final origin = app.activeSwarm;
await key(tester, shortcut, cmd: true);
if (shortcut != LogicalKeyboardKey.keyN) {
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
}
final controller = box(tester);
const initial = HarnessPlacement.currentTab;
@@ -186,10 +188,9 @@ void main() {
findsNothing,
);
}
- expect(find.text('New Harness'), findsNothing);
- expect(find.text('Start Harness'), findsOneWidget);
+ expect(find.text('New Harness'), findsOneWidget);
expect(connections['m']!.starts, isEmpty);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
expect(connections['m']!.starts, hasLength(1));
connections['m']!.created();
await tester.pump();
@@ -308,7 +309,7 @@ void main() {
task: task,
);
final displayed = box(tester).projectFolderRequest!.folderName;
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
expect(connections['m']!.starts, isEmpty);
final connection = connections['studio']!;
expect(connection.starts, hasLength(1));
@@ -324,7 +325,7 @@ void main() {
expect(app.activeSwarm.isStore, isFalse);
expect(app.focusedPane?.machineId, 'studio');
expect(app.focusedPane?.agentId, 'created-1');
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
await tester.pumpWidget(const SizedBox());
},
);
@@ -405,7 +406,7 @@ void main() {
.search!;
expect(updated.query, 'login');
expect(updated.selected?.agentId, 'a1');
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
expect(app.focusedPane?.agentId, 'a1');
expect(app.activeSwarm, same(origin));
expect(app.swarms.length, 1);
@@ -441,10 +442,10 @@ void main() {
expect(find.text('New Pane'), findsNothing);
expect(app.swarms.first, same(origin));
expect(app.swarms.length, 1);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
expect(box(tester).task, 'Check the keyboard workflow');
expect(box(tester).placement, HarnessPlacement.currentTab);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
expect(
connections['m']!.starts.single['prompt'],
'Check the keyboard workflow',
@@ -467,16 +468,14 @@ void main() {
await tester.pump();
final shortcut = LogicalKeyboardKey.keyO;
await key(tester, shortcut, cmd: true);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await nameProject(tester, 'keyboard-review');
- box(tester).focusField(NewHarnessField.task);
- await tester.pump();
- await tester.enterText(input, 'Review this project');
+ box(tester).task = 'Review this project';
await dismiss(tester);
app.focusPane(other.id);
await tester.pump();
await key(tester, shortcut, cmd: true);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
expect(box(tester).engine, 'autonomous/typst');
expect(box(tester).project.folder, '/work/release-notes');
expect(box(tester).task, isEmpty);
@@ -484,7 +483,7 @@ void main() {
app.focusPane(first.id);
await tester.pump();
await key(tester, shortcut, cmd: true);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
expect(box(tester).engine, 'codex');
expect(box(tester).project.name, 'keyboard-review');
expect(box(tester).task, 'Review this project');
@@ -502,28 +501,25 @@ void main() {
final origin = app.activeSwarm;
final shortcut = LogicalKeyboardKey.keyO;
await key(tester, shortcut, cmd: true);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
var draft = box(tester);
expect(draft.engine, 'codex');
expect(draft.machineId, 'm');
expect(draft.project.folder, '/work/openharness');
expect(app.swarms.first, same(origin));
expect(app.swarms.length, 1);
- draft.focusField(NewHarnessField.task);
- await tester.pump();
- await tester.enterText(input, 'Check keyboard focus');
- await key(tester, LogicalKeyboardKey.escape);
+ draft.task = 'Check keyboard focus';
await nameProject(tester, 'keyboard-review');
await dismiss(tester);
expect(app.swarms, [origin]);
expect(app.activeSwarm, same(origin));
await key(tester, LogicalKeyboardKey.keyO, cmd: true);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
draft = box(tester);
expect(draft.task, 'Check keyboard focus');
expect(draft.project.name, 'keyboard-review');
expect(draft.placement, HarnessPlacement.currentTab);
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
final connection = connections['m']!;
expect(connection.starts, hasLength(1));
expect(connection.starts.single['engine'], 'codex');
@@ -533,7 +529,7 @@ void main() {
connection.created();
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.swarms.length, 1);
expect(app.activeSwarm.panes.last.agentId, 'created-1');
expect(app.focusedPane?.agentId, 'created-1');
@@ -547,7 +543,7 @@ void main() {
await key(tester, LogicalKeyboardKey.keyO, cmd: true);
final search = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(search, '# openharness');
- await key(tester, LogicalKeyboardKey.enter);
+ await acceptSetupOrSearch(tester);
await tester.enterText(search, 'login');
final before = tester
.widget<SwarmSearchInput>(find.byType(SwarmSearchInput))
diff --git a/desktop/test/new_harness_form_test.dart b/desktop/test/new_harness_form_test.dart
new file mode 100644
index 000000000..97127f66d
--- /dev/null
+++ b/desktop/test/new_harness_form_test.dart
@@ -0,0 +1,739 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/box_chrome.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/mixed_agents.dart';
+import 'support/launch_menu.dart' show harnessChoicesActive;
+import 'swarm_state_test.dart' show createApp;
+
+/// The setup form is driven by six keys and nothing else, so every one of
+/// them is pressed here against a real controller. The bugs this file exists
+/// to stop were all the same shape: a key that moved something and then had
+/// its effect undone by the refresh that followed.
+/// Answers the one request the form's Git rows depend on, so Worktree and
+/// Branch are exercised rather than skipped as unavailable.
+class _Git extends WsConn {
+ _Git()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'engines_probe') return {'engines': []};
+ if (type == 'dsh_list') return {'dsh': []};
+ if (type == 'git_project_info') {
+ return {
+ 'isGit': true,
+ 'branch': 'main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ {'ref': 'refs/heads/feature', 'name': 'feature'},
+ ],
+ };
+ }
+ return {};
+ }
+}
+
+void main() {
+ Future<NewHarnessController> mount(
+ WidgetTester tester, {
+ bool created = false,
+ String? engine,
+ }) async {
+ final app = createApp(connectionForTest: (_) => _Git());
+ seedMixedAgents(app);
+ await app.projectHistory.select('m', '/work/harness-app-landing-page');
+ await app.projectHistory.select('m', '/work/harness-monitor');
+ await app.projectHistory.select('m', '/work/autonomous-harness');
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: engine,
+ folder: '/work/harness-app-landing-page',
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 820,
+ height: 450,
+ child: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return box;
+ }
+
+ Future<void> press(WidgetTester tester, LogicalKeyboardKey key) async {
+ await tester.sendKeyEvent(key);
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> type(WidgetTester tester, String text) async {
+ final input = find.byKey(const ValueKey('new-harness-query'));
+ final previous = tester.widget<TextField>(input).controller!.text;
+ await tester.enterText(input, previous + text);
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('shared setup fields stay available for every agent', (
+ tester,
+ ) async {
+ await mount(tester);
+ for (final label in [
+ 'Project',
+ 'Agent',
+ 'Machine',
+ 'Branch',
+ 'Worktree',
+ 'Approvals',
+ ]) {
+ expect(find.text(label), findsOneWidget, reason: '$label must not go');
+ }
+ });
+
+ testWidgets('down and up walk the rows and wrap', (tester) async {
+ final box = await mount(tester);
+ expect(box.field, NewHarnessField.projectMenu);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.field, NewHarnessField.agent);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.field, NewHarnessField.machine);
+ await press(tester, LogicalKeyboardKey.arrowUp);
+ expect(box.field, NewHarnessField.agent);
+ await press(tester, LogicalKeyboardKey.arrowUp);
+ expect(box.field, NewHarnessField.projectMenu);
+ });
+
+ testWidgets('right walks every agent instead of bouncing between two', (
+ tester,
+ ) async {
+ final box = await mount(tester);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.field, NewHarnessField.agent);
+ final seen = <String>{box.engine};
+ for (var i = 0; i < 6; i++) {
+ await press(tester, LogicalKeyboardKey.arrowRight);
+ seen.add(box.engine);
+ }
+ expect(
+ seen.length,
+ greaterThan(2),
+ reason: 'Stepping from the cursor made the arrows flip between a pair.',
+ );
+ });
+
+ testWidgets('left and right step opposite ways and return', (tester) async {
+ final box = await mount(tester);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ final first = box.engine;
+ await press(tester, LogicalKeyboardKey.arrowRight);
+ expect(box.engine, isNot(first));
+ await press(tester, LogicalKeyboardKey.arrowLeft);
+ expect(box.engine, first, reason: 'Left must undo right.');
+ });
+
+ testWidgets('right walks the projects', (tester) async {
+ final box = await mount(tester);
+ final seen = <String>{box.projectLabel};
+ for (var i = 0; i < 4; i++) {
+ await press(tester, LogicalKeyboardKey.arrowRight);
+ seen.add(box.projectLabel);
+ }
+ expect(seen.length, greaterThan(2));
+ });
+
+ testWidgets('worktree flips on its own row, without a list', (tester) async {
+ final box = await mount(tester);
+ for (var i = 0; i < 4; i++) {
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ }
+ final was = box.worktree;
+ await press(tester, LogicalKeyboardKey.arrowRight);
+ expect(box.worktree, !was);
+ await press(tester, LogicalKeyboardKey.arrowLeft);
+ expect(box.worktree, was);
+ });
+
+ testWidgets('a hyphen is typed, never swallowed as a value key', (
+ tester,
+ ) async {
+ final box = await mount(tester);
+ final engine = box.engine;
+ await type(tester, 'harness-app');
+ expect(
+ box.query,
+ 'harness-app',
+ reason: 'Folder and branch names are full of hyphens.',
+ );
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.engine, engine, reason: 'and it changed no value on the way.');
+ });
+
+ testWidgets('a path prompt asks for a path, not a search', (tester) async {
+ final box = await mount(tester);
+ await press(tester, LogicalKeyboardKey.enter);
+ for (var step = 0; step < 40; step++) {
+ if (box.selected?.id == NewHarnessController.existingProjectId) break;
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ }
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.project);
+ expect(find.textContaining('Search'), findsNothing);
+ expect(find.textContaining('path'), findsOneWidget);
+ });
+
+ testWidgets('typing filters, and one match still shows its list', (
+ tester,
+ ) async {
+ final box = await mount(tester);
+ await type(tester, 'landing');
+ expect(box.query, 'landing');
+ expect(
+ box.matchCount,
+ greaterThan(0),
+ reason: 'A subsequence search must find harness-app-landing-page.',
+ );
+ expect(
+ find.text('harness-app-landing-page'),
+ findsOneWidget,
+ reason: 'Hiding the list on one match made a hit look like a miss.',
+ );
+ expect(
+ harnessChoicesActive(tester),
+ isTrue,
+ reason: 'Typing hands the keyboard to the filtered choices.',
+ );
+ });
+
+ testWidgets('a gappy query still matches, fzf style', (tester) async {
+ final box = await mount(tester);
+ await type(tester, 'harness l');
+ expect(box.matchCount, greaterThan(0));
+ });
+
+ testWidgets('backspace deletes and escape clears before it closes', (
+ tester,
+ ) async {
+ var closed = false;
+ final app = createApp();
+ seedMixedAgents(app);
+ final box = NewHarnessController(app, machineId: 'm');
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ home: Scaffold(
+ body: SizedBox(
+ width: 820,
+ height: 450,
+ child: NewHarnessForm(
+ controller: box,
+ onClose: () => closed = true,
+ onCreated: () {},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await type(tester, 'har');
+ expect(box.query, 'har');
+ await press(tester, LogicalKeyboardKey.backspace);
+ expect(box.query, 'ha');
+ await press(tester, LogicalKeyboardKey.escape);
+ expect(box.query, isEmpty, reason: 'Escape gives the text back first.');
+ expect(closed, isFalse);
+ await press(tester, LogicalKeyboardKey.escape);
+ expect(closed, isTrue, reason: 'A second Escape closes.');
+ });
+
+ testWidgets('down moves the highlight in the list without resetting it', (
+ tester,
+ ) async {
+ final box = await mount(tester);
+ await type(tester, 'harness');
+ final first = box.selected?.id;
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(
+ box.selected?.id,
+ isNot(first),
+ reason: 'Applying each row as it was passed snapped the cursor home.',
+ );
+ final second = box.selected?.id;
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.selected?.id, isNot(second));
+ });
+
+ testWidgets('return takes the highlighted match and clears the search', (
+ tester,
+ ) async {
+ final box = await mount(tester);
+ await type(tester, 'harness');
+ final wanted = box.selected?.title;
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.query, isEmpty, reason: 'Taking a value ends the search.');
+ if (wanted != null) {
+ expect(box.projectLabel, contains(wanted));
+ }
+ });
+
+ testWidgets('the doors lead, and the highlight opens on the first project', (
+ tester,
+ ) async {
+ final box = await mount(tester);
+ await type(tester, 'harness');
+ expect(
+ tester.getTopLeft(find.text('New Project')).dy,
+ lessThan(tester.getTopLeft(find.text('harness-monitor')).dy),
+ reason: 'The three doors sit above the recents, not under them.',
+ );
+ expect(
+ box.selected?.synthetic,
+ isFalse,
+ reason: 'The highlight opens on the first real project, not a door.',
+ );
+ });
+
+ testWidgets('Tab walks the rows and never escapes the form', (tester) async {
+ final box = await mount(tester);
+ for (var i = 0; i < 3; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pumpAndSettle();
+ }
+ expect(box.field, NewHarnessField.branch, reason: 'Tab walks the rows.');
+ // The real bug: traversal moved focus out and the form went deaf. Up
+ // rather than down, since the row under Branch edits no field at all.
+ await press(tester, LogicalKeyboardKey.arrowUp);
+ expect(
+ box.field,
+ NewHarnessField.machine,
+ reason: 'Keys must still reach the form after Tab.',
+ );
+ });
+
+ testWidgets('the doors lead, and the highlight opens on the first project', (
+ tester,
+ ) async {
+ final box = await mount(tester);
+ await type(tester, 'harness');
+ expect(
+ tester.getTopLeft(find.text('New Project')).dy,
+ lessThan(tester.getTopLeft(find.text('harness-monitor')).dy),
+ reason: 'The three doors sit above the recents, not under them.',
+ );
+ expect(
+ box.selected?.synthetic,
+ isFalse,
+ reason: 'The highlight opens on the first real project, not a door.',
+ );
+ });
+
+ testWidgets('the doors can be reached and opened', (tester) async {
+ final box = await mount(tester);
+ await type(tester, 'harness');
+ // Walk down past the matches until the highlight lands on a door.
+ var guard = 0;
+ while (box.selected?.synthetic != true && guard++ < 30) {
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ }
+ expect(
+ box.selected?.synthetic,
+ isTrue,
+ reason: 'A row drawn but unreachable is worse than one not drawn.',
+ );
+ // New Project opens its own prompt rather than answering the row.
+ while (box.selected?.id != NewHarnessController.newProjectId &&
+ guard++ < 60) {
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ }
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.projectName);
+ expect(find.text('New Project'), findsOneWidget);
+ // And Escape backs out of the door to the list it came from.
+ await press(tester, LogicalKeyboardKey.escape);
+ expect(box.field, NewHarnessField.projectMenu);
+ });
+
+ testWidgets('the doors are still listed', (tester) async {
+ await mount(tester);
+ await type(tester, 'harness');
+ expect(find.text('Open Folder'), findsOneWidget);
+ expect(find.text('New Project'), findsOneWidget);
+ expect(find.text('Clone Repository'), findsOneWidget);
+ });
+
+ testWidgets('the choices are always listed, and Return makes them live', (
+ tester,
+ ) async {
+ final box = await mount(tester);
+ expect(find.text('New Harness'), findsOneWidget);
+ expect(
+ find.text('Open Folder'),
+ findsOneWidget,
+ reason: 'The doors are on screen without being searched for.',
+ );
+
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.busy, isFalse, reason: 'A stray Return must not launch.');
+ final first = box.selected?.id;
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(
+ box.field,
+ NewHarnessField.projectMenu,
+ reason: 'With the list live the arrows move in it, not between rows.',
+ );
+ expect(box.selected?.id, isNot(first));
+
+ // Escape hands the arrows back to the rows; the list stays on screen.
+ await press(tester, LogicalKeyboardKey.escape);
+ expect(find.text('Open Folder'), findsOneWidget);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.field, NewHarnessField.agent);
+ });
+
+ testWidgets('the selection bar marks which column has the keys', (
+ tester,
+ ) async {
+ final bright = Colors.white.withValues(alpha: .12);
+ int barsOn() => tester
+ .widgetList<Container>(find.byType(Container))
+ .where((box) => box.color == bright)
+ .length;
+
+ await mount(tester);
+ final choices = find.byKey(const ValueKey('new-harness-choices'));
+ expect(
+ tester
+ .widgetList<Container>(
+ find.descendant(of: choices, matching: find.byType(Container)),
+ )
+ .where((box) => box.color != null && box.color != Colors.transparent),
+ isEmpty,
+ reason: 'The right column must not highlight a saved value while the left has focus.',
+ );
+ expect(
+ barsOn(),
+ 1,
+ reason: 'At rest the item column holds the only full highlight.',
+ );
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(
+ barsOn(),
+ 1,
+ reason: 'Live, the bar moves to the list — it never lights both.',
+ );
+ expect(harnessChoicesActive(tester), isTrue);
+ await press(tester, LogicalKeyboardKey.escape);
+ expect(harnessChoicesActive(tester), isFalse);
+ });
+
+ testWidgets('the list dims while the items hold the keys', (tester) async {
+ final box = await mount(tester);
+ // An unselected option stays quieter than the active choice.
+ final other = box.options
+ .firstWhere((row) => !row.synthetic && !identical(row, box.selected))
+ .title;
+ Color? inkOf(String text) =>
+ tester.widget<Text>(find.text(text)).style?.color;
+
+ expect(
+ inkOf(other),
+ kBoxFaint,
+ reason: 'The column the arrows are not in is grey.',
+ );
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(
+ inkOf(other),
+ Colors.white70,
+ reason: 'Handing the arrows over brings the column up.',
+ );
+ await press(tester, LogicalKeyboardKey.escape);
+ expect(inkOf(other), kBoxFaint);
+ });
+
+ testWidgets('the right column follows the focused row', (tester) async {
+ await mount(tester);
+ expect(find.text('Open Folder'), findsOneWidget);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ expect(
+ find.text('Open Folder'),
+ findsNothing,
+ reason: 'Agent has its own choices; it must not show the project doors.',
+ );
+ expect(find.text('Codex'), findsWidgets);
+ });
+
+ testWidgets('creation stays a distinct action while editing values', (
+ tester,
+ ) async {
+ await mount(tester);
+ expect(find.text('New Harness'), findsOneWidget);
+ expect(
+ tester
+ .widget<Semantics>(
+ find.byKey(const ValueKey('new-harness-field-start')),
+ )
+ .properties
+ .selected,
+ isFalse,
+ );
+ });
+
+ testWidgets('a visible prompt names the search, and shows what is typed', (
+ tester,
+ ) async {
+ await mount(tester);
+ expect(
+ find.text('Search project'),
+ findsOneWidget,
+ reason: '"Type to search" in a key guide is a sentence nobody reads.',
+ );
+ // The caret belongs to the arrows: absent until they are handed over.
+ EditableText input() =>
+ tester.widget<EditableText>(find.byType(EditableText));
+ expect(input().showCursor, isFalse);
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(input().showCursor, isTrue);
+ expect(input().focusNode.hasFocus, isTrue);
+
+ await type(tester, 'harn');
+ expect(find.text('harn'), findsOneWidget);
+ expect(input().controller.text, 'harn');
+ await press(tester, LogicalKeyboardKey.escape);
+ await press(tester, LogicalKeyboardKey.escape);
+ expect(input().showCursor, isFalse);
+ // Worktree is a boolean: no list, so no prompt either.
+ await press(tester, LogicalKeyboardKey.escape);
+ for (var i = 0; i < 4; i++) {
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ }
+ expect(find.textContaining('Search '), findsNothing);
+ });
+
+ testWidgets('the field stays put when its choices open', (tester) async {
+ await mount(tester);
+ final field = find.byKey(const ValueKey('new-harness-field-project'));
+ final before = tester.getRect(field);
+ await type(tester, 'harness');
+ expect(find.text('harness-monitor'), findsWidgets);
+ expect(
+ tester.getRect(field),
+ before,
+ reason: 'Filtering changes choices without moving the field.',
+ );
+ });
+
+ /// Walk the highlight in the open list until [wanted] holds, so a test
+ /// asserts on the row it meant rather than on a position.
+ Future<void> highlight(
+ WidgetTester tester,
+ NewHarnessController box,
+ bool Function(NewHarnessOption row) wanted,
+ ) async {
+ for (var step = 0; step < 40; step++) {
+ final row = box.selected;
+ if (row != null && wanted(row)) return;
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ }
+ fail('Never reached the wanted row.');
+ }
+
+ testWidgets('Open Folder asks the app to browse', (tester) async {
+ var browsed = false;
+ final app = createApp(connectionForTest: (_) => _Git());
+ seedMixedAgents(app);
+ await app.projectHistory.select('m', '/work/harness-app-landing-page');
+ final box = NewHarnessController(app, machineId: 'm', folder: '/work/a');
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ home: Scaffold(
+ body: SizedBox(
+ width: 820,
+ height: 450,
+ child: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
+ onBrowse: () => browsed = true,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await type(tester, 'harness');
+ // "Open Folder" in the menu opens a path prompt; the chooser itself is
+ // a row inside THAT list, which must be on screen before anything typed.
+ await highlight(
+ tester,
+ box,
+ (row) => row.id == NewHarnessController.existingProjectId,
+ );
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.project);
+ await highlight(
+ tester,
+ box,
+ (row) => row.id == NewHarnessController.browseId,
+ );
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(browsed, isTrue, reason: 'Open Folder must reach the chooser.');
+ });
+
+ testWidgets('New Project names a project and takes it', (tester) async {
+ final box = await mount(tester);
+ await press(tester, LogicalKeyboardKey.enter);
+ await highlight(
+ tester,
+ box,
+ (row) => row.id == NewHarnessController.newProjectId,
+ );
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.projectName);
+ await type(tester, 'ledger');
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(
+ box.projectLabel,
+ contains('ledger'),
+ reason: 'Naming a project must actually set it.',
+ );
+ });
+
+ testWidgets('Clone opens the repository prompt', (tester) async {
+ final box = await mount(tester);
+ await type(tester, 'harness');
+ await highlight(
+ tester,
+ box,
+ (row) => row.id == NewHarnessController.repositoryId,
+ );
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.projectRepository);
+ expect(find.text('Repository'), findsOneWidget);
+ });
+
+ testWidgets('a new branch name can be created from the Branch row', (
+ tester,
+ ) async {
+ final box = await mount(tester);
+ for (var i = 0; i < 3; i++) {
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ }
+ expect(box.field, NewHarnessField.branch);
+ await type(tester, 'spike');
+ await highlight(
+ tester,
+ box,
+ (row) => row.id.startsWith(NewHarnessController.createBranchId),
+ );
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(
+ box.branchRowLabel,
+ contains('spike'),
+ reason: 'Create branch is an answer, not a door.',
+ );
+ });
+
+ testWidgets('the worktree row reads as a question', (tester) async {
+ final box = await mount(tester);
+ expect(find.text('Worktree'), findsOneWidget);
+ expect(find.text('Yes'), findsOneWidget);
+ for (var i = 0; i < 4; i++) {
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ }
+ await press(tester, LogicalKeyboardKey.arrowRight);
+ expect(box.worktree, isFalse);
+ expect(find.text('No'), findsOneWidget);
+ });
+
+ testWidgets('Profile follows the chosen agent and hidden rows are skipped', (
+ tester,
+ ) async {
+ final box = await mount(tester, engine: 'codex');
+ expect(find.text('Profile'), findsOneWidget);
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ await type(tester, 'claude');
+ expect(box.engine, 'codex');
+ expect(find.text('Profile'), findsOneWidget);
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.engine, 'claude');
+ expect(find.text('Profile'), findsNothing);
+
+ for (var i = 0; i < 4; i++) {
+ await press(tester, LogicalKeyboardKey.arrowDown);
+ }
+ expect(box.field, NewHarnessField.mode);
+ await press(tester, LogicalKeyboardKey.tab);
+ expect(
+ tester
+ .widget<Semantics>(
+ find.byKey(const ValueKey('new-harness-field-start')),
+ )
+ .properties
+ .selected,
+ isTrue,
+ );
+ await press(tester, LogicalKeyboardKey.arrowUp);
+ expect(
+ tester
+ .widget<Semantics>(
+ find.byKey(const ValueKey('new-harness-field-approvals')),
+ )
+ .properties
+ .selected,
+ isTrue,
+ );
+
+ for (var i = 0; i < 4; i++) {
+ await press(tester, LogicalKeyboardKey.arrowUp);
+ }
+ await type(tester, 'codex');
+ expect(find.text('Profile'), findsNothing);
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.engine, 'codex');
+ expect(find.text('Profile'), findsOneWidget);
+ });
+
+ testWidgets('typing moves keyboard focus from fields to choices', (
+ tester,
+ ) async {
+ await mount(tester);
+ expect(harnessChoicesActive(tester), isFalse);
+ await type(tester, 'harness');
+ expect(harnessChoicesActive(tester), isTrue);
+ expect(find.text('Select Item'), findsNothing);
+ });
+}
diff --git a/desktop/test/new_harness_git_test.dart b/desktop/test/new_harness_git_test.dart
index beeaa5241..929eb569a 100644
--- a/desktop/test/new_harness_git_test.dart
+++ b/desktop/test/new_harness_git_test.dart
@@ -2,7 +2,6 @@ import 'dart:async';
import 'dart:io';
import 'dart:math';
-import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -10,7 +9,7 @@ import 'package:harness/core/git_worktree.dart';
import 'package:harness/core/models.dart';
import 'package:harness/e2ee/envelope.dart';
import 'package:harness/state/new_harness.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/ws/ws_conn.dart';
import 'box_render_preview_test.dart' show loadPreviewFonts;
@@ -49,6 +48,7 @@ class _Connection extends WsConn {
final answers = <String, Map<String, dynamic>>{};
Map<String, dynamic>? failure;
bool loseReply = false;
+ int gitFailures = 0;
@override
Future<Map<String, dynamic>> request(
String type, {
@@ -58,6 +58,10 @@ class _Connection extends WsConn {
if (type == 'git_project_info') {
final path = payload['path'] as String;
reads.add(path);
+ if (gitFailures > 0) {
+ gitFailures--;
+ throw const WsRequestTimeout('git_project_info');
+ }
return pending[path]?.future ??
Future.value(
answers[path] ?? (path == '/plain' ? {'isGit': false} : _git),
@@ -110,6 +114,80 @@ void main() {
);
Future<void> settle() => Future<void>.delayed(Duration.zero);
+
+ test(
+ 'failed Git discovery blocks launch and the next Start retries it',
+ () async {
+ final connection = _Connection()..gitFailures = 2;
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/repo',
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await settle();
+ expect(box.gitError, isNotNull);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('Could not check Git'));
+ expect(box.busy, isFalse);
+ expect(connection.starts, isEmpty);
+
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(connection.starts, hasLength(1));
+ expect(connection.starts.single['projectSource'], 'worktree');
+ expect(connection.reads, ['/repo', '/repo', '/repo']);
+ },
+ );
+
+ test('a remote branch cannot launch in the main folder after Worktree is disabled', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/repo',
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await settle();
+ box.focusField(NewHarnessField.branch);
+ box.accept(box.options.firstWhere((row) => row.title == 'origin/release'));
+ box.toggleWorktree();
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, 'Choose a local branch, or turn Worktree on.');
+ expect(connection.starts, isEmpty);
+ box.toggleWorktree();
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(
+ connection.starts.single['branchRef'],
+ 'refs/remotes/origin/release',
+ );
+ expect(connection.starts.single['branchName'], 'release');
+ });
+
+ test('closing during Git discovery never sends a late create', () async {
+ final connection = _Connection();
+ final pending = connection.pending['/repo'] = Completer();
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/repo',
+ );
+ addTearDown(app.dispose);
+ final creating = box.create();
+ expect(box.busy, isTrue);
+ box.dispose();
+ pending.complete(_git);
+ expect(await creating, NewHarnessOutcome.failed);
+ expect(connection.starts, isEmpty);
+ });
+
test('Git defaults follow the project, late replies are ignored, and draft choices survive', () async {
final connection = _Connection();
final app = createApp(connectionForTest: (_) => connection);
@@ -178,6 +256,41 @@ void main() {
expect(box.branchRef, 'refs/heads/main');
});
+ test('the form filters a field and takes what it landed on', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/repo',
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await settle();
+ box.focusField(NewHarnessField.branch);
+ await settle();
+ expect(box.branchLabel, 'main');
+ // Typing narrows the row, and the row takes what it narrowed to: on the
+ // form there is no list to press Return in, so nothing else would.
+ box.setQuery('feat');
+ box.takeSelection();
+ await settle();
+ expect(box.branchLabel, 'feature');
+ expect(box.matchCount, lessThan(box.total));
+
+ // And the arrows step from the value the field HAS, through a stable
+ // order — the displayed list re-ranks the chosen row to the front, which
+ // is why stepping through THAT walked in circles.
+ box.setQuery('');
+ final wheel = box.stepValues();
+ final at = wheel.indexWhere(box.isCurrent);
+ expect(at, isNonNegative, reason: 'The taken branch must be on the wheel.');
+ box.applyOption(wheel[(at + 1) % wheel.length]);
+ await settle();
+ expect(box.branchLabel, isNot('feature'));
+ });
+
test('one Start waits for Git detection and lost replies reuse the original receipt', () async {
final connection = _Connection()..loseReply = true;
final ready = connection.pending['/repo'] = Completer();
@@ -594,7 +707,7 @@ void main() {
});
testWidgets(
- 'compact launch, checkbox controls, hover selection, branch search and Cmd-Enter start',
+ 'setup branch and worktree choices are used by the explicit launch action',
(tester) async {
final connection = _Connection();
final app = createApp(connectionForTest: (_) => connection);
@@ -607,77 +720,29 @@ void main() {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
- body: Center(
- child: SizedBox(
- width: 680,
- height: 440,
- child: NewHarnessBox(
- controller: box,
- onClose: () {},
- onCreated: () {},
- onNeedsForm: () {},
- ),
+ body: SizedBox(
+ width: 820,
+ height: 450,
+ child: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
),
),
),
),
);
- await tester.pump();
- expect(find.text('New Harness'), findsNothing);
- expect(find.text('Start Harness'), findsOneWidget);
- for (final name in ['task', 'placement']) {
- expect(find.byKey(ValueKey('new-harness-field-$name')), findsNothing);
- }
- expect(find.text('[x]'), findsOneWidget);
- // Worktree sits just above Start.
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
- await tester.sendKeyEvent(LogicalKeyboardKey.space);
- await tester.pump();
- expect(box.worktree, false);
- expect(find.text('[ ]'), findsOneWidget);
- await tester.tap(
- find.byKey(const ValueKey('new-harness-field-worktree')),
- );
- await tester.pump();
- expect(find.text('[x]'), findsOneWidget);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(box.worktree, false);
- final branchRow = find.byKey(const ValueKey('new-harness-field-branch'));
- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- await mouse.addPointer(location: Offset.zero);
- await mouse.moveTo(tester.getCenter(branchRow));
- await mouse.moveBy(const Offset(4, 0));
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(box.field, NewHarnessField.branch);
- await mouse.removePointer();
- expect(box.options.where(box.isCurrent).single.title, 'main');
- expect(
- box.options.firstWhere((row) => row.title == 'origin/release').enabled,
- false,
- );
- final input = find.byKey(const ValueKey('new-harness-input'));
- await tester.enterText(input, 'feature');
+ await tester.pumpAndSettle();
+ await openLaunchRow(tester, 'branch');
+ await typeHarnessQuery(tester, 'feature');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(box.branchLabel, 'feature');
expect(connection.starts, isEmpty);
- await openLaunchRow(tester, 'worktree');
- expect(box.worktree, true);
- await openLaunchRow(tester, 'branch');
- await tester.enterText(input, 'origin/release');
- await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
- await tester.pump();
- expect(
- connection.starts.single,
- containsPair('branchRef', 'refs/remotes/origin/release'),
- );
+ await startHarness(tester);
+ expect(connection.starts.single['branchRef'], 'refs/heads/feature');
expect(connection.starts.single['projectSource'], 'worktree');
- expect(connection.starts.single.containsKey('prompt'), false);
+ expect(connection.starts.single.containsKey('prompt'), isFalse);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
box.dispose();
@@ -685,81 +750,6 @@ void main() {
await tester.pump(const Duration(milliseconds: 200));
},
);
- testWidgets(
- 'Git errors retry without losing isolation, and advanced options wait for detection',
- (tester) async {
- final connection = _Connection();
- final ready = connection.pending['/repo'] = Completer();
- final app = createApp(connectionForTest: (_) => connection);
- final box = NewHarnessController(
- app,
- machineId: 'm',
- engine: 'codex',
- folder: '/repo',
- );
- var advanced = 0;
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: NewHarnessBox(
- controller: box,
- onClose: () {},
- onCreated: () {},
- onNeedsForm: () => advanced++,
- ),
- ),
- ),
- );
- Future<void> options() async {
- await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
- await tester.sendKeyEvent(LogicalKeyboardKey.period);
- await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
- await tester.pump();
- }
-
- await options();
- expect(advanced, 0);
- ready.complete({'error': 'GIT_UNAVAILABLE'});
- await tester.pump();
- expect(advanced, 0);
- expect(box.error, contains('Retry Worktree'));
- final start = find.byKey(const ValueKey('new-harness-field-create'));
- await tester.tap(start);
- await tester.pump();
- expect(box.error, contains('Could not check Git'));
- expect(connection.starts, isEmpty);
- connection.pending.remove('/repo');
- await tester.tap(
- find.byKey(const ValueKey('new-harness-field-worktree')),
- );
- await tester.pump();
- expect(box.error, isNull);
- expect(box.worktree, true);
- expect(find.text('[x]'), findsOneWidget);
- await options();
- expect(advanced, 1);
- await openLaunchRow(tester, 'branch');
- await tester.enterText(
- find.byKey(const ValueKey('new-harness-input')),
- 'origin/release',
- );
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- await tester.tap(
- find.byKey(const ValueKey('new-harness-field-worktree')),
- );
- await tester.pump();
- expect(box.worktree, false);
- await tester.tap(start);
- await tester.pump();
- expect(box.error, contains('Choose a local branch'));
- expect(connection.starts, isEmpty);
- await tester.pumpWidget(const SizedBox());
- box.dispose();
- app.dispose();
- await tester.pump(const Duration(milliseconds: 200));
- },
- );
testWidgets('Git and non-Git launch layouts fit at large text sizes', (
tester,
@@ -793,8 +783,7 @@ void main() {
alignment: Alignment.bottomCenter,
child: SizedBox(
width: 720,
- child: NewHarnessBox(
- docked: true,
+ child: NewHarnessForm(
controller: box,
onClose: () {},
onCreated: () {},
@@ -807,7 +796,8 @@ void main() {
),
);
await tester.pump();
- expect(find.text('Start Harness').hitTestable(), findsOneWidget);
+ await openLaunchRow(tester, 'start');
+ expect(find.text('New Harness').hitTestable(), findsOneWidget);
expect(tester.takeException(), isNull);
if (renderDir != null) {
await expectLater(
@@ -817,8 +807,9 @@ void main() {
}
}
await openLaunchRow(tester, 'branch');
+ expect(find.textContaining('Search branch'), findsOneWidget);
expect(
- find.byKey(const ValueKey('new-harness-input')).hitTestable(),
+ find.byKey(const ValueKey('new-harness-query')).hitTestable(),
findsOneWidget,
);
expect(tester.takeException(), isNull);
@@ -832,11 +823,11 @@ void main() {
await tester.pump();
expect(
find.byKey(const ValueKey('new-harness-field-branch')),
- findsNothing,
+ findsOneWidget,
);
expect(
find.byKey(const ValueKey('new-harness-field-worktree')),
- findsNothing,
+ findsOneWidget,
);
if (renderDir != null) {
await expectLater(
diff --git a/desktop/test/new_harness_project_context_test.dart b/desktop/test/new_harness_project_context_test.dart
index 8e6742176..bb2e3d10a 100644
--- a/desktop/test/new_harness_project_context_test.dart
+++ b/desktop/test/new_harness_project_context_test.dart
@@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/project_history.dart';
import 'package:harness/state/new_harness.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/ws/ws_conn.dart';
import 'support/mixed_agents.dart';
@@ -65,8 +65,7 @@ void main() {
child: SizedBox(
width: 760,
height: 420,
- child: NewHarnessBox(
- docked: true,
+ child: NewHarnessForm(
controller: box,
onClose: () {},
onCreated: () =>
@@ -86,43 +85,37 @@ void main() {
box.focusField(NewHarnessField.machine);
}
- testWidgets(
- 'the proposed project name is selected for immediate replacement',
- (tester) async {
- final app = createApp();
- seedMixedAgents(app);
- addTearDown(app.dispose);
- final box = NewHarnessController(
- app,
- machineId: 'm',
- engine: 'codex',
- autoProject: true,
- now: () => DateTime(2026, 9, 20, 17, 22, 19),
- );
- addTearDown(box.dispose);
- await mount(tester, box);
- await openLaunchRow(tester, 'project');
- box.accept(
- box.options.firstWhere(
- (row) => row.id == NewHarnessController.newProjectId,
- ),
- );
- await tester.pump();
- final controller = tester.widget<TextField>(input).controller!;
- expect(controller.text, 'codex-2026-09-20-17-22');
- expect(
- controller.selection,
- TextSelection(baseOffset: 0, extentOffset: controller.text.length),
- );
- await tester.enterText(input, 'design-system');
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(box.projectLabel, '~/harnesses/design-system');
- expect(box.project.generated, isNull);
- await tester.pump(const Duration(milliseconds: 200));
- await tester.pumpWidget(const SizedBox());
- },
- );
+ testWidgets('the proposed project name can be replaced before accepting', (
+ tester,
+ ) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ autoProject: true,
+ now: () => DateTime(2026, 9, 20, 17, 22, 19),
+ );
+ addTearDown(box.dispose);
+ await mount(tester, box);
+ await openLaunchRow(tester, 'project');
+ box.accept(
+ box.options.firstWhere(
+ (row) => row.id == NewHarnessController.newProjectId,
+ ),
+ );
+ await tester.pump();
+ expect(box.query, 'codex-2026-09-20-17-22');
+ await typeHarnessQuery(tester, 'design-system');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box.projectLabel, '~/harnesses/design-system');
+ expect(box.project.generated, isNull);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ });
testWidgets(
'saved project history loads on first opening without replacing the draft',
@@ -228,6 +221,8 @@ void main() {
box.focusField(NewHarnessField.projectMenu);
await mount(tester, box);
await tester.pump(const Duration(milliseconds: 200));
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
final selected = box.selected?.id;
final machine = app.machineStates['m']!;
machine.agents = [
@@ -258,13 +253,13 @@ void main() {
app.notifyListeners();
await tester.pump(const Duration(milliseconds: 200));
expect(changes, 0);
- await tester.enterText(input, 'product video');
+ await typeHarnessQuery(tester, 'product video');
await tester.pump();
expect(box.selected!.project!.folder, '/work/product-video');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(box.project.folder, '/work/product-video');
- expect(box.field, NewHarnessField.launch);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
await tester.pumpWidget(const SizedBox());
},
);
@@ -346,17 +341,17 @@ void main() {
);
await tester.pump();
expect(box.field, NewHarnessField.projectName);
- expect(find.text('M2:~/harnesses/<name>'), findsOneWidget);
+ expect(box.query, isEmpty);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(box.error, 'Type a project name.');
- await tester.enterText(input, 'payments processing');
+ await typeHarnessQuery(tester, 'payments processing');
await tester.pump();
expect(find.text('Create payments-processing'), findsOneWidget);
- expect(find.text('M2:~/harnesses/payments-processing'), findsOneWidget);
+ expect(box.query, 'payments processing');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- expect(box.field, NewHarnessField.launch);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(box.project.name, 'payments processing');
expect(
box.projectFolderRequest!.payload['projectName'],
@@ -373,7 +368,7 @@ void main() {
);
await tester.pump();
expect(box.query, 'payments processing');
- await tester.enterText(input, '');
+ await typeHarnessQuery(tester, '');
await tester.pump();
expect(await box.createNow(), NewHarnessOutcome.failed);
expect(box.error, 'Type a project name.');
@@ -382,7 +377,7 @@ void main() {
expect(box.field, NewHarnessField.projectMenu);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- expect(box.field, NewHarnessField.launch);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(box.project.name, 'payments processing');
await tester.pump(const Duration(milliseconds: 200));
await tester.pumpWidget(const SizedBox());
@@ -438,9 +433,12 @@ void main() {
await mount(tester, box);
final agent = find.byKey(const ValueKey('new-harness-field-agent'));
final project = find.byKey(const ValueKey('new-harness-field-project'));
- expect(tester.getRect(agent).top, lessThan(tester.getRect(project).top));
+ expect(
+ tester.getRect(agent).top,
+ greaterThan(tester.getRect(project).top),
+ );
expect(input, findsNothing);
- expect(find.text('/work/payments'), findsOneWidget);
+ expect(find.text(box.projectLabel), findsOneWidget);
expect(find.text('M2'), findsOneWidget);
expect(
find.byKey(const ValueKey('new-harness-field-machine')),
@@ -450,7 +448,7 @@ void main() {
find.byKey(const ValueKey('new-harness-field-mode')),
findsNothing,
);
- expect(find.text('Auto-approve'), findsNothing);
+ expect(find.text('Auto-approve'), findsOneWidget);
for (final (name, field) in [
('agent', NewHarnessField.agent),
('machine', NewHarnessField.machine),
@@ -459,23 +457,31 @@ void main() {
await openLaunchRow(tester, name);
await tester.pump();
expect(box.field, field);
- expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ expect(
+ FocusManager.instance.primaryFocus?.debugLabel,
+ 'new-harness-query',
+ );
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- expect(box.field, NewHarnessField.launch);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
}
await openLaunchRow(tester, 'project');
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ box.move(
+ box.options.indexWhere(
+ (row) => row.id == NewHarnessController.newProjectId,
+ ) -
+ box.cursor,
+ );
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- await tester.enterText(input, 'payments processing');
+ await typeHarnessQuery(tester, 'payments processing');
await tester.pump();
expect(find.text('Create payments-processing'), findsOneWidget);
- expect(find.text('M2:~/harnesses/payments-processing'), findsOneWidget);
+ expect(box.query, 'payments processing');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- expect(box.field, NewHarnessField.launch);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expect(box.task, 'Review the retry path');
expect(
box.projectFolderRequest!.payload['projectName'],
@@ -486,63 +492,62 @@ void main() {
},
);
- testWidgets(
- 'machine is nested in Project and switching back restores its folder',
- (tester) async {
- final app = createApp();
- seedMixedAgents(app);
- final box = NewHarnessController(
- app,
- machineId: 'm',
- engine: 'codex',
- folder: '/work/payments',
- task: 'Keep this task',
- );
- addTearDown(box.dispose);
- addTearDown(app.dispose);
- await mount(tester, box);
- box.focusField(NewHarnessField.project);
- box.setQuery('payments processing');
- chooseMachine(box);
- await tester.pump();
- expect(box.field, NewHarnessField.machine);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- expect(box.field, NewHarnessField.projectMenu);
- expect(box.query, isEmpty);
- chooseMachine(box);
- box.setQuery('Office');
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(box.field, NewHarnessField.projectMenu);
- expect(box.machineId, 'studio');
- expect(box.project.folder, isNull);
- expect(box.query, isEmpty);
- expect(box.task, 'Keep this task');
- box.setFolder('/work/remote-payments');
- expect(box.field, NewHarnessField.launch);
- box.focusField(NewHarnessField.project);
- chooseMachine(box);
- box.setQuery('M2');
- box.accept();
- expect(box.machineId, 'm');
- expect(box.project.folder, '/work/payments');
- // This cache travels with the draft through Escape and More options.
- final restored = NewHarnessController(
- app,
- machineId: 'm',
- draft: box.draft,
- );
- addTearDown(restored.dispose);
- restored.focusField(NewHarnessField.machine);
- restored.setQuery('Office');
- restored.accept();
- expect(restored.project.folder, '/work/remote-payments');
- await tester.pump(const Duration(milliseconds: 200));
- await tester.pumpWidget(const SizedBox());
- },
- );
+ testWidgets('machine changes retain each machine’s folder in the draft', (
+ tester,
+ ) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/payments',
+ task: 'Keep this task',
+ );
+ addTearDown(box.dispose);
+ addTearDown(app.dispose);
+ await mount(tester, box);
+ box.focusField(NewHarnessField.project);
+ box.setQuery('payments processing');
+ chooseMachine(box);
+ await tester.pump();
+ expect(box.field, NewHarnessField.machine);
+ box.back();
+ await tester.pump();
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.query, isEmpty);
+ chooseMachine(box);
+ box.setQuery('Office');
+ await tester.pump();
+ box.accept();
+ await tester.pump();
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.machineId, 'studio');
+ expect(box.project.folder, isNull);
+ expect(box.query, isEmpty);
+ expect(box.task, 'Keep this task');
+ box.setFolder('/work/remote-payments');
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ box.focusField(NewHarnessField.project);
+ chooseMachine(box);
+ box.setQuery('M2');
+ box.accept();
+ expect(box.machineId, 'm');
+ expect(box.project.folder, '/work/payments');
+ // This cache travels with the draft through Escape and More options.
+ final restored = NewHarnessController(
+ app,
+ machineId: 'm',
+ draft: box.draft,
+ );
+ addTearDown(restored.dispose);
+ restored.focusField(NewHarnessField.machine);
+ restored.setQuery('Office');
+ restored.accept();
+ expect(restored.project.folder, '/work/remote-payments');
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ });
test(
'project choices belong only to the selected machine, including stale rows',
@@ -666,7 +671,7 @@ void main() {
await tester.pump();
expect(box.machineId, 'studio');
expect(box.projectLocation, 'iMac · Office:~/payments');
- expect(box.field, NewHarnessField.launch);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
await tester.pump(const Duration(milliseconds: 200));
await tester.pumpWidget(const SizedBox());
},
diff --git a/desktop/test/new_harness_scenarios_test.dart b/desktop/test/new_harness_scenarios_test.dart
new file mode 100644
index 000000000..5bd8ef459
--- /dev/null
+++ b/desktop/test/new_harness_scenarios_test.dart
@@ -0,0 +1,1017 @@
+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/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'keymap_host_test.dart' show key;
+import 'support/launch_menu.dart';
+import 'support/mixed_agents.dart';
+import 'swarm_state_test.dart' show createApp;
+
+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>>? starting;
+ var failStart = false;
+ var loseReply = false;
+ var profileReads = 0;
+ @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 'fs_list_dir':
+ return {
+ 'path': payload['path'] ?? '/home/test',
+ 'entries': [
+ if (payload['path'] == '/work')
+ {'name': 'my project', 'isDir': true},
+ ],
+ };
+ case 'codex_profiles_list':
+ profileReads++;
+ return {
+ 'profiles': [
+ {'path': '/profiles/work', 'label': 'Work'},
+ ],
+ };
+ case 'agent_create':
+ starts.add(Map.of(payload));
+ if (starting != null) return starting!.future;
+ if (loseReply) {
+ loseReply = false;
+ throw const WsRequestTimeout('agent_create');
+ }
+ if (failStart) {
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'START_FAILED',
+ 'detail': 'Fixture launch refused',
+ },
+ };
+ }
+ return created(payload);
+ case 'agent_create_status':
+ return created(payload);
+ default:
+ return {};
+ }
+ }
+
+ Map<String, dynamic> created(Map<String, dynamic> payload) => {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {'id': 'created', 'name': 'Created', 'engine': 'codex'},
+ };
+}
+
+const _git = {
+ 'isGit': true,
+ 'branch': 'main',
+ 'defaultRef': 'refs/remotes/origin/main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ {
+ 'ref': 'refs/heads/feature',
+ 'name': 'feature',
+ 'worktree': '/work/feature',
+ },
+ {
+ 'ref': 'refs/remotes/origin/release',
+ 'name': 'origin/release',
+ 'remote': true,
+ },
+ ],
+};
+
+class _Scenario {
+ late final AppNotifier app;
+ late final NewHarnessController box;
+ final connections = <String, _Connection>{};
+ int closes = 0, creates = 0, stores = 0, links = 0;
+}
+
+Future<_Scenario> _mount(
+ WidgetTester tester, {
+ String engine = 'codex',
+ Size size = const Size(1000, 700),
+ double scale = 1,
+ bool git = true,
+ Future<Map<String, dynamic>>? gitReply,
+ FutureOr<void> Function(_Scenario)? onBrowse,
+}) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ final scenario = _Scenario();
+ scenario.app = createApp(
+ connectionForTest: (machine) =>
+ scenario.connections.putIfAbsent(machine, () => _Connection(machine)),
+ );
+ seedMixedAgents(scenario.app);
+ scenario.app.machineStates['m']!.localOnly = true;
+ scenario.app.gitProjectReaderForTest = (_, _) async =>
+ gitReply ?? (git ? _git : {'isGit': false});
+ await scenario.app.projectHistory.select('m', '/work/a-unique-parent/repo');
+ scenario.box = NewHarnessController(
+ scenario.app,
+ machineId: 'm',
+ engine: engine,
+ offersStore: true,
+ folder: '/work/repo',
+ );
+ addTearDown(scenario.app.dispose);
+ addTearDown(scenario.box.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: NewHarnessForm(
+ controller: scenario.box,
+ onClose: () => scenario.closes++,
+ onCreated: () => scenario.creates++,
+ onStore: () => scenario.stores++,
+ onLinkProfile: () => scenario.links++,
+ onBrowse: () => onBrowse?.call(scenario),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return scenario;
+}
+
+Finder _option(String id) => find.byKey(ValueKey('new-harness-option-$id'));
+Finder _field(String id) => find.byKey(ValueKey('new-harness-field-$id'));
+
+void main() {
+ testWidgets('accessibility clicks activate fields like pointer clicks', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ final scenario = await _mount(tester);
+ void activate(String name) {
+ final node = tester.getSemantics(_field(name));
+ node.owner!.performAction(node.id, SemanticsAction.tap);
+ }
+
+ expect(scenario.box.worktree, isTrue);
+ activate('worktree');
+ await tester.pump();
+ expect(scenario.box.worktree, isFalse);
+ activate('worktree');
+ await tester.pump();
+ expect(scenario.box.worktree, isTrue);
+ activate('agent');
+ await tester.pumpAndSettle();
+ expect(harnessChoicesActive(tester), isTrue);
+ expect(
+ tester.widget<EditableText>(find.byType(EditableText)).focusNode.hasFocus,
+ isTrue,
+ );
+ semantics.dispose();
+ });
+
+ for (final scale in [1.0, 1.8]) {
+ testWidgets(
+ 'prompt shares action icon column and text baseline at $scale',
+ (tester) async {
+ await _mount(tester, scale: scale, size: const Size(1600, 1000));
+ final prompt = find.byKey(const ValueKey('new-harness-prompt'));
+ final hint = find.text('Search project');
+ double baseline(Finder finder) {
+ final render = tester.renderObject<RenderBox>(finder);
+ return render
+ .localToGlobal(
+ Offset(
+ 0,
+ render.getDryBaseline(
+ render.constraints,
+ TextBaseline.alphabetic,
+ )!,
+ ),
+ )
+ .dy;
+ }
+
+ expect(baseline(prompt), closeTo(baseline(hint), .1));
+ for (final id in [
+ NewHarnessController.repositoryId,
+ NewHarnessController.existingProjectId,
+ NewHarnessController.newProjectId,
+ ]) {
+ final icon = find.descendant(
+ of: _option(id),
+ matching: find.byType(Icon),
+ );
+ expect(
+ tester.getCenter(prompt).dx,
+ closeTo(tester.getCenter(icon).dx, .1),
+ );
+ }
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
+ testWidgets(
+ 'names stay single-line while full project paths remain searchable',
+ (tester) async {
+ final scenario = await _mount(tester);
+ await typeHarnessQuery(tester, 'unique-parent');
+ final option = scenario.box.options.singleWhere((row) => !row.synthetic);
+ expect(option.title, 'repo');
+ expect(
+ find.descendant(of: _option(option.id), matching: find.byType(Text)),
+ findsOneWidget,
+ );
+ expect(find.text(option.detail), findsNothing);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(scenario.box.project.folder, '/work/a-unique-parent/repo');
+ expect(scenario.creates, 0);
+ },
+ );
+
+ testWidgets(
+ 'only the local machine carries a note and disabled choices explain refusal',
+ (tester) async {
+ final scenario = await _mount(tester);
+ scenario.app.machineStates['studio']!.needsLink = true;
+ await openLaunchRow(tester, 'machine');
+ expect(
+ find.descendant(of: _option('m'), matching: find.text('This machine')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: _option('studio'),
+ matching: find.text('This machine'),
+ ),
+ findsNothing,
+ );
+ expect(find.text('Remote'), findsNothing);
+ for (final (id, message) in [
+ ('studio', 'not linked'),
+ ('build', 'offline'),
+ ]) {
+ await tester.tap(_option(id));
+ await tester.pump();
+ expect(scenario.box.machineId, 'm');
+ expect(scenario.box.error, contains(message));
+ expect(harnessChoicesActive(tester), isTrue);
+ }
+ await tester.tap(_option('m'));
+ await tester.pump();
+ expect(scenario.box.machineId, 'm');
+ expect(scenario.box.error, isNull);
+ expect(find.byKey(const ValueKey('new-harness-status')), findsNothing);
+ },
+ );
+
+ testWidgets(
+ 'branch metadata is hidden and unavailable remote branches cannot be applied',
+ (tester) async {
+ final scenario = await _mount(tester);
+ await openLaunchRow(tester, 'worktree');
+ expect(scenario.box.worktree, isFalse);
+ await openLaunchRow(tester, 'branch');
+ for (final option in scenario.box.options) {
+ expect(
+ find.descendant(of: _option(option.id), matching: find.byType(Text)),
+ findsOneWidget,
+ );
+ }
+ await tester.tap(_option('refs/remotes/origin/release'));
+ await tester.pump();
+ expect(scenario.box.branchRef, 'refs/heads/main');
+ expect(scenario.box.error, contains('Turn Worktree on'));
+ await tester.tap(_option('refs/heads/feature'));
+ await tester.pump();
+ expect(scenario.box.branchRef, 'refs/heads/feature');
+ expect(scenario.box.opensWorktree, isTrue);
+ expect(scenario.creates, 0);
+ },
+ );
+
+ for (final engine in ['codex', 'claude', 'cursor', 'opencode']) {
+ testWidgets(
+ '$engine approvals are single-line and each value applies without starting',
+ (tester) async {
+ final scenario = await _mount(tester, engine: engine);
+ await openLaunchRow(tester, 'approvals');
+ final modes = scenario.box.options.toList();
+ expect(modes.map((mode) => mode.id), switch (engine) {
+ 'codex' => ['readOnly', 'ask', 'auto', 'full'],
+ 'claude' => ['auto', 'acceptEdits', 'plan', 'ask', 'full'],
+ _ => ['auto', 'ask'],
+ });
+ for (final mode in modes) {
+ expect(
+ find.descendant(of: _option(mode.id), matching: find.byType(Text)),
+ findsOneWidget,
+ );
+ await tester.tap(_option(mode.id));
+ await tester.pump();
+ expect(scenario.box.mode, mode.id);
+ expect(scenario.box.engine, engine);
+ expect(scenario.creates, 0);
+ await key(tester, LogicalKeyboardKey.enter);
+ }
+ },
+ );
+ }
+
+ testWidgets(
+ 'clicking approvals uses the chosen agent, not the list preview',
+ (tester) async {
+ final scenario = await _mount(tester);
+ await tester.tap(_field('agent'));
+ await tester.pump();
+ await tester.tap(_option('claude'));
+ await tester.pump();
+ expect(scenario.box.engine, 'claude');
+ expect(_field('profile'), findsNothing);
+ await tester.tap(_field('approvals'));
+ await tester.pump();
+ expect(scenario.box.options.map((mode) => mode.id), [
+ 'auto',
+ 'acceptEdits',
+ 'plan',
+ 'ask',
+ 'full',
+ ]);
+ await tester.tap(_option('plan'));
+ await tester.pump();
+ expect(scenario.box.engine, 'claude');
+ expect(scenario.box.mode, 'plan');
+
+ // Browsing a different engine must not change the saved agent's settings.
+ await tester.tap(_field('agent'));
+ await tester.pump();
+ await typeHarnessQuery(tester, 'Codex');
+ expect(scenario.box.selected?.id, 'codex');
+ await tester.tap(_field('approvals'));
+ await tester.pump();
+ expect(scenario.box.options.map((mode) => mode.id), [
+ 'auto',
+ 'acceptEdits',
+ 'plan',
+ 'ask',
+ 'full',
+ ]);
+ await tester.tap(_option('ask'));
+ await tester.pump();
+ expect(scenario.box.engine, 'claude');
+ expect(scenario.box.mode, 'ask');
+ expect(scenario.creates, 0);
+ },
+ );
+
+ testWidgets(
+ 'empty results explain Return and Escape clears search before closing',
+ (tester) async {
+ final scenario = await _mount(tester);
+ await openLaunchRow(tester, 'machine');
+ await typeHarnessQuery(tester, 'nonexistent-machine');
+ expect(find.text('No matches'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.numpadEnter);
+ expect(scenario.box.error, contains('No values match'));
+ expect(scenario.box.machineId, 'm');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(scenario.box.query, isEmpty);
+ expect(scenario.closes, 0);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(scenario.closes, 0);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(scenario.closes, 1);
+ },
+ );
+
+ testWidgets('reverse Tab, key repeats and Page keys stay within setup', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester, engine: 'claude');
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(
+ tester.widget<Semantics>(_field('start')).properties.selected,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(
+ tester.widget<Semantics>(_field('approvals')).properties.selected,
+ isTrue,
+ );
+ final originalMode = scenario.box.mode;
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(scenario.box.mode, isNot(originalMode));
+ await key(tester, LogicalKeyboardKey.pageUp);
+ expect(scenario.box.mode, originalMode);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowUp);
+ await tester.sendKeyRepeatEvent(LogicalKeyboardKey.arrowUp);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowUp);
+ await tester.pump();
+ expect(
+ tester.widget<Semantics>(_field('branch')).properties.selected,
+ isTrue,
+ );
+ expect(FocusManager.instance.primaryFocus?.debugLabel, 'new-harness-form');
+ expect(scenario.creates, 0);
+ });
+
+ testWidgets(
+ 'paste fills the active search and backspace removes a whole Unicode character',
+ (tester) async {
+ final scenario = await _mount(tester);
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method == 'Clipboard.getData') {
+ return {'text': 'repo👩🏽‍💻'};
+ }
+ return null;
+ },
+ );
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ await tester.pump();
+ expect(scenario.box.query, 'repo👩🏽‍💻');
+ await key(tester, LogicalKeyboardKey.backspace);
+ expect(scenario.box.query, 'repo');
+ expect(scenario.creates, 0);
+ },
+ );
+
+ testWidgets(
+ 'Store, profile linking and profile refresh are reachable by pointer',
+ (tester) async {
+ final scenario = await _mount(tester);
+ await openLaunchRow(tester, 'agent');
+ await typeHarnessQuery(tester, 'nothing-installed-with-this-name');
+ await tester.tap(_option(NewHarnessController.storeId));
+ await tester.pump();
+ expect(scenario.stores, 1);
+ await openLaunchRow(tester, 'profile');
+ await tester.tap(_option(NewHarnessController.linkProfileId));
+ await tester.pump();
+ expect(scenario.links, 1);
+ final connection = scenario.connections['m']!;
+ final reads = connection.profileReads;
+ await tester.tap(_option(NewHarnessController.refreshProfilesId));
+ await tester.pumpAndSettle();
+ expect(connection.profileReads, reads + 1);
+ expect(scenario.creates, 0);
+ },
+ );
+
+ testWidgets('an empty clone prompt validates without starting', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester);
+ await tester.tap(_option(NewHarnessController.repositoryId));
+ await tester.pump();
+ expect(scenario.box.field, NewHarnessField.projectRepository);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(scenario.box.error, isNotNull);
+ expect(scenario.creates, 0);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(scenario.box.field, NewHarnessField.projectMenu);
+ });
+
+ testWidgets('the three project actions have icons, project names do not', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester);
+ for (final id in [
+ NewHarnessController.repositoryId,
+ NewHarnessController.existingProjectId,
+ NewHarnessController.newProjectId,
+ ]) {
+ expect(
+ find.descendant(of: _option(id), matching: find.byType(Icon)),
+ findsOneWidget,
+ );
+ }
+ final project = scenario.box.options.firstWhere(
+ (option) => !option.synthetic,
+ );
+ expect(
+ find.descendant(of: _option(project.id), matching: find.byType(Icon)),
+ findsNothing,
+ );
+ });
+
+ testWidgets(
+ 'native text input supports paste, selection replacement and composition',
+ (tester) async {
+ final scenario = await _mount(tester);
+ await tester.tap(_option(NewHarnessController.repositoryId));
+ await tester.pumpAndSettle();
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ expect(find.text('No matches'), findsNothing);
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async => call.method == 'Clipboard.getData'
+ ? {'text': 'https://github.com/example/moon'}
+ : null,
+ );
+ final editor = tester.state<EditableTextState>(find.byType(EditableText));
+ Actions.invoke(
+ FocusManager.instance.primaryFocus!.context!,
+ const PasteTextIntent(SelectionChangedCause.keyboard),
+ );
+ await tester.pumpAndSettle();
+ expect(scenario.box.query, 'https://github.com/example/moon');
+ editor.selectAll(SelectionChangedCause.keyboard);
+ await tester.pump();
+ final input = tester.widget<EditableText>(find.byType(EditableText));
+ expect(input.controller.selection.start, 0);
+ expect(input.controller.selection.end, scenario.box.query.length);
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'hello',
+ selection: TextSelection.collapsed(offset: 5),
+ composing: TextRange(start: 0, end: 5),
+ ),
+ );
+ await tester.pump();
+ expect(scenario.box.query, 'hello');
+ expect(
+ input.controller.value.composing,
+ const TextRange(start: 0, end: 5),
+ );
+ expect(scenario.creates, 0);
+ },
+ );
+
+ for (final shortcut in [
+ LogicalKeyboardKey.enter,
+ LogicalKeyboardKey.numpadEnter,
+ LogicalKeyboardKey.escape,
+ LogicalKeyboardKey.tab,
+ LogicalKeyboardKey.arrowDown,
+ LogicalKeyboardKey.arrowUp,
+ LogicalKeyboardKey.pageDown,
+ LogicalKeyboardKey.pageUp,
+ ]) {
+ testWidgets('${shortcut.keyLabel} leaves an IME candidate uncommitted', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester);
+ await openLaunchRow(tester, 'agent');
+ const candidate = TextEditingValue(
+ text: 'cla',
+ selection: TextSelection.collapsed(offset: 3),
+ composing: TextRange(start: 0, end: 3),
+ );
+ tester.testTextInput.updateEditingValue(candidate);
+ await tester.pump();
+ final selected = scenario.box.selected?.id;
+ await key(tester, shortcut);
+ expect(scenario.box.engine, 'codex');
+ expect(scenario.box.field, NewHarnessField.agent);
+ expect(scenario.box.query, 'cla');
+ expect(scenario.box.selected?.id, selected);
+ expect(harnessChoicesActive(tester), isTrue);
+ expect(scenario.creates, 0);
+ expect(scenario.closes, 0);
+
+ // Once the input method commits, Return accepts the visible choice.
+ tester.testTextInput.updateEditingValue(
+ candidate.copyWith(composing: TextRange.empty),
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(scenario.box.engine, 'claude');
+ expect(harnessChoicesActive(tester), isFalse);
+ });
+ }
+
+ testWidgets('typing on an idle field retains the first character', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester);
+ expect(harnessChoicesActive(tester), isFalse);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyR, character: 'r');
+ await tester.pumpAndSettle();
+ expect(scenario.box.query, 'r');
+ expect(harnessChoicesActive(tester), isTrue);
+ final input = tester.widget<EditableText>(find.byType(EditableText));
+ expect(input.focusNode.hasFocus, isTrue);
+ expect(
+ input.controller.selection,
+ const TextSelection.collapsed(offset: 1),
+ );
+ tester.testTextInput.enterText('repo');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(scenario.box.project.folder, '/work/repo');
+ expect(harnessChoicesActive(tester), isFalse);
+ expect(scenario.creates, 0);
+ });
+
+ testWidgets('clicking the search prompt activates its choices and editor', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester);
+ expect(harnessChoicesActive(tester), isFalse);
+ await tester.tap(find.byType(TextField));
+ await tester.pumpAndSettle();
+ expect(harnessChoicesActive(tester), isTrue);
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ tester.testTextInput.enterText('repo');
+ await tester.pump();
+ expect(scenario.box.query, 'repo');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(scenario.box.query, isEmpty);
+ expect(harnessChoicesActive(tester), isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(harnessChoicesActive(tester), isFalse);
+ expect(scenario.closes, 0);
+ });
+
+ testWidgets('mouse scrolling can reach choices beyond the first nine', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester);
+ await openLaunchRow(tester, 'agent');
+ expect(scenario.box.options.length, greaterThan(9));
+ final last = scenario.box.options.last;
+ final choices = find.byKey(const ValueKey('new-harness-choices'));
+ await tester.scrollUntilVisible(
+ _option(last.id),
+ 160,
+ scrollable: find.descendant(
+ of: choices,
+ matching: find.byWidgetPredicate(
+ (widget) =>
+ widget is Scrollable &&
+ widget.axisDirection == AxisDirection.down,
+ ),
+ ),
+ );
+ expect(_option(last.id).hitTestable(), findsOneWidget);
+ await tester.tap(_option(last.id));
+ await tester.pump();
+ expect(scenario.stores, 1);
+ expect(scenario.creates, 0);
+ });
+
+ for (final (door, input) in [
+ (NewHarnessController.newProjectId, 'hello moon'),
+ (NewHarnessController.repositoryId, 'https://github.com/example/moon.git'),
+ (NewHarnessController.existingProjectId, '/work/my project'),
+ ]) {
+ testWidgets('$door accepts pasted input and returns focus to fields', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester);
+ // Exercise remote path completion without reading the real filesystem.
+ scenario.app.machineStates['m']!.localOnly = false;
+ await tester.tap(_option(door));
+ await tester.pump();
+ if (door == NewHarnessController.existingProjectId) {
+ expect(find.text('Browse Folder'), findsOneWidget);
+ expect(find.text('Open Folder'), findsNothing);
+ }
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async =>
+ call.method == 'Clipboard.getData' ? {'text': input} : null,
+ );
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pumpAndSettle();
+ expect(scenario.box.query, input);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(scenario.box.field, NewHarnessField.projectMenu);
+ expect(harnessChoicesActive(tester), isFalse);
+ expect(scenario.box.query, isEmpty);
+ switch (door) {
+ case NewHarnessController.newProjectId:
+ expect(scenario.box.project.name, 'hello moon');
+ case NewHarnessController.repositoryId:
+ expect(scenario.box.project.repository?.name, 'moon');
+ case NewHarnessController.existingProjectId:
+ expect(scenario.box.project.folder, '/work/my project');
+ }
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(scenario.box.field, NewHarnessField.agent);
+ expect(scenario.creates, 0);
+ expect(scenario.connections.values.expand((c) => c.starts), isEmpty);
+ });
+ }
+
+ testWidgets(
+ 'delayed clipboard replies cannot overwrite a changed field or query',
+ (tester) async {
+ final scenario = await _mount(tester);
+ var pending = Completer<Map<String, dynamic>>();
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async =>
+ call.method == 'Clipboard.getData' ? pending.future : null,
+ );
+ await key(tester, LogicalKeyboardKey.keyV, ctrl: true);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ pending.complete({'text': 'stale project'});
+ await tester.pump();
+ expect(scenario.box.field, NewHarnessField.agent);
+ expect(scenario.box.query, isEmpty);
+ pending = Completer<Map<String, dynamic>>();
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ await typeHarnessQuery(tester, 'claude');
+ pending.complete({'text': 'stale agent'});
+ await tester.pump();
+ expect(scenario.box.query, 'claude');
+ pending = Completer<Map<String, dynamic>>();
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ await tester.pumpWidget(const SizedBox());
+ pending.complete({'text': 'closed'});
+ await tester.pump();
+ expect(scenario.box.query, 'claude');
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'clipboard errors are recoverable and empty paste preserves input',
+ (tester) async {
+ final scenario = await _mount(tester);
+ var fail = true;
+ var pasted = '';
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method != 'Clipboard.getData') return null;
+ if (fail) throw PlatformException(code: 'unavailable');
+ return {'text': pasted};
+ },
+ );
+ await key(tester, LogicalKeyboardKey.keyV, ctrl: true);
+ await tester.pump();
+ expect(find.text('Could not paste. Try again.'), findsOneWidget);
+ fail = false;
+ await typeHarnessQuery(tester, 'repo');
+ await key(tester, LogicalKeyboardKey.keyV, ctrl: true);
+ expect(scenario.box.query, 'repo');
+ pasted = '\r\nhello\nmoon';
+ await key(tester, LogicalKeyboardKey.keyV, ctrl: true);
+ await tester.pump();
+ expect(scenario.box.query, 'repo hello moon');
+ },
+ );
+
+ testWidgets('a delayed paste cannot replace a newer text selection', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester);
+ await tester.tap(_option(NewHarnessController.newProjectId));
+ await tester.pump();
+ await typeHarnessQuery(tester, 'hello moon');
+ final pending = Completer<Map<String, dynamic>>();
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async =>
+ call.method == 'Clipboard.getData' ? pending.future : null,
+ );
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ const selection = TextSelection(baseOffset: 0, extentOffset: 5);
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(text: 'hello moon', selection: selection),
+ );
+ await tester.pump();
+ pending.complete({'text': 'stale'});
+ await tester.pump();
+ expect(scenario.box.query, 'hello moon');
+ expect(
+ tester
+ .widget<EditableText>(find.byType(EditableText))
+ .controller
+ .selection,
+ selection,
+ );
+ });
+
+ testWidgets('folder browser failure stays visible and retry restores focus', (
+ tester,
+ ) async {
+ var attempts = 0;
+ final scenario = await _mount(
+ tester,
+ onBrowse: (scenario) async {
+ if (attempts++ == 0) throw PlatformException(code: 'unavailable');
+ scenario.box.setFolder('/work/chosen folder');
+ },
+ );
+ await tester.tap(_option(NewHarnessController.existingProjectId));
+ await tester.pumpAndSettle();
+ await tester.tap(_option(NewHarnessController.browseId));
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ expect(find.text('Could not browse folders. Try again.'), findsOneWidget);
+ expect(scenario.box.project.folder, '/work/repo');
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ await tester.tap(_option(NewHarnessController.browseId));
+ await tester.pumpAndSettle();
+ expect(attempts, 2);
+ expect(scenario.box.project.folder, '/work/chosen folder');
+ expect(scenario.box.error, isNull);
+ expect(scenario.box.field, NewHarnessField.projectMenu);
+ expect(harnessChoicesActive(tester), isFalse);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(scenario.box.field, NewHarnessField.agent);
+ expect(scenario.creates, 0);
+ });
+
+ testWidgets('cancelled folder browser preserves the draft and input focus', (
+ tester,
+ ) async {
+ final pending = Completer<void>();
+ final scenario = await _mount(tester, onBrowse: (_) => pending.future);
+ await tester.tap(_option(NewHarnessController.existingProjectId));
+ await tester.pumpAndSettle();
+ await tester.tap(_option(NewHarnessController.browseId));
+ await tester.pump();
+ pending.complete();
+ await tester.pumpAndSettle();
+ expect(scenario.box.project.folder, '/work/repo');
+ expect(scenario.box.field, NewHarnessField.project);
+ expect(harnessChoicesActive(tester), isTrue);
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ await typeHarnessQuery(tester, '/work');
+ expect(scenario.box.query, '/work');
+ expect(scenario.closes, 0);
+ });
+
+ testWidgets('a folder browser failure after dismissal has no stale effect', (
+ tester,
+ ) async {
+ final pending = Completer<void>();
+ final scenario = await _mount(tester, onBrowse: (_) => pending.future);
+ await tester.tap(_option(NewHarnessController.existingProjectId));
+ await tester.pumpAndSettle();
+ await tester.tap(_option(NewHarnessController.browseId));
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ pending.completeError(PlatformException(code: 'unavailable'));
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ expect(scenario.box.error, isNull);
+ expect(scenario.box.project.folder, '/work/repo');
+ });
+
+ testWidgets('Git discovery does not flash a non-Git explanation', (
+ tester,
+ ) async {
+ final pending = Completer<Map<String, dynamic>>();
+ final scenario = await _mount(tester, gitReply: pending.future);
+ expect(scenario.box.checkingGit, isTrue);
+ expect(find.text('Not a Git repository'), findsNothing);
+ await tester.tap(_field('worktree'));
+ await tester.pump();
+ pending.complete(_git);
+ await tester.pumpAndSettle();
+ expect(scenario.box.checkingGit, isFalse);
+ expect(find.text('Yes'), findsOneWidget);
+ await tester.tap(_field('worktree'));
+ await tester.pump();
+ expect(scenario.box.worktree, isFalse);
+ await tester.tap(_field('worktree'));
+ await tester.pump();
+ expect(scenario.box.worktree, isTrue);
+ });
+
+ testWidgets('narrow layout back actions leave both lists and prompts', (
+ tester,
+ ) async {
+ final scenario = await _mount(tester, size: const Size(520, 520));
+ await tester.tap(_field('project'));
+ await tester.pump();
+ expect(harnessChoicesActive(tester), isTrue);
+ await tester.tap(find.text('Project'));
+ await tester.pump();
+ expect(harnessChoicesActive(tester), isFalse);
+ await tester.tap(_field('project'));
+ await tester.pump();
+ await tester.tap(_option(NewHarnessController.existingProjectId));
+ await tester.pump();
+ expect(scenario.box.field, NewHarnessField.project);
+ await tester.tap(find.text('Folder'));
+ await tester.pump();
+ expect(scenario.box.field, NewHarnessField.projectMenu);
+ expect(harnessChoicesActive(tester), isFalse);
+ expect(scenario.creates, 0);
+ });
+
+ testWidgets(
+ 'folder completion can switch machines and reverse Tab walks choices',
+ (tester) async {
+ final scenario = await _mount(tester);
+ scenario.app.machineStates['m']!.localOnly = false;
+ await tester.tap(_option(NewHarnessController.existingProjectId));
+ await tester.pump();
+ await typeHarnessQuery(tester, '/work/my');
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pumpAndSettle();
+ final first = scenario.box.selected!.id;
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(scenario.box.selected!.id, isNot(first));
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(scenario.box.selected!.id, first);
+ await tester.tap(_option(NewHarnessController.changeMachineId));
+ await tester.pump();
+ expect(scenario.box.field, NewHarnessField.machine);
+ expect(harnessChoicesActive(tester), isTrue);
+ expect(scenario.creates, 0);
+ },
+ );
+
+ testWidgets(
+ 'launch failure keeps keys active and retry starts exactly once',
+ (tester) async {
+ final scenario = await _mount(tester, git: false);
+ final connection = scenario.connections['m']!;
+ connection.failStart = true;
+ await startHarness(tester);
+ await tester.pumpAndSettle();
+ expect(scenario.creates, 0);
+ expect(scenario.box.error, contains('Fixture launch refused'));
+ expect(
+ FocusManager.instance.primaryFocus?.debugLabel,
+ 'new-harness-form',
+ );
+ connection.failStart = false;
+ await key(tester, LogicalKeyboardKey.numpadEnter);
+ await tester.pumpAndSettle();
+ expect(scenario.creates, 1);
+ expect(connection.starts, hasLength(2));
+ },
+ );
+
+ for (final (size, scale) in [
+ (const Size(520, 520), 1.0),
+ (const Size(600, 680), 2.0),
+ ]) {
+ testWidgets(
+ 'all fields and inline remote notes remain reachable at $size, $scale',
+ (tester) async {
+ final scenario = await _mount(tester, size: size, scale: scale);
+ for (final name in [
+ 'project',
+ 'agent',
+ 'machine',
+ 'branch',
+ 'approvals',
+ 'profile',
+ ]) {
+ await openLaunchRow(tester, name);
+ expect(harnessChoicesActive(tester), isTrue, reason: name);
+ expect(
+ _option(scenario.box.selected!.id).hitTestable(),
+ findsOneWidget,
+ reason: name,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(_field(name).hitTestable(), findsOneWidget);
+ }
+ await openLaunchRow(tester, 'start');
+ expect(_field('start').hitTestable(), findsOneWidget);
+ expect(scenario.creates, 0);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+}
diff --git a/desktop/test/new_harness_start_failures_test.dart b/desktop/test/new_harness_start_failures_test.dart
new file mode 100644
index 000000000..a487ebcb9
--- /dev/null
+++ b/desktop/test/new_harness_start_failures_test.dart
@@ -0,0 +1,198 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/first_task.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ bool catalogUnavailable = false, installed = false;
+ final install = Completer<Map<String, dynamic>>();
+ int installs = 0;
+ final starts = <Map<String, dynamic>>[];
+
+ @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': []};
+ case 'git_project_info':
+ return {'isGit': false};
+ case 'fs_list_dir':
+ return {'path': '/work', 'entries': []};
+ case 'dsh_list':
+ if (catalogUnavailable) {
+ throw const WsRequestFailure(
+ responseType: 'dsh_list',
+ code: 'UNSUPPORTED',
+ );
+ }
+ return {
+ 'dsh': [
+ {
+ 'id': 'autonomous/blender',
+ 'name': 'Blender',
+ 'engine': 'claude',
+ 'installed': installed,
+ },
+ ],
+ };
+ case 'dsh_install':
+ installs++;
+ final reply = await install.future;
+ installed = reply['ok'] == true;
+ return reply;
+ case 'agent_create':
+ starts.add(Map.of(payload));
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'created',
+ 'name': 'Created',
+ 'engine': payload['engine'],
+ },
+ };
+ default:
+ return {};
+ }
+ }
+}
+
+void main() {
+ for (final failure in [false, true]) {
+ test('a missing Store harness waits for installation (failure=$failure)', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'autonomous/blender',
+ folder: '/work',
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ final creating = box.create();
+ await Future<void>.delayed(Duration.zero);
+ expect(box.status, startsWith('Installing Blender'));
+ expect(box.busy, isTrue);
+ expect(connection.installs, 1);
+ expect(connection.starts, isEmpty);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.requestDismiss(), isFalse);
+
+ connection.install.complete(
+ failure ? {'ok': false, 'detail': 'Disk is full'} : {'ok': true},
+ );
+ expect(
+ await creating,
+ failure ? NewHarnessOutcome.failed : NewHarnessOutcome.created,
+ );
+ expect(box.busy, isFalse);
+ if (failure) {
+ expect(box.error, 'Disk is full');
+ expect(connection.starts, isEmpty);
+ // An installation completed outside the dialog is discovered on retry.
+ connection.installed = true;
+ expect(await box.create(), NewHarnessOutcome.created);
+ }
+ expect(connection.installs, 1);
+ expect(connection.starts, hasLength(1));
+ expect(connection.starts.single['engine'], 'claude');
+ expect(connection.starts.single['dsh'], 'autonomous/blender');
+ });
+ }
+
+ test(
+ 'an unsupported Store catalog is actionable and does not launch',
+ () async {
+ final connection = _Connection()..catalogUnavailable = true;
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'autonomous/blender',
+ folder: '/work',
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('Update Harness CLI'));
+ expect(box.busy, isFalse);
+ expect(connection.installs, 0);
+ expect(connection.starts, isEmpty);
+ connection.catalogUnavailable = false;
+ connection.installed = true;
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(connection.starts, hasLength(1));
+ },
+ );
+
+ test(
+ 'dismissal during installation cannot launch after the dialog is disposed',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'autonomous/blender',
+ folder: '/work',
+ );
+ addTearDown(app.dispose);
+ final creating = box.create();
+ await Future<void>.delayed(Duration.zero);
+ expect(connection.installs, 1);
+ box.dispose();
+ connection.install.complete({'ok': true});
+ expect(await creating, NewHarnessOutcome.failed);
+ expect(connection.starts, isEmpty);
+ },
+ );
+
+ test(
+ 'an oversized carried task is retained and can be shortened before retry',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ final task = 'x' * (kFirstTaskMaxLength + 1);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work',
+ task: task,
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(
+ box.error,
+ contains('A first message can be $kFirstTaskMaxLength'),
+ );
+ expect(box.task, task);
+ expect(connection.starts, isEmpty);
+ box.focusField(NewHarnessField.task);
+ box.setQuery('shortened task');
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(connection.starts.single['prompt'], 'shortened task');
+ },
+ );
+}
diff --git a/desktop/test/open_picker_rendering_test.dart b/desktop/test/open_picker_rendering_test.dart
index 81d25f6ce..9d12337db 100644
--- a/desktop/test/open_picker_rendering_test.dart
+++ b/desktop/test/open_picker_rendering_test.dart
@@ -21,19 +21,34 @@ void main() {
final results = find.byType(SwarmSearchResults);
final search = tester.widget<SwarmSearchResults>(results).search;
final rows = find.descendant(of: results, matching: find.byType(ListTile));
+ final prompt = find.byKey(const ValueKey('swarm-search-prompt'));
+ final visibleTiles = tester.widgetList<ListTile>(rows);
+ for (final tile in visibleTiles.where((tile) => tile.leading != null)) {
+ expect(
+ tester.getCenter(prompt).dx,
+ closeTo(tester.getCenter(find.byWidget(tile.leading!)).dx, .1),
+ reason: 'The prompt, create action and engine marks share one column.',
+ );
+ }
expect(search.rows.length, greaterThan(50));
- expect(rows.evaluate().length, lessThan(12));
+ expect(rows.evaluate().length, lessThan(35));
final visited = <String>{};
for (var step = 0; step < 35; step++) {
await key(tester, LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
- final row = FocusManager.instance.primaryFocus?.context
- ?.findAncestorWidgetOfExactType<ListTile>();
- if (row != null) {
- final id = (row.key! as ValueKey<String>).value;
- visited.add(id);
- expect(search.selected?.id, id);
- expect(find.byKey(row.key!).hitTestable(), findsOneWidget);
+ final selected = search.selected;
+ if (selected != null) {
+ visited.add(selected.id);
+ expect(find.byKey(ValueKey(selected.id)).hitTestable(), findsOneWidget);
+ expect(
+ tester
+ .widget<TextField>(
+ find.byKey(const ValueKey('swarm-search-input')),
+ )
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
}
}
// Focus crosses the initial viewport repeatedly as new rows are built.
diff --git a/desktop/test/prompt_context_test.dart b/desktop/test/prompt_context_test.dart
index a8941bc6f..27161a42c 100644
--- a/desktop/test/prompt_context_test.dart
+++ b/desktop/test/prompt_context_test.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart' show RenderParagraph;
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/prompt_style.dart';
import 'package:harness/widgets/prompt_context.dart';
@@ -9,12 +10,23 @@ void main() {
WidgetTester tester,
double width, {
PromptStyle style = PromptStyle.symbols,
+ double scale = 1,
+ PromptContext data = const PromptContext(
+ machine: 'mac-studio',
+ project: 'autonomous-harness',
+ branch: 'deehw/worktree-and-branches',
+ ),
}) async {
tester.view.devicePixelRatio = 1;
- tester.view.physicalSize = const Size(1600, 200);
+ tester.view.physicalSize = Size(width + 10, 200 * scale);
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
@@ -24,11 +36,7 @@ void main() {
alignment: Alignment.centerLeft,
child: PromptContextView(
prefs: PromptPrefs(style: style),
- contextData: const PromptContext(
- machine: 'mac-studio',
- project: 'autonomous-harness',
- branch: 'deehw/worktree-and-branches',
- ),
+ contextData: data,
),
),
),
@@ -42,18 +50,27 @@ void main() {
'a crowded line keeps the branch and cuts the folder in the middle',
(tester) async {
for (final (width, style) in [
- (560.0, PromptStyle.symbols),
- (620.0, PromptStyle.powerline),
+ (610.0, PromptStyle.symbols),
+ (670.0, PromptStyle.powerline),
]) {
await line(tester, width, style: style);
expect(find.text('deehw/worktree-and-branches'), findsOneWidget);
+ final branch = find.descendant(
+ of: find.text('deehw/worktree-and-branches'),
+ matching: find.byType(RichText),
+ );
+ expect(
+ tester.renderObject<RenderParagraph>(branch).didExceedMaxLines,
+ isFalse,
+ reason: '$style at $width keeps the full branch before the project.',
+ );
final folder = find.textContaining('…');
expect(folder, findsOneWidget);
final shown =
tester.widget<Text>(folder).data ??
tester.widget<Text>(folder).textSpan!.toPlainText();
expect(shown, startsWith('aut'));
- expect(shown, endsWith('ess'));
+ expect(shown, endsWith('ss'));
expect(tester.takeException(), isNull);
}
},
@@ -66,6 +83,44 @@ void main() {
expect(tester.takeException(), isNull);
});
+ testWidgets('long branches use the room left by short metadata', (
+ tester,
+ ) async {
+ const branch =
+ 'feat/centered-new-harness-palette-with-readable-branch-names';
+ for (final style in PromptStyle.values) {
+ for (final scale in [1.0, 1.8]) {
+ await line(
+ tester,
+ 1500 * scale,
+ style: style,
+ scale: scale,
+ data: const PromptContext(
+ machine: 'M2',
+ project: 'autonomous-harness',
+ branch: branch,
+ ),
+ );
+ final text = find.descendant(
+ of: find.text(branch),
+ matching: find.byType(RichText),
+ );
+ expect(
+ tester.renderObject<RenderParagraph>(text).didExceedMaxLines,
+ isFalse,
+ reason: '$style at $scale: the whole metadata line fits.',
+ );
+ expect(
+ tester.getRect(text).right,
+ lessThanOrEqualTo(
+ tester.getRect(find.byType(PromptContextView)).right,
+ ),
+ );
+ expect(tester.takeException(), isNull);
+ }
+ }
+ });
+
testWidgets('a line too narrow for every segment still lays out', (
tester,
) async {
diff --git a/desktop/test/support/launch_menu.dart b/desktop/test/support/launch_menu.dart
index 12891e5f9..179b7b5f4 100644
--- a/desktop/test/support/launch_menu.dart
+++ b/desktop/test/support/launch_menu.dart
@@ -1,32 +1,36 @@
-import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/state/new_harness.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+
+bool harnessChoicesActive(WidgetTester tester) {
+ final choices = find.byKey(const ValueKey('new-harness-choices'));
+ return choices.evaluate().isNotEmpty &&
+ tester.widget<Semantics>(choices).properties.focused == true;
+}
/// Open a launch row through the same navigation keys as the visible menu.
Future<void> openLaunchRow(WidgetTester tester, String name) async {
- final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
- .controller;
- expect(box.field, NewHarnessField.launch);
- final index = [
- 'agent',
- 'machine',
- 'project',
- if (box.isGitProject) 'branch',
- if (box.canUseWorktree || box.gitError != null) 'worktree',
- ].indexOf(name);
- expect(index, greaterThanOrEqualTo(0));
- await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
- await tester.pump();
- for (var i = 0; i < index; i++) {
+ // The setup screen starts at Project; its semantic selection also reports
+ // keyboard focus, so tests drive the visible rows rather than a controller.
+ final target = name == 'create' ? 'start' : name;
+ for (var i = 0; i < 3 && harnessChoicesActive(tester); i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ }
+ final row = find.byKey(ValueKey('new-harness-field-$target'));
+ for (var i = 0; i < 8; i++) {
+ if (tester.widget<Semantics>(row).properties.selected == true) break;
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
}
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
+ expect(tester.widget<Semantics>(row).properties.selected, isTrue);
+ if (target != 'start') {
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ }
+ await tester.pumpAndSettle();
}
/// Settings are deliberately separate from the arrow/Enter selection path.
@@ -35,32 +39,46 @@ Future<void> openAgentSetting(
String engine,
String setting,
) async {
- final row = find.byKey(ValueKey(engine));
- await tester.ensureVisible(row);
- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- await mouse.addPointer(location: tester.getCenter(row));
- await mouse.moveTo(tester.getCenter(row));
- await tester.pump();
- await tester.tap(find.byKey(ValueKey('new-harness-settings-$engine')));
- await tester.pump();
- await tester.tap(
- find
- .ancestor(
- of: find.byKey(ValueKey(setting)),
- matching: find.byType(InkWell),
- )
- .first,
+ await openLaunchRow(
+ tester,
+ setting == NewHarnessController.permissionsId ? 'approvals' : 'profile',
);
- await tester.pump();
- await mouse.removePointer();
}
/// Exercises compatibility for carried tasks and advanced drafts. Task is no
/// longer a visible launch row.
Future<void> openLegacyTaskEditor(WidgetTester tester) async {
tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller
.focusField(NewHarnessField.task);
await tester.pump();
}
+
+/// Edit the setup field through Flutter's text input connection.
+Future<void> typeHarnessQuery(WidgetTester tester, String text) async {
+ final input = find.byKey(const ValueKey('new-harness-query'));
+ if (input.evaluate().isEmpty) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ }
+ await tester.enterText(input, text);
+ await tester.pump();
+}
+
+Future<void> startHarness(WidgetTester tester) async {
+ await openLaunchRow(tester, 'start');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+}
+
+/// Accept the open list, or explicitly navigate to the setup launch action.
+/// Other screens keep their normal Return behavior.
+Future<void> acceptSetupOrSearch(WidgetTester tester) async {
+ if (find.byType(NewHarnessForm).evaluate().isNotEmpty &&
+ !harnessChoicesActive(tester)) {
+ await openLaunchRow(tester, 'start');
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+}
diff --git a/desktop/test/swarm_add_agent_test.dart b/desktop/test/swarm_add_agent_test.dart
index 44bbde3dd..8753075ab 100644
--- a/desktop/test/swarm_add_agent_test.dart
+++ b/desktop/test/swarm_add_agent_test.dart
@@ -33,11 +33,8 @@ void main() {
'Agent 0',
);
await tester.pump();
- expect(
- find.textContaining('enter open', findRichText: true),
- findsOneWidget,
- );
- expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
+ expect(find.byKey(const ValueKey('swarm-search-hints')), findsNothing);
+ expect(find.byKey(const ValueKey('swarm-search-count')), findsNothing);
expect(find.byType(AlertDialog), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
diff --git a/desktop/test/swarm_commands_test.dart b/desktop/test/swarm_commands_test.dart
index b8b0da46c..fcc1efafb 100644
--- a/desktop/test/swarm_commands_test.dart
+++ b/desktop/test/swarm_commands_test.dart
@@ -1,9 +1,11 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.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/terminal/terminal_binary.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:xterm/xterm.dart';
import 'swarm_interactions_test.dart' show chord;
@@ -11,6 +13,91 @@ import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
void main() {
+ for (final pointer in [false, true]) {
+ testWidgets(
+ 'Cmd-P hands New Harness focus to the form without launching (pointer=$pointer)',
+ (tester) async {
+ final previousEntry = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = previousEntry);
+ final app = createApp();
+ final frames = <TerminalBinaryFrame>[];
+ final pane = app.adoptSessionForTest(terminal('a0', frames));
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ final original = app.activeSwarm;
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await tester.enterText(input, '> New Harness');
+ await tester.pump();
+ final command = find.byKey(const ValueKey('command:agent.new'));
+ expect(command, findsOneWidget);
+ if (pointer) {
+ await tester.tap(command);
+ } else {
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ }
+ await tester.pumpAndSettle();
+ expect(input, findsNothing);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ expect(app.activeSwarm, same(original));
+ expect(app.panes.single, same(pane));
+ expect(frames, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(NewHarnessForm), findsNothing);
+ expect(
+ tester
+ .widget<TerminalView>(find.byType(TerminalView))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.pump();
+ expect(frames.single.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets('an unmatched command cannot execute the previous selection', (
+ tester,
+ ) async {
+ final app = createApp();
+ final frames = <TerminalBinaryFrame>[];
+ final pane = app.adoptSessionForTest(terminal('a0', frames));
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await tester.enterText(input, '> pin');
+ await tester.pump();
+ expect(find.byKey(const ValueKey('command:pane.pin')), findsOneWidget);
+ await tester.enterText(input, '> no-command-matches-this-924');
+ await tester.pump();
+ for (final key in [
+ LogicalKeyboardKey.arrowDown,
+ LogicalKeyboardKey.arrowUp,
+ LogicalKeyboardKey.enter,
+ LogicalKeyboardKey.numpadEnter,
+ ]) {
+ await tester.sendKeyEvent(key);
+ await tester.pump();
+ expect(input, findsOneWidget);
+ expect(app.isPanePinned(pane), isFalse);
+ expect(frames, isEmpty);
+ }
+ await tester.enterText(input, '> pin');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.isPanePinned(pane), isTrue);
+ expect(input, findsNothing);
+ expect(frames, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+
test(
'commands are opt-in, cannot add agents and recheck availability',
() async {
diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dart
index ca965f59f..a4dc53c86 100644
--- a/desktop/test/swarm_interactions_test.dart
+++ b/desktop/test/swarm_interactions_test.dart
@@ -191,7 +191,7 @@ void main() {
);
await tester.pump();
await tester.sendKeyDownEvent(LogicalKeyboardKey.control);
- await tester.sendKeyEvent(LogicalKeyboardKey.keyP);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyN);
await tester.sendKeyUpEvent(LogicalKeyboardKey.control);
await tester.pump();
final selected = find.byWidgetPredicate(
diff --git a/desktop/test/swarm_picker_activation_test.dart b/desktop/test/swarm_picker_activation_test.dart
index fc069d3c2..5f6baf263 100644
--- a/desktop/test/swarm_picker_activation_test.dart
+++ b/desktop/test/swarm_picker_activation_test.dart
@@ -25,7 +25,8 @@ void main() {
final panelRect = tester.getRect(results);
final fieldRect = tester.getRect(field);
expect(fieldRect.left, panelRect.left);
- expect(fieldRect.right, panelRect.right);
+ expect(fieldRect.right, lessThanOrEqualTo(panelRect.right));
+ expect(fieldRect.width, greaterThan(panelRect.width / 2));
await chord(tester, LogicalKeyboardKey.keyN);
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.byKey(const ValueKey('create-agent-submit')), findsOneWidget);
@@ -62,11 +63,8 @@ void main() {
await tester.pump();
expect(find.byType(Checkbox), findsNothing);
expect(app.panes, isEmpty);
- expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
- expect(
- find.textContaining('enter open', findRichText: true),
- findsOneWidget,
- );
+ expect(find.byKey(const ValueKey('swarm-search-count')), findsNothing);
+ expect(find.byKey(const ValueKey('swarm-search-hints')), findsNothing);
expect(find.byKey(const ValueKey('swarm-search-accept')), findsNothing);
if (activate == 'click') {
await tester.tap(find.byKey(ValueKey(agentDestinationId('m', 'a0'))));
diff --git a/desktop/test/swarm_search_identity_test.dart b/desktop/test/swarm_search_identity_test.dart
index 8a551155b..c5729a995 100644
--- a/desktop/test/swarm_search_identity_test.dart
+++ b/desktop/test/swarm_search_identity_test.dart
@@ -8,7 +8,6 @@ import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/state/terminal_pane.dart';
-import 'package:harness/widgets/search_result_text.dart';
import 'swarm_interactions_test.dart' show chord;
import 'swarm_screen_test.dart' show mount, terminal;
@@ -319,7 +318,7 @@ void main() {
);
testWidgets(
- 'Cmd P renders one harness result and opens it from a tab-name alias',
+ 'Cmd O renders one harness result and opens it from a tab-name alias',
(tester) async {
final app = createApp();
final machine = app.machineStates['m']!..nodeOnline = true;
@@ -354,25 +353,13 @@ void main() {
// One harness, then the row that makes what was typed instead.
expect(find.byType(ListTile), findsNWidgets(2));
expect(find.byKey(const ValueKey(kSwarmCreateRowId)), findsOneWidget);
- // Context remains visible and searchable when drawn as separate segments.
- // A folder short of room keeps both ends; the line still reads it whole.
- bool shows(String text, String value) =>
- text == value ||
- text.contains('…') &&
- value.startsWith(text.split('…').first) &&
- value.endsWith(text.split('…').last);
+ // Minimal rows keep the full metadata accessible and searchable.
for (final value in [
'Claude',
'Test host',
'autonomous-harness',
'main',
]) {
- expect(
- find.byWidgetPredicate(
- (widget) => widget is SearchResultText && shows(widget.text, value),
- ),
- findsOneWidget,
- );
expect(
find.byWidgetPredicate(
(widget) =>
@@ -382,10 +369,7 @@ void main() {
findsWidgets,
);
}
- expect(
- find.textContaining('enter open', findRichText: true),
- findsOneWidget,
- );
+ expect(find.byKey(const ValueKey('swarm-search-hints')), findsNothing);
await tester.enterText(input, 'Architecture review');
await tester.pump();
expect(find.byType(ListTile), findsNWidgets(2));
diff --git a/desktop/test/swarm_search_preview_test.dart b/desktop/test/swarm_search_preview_test.dart
index f8d5c087f..b4f4672ff 100644
--- a/desktop/test/swarm_search_preview_test.dart
+++ b/desktop/test/swarm_search_preview_test.dart
@@ -33,6 +33,7 @@ Future<void> seedPreviews(AppNotifier app) async {
name: name,
engine: engine,
terminalAvailable: true,
+ lastActivityAt: DateTime.now().subtract(const Duration(minutes: 33)),
project: AgentProject(
name: id == 'a0' ? 'storefront' : 'workbench',
cwd: '/work/${id == 'a0' ? 'storefront' : 'workbench'}',
@@ -428,14 +429,19 @@ void main() {
);
await tester.pump(const Duration(milliseconds: 200));
expect(tester.takeException(), isNull);
- final preview = tester.getRect(
- find.byKey(const ValueKey('swarm-search-preview')),
- );
- final list = tester.getRect(
- find.byKey(const ValueKey('swarm-search-result-list')),
- );
- if (size.width < 864) {
- expect(preview.bottom, lessThanOrEqualTo(list.top));
+ final preview = find.byKey(const ValueKey('swarm-search-preview'));
+ if (size.width < 848) {
+ expect(preview, findsNothing);
+ } else {
+ expect(preview, findsOneWidget);
+ expect(
+ tester.getRect(preview).left,
+ greaterThan(
+ tester
+ .getRect(find.byKey(const ValueKey('swarm-search-result-list')))
+ .left,
+ ),
+ );
}
final directory = Platform.environment['HARNESS_PREVIEW_CAPTURE_DIR'];
if (directory != null) {
diff --git a/desktop/test/swarm_search_render_test.dart b/desktop/test/swarm_search_render_test.dart
index 7a2aa2296..50518fdf6 100644
--- a/desktop/test/swarm_search_render_test.dart
+++ b/desktop/test/swarm_search_render_test.dart
@@ -274,7 +274,7 @@ void main() {
find.byKey(ValueKey(search.selected!.id)),
);
expect(selected.selected, isTrue);
- expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
+ expect(find.byKey(const ValueKey('swarm-search-count')), findsNothing);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
expect(input, isEmpty);
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/swarm_search_test.dart b/desktop/test/swarm_search_test.dart
index 1d634bc47..866fd220d 100644
--- a/desktop/test/swarm_search_test.dart
+++ b/desktop/test/swarm_search_test.dart
@@ -346,11 +346,8 @@ void main() {
await tester.pump();
await tester.enterText(jumpField, 'Agent 0');
await tester.pump();
- expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
- expect(
- find.textContaining('enter open', findRichText: true),
- findsOneWidget,
- );
+ expect(find.byKey(const ValueKey('swarm-search-count')), findsNothing);
+ expect(find.byKey(const ValueKey('swarm-search-hints')), findsNothing);
await chord(tester, LogicalKeyboardKey.enter);
expect(find.byType(Dialog), findsNothing);
expect(app.activeSwarm, same(target));
diff --git a/desktop/test/swarm_split_test.dart b/desktop/test/swarm_split_test.dart
index baccfb12c..ba848eddd 100644
--- a/desktop/test/swarm_split_test.dart
+++ b/desktop/test/swarm_split_test.dart
@@ -1,3 +1,5 @@
+import 'support/launch_menu.dart';
+
import 'dart:async';
import 'package:flutter/gestures.dart';
@@ -9,7 +11,7 @@ import 'package:harness/state/new_harness.dart';
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_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/ws/ws_conn.dart';
import 'package:xterm/xterm.dart';
@@ -417,7 +419,7 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
final box = tester
- .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
.controller;
expect(box.split?.axis, axis);
expect(box.split?.paneId, pane.id);
@@ -426,7 +428,7 @@ void main() {
expect(box.project.folder, '/work/checkout');
expect(app.panes, [pane]);
expect(connection.calls, isNot(contains('agent_create')));
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await startHarness(tester);
await tester.pump();
expect(
connection.calls.where((call) => call == 'agent_create'),
diff --git a/desktop/test/terminal_catalog_test.dart b/desktop/test/terminal_catalog_test.dart
index 77d64d3d9..aa102b606 100644
--- a/desktop/test/terminal_catalog_test.dart
+++ b/desktop/test/terminal_catalog_test.dart
@@ -1,9 +1,7 @@
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/state/swarm_navigation.dart';
-import 'package:harness/widgets/search_result_text.dart';
import 'package:harness/widgets/swarm_switcher.dart';
import 'package:harness/terminal/terminal_binary.dart';
@@ -28,8 +26,8 @@ void main() {
final search = tester
.widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
.search;
- // Existing matches grow upward from the pinned New Harness action.
- await key(tester, LogicalKeyboardKey.arrowUp);
+ // Existing matches follow the New Harness action from top to bottom.
+ await key(tester, LogicalKeyboardKey.arrowDown);
expect(search.selected!.isCreate, isFalse);
final selected = search.selected!.id;
tester.view.physicalSize = const Size(600, 800);
@@ -50,21 +48,11 @@ void main() {
findsOneWidget,
reason: 'Selected row must remain visible with preview=$preview',
);
- final texts = find.descendant(
- of: row,
- matching: find.byType(SearchResultText),
- );
- final title = tester.getRect(texts.first);
- final detail = tester.getRect(texts.last);
final bounds = tester.getRect(row);
- expect(detail.top, greaterThanOrEqualTo(title.bottom - .01));
- final titleParagraph = tester.renderObject<RenderParagraph>(
- find.descendant(of: texts.first, matching: find.byType(RichText)),
+ expect(
+ find.descendant(of: row, matching: find.text(search.selected!.title)),
+ findsOneWidget,
);
- expect(titleParagraph.didExceedMaxLines, isFalse);
- expect(title.left, greaterThanOrEqualTo(bounds.left));
- expect(title.right, lessThanOrEqualTo(bounds.right));
- expect(detail.bottom, lessThanOrEqualTo(bounds.bottom));
final viewport = tester.getRect(
find.byKey(const ValueKey('swarm-search-result-list')),
);
@@ -164,7 +152,7 @@ void main() {
);
testWidgets(
- 'same-task results identify their agent without opening a preview',
+ 'same-task results show identity in preview and remain searchable by metadata',
(tester) async {
final app = createApp();
addTearDown(app.dispose);
@@ -172,22 +160,25 @@ void main() {
app.adoptSessionForTest(terminal('a0', []));
await mount(tester, app);
await key(tester, LogicalKeyboardKey.keyO, cmd: true);
- await key(tester, LogicalKeyboardKey.slash, ctrl: true);
final input = find.byKey(const ValueKey('swarm-search-input'));
- await tester.enterText(input, 'login');
- await tester.pump();
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
for (final (id, engine) in [('a0', 'Codex'), ('a1', 'Claude')]) {
- final row = find.byKey(ValueKey(agentDestinationId('m', id)));
- final visibleText = tester
- .widgetList<SearchResultText>(
- find.descendant(of: row, matching: find.byType(SearchResultText)),
- )
- .map((widget) => widget.text)
- .join(' ');
- expect(visibleText, contains(engine));
- expect(visibleText, contains('M2'));
+ await tester.enterText(input, 'login $engine M2');
+ await tester.pump();
+ expect(search.selected!.id, agentDestinationId('m', id));
+ final preview = find.byKey(const ValueKey('swarm-search-preview'));
+ expect(preview, findsOneWidget);
+ expect(
+ find.descendant(of: preview, matching: find.textContaining(engine)),
+ findsWidgets,
+ );
+ expect(
+ find.descendant(of: preview, matching: find.textContaining('M2')),
+ findsWidgets,
+ );
}
- expect(find.byKey(const ValueKey('swarm-search-preview')), findsNothing);
await tester.pumpWidget(const SizedBox());
},
);
diff --git a/desktop/test/terminal_ui_typography_test.dart b/desktop/test/terminal_ui_typography_test.dart
index d0140e2b7..165cd935a 100644
--- a/desktop/test/terminal_ui_typography_test.dart
+++ b/desktop/test/terminal_ui_typography_test.dart
@@ -11,9 +11,10 @@ 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/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_dialogs.dart';
import 'package:harness/widgets/swarm_search_preview.dart';
+import 'package:harness/widgets/search_result_text.dart';
import 'package:harness/widgets/workspace_welcome.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:xterm/xterm.dart';
@@ -94,11 +95,20 @@ void main() {
// The welcome page stands where a terminal will and is set like one, so
// it follows the terminal's size instead; see [checkWelcome].
final welcome = find.byType(WorkspaceWelcome);
+ final setup = find.byWidgetPredicate(
+ (widget) =>
+ widget is NewHarnessForm ||
+ widget.key == const ValueKey('swarm-search-results'),
+ );
for (final element in find.byType(RichText).evaluate()) {
if (find
- .descendant(of: welcome, matching: find.byWidget(element.widget))
- .evaluate()
- .isNotEmpty) {
+ .descendant(of: welcome, matching: find.byWidget(element.widget))
+ .evaluate()
+ .isNotEmpty ||
+ find
+ .descendant(of: setup, matching: find.byWidget(element.widget))
+ .evaluate()
+ .isNotEmpty) {
continue;
}
check((element.widget as RichText).text, const TextStyle());
@@ -220,7 +230,7 @@ void main() {
});
testWidgets(
- 'tabs, panes, welcome, Cmd-N, Cmd-O and Cmd-P keep the scale while the terminal zooms',
+ 'tabs keep the UI scale while welcome and setup screens follow terminal zoom',
(tester) async {
final app = createApp();
final map = MemoryKeymap();
@@ -245,11 +255,13 @@ void main() {
selectFont(18, TerminalFontChoice.monaco);
await tester.pumpAndSettle();
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- expect(find.byType(NewHarnessBox), findsOneWidget);
- final box = checkText(tester);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ final box = checkText(tester, atLeast: 1);
+ expect(tester.widget<Text>(find.text('New Harness')).style!.fontSize, 18);
selectFont(22);
await tester.pumpAndSettle();
- expectSameSizes(box, checkText(tester));
+ expectSameSizes(box, checkText(tester, atLeast: 1));
+ expect(tester.widget<Text>(find.text('New Harness')).style!.fontSize, 22);
await key(tester, LogicalKeyboardKey.escape);
for (final shortcut in [
LogicalKeyboardKey.keyO,
@@ -258,10 +270,10 @@ void main() {
await key(tester, shortcut, cmd: true);
final input = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(input, 'Agent');
- await key(tester, LogicalKeyboardKey.arrowUp);
+ await key(tester, LogicalKeyboardKey.arrowDown);
await tester.pumpAndSettle();
expect(find.byType(SwarmSearchPreview), findsOneWidget);
- final search = checkText(tester);
+ final search = checkText(tester, atLeast: 1);
selectFont(
shortcut == LogicalKeyboardKey.keyO ? 9 : 18,
TerminalFontChoice.monaco,
@@ -269,7 +281,19 @@ void main() {
await tester.pumpAndSettle();
expect(tester.widget<TextField>(input).controller!.text, 'Agent');
expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
- expectSameSizes(search, checkText(tester));
+ expectSameSizes(search, checkText(tester, atLeast: 1));
+ expect(
+ tester.widget<TextField>(input).style!.fontSize,
+ terminalFontStore.size,
+ );
+ 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);
+ }
await key(tester, LogicalKeyboardKey.escape);
}
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/workspace_start_guide_test.dart b/desktop/test/workspace_start_guide_test.dart
index 7a024868f..038fb1230 100644
--- a/desktop/test/workspace_start_guide_test.dart
+++ b/desktop/test/workspace_start_guide_test.dart
@@ -18,7 +18,7 @@ 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_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/harness_customize_pane.dart';
import 'package:harness/settings/appearance/wallpaper_section.dart';
import 'package:harness/widgets/workspace_start_guide.dart';
@@ -137,12 +137,12 @@ void main() {
final search = find.byKey(const ValueKey('swarm-search-input'));
expect(find.byType(WorkspaceWelcome), findsOneWidget);
expect(find.text('Follow your curiosity.'), findsOneWidget);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(search, findsNothing);
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
final tab = app.activeSwarmId;
expect(find.byType(WorkspaceWelcome), findsOneWidget);
@@ -156,10 +156,10 @@ void main() {
expect(search, findsNothing);
await tester.tap(find.byKey(const ValueKey('welcome-agent.new')));
await tester.pump();
- expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
await key(tester, LogicalKeyboardKey.escape);
expect(app.activeSwarmId, tab);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.launches, isEmpty);
await tester.pumpWidget(const SizedBox());
});
@@ -180,7 +180,7 @@ void main() {
await _mount(tester, app);
expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
await key(tester, LogicalKeyboardKey.keyO, cmd: true);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(find.byKey(const ValueKey('swarm-search-input')), findsOneWidget);
expect(find.text('Existing work'), findsOneWidget);
expect(find.byType(WorkspaceWelcome), findsOneWidget);
@@ -203,7 +203,7 @@ void main() {
addTearDown(app.dispose);
final pane = app.adoptSessionForTest(terminal('a0', []));
await _mount(tester, app);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(app.focusedPane, same(pane));
await tester.pumpWidget(const SizedBox());
});
@@ -283,7 +283,7 @@ void main() {
expect(app.swarms, [first, second, welcome]);
expect(app.allPanes, [pane, other]);
expect(find.byType(WorkspaceWelcome).hitTestable(), findsOneWidget);
- expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
await key(tester, LogicalKeyboardKey.keyO, cmd: true);
expect(
@@ -313,8 +313,8 @@ void main() {
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
await tester.pump(const Duration(milliseconds: 150));
- expect(find.byType(NewHarnessBox), findsOneWidget);
- expectGuideFixed(find.byKey(const ValueKey('new-harness-box')));
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ expectGuideFixed(find.byKey(const ValueKey('new-harness-form')));
await key(tester, LogicalKeyboardKey.escape);
await tester.pump();
await key(tester, LogicalKeyboardKey.keyW, cmd: true);
@@ -459,7 +459,7 @@ void main() {
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
await tester.pumpAndSettle();
- expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
expectCentered();
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
diff --git a/desktop/tool/native_benchmark/core_driver.dart b/desktop/tool/native_benchmark/core_driver.dart
index 539a4c3b6..e323a1b23 100644
--- a/desktop/tool/native_benchmark/core_driver.dart
+++ b/desktop/tool/native_benchmark/core_driver.dart
@@ -8,8 +8,7 @@ import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:harness/state/app_state.dart';
-import 'package:harness/state/new_harness.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_search_input.dart';
import 'package:harness/widgets/terminal_find_bar.dart';
import 'package:harness/widgets/workspace_welcome.dart';
@@ -134,21 +133,16 @@ Future<void> runCoreBenchmark(
}
Future<void> dismissNew() async {
- final element = benchmarkFind((w) => w is NewHarnessBox);
- if (element == null) return;
- final controller = (element.widget as NewHarnessBox).controller;
for (
var step = 0;
- step < 8 && controller.field != NewHarnessField.launch;
+ step < 4 && benchmarkFind((w) => w is NewHarnessForm) != null;
step++
) {
benchmarkKey(_escape, command: false);
await benchmarkFrame();
}
- benchmarkKey(_escape, command: false);
- await benchmarkFrame();
_check(
- benchmarkFind((w) => w is NewHarnessBox) == null,
+ benchmarkFind((w) => w is NewHarnessForm) == null,
'New harness did not close',
);
}
@@ -228,10 +222,14 @@ Future<void> runCoreBenchmark(
));
await benchmarkFrame();
_check(
- benchmarkFind((w) => w is NewHarnessBox) != null,
+ benchmarkFind((w) => w is NewHarnessForm) != null,
'Cmd+N did not open',
);
- _editingValue(); // The visible surface must also own editable focus.
+ _check(
+ FocusManager.instance.primaryFocus?.debugLabel ==
+ 'new-harness-form',
+ 'Cmd+N did not take keyboard focus',
+ );
case 'cmd_o':
benchmarkKey((
LogicalKeyboardKey.keyO,
diff --git a/desktop/tool/native_benchmark/flutter_driver.dart b/desktop/tool/native_benchmark/flutter_driver.dart
index 4a117525e..b6877ef46 100644
--- a/desktop/tool/native_benchmark/flutter_driver.dart
+++ b/desktop/tool/native_benchmark/flutter_driver.dart
@@ -10,8 +10,7 @@ import 'package:flutter/services.dart';
import 'package:harness/settings/settings_screen.dart';
import 'package:harness/shortcuts/shortcuts_browser.dart';
import 'package:harness/state/app_state.dart';
-import 'package:harness/state/new_harness.dart';
-import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_search_input.dart';
import 'package:harness/widgets/terminal_find_bar.dart';
import 'package:harness/widgets/workspace_welcome.dart';
@@ -128,7 +127,7 @@ Future<void> runFlutterDispatchBenchmark(
(
'cmd_n',
(LogicalKeyboardKey.keyN, PhysicalKeyboardKey.keyN),
- (w) => w is NewHarnessBox,
+ (w) => w is NewHarnessForm,
),
(
'cmd_o',
@@ -188,26 +187,23 @@ Future<void> runFlutterDispatchBenchmark(
'firstFrame': firstFrame,
'readyFrame': readyFrame,
});
- // With no inherited project, Cmd-N starts on the project question.
- // Escape first returns to its launch summary, then closes the box.
- if (element.widget case NewHarnessBox(:final controller)) {
- for (
- var step = 0;
- step < 8 && controller.field != NewHarnessField.launch;
- step++
- ) {
+ // Escape clears a filter or prompt before closing. Stop dispatching
+ // as soon as the form disappears so no key reaches the terminal.
+ if (element.widget is NewHarnessForm) {
+ for (var step = 0; step < 4 && _find(matches) != null; step++) {
_key(_escape, command: false);
await _frame();
}
+ } else {
+ _key(_escape, command: false);
}
- _key(_escape, command: false);
for (var frame = 0; frame < 120 && _find(matches) != null; frame++) {
await _frame();
}
if (_find(matches) != null) {
throw StateError(
'$operation did not dismiss; focus ${FocusManager.instance.primaryFocus}; '
- 'creation field ${(_find((w) => w is NewHarnessBox)?.widget as NewHarnessBox?)?.controller.field}',
+ 'creation field ${(_find((w) => w is NewHarnessForm)?.widget as NewHarnessForm?)?.controller.field}',
);
}
}