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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Make New Harness compact with predictable launch defaults (#350)
Deeaa4bd36c2153
diff --git a/desktop/design/images/terminal-new-harness-compact.png b/desktop/design/images/terminal-new-harness-compact.pngnew file mode 100644index 000000000..258ff8e0aBinary files /dev/null and b/desktop/design/images/terminal-new-harness-compact.png differdiff --git a/desktop/design/images/terminal-new-harness-runner.png b/desktop/design/images/terminal-new-harness-runner.pngnew file mode 100644index 000000000..53b0325adBinary files /dev/null and b/desktop/design/images/terminal-new-harness-runner.png differdiff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.mdindex 6e48ce263..62827b96e 100644--- a/desktop/design/new-harness-entry-rules.md+++ b/desktop/design/new-harness-entry-rules.md@@ -8,35 +8,38 @@ Escape leaves that tab open. The command dock opens only after an explicitCmd-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 `[ New Harness ]` selected. Agent, Project, and-Options are the only main rows. Enter launches using the displayed settings;-Enter on a field edits it. Options starts collapsed on a fresh draft and expands-Model, Branch, Worktree, Approvals, and applicable Profile settings. Resumed-drafts retain their expansion state. The launch action stays pinned below the-scrolling fields and prints the live `picker.start` shortcut (⇧⏎ by default).-That shortcut accepts the highlighted value before starting; it cannot skip an-unfinished machine or specialized-agent choice. Carried tasks remain in the draft.--The right pane shows resolved launch settings until a field is edited. Enter,-Right, or typing replaces the summary with choices; accepting returns to the-field. Agent combines coding agents and specialized harnesses in one list.-Choosing Blender opens a compatible coding-agent list in the same pane. Project+The compact, centered launch form starts with `New Harness` selected.+Agent, Project, and collapsed Options are the main rows. Options expands Model,+Approvals, applicable Profile, Branch, and Worktree in consecutive rows. Enter launches+using the displayed settings. The launch action follows the fields with one blank row+and no extra shortcut hint. Enter on the selected action launches; there is no+Shift-Enter shortcut. Carried tasks remain in the draft.++Up/Down moves between fields and automatically reveals that field's chooser to+the right, without moving the form. Right, typing, or Enter moves keyboard focus+into the chooser. Enter accepts a value and returns focus to New Harness; a+second Enter launches. Escape discards the search and returns to the form.+There is no summary pane. Agent combines coding agents and specialized+harnesses in one list. Choosing Blender opens a compatible coding-agent list+in the chooser. Projectsearches all machine/folder pairs, local first, with unavailable destinationsdimmed. Choosing a pair sets both the machine and project. New Folder, OpenFolder, and Clone Repository first ask for a machine, with local preselected,then show their name, path/browser, or URL prompt. Escape retraces these steps.-There is no permanent Machine field or machine scope selector.+Project displays `machine:full-path`; there is no separate Machine row.Use the terminal's selected font and measured cells. All controls are plaintext, with one-row highlights. Worktree uses `[x]` / `[ ]`. Narrow windows show-the active list full-width with a back action. Opening, searching, and cancelling+the active list on the same column with its own height. Validation messages have+their own whole rows. The chooser starts with search, without+a back/title row; Left or Escape returns to the form. Opening, searching, and cancellingnever send input to an existing harness or start one.| 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 |-| Cmd-Shift-P → New Harness | Focused pane's agent, machine, and project | Current tab |-| Cmd-N or the New Harness command | Focused pane's defaults; retain a task and destination already chosen in search | Current tab unless its source requests a new tab |+| Cmd-T, then Cmd-N | Last successful agent, local machine, last project on that machine | The blank tab opened by Cmd-T |+| Cmd-Shift-P → New Harness | Last successful agent, local machine, last project on that machine | Current tab |+| Cmd-N or the New Harness command | Last successful agent, local machine, last project on that machine; retain explicit task and destination | Current tab unless its source requests a new tab || Explicit pane split | Focused pane's defaults | Requested split in that tab || Store New Harness, or a product's Open action in the pane or native Models menu | Explicit product and machine; suggested project named for that product | New tab || Store Resume Harness | Existing harness and its machine; choose from a menu when several match | Focus its existing tab or reopen a view of the same harness |@@ -71,9 +74,9 @@ then reads `Blender · Codex`. Choosing a direct agent removes the package choicand sends no `dsh`; it does not remove project instructions or skills.Explicit entry choices and pending receipts win over remembered defaults. A-remembered package no longer offered by the machine falls back to a direct-coding agent. A package requested explicitly keeps its identity. Missing packages-install when started; the right pane narrates the machine's installation and+remembered agent, package, project, or profile that is unavailable requires an+explicit replacement. A package requested explicitly keeps its identity. Packages+offered by the machine can install when started; the dialog narrates installation andfailure details. Another agent or project machine clears that narration.Machine changes re-evaluate compatibility and never silently substitute atlaunch. The installed package's compatibility takes precedence over a newer@@ -81,11 +84,13 @@ catalog listing.The existing local state store retains separate engine and harness recents andthe last successful engine per harness. Legacy preference keys and the app data-directory stay in place. Fresh forms no longer inherit an expanded Options panel.+directory stay in place. Fresh forms use successful launches, not canceled edits.## Model selection-Model lives under Options and uses the chosen agent’s supported routes. Its picker reuses the Models menu's subscription usage+Model lives under Options and uses the chosen agent’s supported routes. Show the+selected model name, or its provider (OpenAI / Anthropic) when the launch model+is not reported. Its picker reuses the Models menu's subscription usagesource and the selected machine's model catalog. It shows the relevantsubscription/default login, running models on the person's machines, and sharedmodels grouped by grid. Each model identifies its serving machine; search matches@@ -97,7 +102,7 @@ model, refreshes availability, and blocks Start with an explanation if the newcombination is unavailable. It never substitutes a subscription. Refresh modelsupdates the choices; Manage Models opens the existing Models panel for lifecyclemanagement and preserves the launch draft. Choosing Terminal clears model routing;-its Model row is disabled and explains that Terminal does not use a model.+its Model row is omitted.An explicit model survives draft dismissal/restoration and uncertain creationreceipts. A new session starts with the selected engine's default subscription;@@ -108,9 +113,10 @@ is needed while continuing to allow ordinary subscription launches.## Git projects-Git projects enable Branch and Worktree. Worktree defaults to **Yes** for a-repository with a commit; Enter, Space, Left/Right, Page Up/Down, or a click toggles-`[x]` and `[ ]`. Folders without Git keep both Options rows disabled. Discovery runs on the selected machine+Git projects enable Branch and Worktree. Worktree defaults to **Yes**;+Enter, Space, Left/Right, Page Up/Down, or a click toggles `[x]` and `[ ]`.+An empty repository explains that a commit is required for a worktree and asks+for a choice. Folders without Git keep both rows disabled. Discovery runs on the selected machinewithout fetching, switching branches, or creating a worktree. A faileddiscovery offers Retry and blocks starting until the result is known.@@ -129,8 +135,10 @@ in the repository's main checkout, so Cmd-N from a worktree pane starts besideit rather than inside it. Worktrees Start made are never offered as recentprojects.-**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:+**Branch** starts on `main` (local, or `origin/main`) with Worktree on, and on the+folder's own branch after the user turns Worktree off. Missing `main` requires+an explicit branch choice; a failed worktree creation never silently turns+Worktree off. Branch does not follow the pane New Harness was opened from:New Harness is new work, and another agent's branch is one pick away. The startaction reads **New Harness**, whatever the rows say.The picker names local branches; a remote branch is listed only when no local@@ -184,7 +192,7 @@ worktree it finds in `~/harnesses/worktrees` only when no live or stoppedharness uses it, nothing is uncommitted, and it has been idle for a week; thebranch stays unless Harness made it and its commits are all elsewhere.-Drafts and advanced options preserve these choices. A lost start reply reuses+Drafts preserve these choices. A lost start reply reusesits receipt, and retrying a confirmed launch failure reuses its preparedworktree: the retry selects that worktree's branch with Worktree off.@@ -192,12 +200,12 @@ worktree: the retry selects that worktree's branch with Worktree off.- Workspace drafts belong to their original machine, focused source harness,and project context. A different focused harness does not inherit their edits.-- Cmd-N and Cmd-Shift-P can resume the same workspace draft. The current tab controls- placement; a saved draft cannot redirect it to an old destination.+- Fresh Cmd-N and Cmd-Shift-P creation use the same successful-launch defaults.+ The current tab controls placement; a saved draft cannot redirect it to an old destination.- Store drafts belong to the explicitly requested product and machine. OpeningBlender cannot restore Workshop's agent, task, or generated project name.-- Escape preserves edits. Reopening the same source without a new task resumes- its compatible draft, including the selected agent. Store Open still wins if the+- Escape discards ordinary Cmd-N edits. Explicit Store entries can resume their+ compatible draft, including the selected agent. Store Open still wins if theharness or machine was changed inside that saved draft.- A newly typed search task or Store example starts from that entry's defaults.Repeating the same request while its draft is already open keeps its edits.@@ -221,6 +229,21 @@ never silently renamed, and existing files are never overwritten.## Regression coverage+`tool/check_new_harness_coverage.mjs` requires 100% executable-line coverage of+the complete `lib/state/new_harness.dart` and `lib/widgets/new_harness_form.dart`+modules, including the install clock. Neither module excludes lines from coverage.+After running tests with `flutter test --coverage --branch-coverage`, run+`node tool/check_new_harness_coverage.mjs coverage/lcov.info`. This is a line+coverage gate; branch coverage and the native fixtures provide additional evidence,+not a guarantee about every possible external machine or agent failure.++- `test/new_harness_controller_edges_test.dart`: late discovery, unavailable+ main, conflicting worktrees, profile validation/link errors, stale choices,+ generated-name collisions, bounded folder caches, and lost creation receipts.+- `test/new_harness_scenarios_test.dart`: keyboard and pointer parity, Unicode+ editing and composition, unavailable replacements, long errors, small windows,+ delayed folder/browser/launch replies, and callbacks after form disposal.+- `test/new_harness_git_test.dart`, `test/git_worktree_test.dart`, and`test/git_worktree_failures_test.dart`: Git defaults, disabled non-Git rows,keyboard/click toggles, branch search, branch resolution, stalediff --git a/desktop/design/terminal-dialogs.md b/desktop/design/terminal-dialogs.mdindex 3b4c4a9b7..9835e0256 100644--- a/desktop/design/terminal-dialogs.md+++ b/desktop/design/terminal-dialogs.md@@ -71,8 +71,9 @@ when using custom row widgets.followed by status and harness type. Omit missing fields and preserveimportant state such as Offline.- Boolean controls use `[x]` and `[ ]`; Enter and Space toggle them.-- Actions use concise text, such as `[ New Harness ]`. Shortcut hints are text- beside the action, resolved from the live keymap.+- Menu actions use concise text, such as `New Harness`, with the same row+ highlight as other choices and no surrounding brackets. Shortcut hints,+ when needed, are text beside the action, resolved from the live keymap.- Omit redundant heading rows such as “New Tab” or “New Pane.” Add a label orexplanation only when it helps someone understand a choice or state.- Preserve user content, including Unicode. The restriction on decorative@@ -156,25 +157,53 @@ come from Harness's own Terminal preferences, not Apple Terminal or iTerm.## Keep the terminal interaction-Cmd-N opens with **Agent**, **Project**, **Options**, and the selected-`[ New Harness ]` action. Enter launches with the displayed settings. Options-starts collapsed on a fresh draft and expands Model, Branch, Worktree,-Approvals, and Profile in place. Keep Worktree as `[x]` / `[ ]`.----The right pane shows the resolved machine, full folder, model, and applicable-Git and agent settings. Enter or typing on a field replaces that summary with-its searchable choices; accepting a value restores the summary. Narrow windows-show the active choices in place of the form. No permanent Machine field or-additional top-level Harness field.+Cmd-N opens a compact, centered key/value form with Agent, Project, collapsed+Options, and `New Harness` selected. Enter launches with the displayed+settings. Options expands Model, Approvals, applicable Profile, Branch, and Worktree+as consecutive rows without internal blank rows. Machine is selected with Project. Keep a blank row between Agent and Project and before Options.+Worktree uses `[x]` / `[ ]`. There is no duplicate summary pane.+Project shows the committed machine and full path, such as+`M2:~/code/autonomous-harness`. Browsing the chooser never changes this value+until a choice is accepted.++++Reserve nine columns for labels and two blank columns before values. The launch+action follows the last visible field with exactly one blank row; never pin it+to the bottom with a flexible spacer. The form and chooser use whole character+columns and rows. The form fits its visible rows, stays centered, and keeps its+geometry when choices appear beside it. The chooser starts directly with its search line;+omit a redundant back/title row such as `< Agent`.++Up/Down selects a field and automatically reveals its small chooser to the+right. Navigation still belongs to the form. Right, typing, or Enter moves+focus into the chooser; then Up/Down moves its choices. Enter accepts a value,+closes the chooser, and selects New Harness, ready for the next Enter to launch.+A held Enter must not accept and launch in one keypress. Escape discards the+search and returns to the form in one step; Left also returns when the search+is empty. Nested project and specialized-agent steps retrace their choices.+On narrow windows, the active chooser replaces the form on the same column with+enough rows for its list. Returning restores the compact form. Validation messages+get whole rows of their own so neither the explanation nor the choices are clipped.++Fresh Cmd-N uses the last successfully launched agent, the last used project+on the local machine, the local machine, branch `main`, and Worktree Yes for a+Git project. Model shows the selected model name, or OpenAI / Anthropic when+the subscription agent has not reported a model. Approvals starts at Auto-approve.+Focused panes and canceled edits do not change these defaults; unresolved+launch receipts remain recoverable. An explicit split can inherit its source.+If a required value is unavailable or uncertain, explain it and require a+choice. Never substitute another branch, project, agent, or profile, or turn+Worktree off after a worktree creation failure.Agent offers Codex, Claude Code, Terminal, and specialized harnesses together.-A direct agent completes the choice. A specialized harness such as Blender-opens `Run Blender with` in the same pane, offering compatible coding agents-with its remembered choice selected. The left value then reads+Keep agent choices to one line. A direct agent completes the choice. A specialized harness such as Blender+uses `Run Blender with` as the search hint, offering compatible coding agents+with its remembered choice selected. The Agent value then reads`Blender · Codex`.++Project searches existing `machine:project` pairs across the inventory; names,machine names, and paths are searchable. Put local projects first before asearch, and dim unavailable destinations with a short reason. Selecting adiff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.mdindex b9d8a5276..42705e2d6 100644--- a/desktop/design/terminal-workspace.md+++ b/desktop/design/terminal-workspace.md@@ -11,8 +11,10 @@ are the detailed implementation references for this system.## Text is the interface-Use meaningful names and familiar terminal punctuation. Prefer `[ New Harness ]`-and `[ Customize Harness ]` to rounded buttons with pictograms. A checkbox is+Use meaningful names and familiar terminal punctuation. Menu actions such as+`New Harness` use plain text and the same row highlight as other choices.+Standalone actions can use brackets, such as `[ Customize Harness ]`, instead+of rounded buttons with pictograms. A checkbox is`[x]` or `[ ]`. Harness search has no prefix; `#` selects projects and `>` selectscommands as editable text. Small, established actions may use `+`,`@`, `:`, and `*`, with a descriptive tooltip and accessible name.diff --git a/desktop/integration_test/native_workspace_e2e_test.dart b/desktop/integration_test/native_workspace_e2e_test.dartindex 0400747a2..fa24237cc 100644--- a/desktop/integration_test/native_workspace_e2e_test.dart+++ b/desktop/integration_test/native_workspace_e2e_test.dart@@ -31,7 +31,6 @@ 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';@@ -197,6 +196,7 @@ class _FirstCreationApp extends AppNotifier {..localOnly = true..nodeOnline = true..agentLoadStatus = AgentLoadStatus.loaded;+ gitProjectReaderForTest = (_, _) async => {'isGit': false};status = AppStatus.authenticated;}@@ -934,6 +934,8 @@ void main() {(tester) async {final connection = _InstallingConnection();final app = _FirstCreationApp(connection);+ await app.agentPreference.remember('claude');+ await app.projectHistory.select('m', '/fixture/project');addTearDown(app.dispose);addTearDown(connection.close);await tester.pumpWidget(@@ -973,7 +975,8 @@ void main() {.controller;expect(box.harnessId, 'autonomous/circuit');- await key(tester, LogicalKeyboardKey.enter, shift: true);+ await key(tester, LogicalKeyboardKey.enter);+ await startHarness(tester);await settle();expect(connection.installs, ['autonomous/circuit']);expect(@@ -1003,7 +1006,7 @@ void main() {expect(inPane('✗'), findsOneWidget);expect(connection.creates, isEmpty);- await key(tester, LogicalKeyboardKey.enter, shift: true);+ await key(tester, LogicalKeyboardKey.enter);await settle();expect(connection.installs, hasLength(2));expect(inPane('✗'), findsNothing);@@ -1024,7 +1027,7 @@ void main() {(tester) async {final connection = _CreationConnection();final app = _FirstCreationApp(connection);- await app.agentPreference.select('codex');+ await app.agentPreference.remember('codex');final projects = SwarmProjectStore();addTearDown(app.dispose);addTearDown(projects.dispose);@@ -1049,8 +1052,23 @@ void main() {.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller;expect(box.engine, 'codex');- expect(box.projectLabel, startsWith('~/harnesses/codex-'));+ expect(box.needsProject, isTrue);+ await startHarness(tester);+ expect(connection.creates, isEmpty);+ expect(box.requiredChoice?.message, 'Choose a project.');+ await tester.tap(+ find.byKey(+ ValueKey('new-harness-option-${NewHarnessController.newProjectId}'),+ ),+ );+ await tester.pump();+ expect(box.field, NewHarnessField.machine);+ await key(tester, LogicalKeyboardKey.enter);+ expect(box.field, NewHarnessField.projectName);+ await typeHarnessQuery(tester, 'first-project');+ await key(tester, LogicalKeyboardKey.enter);final proposedFolder = box.projectFolderRequest!.folderName;+ expect(proposedFolder, 'first-project');expect(connection.creates, isEmpty);expect(find.byType(WorkspaceWelcome), findsOneWidget);await startHarness(tester);@@ -1446,6 +1464,8 @@ void main() {app.machineStates['m']!..localOnly = true..terminalCapabilityAvailable = true;+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');final originalInput = <TerminalBinaryFrame>[];app.adoptSessionForTest(terminal('a0', originalInput));final source = app.activeSwarm;@@ -1596,12 +1616,14 @@ void main() {await tester.pump(const Duration(milliseconds: 200));await reply.future;expect(find.byType(NewHarnessForm), findsNothing);- expect(find.byType(ModelsPanel), findsOneWidget);+ final models = find.byKey(const ValueKey('swarm-search-input'));+ expect(models, findsOneWidget);+ expect(tester.widget<TextField>(models).controller!.text, ':local');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(models, findsNothing);expect(connection.creates, isEmpty);expect(originalInput, isEmpty);await tester.pumpWidget(const SizedBox());@@ -1611,7 +1633,8 @@ void main() {await open('autonomous/blender', task: task);const product = 'autonomous/blender';const prefix = 'blender';- expect(prompt().engine, product);+ expect(prompt().harnessId, product);+ expect(prompt().engine, 'claude');expect(prompt().projectLabel, startsWith('~/harnesses/$prefix-'));expect(prompt().task, task ?? '');final folder = prompt().projectFolderRequest!.folderName;@@ -1649,11 +1672,15 @@ void main() {}testWidgets(- 'native creation retains edited defaults and uses the chosen destination',+ 'native creation resets canceled edits and launches the reviewed choices',(tester) async {final connection = _CreationConnection();final app = createApp(connectionForTest: (_) => connection);seedMixedAgents(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');final input = <TerminalBinaryFrame>[];final original = app.adoptSessionForTest(terminal('a0', input));final source = app.activeSwarm;@@ -1691,11 +1718,8 @@ void main() {expect(prompt().task, task);expect(app.swarms, [source]);expect(app.activeSwarm, same(source));- expect(prompt().field, NewHarnessField.projectMenu);+ expect(prompt().field, NewHarnessField.launch);- await openLaunchRow(tester, 'machine');- await key(tester, LogicalKeyboardKey.enter);- expect(prompt().machineId, 'm');await openLaunchRow(tester, 'project');await typeHarnessQuery(tester, 'openharness');await key(tester, LogicalKeyboardKey.enter);@@ -1731,8 +1755,17 @@ void main() {}expect(prompt().selected?.id, NewHarnessController.existingProjectId);await key(tester, LogicalKeyboardKey.enter);+ expect(prompt().field, NewHarnessField.machine);+ await key(tester, LogicalKeyboardKey.enter);expect(prompt().field, NewHarnessField.project);- expect(prompt().options.single.id, NewHarnessController.browseId);+ expect(+ prompt().options.any(+ (option) => option.id == NewHarnessController.browseId,+ ),+ isTrue,+ );+ await key(tester, LogicalKeyboardKey.escape);+ expect(prompt().field, NewHarnessField.machine);await key(tester, LogicalKeyboardKey.escape);expect(prompt().field, NewHarnessField.projectMenu);@@ -1752,14 +1785,21 @@ void main() {);expect(connection.creates, isEmpty);- // Reopen from the same source. Escape kept the task and edited defaults- // without creating a temporary tab.+ // A canceled draft does not become the next Cmd-N's defaults.await key(tester, LogicalKeyboardKey.keyN, cmd: true);await tester.pump(const Duration(milliseconds: 80));+ expect(prompt().engine, 'codex');+ expect(prompt().modeLabel, 'Auto-approve');+ expect(prompt().task, '');+ expect(prompt().project.folder, '/work/openharness');+ await openLaunchRow(tester, 'agent');+ await typeHarnessQuery(tester, 'claude');+ await key(tester, LogicalKeyboardKey.enter);+ await openLaunchRow(tester, 'approvals');+ await typeHarnessQuery(tester, 'Plan first');+ await key(tester, LogicalKeyboardKey.enter);expect(prompt().engine, 'claude');expect(prompt().mode, 'plan');- expect(prompt().task, task);- expect(prompt().project.folder, '/work/openharness');await startHarness(tester);await tester.pump(const Duration(milliseconds: 200));expect(find.byType(NewHarnessForm), findsNothing);@@ -1767,7 +1807,7 @@ void main() {expect(source.panes.length, 2);expect(source.panes.first, same(original));expect(app.focusedPane!.agentId, 'made');- expect(connection.creates.single, containsPair('prompt', task));+ expect(connection.creates.single['prompt'], isNull);expect(connection.creates.single, containsPair('engine', 'claude'));expect(connection.creates.single, containsPair('permissionMode', 'plan'));expect(diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex adefe78b8..08053723c 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -1839,13 +1839,11 @@ class _SwarmScreenState extends State<SwarmScreen> {// row would have started the harness on.if (newHarnessOpensInBox) task ??= search?.createTask;if (app.activeSwarmId != target) return;- // In the box, the new harness starts as another of the one you were in —- // its agent, its machine, its project — the way a tmux split inherits its- // pane and a new terminal tab opens where the last one was. The form keeps- // what it always did: it inherits only for a split.+ // A fresh launcher uses saved choices on this computer. Only an explicit+ // split inherits its source pane; changing focus never changes Cmd-N's+ // defaults.final focused =- source == _NewHarnessSource.workspace &&- (newHarnessOpensInBox || requestedSplit != null)+ source == _NewHarnessSource.workspace && requestedSplit != null? app.focusedPane ?? _newTabSources[target]: null;final machine = focused == null ? null : app.stateOf(focused.machineId);@@ -1860,19 +1858,24 @@ class _SwarmScreenState extends State<SwarmScreen> {.firstOrNull?.machine.machineId ??- app.machineStates.keys.firstOrNull;+ (newHarnessOpensInBox ? null : app.machineStates.keys.firstOrNull);final paneProject =projectName != null || agent == null || id != focused?.machineId? null: machine?.projectOf(agent);- // Another one of these: its agent, machine and folder — not its branch.- // New Harness is new work; another agent's branch is one pick away, and- // joins its worktree rather than being where Start begins.- final initialFolder = folder ?? paneProject?.cwd;if (id == null) {await _showMachinesControls();return;}+ await Future.wait([app.agentPreference.load(), app.projectHistory.load()]);+ if (!mounted || app.activeSwarmId != target) return;+ final initialFolder =+ folder ??+ paneProject?.cwd ??+ (newHarnessOpensInBox && source == _NewHarnessSource.workspace+ ? app.projectHistory.selected(id) ??+ app.projectHistory.recent(id).firstOrNull+ : null);if (!newHarnessOpensInBox) {await _newAgentForm(machineId: id,@@ -1896,7 +1899,7 @@ class _SwarmScreenState extends State<SwarmScreen> {autoProject:projectName == null &&initialFolder == null &&- (source == _NewHarnessSource.product || app.panes.isEmpty),+ source == _NewHarnessSource.product,task: task,draftContext: (source: source,@@ -2049,7 +2052,9 @@ class _SwarmScreenState extends State<SwarmScreen> {draft ??(savedDraft != null &&(savedDraft.attempt?.awaitingConfirmation == true ||- (task == null && matchesSelection(savedDraft)))+ (origin.source != _NewHarnessSource.workspace &&+ task == null &&+ matchesSelection(savedDraft)))? savedDraft: null);if (resumed != null) _newHarnessDrafts.remove(origin);@@ -2114,8 +2119,6 @@ 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(@@ -2139,21 +2142,12 @@ class _SwarmScreenState extends State<SwarmScreen> {),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,+ child: Padding(+ padding: EdgeInsets.symmetric(+ horizontal: terminalCellSizeOf(context).width * 2,+ vertical: terminalCellSizeOf(context).height,),+ child: content,),),],@@ -2330,7 +2324,10 @@ class _SwarmScreenState extends State<SwarmScreen> {if (restoreFocus) {// Creation can replace a picker whose editor is now detached. Its node// still holds a context, but cannot receive keys after cancellation.- if (previous?.context?.mounted == true && previous!.canRequestFocus) {+ if (previous != null &&+ previous is! FocusScopeNode &&+ previous.context?.mounted == true &&+ previous.canRequestFocus) {previous.requestFocus();} else if (app.focusedPane?.session?.focusInput() != true) {_shellFocus.requestFocus();diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex d6c201bfa..8df84160c 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -567,14 +567,6 @@ final harnessCommands = <HarnessCommand>[extraKeys: ['enter', 'ctrl+m'],context: KeymapContext.picker,),- // Starts New Harness from any field, without walking down to its button.- const HarnessCommand(- 'picker.start',- 'Start the new harness from any field',- ShortcutGroup.actions,- extraKeys: ['shift+enter'],- context: KeymapContext.picker,- ),const HarnessCommand('picker.refresh','Refresh the machine list',diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 67267f5ec..2200cf594 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1,5 +1,5 @@import 'dart:async';-import 'dart:io' show exit, pid;+import 'dart:io' show Directory, exit, pid;import 'dart:math' show Random;import 'package:dio/dio.dart';@@ -7067,6 +7067,9 @@ class AppNotifier extends ChangeNotifier {final reader = gitProjectReaderForTest;if (reader != null) return reader(machineId, path);if (machine.isLocalMachine) {+ if (!await Directory(path).exists()) {+ return {'error': 'PROJECT_UNAVAILABLE'};+ }return readLocalGitProject(path, refresh: refresh);}if (connectionForTest == null &&diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex f0b364cb1..c7a4d1a4d 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -139,22 +139,17 @@ String? currentBranchRef(GitProjectInfo info) =>? 'refs/heads/${info.branch}': null;-/// Worktree starts on for a Git project with a commit to start from.-bool worktreeByDefault(GitProjectInfo info) =>- info.isGit && info.branches.any((branch) => !branch.remote);+/// Git projects keep Worktree on; an empty repository asks for a choice.+bool worktreeByDefault(GitProjectInfo info) => info.isGit;-/// Where Start begins when no branch was chosen: new work from the default-/// branch (the local one, which Start brings up to its remote), work in the-/// folder on the branch it is on.+/// New work starts from main. If it is absent, require an explicit choice.+/// With Worktree off, show the branch the folder is actually on.String? defaultBranchRef(GitProjectInfo info, {required bool worktree}) {if (!worktree) return currentBranchRef(info);- final remote = info.defaultRef;- final local = remote == null- ? null- : 'refs/heads/${remote.split('/').skip(3).join('/')}';- return info.branches.any((b) => b.ref == local)- ? local- : remote ?? currentBranchRef(info);+ for (final ref in ['refs/heads/main', 'refs/remotes/origin/main']) {+ if (info.branches.any((branch) => branch.ref == ref)) return ref;+ }+ return null;}/// The branch a worktree started from [base] is on, unless [name] was typed:@@ -193,6 +188,8 @@ WorktreePlan planWorktree(final fresh = WorktreePlan(WorktreeStart.newBranch, placeholder, base: base);final defaultName = info.defaultRef?.split('/').skip(3).join('/');if (base == null ||+ base == 'refs/heads/main' ||+ base == 'refs/remotes/origin/main' ||base == info.defaultRef ||base == 'refs/heads/$defaultName') {return fresh;@@ -421,6 +418,7 @@ class NewHarnessController extends ChangeNotifier {_home = home ?? Platform.environment['HOME'] {final explicitSelection =draft != null || engine != null || harnessId != null;+ _rememberedAgent = !explicitSelection;engine = draft?.engine ?? engine;_harnessId =draft?.harnessId ??@@ -435,7 +433,6 @@ class NewHarnessController extends ChangeNotifier {: harnessId != null && engine != null && !isHarnessId(engine)? engine: _initialEngine(isHarnessId(engine) ? null : engine);- if (!explicitSelection) _forgetUnofferedHarness();_model = isTerminal ? null : draft?.model;_modelUsage = modelUsage;_ownsModelUsage = modelUsage == null;@@ -474,8 +471,8 @@ class NewHarnessController extends ChangeNotifier {? NewHarnessProject.fresh(projectName): _generatedProject();}- // A missing project is the only required question. Carried tasks remain- // part of the draft for Store examples and advanced options.+ // Start at the missing project when there is no saved one. Any other+ // unavailable value is explained by requiredChoice before launching.field = needsProject && !checking? NewHarnessField.projectMenu: NewHarnessField.launch;@@ -493,7 +490,6 @@ class NewHarnessController extends ChangeNotifier {if (!_selectionTouched && !explicitSelection) {_harnessId = app.agentPreference.harness;_engine = _initialEngine(null);- _forgetUnofferedHarness();if (_project.generated != null) _project = _generatedProject();} else if (!_selectionTouched && draft == null && isHarnessId(engine)) {_engine = _initialEngine(null);@@ -525,7 +521,6 @@ class NewHarnessController extends ChangeNotifier {return;}_engine = _initialEngine(null);- if (!explicitSelection) _forgetUnofferedHarness();_refresh();}),);@@ -572,19 +567,10 @@ class NewHarnessController extends ChangeNotifier {return entry != null && !entry.isViewerPackage;}- /// A remembered harness the machine no longer offers opens as Code. Only- /// a remembered one: a harness someone asked for by name keeps its row, and- /// its start explains what is wrong.- void _forgetUnofferedHarness() {- final id = _harnessId;- if (id == null || _offered(id)) return;- _harnessId = null;- _engine = _initialEngine(null);- }-String get harnessLabel => _harnessId == null ? 'Code' : labelOf(_harnessId!);bool advancedOpen = false;bool _selectionTouched = false;+ bool _rememberedAgent = false;void toggleAdvanced() {if (locked) return;advancedOpen = !advancedOpen;@@ -612,14 +598,15 @@ class NewHarnessController extends ChangeNotifier {[knownHarnessBase[canonicalHarnessId(_harnessId!)] ?? 'claude'];String _initialEngine(String? requested) {final allowed = compatibleEngines;- for (final candidate in [- requested,- app.agentPreference.engineFor(_harnessId),- app.agentPreference.value,- selectedHarness?.engine,- ]) {- if (candidate != null && allowed.contains(candidate)) return candidate;- }+ final remembered =+ requested ??+ app.agentPreference.engineFor(_harnessId) ??+ (_harnessId == null || _harnessId == app.agentPreference.harness+ ? app.agentPreference.value+ : null);+ if (remembered != null) return remembered;+ final preferred = selectedHarness?.engine;+ if (preferred != null && allowed.contains(preferred)) return preferred;return allowed.first;}@@ -644,12 +631,6 @@ class NewHarnessController extends ChangeNotifier {bool refreshingBranches = false;String? branchRefreshError;DateTime? _branchesCheckedAt;- Future<void> waitForGitProject() async {- while (checkingGit && !_disposed) {- await _gitFuture;- }- }-bool get isGitProject => _gitProject.isGit && !isTerminal;bool get canUseWorktree => isGitProject && !checkingGit;bool get worktree =>@@ -660,7 +641,9 @@ class NewHarnessController extends ChangeNotifier {String? get branchRef =>_branchRef ?? defaultBranchRef(_gitProject, worktree: worktree);String? get gitError => _gitProject.error;- String get branchLabel => _refName(branchRef) ?? 'Detached HEAD';+ String get branchLabel =>+ _refName(branchRef) ??+ (worktree ? 'main · unavailable' : 'Detached HEAD');String? _refName(String? ref) =>_gitProject.branches.where((branch) => branch.ref == ref)@@ -719,28 +702,6 @@ class NewHarnessController extends ChangeNotifier {? worktreePlan?.kind == WorktreeStart.openWorktree: _branchHere == null && _worktreeOf(branchRef) != null;- /// What Start does with Git, in words for the summary and screen readers.- String get gitSummary {- if (!isGitProject) return '';- final plan = worktreePlan;- if (plan == null) {- final here = _branchHere;- return here != null- ? ', on a new branch $here'- : opensWorktree- ? ', in the worktree of $branchLabel'- : ', on $branchLabel';- }- return switch (plan.kind) {- WorktreeStart.newBranch =>- ', in a new worktree on ${plan.branch == placeholder ? 'a branch named after the session' : plan.branch} from ${_refName(plan.base) ?? 'HEAD'}',- WorktreeStart.existingBranch => ', in a new worktree on ${plan.branch}',- WorktreeStart.openWorktree => ', in the worktree of ${plan.branch}',- WorktreeStart.unavailable =>- ', but ${plan.branch} is the project folder’s branch',- };- }-void toggleWorktree() {if (locked || !canUseWorktree) return;_worktree = !worktree;@@ -897,7 +858,7 @@ class NewHarnessController extends ChangeNotifier {String get subscriptionLabel => switch (_engine) {'codex' => 'OpenAI','claude' => 'Anthropic',- _ => '$agentLabel default',+ _ => agentLabel,};String get modelLabel => _model == null? subscriptionLabel@@ -1105,7 +1066,6 @@ class NewHarnessController extends ChangeNotifier {// engine while its settings are open in a child picker.String? _agentPreview;String get _settingsEngine => _agentPreview ?? _engine;- String get agentSettingsLabel => labelOf(_settingsEngine);LocalCodexProfile? get _settingsProfile =>_settingsEngine == _engine ? _profile : null;List<PermissionMode> get _settingsModes =>@@ -1122,7 +1082,6 @@ class NewHarnessController extends ChangeNotifier {_modes.any((mode) => mode.id == _mode) ? _mode : kDefaultPermissionMode;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' && _model == null;bool get hasProfile => _baseOf(_settingsEngine) == 'codex';bool get supportsProfiles =>@@ -1203,9 +1162,6 @@ class NewHarnessController extends ChangeNotifier {(value == NewHarnessField.mode && _settingsModes.isNotEmpty) ||(value == NewHarnessField.profile && hasProfile);- NewHarnessField get nextMainField => field == NewHarnessField.machine- ? NewHarnessField.projectMenu- : fields[(fields.indexOf(field) + 1) % fields.length];int cursor = 0;List<NewHarnessOption> options = const [];@@ -1237,6 +1193,65 @@ class NewHarnessController extends ChangeNotifier {_project.repository == null &&projectFolderSlug(_project.name ?? '') == null;+ /// A missing or ambiguous saved value stays visible until the person+ /// replaces it. These checks never select a different launch target.+ ({NewHarnessField field, String message})? get requiredChoice {+ if (checking) return null;+ if (needsProject) {+ return (field: NewHarnessField.projectMenu, message: 'Choose a project.');+ }+ final machine = _machine;+ if (machine == null || machine.isOffline || machine.needsLink) {+ return (+ field: NewHarnessField.machine,+ message: 'This machine is unavailable. Choose a machine.',+ );+ }+ if (_harnessId != null && !_offered(_harnessId!)) {+ return (+ field: NewHarnessField.harness,+ message: '$harnessLabel is unavailable. Choose an agent.',+ );+ }+ if (!compatibleEngines.contains(_engine) ||+ (_rememberedAgent &&+ !_selectionTouched &&+ machine.engines[_engine]?.installed == false)) {+ return (+ field: _harnessId == null+ ? NewHarnessField.harness+ : NewHarnessField.agent,+ message: '$agentLabel is unavailable. Choose an agent.',+ );+ }+ if (gitError == 'PROJECT_UNAVAILABLE') {+ return (+ field: NewHarnessField.projectMenu,+ message: 'This project is unavailable. Choose a project.',+ );+ }+ if (!checkingGit && isGitProject && worktree && branchRef == null) {+ return (+ field: _gitProject.branches.isEmpty+ ? NewHarnessField.projectMenu+ : NewHarnessField.branch,+ message: _gitProject.branches.isEmpty+ ? 'This project has no commits. Choose a project or make an initial commit.'+ : 'This project has no main branch. Choose a branch.',+ );+ }+ if (usesProfile &&+ _profile != null &&+ _profilesLoaded &&+ !_profiles.any((profile) => profile.path == _profile!.path)) {+ return (+ field: NewHarnessField.profile,+ message: 'This profile is unavailable. Choose a profile.',+ );+ }+ return null;+ }+// ---- what the line says -------------------------------------------------/// The same on every New Harness: where Start goes is said by the Branch row,@@ -1247,7 +1262,7 @@ class NewHarnessController extends ChangeNotifier {String get launchAgentLabel =>_harnessId == null ? agentLabel : '$harnessLabel · $agentLabel';String get launchProjectLabel =>- '$machineLabel:${needsProject ? "Choose project" : p.basename(projectLabel)}';+ '$machineLabel:${needsProject ? "Choose project" : projectLabel}';String labelOf(String id) => currentHarnessName(id,_machine?.dsh[id]?.name ??@@ -1937,6 +1952,7 @@ class NewHarnessController extends ChangeNotifier {}List<LocalCodexProfile> _profiles = const [];+ bool _profilesLoaded = false;String? _profilesMachine;int _profileRevision = 0;int _profileRequest = 0;@@ -1945,6 +1961,7 @@ class NewHarnessController extends ChangeNotifier {void _resetProfiles() {_profiles = const [];+ _profilesLoaded = false;_profilesMachine = null;_profileRevision++;_profileRequest++;@@ -1962,6 +1979,7 @@ class NewHarnessController extends ChangeNotifier {request == _profileRequest;_profilesMachine = machine;loadingProfiles = true;+ _profilesLoaded = false;error = null;_refresh();try {@@ -1979,6 +1997,7 @@ class NewHarnessController extends ChangeNotifier {for (final raw in result['profiles'] as List? ?? const [])LocalCodexProfile.fromJson(Map<String, dynamic>.from(raw as Map)),];+ _profilesLoaded = true;} catch (_) {if (current() && field == NewHarnessField.profile) {error =@@ -2066,6 +2085,10 @@ class NewHarnessController extends ChangeNotifier {detail: profile.path,profile: profile,machineId: _machineId,+ enabled:+ !_profilesLoaded ||+ _profiles.any((available) => available.path == profile.path),+ why: 'This profile is unavailable. Choose a profile.',),]),];@@ -3042,9 +3065,30 @@ class NewHarnessController extends ChangeNotifier {if (busy || linkingProfile) {return NewHarnessOutcome.failed;}- if (needsProject && !checking) {- focusField(NewHarnessField.projectMenu);- return _fail('Choose a project, or create a new one.');+ if (!checking && usesProfile && _profile != null) {+ if (loadingProfiles) {+ return _fail(+ 'Profiles are still loading. Try again when they are ready.',+ );+ }+ final validation = refreshProfiles();+ busy = true;+ status = 'Checking profile…';+ notifyListeners();+ await validation;+ if (_disposed) return NewHarnessOutcome.failed;+ busy = false;+ status = null;+ if (!_profilesLoaded) {+ focusField(NewHarnessField.profile);+ return _fail(+ 'Could not verify this profile. Choose a profile or refresh to retry.',+ );+ }+ }+ if (requiredChoice case final choice?) {+ focusField(choice.field);+ return _fail(choice.message);}if (!checking) {_syncGitProject();@@ -3058,6 +3102,10 @@ class NewHarnessController extends ChangeNotifier {busy = false;status = null;}+ if (requiredChoice case final choice?) {+ focusField(choice.field);+ return _fail(choice.message);+ }if (gitError != null) {return _fail('Could not check Git on $machineLabel. Check the connection and Harness CLI, then retry.',@@ -3150,6 +3198,11 @@ class NewHarnessController extends ChangeNotifier {'${labelOf(harness)} harness.',);}+ if (!_offered(harness)) {+ busy = false;+ focusField(NewHarnessField.harness);+ return _fail('$harnessLabel is unavailable. Choose an agent.');+ }harness =harnessForOperation(machine.dsh.entries, harness)?.id ?? harness;if (machine.dsh[harness]?.installed == false) {diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dartindex c320b0c64..969acef0d 100644--- a/desktop/lib/widgets/new_harness_form.dart+++ b/desktop/lib/widgets/new_harness_form.dart@@ -6,9 +6,7 @@ import 'package:xterm/xterm.dart' show TerminalTheme;import '../shortcuts/app_keymap.dart';import '../shortcuts/keymap.dart';-import '../shortcuts/keymap_commands.dart' show describeKeyBinding;import '../core/dsh_catalog.dart';-import '../core/test_run.dart';import '../shared/theme/app_theme.dart' as grid;import '../terminal/terminal_text.dart';import '../terminal/terminal_theme.dart';@@ -17,15 +15,9 @@ import '../state/new_harness.dart';import 'box_chrome.dart' show kTerminalCornerRadius, terminalPaneBorder;import 'dsh_install_panel.dart' show describeInstallFailure;-/// Agent and Project are the main choices; Options holds the launch settings.-///-/// Shares Open Harness's terminal typography and quiet selection treatment.-/// ↑↓ walk fields or choices. Return edits or accepts, and the initially-/// selected New Harness action launches. The right pane shows resolved-/// settings until a field is edited. Typing filters without committing.-///-/// Unavailable Git fields explain why they cannot be changed. Profile only-/// appears for agents that use it.+/// Agent, Project, and collapsed Options in a compact terminal grid.+/// Enter on the selected launch action starts with the displayed defaults.+/// Selecting a field reveals its chooser beside the centered form.class NewHarnessForm extends StatefulWidget {const NewHarnessForm({super.key,@@ -48,16 +40,15 @@ class NewHarnessForm extends StatefulWidget {State<NewHarnessForm> createState() => _NewHarnessFormState();}-/// Core launch choices stay visible; less common settings expand in place.enum _Row {agent,project,advanced,model,- branch,- worktree,approvals,profile,+ branch,+ worktree,start,}@@ -75,20 +66,24 @@ class _NewHarnessFormState extends State<NewHarnessForm> {static const _advancedRows = {_Row.model,- _Row.branch,- _Row.worktree,_Row.approvals,_Row.profile,+ _Row.branch,+ _Row.worktree,};+List<_Row> get _rows => [for (final row in _Row.values)if ((!_advancedRows.contains(row) || box.advancedOpen) &&- (row != _Row.profile || box.usesProfile))+ (row != _Row.profile || box.usesProfile) &&+ (row != _Row.model || !box.isTerminal) &&+ (row != _Row.approvals || box.hasModes))row,];- /// Whether the focused field's choices replace the launch summary.+ /// Choices can be visible before they own keyboard focus.bool _listOpen = false;+ bool _hideChoices = false;String? _folderAction;@override@@ -198,8 +193,6 @@ class _NewHarnessFormState extends State<NewHarnessForm> {_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',- _Row.model when box.isTerminal => 'Not used by Terminal',_ => null,};@@ -228,7 +221,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {_Row.worktree => box.worktree ? '[x]' : '[ ]',_Row.approvals => box.modeLabel,_Row.profile => box.profileLabel ?? 'Default',- _Row.start => '',+ _Row.start => box.checking ? 'Check status' : _label(row),};/// Focusing a row focuses the field it edits, so the controller's option@@ -250,6 +243,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {setState(() {_row = rows[(rows.indexOf(_row) + delta) % rows.length];_listOpen = false;+ _hideChoices = false;});if (box.query.isNotEmpty) box.setQuery('');_syncField();@@ -333,20 +327,22 @@ class _NewHarnessFormState extends State<NewHarnessForm> {box.applyOption(_wheel[_at]);}- /// Hand the keys back to the rows, leaving the choices on screen.+ /// Close the chooser and hand the keys back to the rows.///- /// One implementation for the two ways out that are not Escape: ← from the- /// live list, and the narrow layout's back chevron. They used to be written- /// twice, which is how a back button and a back key drift apart.+ /// Left returns from a chooser, including in a narrow window.void _backToRows() {- _folderAction = null;- if (_prompts.contains(box.field) || box.field == NewHarnessField.machine) {+ if (_prompts.contains(box.field) ||+ (box.field == NewHarnessField.machine && _folderAction != null)) {box.focusField(NewHarnessField.projectMenu);} else if (box.field == NewHarnessField.agent) {box.focusField(NewHarnessField.harness);}+ _folderAction = null;box.setQuery('');- setState(() => _listOpen = false);+ setState(() {+ _listOpen = false;+ _hideChoices = true;+ });_focus.requestFocus();_revealRow();}@@ -371,6 +367,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {/// 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;+ setState(() => _listOpen = true);box.setQuery(value);_focusEditor();}@@ -529,12 +526,28 @@ class _NewHarnessFormState extends State<NewHarnessForm> {Future<void> _start() async {if (box.busy) return;- switch (await box.create()) {+ if (box.requiredChoice case final choice?) {+ box.focusField(choice.field);+ setState(() => _listOpen = true);+ box.warn(choice.message);+ _focusEditor();+ _revealRow();+ return;+ }+ final outcome = await box.create();+ if (!mounted) return;+ switch (outcome) {case NewHarnessOutcome.created:widget.onCreated();case NewHarnessOutcome.failed:// The controller has said why on the line; keep the keys live.- if (mounted) _focus.requestFocus();+ if (box.requiredChoice != null) {+ setState(() => _listOpen = true);+ _focusEditor();+ _revealRow();+ } else {+ _focus.requestFocus();+ }}}@@ -552,7 +565,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {box.applyOption(option);if (box.error != null) return;box.setQuery('');- if (field == NewHarnessField.machine) {+ if (field == NewHarnessField.machine && _folderAction != null) {box.focusField(switch (_folderAction) {NewHarnessController.newProjectId => NewHarnessField.projectName,NewHarnessController.repositoryId =>@@ -569,33 +582,13 @@ class _NewHarnessFormState extends State<NewHarnessForm> {box.focusField(NewHarnessField.harness);}_folderAction = null;- setState(() => _listOpen = false);+ _selectRow(_Row.start);}}_focusEditor();_revealRow();}- /// ⇧⏎ from anywhere: start with what is on screen, instead of walking- /// down every field to the button. A value highlighted in a live list is- /// taken first — it is what the person was looking at when they pressed- /// it — and a door's prompt is finished the way Return finishes it.- void _go() {- if (box.locked) return;- if (_picking) {- final option = box.selected;- if (option == null || !option.enabled) {- _confirm();- return;- }- _acceptChoice(option);- // Folder and specialized-agent steps must be finished before launch.- if (_picking || box.error != null) return;- }- setState(() => _listOpen = false);- unawaited(_start());- }-void _confirm() {// Return chooses a value in the list; only the start row launches.if (_picking) {@@ -625,24 +618,25 @@ class _NewHarnessFormState extends State<NewHarnessForm> {if (box.requestDismiss()) widget.onClose();return;}- // 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 (box.field == NewHarnessField.agent && _picking) {+ // Escape goes back one screen, discarding its uncommitted search.+ if (box.field == NewHarnessField.agent && _picking) {box.focusField(NewHarnessField.harness);setState(() => _listOpen = true);} else if (_prompts.contains(box.field) && _folderAction != null) {_chooseFolderMachine(_folderAction!, preferLocal: false);} else if (_prompts.contains(box.field) ||- box.field == NewHarnessField.machine) {+ (box.field == NewHarnessField.machine && _folderAction != null)) {_folderAction = null;setState(() {box.focusField(NewHarnessField.projectMenu);_listOpen = true;});- } else if (_listOpen) {- setState(() => _listOpen = false);+ } else if (_picking || (!_hideChoices && _hasChoices)) {+ setState(() {+ _listOpen = false;+ _hideChoices = true;+ });+ box.setQuery('');} else {if (box.requestDismiss()) widget.onClose();}@@ -659,6 +653,11 @@ class _NewHarnessFormState extends State<NewHarnessForm> {if (event is! KeyDownEvent && event is! KeyRepeatEvent) {return KeyEventResult.ignored;}+ if (event is KeyRepeatEvent &&+ (event.logicalKey == LogicalKeyboardKey.enter ||+ event.logicalKey == LogicalKeyboardKey.numpadEnter)) {+ return KeyEventResult.handled;+ }// 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;@@ -730,10 +729,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {_stepValue(1);case LogicalKeyboardKey.enter:case LogicalKeyboardKey.numpadEnter:- // ⇧⏎ is `picker.start`, a keymap command so it can be remapped: let- // it past, to the region that dispatches it.if (HardwareKeyboard.instance.isShiftPressed) {- return KeyEventResult.ignored;+ return KeyEventResult.handled;}_confirm();case LogicalKeyboardKey.escape:@@ -777,7 +774,6 @@ class _NewHarnessFormState extends State<NewHarnessForm> {TerminalTheme get _theme =>terminalThemeFor(grid.AppTheme.palette.value, terminalThemeStore.value);- Color get _rule => _theme.foreground.withValues(alpha: .16);Color get _faint => _theme.foreground.withValues(alpha: .54);// Only the column that owns the keys carries Open Harness's full highlight.@@ -824,13 +820,14 @@ class _NewHarnessFormState extends State<NewHarnessForm> {/// selection bar has a column of air on either side.double get _margin => _cell;- /// The fzf pointer column on the right: `>`, and the action glyphs, live+ /// The fzf pointer column in the choices: `>`, and the action glyphs, live/// in these two cells, and every name, heading and notice starts after it.double get _gutter => _cell * 2;- /// A field's label is padded to this many cells, as `ls -l` pads a column,- /// so every value on the left starts on the same column.- static const _labelCells = 10;+ /// The longest label is Approvals (nine cells), followed by two spaces.+ /// Every editable field uses this same value column.+ static const _labelCells = 9;+ static const _labelGapCells = 2;/// One row, with its content sitting on the line.Widget _oneRow(Widget child) => SizedBox(@@ -841,6 +838,35 @@ class _NewHarnessFormState extends State<NewHarnessForm> {/// Geometry follows the same size, so the columns keep their proportions.double _scale = 1;+ /// Notices need real rows too; otherwise a compact frame clips the reason+ /// a launch was refused below its last action.+ int _noticeRows(BuildContext context, int columns) {+ if (_picking) return 0;+ final required = box.requiredChoice?.message;+ final messages = [+ ?required,+ if ((box.error != null || box.status != null) &&+ (box.error == null || box.error != required))+ box.error ?? box.status!,+ ];+ var rows = 0;+ for (final message in messages) {+ rows += 1 + _textRows(context, message, columns - 4);+ }+ return rows;+ }++ int _textRows(BuildContext context, String text, int columns) {+ final painter = TextPainter(+ text: TextSpan(text: text, style: _ink()),+ textDirection: TextDirection.ltr,+ textScaler: MediaQuery.textScalerOf(context),+ )..layout(maxWidth: columns.clamp(1, 1000) * _cell);+ final rows = (painter.height / _rowHeight).ceil();+ painter.dispose();+ return rows;+ }+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -856,7 +882,6 @@ class _NewHarnessFormState extends State<NewHarnessForm> {composing: _isComposing,actions: {'picker.accept': () => _runCommand(_confirm),- 'picker.start': () => _runCommand(_go),'picker.cancel': () => _runCommand(_cancel),'picker.next': () =>_runCommand(() => _picking ? _stepMatch(1) : _moveRow(1)),@@ -874,65 +899,65 @@ class _NewHarnessFormState extends State<NewHarnessForm> {key: const ValueKey('new-harness-form'),focusNode: _focus,onKeyEvent: _onKey,- child: Material(- key: const ValueKey('new-harness-surface'),- elevation: 0,- color: _theme.background,- surfaceTintColor: Colors.transparent,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(kTerminalCornerRadius),- side: terminalPaneBorder(focused: true),- ),- clipBehavior: Clip.antiAlias,- child: DefaultTextStyle.merge(- style: _ink(),- child: 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)- : _installing != null- ? _installPane(_installing!)- : _items(),- ),- if (!_picking &&- _installing == null &&- (box.error != null || box.status != null))- Padding(- padding: EdgeInsets.fromLTRB(- _margin * 2,- 0,- _margin * 2,- _rowHeight,- ),- child: _status(),- ),- ],- );- }- return Row(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Expanded(flex: 55, child: _items()),- VerticalDivider(width: 1, thickness: 1, color: _rule),- Expanded(- flex: 45,- child: _installing != null- ? _installPane(_installing!)- : _picking- ? _sidePane()- : _summaryPane(),+ child: LayoutBuilder(+ builder: (context, constraints) {+ final columns = (constraints.maxWidth / _cell).floor();+ final rows = (constraints.maxHeight / _rowHeight).floor();+ final mainColumns = columns.clamp(1, 56);+ final contentRows =+ _rows.length ++ 5 ++ (box.task.isNotEmpty ? 1 : 0) ++ _noticeRows(context, mainColumns);+ final mainRows = rows.clamp(1, contentRows);+ final left = (columns - mainColumns) ~/ 2;+ final top = (rows - mainRows) ~/ 2;+ final available = columns - left - mainColumns - 1;+ final beside = available >= 28;+ final showChoices = _hasChoices && (_picking || !_hideChoices);+ final pickerColumns = beside+ ? available.clamp(28, 40)+ : mainColumns;+ final notice = _picking ? box.error ?? box.status : null;+ final pickerRows = rows.clamp(+ 1,+ 16 ++ (notice == null+ ? 0+ : 1 + _textRows(context, notice, pickerColumns - 6)),+ );+ final pickerTop = top.clamp(0, rows - pickerRows);+ final replaceForm = _picking && !beside;+ return Stack(+ children: [+ Positioned(+ left: left * _cell,+ top: (replaceForm ? pickerTop : top) * _rowHeight,+ width: mainColumns * _cell,+ height: (replaceForm ? pickerRows : mainRows) * _rowHeight,+ child: _surface(+ const ValueKey('new-harness-surface'),+ _installing != null+ ? _installPane(_installing!)+ : replaceForm+ ? _sidePane()+ : _items(),+ ),+ ),+ if (showChoices && beside)+ Positioned(+ left: (left + mainColumns + 1) * _cell,+ top: pickerTop * _rowHeight,+ width: pickerColumns * _cell,+ height: pickerRows * _rowHeight,+ child: _surface(+ const ValueKey('new-harness-chooser-surface'),+ _sidePane(),),- ],- );- },- ),- ),+ ),+ ],+ );+ },),),);@@ -946,99 +971,103 @@ class _NewHarnessFormState extends State<NewHarnessForm> {);}- Widget _items() => Padding(- padding: EdgeInsets.fromLTRB(_margin, _rowHeight, _margin, _rowHeight),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Expanded(- child: Scrollbar(- controller: _fieldsScroll,- thumbVisibility: true,- child: SingleChildScrollView(- controller: _fieldsScroll,- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- for (final row in _rows.where(- (row) => row != _Row.start,- )) ...[- // Blank rows group the fields: what runs, where it- // runs, then the settings most people never open.- if (row == _Row.advanced) SizedBox(height: _rowHeight),- _buildRow(row),- ],- ],- ),- ),- ),- ),- _buildButton(),- ],+ Widget _surface(Key key, Widget child) => Material(+ key: key,+ elevation: 0,+ color: _theme.background,+ surfaceTintColor: Colors.transparent,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),+ side: terminalPaneBorder(focused: true),),+ clipBehavior: Clip.antiAlias,+ child: DefaultTextStyle.merge(style: _ink(), child: child),);- Widget _summaryPane() {- final values = <(String, String)>[- ('Machine', box.machineLabel),- ('Folder', box.projectLabel),- if (!box.isTerminal) ('Model', box.modelLabel),- if (box.isGitProject) ...[- ('Branch', box.branchRowLabel),- ('Worktree', box.worktree ? 'Yes' : 'No'),- ],- if (box.hasModes) ('Approvals', box.modeLabel),- if (box.usesProfile) ('Profile', box.profileLabel ?? 'Default'),- if (box.task.isNotEmpty) ('Task', box.task),- ];- return SingleChildScrollView(- key: const ValueKey('new-harness-summary'),- padding: EdgeInsets.symmetric(- horizontal: _cell * 2,- vertical: _rowHeight,- ),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- for (final (label, value) in values)- Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- SizedBox(- width: _cell * 11,- child: Text(label, style: _ink(_faint)),+ Widget _items() => Padding(+ padding: EdgeInsets.fromLTRB(_margin, _rowHeight, _margin, _rowHeight),+ child: Scrollbar(+ controller: _fieldsScroll,+ thumbVisibility: true,+ child: SingleChildScrollView(+ controller: _fieldsScroll,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final row in _rows.where((row) => row != _Row.start)) ...[+ // Blank rows are part of the grid, never flexible spacers.+ if (row == _Row.project || row == _Row.advanced)+ SizedBox(height: _rowHeight),+ _buildRow(row),+ ],+ if (box.task.isNotEmpty)+ Padding(+ padding: EdgeInsets.symmetric(horizontal: _margin),+ child: _oneRow(+ Row(+ children: [+ SizedBox(+ width: _cell * (_labelCells + _labelGapCells),+ child: Text('Task', style: _ink(_faint)),+ ),+ Expanded(+ child: Tooltip(+ message: box.task,+ child: Text(+ box.task,+ style: _ink(),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ ),+ ],+ ),),- Expanded(child: Text(value, style: _ink(_faint))),- ],- ),- if (box.error != null || box.status != null) ...[- SizedBox(height: _rowHeight),- _status(),+ ),+ _buildButton(),+ if (!_picking && box.requiredChoice != null) ...[+ SizedBox(height: _rowHeight),+ Padding(+ padding: EdgeInsets.symmetric(horizontal: _margin),+ child: Text(+ box.requiredChoice!.message,+ style: _ink(_theme.red),+ ),+ ),+ ],+ if (!_picking &&+ (box.error != null || box.status != null) &&+ (box.error == null ||+ box.error != box.requiredChoice?.message)) ...[+ SizedBox(height: _rowHeight),+ Padding(+ padding: EdgeInsets.symmetric(horizontal: _margin),+ child: _status(),+ ),+ ],],- ],+ ),),- );- }+ ),+ );- /// The only action that starts an agent, and the one thing on this form- /// that is not a value. A terminal has no buttons, only text in cells, so- /// it is drawn the way BIOS draws `[Yes]`: bracketed, on the label column,- /// one row tall — with the key that reaches it from anywhere printed- /// beside it, so nobody has to walk down every field to find it.+ /// The launch action uses plain text on the label column and the same+ /// single-row highlight as the fields. It is selected when the form opens.Widget _buildButton() {final on = _row == _Row.start && !_picking;- final label = box.checking ? 'Check status' : 'New Harness';+ final label = _value(_Row.start);return Semantics(key: const ValueKey('new-harness-field-start'),container: true,button: true,- // The brackets and the key are how it LOOKS; a screen reader says- // what it is.label: label,excludeSemantics: true,selected: on,- enabled: !box.busy && !box.linkingProfile,- onTap: !box.busy && !box.linkingProfile ? _start : null,+ enabled: !box.busy && !box.linkingProfile && box.requiredChoice == null,+ onTap: !box.busy && !box.linkingProfile && box.requiredChoice == null+ ? _start+ : null,child: Padding(key: _itemKeys[_Row.start],// One blank row between the last field and the action.@@ -1046,37 +1075,24 @@ class _NewHarnessFormState extends State<NewHarnessForm> {child: GestureDetector(behavior: HitTestBehavior.opaque,excludeFromSemantics: true,- onTap: !box.busy && !box.linkingProfile ? _start : null,+ onTap: !box.busy && !box.linkingProfile && box.requiredChoice == null+ ? _start+ : null,child: Container(color: on ? _activeFill : Colors.transparent,padding: EdgeInsets.symmetric(horizontal: _margin),height: _rowHeight,alignment: Alignment.centerLeft,- // In a narrow pane at large text the key hint gives way first,- // clipped like a terminal line, so the label is never what is cut.- child: Row(- children: [- Flexible(- flex: 4,- child: Text(- '[ $label ]',- maxLines: 1,- softWrap: false,- overflow: TextOverflow.clip,- style: _ink(_theme.cursor),- ),- ),- SizedBox(width: _cell * 2),- Flexible(- child: Text(- _startKeyLabel,- maxLines: 1,- softWrap: false,- overflow: TextOverflow.clip,- style: _ink(_faint),- ),- ),- ],+ child: Text(+ label,+ maxLines: 1,+ softWrap: false,+ overflow: TextOverflow.clip,+ style: _ink(+ box.requiredChoice != null || _picking+ ? _faint+ : _theme.foreground,+ ),),),),@@ -1084,23 +1100,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {);}- /// The start key as the keymap has it bound — a remap shows the new key.- String get _startKeyLabel {- final binding = KeymapTheme.of(context)- ?.bindings('picker.start', context: KeymapContext.picker)- .firstOrNull;- // A space after each modifier — `⇧ ⏎`, not `⇧⏎` — so the glyphs read as- // separate keys at terminal size rather than as one symbol.- final keys = binding == null ? '⇧⏎' : describeKeyBinding(binding);- return keys- .replaceAllMapped(RegExp('([⌘⌥⌃⇧])'), (m) => '${m[1]} ')- .replaceAll(RegExp(' +'), ' ')- .trim();- }-- /// 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(+ /// The chooser uses the same frame, font, and cell origin as the form.+ Widget _sidePane() => Semantics(key: const ValueKey('new-harness-choices'),container: true,focused: _picking,@@ -1110,33 +1111,13 @@ class _NewHarnessFormState extends State<NewHarnessForm> {child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- if (compact)- Padding(- // The back row, then one blank row.- padding: EdgeInsets.only(bottom: _rowHeight),- child: InkWell(- canRequestFocus: false,- onTap: _backToRows,- child: Padding(- padding: EdgeInsets.symmetric(horizontal: _margin),- child: Row(- children: [- _inGutter(Text('<', style: _ink(_faint))),- Text(_label(_row), style: _ink(_faint)),- ],- ),- ),- ),- ),if (_hasChoices) ...[- if (box.field == NewHarnessField.agent ||- box.field == NewHarnessField.machine ||+ if ((box.field == NewHarnessField.machine &&+ _folderAction != null) ||_prompts.contains(box.field)) ...[_atTextColumn(Text(- box.field == NewHarnessField.agent- ? 'Run ${box.harnessLabel} with'- : box.field == NewHarnessField.machine+ box.field == NewHarnessField.machine? switch (_folderAction) {NewHarnessController.newProjectId => 'New Folder',NewHarnessController.repositoryId =>@@ -1168,7 +1149,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {),),],- if (box.error != null || box.status != null) ...[+ if (_picking && (box.error != null || box.status != null)) ...[SizedBox(height: _rowHeight),_atTextColumn(_status()),],@@ -1268,7 +1249,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {line(null,run.failed- ? 'What was downloaded is kept. $_startKeyLabel tries again.'+ ? 'What was downloaded is kept. Enter tries again.': run.done? 'Starting the harness…': 'The first install takes a few minutes.',@@ -1376,7 +1357,9 @@ class _NewHarnessFormState extends State<NewHarnessForm> {/// What the prompt is actually for. A path prompt is not a search — it/// wants a folder typed at it — so it borrows the controller's own words/// rather than calling everything "Search".- String get _promptHint => box.hint;+ String get _promptHint => box.field == NewHarnessField.agent+ ? 'Run ${box.harnessLabel} with'+ : box.hint;Widget _searchBar() {return Padding(@@ -1413,8 +1396,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {showCursor: _picking,style: _ink(_theme.foreground),cursorColor: _theme.cursor,- // A block caret, one cell wide, as a terminal draws it.- cursorWidth: _cell,+ cursorWidth: 2,cursorRadius: Radius.zero,cursorOpacityAnimates: false,autocorrect: false,@@ -1476,7 +1458,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {/// Whether a choice carries a description under its name.bool _showsDetail(NewHarnessOption option) =>- (_row == _Row.agent || _row == _Row.model || _row == _Row.profile) &&+ (_row == _Row.model || _row == _Row.profile) &&option.detail.isNotEmpty &&!_isDoor(option);@@ -1516,7 +1498,11 @@ class _NewHarnessFormState extends State<NewHarnessForm> {key: ValueKey('new-harness-option-${option.id}'),// Colour is not announced, so the word the row no longer prints is// still what a screen reader says.- hint: unlinked ? 'Link required' : null,+ hint: unlinked+ ? 'Link required'+ : _row == _Row.agent && option.detail.isNotEmpty+ ? option.detail+ : null,selected: on,enabled: option.enabled && !box.locked,button: _isDoor(option),@@ -1581,6 +1567,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {setState(() {_row = row;_listOpen = false;+ _hideChoices = false;});box.setQuery('');_syncField();@@ -1608,7 +1595,9 @@ class _NewHarnessFormState extends State<NewHarnessForm> {setState(() {_row = _Row.advanced;_listOpen = false;+ _hideChoices = false;});+ box.setQuery('');_focusEditor();_revealRow();}@@ -1647,7 +1636,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {width: _cell * _labelCells,child: Text(_label(row), style: _ink(_faint)),),- SizedBox(width: _cell * 2),+ SizedBox(width: _cell * _labelGapCells),Expanded(child: Text(value,@@ -1666,7 +1655,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {}/// An install's running clock, ticking itself so the form does not rebuild-/// every second. Frozen under test, where a periodic timer never settles.+/// every second. Disposed with the install pane.class _Elapsed extends StatefulWidget {const _Elapsed({required this.run, required this.style});@@ -1683,16 +1672,11 @@ class _ElapsedState extends State<_Elapsed> {@overridevoid initState() {super.initState();- _tick = kUnderTest ? null : _startClock();+ _tick = Timer.periodic(const Duration(seconds: 1), (_) {+ if (mounted && widget.run.inProgress) setState(() {});+ });}- // coverage:ignore-start- // Never runs under flutter test (see initState), where coverage is measured.- Timer _startClock() => Timer.periodic(const Duration(seconds: 1), (_) {- if (mounted && widget.run.inProgress) setState(() {});- });- // coverage:ignore-end-@overridevoid dispose() {_tick?.cancel();diff --git a/desktop/test/advanced_agent_keyboard_test.dart b/desktop/test/advanced_agent_keyboard_test.dartindex 9b7b5e42a..86de57c0a 100644--- a/desktop/test/advanced_agent_keyboard_test.dart+++ b/desktop/test/advanced_agent_keyboard_test.dart@@ -252,7 +252,12 @@ void main() {final connection = _Connection();final app = createApp(connectionForTest: (_) => connection);addTearDown(app.dispose);- app.machineStates['m']!.nodeOnline = true;+ app.machineStates['m']!+ ..nodeOnline = true+ ..localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');app.adoptSessionForTest(terminal('a0', []));await mount(tester, app);await key(tester, LogicalKeyboardKey.keyT, cmd: true);diff --git a/desktop/test/box_flows_test.dart b/desktop/test/box_flows_test.dartindex 89613a64d..c8b6066d9 100644--- a/desktop/test/box_flows_test.dart+++ b/desktop/test/box_flows_test.dart@@ -33,10 +33,14 @@ void main() {tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller;testWidgets(- 'edited defaults and a carried task survive closing and reopening',+ 'canceled edits and tasks do not replace successful launch defaults',(tester) async {final app = createApp();seedMixedAgents(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');app.adoptSessionForTest(terminal('a0', []));addTearDown(app.dispose);await mount(tester, app);@@ -51,9 +55,9 @@ void main() {await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump();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(box(tester).task, '');+ expect(box(tester).engine, 'codex');+ expect(box(tester).project.folder, '/work/openharness');expect(app.panes, hasLength(1));expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());@@ -168,12 +172,13 @@ void main() {) async {final app = createApp();seedMixedAgents(app);- app.machineStates['m']!.localOnly = false;+ app.machineStates['m']!.localOnly = true;app.gitProjectReaderForTest = (_, _) async => {'isGit': false};app.adoptSessionForTest(terminal('a0', []));addTearDown(app.dispose);await mount(tester, app);await chord(tester, LogicalKeyboardKey.keyN);+ app.machineStates['m']!.localOnly = false;await openLaunchRow(tester, 'project');final controller = box(tester);controller.move(@@ -216,11 +221,15 @@ void main() {await tester.pumpWidget(const SizedBox());});- testWidgets('different source panes retain separate setup drafts', (+ testWidgets('changing source panes never changes fresh launch defaults', (tester,) async {final app = createApp();seedMixedAgents(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');final first = app.adoptSessionForTest(terminal('a0', []));await app.addAgentToSwarm('m', 'a1');addTearDown(app.dispose);@@ -235,14 +244,14 @@ void main() {app.focusPane(other.id);await tester.pump();await chord(tester, LogicalKeyboardKey.keyN);- expect(box(tester).project.folder, isNot('/work/first-draft'));+ expect(box(tester).project.folder, '/work/openharness');box(tester).setFolder('/work/second-draft');await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump();app.focusPane(first.id);await tester.pump();await chord(tester, LogicalKeyboardKey.keyN);- expect(box(tester).project.folder, '/work/first-draft');+ expect(box(tester).project.folder, '/work/openharness');expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());});diff --git a/desktop/test/box_polish_test.dart b/desktop/test/box_polish_test.dartindex e931cef79..6bdb40849 100644--- a/desktop/test/box_polish_test.dart+++ b/desktop/test/box_polish_test.dart@@ -19,6 +19,10 @@ void main() {(tester) async {final app = createApp();seedMixedAgents(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');app.adoptSessionForTest(terminal('a0', []));addTearDown(app.dispose);await mount(tester, app);@@ -30,6 +34,7 @@ void main() {await tester.pump();final status = find.byKey(const ValueKey('new-harness-status'));expect(find.text('The selected folder is unavailable.'), findsOneWidget);+ expect(status.hitTestable(), findsOneWidget);final semantics = tester.widget<Semantics>(find.ancestor(of: status, matching: find.byType(Semantics)).first,);@@ -49,8 +54,6 @@ void main() {// Clearing the filter clears its warning. Check the field view too.box.warn('The selected folder is unavailable.');await tester.pump();- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pump();expect(status.hitTestable(), findsOneWidget);expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());diff --git a/desktop/test/command_dock_interaction_test.dart b/desktop/test/command_dock_interaction_test.dartindex 6b5704f4a..0c1ea7d68 100644--- a/desktop/test/command_dock_interaction_test.dart+++ b/desktop/test/command_dock_interaction_test.dart@@ -29,6 +29,10 @@ void main() {) async {final app = createApp();seedMixedAgents(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');final map = MemoryKeymap();addTearDown(app.dispose);addTearDown(map.dispose);@@ -136,7 +140,10 @@ void main() {expect(tester.widget<TextField>(input).cursorWidth, 2);expect(find.byKey(const ValueKey('swarm-search-prompt')), findsNothing);expect(find.text('Harness:'), findsNothing);- expect(find.text('[ New Harness ]'), findsNothing);+ expect(+ find.byKey(const ValueKey('new-harness-field-start')),+ findsNothing,+ );expect(find.text('Select Item'), findsNothing);expect(find.byKey(const ValueKey('swarm-search-hints')), findsNothing);final search = testerdiff --git a/desktop/test/harness_agent_selection_test.dart b/desktop/test/harness_agent_selection_test.dartindex be396b1b2..2387b1178 100644--- a/desktop/test/harness_agent_selection_test.dart+++ b/desktop/test/harness_agent_selection_test.dart@@ -676,7 +676,7 @@ void main() {('compact', const Size(600, 720)),]) {testWidgets(- '$layout form keeps Agent and Project visible and expands Advanced inline',+ '$layout form keeps Options collapsed and chooses a specialized agent inline',(tester) async {final renderDir = Platform.environment['HARNESS_LAUNCH_RENDER_DIR'];if (renderDir != null) await tester.runAsync(loadPreviewFonts);@@ -708,7 +708,7 @@ void main() {controller: box,onClose: () {},onCreated: () {},- onNeedsForm: () => fail('Advanced must stay inline'),+ onNeedsForm: () => fail('Settings must stay inline'),),),),@@ -728,7 +728,12 @@ void main() {);await tester.tap(find.byKey(const ValueKey('new-harness-field-agent')));await tester.pump();- expect(find.text('Browse Harness Store'), findsOneWidget);+ expect(+ box.options.any(+ (option) => option.id == NewHarnessController.storeId,+ ),+ isTrue,+ );if (renderDir != null) {await expectLater(find.byType(MaterialApp),@@ -742,8 +747,9 @@ void main() {await tester.pump();expect(find.text('Browse Harness Store'), findsNothing);expect(box.options.map((row) => row.id).toSet(), {'codex', 'claude'});- await openLaunchRow(tester, 'advanced');+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();+ await openLaunchRow(tester, 'advanced');expect(find.byKey(const ValueKey('new-harness-field-machine')),findsNothing,diff --git a/desktop/test/harness_picker_entry_test.dart b/desktop/test/harness_picker_entry_test.dartindex 8df097d8b..5218a3f1d 100644--- a/desktop/test/harness_picker_entry_test.dart+++ b/desktop/test/harness_picker_entry_test.dart@@ -54,6 +54,10 @@ void main() {addTearDown(tester.view.reset);final app = createApp();await seedPreviews(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');final frames = <TerminalBinaryFrame>[];app.adoptSessionForTest(terminal('a69', frames));final pane = app.focusedPane;diff --git a/desktop/test/harness_placement_test.dart b/desktop/test/harness_placement_test.dartindex 20ee5a2d2..2e4339f2d 100644--- a/desktop/test/harness_placement_test.dart+++ b/desktop/test/harness_placement_test.dart@@ -17,8 +17,9 @@ import 'package:harness/state/swarm_search.dart';import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/ws/ws_conn.dart';-import 'swarm_interactions_test.dart' show chord;-import 'swarm_screen_test.dart' show mount, terminal;+import 'swarm_interactions_test.dart' as interactions;+import 'swarm_screen_test.dart' show terminal;+import 'swarm_screen_test.dart' as workspace;import 'swarm_state_test.dart' show createApp;class _Connection extends WsConn {@@ -98,6 +99,30 @@ SwarmSearchController picker(AppNotifier app, HarnessPlacement placement) =>placement: placement,);+AppNotifier? fixtureApp;++Future<void> mount(WidgetTester tester, AppNotifier app) async {+ fixtureApp = app;+ addTearDown(() => fixtureApp = null);+ app.gitProjectReaderForTest ??= (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/project');+ await workspace.mount(tester, app);+}++// Cmd-N resolves this computer first. The remaining placement fixture uses+// the fake daemon, so it must not prepare real folders or open native terminals.+Future<void> chord(+ WidgetTester tester,+ LogicalKeyboardKey key, {+ bool shift = false,+}) async {+ final machine = fixtureApp?.machineStates['m'];+ if (key == LogicalKeyboardKey.keyN) machine?.localOnly = true;+ await interactions.chord(tester, key, shift: shift);+ if (key == LogicalKeyboardKey.keyN) machine?.localOnly = false;+}+void main() {for (final field in [NewHarnessField.agent, NewHarnessField.machine]) {test(@@ -105,6 +130,7 @@ void main() {() async {final connection = _Connection();final app = createApp(connectionForTest: (_) => connection);+ app.machineStates['m']!.nodeOnline = true;addTearDown(app.dispose);app.machineStates['remote'] = MachineState(const Machine(@@ -161,10 +187,10 @@ void main() {for (final (dismiss, profile) in [('escape', 'Work'),('outside', 'Default'),- ('advanced', 'Work'),+ ('chooser', 'Work'),]) {testWidgets(- 'inline advanced keeps the draft and $profile profile after $dismiss',+ 'setup with $profile profile handles $dismiss without starting',(tester) async {newHarnessOpensInBox = true;addTearDown(() => newHarnessOpensInBox = false);@@ -225,12 +251,11 @@ void main() {'https://github.com/acme/terminal-tools.git',);expect(find.byType(AlertDialog), findsNothing);- if (dismiss == 'advanced') {- await tester.tap(- find.byKey(const ValueKey('new-harness-field-advanced')),- );+ if (dismiss == 'chooser') {+ await openLaunchRow(tester, 'model');+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump();- expect(box.advancedOpen, isFalse);+ expect(harnessChoicesActive(tester), isFalse);} else {if (dismiss == 'escape') {await tester.sendKeyEvent(LogicalKeyboardKey.escape);@@ -243,6 +268,13 @@ void main() {box = tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller;+ expect(box.task, isEmpty);+ expect(box.mode, 'auto');+ expect(box.profileLabel, isNot('Work'));+ expect(box.project.repository, isNull);+ expect(connection.requests, isEmpty);+ await tester.pumpWidget(const SizedBox());+ return;}expect(box.task,@@ -356,108 +388,99 @@ void main() {),('/work/space project', 'space project', {'cwd': '/work/space project'}),]) {- testWidgets(- 'advanced options retain the task, read-only mode, and $projectQuery',- (tester) async {- newHarnessOpensInBox = true;- addTearDown(() => newHarnessOpensInBox = false);- final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);- addTearDown(app.dispose);- app.machineStates['m']!.nodeOnline = true;- app.adoptSessionForTest(terminal('a0', []));- final original = app.activeSwarm;- await mount(tester, app);- await chord(tester, LogicalKeyboardKey.keyT);- await chord(tester, LogicalKeyboardKey.keyN);- await tester.pump();- final input = find.byKey(const ValueKey('new-harness-query'));- tester- .widget<NewHarnessForm>(find.byType(NewHarnessForm))- .controller- .task =- 'Review the project before changing anything';- await tester.tap(- find.byKey(const ValueKey('new-harness-field-project')),- );- await tester.pump();- await tester.tap(- find.byKey(- ValueKey(- projectQuery.startsWith('/')- ? 'new-harness-option-${NewHarnessController.existingProjectId}'- : projectQuery.contains('/')- ? 'new-harness-option-${NewHarnessController.repositoryId}'- : 'new-harness-option-${NewHarnessController.newProjectId}',- ),- ),- );- await tester.pump();- await tester.sendKeyEvent(LogicalKeyboardKey.enter);- await tester.pump();- await tester.enterText(input, projectQuery);- await tester.pump(const Duration(milliseconds: 250));- await tester.sendKeyEvent(LogicalKeyboardKey.enter);- await tester.pump();- await openLaunchRow(tester, 'mode');- await tester.tap(- find.byKey(const ValueKey('new-harness-option-readOnly')),- );- await tester.pumpAndSettle();- final box = tester- .widget<NewHarnessForm>(find.byType(NewHarnessForm))- .controller;- expect(box.mode, 'readOnly');- await tester.tap(- find.byKey(const ValueKey('new-harness-field-advanced')),- );- await tester.pump();- expect(box.advancedOpen, isFalse);- await tester.tap(- find.byKey(const ValueKey('new-harness-field-advanced')),- );- await tester.pump();- expect(find.byType(AlertDialog), findsNothing);- expect(box.projectLabel, contains(detail));- expect(- find.descendant(- of: find.byKey(const ValueKey('new-harness-field-approvals')),- matching: find.text('Read only'),- ),- findsOneWidget,- );- expect(app.swarms, contains(original));- expect(app.swarms, hasLength(2));- await startHarness(tester);- await tester.pump();- final request = connection.requests.single;- for (final field in preparation.entries) {- expect(request.payload[field.key], field.value);- }- expect(request.payload['permissionMode'], 'readOnly');- expect(request.payload['bypassPermission'], false);- expect(- request.payload['prompt'],- 'Review the project before changing anything',- );- connection.created();- await tester.pump(const Duration(milliseconds: 100));- await tester.pump();- expect(app.swarms, hasLength(2));- expect(app.activeSwarm.name, 'Made');- await chord(tester, LogicalKeyboardKey.keyN);- expect(- tester+ testWidgets('settings retain the task, read-only mode, and $projectQuery', (+ tester,+ ) async {+ newHarnessOpensInBox = true;+ addTearDown(() => newHarnessOpensInBox = false);+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ addTearDown(app.dispose);+ app.machineStates['m']!.nodeOnline = true;+ app.adoptSessionForTest(terminal('a0', []));+ final original = app.activeSwarm;+ await mount(tester, app);+ await chord(tester, LogicalKeyboardKey.keyT);+ await chord(tester, LogicalKeyboardKey.keyN);+ await tester.pump();+ final input = find.byKey(const ValueKey('new-harness-query'));+ tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller- .task,- isEmpty,- reason: 'A task created through advanced options must not reappear as a draft',- );- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pumpWidget(const SizedBox());- },- );+ .task =+ 'Review the project before changing anything';+ await tester.tap(find.byKey(const ValueKey('new-harness-field-project')));+ await tester.pump();+ await tester.tap(+ find.byKey(+ ValueKey(+ projectQuery.startsWith('/')+ ? 'new-harness-option-${NewHarnessController.existingProjectId}'+ : projectQuery.contains('/')+ ? 'new-harness-option-${NewHarnessController.repositoryId}'+ : 'new-harness-option-${NewHarnessController.newProjectId}',+ ),+ ),+ );+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ await tester.enterText(input, projectQuery);+ await tester.pump(const Duration(milliseconds: 250));+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ await openLaunchRow(tester, 'mode');+ await tester.tap(+ find.byKey(const ValueKey('new-harness-option-readOnly')),+ );+ await tester.pumpAndSettle();+ final box = tester+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))+ .controller;+ expect(box.mode, 'readOnly');+ await openLaunchRow(tester, 'mode');+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(find.byType(AlertDialog), findsNothing);+ expect(box.projectLabel, contains(detail));+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('new-harness-field-approvals')),+ matching: find.text('Read only'),+ ),+ findsOneWidget,+ );+ expect(app.swarms, contains(original));+ expect(app.swarms, hasLength(2));+ await startHarness(tester);+ await tester.pump();+ final request = connection.requests.single;+ for (final field in preparation.entries) {+ expect(request.payload[field.key], field.value);+ }+ expect(request.payload['permissionMode'], 'readOnly');+ expect(request.payload['bypassPermission'], false);+ expect(+ request.payload['prompt'],+ 'Review the project before changing anything',+ );+ connection.created();+ await tester.pump(const Duration(milliseconds: 100));+ await tester.pump();+ expect(app.swarms, hasLength(2));+ expect(app.activeSwarm.name, 'Made');+ await chord(tester, LogicalKeyboardKey.keyN);+ expect(+ tester+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))+ .controller+ .task,+ isEmpty,+ reason: 'A completed task must not reappear as a draft',+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpWidget(const SizedBox());+ });}test('placement picker pins creation, searches only harnesses and focuses matches', () {@@ -876,7 +899,7 @@ void main() {for (final placement in HarnessPlacement.values) {testWidgets(- '${placement.title} keeps its tab on Escape and carries inherited creation context',+ '${placement.title} keeps its tab on Escape and uses the saved local creation context',(tester) async {newHarnessOpensInBox = true;addTearDown(() => newHarnessOpensInBox = false);@@ -949,7 +972,8 @@ void main() {expect(app.swarms, contains(original));// The creation box was opened from a search editor that is now gone.// Returning focus to that detached editor would disable shortcuts.- await chord(tester, LogicalKeyboardKey.keyP, shift: true);+ expect(find.byType(NewHarnessForm), findsNothing);+ await chord(tester, LogicalKeyboardKey.keyP);expect(find.byKey(const ValueKey('swarm-search-input')),findsOneWidget,@@ -1016,7 +1040,7 @@ void main() {expect(box.engine,'codex',- reason: 'The pane\'s agent, machine and folder carry over.',+ reason: 'The successful local defaults are used.',);expect(box.project.folder, '/work/project');expect(box.branchRef, 'refs/heads/main', reason: 'New work, from main.');diff --git a/desktop/test/harness_store_entry_test.dart b/desktop/test/harness_store_entry_test.dartindex 8e25ab38e..cd8baa340 100644--- a/desktop/test/harness_store_entry_test.dart+++ b/desktop/test/harness_store_entry_test.dart@@ -55,7 +55,7 @@ void main() {await openStore();expect(app.activeSwarm, same(store));expect(app.swarms, hasLength(2));- await key(tester, LogicalKeyboardKey.keyW, cmd: true, shift: true);+ await key(tester, LogicalKeyboardKey.keyW, cmd: true);expect(app.activeSwarm, same(work));expect(tester.state(view), same(terminalState));await key(tester, LogicalKeyboardKey.arrowLeft);@@ -150,12 +150,16 @@ void main() {);}- testWidgets('browsing from harness choices retains the task and defaults', (+ testWidgets('fresh creation after browsing uses successful launch defaults', (tester,) async {newHarnessOpensInBox = true;addTearDown(() => newHarnessOpensInBox = false);final app = createApp();+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/saved');final map = MemoryKeymap();addTearDown(app.dispose);addTearDown(map.dispose);@@ -187,10 +191,10 @@ void main() {final resumed = tester.widget<NewHarnessForm>(find.byType(NewHarnessForm)).controller;- expect(resumed.task, draft.task);+ expect(resumed.task, '');expect(resumed.engine, draft.engine);expect(resumed.machineId, draft.machineId);- expect(resumed.project, draft.project);+ expect(resumed.project.folder, '/work/saved');await key(tester, LogicalKeyboardKey.escape);expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());diff --git a/desktop/test/keymap_runtime_test.dart b/desktop/test/keymap_runtime_test.dartindex f401e22e4..8af7881f9 100644--- a/desktop/test/keymap_runtime_test.dart+++ b/desktop/test/keymap_runtime_test.dart@@ -110,6 +110,10 @@ void main() {final app = createApp();addTearDown(map.dispose);addTearDown(app.dispose);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');await mount(tester, app, map);await key(tester, LogicalKeyboardKey.keyN, cmd: true);final box = tester@@ -156,6 +160,10 @@ void main() {final app = createApp();addTearDown(map.dispose);addTearDown(app.dispose);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');await mount(tester, app, map, native: true);await key(tester, LogicalKeyboardKey.keyN, cmd: true);final form = find.byType(NewHarnessForm);diff --git a/desktop/test/new_harness_accessibility_test.dart b/desktop/test/new_harness_accessibility_test.dartindex 8e9d38cf1..6467ec6f5 100644--- a/desktop/test/new_harness_accessibility_test.dart+++ b/desktop/test/new_harness_accessibility_test.dart@@ -22,6 +22,10 @@ void main() {addTearDown(() => newHarnessOpensInBox = false);final app = createApp();seedMixedAgents(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');final map = MemoryKeymap();final input = <TerminalBinaryFrame>[];app.adoptSessionForTest(terminal('a0', input));@@ -45,6 +49,7 @@ void main() {);expect(input, isEmpty);// Pointer users can open the same choices and return to field navigation.+ await key(tester, LogicalKeyboardKey.escape);await tester.tap(find.byKey(const ValueKey('new-harness-field-agent')));await tester.pump();expect(harnessChoicesActive(tester), isTrue);@@ -56,6 +61,8 @@ void main() {expect(box.engine, 'claude');expect(harnessChoicesActive(tester), isFalse);await key(tester, LogicalKeyboardKey.arrowDown);+ expect(box.field, NewHarnessField.harness);+ await key(tester, LogicalKeyboardKey.arrowDown);expect(box.field, NewHarnessField.projectMenu);expect(input, isEmpty);semantics.dispose();diff --git a/desktop/test/new_harness_agent_settings_test.dart b/desktop/test/new_harness_agent_settings_test.dartindex 7c5c261fd..243f7df19 100644--- a/desktop/test/new_harness_agent_settings_test.dart+++ b/desktop/test/new_harness_agent_settings_test.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/codex_profiles.dart';import 'package:harness/core/engine_availability.dart';import 'package:harness/state/new_harness.dart';import 'package:harness/widgets/new_harness_form.dart';@@ -98,6 +99,62 @@ void main() {setUp(() => newHarnessOpensInBox = true);tearDown(() => newHarnessOpensInBox = false);+ test(+ 'a remembered agent missing from the catalog requires a replacement',+ () async {+ final connection = _Profiles('m');+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );+ addTearDown(app.dispose);+ await app.agentPreference.remember('claude', harnessId: 'retired/agent');+ final box = NewHarnessController(app, machineId: 'm', folder: '/work');+ addTearDown(box.dispose);+ await Future<void>.delayed(Duration.zero);+ expect(box.harnessId, 'retired/agent');+ expect(box.requiredChoice?.field, NewHarnessField.harness);+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, contains('Choose an agent'));+ expect(box.harnessId, 'retired/agent');+ expect(connection.creates, isEmpty);+ },+ );++ for (final unavailable in [false, true]) {+ test(+ 'an unverified or missing saved profile requires a choice (lookup failed=$unavailable)',+ () async {+ final connection = _Profiles('m')..failProfiles = unavailable;+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );+ addTearDown(app.dispose);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ draft: const NewHarnessDraft(+ machineId: 'm',+ engine: 'codex',+ project: NewHarnessProject.folder('/work'),+ task: '',+ permissionMode: 'full',+ profile: LocalCodexProfile('/profiles/m/removed', 'Removed'),+ profileChosen: true,+ ),+ );+ addTearDown(box.dispose);+ await Future<void>.delayed(Duration.zero);+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, contains('Choose a profile'));+ expect(box.field, NewHarnessField.profile);+ expect(box.draft.profile?.path, '/profiles/m/removed');+ expect(connection.creates, isEmpty);+ },+ );+ }+void setting(NewHarnessController box, String id) {if (id == NewHarnessController.permissionsId ||id == NewHarnessController.profileId) {@@ -113,6 +170,10 @@ void main() {final connection = _Profiles('m');final app = createApp(connectionForTest: (_) => connection);seedMixedAgents(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');addTearDown(app.dispose);final map = MemoryKeymap();addTearDown(map.dispose);diff --git a/desktop/test/new_harness_box_test.dart b/desktop/test/new_harness_box_test.dartindex b9b860fc9..f5a357c3f 100644--- a/desktop/test/new_harness_box_test.dart+++ b/desktop/test/new_harness_box_test.dart@@ -411,7 +411,10 @@ void main() {test('Return sends one create, with the project name when there is one', () async {final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -448,7 +451,10 @@ void main() {]) {test('a missing $engine goes directly to the daemon launch', () async {final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );addTearDown(app.dispose);app.machineStates['m']!.engines.replace([EngineAvailability(engine: engine, installed: false),@@ -476,7 +482,10 @@ void main() {test('a failed first launch shows the daemon error', () async {final connection = _Connection()..createFailure = 'Automatic installation failed.';- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );addTearDown(app.dispose);app.machineStates['m']!.engines.replace([const EngineAvailability(engine: 'amp', installed: false),@@ -500,7 +509,10 @@ void main() {'a lost reply is checked on, never answered with a second harness',() async {final connection = _Connection()..loseFirstReply = true;- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -516,10 +528,12 @@ void main() {expect(box.query, isEmpty);expect(box.returnCreates, isTrue);expect(await box.create(), NewHarnessOutcome.created);- expect(connection.calls.map((call) => call.type), [- 'agent_create',- 'agent_create_status',- ]);+ expect(+ connection.calls+ .map((call) => call.type)+ .where((type) => type.startsWith('agent_create')),+ ['agent_create', 'agent_create_status'],+ );},);@@ -531,6 +545,10 @@ void main() {final app = createApp();seedMixedAgents(app);app.adoptSessionForTest(terminal('a0', []));+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');await app.addAgentToSwarm('m', 'a0');await mount(tester, app);await chord(tester, LogicalKeyboardKey.keyN);@@ -553,7 +571,10 @@ void main() {test('a typed task is never dropped without being said, on any path', () async {final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -897,7 +918,7 @@ void main() {await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();expect(box.engine, 'claude');- expect(box.field, NewHarnessField.harness);+ expect(box.field, NewHarnessField.launch);expect(closed, 0);await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump();diff --git a/desktop/test/new_harness_controller_edges_test.dart b/desktop/test/new_harness_controller_edges_test.dartnew file mode 100644index 000000000..77da0ae69--- /dev/null+++ b/desktop/test/new_harness_controller_edges_test.dart@@ -0,0 +1,684 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/codex_profiles.dart';+import 'package:harness/core/first_task.dart';+import 'package:harness/core/git_worktree.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/project_folder.dart';+import 'package:harness/core/repository_clone.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/new_harness.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show createApp;++const _git = <String, dynamic>{+ 'isGit': true,+ 'branch': 'feature',+ 'branches': [+ {'ref': 'refs/heads/main', 'name': 'main'},+ {'ref': 'refs/heads/feature', 'name': 'feature'},+ {'ref': 'refs/heads/release', 'name': 'release'},+ {+ 'ref': 'refs/remotes/origin/feature',+ 'name': 'origin/feature',+ 'remote': true,+ },+ {+ 'ref': 'refs/remotes/origin/release',+ 'name': 'origin/release',+ 'remote': true,+ },+ ],+};++typedef _Reply = FutureOr<Map<String, dynamic>> Function(Map<String, dynamic>);++class _Connection extends WsConn {+ _Connection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ final calls = <(String, Map<String, dynamic>)>[];+ final replies = <String, _Reply>{};+ Map<String, dynamic> git = {'isGit': false};+ List<Map<String, dynamic>> catalog = [+ {+ 'id': 'autonomous/blender',+ 'name': 'Blender',+ 'engine': 'claude',+ 'engines': ['codex', 'claude'],+ 'installed': true,+ },+ ];++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ calls.add((type, Map.of(payload)));+ if (replies[type] case final reply?) return reply(payload);+ return switch (type) {+ 'git_project_info' => {...git, 'refreshed': true},+ 'engines_probe' => {+ 'engines': [+ {'engine': 'codex', 'installed': true, 'supportsCodexHome': true},+ {'engine': 'claude', 'installed': true},+ ],+ },+ 'dsh_list' => {'dsh': catalog},+ 'fs_list_dir' => {'path': payload['path'] ?? '/home/test', 'entries': []},+ 'codex_profiles_list' => {+ 'profiles': [+ {'path': '/profiles/work', 'label': 'Work'},+ ],+ },+ 'agent_create' || 'agent_create_status' => {+ 'creationId': payload['creationId'],+ 'state': 'created',+ 'agent': {'id': 'created', 'name': 'Created', 'engine': 'codex'},+ },+ _ => {},+ };+ }++ Iterable<Map<String, dynamic>> requests(String type) =>+ calls.where((call) => call.$1 == type).map((call) => call.$2);+}++class _Fixture {+ _Fixture() {+ app = createApp(connectionForTest: (_) => connection, connected: true);+ app.machineStates['m']!.agents = [];+ addTearDown(app.dispose);+ }+ final connection = _Connection();+ late final AppNotifier app;+ NewHarnessController box({+ String engine = 'codex',+ String? harnessId,+ String? folder = '/work/repo',+ String? projectName,+ bool autoProject = false,+ NewHarnessDraft? draft,+ }) {+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: engine,+ harnessId: harnessId,+ folder: folder,+ projectName: projectName,+ autoProject: autoProject,+ draft: draft,+ offersStore: true,+ now: () => DateTime(2026, 9, 25, 9, 10, 11),+ );+ addTearDown(box.dispose);+ return box;+ }+}++NewHarnessDraft _draft(+ NewHarnessProject project, {+ String engine = 'codex',+ bool? worktree,+ String? branchRef,+ String? branchName,+ GitProjectInfo? gitProject,+ LocalCodexProfile? profile,+}) => NewHarnessDraft(+ machineId: 'm',+ engine: engine,+ project: project,+ task: '',+ permissionMode: 'full',+ worktree: worktree,+ branchRef: branchRef,+ branchName: branchName,+ gitProject: gitProject,+ profile: profile,+);++Future<void> _settle() => Future<void>.delayed(Duration.zero);++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ test(+ 'profile support is unknown until the selected machine answers',+ () async {+ final fixture = _Fixture();+ final box = fixture.box();+ expect(box.profileHelp, 'Checking Codex profile support on Test host…');+ expect(box.supportsProfiles, isFalse);+ await _settle();+ expect(box.profileHelp, isNull);+ expect(box.supportsProfiles, isTrue);+ },+ );++ test(+ 'project identity preserves generated intent in sets and draft requests',+ () {+ final generated = ProjectFolderRequest.generated(+ label: 'Codex',+ at: DateTime(2026),+ );+ final projects = [+ const NewHarnessProject.fresh('name'),+ const NewHarnessProject.folder('/work'),+ NewHarnessProject.clone(GitHubRepository.parse('openai/codex')!),+ NewHarnessProject.generated(generated),+ ];+ expect(projects.map((project) => project.isNew), [+ true,+ false,+ true,+ true,+ ]);+ expect({...projects, ...projects}, hasLength(4));+ expect(NewHarnessProject.generated(generated), projects.last);+ expect(+ NewHarnessProject.generated(generated).hashCode,+ projects.last.hashCode,+ );+ expect(+ projects.last,+ isNot(const NewHarnessProject.fresh('codex-2026-01-01-00-00')),+ );+ expect(_draft(projects.first).projectFolderRequest!.name, 'name');+ expect(_draft(projects[1]).projectFolderRequest, isNull);+ expect(+ _draft(projects[2]).projectFolderRequest!.repository!.url,+ 'https://github.com/openai/codex.git',+ );+ expect(_draft(projects.last).projectFolderRequest, same(generated));+ expect(+ _draft(projects.first, engine: 'terminal').projectFolderRequest,+ isNull,+ );+ final pending = _draft(+ projects[1],+ worktree: true,+ branchRef: 'refs/heads/main',+ ).projectFolderRequest!;+ expect(pending.createsWorktree, isTrue);+ expect(pending.branchRef, 'refs/heads/main');+ final branch = _draft(+ projects[1],+ worktree: false,+ branchRef: 'refs/heads/release',+ ).projectFolderRequest!;+ expect(branch.createsWorktree, isFalse);+ expect(branch.branchRef, 'refs/heads/release');+ },+ );++ test(+ 'worktree plans distinguish current, existing and remote tracking branches',+ () {+ final info = GitProjectInfo.fromJson(_git);+ WorktreePlan plan(String? base, [String? name]) => planWorktree(+ info,+ base: base,+ name: name,+ placeholder: 'brave-otter',+ );+ expect(+ plan('refs/heads/main', 'feature').kind,+ WorktreeStart.unavailable,+ );+ expect(plan('refs/heads/feature').branch, 'brave-otter');+ expect(plan('refs/remotes/origin/feature').branch, 'brave-otter');+ expect(+ plan('refs/remotes/origin/release').kind,+ WorktreeStart.existingBranch,+ );+ expect(plan('refs/heads/missing').branch, 'brave-otter');+ expect(+ plan('refs/heads/main', 'release').kind,+ WorktreeStart.existingBranch,+ );+ final fresh = plan('refs/remotes/upstream/new');+ expect(fresh.branch, 'new');+ expect(fresh.tracks, isTrue);+ },+ );++ test(+ 'explicit runner and empty named drafts retain their intended launch',+ () async {+ final fixture = _Fixture();+ final runner = fixture.box(+ harnessId: 'autonomous/blender',+ engine: 'codex',+ );+ await _settle();+ expect(runner.launchAgentLabel, 'Blender · Codex');+ final named = fixture.box(+ projectName: 'my-project',+ draft: _draft(const NewHarnessProject.fresh()),+ );+ expect(named.project.name, 'my-project');+ final generated = fixture.box(+ autoProject: true,+ draft: _draft(const NewHarnessProject.fresh()),+ );+ expect(generated.project.generated, isNotNull);+ final missing = fixture.box(folder: null);+ expect(missing.projectLocation, 'Choose a project on Test host');+ expect(missing.requiredChoice!.field, NewHarnessField.projectMenu);+ },+ );++ test(+ 'main stays unavailable and a delayed Git read revalidates before creating',+ () async {+ final fixture = _Fixture();+ final pending = Completer<Map<String, dynamic>>();+ fixture.connection.replies['git_project_info'] = (_) => pending.future;+ final box = fixture.box();+ final creating = box.create();+ expect(box.busy, isTrue);+ pending.complete({+ 'isGit': true,+ 'branch': 'trunk',+ 'branches': [+ {'ref': 'refs/heads/trunk', 'name': 'trunk'},+ ],+ 'refreshed': true,+ });+ expect(await creating, NewHarnessOutcome.failed);+ expect(box.branchLabel, 'main · unavailable');+ expect(box.worktree, isTrue);+ expect(box.field, NewHarnessField.branch);+ expect(box.error, contains('Choose a branch'));+ expect(fixture.connection.requests('agent_create'), isEmpty);+ },+ );++ test('early branch focus refreshes after discovery and replaces a colliding placeholder', () async {+ final fixture = _Fixture();+ final pending = Completer<Map<String, dynamic>>();+ fixture.connection.replies['git_project_info'] = (payload) =>+ payload['refresh'] == true+ ? {..._git, 'refreshed': true}+ : pending.future;+ final box = fixture.box(+ draft: _draft(+ const NewHarnessProject.folder('/work/repo'),+ gitProject: GitProjectInfo.fromJson(_git),+ ),+ );+ final placeholder = box.placeholder;+ box.focusField(NewHarnessField.branch);+ pending.complete({+ ..._git,+ 'branches': [+ ..._git['branches'] as List,+ {'ref': 'refs/heads/$placeholder', 'name': placeholder},+ ],+ });+ await _settle();+ expect(box.placeholder, isNot(placeholder));+ expect(+ fixture.connection+ .requests('git_project_info')+ .where((request) => request['refresh'] == true),+ isNotEmpty,+ );+ });++ test(+ 'typing the current checkout branch cannot create a second worktree',+ () async {+ final fixture = _Fixture();+ fixture.connection.git = _git;+ final box = fixture.box(+ draft: _draft(+ const NewHarnessProject.folder('/work/repo'),+ gitProject: GitProjectInfo.fromJson(_git),+ worktree: true,+ branchName: 'feature',+ ),+ );+ await _settle();+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, contains('project folder’s branch'));+ expect(box.worktree, isTrue);+ expect(fixture.connection.requests('agent_create'), isEmpty);+ },+ );++ test('agent preview navigation never commits a runner and settings retain its provider', () async {+ final fixture = _Fixture();+ final box = fixture.box(harnessId: 'autonomous/blender');+ await _settle();+ expect(+ box.agentSettingsFor('autonomous/blender').first.detail,+ 'Auto-approve',+ );+ expect(+ box.agentSettingsFor('unknown/tool').first.id,+ NewHarnessController.permissionsId,+ );+ box.focusField(NewHarnessField.agent);+ box.move(1);+ expect(box.engine, 'codex');+ final next = box.selected!.id;+ box.page(-1, 1);+ expect(box.engine, 'codex');+ expect(box.selected!.id, isNot(next));+ box.focusField(NewHarnessField.machine);+ box.nextField();+ expect(box.field, NewHarnessField.projectMenu);+ });++ test(+ 'carried task validates length while editing and ignores value rows',+ () async {+ final fixture = _Fixture();+ final box = fixture.box();+ box.focusField(NewHarnessField.task);+ final oversized = 'x' * (kFirstTaskMaxLength + 1);+ box.setQuery(oversized);+ expect(box.task, oversized);+ expect(box.error, contains('this is ${oversized.length}'));+ const irrelevant = NewHarnessOption(id: 'claude', title: 'Claude');+ box.applyOption(irrelevant);+ expect(box.engine, 'codex');+ box.setQuery('Keep this');+ expect(box.error, isNull);+ box.focusField(NewHarnessField.launch);+ box.applyOption(irrelevant);+ expect(box.task, 'Keep this');+ expect(box.engine, 'codex');+ },+ );++ for (final field in [+ NewHarnessField.projectName,+ NewHarnessField.projectRepository,+ ]) {+ test(+ 'a stale $field value cannot move a project to another machine',+ () async {+ final fixture = _Fixture();+ final box = fixture.box();+ box.focusField(field);+ box.applyOption(+ const NewHarnessOption(+ id: 'old',+ title: 'Old machine project',+ machineId: 'removed',+ project: NewHarnessProject.fresh('wrong-machine'),+ ),+ );+ expect(box.project.folder, '/work/repo');+ expect(box.error, contains('machine has changed'));+ },+ );+ }++ test(+ 'controller doors preserve the project until a value is accepted',+ () async {+ final fixture = _Fixture();+ final box = fixture.box();+ await _settle();+ for (final (id, field) in [+ (NewHarnessController.permissionsId, NewHarnessField.mode),+ (NewHarnessController.profileId, NewHarnessField.profile),+ (NewHarnessController.changeMachineId, NewHarnessField.machine),+ (NewHarnessController.repositoryId, NewHarnessField.projectRepository),+ ]) {+ box.focusField(NewHarnessField.harness);+ box.accept(NewHarnessOption(id: id, title: 'Choose'));+ expect(box.field, field);+ expect(box.project.folder, '/work/repo');+ }+ expect(fixture.connection.requests('agent_create'), isEmpty);+ },+ );++ testWidgets(+ 'missing path matches explain the empty folder without launching',+ (tester) async {+ final fixture = _Fixture();+ final box = fixture.box();+ box.focusField(NewHarnessField.project);+ box.setQuery('/no-match');+ await tester.pump(const Duration(milliseconds: 100));+ // Browse and Change Machine remain available, but neither is a path match.+ box.cursor = -1;+ box.accept();+ expect(box.error, contains('No folder matches'));+ expect(box.project.folder, '/work/repo');+ expect(fixture.connection.requests('agent_create'), isEmpty);+ },+ );++ test(+ 'legacy quick start refuses browsing, Store and disabled choices',+ () async {+ final fixture = _Fixture();+ final box = fixture.box();+ await _settle();+ box.focusField(NewHarnessField.project);+ expect(await box.createNow(), NewHarnessOutcome.failed);+ expect(box.error, 'Choose a folder to continue.');+ box.focusField(NewHarnessField.harness);+ box.cursor = box.options.indexWhere(+ (row) => row.id == NewHarnessController.storeId,+ );+ expect(await box.createNow(), NewHarnessOutcome.failed);+ expect(box.error, contains('Store first'));+ box.focusField(NewHarnessField.projectName);+ box.setQuery('!!!');+ expect(box.selected!.enabled, isFalse);+ expect(await box.createNow(), NewHarnessOutcome.failed);+ expect(box.error, contains('Use a project name'));+ expect(fixture.connection.requests('agent_create'), isEmpty);+ },+ );++ test('generated projects avoid existing remote folder names without creating folders', () async {+ final fixture = _Fixture();+ fixture.connection.replies['fs_list_dir'] = (payload) => {+ 'path': payload['path'] ?? '/home/test',+ 'entries': [+ if (payload['path'] == '/home/test/harnesses') ...[+ {'name': 'codex-2026-09-25-09-10', 'isDir': true},+ {'name': 'codex-2026-09-25-09-10-11', 'isDir': true},+ ],+ ],+ };+ final box = fixture.box(folder: null, autoProject: true);+ await _settle();+ expect(box.project.name, 'codex-2026-09-25-09-10-11-2');+ expect(box.project.generated!.isGenerated, isTrue);+ expect(+ fixture.connection.calls.every((call) => call.$1 != 'fs_mkdir'),+ isTrue,+ );+ expect(fixture.connection.requests('agent_create'), isEmpty);+ });++ test('profile discovery includes observed agent paths and link failures preserve selection', () async {+ final fixture = _Fixture();+ fixture.app.machineStates['m']!.agents = [+ const Agent(+ id: 'existing',+ name: 'Existing',+ engine: 'codex',+ codexHome: '/profiles/seen',+ ),+ ];+ fixture.connection.replies['codex_profile_link'] = (_) => {+ 'error': 'MISSING',+ };+ final box = fixture.box();+ await _settle();+ box.focusField(NewHarnessField.profile);+ await _settle();+ expect(+ fixture.connection+ .requests('codex_profiles_list')+ .single['observedPaths'],+ contains('/profiles/seen'),+ );+ await box.linkProfile('/profiles/bad');+ expect(box.linkingProfile, isFalse);+ expect(box.error, contains('Try another folder'));+ expect(box.draft.profile, isNull);+ expect(box.field, NewHarnessField.profile);+ expect(fixture.connection.requests('agent_create'), isEmpty);+ });++ test(+ 'launch waits for an explicit profile check already in progress',+ () async {+ final fixture = _Fixture();+ final pending = Completer<Map<String, dynamic>>();+ fixture.connection.replies['codex_profiles_list'] = (_) => pending.future;+ final box = fixture.box(+ draft: _draft(+ const NewHarnessProject.folder('/work/repo'),+ profile: const LocalCodexProfile('/profiles/work', 'Work'),+ ),+ );+ await _settle();+ box.focusField(NewHarnessField.profile);+ expect(box.loadingProfiles, isTrue);+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, contains('still loading'));+ expect(fixture.connection.requests('agent_create'), isEmpty);+ pending.complete({+ 'profiles': [+ {'path': '/profiles/work', 'label': 'Work'},+ ],+ });+ await _settle();+ expect(box.loadingProfiles, isFalse);+ expect(await box.create(), NewHarnessOutcome.created);+ expect(+ fixture.connection.requests('agent_create').single['codexHome'],+ '/profiles/work',+ );+ },+ );++ testWidgets(+ 'relative paths use the committed project and old listings are evicted',+ (tester) async {+ final fixture = _Fixture();+ final box = fixture.box();+ box.focusField(NewHarnessField.project);+ for (final path in ['./child/', '../sibling/']) {+ box.setQuery(path);+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(+ fixture.connection.requests('fs_list_dir').map((call) => call['path']),+ containsAll(['/work/repo/child', '/work/sibling']),+ );+ for (var i = 0; i < 18; i++) {+ box.setQuery('/folder$i/');+ await tester.pump(const Duration(milliseconds: 100));+ }+ box.setQuery('/folder0/');+ expect(box.listing, isTrue);+ await tester.pump(const Duration(milliseconds: 100));+ expect(+ fixture.connection+ .requests('fs_list_dir')+ .where((call) => call['path'] == '/folder0'),+ hasLength(2),+ );+ expect(box.listing, isFalse);+ },+ );++ testWidgets('unresolved remote home keeps relative completion safe', (+ tester,+ ) async {+ final fixture = _Fixture();+ final home = Completer<Map<String, dynamic>>();+ fixture.connection.replies['fs_list_dir'] = (_) => home.future;+ final box = fixture.box(folder: null);+ box.focusField(NewHarnessField.project);+ box.setQuery('~/');+ expect(box.options.map((row) => row.id), [+ NewHarnessController.browseId,+ NewHarnessController.changeMachineId,+ ]);+ expect(box.total, 0);+ home.complete({'error': 'UNAVAILABLE'});+ await tester.pump(const Duration(milliseconds: 200));+ expect(box.needsProject, isTrue);+ expect(fixture.connection.requests('agent_create'), isEmpty);+ });++ test(+ 'a lost creation reply cannot launch again when its machine disappears',+ () async {+ final fixture = _Fixture();+ fixture.connection.replies['agent_create'] = (_) =>+ throw const WsRequestTimeout('agent_create');+ final box = fixture.box();+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.checking, isTrue);+ fixture.app.machineStates.remove('m');+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, 'Choose a machine.');+ expect(box.checking, isTrue);+ expect(fixture.connection.requests('agent_create'), hasLength(1));+ },+ );++ test(+ 'late remembered agent loading leaves an unsupported task editor safely',+ () async {+ final fixture = _Fixture();+ final box = NewHarnessController(+ fixture.app,+ machineId: 'm',+ folder: '/work/repo',+ );+ addTearDown(box.dispose);+ box.focusField(NewHarnessField.task);+ box.setQuery('Keep this task');+ await fixture.app.agentPreference.select('terminal');+ await _settle();+ expect(box.engine, 'terminal');+ expect(box.field, NewHarnessField.harness);+ expect(box.query, isEmpty);+ expect(box.task, 'Keep this task');+ },+ );++ test('a harness removed during the launch probe requires an explicit replacement', () async {+ final fixture = _Fixture();+ final box = fixture.box(harnessId: 'autonomous/blender');+ await _settle();+ expect(box.requiredChoice, isNull);+ fixture.connection.catalog = [];+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.harnessId, 'autonomous/blender');+ expect(box.error, contains('Choose an agent'));+ expect(box.field, NewHarnessField.harness);+ expect(box.busy, isFalse);+ expect(fixture.connection.requests('agent_create'), isEmpty);+ });+}diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dartindex 830f28374..d1971f3e5 100644--- a/desktop/test/new_harness_entry_rules_test.dart+++ b/desktop/test/new_harness_entry_rules_test.dart@@ -106,23 +106,27 @@ void main() {setUp(() {newHarnessOpensInBox = true;+ });+ tearDown(() {+ map.dispose();+ app.dispose();+ newHarnessOpensInBox = false;+ });++ Future<void> mount(WidgetTester tester, {bool store = true}) async {connections = {for (final id in ['m', 'studio', 'build']) id: _Connection(id),};app = createApp(connectionForTest: (id) => connections[id]!);seedMixedAgents(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};for (final machine in app.machineStates.values) {machine.dsh.replace(_products.map((json) => DshEntry.fromJson(json)!));}map = MemoryKeymap();- });- tearDown(() {- map.dispose();- app.dispose();- newHarnessOpensInBox = false;- });-- Future<void> mount(WidgetTester tester, {bool store = true}) async {+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');app.adoptSessionForTest(terminal('a0', []));if (store) app.openStore();await configured.mount(tester, app, map);@@ -198,7 +202,13 @@ void main() {findsNothing,);}- expect(find.text('[ New Harness ]'), findsOneWidget);+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('new-harness-field-start')),+ matching: find.text('New Harness'),+ ),+ findsOneWidget,+ );expect(connections['m']!.starts, isEmpty);await acceptSetupOrSearch(tester);expect(connections['m']!.starts, hasLength(1));@@ -393,6 +403,8 @@ void main() {'an in-flight or uncertain Store start cannot be replaced or retried as a new task',(tester) async {await mount(tester);+ // This receipt test leaves folder preparation to the fake remote CLI.+ app.machineStates['m']!.localOnly = false;await product(tester, 'autonomous/workshop', task: 'Original task');final original = box(tester);final starting = original.create();@@ -506,7 +518,7 @@ void main() {});testWidgets(- 'Cmd-N keeps drafts separate when the focused source pane changes',+ 'Cmd-N uses local saved defaults regardless of the focused pane',(tester) async {await mount(tester, store: false);final first = app.focusedPane!;@@ -521,16 +533,18 @@ void main() {app.focusPane(other.id);await tester.pump();await key(tester, shortcut, cmd: true);- expect(box(tester).harnessId, 'autonomous/typst');- expect(box(tester).project.folder, '/work/release-notes');+ expect(box(tester).harnessId, isNull);+ expect(box(tester).engine, 'codex');+ expect(box(tester).machineId, 'm');+ expect(box(tester).project.folder, '/work/openharness');expect(box(tester).task, isEmpty);await dismiss(tester);app.focusPane(first.id);await tester.pump();await key(tester, shortcut, cmd: true);expect(box(tester).engine, 'codex');- expect(box(tester).project.name, 'keyboard-review');- expect(box(tester).task, 'Review this project');+ expect(box(tester).project.folder, '/work/openharness');+ expect(box(tester).task, isEmpty);expect(connections.values.expand((c) => c.starts), isEmpty);await dismiss(tester);await tester.pumpWidget(const SizedBox());@@ -538,49 +552,50 @@ void main() {},);- testWidgets('Cmd-N inherits its source and resumes edits after finding', (- tester,- ) async {- await mount(tester, store: false);- final origin = app.activeSwarm;- final shortcut = LogicalKeyboardKey.keyN;- await key(tester, shortcut, cmd: true);- 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.task = 'Check keyboard focus';- await nameProject(tester, 'keyboard-review');- await dismiss(tester);- expect(app.swarms, [origin]);- expect(app.activeSwarm, same(origin));- await openHarnessPicker(tester);- await acceptSetupOrSearch(tester);- expect(find.byType(NewHarnessForm), findsNothing);- expect(connections.values.expand((c) => c.starts), isEmpty);- await key(tester, LogicalKeyboardKey.keyN, cmd: true);- draft = box(tester);- expect(draft.task, 'Check keyboard focus');- expect(draft.project.name, 'keyboard-review');- expect(draft.placement, HarnessPlacement.currentTab);- await acceptSetupOrSearch(tester);- final connection = connections['m']!;- expect(connection.starts, hasLength(1));- expect(connection.starts.single['engine'], 'codex');- expect(connection.starts.single['projectName'], 'keyboard-review');- expect(connection.starts.single['prompt'], 'Check keyboard focus');- expect(connection.starts.single['dsh'], isNull);- connection.created();- await tester.pump();- await tester.pump(const Duration(milliseconds: 200));- expect(find.byType(NewHarnessForm), findsNothing);- expect(app.swarms.length, 1);- expect(app.activeSwarm.panes.last.agentId, 'created-1');- expect(app.focusedPane?.agentId, 'created-1');- await tester.pumpWidget(const SizedBox());- });+ testWidgets(+ 'fresh Cmd-N keeps successful defaults and discards canceled edits',+ (tester) async {+ await mount(tester, store: false);+ final origin = app.activeSwarm;+ final shortcut = LogicalKeyboardKey.keyN;+ await key(tester, shortcut, cmd: true);+ 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.task = 'Check keyboard focus';+ await nameProject(tester, 'keyboard-review');+ await dismiss(tester);+ expect(app.swarms, [origin]);+ expect(app.activeSwarm, same(origin));+ await openHarnessPicker(tester);+ await acceptSetupOrSearch(tester);+ expect(find.byType(NewHarnessForm), findsNothing);+ expect(connections.values.expand((c) => c.starts), isEmpty);+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);+ draft = box(tester);+ expect(draft.task, isEmpty);+ expect(draft.project.folder, '/work/openharness');+ expect(draft.placement, HarnessPlacement.currentTab);+ await acceptSetupOrSearch(tester);+ final connection = connections['m']!;+ expect(connection.starts, hasLength(1));+ expect(connection.starts.single['engine'], 'codex');+ expect(connection.starts.single['cwd'], '/work/openharness');+ expect(connection.starts.single['prompt'], isNull);+ expect(connection.starts.single['dsh'], isNull);+ connection.created();+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.byType(NewHarnessForm), findsNothing);+ expect(app.swarms.length, 1);+ expect(app.activeSwarm.panes.last.agentId, 'created-1');+ expect(app.focusedPane?.agentId, 'created-1');+ await tester.pumpWidget(const SizedBox());+ },+ );testWidgets('switching the picker keeps its project scope and Escape goes back',diff --git a/desktop/test/new_harness_form_test.dart b/desktop/test/new_harness_form_test.dartindex c6542ddf1..bd98123ae 100644--- a/desktop/test/new_harness_form_test.dart+++ b/desktop/test/new_harness_form_test.dart@@ -109,42 +109,61 @@ void main() {await tester.pumpAndSettle();}- testWidgets('core fields stay visible and advanced fields expand', (+ testWidgets('Agent and Project stay compact until Options is opened', (tester,) async {- await mount(tester);- for (final label in ['Agent', 'Project', 'Options']) {- expect(find.text(label), findsOneWidget);+ await mount(tester, engine: 'codex');+ for (final field in ['agent', 'project', 'advanced']) {+ expect(find.byKey(ValueKey('new-harness-field-$field')), findsOneWidget);}- expect(- find.byKey(const ValueKey('new-harness-field-worktree')),- findsNothing,- );+ for (final field in [+ 'model',+ 'approvals',+ 'profile',+ 'branch',+ 'worktree',+ ]) {+ expect(find.byKey(ValueKey('new-harness-field-$field')), findsNothing);+ }+ expect(find.byKey(const ValueKey('new-harness-summary')), findsNothing);await openLaunchRow(tester, 'advanced');- for (final label in ['worktree', 'approvals', 'model', 'branch']) {- expect(find.byKey(ValueKey('new-harness-field-$label')), findsOneWidget);+ for (final field in [+ 'model',+ 'approvals',+ 'profile',+ 'branch',+ 'worktree',+ ]) {+ expect(find.byKey(ValueKey('new-harness-field-$field')), findsOneWidget);}+ await press(tester, LogicalKeyboardKey.enter);+ expect(find.byKey(const ValueKey('new-harness-field-model')), findsNothing);});- testWidgets('down and up walk the core rows and wrap', (tester) async {- final box = await mount(tester, focus: 'agent');- expect(box.field, NewHarnessField.harness);- await press(tester, LogicalKeyboardKey.arrowDown);- expect(box.field, NewHarnessField.projectMenu);- await press(tester, LogicalKeyboardKey.arrowDown);- expect(- tester- .widget<Semantics>(- find.byKey(const ValueKey('new-harness-field-advanced')),- )- .properties- .selected,- isTrue,- );- await press(tester, LogicalKeyboardKey.arrowDown);- expect(box.field, NewHarnessField.launch);- await press(tester, LogicalKeyboardKey.arrowDown);- expect(box.field, NewHarnessField.harness);+ testWidgets('down and up walk the fixed rows and wrap', (tester) async {+ final box = await mount(tester, engine: 'codex', focus: 'agent');+ await openLaunchRow(tester, 'advanced');+ await focusLaunchRow(tester, 'agent');+ for (final name in [+ 'project',+ 'advanced',+ 'model',+ 'approvals',+ 'profile',+ 'branch',+ 'worktree',+ 'start',+ 'agent',+ ]) {+ await press(tester, LogicalKeyboardKey.arrowDown);+ expect(+ tester+ .widget<Semantics>(find.byKey(ValueKey('new-harness-field-$name')))+ .properties+ .selected,+ isTrue,+ );+ }await press(tester, LogicalKeyboardKey.arrowUp);expect(box.field, NewHarnessField.launch);});@@ -217,9 +236,9 @@ void main() {expect(harnessChoicesActive(tester), isFalse);expect(box.engine, engine, reason: 'Leaving is not choosing either.');expect(- find.byKey(const ValueKey('new-harness-summary')),+ find.byKey(const ValueKey('new-harness-field-agent')),findsOneWidget,- reason: 'Leaving choices restores the launch summary.',+ reason: 'Leaving choices restores the form.',);await press(tester, LogicalKeyboardKey.arrowDown);// Model sits between Agent and Machine on this form.@@ -316,7 +335,7 @@ void main() {expect(box.matchCount, greaterThan(0));});- testWidgets('backspace deletes and escape clears before it closes', (+ testWidgets('backspace edits and Escape returns to the form in one step', (tester,) async {var closed = false;@@ -348,9 +367,8 @@ void main() {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(box.query, isEmpty);+ expect(harnessChoicesActive(tester), isFalse);expect(closed, isFalse);await press(tester, LogicalKeyboardKey.escape);expect(closed, isTrue, reason: 'Escape backs out before dismissing.');@@ -392,8 +410,10 @@ void main() {final box = await mount(tester);await type(tester, 'harness');expect(- tester.getTopLeft(find.text('New Folder')).dy,- lessThan(tester.getTopLeft(find.text('M2:harness-monitor')).dy),+ box.options.indexWhere(+ (option) => option.id == NewHarnessController.newProjectId,+ ),+ lessThan(box.options.indexWhere((option) => option.project != null)),reason: 'The three doors sit above the recents, not under them.',);expect(@@ -424,23 +444,6 @@ void main() {);});- 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 Folder')).dy,- lessThan(tester.getTopLeft(find.text('M2: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');@@ -528,7 +531,7 @@ void main() {testWidgets('Return replaces the summary with choices', (tester) async {final box = await mount(tester);- expect(find.text('[ New Harness ]'), findsOneWidget);+ expect(find.text('New Harness'), findsOneWidget);expect(find.text('Open Folder'),findsNothing,@@ -592,17 +595,19 @@ void main() {expect(harnessChoicesActive(tester), isFalse);});- testWidgets('the summary returns when editing ends', (tester) async {+ testWidgets('choices replace the form and Escape restores it', (+ tester,+ ) async {await mount(tester);- final summary = find.byKey(const ValueKey('new-harness-summary'));- expect(summary, findsOneWidget);+ final form = find.byKey(const ValueKey('new-harness-field-project'));+ expect(form, findsOneWidget);await press(tester, LogicalKeyboardKey.enter);- expect(summary, findsNothing);+ expect(form, findsNothing);await press(tester, LogicalKeyboardKey.escape);- expect(summary, findsOneWidget);+ expect(form, findsOneWidget);});- testWidgets('the right column follows the focused row', (tester) async {+ testWidgets('the choices follow the focused row', (tester) async {await mount(tester);expect(find.text('Open Folder'), findsNothing);await openLaunchRow(tester, 'agent');@@ -618,7 +623,7 @@ void main() {tester,) async {await mount(tester);- expect(find.text('[ New Harness ]'), findsOneWidget);+ expect(find.text('New Harness'), findsOneWidget);expect(tester.widget<Semantics>(@@ -659,18 +664,25 @@ void main() {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('M2:harness-monitor'), findsWidgets);- expect(- tester.getRect(field),- before,- reason: 'Filtering changes choices without moving the field.',- );- });+ testWidgets(+ 'a narrow chooser keeps the column and restores the compact form',+ (tester) async {+ await mount(tester);+ final field = find.byKey(const ValueKey('new-harness-surface'));+ final before = tester.getRect(field);+ await type(tester, 'harness');+ expect(find.byKey(const ValueKey('new-harness-choices')), findsOneWidget);+ expect(+ tester.getRect(field).topLeft,+ before.topLeft,+ reason: 'The chooser keeps the same column and has room for its list.',+ );+ expect(tester.getRect(field).width, before.width);+ expect(tester.getRect(field).height, greaterThan(before.height));+ await press(tester, LogicalKeyboardKey.escape);+ expect(tester.getRect(field), before);+ },+ );/// Walk the highlight in the open list until [wanted] holds, so a test/// asserts on the row it meant rather than on a position.@@ -795,17 +807,17 @@ void main() {);});- testWidgets('the worktree row reads as a question', (tester) async {+ testWidgets('the worktree row uses a terminal checkbox', (tester) async {final box = await mount(tester);await focusLaunchRow(tester, 'worktree');expect(find.byKey(const ValueKey('new-harness-field-worktree')),findsOneWidget,);- expect(find.text('Yes'), findsOneWidget);+ expect(find.text('[x]'), findsOneWidget);await press(tester, LogicalKeyboardKey.arrowRight);expect(box.worktree, isFalse);- expect(find.text('No'), findsOneWidget);+ expect(find.text('[ ]'), findsOneWidget);});testWidgets('Profile follows the chosen agent and hidden rows are skipped', (@@ -822,7 +834,7 @@ void main() {expect(box.engine, 'codex');expect(find.byKey(const ValueKey('new-harness-field-profile')),- findsOneWidget,+ findsNothing,);await press(tester, LogicalKeyboardKey.enter);expect(box.engine, 'claude');@@ -834,7 +846,7 @@ void main() {expect(tester.widget<Semantics>(- find.byKey(const ValueKey('new-harness-field-start')),+ find.byKey(const ValueKey('new-harness-field-branch')),).properties.selected,diff --git a/desktop/test/new_harness_git_test.dart b/desktop/test/new_harness_git_test.dartindex 108a04a53..0b869e16c 100644--- a/desktop/test/new_harness_git_test.dart+++ b/desktop/test/new_harness_git_test.dart@@ -122,9 +122,76 @@ void main() {Future<void> settle() => Future<void>.delayed(Duration.zero);+ test(+ 'missing main requires choosing a branch without changing Worktree',+ () async {+ final connection = _Connection()+ ..answers['/repo'] = {+ 'isGit': true,+ 'branch': 'master',+ 'defaultRef': 'refs/remotes/origin/master',+ 'branches': [+ {'ref': 'refs/heads/master', 'name': 'master'},+ {'ref': 'refs/heads/feature', 'name': 'feature'},+ ],+ };+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ expect(box.branchRef, isNull);+ expect(box.worktree, isTrue);+ expect(box.requiredChoice?.field, NewHarnessField.branch);+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, contains('Choose a branch'));+ expect(connection.starts, isEmpty);+ expect(box.worktree, isTrue);+ box.accept(+ box.options.singleWhere((option) => option.id == 'refs/heads/feature'),+ );+ expect(box.branchRef, 'refs/heads/feature');+ expect(box.requiredChoice, isNull);+ },+ );++ test('an unavailable saved folder requires choosing a project', () async {+ final connection = _Connection()+ ..answers['/missing'] = {'error': 'PROJECT_UNAVAILABLE'};+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/missing',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.field, NewHarnessField.projectMenu);+ expect(box.error, contains('Choose a project'));+ expect(box.project.folder, '/missing');+ expect(connection.starts, isEmpty);+ });+test('Branch opens immediately, discovers remote matches, and never queries on typing', () async {final connection = _Connection()..refreshing = Completer();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -175,7 +242,10 @@ void main() {test('failed branch refresh preserves usable choices and manual retry keeps the query', () async {final connection = _Connection()..refreshing = Completer();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -217,7 +287,10 @@ void main() {},],};- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -250,7 +323,10 @@ void main() {test('a late refresh from another project is discarded', () async {final connection = _Connection()..refreshing = Completer();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -274,7 +350,10 @@ void main() {'Branch shows refresh progress and manual refresh keeps the typed query',(tester) async {final connection = _Connection()..refreshing = Completer();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -341,7 +420,10 @@ void main() {'failed Git discovery blocks launch and the next Start retries it',() async {final connection = _Connection()..gitFailures = 2;- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -366,7 +448,10 @@ void main() {test('a remote branch cannot launch in the main folder after Worktree is disabled', () async {final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -394,7 +479,10 @@ void main() {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 app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -412,7 +500,10 @@ void main() {test('Git defaults follow the project, late replies are ignored, and draft choices survive', () async {final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -480,7 +571,10 @@ void main() {test('the form filters a field and takes what it landed on', () async {final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -516,7 +610,10 @@ void main() {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();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -549,7 +646,10 @@ void main() {'preparedFolder': '/prepared','failure': {'code': 'TMUX_UNAVAILABLE'},};- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -583,7 +683,10 @@ void main() {const folder = '/harnesses/worktrees/repo/claude-0922-1136';final connection = _Connection()..answers[folder] = linked('harness/claude-0922-1136');- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -628,7 +731,10 @@ void main() {'preparedFolder': prepared,'failure': {'code': 'TMUX_UNAVAILABLE'},};- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -687,7 +793,10 @@ void main() {test('search finds remote-qualified and older Harness branches', () async {final connection = _Connection()..answers['/repo'] = rich;- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -725,7 +834,10 @@ void main() {},],};- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -743,7 +855,10 @@ void main() {'From is where new work starts; Branch is the branch it is on',() async {final connection = _Connection()..answers['/repo'] = rich;- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -871,7 +986,10 @@ void main() {'Worktree off can make a new branch for the folder, from its branch',() async {final connection = _Connection()..answers['/repo'] = rich;- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -918,7 +1036,10 @@ void main() {test('Create branch cleans up a typed name', () async {final connection = _Connection()..answers['/repo'] = rich;- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -941,7 +1062,10 @@ void main() {'Worktree off never switches a folder a harness is working in',() async {final connection = _Connection()..answers['/repo'] = rich;- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );app.machineStates['m']!.agents = [const Agent(id: 'busy',@@ -968,10 +1092,13 @@ void main() {},);- test('a repository with no commit starts without a worktree', () async {+ test('an empty repository keeps Worktree on and requires a choice', () async {final connection = _Connection()..answers['/empty'] = {'isGit': true, 'branch': 'main', 'branches': []};- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -982,14 +1109,21 @@ void main() {addTearDown(box.dispose);await settle();expect(box.isGitProject, true);- expect(box.worktree, false);+ expect(box.worktree, true);+ expect(box.requiredChoice?.message, contains('no commits'));+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.worktree, true);+ expect(connection.starts, isEmpty);});testWidgets('setup branch and worktree choices are used by the explicit launch action',(tester) async {final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -1036,7 +1170,10 @@ void main() {final renderDir = Platform.environment['HARNESS_LAUNCH_RENDER_DIR'];if (renderDir != null) await tester.runAsync(loadPreviewFonts);final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -1076,7 +1213,7 @@ void main() {);await tester.pump();await openLaunchRow(tester, 'start');- expect(find.text('[ New Harness ]').hitTestable(), findsOneWidget);+ expect(find.text('New Harness').hitTestable(), findsOneWidget);expect(tester.takeException(), isNull);if (renderDir != null) {await expectLater(@@ -1104,7 +1241,7 @@ void main() {find.byKey(const ValueKey('new-harness-field-branch')),findsOneWidget,);- // Branch and Worktree remain in the expanded Options group.+ // Branch and Worktree remain visible in the form.expect(find.byKey(const ValueKey('new-harness-field-worktree')),findsOneWidget,diff --git a/desktop/test/new_harness_grid_test.dart b/desktop/test/new_harness_grid_test.dartindex 44c07ba93..20eed8716 100644--- a/desktop/test/new_harness_grid_test.dart+++ b/desktop/test/new_harness_grid_test.dart@@ -4,12 +4,13 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness/shortcuts/app_keymap.dart';import 'package:harness/shortcuts/keymap_host.dart';import 'package:harness/state/new_harness.dart';+import 'package:harness/terminal/terminal_text.dart';import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/ws/ws_conn.dart';import 'keymap_host_test.dart' show MemoryKeymap, key;import 'support/launch_menu.dart'- show focusLaunchRow, openLaunchRow, typeHarnessQuery;+ show harnessChoicesActive, focusLaunchRow, openLaunchRow;import 'support/mixed_agents.dart';import 'swarm_state_test.dart' show createApp;@@ -56,6 +57,8 @@ void main() {WidgetTester tester, {String focus = 'agent',double width = 820,+ double height = 450,+ double scale = 1,MemoryKeymap? keymap,}) async {final daemon = _Daemon();@@ -72,6 +75,11 @@ void main() {await tester.pumpWidget(MaterialApp(theme: ThemeData.dark(),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(scale)),+ child: child!,+ ),home: KeymapProvider(keymap: keymap,child: KeymapHost(@@ -82,7 +90,7 @@ void main() {body: Center(child: SizedBox(width: width,- height: 450,+ height: height,child: NewHarnessForm(controller: box,onClose: () {},@@ -100,72 +108,132 @@ void main() {return (box, daemon);}- group('⇧⏎ starts from any field', () {- testWidgets('from a value row, without walking to the button', (- tester,- ) async {- final (_, daemon) = await mount(tester);- await key(tester, LogicalKeyboardKey.enter);- expect(- daemon.requests,- isNot(contains('agent_create')),- reason: 'Plain Return on a value row must still never start.',- );- await key(tester, LogicalKeyboardKey.enter, shift: true);- expect(daemon.requests, contains('agent_create'));- });-- testWidgets('taking the value highlighted in a live list first', (- tester,- ) async {- final (box, daemon) = await mount(tester);- await key(tester, LogicalKeyboardKey.arrowRight);- await key(tester, LogicalKeyboardKey.arrowDown);- final wanted = box.selected!.id;- expect(wanted, isNot(box.engine));- await key(tester, LogicalKeyboardKey.enter, shift: true);- expect(- box.engine,- wanted,- reason: 'The highlight is what the person was looking at.',- );- expect(daemon.requests, contains('agent_create'));- });-- testWidgets('the button prints the key that reaches it', (tester) async {- await mount(tester);- expect(find.text('[ New Harness ]'), findsOneWidget);- expect(find.textContaining('⇧'), findsWidgets);- });- });-- testWidgets('quick start cannot launch from an empty choice list', (+ testWidgets('Enter accepts a value before a separate Enter launches', (tester,) async {final (box, daemon) = await mount(tester);- await openLaunchRow(tester, 'agent');- await typeHarnessQuery(tester, 'no-such-agent-123456');+ await key(tester, LogicalKeyboardKey.enter);+ expect(harnessChoicesActive(tester), isTrue);+ expect(daemon.requests, isNot(contains('agent_create')));+ await key(tester, LogicalKeyboardKey.enter);+ expect(box.field, NewHarnessField.launch);+ expect(daemon.requests, isNot(contains('agent_create')));+ expect(find.textContaining('⇧'), findsNothing);await key(tester, LogicalKeyboardKey.enter, shift: true);- expect(box.error, 'No values match this search.');expect(daemon.requests, isNot(contains('agent_create')));+ await key(tester, LogicalKeyboardKey.enter);+ expect(daemon.requests, contains('agent_create'));});group('one grid', () {double heightOf(WidgetTester tester, String field) =>tester.getSize(find.byKey(ValueKey('new-harness-field-$field'))).height;+ for (final (width, height, scale) in [+ (823.25, 417.5, 1.0),+ (1283.7, 587.3, 1.6),+ ]) {+ testWidgets(+ 'fields and action keep whole cells at $width × $height, scale $scale',+ (tester) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1400, 900);+ addTearDown(tester.view.reset);+ final (box, _) = await mount(+ tester,+ width: width,+ height: height,+ scale: scale,+ );+ await openLaunchRow(tester, 'advanced');+ final surface = find.byKey(const ValueKey('new-harness-surface'));+ final origin = tester.getTopLeft(surface);+ final cell = terminalCellSizeOf(tester.element(surface));+ Finder textIn(String key, String text) => find.descendant(+ of: find.byKey(ValueKey(key)),+ matching: find.text(text),+ );+ Finder label(String name, String text) =>+ textIn('new-harness-field-$name', text);+ void onGrid(Finder text) {+ final offset = tester.getTopLeft(text) - origin;+ expect(+ offset.dx / cell.width,+ closeTo((offset.dx / cell.width).roundToDouble(), .01),+ );+ expect(+ offset.dy / cell.height,+ closeTo((offset.dy / cell.height).roundToDouble(), .01),+ );+ }++ final agent = label('agent', 'Agent');+ final start = label('start', 'New Harness');+ final fields = {+ 'agent': 'Agent',+ 'model': 'Model',+ 'approvals': 'Approvals',+ if (box.usesProfile) 'profile': 'Profile',+ 'project': 'Project',+ 'advanced': 'Options',+ 'branch': 'Branch',+ 'worktree': 'Worktree',+ };+ for (final entry in fields.entries) {+ final text = label(entry.key, entry.value);+ onGrid(text);+ expect(tester.getTopLeft(text).dx, tester.getTopLeft(agent).dx);+ }+ onGrid(start);+ final lastAgentSetting = box.usesProfile+ ? label('profile', 'Profile')+ : label('approvals', 'Approvals');+ expect(+ tester.getTopLeft(label('branch', 'Branch')).dy -+ tester.getBottomLeft(lastAgentSetting).dy,+ closeTo(0, .01),+ );+ expect(+ tester.getTopLeft(start).dy -+ tester.getBottomLeft(label('worktree', 'Worktree')).dy,+ closeTo(cell.height, .01),+ );+ final value = label('agent', box.launchAgentLabel);+ onGrid(value);+ expect(+ tester.getTopLeft(value).dx - tester.getTopLeft(agent).dx,+ closeTo(11 * cell.width, .01),+ );+ final size = tester.getSize(surface);+ expect(size.width / cell.width, closeTo(56, .01));+ expect(+ size.height / cell.height,+ closeTo(box.usesProfile ? 14 : 13, .01),+ );+ expect(tester.takeException(), isNull);+ },+ );+ }+testWidgets('every field is exactly one row', (tester) async {await mount(tester);+ await openLaunchRow(tester, 'advanced');final row = heightOf(tester, 'agent');- for (final field in ['project', 'advanced']) {+ for (final field in [+ 'model',+ 'approvals',+ 'project',+ 'branch',+ 'worktree',+ ]) {expect(heightOf(tester, field), row, reason: '$field drifted');}});testWidgets('a wrapped notice is a whole number of rows', (tester) async {final (box, _) = await mount(tester, focus: 'model');- await openLaunchRow(tester, 'model');final row = heightOf(tester, 'agent');+ await openLaunchRow(tester, 'model');final notice = box.modelNotice;expect(notice, isNotNull);final height = tester.getSize(find.text(notice!)).height;@@ -198,19 +266,33 @@ void main() {expect(left('project', box.launchProjectLabel), closeTo(column, .5));});- testWidgets('a blank row sets Advanced apart from the core fields', (- tester,- ) async {- await mount(tester);- // Branch is the last core field now, under Project.- final project = tester.getRect(- find.byKey(const ValueKey('new-harness-field-project')),- );- final advanced = tester.getRect(- find.byKey(const ValueKey('new-harness-field-advanced')),- );- expect(advanced.top - project.bottom, closeTo(project.height, .5));- });+ testWidgets(+ 'Options rows are consecutive and Machine has no separate row',+ (tester) async {+ final (box, _) = await mount(tester);+ await openLaunchRow(tester, 'advanced');+ expect(+ find.byKey(const ValueKey('new-harness-field-machine')),+ findsNothing,+ );+ final fields = [+ 'advanced',+ 'model',+ 'approvals',+ if (box.usesProfile) 'profile',+ 'branch',+ 'worktree',+ ];+ Rect? previous;+ for (final field in fields) {+ final row = tester.getRect(+ find.byKey(ValueKey('new-harness-field-$field')),+ );+ if (previous != null) expect(row.top, closeTo(previous.bottom, .01));+ previous = row;+ }+ },+ );});group('small reads', () {@@ -227,12 +309,6 @@ void main() {expect(hint, box.hint);});- testWidgets('the key hint spaces its keys: ⇧ ⏎, not ⇧⏎', (tester) async {- await mount(tester);- final hint = find.textContaining('⇧');- expect(tester.widget<Text>(hint).data, startsWith('⇧ '));- });-testWidgets('this computer leads the machine list', (tester) async {final (box, _) = await mount(tester, focus: 'machine');// Make the machine that lists LAST the local one, so this passes only@@ -264,47 +340,101 @@ void main() {});});- // One test per behaviour a coverage run found untested among the lines this- // branch changed. Each names the behaviour, not the line.- group('reached only by less common paths', () {- testWidgets('a field the controller moves to opens Advanced to show it', (+ group('focus ownership', () {+ for (final activation in ['right', 'typing', 'enter']) {+ testWidgets('$activation enters the automatically visible chooser', (+ tester,+ ) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(2200, 700);+ addTearDown(tester.view.reset);+ final (box, daemon) = await mount(tester, focus: 'start', width: 2200);+ final surface = find.byKey(const ValueKey('new-harness-surface'));+ final chooser = find.byKey(+ const ValueKey('new-harness-chooser-surface'),+ );+ final frame = tester.getRect(surface);+ final originalEngine = box.engine;+ expect(chooser, findsNothing);+ await key(tester, LogicalKeyboardKey.arrowDown);+ expect(box.field, NewHarnessField.harness);+ expect(chooser, findsOneWidget);+ expect(harnessChoicesActive(tester), isFalse);+ expect(+ FocusManager.instance.primaryFocus?.debugLabel,+ 'new-harness-form',+ );+ // A visible chooser does not capture navigation before activation.+ await key(tester, LogicalKeyboardKey.arrowDown);+ expect(box.field, NewHarnessField.projectMenu);+ await key(tester, LogicalKeyboardKey.arrowUp);+ expect(box.field, NewHarnessField.harness);+ expect(box.engine, originalEngine);+ switch (activation) {+ case 'right':+ await key(tester, LogicalKeyboardKey.arrowRight);+ case 'enter':+ await key(tester, LogicalKeyboardKey.enter);+ case 'typing':+ await tester.sendKeyEvent(LogicalKeyboardKey.keyC, character: 'c');+ await tester.pumpAndSettle();+ expect(box.query, 'c');+ await key(tester, LogicalKeyboardKey.backspace);+ expect(box.query, isEmpty);+ }+ expect(harnessChoicesActive(tester), isTrue);+ expect(+ FocusManager.instance.primaryFocus?.debugLabel,+ 'new-harness-query',+ );+ final first = box.selected!.id;+ await key(tester, LogicalKeyboardKey.arrowDown);+ expect(box.selected!.id, isNot(first));+ expect(box.field, NewHarnessField.harness);+ expect(box.engine, originalEngine);+ expect(tester.getRect(surface), frame);+ await key(tester, LogicalKeyboardKey.escape);+ expect(harnessChoicesActive(tester), isFalse);+ expect(chooser, findsNothing);+ expect(box.engine, originalEngine);+ await key(tester, LogicalKeyboardKey.arrowRight);+ final wanted = box.selected!.id;+ await tester.sendKeyDownEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(box.engine, wanted);+ expect(box.field, NewHarnessField.launch);+ expect(chooser, findsNothing);+ expect(tester.getRect(surface), frame);+ await tester.sendKeyRepeatEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(daemon.requests, isNot(contains('agent_create')));+ await key(tester, LogicalKeyboardKey.enter);+ expect(daemon.requests, contains('agent_create'));+ expect(tester.takeException(), isNull);+ });+ }++ testWidgets('a controller-selected field is already visible', (tester,) async {final (box, _) = await mount(tester);- expect(box.advancedOpen, isFalse);box.focusField(NewHarnessField.mode);await tester.pumpAndSettle();+ expect(find.text('Options'), findsOneWidget);expect(box.advancedOpen, isTrue);expect(- find.byKey(const ValueKey('new-harness-field-approvals')),- findsOneWidget,+ tester+ .widget<Semantics>(+ find.byKey(const ValueKey('new-harness-field-approvals')),+ )+ .properties+ .selected,+ isTrue,);});- testWidgets('the page keys open and close Advanced from its own row', (- tester,- ) async {- final (box, _) = await mount(tester, focus: 'advanced');- await key(tester, LogicalKeyboardKey.pageDown);- expect(box.advancedOpen, isTrue);- await key(tester, LogicalKeyboardKey.pageUp);- expect(box.advancedOpen, isFalse);- });-- testWidgets('clicking the Advanced row opens and closes it', (- tester,- ) async {- final (box, _) = await mount(tester);- final advanced = find.byKey(const ValueKey('new-harness-field-advanced'));- await tester.tap(advanced);- await tester.pumpAndSettle();- expect(box.advancedOpen, isTrue);- await tester.tap(advanced);- await tester.pumpAndSettle();- expect(box.advancedOpen, isFalse);- });-- testWidgets('⇧⏎ inside a door prompt finishes it, then starts', (+ testWidgets('Enter finishes a project prompt before launching', (tester,) async {final (box, daemon) = await mount(tester, focus: 'project');@@ -312,12 +442,10 @@ void main() {await tester.pumpAndSettle();box.setQuery('ledger');await tester.pumpAndSettle();- await key(tester, LogicalKeyboardKey.enter, shift: true);- expect(- box.projectLabel,- contains('ledger'),- reason: 'The name typed in the prompt is the project it starts in.',- );+ await key(tester, LogicalKeyboardKey.enter);+ expect(box.projectLabel, contains('ledger'));+ expect(daemon.requests, isNot(contains('agent_create')));+ await key(tester, LogicalKeyboardKey.enter);expect(daemon.requests, contains('agent_create'));});@@ -354,14 +482,6 @@ void main() {},);- testWidgets('⌘. opens and closes Advanced from any field', (tester) async {- final (box, _) = await mount(tester);- await key(tester, LogicalKeyboardKey.period, cmd: true);- expect(box.advancedOpen, isTrue);- await key(tester, LogicalKeyboardKey.period, cmd: true);- expect(box.advancedOpen, isFalse);- });-testWidgets('a narrow window keeps a status line on the grid', (tester,) async {diff --git a/desktop/test/new_harness_install_e2e_test.dart b/desktop/test/new_harness_install_e2e_test.dartindex 1261d9d34..f09b5bcbb 100644--- a/desktop/test/new_harness_install_e2e_test.dart+++ b/desktop/test/new_harness_install_e2e_test.dart@@ -1,5 +1,5 @@// New Harness, end to end through the real app model: the machine's catalog-// arrives over `dsh_list`, the harness is picked with keys, ⇧⏎ sends+// arrives over `dsh_list`, the harness is picked with keys, Enter on New Harness sends// `dsh_install`, the machine narrates through `dsh_install_status` pushes,// and `agent_create` follows only once the install lands. Only the socket is// a fixture; AppNotifier, MachineDsh, the controller and the form are real.@@ -19,7 +19,7 @@ import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/ws/ws_conn.dart';import 'keymap_host_test.dart' show MemoryKeymap, key;-import 'support/launch_menu.dart' show focusLaunchRow;+import 'support/launch_menu.dart' show focusLaunchRow, startHarness;const _circuit = 'autonomous/autonomous-circuit';@@ -229,7 +229,7 @@ void main() {expect(box.harnessId, _circuit);expect(pane, findsNothing, reason: 'quiet until start');- await key(tester, LogicalKeyboardKey.enter, shift: true);+ await startHarness(tester);await settle(tester);expect(machine.installs, [_circuit]);expect(inPane('Installing Autonomous Circuit on This Mac'), findsOneWidget);@@ -262,59 +262,64 @@ void main() {expect(tester.takeException(), isNull);});- testWidgets('a failed install explains itself; ⇧⏎ retries and creates', (- tester,- ) async {- final box = await mount(tester);- await pickCircuit(tester);- await key(tester, LogicalKeyboardKey.enter, shift: true);- await settle(tester);- await say({'id': _circuit, 'phase': 'clone'});- await say({'id': _circuit, 'phase': 'setup', 'line': 'npm ci'});- await say({- 'id': _circuit,- 'phase': 'failed',- 'error': 'DSH_SETUP_FAILED',- 'detail': 'setup exited 1 · npm ERR! code E401',- });- machine.reply!.complete({- 'ok': false,- 'error': 'DSH_SETUP_FAILED',- 'detail': 'setup exited 1 · npm ERR! code E401',- });- await settle(tester);+ testWidgets(+ 'a failed install explains itself; New Harness retries and creates',+ (tester) async {+ final box = await mount(tester);+ await pickCircuit(tester);+ await startHarness(tester);+ await settle(tester);+ await say({'id': _circuit, 'phase': 'clone'});+ await say({'id': _circuit, 'phase': 'setup', 'line': 'npm ci'});+ await say({+ 'id': _circuit,+ 'phase': 'failed',+ 'error': 'DSH_SETUP_FAILED',+ 'detail': 'setup exited 1 · npm ERR! code E401',+ });+ machine.reply!.complete({+ 'ok': false,+ 'error': 'DSH_SETUP_FAILED',+ 'detail': 'setup exited 1 · npm ERR! code E401',+ });+ await settle(tester);- expect(machine.creates, isEmpty);- expect(- inPane('Autonomous Circuit did not install on This Mac'),- findsOneWidget,- );- expect(inPane('✓'), findsOneWidget, reason: 'fetch had finished');- expect(inPane('✗'), findsOneWidget, reason: 'set up is what failed');- expect(find.textContaining('tries again'), findsOneWidget);- expect(box.busy, isFalse);+ expect(machine.creates, isEmpty);+ expect(+ inPane('Autonomous Circuit did not install on This Mac'),+ findsOneWidget,+ );+ expect(inPane('✓'), findsOneWidget, reason: 'fetch had finished');+ expect(inPane('✗'), findsOneWidget, reason: 'set up is what failed');+ expect(find.textContaining('tries again'), findsOneWidget);+ expect(box.busy, isFalse);- // Opening a list covers the pane while choosing; leaving it brings it back.- await focusLaunchRow(tester, 'agent');- await key(tester, LogicalKeyboardKey.enter);- await tester.pumpAndSettle();- expect(pane, findsNothing);- await key(tester, LogicalKeyboardKey.escape);- await tester.pumpAndSettle();- expect(pane, findsOneWidget);+ // Opening a list covers the pane while choosing; leaving it brings it back.+ await key(tester, LogicalKeyboardKey.arrowDown);+ await key(tester, LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(pane, findsNothing);+ await key(tester, LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(pane, findsOneWidget);- await key(tester, LogicalKeyboardKey.enter, shift: true);- await settle(tester);- expect(machine.installs, [_circuit, _circuit]);- expect(inPane('✗'), findsNothing, reason: 'a retry is a fresh run');- expect(inPane('Installing Autonomous Circuit on This Mac'), findsOneWidget);- await say({'id': _circuit, 'phase': 'done'});- machine.reply!.complete({'ok': true});- await settle(tester);- await settle(tester);- expect(machine.creates.single['dsh'], _circuit);- expect(tester.takeException(), isNull);- });+ await key(tester, LogicalKeyboardKey.arrowUp);+ await key(tester, LogicalKeyboardKey.enter);+ await settle(tester);+ expect(machine.installs, [_circuit, _circuit]);+ expect(inPane('✗'), findsNothing, reason: 'a retry is a fresh run');+ expect(+ inPane('Installing Autonomous Circuit on This Mac'),+ findsOneWidget,+ );+ await say({'id': _circuit, 'phase': 'done'});+ machine.reply!.complete({'ok': true});+ await settle(tester);+ await settle(tester);+ expect(machine.creates.single['dsh'], _circuit);+ expect(tester.takeException(), isNull);+ },+ );testWidgets('a dropped socket says the install may still be finishing', (tester,@@ -322,7 +327,7 @@ void main() {await mount(tester);await pickCircuit(tester);machine.dropInstall = StateError('socket closed');- await key(tester, LogicalKeyboardKey.enter, shift: true);+ await startHarness(tester);await settle(tester);expect(machine.creates, isEmpty);expect(pane, findsOneWidget);@@ -353,7 +358,7 @@ void main() {) async {await mount(tester, width: width, textScale: scale);await pickCircuit(tester);- await key(tester, LogicalKeyboardKey.enter, shift: true);+ await startHarness(tester);await settle(tester);await say({'id': _circuit, 'phase': 'clone'});await say({diff --git a/desktop/test/new_harness_install_pane_test.dart b/desktop/test/new_harness_install_pane_test.dartindex 1829d3678..bd9be0b9b 100644--- a/desktop/test/new_harness_install_pane_test.dart+++ b/desktop/test/new_harness_install_pane_test.dart@@ -5,7 +5,6 @@import 'dart:async';import 'package:flutter/material.dart';-import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';@@ -22,7 +21,8 @@ import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/shortcuts/app_keymap.dart';import 'package:harness/shortcuts/keymap_host.dart';-import 'keymap_host_test.dart' show MemoryKeymap, key;+import 'keymap_host_test.dart' show MemoryKeymap;+import 'support/launch_menu.dart' show startHarness;DshEntry _entry(String id, String name, {required bool installed}) => DshEntry(id: id,@@ -323,23 +323,26 @@ void main() {installed: true,);- test('a remembered harness the Store dropped opens as Code', () async {- final notifier = await app(- remember: (n) => n.agentPreference.remember('codex', harnessId: gone),- );- final box = controller(notifier);- await Future<void>.delayed(Duration.zero);- expect(box.harnessId, isNull);- expect(box.harnessLabel, 'Code');- expect(- box.engine,- 'codex',- reason: 'Code keeps the agent last used, which Code can run',- );- expect(harnessList(box), isNot(contains(gone)));- });+ test(+ 'a remembered harness the Store dropped requires a replacement',+ () async {+ final notifier = await app(+ remember: (n) => n.agentPreference.remember('codex', harnessId: gone),+ );+ final box = controller(notifier);+ await Future<void>.delayed(Duration.zero);+ expect(box.harnessId, gone);+ expect(box.requiredChoice?.field, NewHarnessField.harness);+ expect(+ box.engine,+ 'codex',+ reason:+ 'The remembered value is retained until a replacement is chosen',+ );+ },+ );- test('a remembered viewer package opens as Code too', () async {+ test('a remembered viewer package requires an agent choice', () async {final notifier = await app(catalog: [_blender, viewer],remember: (n) =>@@ -347,8 +350,8 @@ void main() {);final box = controller(notifier);await Future<void>.delayed(Duration.zero);- expect(box.harnessId, isNull);- expect(harnessList(box), isNot(contains(viewer.id)));+ expect(box.harnessId, viewer.id);+ expect(box.requiredChoice?.field, NewHarnessField.harness);});test('before the catalog answers, recents are kept as they are', () async {@@ -374,26 +377,30 @@ void main() {},);- test('a remembered agent the harness cannot run falls back', () async {- final only = DshEntry(- id: _blender.id,- name: _blender.name,- engine: 'claude',- engines: const ['claude'],- installed: true,- );- final notifier = await app(- catalog: [only],- remember: (n) async {- // Codex was remembered for it before the harness narrowed.- await n.agentPreference.remember('codex', harnessId: only.id);- },- );- final box = controller(notifier);- await Future<void>.delayed(Duration.zero);- expect(box.harnessId, only.id);- expect(box.engine, 'claude');- });+ test(+ 'a remembered agent the harness cannot run requires a choice',+ () async {+ final only = DshEntry(+ id: _blender.id,+ name: _blender.name,+ engine: 'claude',+ engines: const ['claude'],+ installed: true,+ );+ final notifier = await app(+ catalog: [only],+ remember: (n) async {+ // Codex was remembered for it before the harness narrowed.+ await n.agentPreference.remember('codex', harnessId: only.id);+ },+ );+ final box = controller(notifier);+ await Future<void>.delayed(Duration.zero);+ expect(box.harnessId, only.id);+ expect(box.engine, 'codex');+ expect(box.requiredChoice?.field, NewHarnessField.agent);+ },+ );});group('installing on the way to start', () {@@ -406,7 +413,7 @@ void main() {box.focusField(NewHarnessField.harness);box.applyOption(box.options.firstWhere((o) => o.id == _circuit.id));await tester.pump();- await key(tester, LogicalKeyboardKey.enter, shift: true);+ await startHarness(tester);await tester.pump();expect(notifier.installs, [_circuit.id]);@@ -423,6 +430,13 @@ void main() {);expect(find.text('Fetch Autonomous Circuit'), findsOneWidget);expect(find.text('>'), findsWidgets, reason: 'fetch is the live step');+ await tester.pump(const Duration(seconds: 1));+ expect(+ box.busy,+ isTrue,+ reason: 'the install remains live across timer ticks',+ );+ expect(pane, findsOneWidget);final fetching = box.installRun!.phases.first.at;notifier.narrate(@@ -481,7 +495,7 @@ void main() {box.focusField(NewHarnessField.harness);box.applyOption(box.options.firstWhere((o) => o.id == _circuit.id));await tester.pump();- await key(tester, LogicalKeyboardKey.enter, shift: true);+ await startHarness(tester);await tester.pump();notifier.narrate(_circuit.id, 'setup', line: 'npm ci');notifier.narrate(_circuit.id, 'failed', code: 'DSH_BUSY');@@ -523,7 +537,7 @@ void main() {n.agentPreference.remember('claude', harnessId: _blender.id),);await mount(tester, notifier);- await key(tester, LogicalKeyboardKey.enter, shift: true);+ await startHarness(tester);await tester.pump();expect(notifier.installs, isEmpty);expect(find.byKey(const ValueKey('new-harness-install')), findsNothing);diff --git a/desktop/test/new_harness_models_test.dart b/desktop/test/new_harness_models_test.dartindex 09b4910cb..86cacfbff 100644--- a/desktop/test/new_harness_models_test.dart+++ b/desktop/test/new_harness_models_test.dart@@ -57,6 +57,7 @@ class _Connection extends WsConn {Map<String, dynamic> answer = catalog();Future<Map<String, dynamic>>? waiting;bool loseReply = false;+ int modelReads = 0;final creates = <Map<String, dynamic>>[];@overrideFuture<Map<String, dynamic>> request(@@ -66,6 +67,7 @@ class _Connection extends WsConn {}) async {switch (type) {case 'grid_models_list':+ modelReads++;return waiting ?? answer;case 'git_project_info':return {'isGit': false};@@ -369,8 +371,10 @@ void main() {expect(box.engine, 'terminal');expect(box.model, isNull);expect(box.draft.model, isNull);- await openLaunchRow(tester, 'advanced');- expect(find.text('Not used by Terminal'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('new-harness-field-model')),+ findsNothing,+ );await startHarness(tester);await tester.pumpAndSettle();final payload = connections['m']!.creates.single;@@ -422,7 +426,7 @@ void main() {await load(box);box.applyOption(localChoice(box));select(box, NewHarnessField.agent, 'cursor');- expect(box.subscriptionLabel, 'Cursor default');+ expect(box.subscriptionLabel, 'Cursor');expect(box.modelNotice, contains('own login'));expect(await box.create(), NewHarnessOutcome.failed);await load(box);@@ -576,7 +580,8 @@ void main() {),);await tester.pumpAndSettle();- final order = ['agent', 'project', 'advanced'];+ await openLaunchRow(tester, 'advanced');+ final order = ['agent', 'project', 'model', 'branch', 'worktree'];final positions = [for (final name in order)tester@@ -593,7 +598,6 @@ void main() {await tester.pumpAndSettle();expect(box.modelLabel, 'Qwen-35B · Mac Studio');expect(box.machineId, 'm');- await openLaunchRow(tester, 'advanced');final start = find.byKey(const ValueKey('new-harness-field-start'));expect(start.hitTestable(), findsOneWidget);final semantics = tester.ensureSemantics();@@ -605,8 +609,36 @@ void main() {findsNothing,);await openLaunchRow(tester, 'model');+ await tester.scrollUntilVisible(+ find.text('Refresh models'),+ 60,+ scrollable: find.descendant(+ of: find.byKey(const ValueKey('new-harness-choices')),+ matching: find.byWidgetPredicate(+ (widget) =>+ widget is Scrollable &&+ widget.axisDirection == AxisDirection.down,+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('Refresh models').hitTestable(), findsOneWidget);+ final beforeRefresh = connections['m']!.modelReads;await tester.tap(find.text('Refresh models'));await tester.pumpAndSettle();+ expect(connections['m']!.modelReads, greaterThan(beforeRefresh));+ await tester.scrollUntilVisible(+ find.text('Manage Models…'),+ 60,+ scrollable: find.descendant(+ of: find.byKey(const ValueKey('new-harness-choices')),+ matching: find.byWidgetPredicate(+ (widget) =>+ widget is Scrollable &&+ widget.axisDirection == AxisDirection.down,+ ),+ ),+ );await tester.tap(find.text('Manage Models…'));await tester.pumpAndSettle();expect(managed, 1);diff --git a/desktop/test/new_harness_project_context_test.dart b/desktop/test/new_harness_project_context_test.dartindex d636be2b8..203f80de0 100644--- a/desktop/test/new_harness_project_context_test.dart+++ b/desktop/test/new_harness_project_context_test.dart@@ -327,8 +327,7 @@ 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();+ await openLaunchRow(tester, 'project');final selected = box.selected?.id;final machine = app.machineStates['m']!;machine.agents = [@@ -355,7 +354,6 @@ void main() {'/work/openharness',],);- expect(find.text('M2:product-video'), findsOneWidget);expect(box.selected?.id, selected);var changes = 0;box.addListener(() => changes++);@@ -364,6 +362,7 @@ void main() {expect(changes, 0);await typeHarnessQuery(tester, 'product video');await tester.pump();+ expect(find.text('M2:product-video'), findsOneWidget);expect(box.selected!.project!.folder, '/work/product-video');await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();diff --git a/desktop/test/new_harness_scenarios_test.dart b/desktop/test/new_harness_scenarios_test.dartindex 6b56c4b47..ea63e5506 100644--- a/desktop/test/new_harness_scenarios_test.dart+++ b/desktop/test/new_harness_scenarios_test.dart@@ -185,7 +185,6 @@ Future<_Scenario> _mount();await tester.pumpAndSettle();if (editProject) {- await openLaunchRow(tester, 'advanced');await openLaunchRow(tester, 'project');}return scenario;@@ -215,7 +214,7 @@ void main() {}testWidgets(- 'Cmd-N opens with two fields, collapsed Options and explicit launch selected',+ 'Cmd-N opens Agent, Project and Options with Enter ready to launch',(tester) async {final scenario = await _mount(tester,@@ -228,7 +227,6 @@ void main() {expect(_field('advanced'), findsOneWidget);for (final name in ['machine',- 'harness','model','branch','worktree',@@ -242,8 +240,8 @@ void main() {isTrue,);expect(find.byType(TextField), findsNothing);- expect(find.byKey(const ValueKey('new-harness-summary')), findsOneWidget);- expect(find.text('/work/repo'), findsOneWidget);+ expect(find.byKey(const ValueKey('new-harness-summary')), findsNothing);+ expect(find.text('M2:/work/repo'), findsOneWidget);expect(scenario.connections.values.expand((c) => c.starts), isEmpty);await capture(tester, 'rest');await key(tester, LogicalKeyboardKey.enter);@@ -273,6 +271,8 @@ void main() {await openLaunchRow(tester, 'agent');expect(scenario.box.options.any((o) => o.title == 'Code'), isFalse);await typeHarnessQuery(tester, 'blender');+ final query = find.byKey(const ValueKey('new-harness-query'));+ final queryTop = tester.getTopLeft(query).dy;await key(tester, LogicalKeyboardKey.enter);expect(scenario.box.field, NewHarnessField.agent);expect(scenario.box.options.map((o) => o.id).toSet(), {@@ -280,6 +280,11 @@ void main() {'codex',});expect(scenario.box.selected!.id, 'claude');+ expect(+ tester.widget<TextField>(query).decoration!.hintText,+ 'Run Blender with',+ );+ expect(tester.getTopLeft(query).dy, queryTop);expect(find.text('Run Blender with'), findsOneWidget);await capture(tester, 'blender');await key(tester, LogicalKeyboardKey.arrowLeft);@@ -296,6 +301,11 @@ void main() {await key(tester, LogicalKeyboardKey.enter);expect(scenario.box.launchAgentLabel, 'Blender · Codex');expect(harnessChoicesActive(tester), isFalse);+ for (final label in ['Agent', 'Project', 'Options']) {+ expect(find.text(label), findsOneWidget);+ }+ expect(find.text('Agent default'), findsNothing);+ await capture(tester, 'blender-form');await openLaunchRow(tester, 'agent');await typeHarnessQuery(tester, 'Claude Code');await key(tester, LogicalKeyboardKey.enter);@@ -323,7 +333,7 @@ void main() {await key(tester, LogicalKeyboardKey.enter);expect(scenario.box.machineId, 'studio');expect(scenario.box.project.folder, '/work/repo');- expect(scenario.box.launchProjectLabel, 'iMac · Office:repo');+ expect(scenario.box.launchProjectLabel, 'iMac · Office:/work/repo');await openLaunchRow(tester, 'project');await typeHarnessQuery(tester, 'build');expect(scenario.box.selected!.enabled, isFalse);@@ -450,6 +460,7 @@ void main() {}expect(scenario.box.worktree, isTrue);+ await focusLaunchRow(tester, 'worktree');activate('worktree');await tester.pump();expect(scenario.box.worktree, isFalse);@@ -582,12 +593,25 @@ void main() {('studio', 'not linked'),('build', 'offline'),]) {+ await tester.scrollUntilVisible(+ _option(id),+ 40,+ scrollable: find.descendant(+ of: find.byKey(const ValueKey('new-harness-choices')),+ matching: find.byWidgetPredicate(+ (widget) =>+ widget is Scrollable &&+ widget.axisDirection == AxisDirection.down,+ ),+ ),+ );await tester.tap(_option(id));await tester.pump();expect(scenario.box.machineId, 'm');expect(scenario.box.error, contains(message));expect(harnessChoicesActive(tester), isTrue);}+ await typeHarnessQuery(tester, 'M2');await tester.tap(_option('m'));await tester.pump();expect(scenario.box.machineId, 'm');@@ -643,7 +667,7 @@ void main() {expect(scenario.box.mode, mode.id);expect(scenario.box.engine, engine);expect(scenario.creates, 0);- await key(tester, LogicalKeyboardKey.enter);+ await openLaunchRow(tester, 'approvals');}},);@@ -653,12 +677,14 @@ void main() {'clicking approvals uses the chosen agent, not the list preview',(tester) async {final scenario = await _mount(tester);+ await focusLaunchRow(tester, 'agent');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 openLaunchRow(tester, 'advanced');await tester.tap(_field('approvals'));await tester.pump();expect(scenario.box.options.map((mode) => mode.id), [@@ -678,6 +704,7 @@ void main() {await tester.pump();await typeHarnessQuery(tester, 'Codex');expect(scenario.box.selected?.id, 'codex');+ await focusLaunchRow(tester, 'approvals');await tester.tap(_field('approvals'));await tester.pump();expect(scenario.box.options.map((mode) => mode.id), [@@ -696,7 +723,7 @@ void main() {);testWidgets(- 'empty results explain Return and Escape clears search before closing',+ 'empty results explain Return and Escape retraces the project steps',(tester) async {final scenario = await _mount(tester);await openLaunchRow(tester, 'machine');@@ -716,8 +743,6 @@ void main() {await key(tester, LogicalKeyboardKey.escape);expect(scenario.closes, 0);await key(tester, LogicalKeyboardKey.escape);- expect(scenario.closes, 0);- await key(tester, LogicalKeyboardKey.escape);expect(scenario.closes, 1);},);@@ -734,9 +759,10 @@ void main() {);await key(tester, LogicalKeyboardKey.tab, shift: true);expect(- tester.widget<Semantics>(_field('approvals')).properties.selected,+ tester.widget<Semantics>(_field('advanced')).properties.selected,isTrue,);+ await focusLaunchRow(tester, 'approvals');final originalMode = scenario.box.mode;await key(tester, LogicalKeyboardKey.pageDown);expect(scenario.box.mode, isNot(originalMode));@@ -746,9 +772,9 @@ void main() {await tester.sendKeyRepeatEvent(LogicalKeyboardKey.arrowUp);await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowUp);await tester.pump();- // Two steps up from Approvals: Worktree, then Branch.+ // Two steps up from Approvals: Model, then Options.expect(- tester.widget<Semantics>(_field('branch')).properties.selected,+ tester.widget<Semantics>(_field('advanced')).properties.selected,isTrue,);expect(FocusManager.instance.primaryFocus?.debugLabel, 'new-harness-form');@@ -966,8 +992,6 @@ void main() {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);});@@ -1004,7 +1028,7 @@ void main() {(NewHarnessController.repositoryId, 'https://github.com/example/moon.git'),(NewHarnessController.existingProjectId, '/work/my project'),]) {- testWidgets('$door accepts pasted input and returns focus to fields', (+ testWidgets('$door accepts pasted input and returns focus to launch', (tester,) async {final scenario = await _mount(tester);@@ -1028,7 +1052,7 @@ void main() {await tester.pumpAndSettle();expect(scenario.box.query, input);await key(tester, LogicalKeyboardKey.enter);- expect(scenario.box.field, NewHarnessField.projectMenu);+ expect(scenario.box.field, NewHarnessField.launch);expect(harnessChoicesActive(tester), isFalse);expect(scenario.box.query, isEmpty);switch (door) {@@ -1217,6 +1241,7 @@ void main() {final scenario = await _mount(tester, gitReply: pending.future);expect(scenario.box.checkingGit, isTrue);expect(find.text('Not a Git repository'), findsNothing);+ await focusLaunchRow(tester, 'worktree');await tester.tap(_field('worktree'));await tester.pump();pending.complete(_git);@@ -1231,30 +1256,31 @@ void main() {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 focusLaunchRow(tester, 'project');- 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.machine);- await key(tester, LogicalKeyboardKey.enter);- expect(scenario.box.field, NewHarnessField.project);- await tester.tap(find.text('Project'));- await tester.pump();- expect(scenario.box.field, NewHarnessField.projectMenu);- expect(harnessChoicesActive(tester), isFalse);- expect(scenario.creates, 0);- });+ testWidgets(+ 'narrow layout Left leaves lists and prompts without a title row',+ (tester) async {+ final scenario = await _mount(tester, size: const Size(520, 520));+ await focusLaunchRow(tester, 'project');+ await tester.tap(_field('project'));+ await tester.pump();+ expect(harnessChoicesActive(tester), isTrue);+ expect(find.text('<'), findsNothing);+ await key(tester, LogicalKeyboardKey.arrowLeft);+ 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.machine);+ await key(tester, LogicalKeyboardKey.enter);+ expect(scenario.box.field, NewHarnessField.project);+ expect(find.text('<'), findsNothing);+ await key(tester, LogicalKeyboardKey.arrowLeft);+ 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',@@ -1273,6 +1299,15 @@ void main() {expect(scenario.box.selected!.id, isNot(first));await key(tester, LogicalKeyboardKey.tab);expect(scenario.box.selected!.id, first);+ for (+ var i = 0;+ scenario.box.selected?.id != NewHarnessController.changeMachineId &&+ i < 10;+ i+++ ) {+ await key(tester, LogicalKeyboardKey.arrowDown);+ }+ await tester.pump();await tester.tap(_option(NewHarnessController.changeMachineId));await tester.pump();expect(scenario.box.field, NewHarnessField.machine);@@ -1303,6 +1338,230 @@ void main() {},);+ testWidgets(+ 'a launch reply after the form is removed cannot run its old callback',+ (tester) async {+ final scenario = await _mount(tester, git: false, editProject: false);+ final connection = scenario.connections['m']!;+ connection.starting = Completer();+ await key(tester, LogicalKeyboardKey.enter);+ expect(connection.starts, hasLength(1));+ await tester.pumpWidget(const SizedBox());+ connection.starting!.complete(+ connection.created(connection.starts.single),+ );+ await tester.pump(const Duration(milliseconds: 200));+ expect(scenario.creates, 0);+ expect(tester.takeException(), isNull);+ },+ );++ testWidgets(+ 'a missing branch discovered during launch opens the branch chooser',+ (tester) async {+ final git = Completer<Map<String, dynamic>>();+ final scenario = await _mount(+ tester,+ editProject: false,+ gitReply: git.future,+ );+ await key(tester, LogicalKeyboardKey.enter);+ expect(scenario.box.busy, isTrue);+ git.complete({+ 'isGit': true,+ 'branch': 'trunk',+ 'branches': [+ {'ref': 'refs/heads/trunk', 'name': 'trunk'},+ ],+ });+ await tester.pumpAndSettle();+ expect(scenario.box.field, NewHarnessField.branch);+ expect(harnessChoicesActive(tester), isTrue);+ expect(scenario.box.error, contains('Choose a branch'));+ expect(scenario.box.worktree, isTrue);+ expect(scenario.connections['m']!.starts, isEmpty);+ },+ );++ testWidgets(+ 'pointer toggles Options and a carried task survives returning to launch',+ (tester) async {+ final scenario = await _mount(tester, editProject: false, git: false);+ await tester.tap(_field('advanced'));+ await tester.pumpAndSettle();+ expect(scenario.box.advancedOpen, isTrue);+ expect(_field('model'), findsOneWidget);+ await tester.tap(_field('advanced'));+ await tester.pumpAndSettle();+ expect(scenario.box.advancedOpen, isFalse);+ expect(_field('model'), findsNothing);+ await focusLaunchRow(tester, 'start');+ scenario.box.task = 'Keep this carried task';+ scenario.box.focusField(NewHarnessField.task);+ await tester.pumpAndSettle();+ expect(find.text('Keep this carried task'), findsOneWidget);+ await startHarness(tester);+ await tester.pumpAndSettle();+ expect(+ scenario.connections['m']!.starts.single['prompt'],+ 'Keep this carried task',+ );+ expect(scenario.creates, 1);+ },+ );++ testWidgets(+ 'Enter opens the required replacement chooser without launching',+ (tester) async {+ final scenario = await _mount(tester, git: false, editProject: false);+ scenario.app.machineStates['m']!.needsLink = true;+ scenario.app.notifyListeners();+ await tester.pump(const Duration(milliseconds: 200));+ await key(tester, LogicalKeyboardKey.enter);+ expect(scenario.box.field, NewHarnessField.machine);+ expect(harnessChoicesActive(tester), isTrue);+ expect(scenario.box.error, contains('Choose a machine'));+ expect(scenario.creates, 0);+ expect(scenario.connections['m']!.starts, isEmpty);+ },+ );++ testWidgets(+ 'controller-selected Model opens its row and Manage Models uses the app door',+ (tester) async {+ final scenario = await _mount(tester, git: false, editProject: false);+ var requests = 0;+ final subscription = scenario.app.modelsRequests.listen(+ (_) => requests++,+ );+ addTearDown(subscription.cancel);+ scenario.box.focusField(NewHarnessField.model);+ await tester.pumpAndSettle();+ expect(+ tester.widget<Semantics>(_field('model')).properties.selected,+ isTrue,+ );+ await key(tester, LogicalKeyboardKey.enter);+ await tester.tap(_option(NewHarnessController.manageModelsId));+ await tester.pump();+ expect(requests, 1);+ expect(scenario.creates, 0);+ },+ );++ testWidgets(+ 'fallback Backspace retains Unicode clusters and selected text after focus moves',+ (tester) async {+ final scenario = await _mount(tester);+ await typeHarnessQuery(tester, 'a👩🏽💻b');+ final editor = tester.widget<TextField>(+ find.byKey(const ValueKey('new-harness-query')),+ );+ final parent = tester+ .widget<Focus>(find.byKey(const ValueKey('new-harness-form')))+ .focusNode!;+ Future<void> backspace(TextSelection selection) async {+ parent.requestFocus();+ await tester.pump();+ editor.controller!.selection = selection;+ await key(tester, LogicalKeyboardKey.backspace);+ }++ await backspace(TextSelection.collapsed(offset: 'a👩🏽💻'.length));+ expect(scenario.box.query, 'ab');+ await backspace(const TextSelection(baseOffset: 0, extentOffset: 1));+ expect(scenario.box.query, 'b');+ await backspace(const TextSelection.collapsed(offset: -1));+ expect(scenario.box.query, 'b');+ await backspace(const TextSelection.collapsed(offset: 0));+ expect(scenario.box.query, 'b');+ await backspace(const TextSelection.collapsed(offset: 1));+ expect(scenario.box.query, isEmpty);+ await backspace(const TextSelection.collapsed(offset: 0));+ expect(scenario.box.query, isEmpty);+ expect(scenario.creates, 0);+ },+ );++ testWidgets(+ 'a late browser return cannot change the focused row during launch',+ (tester) async {+ final browsing = Completer<void>();+ final scenario = await _mount(+ tester,+ git: false,+ onBrowse: (_) => browsing.future,+ );+ await tester.tap(_option(NewHarnessController.existingProjectId));+ await tester.pump();+ await key(tester, LogicalKeyboardKey.enter);+ await tester.tap(_option(NewHarnessController.browseId));+ await tester.pump();+ scenario.box.focusField(NewHarnessField.launch);+ final connection = scenario.connections['m']!;+ connection.starting = Completer();+ final creating = scenario.box.create();+ await tester.pump();+ expect(scenario.box.busy, isTrue);+ browsing.complete();+ await tester.pump();+ expect(scenario.box.field, NewHarnessField.launch);+ connection.starting!.complete(+ connection.created(connection.starts.single),+ );+ await tester.pump();+ expect(await creating, NewHarnessOutcome.created);+ expect(connection.starts, hasLength(1));+ await tester.pumpAndSettle();+ },+ );++ for (final (size, scale) in [+ (const Size(1000, 700), 1.0),+ (const Size(520, 700), 1.0),+ (const Size(800, 1000), 2.0),+ ]) {+ testWidgets('wrapped launch errors remain visible at $size, $scale', (+ tester,+ ) async {+ final scenario = await _mount(+ tester,+ git: false,+ editProject: false,+ size: size,+ scale: scale,+ );+ scenario.box.warn(+ 'Could not create this worktree. The selected folder is not writable. Choose another project or repair its permissions before trying again.',+ );+ await tester.pumpAndSettle();+ final notice = find.byKey(const ValueKey('new-harness-status'));+ final surface = tester.getRect(+ find.byKey(const ValueKey('new-harness-surface')),+ );+ final bounds = tester.getRect(notice);+ expect(notice.hitTestable(), findsOneWidget);+ expect(bounds.bottom, lessThanOrEqualTo(surface.bottom));+ expect(bounds.top, greaterThan(surface.top));+ expect(scenario.creates, 0);+ expect(tester.takeException(), isNull);+ });+ }++ testWidgets('expanded fields scroll into view in a short window', (+ tester,+ ) async {+ await _mount(tester, editProject: false, size: const Size(760, 180));+ await openLaunchRow(tester, 'advanced');+ await focusLaunchRow(tester, 'start');+ await tester.pumpAndSettle();+ expect(_field('start').hitTestable(), findsOneWidget);+ await key(tester, LogicalKeyboardKey.arrowDown);+ await tester.pumpAndSettle();+ expect(_field('agent').hitTestable(), findsOneWidget);+ expect(tester.takeException(), isNull);+ });+for (final (size, scale) in [(const Size(520, 520), 1.0),(const Size(600, 680), 2.0),diff --git a/desktop/test/new_harness_start_failures_test.dart b/desktop/test/new_harness_start_failures_test.dartindex a487ebcb9..295f0e22d 100644--- a/desktop/test/new_harness_start_failures_test.dart+++ b/desktop/test/new_harness_start_failures_test.dart@@ -80,7 +80,10 @@ 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 app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -124,7 +127,10 @@ void main() {'an unsupported Store catalog is actionable and does not launch',() async {final connection = _Connection()..catalogUnavailable = true;- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -149,7 +155,10 @@ void main() {'dismissal during installation cannot launch after the dialog is disposed',() async {final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final box = NewHarnessController(app,machineId: 'm',@@ -171,7 +180,10 @@ void main() {'an oversized carried task is retained and can be shortened before retry',() async {final connection = _Connection();- final app = createApp(connectionForTest: (_) => connection);+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );final task = 'x' * (kFirstTaskMaxLength + 1);final box = NewHarnessController(app,diff --git a/desktop/test/open_picker_rendering_test.dart b/desktop/test/open_picker_rendering_test.dartindex 59aa5a33b..62642c24a 100644--- a/desktop/test/open_picker_rendering_test.dart+++ b/desktop/test/open_picker_rendering_test.dart@@ -46,6 +46,10 @@ void main() {addTearDown(map.dispose);addTearDown(projects.dispose);await seedPreviews(app);+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');app.adoptSessionForTest(terminal('a69', []));tester.view.devicePixelRatio = 1;tester.view.physicalSize = const Size(1280, 800);diff --git a/desktop/test/support/launch_menu.dart b/desktop/test/support/launch_menu.dartindex 47c1c1f87..582f24036 100644--- a/desktop/test/support/launch_menu.dart+++ b/desktop/test/support/launch_menu.dart@@ -32,6 +32,8 @@ Future<void> focusLaunchRow(WidgetTester tester, String name) async {await tester.pump();}if (target == 'machine') {+ // Existing project-flow tests use this to choose the folder's machine.+ // The direct Machine row is exercised separately in the grid tests.await openLaunchRow(tester, 'project');await tester.tap(find.byKey(const ValueKey('new-harness-option-project:existing')),diff --git a/desktop/test/swarm_commands_test.dart b/desktop/test/swarm_commands_test.dartindex 3208f08a2..575edd472 100644--- a/desktop/test/swarm_commands_test.dart+++ b/desktop/test/swarm_commands_test.dart@@ -21,6 +21,10 @@ void main() {newHarnessOpensInBox = true;addTearDown(() => newHarnessOpensInBox = previousEntry);final app = createApp();+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');final frames = <TerminalBinaryFrame>[];final pane = app.adoptSessionForTest(terminal('a0', frames));addTearDown(app.dispose);diff --git a/desktop/test/terminal_ui_typography_test.dart b/desktop/test/terminal_ui_typography_test.dartindex f46958f6b..b0a60b968 100644--- a/desktop/test/terminal_ui_typography_test.dart+++ b/desktop/test/terminal_ui_typography_test.dart@@ -264,6 +264,10 @@ void main() {'tabs, welcome, and setup screens follow terminal zoom while general UI keeps its scale',(tester) async {final app = createApp();+ app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ await app.agentPreference.remember('codex');+ await app.projectHistory.select('m', '/work/openharness');final map = MemoryKeymap();addTearDown(app.dispose);addTearDown(map.dispose);@@ -288,17 +292,15 @@ void main() {await key(tester, LogicalKeyboardKey.keyN, cmd: true);expect(find.byType(NewHarnessForm), findsOneWidget);final box = checkText(tester, atLeast: 1);- expect(- tester.widget<Text>(find.text('[ New Harness ]')).style!.fontSize,- 18,+ final start = find.descendant(+ of: find.byKey(const ValueKey('new-harness-field-start')),+ matching: find.text('New Harness'),);+ expect(tester.widget<Text>(start).style!.fontSize, 18);selectFont(22);await tester.pumpAndSettle();expectSameSizes(box, checkText(tester, atLeast: 1));- expect(- tester.widget<Text>(find.text('[ New Harness ]')).style!.fontSize,- 22,- );+ expect(tester.widget<Text>(start).style!.fontSize, 22);await key(tester, LogicalKeyboardKey.escape);for (final shortcut in [LogicalKeyboardKey.keyP,diff --git a/desktop/test/workspace_start_guide_test.dart b/desktop/test/workspace_start_guide_test.dartindex 53ed1707b..454005304 100644--- a/desktop/test/workspace_start_guide_test.dart+++ b/desktop/test/workspace_start_guide_test.dart@@ -155,6 +155,22 @@ Future<void> _mount(}void main() {+ Future<void> chooseProject(WidgetTester tester) async {+ await openLaunchRow(tester, 'agent');+ await typeHarnessQuery(tester, 'Codex');+ await key(tester, LogicalKeyboardKey.enter);+ await openLaunchRow(tester, 'project');+ await tester.tap(+ find.byKey(+ ValueKey('new-harness-option-${NewHarnessController.newProjectId}'),+ ),+ );+ await tester.pumpAndSettle();+ await key(tester, LogicalKeyboardKey.enter);+ await typeHarnessQuery(tester, 'first-project');+ await key(tester, LogicalKeyboardKey.enter);+ }+setUp(() {newHarnessOpensInBox = true;});@@ -183,6 +199,7 @@ void main() {expect(find.byType(NewHarnessForm), findsOneWidget);expect(app.launches, isEmpty);expect(journey.completed(OnboardingStep.harnesses), isFalse);+ await chooseProject(tester);if (keyboard) {await startHarness(tester);} else {@@ -192,7 +209,7 @@ void main() {}await tester.pumpAndSettle();expect(app.launches, hasLength(1));- expect(app.launches.single.project?.isGenerated, isTrue);+ expect(app.launches.single.project?.folderName, 'first-project');expect(find.byType(NewHarnessForm), findsNothing);expect(find.byType(TerminalView), findsOneWidget);expect(@@ -241,6 +258,7 @@ void main() {await key(tester, LogicalKeyboardKey.keyN, cmd: true);await tester.pumpAndSettle();final start = find.byKey(const ValueKey('new-harness-field-start'));+ await chooseProject(tester);await startHarness(tester);await tester.pump();expect(find.text('Starting harness…'), findsOneWidget);@@ -268,6 +286,7 @@ void main() {await tester.tap(find.byKey(const ValueKey('welcome-agent.new')));await tester.pumpAndSettle();app.creation = null;+ await chooseProject(tester);await tester.tap(start);await tester.pumpAndSettle();expect(app.launches, hasLength(2));diff --git a/desktop/tool/check_new_harness_coverage.mjs b/desktop/tool/check_new_harness_coverage.mjsnew file mode 100644index 000000000..179a8778b--- /dev/null+++ b/desktop/tool/check_new_harness_coverage.mjs@@ -0,0 +1,24 @@+// Run the desktop launch tests with --coverage before checking both complete modules.+import { readFileSync } from 'node:fs'++const expected = new Set([+ 'lib/state/new_harness.dart',+ 'lib/widgets/new_harness_form.dart',+])+let total = 0+for (const record of readFileSync(process.argv[2] ?? 'coverage/lcov.info', 'utf8').split('end_of_record')) {+ const path = record.match(/SF:(.*)/)?.[1]+ const name = [...expected].find(name => path === name || path?.endsWith(`/${name}`))+ if (!name) continue+ expected.delete(name)+ const found = Number(record.match(/LF:(\d+)/)?.[1])+ const hit = Number(record.match(/LH:(\d+)/)?.[1])+ const missing = [...record.matchAll(/^DA:(\d+),0$/gm)].map(match => match[1])+ if (!found || hit !== found || missing.length) {+ throw new Error(`${name}: ${hit}/${found} lines; expected 100%. Uncovered: ${missing.join(', ')}`)+ }+ console.log(`${name}: ${hit}/${found} lines (100%)`)+ total += found+}+if (expected.size) throw new Error(`Missing New Harness coverage: ${[...expected].join(', ')}`)+console.log(`New Harness: ${total}/${total} executable lines (100%) across the entire form and controller.`)