Skip to content

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

Reduce Add picker rebuilds and preserve keyboard focus

deee71e0cabf5ef
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index ff5c469af..b60d55de7 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -71,11 +71,17 @@ class _SwarmScreenState extends State<SwarmScreen> {
SwarmProjectStore(storage: kUnderTest ? null : HarnessFileStore.shared);
StreamSubscription<SpokenTaskRequest>? _spokenTasks;
final _shellFocus = FocusNode(debugLabel: 'Swarm shell');
+ final _canvasFocus = FocusNode(
+ debugLabel: 'Swarm canvas',
+ canRequestFocus: false,
+ skipTraversal: true,
+ );
final _navigation = SwarmNavigationHistory();
final _searchText = TextEditingController();
final _searchFocus = FocusNode(debugLabel: 'Search agents and swarms');
SwarmSearchController? _search;
OverlayEntry? _searchOverlay;
+ (String, bool)? _searchHeaderState;
FocusNode? _searchReturnFocus;
bool _spokenPaletteOpen = false;
bool _dialogOpen = false;
@@ -150,6 +156,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_search?.dispose();
_searchFocus.dispose();
_searchText.dispose();
+ _canvasFocus.dispose();
_shellFocus.dispose();
unawaited(_spokenTasks?.cancel());
if (_native) {
@@ -676,6 +683,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
? null
: FocusManager.instance.primaryFocus;
if (_native) _preparePaneFocus();
+ // Search is an overlay, so late pane attachment needs an explicit focus
+ // boundary to keep its programmatic focus request out of the picker.
+ _canvasFocus.descendantsAreFocusable = false;
_search = SwarmSearchController(
app,
adding ? _navigation.recent : _navigation.recentLocations,
@@ -720,17 +730,27 @@ class _SwarmScreenState extends State<SwarmScreen> {
selection: TextSelection.collapsed(offset: search.query.length),
);
}
- _searchOverlay?.markNeedsBuild();
+ // Results listen to their controller directly. Rebuilding the entire
+ // overlay on every arrow also rebuilt the unchanged text editor/button.
+ final header = (search.hint, search.canCreate);
+ if (_searchHeaderState != header) {
+ _searchHeaderState = header;
+ _searchOverlay?.markNeedsBuild();
+ }
}
void _closeSearch({bool restoreFocus = true}) {
if (_search == null) return;
+ // Enable the chosen terminal synchronously, before activation requests its
+ // focus and before the following frame rebuilds the canvas.
+ _canvasFocus.descendantsAreFocusable = true;
_searchOverlay?.remove();
_searchOverlay?.dispose();
_searchOverlay = null;
_search!.removeListener(_syncSearch);
_search!.dispose();
_search = null;
+ _searchHeaderState = null;
_searchText.clear();
_searchFocus.unfocus();
final previous = _searchReturnFocus;
@@ -758,7 +778,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (search == null || !search.canCreate) return;
final target = search.targetId;
final split = search.split;
- _closeSearch(restoreFocus: false);
+ // 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);
}
@@ -1246,67 +1269,73 @@ class _SwarmScreenState extends State<SwarmScreen> {
padding: app.panes.isEmpty
? EdgeInsets.zero
: const EdgeInsets.all(10),
- child: Stack(
- children: [
- Positioned.fill(
- child: PaneGrid(
- notifier: app,
- swarmMode: true,
- onSplit: (paneId, axis) {
- app.focusPane(paneId);
- unawaited(_splitAgent(axis));
- },
- empty: SwarmWelcome(
- key: ValueKey(app.activeSwarmId),
+ child: Focus.withExternalFocusNode(
+ focusNode: _canvasFocus,
+ includeSemantics: false,
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: PaneGrid(
notifier: app,
- projects: _projects.projects,
- onNewAgent: _newAgent,
- onChooseFirstFolder: () =>
- _newAgent(chooseFolderFirst: true),
- onCloneRepository: () =>
- _newAgent(cloneRepositoryFirst: true),
- onAgent: (entry) => _activateSearch(
- SwarmSearchSelection(
- SwarmDestination(
- id: agentDestinationId(
- entry.machineId,
- entry.agent.id,
+ swarmMode: true,
+ onSplit: (paneId, axis) {
+ app.focusPane(paneId);
+ unawaited(_splitAgent(axis));
+ },
+ empty: SwarmWelcome(
+ key: ValueKey(app.activeSwarmId),
+ notifier: app,
+ projects: _projects.projects,
+ onNewAgent: _newAgent,
+ onChooseFirstFolder: () =>
+ _newAgent(chooseFolderFirst: true),
+ onCloneRepository: () =>
+ _newAgent(cloneRepositoryFirst: true),
+ onAgent: (entry) => _activateSearch(
+ SwarmSearchSelection(
+ SwarmDestination(
+ id: agentDestinationId(
+ entry.machineId,
+ entry.agent.id,
+ ),
+ title: entry.agent.name,
+ detail: entry
+ .machine
+ .machine
+ .displayName,
+ swarmId: null,
+ current: false,
+ machineId: entry.machineId,
+ agentId: entry.agent.id,
+ engine: entry.agent.engine,
),
- title: entry.agent.name,
- detail:
- entry.machine.machine.displayName,
- swarmId: null,
- current: false,
- machineId: entry.machineId,
- agentId: entry.agent.id,
- engine: entry.agent.engine,
+ SwarmSearchAction.addHere,
),
- SwarmSearchAction.addHere,
+ app.activeSwarmId,
),
- app.activeSwarmId,
- ),
- searchField: SwarmInlineSearch(
- key: ValueKey(
- 'welcome-search:${app.activeSwarmId}',
+ searchField: SwarmInlineSearch(
+ key: ValueKey(
+ 'welcome-search:${app.activeSwarmId}',
+ ),
+ app: app,
+ projects: _projects,
+ recent: _navigation.recent,
+ commands: _searchCommands,
+ onChoose: _activateSearch,
+ onNewAgent: _newAgent,
),
- app: app,
- projects: _projects,
- recent: _navigation.recent,
- commands: _searchCommands,
- onChoose: _activateSearch,
- onNewAgent: _newAgent,
- ),
- onAddProject: _addProject,
- onLinkMachine: () => _dialog(
- () => showSwarmLinkDialog(context, app),
+ onAddProject: _addProject,
+ onLinkMachine: () => _dialog(
+ () => showSwarmLinkDialog(context, app),
+ ),
+ onMachine: _machine,
+ onProject: _project,
+ onProjectAgents: _projectAgents,
),
- onMachine: _machine,
- onProject: _project,
- onProjectAgents: _projectAgents,
),
),
- ),
- ],
+ ],
+ ),
),
),
],
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 49af1adda..6b764d8d4 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -290,6 +290,9 @@ class SwarmSearchResults extends StatefulWidget {
}
class _SwarmSearchResultsState extends State<SwarmSearchResults> {
+ // Keep a small set of recently built rows, not the whole search catalog.
+ // A new highlight only changes two rows; their neighbors keep their widgets.
+ final _rowWidgets = <String, ({Object presentation, Widget child})>{};
final _scroll = ScrollController();
double _rowHeight = 56;
bool _revealScheduled = false;
@@ -392,12 +395,44 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
itemExtent: _rowHeight,
itemBuilder: (context, index) {
final row = search.rows[index];
+ final highlighted = index == search.cursor;
+ final canSubmit = search.canSubmit(row);
+ final multiSelect = search.multiSelect;
+ final checked =
+ multiSelect && search.isChecked(row);
+ final canToggle =
+ multiSelect && search.canToggle(row);
+ final alreadyHere = search.alreadyHere(row);
+ final presentation = (
+ row,
+ search.query,
+ highlighted,
+ canSubmit,
+ multiSelect,
+ checked,
+ canToggle,
+ alreadyHere,
+ highlighted
+ ? (
+ search.canAccept,
+ search.actionLabel(row),
+ )
+ : null,
+ _rowHeight,
+ scale.scale(11),
+ grid.AppTheme.palette.value,
+ );
+ final previous = _rowWidgets.remove(row.id);
+ if (previous?.presentation == presentation) {
+ _rowWidgets[row.id] = previous!;
+ return previous.child;
+ }
final matches = searchResultMatches(row, terms);
- return ListTile(
+ final tile = ListTile(
key: ValueKey(row.id),
minTileHeight: _rowHeight,
- enabled: search.canSubmit(row),
- selected: index == search.cursor,
+ enabled: canSubmit,
+ selected: highlighted,
selectedColor: Colors.white,
hoverColor: Colors.transparent,
selectedTileColor: Colors.white.withValues(
@@ -412,17 +447,17 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
leading: Row(
mainAxisSize: MainAxisSize.min,
children: [
- if (search.multiSelect) ...[
+ if (multiSelect) ...[
SizedBox(
width: 28,
child: Tooltip(
- message: search.isChecked(row)
+ message: checked
? 'Deselect ${row.title}'
: 'Select ${row.title}',
child: Checkbox(
key: ValueKey('select:${row.id}'),
- value: search.isChecked(row),
- onChanged: search.canToggle(row)
+ value: checked,
+ onChanged: canToggle
? (_) {
search.toggle(row);
widget.onRefocus();
@@ -447,7 +482,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
? EngineMark(
engine: row.engine,
size: 22,
- enabled: search.canSubmit(row),
+ enabled: canSubmit,
)
: const SwarmIcon(
size: 22,
@@ -474,7 +509,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
color: Colors.white60,
),
),
- trailing: search.alreadyHere(row)
+ trailing: alreadyHere
? const Text(
'In this swarm',
style: TextStyle(
@@ -482,7 +517,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
color: Colors.white38,
),
)
- : search.adding && index == search.cursor
+ : search.adding && highlighted
? ConstrainedBox(
constraints: BoxConstraints(
maxWidth:
@@ -512,12 +547,20 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
color: Colors.white60,
),
),
- onTap: search.canSubmit(row)
+ onTap: canSubmit
? () => search.hasSelection
? search.toggle(row)
: _submit(row)
: null,
);
+ _rowWidgets[row.id] = (
+ presentation: presentation,
+ child: tile,
+ );
+ if (_rowWidgets.length > 48) {
+ _rowWidgets.remove(_rowWidgets.keys.first);
+ }
+ return tile;
},
),
),
diff --git a/desktop/test/benchmarks/swarm_add_benchmark.dart b/desktop/test/benchmarks/swarm_add_benchmark.dart
new file mode 100644
index 000000000..512aafc03
--- /dev/null
+++ b/desktop/test/benchmarks/swarm_add_benchmark.dart
@@ -0,0 +1,137 @@
+// Run explicitly with --concurrency=1 after other builds and tests finish.
+// Measures Flutter event handling and frame-pump CPU, not native/display latency.
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/swarm_search_input.dart';
+
+import '../swarm_screen_test.dart' show mount, terminal;
+import '../swarm_state_test.dart' show createApp;
+import 'swarm_benchmark.dart' show distribution;
+
+void main() {
+ testWidgets('Add picker keyboard and frame CPU with 2000 discovered agents', (
+ tester,
+ ) async {
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ app.machineStates['m']!
+ ..nodeOnline = true
+ ..agents = [
+ for (var i = 0; i < 2000; i++)
+ Agent(
+ id: 'a$i',
+ name: 'Agent ${i.toString().padLeft(4, '0')}',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'Project ${i % 50}',
+ cwd: '/work/project-${i % 50}',
+ branch: 'main',
+ ),
+ ),
+ ];
+ for (final i in [0, 1, 2, 3, 1999]) {
+ if (i == 1999) app.newSwarm(name: 'Current work');
+ final session = terminal('a$i', input);
+ session.terminal.write(
+ List.generate(
+ 1000,
+ (row) =>
+ '$row Recent work on agent $i. Useful context for choosing.\r\n',
+ ).join(),
+ );
+ app.adoptSessionForTest(session);
+ }
+ final target = app.activeSwarm;
+ final panes = [...target.panes];
+ const native = MethodChannel('harness/swarm_tabs');
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(native, (_) async => null);
+ addTearDown(() => messenger.setMockMethodCallHandler(native, null));
+ await mount(tester, app, nativeTabs: true);
+
+ Future<void> open() async {
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.meta);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyN);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.meta);
+ await tester.pump();
+ }
+
+ Future<void> close() async {
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 200));
+ }
+
+ Future<Map<String, num>> measure(
+ Future<void> Function(int) action, {
+ Future<void> Function()? after,
+ }) async {
+ final times = <int>[];
+ for (var i = -20; i < 100; i++) {
+ final watch = Stopwatch()..start();
+ await action(i + 20);
+ watch.stop();
+ if (i >= 0) times.add(watch.elapsedMicroseconds);
+ await after?.call();
+ }
+ return distribution(times);
+ }
+
+ Future<Map<String, int>> rebuilds(Future<void> Function() action) async {
+ final counts = <String, int>{};
+ debugOnRebuildDirtyWidget = (element, _) {
+ final type = element.widget.runtimeType.toString();
+ counts.update(type, (value) => value + 1, ifAbsent: () => 1);
+ };
+ try {
+ await action();
+ } finally {
+ debugOnRebuildDirtyWidget = null;
+ }
+ return counts;
+ }
+
+ final opening = await measure((_) => open(), after: close);
+ await open();
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ final controller = tester
+ .widget<SwarmSearchInput>(
+ find.ancestor(of: field, matching: find.byType(SwarmSearchInput)),
+ )
+ .search!;
+ const queries = ['Agent 0', 'Agent 00', 'Agent 000', 'Agent 0000'];
+ Future<void> query(int i) async {
+ await tester.enterText(field, queries[i % queries.length]);
+ await tester.pump();
+ }
+
+ final typing = await measure(query);
+ await query(0);
+ final typingRebuilds = await rebuilds(() => query(1));
+ expect(controller.selected!.agentId, 'a0');
+
+ Future<void> arrow() async {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ }
+
+ final arrows = await measure((_) => arrow());
+ final arrowRebuilds = await rebuilds(arrow);
+ expect(controller.cursor, greaterThan(0));
+ expect(input, isEmpty);
+ expect(app.activeSwarm, same(target));
+ expect(target.panes, panes);
+ expect(tester.takeException(), isNull);
+ debugPrint(
+ 'SWARM_BENCH ${jsonEncode({'kind': 'headless_debug_cpu', 'operation': 'add_picker_frame', 'agents': 2000, 'machines': 1, 'projects': 50, 'retainedTerminals': 5, 'scrollbackLinesPerTerminal': 1000, 'viewport': '1280x800', 'nativeBridge': 'stubbed', 'openAndFrame': opening, 'queryAndFrame': typing, 'arrowAndFrame': arrows, 'queryRebuilds': typingRebuilds, 'arrowRebuilds': arrowRebuilds})}',
+ );
+ await close();
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+}
diff --git a/desktop/test/swarm_search_render_test.dart b/desktop/test/swarm_search_render_test.dart
new file mode 100644
index 000000000..7e6899f38
--- /dev/null
+++ b/desktop/test/swarm_search_render_test.dart
@@ -0,0 +1,186 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/color_palette.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/swarm_search_input.dart';
+
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ testWidgets('Add arrow movement rebuilds only the changed result rows', (
+ tester,
+ ) async {
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a69', input));
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(field, 'Agent');
+ await tester.pump(const Duration(milliseconds: 200));
+ final search = tester
+ .widget<SwarmSearchInput>(
+ find.ancestor(of: field, matching: find.byType(SwarmSearchInput)),
+ )
+ .search!;
+ final previous = search.selected!.id;
+ var fields = 0;
+ var rows = 0;
+ debugOnRebuildDirtyWidget = (element, _) {
+ if (element.widget is TextField) fields++;
+ if (element.widget is ListTile) rows++;
+ };
+ try {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ } finally {
+ debugOnRebuildDirtyWidget = null;
+ }
+ expect(search.selected!.id, isNot(previous));
+ expect(
+ fields,
+ 0,
+ reason: 'Moving the highlight does not change the editor',
+ );
+ expect(rows, 2, reason: 'Only the old and new highlights changed');
+ final selected = tester.widget<ListTile>(
+ find.byKey(ValueKey(search.selected!.id)),
+ );
+ expect(selected.selected, isTrue);
+ expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(input, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
+ testWidgets(
+ 'cached Add rows keep selection through palette and text changes',
+ (tester) async {
+ final app = createApp();
+ final originalPalette = grid.AppTheme.palette.value;
+ addTearDown(() => grid.AppTheme.palette.value = originalPalette);
+ app.adoptSessionForTest(terminal('a69', []));
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await tester.pumpWidget(
+ grid.BrightnessScope(
+ child: MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(notifier: app, nativeTabs: false),
+ ),
+ ),
+ );
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(field, 'Agent');
+ await tester.pump();
+ final row = find.byKey(ValueKey(agentDestinationId('m', 'a0')));
+ final checkbox = find.byKey(
+ ValueKey('select:${agentDestinationId('m', 'a0')}'),
+ );
+ await tester.tap(checkbox);
+ await tester.pump();
+ expect(tester.widget<Checkbox>(checkbox).value, isTrue);
+ final height = tester.getSize(row).height;
+ grid.AppTheme.palette.value = HarnessPalette.ember;
+ await tester.pump();
+ expect(
+ tester.widget<Checkbox>(checkbox).activeColor,
+ HarnessPalette.ember.accent,
+ );
+ expect(tester.widget<Checkbox>(checkbox).value, isTrue);
+ tester.platformDispatcher.textScaleFactorTestValue = 2;
+ await tester.pump();
+ expect(tester.getSize(row).height, greaterThan(height));
+ expect(tester.widget<TextField>(field).controller!.text, 'Agent');
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(find.text('1 selected'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
+ testWidgets('Add header and cached rows respond when capacity changes', (
+ tester,
+ ) async {
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a69', input));
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ final create = find.byKey(const ValueKey('swarm-search-new-agent'));
+ await tester.enterText(field, 'Agent');
+ await tester.pump();
+ final editor = tester.widget<TextField>(field).controller;
+ expect(tester.widget<FilledButton>(create).onPressed, isNotNull);
+ for (var i = 0; i < AppNotifier.maxPanes - 1; i++) {
+ app.adoptSessionForTest(terminal('a$i', input));
+ }
+ app.dismissError(); // Publish the sessions assembled through the test seam.
+ await tester.pump();
+ expect(tester.widget<FilledButton>(create).onPressed, isNull);
+ final row = find.byKey(ValueKey(agentDestinationId('m', 'a0')));
+ expect(tester.widget<ListTile>(row).enabled, isFalse);
+ expect(
+ find.descendant(of: row, matching: find.text('In this swarm')),
+ findsOneWidget,
+ );
+ await app.closePane(app.panes.last.id);
+ await tester.pump();
+ expect(tester.widget<FilledButton>(create).onPressed, isNotNull);
+ expect(tester.widget<TextField>(field).controller, same(editor));
+ expect(editor!.text, 'Agent');
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(input, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
+ testWidgets('a completed background add cannot take the picker keyboard', (
+ tester,
+ ) async {
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', input));
+ app.newSwarm();
+ app.adoptSessionForTest(terminal('a69', input));
+ final target = app.activeSwarm;
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(field, 'Agent');
+ await tester.pump();
+ await app.addAgentToSwarm('m', 'a0', swarmId: target.id);
+ await tester.pump();
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ final search = tester
+ .widget<SwarmSearchInput>(
+ find.ancestor(of: field, matching: find.byType(SwarmSearchInput)),
+ )
+ .search!;
+ final previous = search.selected!.id;
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ expect(search.selected!.id, isNot(previous));
+ expect(input, isEmpty);
+ expect(target.panes, hasLength(2));
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+}
diff --git a/docs/harness-v2-handoff.md b/docs/harness-v2-handoff.md
index 19fde8b50..55442461d 100644
--- a/docs/harness-v2-handoff.md
+++ b/docs/harness-v2-handoff.md
@@ -30,6 +30,10 @@ Research must lead to justified improvements, not feature accumulation.
- Continue on **`main`**, tracking `origin/main`. The user's latest instruction
is to work, commit, and push directly on main from now on. This supersedes
the earlier preference for creating a fresh feature branch after each merge.
+- Add's frame continuation reuses unchanged result rows and keeps background
+ pane additions from taking the picker's Flutter focus. The full suite passes
+ 1,302 tests. Native fixture identity repair is saved in `fe42f2e`; `56f9d2a`
+ preserves the team's subsequent `9e2e4be` branding/update work.
- **`5f3ecae`** saves Cmd-N Add, the prominent New agent button, optional
multi-select, visible machine/project starters and the larger floating-button
inset. **`f514140`** preserves the team's concurrent main through `76a469b`,
@@ -242,18 +246,28 @@ unverified; do not infer them from these UI changes.
**Archived drafts:** both are superseded. The onboarding ideas were adapted into
the common page, without adding another first-tab-only component.
-**Latest verification:** after integrating the team's current main, 1,299
-desktop tests passed with one existing skip.
+**Latest verification:** the Add frame/focus continuation on integrated main
+passes 1,302 desktop tests with one existing skip.
Analyzer reports zero errors/warnings and 14 existing informational diagnostics
-(12 vendored, two inherited from main). Native checks passed 51 keymap decoder
+(12 vendored, two inherited from main). Logs:
+`/private/tmp/harness-add-render-{full-tests,final-analyze}.log`.
+The final macOS arm64 Release build also succeeds with
+`FLUTTER_TARGET=lib/main.dart`; log:
+`/private/tmp/harness-add-render-release-build.log`. The running app was not
+restarted, so do not claim its process has loaded these source changes.
+The preceding Add/shortcut integration passed 51 native keymap decoder
and 347 AppKit assertions, including the exported Dart keymap and hidden window
-layout. The normal macOS arm64 Release build succeeded with
+layout; no Swift changed in the frame/focus continuation. That integrated
+macOS arm64 Release build succeeded with
`FLUTTER_TARGET=lib/main.dart`. Synthetic real-font captures of the visible
starters, Add, multi-select and Navigate were reviewed at 1280×800 and 880×560
with 2× text. These do not measure native display latency or real reconnect.
Integrated test/native/analysis/build logs:
`/private/tmp/harness-revised-add-integrated-{tests,analyze,native,build}.log`.
The integrated Release build uses the new `ai.autonomous.harness` bundle ID.
+Add's new full-frame fixture observes an arrow-selection median of 4.714 ms
+versus 8.592 ms before the change, with 2,000 agents and five retained terminals.
+Opening did not improve. This is headless debug CPU time, not displayed latency.
Navigate/Add timings and their exact scope are in
[the performance record](harness-v2-performance.md). The new navigation catalog
build measured 0.188 ms median / 0.259 ms p95 in the earlier integrated run for
@@ -265,13 +279,14 @@ unmeasured. Log: `/private/tmp/harness-onboarding-main-benchmark.log`.
and [shared-swarm collaboration research](harness-collaboration-design.md), which
were existing uncommitted work. Collaboration is a separate proposal/prototype,
not implemented multiplayer or a prerequisite for finishing this desktop pass.
-The benchmark's product-name, process-identity and initial-responder compatibility
-issues are now repaired. Six isolated Python checks pass, and a read-only check
-recognizes the running renamed preview by its bundle ID. Preserve its isolation
-and foreground/key-window guards. The performance notes explain the earlier
-failed calibration; these tooling fixes provide no new latency measurements.
-The disposable Release build succeeded at
-`/private/tmp/harness-native-benchmark-x227eh35`. Its actual runner correctly
+The benchmark accepts the team's current public bundle ID while still producing
+a distinct Harness Benchmark app. Nine isolated Python checks pass. Preflight
+distinguishes installed copies from workspace builds by exact location as well
+as identity. Preserve its isolation and foreground/key-window guards. The
+performance notes explain the earlier failed calibration; these tooling fixes
+provide no new latency measurements. The identity-fix disposable Release build
+succeeded at `/private/tmp/harness-native-benchmark-7hv6voyr`, before the newer
+Add frame/focus changes. Rebuild it for current-source timing. Its runner correctly
refused to start while the workspace preview was running, writing no timing
result. The [performance record](harness-v2-performance.md) has the artifacts.
@@ -353,9 +368,10 @@ that its isolated window can become active/key.
using the repaired benchmark identity checks for the team's new
`ai.autonomous.harness` macOS bundle identifier (Linux now uses
`com.autonomous.harness` and executable `harness`). Nine isolation tests pass;
- a current disposable Release fixture is ready at
+ an identity-fix disposable Release fixture is available at
`/private/tmp/harness-native-benchmark-7hv6voyr`. Its runner correctly refuses
- the running workspace preview. A request to briefly close/reopen that preview
+ the running workspace preview. Rebuild it for the newer Add frame/focus
+ source. A request to briefly close/reopen that preview
for calibration is pending; elapsed time is not approval. No native samples
have been accepted. See the current performance record for exact artifacts.
Then close remaining visual/platform/release qualification gaps. Maintain
@@ -459,8 +475,9 @@ xterm contains required patches; do not replace it with the pub.dev package.
Build instructions and prior measurements are in the progress/performance notes.
The normal entry point is `desktop/lib/main.dart`. The public app/binary name
-is **Harness**; the development bundle ID remains `ai.autonomous.harness.v2` to
-preserve its separate state. Workspace Release path on the old computer was
+is **Harness**. Main now uses `ai.autonomous.harness`; older running previews may
+still report `ai.autonomous.harness.v2`. Do not infer the exact running process
+or its state from the current on-disk bundle. Workspace Release path here is
`desktop/build/macos/Build/Products/Release/Harness.app`; the installed Harness
was a separate process. Recheck exact bundle paths/PIDs before normally quitting
or relaunching a preview. Do not launch a competing duplicate or use a real
diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.md
index a1bb2a286..5b6b46fa8 100644
--- a/docs/harness-v2-performance.md
+++ b/docs/harness-v2-performance.md
@@ -12,6 +12,48 @@ It prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in
## Current continuation benchmark (2026-09-14)
+### Add picker frame work and keyboard focus
+
+Add now reuses up to 48 recently built result rows. Moving the highlight rebuilds
+the old/new selection and newly revealed rows; unchanged neighbors keep their
+widgets. Query, metadata, availability, selection, palette and text-size changes
+still refresh their presentation. The overlay header rebuilds when its hint or
+creation availability changes, rather than on every controller notification.
+
+The new explicit `test/benchmarks/swarm_add_benchmark.dart` measures an input
+operation plus one Flutter frame pump. It uses 2,000 discovered agents on one
+machine, 50 projects, five retained terminals with 1,000 lines each, and a
+1280×800 viewport. Each distribution has 20 warmups and 100 measured samples;
+the native bridge is stubbed. Runs were sequential in the headless debug runner
+without overlapping this session's tests/builds. These are CPU observations,
+not native input-to-display measurements.
+
+| Operation | Before median / p95 / p99 | Final median / p95 / p99 |
+| --- | ---: | ---: |
+| Cmd-N open + frame | 26.106 / 33.320 / 73.743 ms | 26.686 / 35.267 / 79.533 ms |
+| Query edit + frame | 11.398 / 17.790 / 19.785 ms | 11.193 / 16.182 / 18.320 ms |
+| Arrow selection + frame | 8.592 / 10.188 / 10.713 ms | 4.714 / 5.978 / 10.209 ms |
+
+Arrow selection's median fell about 45%; opening did not improve, and its tail
+was worse in the final run. JIT/shared-host variation limits tail conclusions.
+A single scrolling-arrow rebuild observation went from 19 ListTiles and one
+TextField to three ListTiles and zero TextFields. The regression with no scroll
+observes just the two changed rows. An intermediate run before the focus fix
+measured arrow selection at 4.985 / 7.655 / 8.457 ms; all three runs are retained
+at `/private/tmp/harness-add-frame-{baseline,after,final}.log`.
+
+A separate failing-before regression reproduced a completed background addition
+taking keyboard focus away from the picker. A persistent canvas focus boundary
+now prevents panes requesting Flutter focus while Add/Navigate is open. It is
+released synchronously on close. Opening New agent restores the original focus
+before its dialog opens, so Cancel returns to that terminal. The tests also
+cover live capacity changes and palette/text scaling with a checked selection.
+All 1,302 desktop tests pass with one existing skip; analysis has zero errors
+or warnings and 14 existing infos. The normal macOS arm64 Release build also
+succeeds; no running app was restarted. Logs:
+`/private/tmp/harness-add-render-{full-tests,final-analyze}.log`.
+Build log: `/private/tmp/harness-add-render-release-build.log`.
+
### Native fixture after the public bundle-ID change
The team's `76a469b` gave the workspace preview the installed app's
@@ -24,12 +66,13 @@ identity to be in `/Applications` or the current user's `Applications` folder
before exempting it. Unknown identities, development copies, legacy previews
and other benchmark processes remain blocked.
-Nine isolated Python tests pass. The current disposable arm64 Release fixture
+Nine isolated Python tests pass. The identity-fix disposable arm64 Release fixture
built at `/private/tmp/harness-native-benchmark-7hv6voyr`. Its actual runner
correctly refused the still-running workspace preview at its exact build path;
the installed copy is classified separately. No native samples were taken.
The session requested a brief preview-close/idle window for calibration and
continues independent performance work while that request is pending.
+Rebuild the fixture before measuring the newer Add frame/focus changes above.
Artifacts: `/private/tmp/harness-native-identity-{before,tests,prepare,preflight}.log`.
### History focus hot path
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index f151e4fba..799aa600c 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -6,6 +6,22 @@ Updated 2026-09-14 after integrating the continuation into main. This is a worki
## Continue directly on main
+- Improved Add's arrow-key frame work by reusing unchanged result rows and
+ leaving the text editor alone when only the highlight changes. In the paired
+ 2,000-agent headless fixture, arrow selection median fell 8.592 to 4.714 ms;
+ opening time did not improve. The full distributions and scope are in the
+ [performance record](harness-v2-performance.md). Fixed a reproduced case of a
+ background agent addition taking focus from the picker, while preserving
+ New agent cancellation focus. All **1,302 desktop tests** pass with one
+ existing skip; analysis has zero errors/warnings and 14 existing infos.
+ The normal macOS arm64 Release build succeeds. Test/analysis/build artifacts
+ use `/private/tmp/harness-add-render-*.log`; no running app was restarted.
+- `fe42f2e` repairs the isolated native benchmark for the team's public bundle
+ identity change. Nine isolation checks pass and the disposable Release
+ fixture builds. Its runner correctly refuses the running workspace preview;
+ native latency remains unmeasured. `56f9d2a` preserves the team's concurrent
+ `9e2e4be` branding/update changes. A brief preview-close calibration request
+ is pending; no running app or real agent has been stopped for these checks.
- Saved the Add/shortcut checkpoint as `5f3ecae`, then merged the team's
current main through `76a469b` as `f514140`. The merge was clean and preserves
its Settings toolbar button, independent terminal schemes, dial changes,