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
Restore Add search when agent creation is cancelled
deef7f64a8fd140
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 81c50c1ca..a03cd6360 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -520,6 +520,7 @@ class _SwarmScreenState extends State<SwarmScreen> {bool chooseFolderFirst = false,bool cloneRepositoryFirst = false,String returnToAddQuery = '',+ ({SwarmSearchDraft search, TextEditingValue editing})? returnToAdd,}) async {final targetId = swarmId ?? app.activeSwarmId;NewAgentDialogResult? result;@@ -625,11 +626,22 @@ class _SwarmScreenState extends State<SwarmScreen> {offerFindExisting: true,);});- if (!mounted || result != NewAgentDialogResult.findExisting) return;+ final findingExisting = result == NewAgentDialogResult.findExisting;+ final returningToAdd = result == null && returnToAdd != null;+ if (!mounted || (!findingExisting && !returningToAdd)) return;// The pop result arrives before the screen observes its current route.// Let that frame release modal keyboard ownership before opening Add.await WidgetsBinding.instance.endOfFrame;- if (!mounted || !_routeIsCurrent) return;+ if (!mounted ||+ !_routeIsCurrent ||+ _dialogOpen ||+ _spokenPaletteOpen ||+ _search != null) {+ return;+ }+ // Cancel restores the prior picker only while its swarm remains current.+ // An explicit Find existing action can return to the original destination.+ if (returningToAdd && app.activeSwarmId != targetId) return;final targetExists = app.swarms.any((swarm) => swarm.id == targetId);final splitChanged = split != null && !app.isPaneSplitCurrent(split);if (!targetExists || splitChanged) {@@ -647,7 +659,15 @@ class _SwarmScreenState extends State<SwarmScreen> {if (app.activeSwarmId != targetId) {app.selectSwarm(targetId, attachPending: false);}- _openSearch(adding: true, split: split, query: returnToAddQuery);+ _openSearch(+ adding: true,+ split: split,+ query: returnToAddQuery,+ draft: returnToAdd?.search,+ );+ if (returnToAdd != null && _search?.targetId == targetId) {+ _searchText.value = returnToAdd.editing;+ }}Future<void> _splitAgent(PaneResizeAxis axis) async {@@ -706,6 +726,7 @@ class _SwarmScreenState extends State<SwarmScreen> {bool adding = false,PaneSplitRequest? split,String query = '',+ SwarmSearchDraft? draft,}) {if (_search != null ||!mounted ||@@ -732,6 +753,7 @@ class _SwarmScreenState extends State<SwarmScreen> {catalog: _searchCatalog,locations: _locationCatalog,)..setQuery(query);+ if (draft != null) _search!.restoreDraft(draft);_search!.addListener(_syncSearch);_searchOverlay = OverlayEntry(builder: _buildSearchOverlay);Overlay.of(context).insert(_searchOverlay!);@@ -815,11 +837,22 @@ class _SwarmScreenState extends State<SwarmScreen> {final target = search.targetId;final split = search.split;final query = search.query;+ final draft = search.adding+ ? (+ search: search.draft,+ editing: _searchText.value.copyWith(composing: TextRange.empty),+ )+ : null;// Let the creation dialog remember the original focus for Cancel. Blocking// canvas focus during the picker intentionally cleared route focus history._closeSearch();FocusManager.instance.applyFocusChangesIfNeeded();- await _newAgent(swarmId: target, split: split, returnToAddQuery: query);+ await _newAgent(+ swarmId: target,+ split: split,+ returnToAddQuery: query,+ returnToAdd: draft,+ );}void _addFromNavigation() {diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex ef15211c4..51ae5f553 100644--- a/desktop/lib/state/swarm_search.dart+++ b/desktop/lib/state/swarm_search.dart@@ -8,6 +8,20 @@ import 'pane_arrangement.dart';import 'swarm_catalog.dart';import 'swarm_navigation.dart';+/// An in-memory Add draft for a temporary detour into New agent. Membership and+/// availability are revalidated against a fresh catalog when the picker returns.+class SwarmSearchDraft {+ const SwarmSearchDraft._(+ this.targetId,+ this.query,+ this.selectedId,+ this.checked,+ );+ final String targetId, query;+ final String? selectedId;+ final List<SwarmDestination> checked;+}+/// One search session, shared by the native/Flutter input and its results./// Keystrokes only filter the cached catalog; they never query a machine.class SwarmSearchController extends ChangeNotifier {@@ -66,6 +80,29 @@ class SwarmSearchController extends ChangeNotifier {bool get multiSelect => adding && split == null && !isCommandMode;bool get hasSelection => multiSelect && _checked.isNotEmpty;+ SwarmSearchDraft get draft =>+ SwarmSearchDraft._(targetId, query, selected?.id, checked);++ void restoreDraft(SwarmSearchDraft draft) {+ if (!adding || draft.targetId != targetId) return;+ query = draft.query;+ _selectedId = draft.selectedId;+ cursor = 0;+ _checked.clear();+ if (split == null) {+ final current = {for (final row in _catalog) row.id: row};+ for (final row in draft.checked) {+ if (!_presentIds.contains(row.id)) {+ // Keep unavailable choices visible for removal instead of silently+ // accepting a smaller set. Activation still checks the entire set.+ _checked[row.id] = current[row.id] ?? row;+ }+ }+ }+ _filter();+ notifyListeners();+ }+int get capacity {final target = app.swarms.where((swarm) => swarm.id == targetId)diff --git a/desktop/test/agent_creation_recovery_test.dart b/desktop/test/agent_creation_recovery_test.dartindex e7fffd3fb..a9d73a192 100644--- a/desktop/test/agent_creation_recovery_test.dart+++ b/desktop/test/agent_creation_recovery_test.dart@@ -5,11 +5,14 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/state/app_state.dart';+import 'package:harness/shortcuts/app_keymap.dart';import 'package:harness/stats/harness_stats.dart';import 'package:harness/terminal/terminal_binary.dart';import 'package:harness/widgets/new_agent_dialog.dart';+import 'package:harness/widgets/swarm_switcher.dart';import 'package:harness/ws/ws_conn.dart';+import 'keymap_runtime_test.dart' as runtime;import 'swarm_state_test.dart' show createApp;import 'swarm_screen_test.dart' show mount, terminal;import 'swarm_interactions_test.dart' show chord;@@ -84,6 +87,179 @@ Future<void> _timeOut(}void main() {+ for (final entry in ['Add', 'Split right', 'Split down']) {+ testWidgets('cancel New agent returns to the same $entry search', (+ tester,+ ) async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ app.stateOf('m')!.localOnly = true;+ final input = <TerminalBinaryFrame>[];+ final pane = app.adoptSessionForTest(terminal('a0', input));+ final target = app.activeSwarm;+ final keymap = AppKeymap();+ await runtime.mount(tester, app, keymap);+ final field = find.byKey(const ValueKey('swarm-search-input'));+ if (entry == 'Add') {+ await chord(tester, LogicalKeyboardKey.keyN);+ } else {+ await chord(tester, LogicalKeyboardKey.keyP);+ await tester.enterText(field, '> $entry');+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ }+ await tester.enterText(field, 'Agent 1');+ await tester.pump();+ if (entry == 'Add') {+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);+ await tester.pump();+ expect(find.text('1 selected'), findsOneWidget);+ }+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.pump();+ final before = tester+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))+ .search;+ final selected = before.selected!.id;+ final checked = before.checked.map((row) => row.id).toList();+ final editing = tester.widget<TextField>(field).controller!;+ editing.selection = const TextSelection(baseOffset: 0, extentOffset: 5);+ final value = editing.value;+ await tester.tap(find.byKey(const ValueKey('swarm-search-new-agent')));+ await tester.pumpAndSettle();+ expect(find.byType(AlertDialog), findsOneWidget);+ if (entry == 'Split down') {+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ } else {+ await tester.tap(find.text('Cancel'));+ }+ await tester.pumpAndSettle();+ expect(field, findsOneWidget);+ final restored = tester+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))+ .search;+ expect(tester.widget<TextField>(field).controller!.value, value);+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);+ expect(restored.selected!.id, selected);+ expect(restored.checked.map((row) => row.id), checked);+ expect(restored.targetId, target.id);+ if (entry != 'Add') expect(restored.primaryAction, entry);+ expect(app.activeSwarm, same(target));+ expect(target.panes, [pane]);+ expect(connection.calls, isEmpty);+ expect(input, isEmpty);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(field, findsNothing);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ keymap.dispose();+ });+ }++ for (final change in ['switched swarm', 'closed swarm', 'changed split']) {+ testWidgets('Cancel does not restore Add into a $change', (tester) async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ app.stateOf('m')!.localOnly = true;+ final input = <TerminalBinaryFrame>[];+ app.adoptSessionForTest(terminal('a0', input));+ final original = app.activeSwarm;+ await mount(tester, app);+ final field = find.byKey(const ValueKey('swarm-search-input'));+ if (change == 'changed split') {+ await chord(tester, LogicalKeyboardKey.keyP);+ await tester.enterText(field, '> split right');+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ } else {+ await chord(tester, LogicalKeyboardKey.keyN);+ }+ await tester.tap(find.byKey(const ValueKey('swarm-search-new-agent')));+ await tester.pumpAndSettle();+ if (change == 'changed split') {+ app.adoptSessionForTest(terminal('a1', input));+ } else {+ app.newSwarm();+ if (change == 'closed swarm') await app.closeSwarm(original.id);+ }+ final current = app.activeSwarmId;+ await tester.pump();+ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();+ expect(field, findsNothing);+ expect(app.activeSwarmId, current);+ if (change == 'changed split') {+ expect(find.textContaining('split changed'), findsOneWidget);+ }+ expect(connection.calls, isEmpty);+ expect(input, isEmpty);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+ }++ for (final outcome in ['created', 'uncertain']) {+ testWidgets('$outcome creation keeps the Add return path deliberate', (+ tester,+ ) async {+ final files = FileSelectorPlatform.instance;+ FileSelectorPlatform.instance = _FolderPicker();+ addTearDown(() => FileSelectorPlatform.instance = files);+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ app.stateOf('m')!.localOnly = true;+ final input = <TerminalBinaryFrame>[];+ final existing = app.adoptSessionForTest(terminal('a0', input));+ await mount(tester, app);+ await chord(tester, LogicalKeyboardKey.keyN);+ final field = find.byKey(const ValueKey('swarm-search-input'));+ await tester.enterText(field, 'Agent 12');+ await tester.pump();+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);+ await tester.pump();+ expect(find.text('1 selected'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('swarm-search-new-agent')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const Key('new-agent-folder')));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(FilledButton, 'Create agent'));+ await tester.pump();+ final create = connection.calls.single;+ if (outcome == 'created') {+ create.created();+ } else {+ create.reply.completeError(const WsRequestTimeout('agent_create'));+ }+ // A newly created pane is still waiting on this fixture's terminal+ // handshake; its loading indicator intentionally does not settle.+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 100));+ if (outcome == 'created') {+ expect(find.byType(AlertDialog), findsNothing);+ expect(field, findsNothing);+ expect(app.panes.map((pane) => pane.agentId), ['a0', 'created']);+ } else {+ await tester.tap(find.text('Find existing agent…'));+ await tester.pumpAndSettle();+ expect(tester.widget<TextField>(field).controller!.text, 'Agent 12');+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);+ expect(find.text('1 selected'), findsOneWidget);+ expect(app.panes, [existing]);+ }+ expect(connection.calls.map((call) => call.type), ['agent_create']);+ expect(input, isEmpty);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+ }+for (final change in ['unchanged','welcome',diff --git a/desktop/test/swarm_multi_add_test.dart b/desktop/test/swarm_multi_add_test.dartindex 3e896ea5d..42675474b 100644--- a/desktop/test/swarm_multi_add_test.dart+++ b/desktop/test/swarm_multi_add_test.dart@@ -85,6 +85,40 @@ void main() {},);+ test(+ 'returning Add drafts revalidate membership, missing agents and target',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ final target = app.activeSwarm;+ final search = SwarmSearchController(app, [], adding: true);+ search.setQuery('Agent 0');+ search.toggle();+ search.setQuery('Agent 1');+ search.toggle();+ final draft = search.draft;+ search.dispose();+ app.adoptSessionForTest(terminal('a0', []));+ app.machineStates['m']!.agents.removeWhere((agent) => agent.id == 'a1');+ final restored = SwarmSearchController(app, [], adding: true)+ ..restoreDraft(draft);+ addTearDown(restored.dispose);+ expect(restored.checked.map((row) => row.agentId), ['a1']);+ expect(restored.query, 'Agent 1');+ expect(restored.canAccept, isFalse);+ expect(restored.submit(), isNull);+ expect(restored.unavailableMessage, contains('unavailable'));+ expect(target.panes.map((pane) => pane.agentId), ['a0']);+ app.newSwarm();+ final elsewhere = SwarmSearchController(app, [], adding: true)+ ..restoreDraft(draft);+ addTearDown(elsewhere.dispose);+ expect(elsewhere.checked, isEmpty);+ expect(elsewhere.query, isEmpty);+ expect(app.panes, isEmpty);+ },+ );+test('a stale selection cannot partially add its remaining available agents',() async {diff --git a/desktop/test/swarm_split_test.dart b/desktop/test/swarm_split_test.dartindex 6d9c345df..af34026aa 100644--- a/desktop/test/swarm_split_test.dart+++ b/desktop/test/swarm_split_test.dart@@ -200,7 +200,7 @@ void main() {}testWidgets(- 'split command inherits folder and machine, and cancel keeps the workspace',+ 'split creation returns through Add before restoring terminal input',(tester) async {final connection = _Creation();final app = createApp(connectionForTest: (_) => connection);@@ -235,10 +235,15 @@ void main() {expect(app.panes, [pane]);await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump();+ await tester.pump();expect(find.byType(AlertDialog), findsNothing);expect(app.panes, [pane]);expect(connection.calls, isNot(contains('agent_create')));expect(frames, isEmpty);+ expect(find.byKey(const ValueKey('swarm-search-input')), findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);await tester.pump(const Duration(milliseconds: 10));expect(frames.single.bytes, [27, 91, 67]);diff --git a/docs/harness-agent-creation.md b/docs/harness-agent-creation.mdindex b946a2c74..52ff962ff 100644--- a/docs/harness-agent-creation.md+++ b/docs/harness-agent-creation.md@@ -70,6 +70,20 @@ and asks the user to choose a destination again. The modal handoff waits forthe route to return keyboard ownership. An empty tab appearing behind thedialog cannot take that focus for its welcome search.+When creation started from centered Add or a split, **Cancel** or **Escape** now+returns to that picker with its query, text selection, highlighted result and+checked agents intact. **Find existing agent…** restores those choices too.+Successful creation keeps the picker closed. Ordinary cancellation never selects+a different swarm to resurrect its picker; a changed split gets an explanation+instead of a different insertion position. A second Escape closes Add and+restores the original terminal's keyboard input.++The restored draft reads the current catalog. Agents already added to the target+leave the checked list, and missing choices stay visible for explicit removal.+It cannot silently submit a smaller set, exceed capacity or restore its choices+into a different swarm. The draft exists only for this temporary detour; it does+not persist a pending creation receipt or survive an app restart.+Recovery opens the returned agent in the original swarm/position and counts thecreation once. If that destination changed or closed, the runtime remains inthe catalog for Add agent without opening a different tab or deleting anything.@@ -107,3 +121,17 @@ The normal arm64 Release build also passes with the production entry point at`/private/tmp/harness-find-created-release/Build/Products/Release/Harness.app`;log: `/private/tmp/harness-find-created-release.log`. The app was not launchedand the user's running app and agents were not restarted.++The subsequent Add-return continuation passes 76 affected workflow checks and+one real-font render check at minimum window size and normal/2× text. Nine new+checks cover cancellation, successful/uncertain creation, stale destinations+and selection revalidation. Three reproduced the original loss of the picker;+the split input check also confirms the next key reaches the original terminal+after Add is dismissed. Analysis has no errors/warnings and 14 existing infos.+Logs: `/private/tmp/harness-add-return-final-{tests,analyze}.log`. These use+synthetic agents/replies, including the production Dart keyboard dispatcher;+native Shift-Enter still needs direct verification. Inline New swarm retains+its text but still drops optional checked selections on focus loss.+The normal arm64 Release build succeeds at+`/private/tmp/harness-add-return-release/Build/Products/Release/Harness.app`;+log: `/private/tmp/harness-add-return-release.log`. It was not launched.diff --git a/docs/harness-v2-handoff.md b/docs/harness-v2-handoff.mdindex 9cd80e384..60cd225e9 100644--- a/docs/harness-v2-handoff.md+++ b/docs/harness-v2-handoff.md@@ -40,6 +40,14 @@ query back to Add and retains its original swarm/split. A closed swarm or changesplit gets an explanation instead of redirecting the addition. A backgroundempty tab cannot take focus from the open creation dialog.+Opening **New agent** from centered Add or either split now preserves that+picker for cancellation. Cancel/Escape restores the query, text selection,+highlighted result, checked agents and original split. **Find existing agent…**+also preserves that draft. A successful creation leaves Add closed. Cancel does+not return to a swarm that is no longer current; stale splits get an explanation.+Returning revalidates membership/capacity and keeps unavailable checked agents+visible for removal. This is an in-memory picker draft, not saved creation intent.+Browser sign-in now offers **Open browser**, **Copy link** and immediate **Cancel**while waiting for authorization. Reopening uses the current link without startinganother CLI login. Cancel works even before the CLI finishes starting; late URLs,@@ -87,7 +95,21 @@ Research must lead to justified improvements, not feature accumulation.- Continue on **`main`**, tracking `origin/main`. The user's latest instructionis to work, commit, and push directly on main from now on. This supersedesthe earlier preference for creating a fresh feature branch after each merge.-- First-launch installation passes 59 affected workflow checks and one real-font+- The Add-to-New-agent return flow passes 76 affected workflow checks and one+ real-font render check (77 total). Nine new checks cover cancel/Escape,+ successful and uncertain creation, checked agents, changed targets and draft+ revalidation. The three cancellation regressions failed before the fix. The+ existing split check now verifies both return to Add and the next terminal+ key after dismissing Add. Analysis has zero errors/warnings and 14 existing+ infos. Logs: `/private/tmp/harness-add-return-final-{tests,analyze}.log`.+ The isolated minimum-size/2× text renders preserve the returned selection and+ preview. Shift-Enter passes through the production Dart keyboard dispatcher+ in those fixtures; that is not direct verification of the user's native issue.+ The normal arm64 Release build succeeds at+ `/private/tmp/harness-add-return-release/Build/Products/Release/Harness.app`;+ log: `/private/tmp/harness-add-return-release.log`. It was not launched and no+ real agent was created/stopped. Benchmarking stays deferred.+- **`3ab66ca`** fixes first-launch installation, passing 59 affected workflow checks and one real-fontrender check (60 total). Six new regressions cover minimum-size/2× text actionvisibility, Enter/retry, manual-mode focus and read-only retry, and diagnostics.The original action-visibility and Enter regressions failed before the fix.@@ -569,6 +591,10 @@ that its isolated window can become active/key.CLI and a changed original swarm. A status check must remain read-only. Adurable desktop pending-creations list and crash-window registry reconciliationare still future work; the current dialog cannot resume its intent after closure.+ The centered Add/split picker now survives a New agent cancellation with its+ selection intact. The inline New swarm field retains text, but its optional+ checked selection is still discarded when focus leaves; improve that+ continuation without changing immediate single-agent startup.3. **Recheck fresh terminal positioning and real workflows** on disposablelocal/remote agents: startup, delayed snapshots, resizing, returning to ascrolled view, reconnect, paste, selection, and IME.diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdindex 6538c6518..56393452c 100644--- a/docs/harness-v2-progress.md+++ b/docs/harness-v2-progress.md@@ -6,6 +6,23 @@ Updated 2026-09-14 after integrating the continuation into main. This is a worki## Continue directly on main+- Preserved Add while trying New agent. Cancel/Escape from centered Add or either+ split returns to the same query, caret/selection, highlighted result and+ checked agents. Find existing after an uncertain creation also retains those+ choices. Successful creation opens the new agent without reopening Add.+ Changed/closed targets do not redirect cancellation, and stale splits are+ explained. Fresh catalog validation drops already-added memberships while+ leaving missing checked agents visible for removal. The affected workflow+ suite passes 76 checks plus one real-font render check at 880×560 and 2× text;+ analysis has zero errors/warnings and 14 existing infos. Logs:+ `/private/tmp/harness-add-return-final-{tests,analyze}.log`. Nine new checks+ cover the return path and recovery boundaries; the first three reproduced+ the lost-search behavior. A second Escape returns actual fixture keyboard+ input to the original terminal. Native Shift-Enter and inline New swarm's+ optional selection continuity remain to be verified/improved; benchmarking+ stays deferred. The normal arm64 Release build succeeds at+ `/private/tmp/harness-add-return-release/Build/Products/Release/Harness.app`;+ log: `/private/tmp/harness-add-return-release.log`. It was not launched.- Fixed first-launch installation at minimum window size: Install/Retry/Checkagain stay visible outside the scrollable tool list, and Enter can start orretry the current step. Manual Retry now performs a read-only check instead of