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
Separate swarm navigation from adding agents
dee2d3c024185ec
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 4aefbf521..71315eb5a 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -12,6 +12,7 @@ import '../core/test_run.dart';import '../settings/settings_screen.dart';import '../settings/settings_section.dart';import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';import '../shortcuts/app_shortcuts.dart';import '../shortcuts/app_keymap.dart';import '../shortcuts/keymap.dart';@@ -35,6 +36,7 @@ import '../widgets/pane_grid.dart';import '../widgets/shortcuts_sheet.dart';import '../widgets/swarm_dialogs.dart';import '../widgets/swarm_inline_search.dart';+import '../widgets/swarm_navigator.dart';import '../widgets/swarm_search_input.dart';import '../widgets/swarm_project_agents.dart';import '../widgets/swarm_attention.dart';@@ -202,6 +204,10 @@ class _SwarmScreenState extends State<SwarmScreen> {mounted && _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen;void _runShortcut(String id) {+ if (id == 'agent.new' && _search != null) {+ unawaited(_newAgentFromSearch());+ return;+ }if (!_canExecuteCommand(id)) return;if (id != 'navigation.quick_open' && id != 'navigation.commands') {_closeSearch();@@ -347,7 +353,6 @@ class _SwarmScreenState extends State<SwarmScreen> {const {'picker.next': 'next','picker.previous': 'previous',- 'picker.preview': 'preview','picker.accept': 'submit','picker.add_here': 'add','picker.cancel': 'close',@@ -358,8 +363,6 @@ class _SwarmScreenState extends State<SwarmScreen> {search.move(1);case 'previous':search.move(-1);- case 'preview':- search.togglePreview();case 'submit':final choice = search.submit();if (choice != null) await _chooseSearch(choice);@@ -371,6 +374,11 @@ class _SwarmScreenState extends State<SwarmScreen> {}return;}+ if (call.method == 'newAgent' && _search != null) {+ unawaited(_newAgentFromSearch());+ await WidgetsBinding.instance.endOfFrame;+ return;+ }if (call.method != 'jump') _closeSearch(restoreFocus: false);switch (call.method) {case 'new':@@ -570,22 +578,13 @@ class _SwarmScreenState extends State<SwarmScreen> {Future<void> _splitAgent(PaneResizeAxis axis) async {final split = app.preparePaneSplit(axis);- final pane = app.focusedPane;- if (split == null || pane == null) return;- final machine = app.machineStates[pane.machineId];- final agent = machine?.agents- .where((a) => a.id == pane.agentId)- .firstOrNull;- await _newAgent(- machineId: pane.machineId,- folder: agent == null ? null : machine?.projectOf(agent)?.cwd,- swarmId: split.swarmId,- split: split,- );+ if (split == null) return;+ _openSearch(adding: true, split: split);}Future<void> _jump({bool historyOnly = false}) async {if (!historyOnly) {+ if (_search?.adding == true) _closeSearch(restoreFocus: false);_openSearch();_focusSearch(selectAll: true);return;@@ -601,8 +600,9 @@ class _SwarmScreenState extends State<SwarmScreen> {Future<void> _activateSearch(SwarmSearchSelection selected,- String target,- ) async {+ String target, {+ PaneSplitRequest? split,+ }) async {final command = selected.destination.commandId;if (command != null) {// The result list is gone before a dialog or focus-changing command runs.@@ -617,6 +617,7 @@ class _SwarmScreenState extends State<SwarmScreen> {selected,destinationSwarmId: target,projects: _projects.projects,+ split: split,);if (!opened && mounted) {ScaffoldMessenger.of(context).showSnackBar(@@ -627,7 +628,11 @@ class _SwarmScreenState extends State<SwarmScreen> {}}- void _openSearch() {+ void _openSearch({+ bool adding = false,+ PaneSplitRequest? split,+ String query = '',+ }) {if (_search != null ||!mounted ||_dialogOpen ||@@ -641,11 +646,13 @@ class _SwarmScreenState extends State<SwarmScreen> {if (_native) _preparePaneFocus();_search = SwarmSearchController(app,- _navigation.recent,+ adding ? _navigation.recent : _navigation.recentLocations,projects: _projects,commands: _searchCommands,- previewInitiallyEnabled: true,- );+ adding: adding,+ navigating: !adding,+ split: split,+ )..setQuery(query);_search!.addListener(_syncSearch);_searchOverlay = OverlayEntry(builder: _buildSearchOverlay);Overlay.of(context).insert(_searchOverlay!);@@ -666,6 +673,7 @@ class _SwarmScreenState extends State<SwarmScreen> {}void _showSearchCommands() {+ if (_search?.adding == true) _closeSearch(restoreFocus: false);_openSearch();_search?.setQuery('> ');_focusSearch();@@ -707,13 +715,32 @@ class _SwarmScreenState extends State<SwarmScreen> {Future<void> _chooseSearch(SwarmSearchSelection choice) async {final target = _search?.targetId;+ final split = _search?.split;if (target == null) return;_closeSearch(restoreFocus: choice.destination.isCommand);- await _activateSearch(choice, target);+ await _activateSearch(choice, target, split: split);+ }++ Future<void> _newAgentFromSearch() async {+ final search = _search;+ if (search == null || !search.canCreate) return;+ final target = search.targetId;+ final split = search.split;+ _closeSearch(restoreFocus: false);+ await _newAgent(swarmId: target, split: split);+ }++ void _addFromNavigation() {+ final query = _search?.query ?? '';+ _closeSearch(restoreFocus: false);+ _openSearch(adding: true, query: query);}Widget _buildSearchOverlay(BuildContext context) {final search = _search!;+ // Keep Navigate's editor mounted when `>` enters/leaves command mode so+ // even the next keystroke retains focus and text editing ownership.+ final navigating = search.navigating;return KeymapProvider(keymap: _keymap,child: LayoutBuilder(@@ -723,13 +750,16 @@ class _SwarmScreenState extends State<SwarmScreen> {child: GestureDetector(behavior: HitTestBehavior.opaque,onTap: _closeSearch,- child: const ColoredBox(color: Color(0x66000000)),+ child: const ColoredBox(color: kDialogVeilTint),),),Align(alignment: const Alignment(0, -0.12),child: SizedBox(- width: (constraints.maxWidth - 64).clamp(280.0, 1040.0),+ width: (constraints.maxWidth - 64).clamp(+ 280.0,+ navigating ? 720.0 : 1040.0,+ ),height: (constraints.maxHeight - 96).clamp(220.0, 540.0),child: Material(key: const ValueKey('swarm-search-results'),@@ -741,29 +771,47 @@ class _SwarmScreenState extends State<SwarmScreen> {side: const BorderSide(color: Colors.white24),),clipBehavior: Clip.antiAlias,- child: Column(- children: [- SwarmSearchInput(- inputKey: const ValueKey('swarm-search-input'),- controller: _searchText,- focusNode: _searchFocus,- search: search,- onChoose: _chooseSearch,- onClose: _closeSearch,- onChanged: search.setQuery,- showClose: true,- ),- const Divider(height: 1, color: Colors.white12),- Expanded(- child: SwarmSearchResults(+ child: navigating+ ? SwarmNavigator(search: search,+ editing: _searchText,+ focusNode: _searchFocus,onChoose: _chooseSearch,- onRefocus: _focusSearch,- onCommands: _showSearchCommands,+ onClose: _closeSearch,+ onAdd: _addFromNavigation,+ onNewAgent: _newAgentFromSearch,+ )+ : Column(+ children: [+ SwarmSearchInput(+ inputKey: const ValueKey('swarm-search-input'),+ controller: _searchText,+ focusNode: _searchFocus,+ search: search,+ onChoose: _chooseSearch,+ onClose: _closeSearch,+ onChanged: search.setQuery,+ showClose: true,+ onNewAgent: search.adding+ ? _newAgentFromSearch+ : null,+ ),+ const Divider(height: 1, color: Colors.white12),+ Expanded(+ child: SwarmSearchResults(+ search: search,+ onChoose: _chooseSearch,+ onRefocus: _focusSearch,+ onCommands: search.allowsCommands+ ? _showSearchCommands+ : null,+ onNewAgent: search.adding+ ? _newAgentFromSearch+ : null,+ ),+ ),+ ],),- ),- ],- ),),),),@@ -791,7 +839,8 @@ class _SwarmScreenState extends State<SwarmScreen> {}Future<void> _addAgent() async {- await _jump();+ if (_search != null) _closeSearch(restoreFocus: false);+ _openSearch(adding: true);}Future<void> _addProject() => _dialog(() async {@@ -1062,6 +1111,17 @@ class _SwarmScreenState extends State<SwarmScreen> {autofocus: app.panes.isNotEmpty,child: Scaffold(backgroundColor: grid.AppPalette.swarmField,+ floatingActionButtonLocation:+ FloatingActionButtonLocation.endFloat,+ floatingActionButton: FloatingActionButton.small(+ key: const ValueKey('swarm-add-agent-button'),+ tooltip: 'Add agent',+ onPressed: () => _openSearch(adding: true),+ backgroundColor: grid.AppPalette.swarmAccent,+ foregroundColor: grid.AppPalette.swarmField,+ shape: const CircleBorder(),+ child: const Icon(Icons.add, size: 24),+ ),body: Column(children: [if (!_native) _tabStrip(),@@ -1151,7 +1211,7 @@ class _SwarmScreenState extends State<SwarmScreen> {Padding(padding: app.panes.isEmpty? EdgeInsets.zero- : const EdgeInsets.all(10),+ : const EdgeInsets.fromLTRB(10, 10, 10, 68),child: Stack(children: [Positioned.fill(@@ -1185,6 +1245,7 @@ class _SwarmScreenState extends State<SwarmScreen> {agentId: entry.agent.id,engine: entry.agent.engine,),+ SwarmSearchAction.addHere,),app.activeSwarmId,),@@ -1197,6 +1258,7 @@ class _SwarmScreenState extends State<SwarmScreen> {recent: _navigation.recent,commands: _searchCommands,onChoose: _activateSearch,+ onNewAgent: _newAgent,),onAddProject: _addProject,onLinkMachine: () => _dialog(@@ -1307,21 +1369,11 @@ class _SwarmScreenState extends State<SwarmScreen> {key: const ValueKey('swarm-search-button'),tooltip: withEffectiveShortcutHint(context,- 'Search',+ 'Navigate',ShortcutAction.switchAgent,),onPressed: _jump,- icon: const Icon(Icons.search, size: 20),- ),- IconButton(- key: const ValueKey('swarm-new-agent-button'),- tooltip: withEffectiveShortcutHint(- context,- 'New agent',- ShortcutAction.newAgent,- ),- onPressed: _newAgent,- icon: const Icon(Icons.add, size: 20),+ icon: const Icon(Icons.explore_outlined, size: 20),),IconButton(key: const ValueKey('swarm-notifications-button'),diff --git a/desktop/lib/shared/widgets/app_dialog.dart b/desktop/lib/shared/widgets/app_dialog.dartindex e9faf0cfb..d43fdf6c6 100644--- a/desktop/lib/shared/widgets/app_dialog.dart+++ b/desktop/lib/shared/widgets/app_dialog.dart@@ -27,14 +27,9 @@ import 'package:flutter/services.dart';/// still reads as the window.const double kDialogVeilBlur = 7;-/// The tint over that blur.-///-/// `rgba(0,0,0,.64)` — deeper than Material's own 54% black barrier looks over-/// a light page, because this one is laid over a dark one, where the same alpha-/// barely registers. Read against the panel's own fill rather than picked off a-/// scale: the dialog has to sit clearly in front of the veil, and the veil-/// clearly in front of the window.-const Color kDialogVeilTint = Color(0xA3000000);+/// Shared dark backdrop for dialogs and centered pickers. Terminal output+/// stays in the background while the active surface has the user's attention.+const Color kDialogVeilTint = Color(0xC7000000);/// The app's dialog barrier: a blur, then a tint, then whatever opened.///diff --git a/desktop/lib/shortcuts/keymap.dart b/desktop/lib/shortcuts/keymap.dartindex e994e7746..4c48cde33 100644--- a/desktop/lib/shortcuts/keymap.dart+++ b/desktop/lib/shortcuts/keymap.dart@@ -201,6 +201,9 @@ class KeymapConfig {);}final command = row['command'];+ // Output preview is now always visible in Add. An old customization of+ // its removed toggle must not invalidate the rest of the user's keymap.+ if (command == 'picker.preview' && !commands.contains(command)) continue;if (command != null &&(command is! String || !commands.contains(command))) {throw FormatException('Unknown command in bindings[$i]: $command');diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex 1c18302d4..c002e018b 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -49,7 +49,7 @@ Map<ShortcutAction, List<String>> _readWorkspaceKeys() {final harnessCommands = <HarnessCommand>[const HarnessCommand('navigation.quick_open',- 'Search agents, swarms, machines and projects',+ 'Navigate to an agent or swarm',ShortcutGroup.navigate,action: ShortcutAction.switchAgent,nativeAction: 'jump',@@ -368,13 +368,6 @@ final harnessCommands = <HarnessCommand>[extraKeys: ['cmd+enter'],context: KeymapContext.picker,),- const HarnessCommand(- 'picker.preview',- 'Toggle agent output preview',- ShortcutGroup.navigate,- extraKeys: ['cmd+i'],- context: KeymapContext.picker,- ),const HarnessCommand('picker.cancel','Close search',diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dartindex 5808bb369..098d1fa17 100644--- a/desktop/lib/state/swarm_navigation.dart+++ b/desktop/lib/state/swarm_navigation.dart@@ -1,20 +1,25 @@-import 'package:flutter/foundation.dart' show listEquals;+import 'package:flutter/foundation.dart' show listEquals, setEquals;import '../core/fuzzy_match.dart';import '../core/models.dart';import 'app_state.dart';+import 'pane_arrangement.dart';import 'swarm.dart';import 'swarm_catalog.dart';+import 'terminal_pane.dart';String swarmDestinationId(String id) => 'swarm:$id';String agentDestinationId(String machineId, String agentId) =>'agent:$machineId\u0000$agentId';+String agentLocationId(String swarmId, int paneId) =>+ 'location:$swarmId\u0000$paneId';/// Session-local history contains identities only, never terminal buffers or/// controllers. Repeated discovery/output notifications do not reorder it.class SwarmNavigationHistory {static const capacity = 64;final _recent = <String>[];+ final _recentLocations = <String>[];(String, int?)? _location;final _trail = <(String, int?)>[];int _cursor = -1;@@ -23,6 +28,7 @@ class SwarmNavigationHistory {List<Object?>? _menuPresentation;List<SwarmDestination> _menuDestinations = const [];List<String> get recent => List.unmodifiable(_recent);+ List<String> get recentLocations => List.unmodifiable(_recentLocations);void record(AppNotifier app) {final location = (app.activeSwarmId, app.focusedPaneId);@@ -41,6 +47,12 @@ class SwarmNavigationHistory {if (pane?.agentId != null) {_remember(agentDestinationId(pane!.machineId, pane.agentId!));}+ final destination = pane?.agentId != null+ ? agentLocationId(location.$1, pane!.id)+ : swarmDestinationId(location.$1);+ _recentLocations.remove(destination);+ _recentLocations.insert(0, destination);+ if (_recentLocations.length > capacity) _recentLocations.removeLast();_location = location;}@@ -138,6 +150,8 @@ class SwarmDestination {this.closedId,this.commandId,this.shortcut,+ this.paneId,+ this.swarmName = '',this.projectId,this.members = const {},Iterable<String?> searchFields = const [],@@ -150,6 +164,10 @@ class SwarmDestination {final String? swarmId, machineId, agentId, engine;final String? closedId;final String? commandId, shortcut;++ /// An exact navigation location. Never fall back to a different swarm.+ final int? paneId;+ final String swarmName;bool get isCommand => commandId != null;final String? projectId;final Set<String> members;@@ -173,6 +191,39 @@ class SwarmSearchSelection {final SwarmSearchAction action;}+List<Object?> _catalogPresentation(+ AppNotifier app,+ List<SavedSwarmProject> projects, {+ List<String> recent = const [],+}) => [+ app.activeSwarmId,+ app.focusedPaneId,+ ...recent,+ ...projects,+ for (final swarm in app.swarms) ...[+ swarm.id,+ swarm.name,+ for (final pane in swarm.panes)+ (+ pane.id,+ pane.machineId,+ pane.agentId,+ pane.session?.agentName,+ pane.session?.engineId,+ ),+ ],+ for (final machine in app.machineStates.values)+ (+ machine.machine,+ machine.nodeOnline,+ machine.needsLink,+ machine.agents,+ machine.agents.length,+ machine.localEndpoint?.agentProjects,+ machine.localProjects,+ ),+];+/// One catalog for all search entry points. Terminal output leaves these/// normalized snapshots intact; only discovery, membership or metadata changes/// rebuild them. Typing never reads a folder or asks a machine for data.@@ -185,28 +236,7 @@ class SwarmSearchCatalog {List<SavedSwarmProject> projects, {List<String> recent = const [],}) {- final presentation = <Object?>[- app.activeSwarmId,- app.focusedPaneId,- ...recent,- ...projects,- for (final swarm in app.swarms) ...[- swarm.id,- swarm.name,- for (final pane in swarm.panes)- (pane.id, pane.machineId, pane.agentId, pane.session?.agentName),- ],- for (final machine in app.machineStates.values)- (- machine.machine,- machine.nodeOnline,- machine.needsLink,- machine.agents,- machine.agents.length,- machine.localEndpoint?.agentProjects,- machine.localProjects,- ),- ];+ final presentation = _catalogPresentation(app, projects, recent: recent);if (listEquals(_presentation, presentation)) return _entries;_presentation = presentation;final entries = swarmDestinations(app, recent: recent);@@ -279,11 +309,112 @@ class SwarmSearchCatalog {}}+/// Global navigation lists places that already exist. The same runtime has a+/// separate location in every swarm; discovery alone never creates a result+/// whose activation would add membership. Output reuses the cached snapshot.+class SwarmLocationCatalog {+ List<Object?>? _presentation;+ List<SwarmDestination> _entries = const [];++ List<SwarmDestination> read(+ AppNotifier app,+ List<SavedSwarmProject> projects,+ ) {+ final presentation = _catalogPresentation(app, projects);+ if (listEquals(presentation, _presentation)) return _entries;+ _presentation = presentation;+ // Resolve metadata once, and format only open locations. Navigation does+ // not need the Add catalog's thousands of unused agents or project groups.+ final agents = {+ for (final machine in app.machineStates.entries)+ for (final agent in machine.value.agents)+ (machine.key, agent.id): agent,+ };+ return _entries = List.unmodifiable([+ for (final swarm in app.swarms) ...[+ _swarm(app, swarm),+ for (final pane in swarm.panes)+ if (pane.agentId != null)+ _location(+ app,+ swarm,+ pane,+ agents[(pane.machineId, pane.agentId!)],+ ),+ ],+ ]);+ }++ SwarmDestination _swarm(AppNotifier app, Swarm swarm) {+ final machineLabel = _swarmMachineLabel(app, [+ for (final pane in swarm.panes)+ if (pane.agentId != null) pane.machineId,+ ]);+ return SwarmDestination(+ id: swarmDestinationId(swarm.id),+ title: swarm.name,+ detail: _agentCountLabel(swarm.panes.map((pane) => pane.agentId)),+ machineLabel: machineLabel,+ swarmId: swarm.id,+ swarmName: swarm.name,+ current: swarm.id == app.activeSwarmId,+ searchFields: [machineLabel],+ );+ }++ SwarmDestination _location(+ AppNotifier app,+ Swarm swarm,+ TerminalPane pane,+ Agent? agent,+ ) {+ final machine = app.machineStates[pane.machineId];+ final project = agent == null ? null : machine?.projectOf(agent);+ final machineLabel = machine?.machine.displayName ?? pane.machineId;+ final engine = agent?.engine ?? pane.session?.engineId;+ final detail = [+ machineLabel,+ project?.name,+ project?.branch,+ if (machine?.nodeOnline == false) 'Offline',+ ].whereType<String>().where((s) => s.isNotEmpty).toSet().join(' · ');+ return SwarmDestination(+ id: agentLocationId(swarm.id, pane.id),+ title: agent?.name ?? pane.session?.agentName ?? pane.agentId!,+ detail: detail,+ swarmId: swarm.id,+ swarmName: swarm.name,+ paneId: pane.id,+ machineId: pane.machineId,+ machineLabel: machineLabel,+ agentId: pane.agentId,+ engine: engine,+ current: swarm.id == app.activeSwarmId && pane.id == app.focusedPaneId,+ searchFields: [detail, project?.cwd, engine, swarm.name],+ );+ }+}++/// Keep matching locations together under their swarm, ordered by the best+/// match in each group. The first result remains the best match/previous place.+List<SwarmDestination> rankSwarmLocations(+ List<SwarmDestination> all,+ String query, {+ List<String> recent = const [],+}) {+ final groups = <String, List<SwarmDestination>>{};+ for (final row in rankSwarmDestinations(all, query, recent: recent)) {+ (groups[row.swarmId!] ??= []).add(row);+ }+ return [for (final group in groups.values) ...group];+}+Future<bool> activateSwarmSearchSelection(AppNotifier app,SwarmSearchSelection selection, {required String destinationSwarmId,List<SavedSwarmProject> projects = const [],+ PaneSplitRequest? split,}) async {final destination = selection.destination;if (selection.action == SwarmSearchAction.open && !destination.isGroup) {@@ -294,7 +425,60 @@ Future<bool> activateSwarmSearchSelection();}if (selection.action == SwarmSearchAction.addHere) {+ if (destination.agentId == null) {+ if (split != null || destination.isCommand) return false;+ final target = app.swarms+ .where((swarm) => swarm.id == destinationSwarmId)+ .firstOrNull;+ final catalog = SwarmSearchCatalog().read(app, projects);+ final live = catalog.where((row) => row.id == destination.id).firstOrNull;+ if (target == null ||+ live == null ||+ !setEquals(destination.members, live.members)) {+ return false;+ }+ final members = catalog+ .where(+ (row) =>+ destination.members.contains(row.id) &&+ !target.panes.any(+ (pane) =>+ pane.machineId == row.machineId &&+ pane.agentId == row.agentId,+ ),+ )+ .toList();+ if (members.isEmpty ||+ target.panes.length + members.length > AppNotifier.maxPanes ||+ members.any(+ (row) =>+ !(app.machineStates[row.machineId]?.agents.any(+ (agent) => agent.id == row.agentId,+ ) ??+ false),+ )) {+ return false;+ }+ if (target.panes.isEmpty && target.name == 'New swarm') {+ app.renameSwarm(target.id, destination.title);+ }+ // Every membership is recorded before awaiting any attachment. A slow+ // machine cannot retarget the add or hold up the other agents.+ await Future.wait([+ for (final row in members)+ app.addAgentToSwarm(row.machineId!, row.agentId!, swarmId: target.id),+ ]);+ return members.every(+ (row) => target.panes.any(+ (pane) =>+ pane.machineId == row.machineId && pane.agentId == row.agentId,+ ),+ );+ }if (destination.agentId == null ||+ (split != null &&+ (split.swarmId != destinationSwarmId ||+ !app.isPaneSplitCurrent(split))) ||!app.swarms.any((s) => s.id == destinationSwarmId)) {return false;}@@ -302,10 +486,12 @@ Future<bool> activateSwarmSearchSelection(.where((e) => e.id == destination.id).firstOrNull;if (live == null) return false;- await app.addAgentToSwarm(+ await app.assignAgentToPane(+ null,destination.machineId!,destination.agentId!,swarmId: destinationSwarmId,+ split: split,);if (app.activeSwarmId == destinationSwarmId) {app.revealAgentView(@@ -485,6 +671,11 @@ List<SwarmDestination> swarmDestinations(if (pane.agentId != null) pane.machineId,]),detail: _agentCountLabel(swarm.panes.map((pane) => pane.agentId)),+ members: {+ for (final pane in swarm.panes)+ if (pane.agentId != null)+ agentDestinationId(pane.machineId, pane.agentId!),+ },swarmId: swarm.id,current: swarm.id == app.activeSwarmId,searchFields: context.toSet(),@@ -648,6 +839,23 @@ Future<bool> activateSwarmDestination(if (destination.closedId != null) {return app.reopenClosed(historyId: destination.closedId);}+ if (destination.paneId != null) {+ final swarm = app.swarms+ .where((s) => s.id == destination.swarmId)+ .firstOrNull;+ final pane = swarm?.panes+ .where(+ (p) =>+ p.id == destination.paneId &&+ p.machineId == destination.machineId &&+ p.agentId == destination.agentId,+ )+ .firstOrNull;+ if (swarm == null || pane == null) return false;+ app.selectSwarm(swarm.id, attachPending: false);+ app.focusPane(pane.id, reveal: true);+ return true;+ }if (destination.isSwarm) {if (!app.swarms.any((s) => s.id == destination.swarmId)) return false;app.selectSwarm(destination.swarmId!, attachPending: false);diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex a3ddf3b18..25052cc32 100644--- a/desktop/lib/state/swarm_search.dart+++ b/desktop/lib/state/swarm_search.dart@@ -4,6 +4,7 @@ import 'package:xterm/xterm.dart';import '../terminal/search_output_preview.dart';import 'app_state.dart';+import 'pane_arrangement.dart';import 'swarm_catalog.dart';import 'swarm_navigation.dart';@@ -16,9 +17,10 @@ class SwarmSearchController extends ChangeNotifier {this.projects,this.history,this.commands,- bool previewInitiallyEnabled = false,- }) : previewEnabled = previewInitiallyEnabled,- targetId = app.activeSwarmId,+ this.adding = false,+ this.navigating = false,+ this.split,+ }) : targetId = app.activeSwarmId,targetName = app.activeSwarm.name {_refresh();app.addListener(_refresh);@@ -33,31 +35,47 @@ class SwarmSearchController extends ChangeNotifier {/// Availability is read from workspace state and rechecked at activation./// Commands never enter the ordinary agent/swarm catalog or History.final List<SwarmDestination> Function()? commands;- bool get isCommandMode => history == null && query.trimLeft().startsWith('>');+ final bool adding;+ final bool navigating;+ final PaneSplitRequest? split;+ bool get allowsCommands => split == null && history == null;+ bool get isCommandMode => allowsCommands && query.trimLeft().startsWith('>');final String targetId, targetName;final _cache = SwarmSearchCatalog();+ final _locations = SwarmLocationCatalog();List<SwarmDestination> _catalog = const [];Set<String> _commandIds = const {};List<SwarmDestination> rows = const [];String query = '';String? _selectedId;int cursor = 0;- bool previewEnabled;SearchOutputPreview? preview;String? _previewId;+ bool? _splitCurrent;+ Set<String> _presentIds = const {};bool get canPreview =>+ !navigating &&!isCommandMode &&history == null &&selected != null &&selected?.closedId == null;- bool get previewVisible => previewEnabled && canPreview;+ bool get previewVisible => canPreview;- void togglePreview() {- if (!previewEnabled && !canPreview) return;- previewEnabled = !previewEnabled;- _updatePreview();- notifyListeners();+ List<SwarmDestination> get previewMembers {+ final row = selected;+ if (row == null || row.agentId != null) return const [];+ final memberIds = row.isGroup+ ? row.members+ : {+ for (final swarm in app.swarms.where(+ (swarm) => swarm.id == row.swarmId,+ ))+ for (final pane in swarm.panes)+ if (pane.agentId != null)+ agentDestinationId(pane.machineId, pane.agentId!),+ };+ return _catalog.where((entry) => memberIds.contains(entry.id)).toList();}void _updatePreview() {@@ -68,8 +86,8 @@ class SwarmSearchController extends ChangeNotifier {}final row = selected!;// Keep a snapshot while this selection stays put. Query edits and output- // traffic do not read the buffers again. A new selection or re-enabling- // preview captures fresh context, including any replacement session.+ // traffic do not read the buffers again. Choosing another result+ // captures fresh context, including any replacement session.if (_previewId == row.id) return;final terminal = app.allPanes.where(@@ -88,14 +106,66 @@ class SwarmSearchController extends ChangeNotifier {? 'Search commands…': history != null? 'Search history…'+ : adding+ ? 'Search agents to add…'+ : navigating+ ? 'Find an agent or swarm…': 'Search agents, swarms, machines, projects…';+ bool get canCreate =>+ history == null &&+ app.swarms.any(+ (swarm) =>+ swarm.id == targetId && swarm.panes.length < AppNotifier.maxPanes,+ ) &&+ (split == null || app.isPaneSplitCurrent(split!));++ String get primaryAction => switch (split?.axis) {+ PaneResizeAxis.x => 'Split right',+ PaneResizeAxis.y => 'Split down',+ null => 'Add to this swarm',+ };++ String actionLabel(SwarmDestination? row) => row?.isCommand == true+ ? action(row!)+ : adding+ ? row != null &&+ row.agentId == null &&+ split == null &&+ _missingIds(row).length > 1+ ? 'Add ${_missingIds(row).length} agents'+ : primaryAction+ : row == null+ ? 'Go to'+ : action(row);++ String get unavailableMessage =>+ split != null && !app.isPaneSplitCurrent(split!)+ ? 'The layout changed. Split the agent again.'+ : selected != null && alreadyHere(selected!)+ ? 'This agent is already in this swarm.'+ : 'This swarm has no room for another agent.';+void _refresh() {- final next = history == null+ final next = navigating+ ? _locations.read(app, projects?.projects ?? const [])+ : history == null? _cache.read(app, projects?.projects ?? const [], recent: recent): [...history!.menuDestinations(app), ...closedWorkDestinations(app)];- if (identical(next, _catalog) && !isCommandMode) return;+ final splitCurrent = split == null || app.isPaneSplitCurrent(split!);+ if (identical(next, _catalog) &&+ !isCommandMode &&+ splitCurrent == _splitCurrent) {+ return;+ }_catalog = next;+ _splitCurrent = splitCurrent;+ _presentIds = {+ for (final swarm in app.swarms.where((s) => s.id == targetId))+ for (final pane in swarm.panes)+ if (pane.agentId != null)+ agentDestinationId(pane.machineId, pane.agentId!),+ };_filter();notifyListeners();}@@ -116,7 +186,22 @@ class SwarmSearchController extends ChangeNotifier {availableCommands,query.trimLeft().substring(1).trimLeft(),)- : rankSwarmDestinations(_catalog, query, recent: recent);+ : navigating+ ? rankSwarmLocations(_catalog, query, recent: recent)+ : rankSwarmDestinations(+ adding+ ? _catalog+ .where(+ (row) =>+ (split == null || row.agentId != null) &&+ (_hasMissing(row) ||+ (query.isNotEmpty && row.agentId != null)),+ )+ .toList()+ : _catalog,+ query,+ recent: recent,+ );final index = rows.indexWhere((row) => row.id == _selectedId);cursor = rows.isEmpty? 0@@ -152,29 +237,47 @@ class SwarmSearchController extends ChangeNotifier {false)) {return null;}- return SwarmSearchSelection(destination);+ return SwarmSearchSelection(+ destination,+ adding ? SwarmSearchAction.addHere : SwarmSearchAction.open,+ );}bool canSubmit(SwarmDestination? row) =>row != null &&+ (!adding || row.isCommand || canAdd(row)) &&(!row.isCommand || (isCommandMode && _commandIds.contains(row.id))) &&- (!row.isGroup ||+ (adding ||+ !row.isGroup ||canOpenSwarmGroup(app, row, destinationSwarmId: targetId)) &&(row.closedId == null || app.canReopenClosed(row.closedId!));+ Set<String> _missingIds(SwarmDestination row) {+ final members = row.agentId == null ? row.members : {row.id};+ return members.difference(_presentIds);+ }++ bool _hasMissing(SwarmDestination row) => row.agentId != null+ ? !_presentIds.contains(row.id)+ : row.members.any((id) => !_presentIds.contains(id));++ bool alreadyHere(SwarmDestination row) =>+ adding && row.agentId != null && _presentIds.contains(row.id);+bool canAdd(SwarmDestination? row) =>+ !navigating &&history == null &&- row?.agentId != null &&- row!.hasView &&+ row != null &&+ !row.isCommand &&+ row.closedId == null &&+ _missingIds(row).isNotEmpty &&+ (split == null || row.agentId != null) &&+ (split == null || app.isPaneSplitCurrent(split!)) &&app.swarms.any((swarm) =>swarm.id == targetId &&- swarm.panes.length < AppNotifier.maxPanes &&- !swarm.panes.any(- (pane) =>- pane.machineId == row.machineId &&- pane.agentId == row.agentId,- ),+ swarm.panes.length + _missingIds(row).length <=+ AppNotifier.maxPanes,);SwarmSearchSelection? addHere() => canAdd(selected)diff --git a/desktop/lib/terminal/search_output_preview.dart b/desktop/lib/terminal/search_output_preview.dartindex 772ae0365..31b85f026 100644--- a/desktop/lib/terminal/search_output_preview.dart+++ b/desktop/lib/terminal/search_output_preview.dart@@ -10,27 +10,73 @@ class SearchOutputPreview {// Covers the maximum 120-row viewport plus a small amount of scrollback,// including a short prompt near the top of an otherwise empty tall pane.static const scannedLines = 160;- static const shownLines = 12;static const shownColumns = 192;+ static const shownCharacters = 720;final String text;static final _controls = RegExp(r'[\x00-\x1f\x7f-\x9f]');+ static final _rules = RegExp(r'[-─━═_╌┄]{4,}');+ static final _frame = RegExp(r'^[│┃┆╎┊┇]+\s*|\s*[│┃┆╎┊┇]+$');+ static final _prompt = RegExp(r'^[>›❯_$▌█\s]+$');+ static final _blockStart = RegExp(r'^(?:[>›❯•●◦]|[-*]\s|\d+\.\s)');+ static final _recap = RegExp(r'^(?:[—–-]\s*)?Conversation recap$');+ static final _worked = RegExp(r'^[—–-]\s*Worked for \d');+ static final _inputHint = RegExp(r'^Ask (Codex|Claude) to ');+ static final _indented = RegExp(r'^\s');static SearchOutputPreview capture(Terminal? terminal) {if (terminal == null) return const SearchOutputPreview('');final lines = terminal.buffer.lines;- final excerpt = <String>[];+ final logical = <String>[];final start = math.max(0, lines.length - scannedLines);- for (var row = lines.length - 1; row >= start; row--) {+ for (var row = start; row < lines.length; row++) {// getText works in terminal cells, so a wide Unicode character is not// split as it could be by slicing an arbitrary UTF-16 string.final text = lines[row].getText(0, shownColumns).replaceAll(_controls, '').trimRight();- if (text.trim().isEmpty) continue;- excerpt.add(text);- if (excerpt.length == shownLines) break;+ if (lines[row].isWrapped && logical.isNotEmpty) {+ logical[logical.length - 1] += text;+ } else {+ logical.add(text);+ }}- return SearchOutputPreview(excerpt.reversed.join('\n'));+ final blocks = <String>[];+ var paragraph = '';+ void finish() {+ if (paragraph.isNotEmpty) blocks.add(paragraph);+ paragraph = '';+ }++ for (final line in logical) {+ final text = line.replaceAll(_rules, '').trim().replaceAll(_frame, '');+ if (text.isEmpty ||+ _prompt.hasMatch(text) ||+ _recap.hasMatch(text) ||+ _worked.hasMatch(text) ||+ _inputHint.hasMatch(text)) {+ finish();+ continue;+ }+ if (_blockStart.hasMatch(text) || !_indented.hasMatch(line)) {+ finish();+ }+ paragraph = paragraph.isEmpty ? text : '$paragraph $text';+ }+ finish();+ // Show complete recent paragraphs, not the bottom of a wrapped terminal+ // viewport. This is a reading excerpt, never a second terminal renderer.+ final recentBlocks = blocks.skip(math.max(0, blocks.length - 3)).toList();+ while (recentBlocks.length > 1 &&+ recentBlocks.join('\n\n').runes.length > shownCharacters) {+ recentBlocks.removeAt(0);+ }+ final recent = recentBlocks.join('\n\n');+ final characters = recent.runes.toList();+ return SearchOutputPreview(+ characters.length <= shownCharacters+ ? recent+ : '${String.fromCharCodes(characters.take(shownCharacters)).trimRight()}…',+ );}}diff --git a/desktop/lib/widgets/agent_switcher.dart b/desktop/lib/widgets/agent_switcher.dartindex 60bc9771d..8bd1c36e0 100644--- a/desktop/lib/widgets/agent_switcher.dart+++ b/desktop/lib/widgets/agent_switcher.dart@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';import '../core/models.dart';import '../core/fuzzy_match.dart';import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';import '../state/app_state.dart';import 'engine_identity.dart';@@ -42,7 +43,7 @@ Future<void> showAgentSwitcher(BuildContext context, AppNotifier notifier) {_switcherOpen = true;return showDialog<void>(context: context,- barrierColor: Colors.black.withValues(alpha: 0.3),+ barrierColor: kDialogVeilTint,builder: (context) => _AgentSwitcher(notifier: notifier),).whenComplete(() => _switcherOpen = false);}diff --git a/desktop/lib/widgets/device_row.dart b/desktop/lib/widgets/device_row.dartindex 4e440d60b..4a277fd7b 100644--- a/desktop/lib/widgets/device_row.dart+++ b/desktop/lib/widgets/device_row.dart@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';import 'package:url_launcher/url_launcher.dart';import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';import '../state/app_state.dart';import '../state/dial_status.dart';@@ -166,7 +167,7 @@ class _DeviceRowState extends State<DeviceRow> {Future<void> _showStatus(BuildContext context) {return showDialog<void>(context: context,- barrierColor: Colors.black.withValues(alpha: 0.42),+ barrierColor: kDialogVeilTint,builder: (context) => _DeviceStatusCard(notifier: widget.notifier),);}diff --git a/desktop/lib/widgets/swarm_attention.dart b/desktop/lib/widgets/swarm_attention.dartindex 8a0186220..729c7aa27 100644--- a/desktop/lib/widgets/swarm_attention.dart+++ b/desktop/lib/widgets/swarm_attention.dart@@ -15,7 +15,6 @@ Future<SwarmAttentionEntry?> showSwarmAttention(context: context,transitionDuration: Duration.zero,veilBlur: 0,- veilTint: const Color(0x66000000),builder: (_) => _SwarmAttention(app: app, recent: history.recent),);diff --git a/desktop/lib/widgets/swarm_inline_search.dart b/desktop/lib/widgets/swarm_inline_search.dartindex 4c342ae97..52c85ca57 100644--- a/desktop/lib/widgets/swarm_inline_search.dart+++ b/desktop/lib/widgets/swarm_inline_search.dart@@ -12,8 +12,8 @@ import '../state/swarm_search.dart';import 'swarm_switcher.dart';import 'swarm_search_input.dart';-/// New swarm owns its input and caret. Only the catalog and result actions are-/// shared with the title bar; typing here never activates the native field.+/// New swarm owns its input and caret, sharing the same Add agent results and+/// actions as the floating button and splits.class SwarmInlineSearch extends StatefulWidget {const SwarmInlineSearch({super.key,@@ -22,12 +22,14 @@ class SwarmInlineSearch extends StatefulWidget {required this.recent,required this.onChoose,this.commands,+ this.onNewAgent,});final AppNotifier app;final SwarmProjectStore projects;final List<String> recent;final List<SwarmDestination> Function()? commands;+ final VoidCallback? onNewAgent;final void Function(SwarmSearchSelection choice, String target) onChoose;@override@@ -73,7 +75,7 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {widget.recent,projects: widget.projects,commands: widget.commands,- previewInitiallyEnabled: true,+ adding: true,)..setQuery(_text.text);_search!.addListener(_changed);_overlay.show();@@ -108,6 +110,12 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {widget.onChoose(choice, target);}+ void _newAgent() {+ if (_search?.canCreate == false) return;+ _close();+ widget.onNewAgent?.call();+ }+@overridevoid dispose() {_keymap?.removeListener(_keymapChanged);@@ -162,6 +170,7 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {onChoose: _choose,onRefocus: _focus.requestFocus,onCommands: _showCommands,+ onNewAgent: widget.onNewAgent == null ? null : _newAgent,),),),@@ -178,6 +187,7 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {onChoose: _choose,onClose: _close,onOpen: _begin,+ onNewAgent: widget.onNewAgent == null ? null : _newAgent,onTapOutside: _close,onChanged: (value) {_begin();diff --git a/desktop/lib/widgets/swarm_navigator.dart b/desktop/lib/widgets/swarm_navigator.dartnew file mode 100644index 000000000..42a3bc00d--- /dev/null+++ b/desktop/lib/widgets/swarm_navigator.dart@@ -0,0 +1,347 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../state/swarm_navigation.dart';+import '../state/swarm_search.dart';+import 'engine_identity.dart';+import 'search_result_text.dart';+import 'swarm_icon.dart';+import 'swarm_switcher.dart';++/// A directory of existing places. Unlike Add agent, navigation has no output+/// preview or creation form: each group names the exact destination swarm.+class SwarmNavigator extends StatefulWidget {+ const SwarmNavigator({+ super.key,+ required this.search,+ required this.editing,+ required this.focusNode,+ required this.onChoose,+ required this.onClose,+ required this.onAdd,+ required this.onNewAgent,+ });++ final SwarmSearchController search;+ final TextEditingController editing;+ final FocusNode focusNode;+ final ValueChanged<SwarmSearchSelection> onChoose;+ final VoidCallback onClose, onAdd, onNewAgent;++ @override+ State<SwarmNavigator> createState() => _SwarmNavigatorState();+}++class _SwarmNavigatorState extends State<SwarmNavigator> {+ final _scroll = ScrollController();+ final _offsets = <double>[];+ double _rowHeight = 60, _headingHeight = 34;+ bool _scheduled = false;+ SwarmSearchController get search => widget.search;+ bool startsGroup(int i) =>+ i == 0 || search.rows[i - 1].swarmId != search.rows[i].swarmId;++ @override+ void initState() {+ super.initState();+ search.addListener(_changed);+ }++ void _changed() {+ setState(() {});+ _measure();+ _reveal();+ if (_scheduled) return;+ _scheduled = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _scheduled = false;+ if (mounted) _reveal();+ });+ }++ void _measure() {+ _offsets.clear();+ var offset = 8.0;+ for (var i = 0; i < search.rows.length; i++) {+ _offsets.add(offset);+ offset += _rowHeight + (startsGroup(i) ? _headingHeight : 0);+ }+ _offsets.add(offset);+ }++ void _reveal() {+ if (!_scroll.hasClients ||+ search.rows.isEmpty ||+ _offsets.length <= search.cursor + 1) {+ return;+ }+ final top = _offsets[search.cursor];+ final bottom = _offsets[search.cursor + 1];+ final position = _scroll.position;+ final next = top < position.pixels+ ? top+ : bottom > position.pixels + position.viewportDimension+ ? bottom - position.viewportDimension+ : position.pixels;+ final target = next.clamp(0.0, position.maxScrollExtent);+ if (position.pixels != target) _scroll.jumpTo(target);+ }++ void _choose(SwarmDestination row) {+ final selection = search.submit(row);+ if (selection != null) widget.onChoose(selection);+ }++ @override+ void dispose() {+ search.removeListener(_changed);+ _scroll.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final scale = MediaQuery.textScalerOf(context);+ _rowHeight = 28 + scale.scale(14) + scale.scale(12);+ _headingHeight = 20 + scale.scale(11);+ _measure();+ final terms = swarmQueryTerms(search.query);+ return Column(+ key: const ValueKey('swarm-navigator'),+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 18, 12, 8),+ child: Row(+ children: [+ Icon(+ search.isCommandMode ? Icons.terminal : Icons.explore_outlined,+ color: grid.AppPalette.swarmAccent,+ size: 21,+ ),+ const SizedBox(width: 10),+ Text(+ search.isCommandMode ? 'Commands' : 'Navigate',+ style: const TextStyle(+ fontSize: 16,+ fontWeight: FontWeight.w600,+ color: Colors.white,+ ),+ ),+ const Spacer(),+ TextButton(+ onPressed: widget.onClose,+ style: TextButton.styleFrom(foregroundColor: Colors.white60),+ child: const Text('esc', style: TextStyle(fontSize: 11)),+ ),+ ],+ ),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 0, 20, 16),+ child: SwarmSearchKeys(+ search: search,+ editing: widget.editing,+ onChoose: widget.onChoose,+ onClose: widget.onClose,+ onNewAgent: widget.onNewAgent,+ child: TextField(+ key: const ValueKey('swarm-search-input'),+ controller: widget.editing,+ focusNode: widget.focusNode,+ autofocus: true,+ onChanged: search.setQuery,+ style: const TextStyle(fontSize: 16, color: Colors.white),+ cursorColor: grid.AppPalette.swarmAccent,+ decoration: InputDecoration(+ hintText: search.hint,+ hintStyle: const TextStyle(color: Colors.white54, fontSize: 16),+ prefixIcon: const Icon(+ Icons.search,+ size: 19,+ color: Colors.white54,+ ),+ filled: true,+ fillColor: Colors.black.withValues(alpha: .15),+ contentPadding: const EdgeInsets.symmetric(+ horizontal: 14,+ vertical: 14,+ ),+ enabledBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(8),+ borderSide: const BorderSide(color: Colors.white12),+ ),+ focusedBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(8),+ borderSide: BorderSide(+ color: grid.AppPalette.swarmAccent.withValues(alpha: .6),+ ),+ ),+ ),+ ),+ ),+ ),+ const Divider(height: 1, color: Colors.white12),+ Expanded(+ child: search.isCommandMode+ ? SwarmSearchResults(+ search: search,+ onChoose: widget.onChoose,+ onRefocus: widget.focusNode.requestFocus,+ )+ : search.rows.isEmpty+ ? const Center(+ child: Padding(+ padding: EdgeInsets.all(24),+ child: Text(+ 'No matching open agents or swarms.\nAdd an agent to bring more work into this swarm.',+ textAlign: TextAlign.center,+ style: TextStyle(+ color: Colors.white60,+ fontSize: 14,+ height: 1.6,+ ),+ ),+ ),+ )+ : ListView.builder(+ key: const ValueKey('swarm-navigation-locations'),+ controller: _scroll,+ padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),+ itemCount: search.rows.length,+ itemExtentBuilder: (index, _) =>+ _rowHeight + (startsGroup(index) ? _headingHeight : 0),+ itemBuilder: (context, i) {+ final row = search.rows[i];+ final matches = searchResultMatches(row, terms);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (startsGroup(i))+ SizedBox(+ height: _headingHeight,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 12,+ ),+ child: Row(+ children: [+ const SwarmIcon(+ size: 14,+ color: Colors.white54,+ ),+ const SizedBox(width: 8),+ Expanded(+ child: SearchResultText(+ row.swarmName,+ matches: matches,+ style: const TextStyle(+ fontSize: 11,+ fontWeight: FontWeight.w600,+ color: Colors.white60,+ ),+ ),+ ),+ if (row.swarmId == search.app.activeSwarmId)+ const Text(+ 'Current swarm',+ style: TextStyle(+ fontSize: 10,+ color: Colors.white38,+ ),+ ),+ ],+ ),+ ),+ ),+ SizedBox(+ height: _rowHeight,+ child: ListTile(+ key: ValueKey(row.id),+ contentPadding: const EdgeInsets.symmetric(+ horizontal: 14,+ ),+ minTileHeight: _rowHeight,+ selected: search.cursor == i,+ selectedColor: Colors.white,+ selectedTileColor: grid.AppPalette.swarmAccent+ .withValues(alpha: .12),+ hoverColor: Colors.transparent,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(8),+ ),+ leading: row.agentId == null+ ? const SwarmIcon(+ size: 21,+ color: Colors.white60,+ )+ : EngineMark(engine: row.engine, size: 22),+ title: SearchResultText(+ row.title,+ matches: matches.where((m) => m.title),+ style: const TextStyle(+ fontSize: 14,+ color: Colors.white,+ ),+ ),+ subtitle: SearchResultText(+ row.detail,+ matches: matches.where((m) => !m.title),+ style: const TextStyle(+ fontSize: 12,+ color: Colors.white54,+ ),+ ),+ trailing: row.current+ ? const Icon(+ Icons.check,+ size: 16,+ color: Colors.white38,+ )+ : search.cursor == i+ ? const Icon(+ Icons.keyboard_return,+ size: 17,+ color: Colors.white60,+ )+ : null,+ onTap: () => _choose(row),+ ),+ ),+ ],+ );+ },+ ),+ ),+ if (!search.isCommandMode) ...[+ const Divider(height: 1, color: Colors.white12),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),+ child: Row(+ children: [+ TextButton(+ onPressed: widget.onAdd,+ key: const ValueKey('navigation-add-agent'),+ style: TextButton.styleFrom(foregroundColor: Colors.white70),+ child: const Text(+ 'Add an agent…',+ style: TextStyle(fontSize: 12),+ ),+ ),+ const Spacer(),+ TextButton(+ onPressed: search.selected == null+ ? null+ : () => _choose(search.selected!),+ style: TextButton.styleFrom(foregroundColor: Colors.white),+ child: const SwarmSearchActionLabel('Go to'),+ ),+ const SizedBox(width: 8),+ ],+ ),+ ),+ ],+ ],+ );+ }+}diff --git a/desktop/lib/widgets/swarm_search_input.dart b/desktop/lib/widgets/swarm_search_input.dartindex 6c642a879..e4c15fd57 100644--- a/desktop/lib/widgets/swarm_search_input.dart+++ b/desktop/lib/widgets/swarm_search_input.dart@@ -18,6 +18,7 @@ class SwarmSearchInput extends StatelessWidget {required this.onClose,required this.onChanged,this.onOpen,+ this.onNewAgent,this.groupId,this.onTapOutside,this.showClose = false,@@ -32,6 +33,7 @@ class SwarmSearchInput extends StatelessWidget {final VoidCallback onClose;final ValueChanged<String> onChanged;final VoidCallback? onOpen;+ final VoidCallback? onNewAgent;final Object? groupId;final VoidCallback? onTapOutside;final bool showClose, autofocus;@@ -52,6 +54,7 @@ class SwarmSearchInput extends StatelessWidget {onChoose: onChoose,onClose: onClose,onOpen: onOpen,+ onNewAgent: onNewAgent,child: TextField(key: inputKey,groupId: groupId ?? EditableText,@@ -66,8 +69,7 @@ class SwarmSearchInput extends StatelessWidget {cursorColor: grid.AppPalette.swarmAccent,textAlignVertical: TextAlignVertical.center,decoration: InputDecoration(- hintText:- search?.hint ?? 'Search agents, swarms, machines, projects…',+ hintText: search?.hint ?? 'Search agents to add…',hintStyle: const TextStyle(fontSize: 16, color: Colors.white60),prefixIcon: const Icon(Icons.search, size: 20, color: Colors.white60),prefixIconConstraints: const BoxConstraints(diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dartindex 5389b34e0..871c25653 100644--- a/desktop/lib/widgets/swarm_switcher.dart+++ b/desktop/lib/widgets/swarm_switcher.dart@@ -25,7 +25,6 @@ Future<SwarmSearchSelection?> showSwarmHistory(context: context,transitionDuration: Duration.zero,veilBlur: 0,- veilTint: const Color(0x66000000),builder: (_) => _SwarmHistory(search: search),);} finally {@@ -113,6 +112,7 @@ class SwarmSearchKeys extends StatelessWidget {required this.onChoose,required this.onClose,this.onOpen,+ this.onNewAgent,required this.child,});final SwarmSearchController? search;@@ -123,6 +123,7 @@ class SwarmSearchKeys extends StatelessWidget {/// A focused field may be ready for typing while its suggestions are closed./// The first navigation/accept key reveals them without choosing unseen work.final VoidCallback? onOpen;+ final VoidCallback? onNewAgent;final Widget child;@override@@ -154,14 +155,14 @@ class SwarmSearchKeys extends StatelessWidget {contextKind: KeymapContext.picker,composing: composing,actions: {+ if (onNewAgent != null) 'agent.new': () => run(onNewAgent!),if (search != null || onOpen != null) ...{'picker.accept': () => choose(false),'picker.add_here': () => choose(true),'picker.next': () => move(1),'picker.previous': () => move(-1),- if (search != null) 'picker.preview': search.togglePreview,'picker.cancel': onClose,- if (search?.history == null)+ if (search == null || search.allowsCommands)'navigation.commands': () {editing.value = const TextEditingValue(text: '> ',@@ -182,6 +183,13 @@ class SwarmSearchKeys extends StatelessWidget {bindings: search == null && onOpen == null? {}: {+ if (onNewAgent != null)+ const SingleActivator(+ LogicalKeyboardKey.keyN,+ meta: true,+ includeRepeats: false,+ ): () =>+ run(onNewAgent!),const SingleActivator(LogicalKeyboardKey.enter,includeRepeats: false,@@ -207,13 +215,6 @@ class SwarmSearchKeys extends StatelessWidget {const SingleActivator(LogicalKeyboardKey.arrowDown): () =>move(1),const SingleActivator(LogicalKeyboardKey.arrowUp): () => move(-1),- if (search != null)- const SingleActivator(- LogicalKeyboardKey.keyI,- meta: true,- includeRepeats: false,- ): () =>- run(search.togglePreview),const SingleActivator(LogicalKeyboardKey.keyN,control: true,@@ -260,7 +261,7 @@ double swarmSearchResultsHeight(swarmSearchRowHeight(scale, commands: search.isCommandMode) +52;-/// Shared results for the title bar, New swarm field and History.+/// Shared Add agent results, also used for commands and History.class SwarmSearchResults extends StatefulWidget {const SwarmSearchResults({super.key,@@ -268,11 +269,13 @@ class SwarmSearchResults extends StatefulWidget {required this.onChoose,required this.onRefocus,this.onCommands,+ this.onNewAgent,});final SwarmSearchController search;final ValueChanged<SwarmSearchSelection> onChoose;final VoidCallback onRefocus;final VoidCallback? onCommands;+ final VoidCallback? onNewAgent;@overrideState<SwarmSearchResults> createState() => _SwarmSearchResultsState();}@@ -342,14 +345,17 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {return LayoutBuilder(builder: (context, constraints) {final showPreview =- search.previewVisible && constraints.maxWidth >= 600;+ search.previewVisible || (search.adding && !search.isCommandMode);return Semantics(container: true,label: 'Search results',child: Column(children: [Expanded(- child: Row(+ child: Flex(+ direction: constraints.maxWidth >= 600+ ? Axis.horizontal+ : Axis.vertical,crossAxisAlignment: CrossAxisAlignment.stretch,children: [Expanded(@@ -359,6 +365,10 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {child: Text(search.isCommandMode? 'No matching commands'+ : search.adding && search.query.isEmpty+ ? 'Choose New agent to start fresh.'+ : search.adding+ ? 'No matching agents': 'No matching results',style: const TextStyle(fontSize: 14,@@ -381,6 +391,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {enabled: search.canSubmit(row),selected: index == search.cursor,selectedColor: Colors.white,+ hoverColor: Colors.transparent,selectedTileColor: Colors.white.withValues(alpha: .075,),@@ -425,7 +436,15 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {color: Colors.white60,),),- trailing: row.shortcut == null+ trailing: search.alreadyHere(row)+ ? const Text(+ 'In this swarm',+ style: TextStyle(+ fontSize: 11,+ color: Colors.white38,+ ),+ )+ : row.shortcut == null? null: Text(row.shortcut!,@@ -442,12 +461,16 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {),),if (showPreview) ...[- const VerticalDivider(width: 1, color: Colors.white12),+ if (constraints.maxWidth >= 600)+ const VerticalDivider(width: 1, color: Colors.white12)+ else+ const Divider(height: 1, color: Colors.white12),Expanded(flex: 4,child: _OutputPreview(- row: selected!,+ row: selected,text: search.preview?.text ?? '',+ members: search.previewMembers,),),],@@ -461,7 +484,24 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {padding: const EdgeInsets.symmetric(horizontal: 12),child: Row(children: [- if (widget.onCommands != null)+ if (widget.onNewAgent != null)+ TextButton.icon(+ key: const ValueKey('swarm-search-new-agent'),+ onPressed: search.canCreate+ ? widget.onNewAgent+ : null,+ style: TextButton.styleFrom(+ foregroundColor: Colors.white,+ ),+ icon: const Icon(Icons.add, size: 16),+ label: const Text(+ 'New agent',+ style: TextStyle(fontSize: 12),+ ),+ ),+ if (widget.onCommands != null &&+ (widget.onNewAgent == null ||+ constraints.maxWidth >= 900))TextButton(key: const ValueKey('swarm-search-commands'),onPressed: widget.onCommands,@@ -473,12 +513,15 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {style: TextStyle(fontSize: 12),),),- if (selected != null && !search.canSubmit(selected))+ if ((selected != null && !search.canSubmit(selected)) ||+ search.adding && !search.canCreate)Expanded(child: Text(- selected.isGroup &&- selected.members.length >- AppNotifier.maxPanes+ search.adding+ ? search.unavailableMessage+ : selected!.isGroup &&+ selected.members.length >+ AppNotifier.maxPanes? 'A swarm supports up to ${AppNotifier.maxPanes} agents': 'No room to open this ${selected.isSwarm || selected.isGroup ? 'swarm' : 'agent'}',maxLines: 1,@@ -491,43 +534,15 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {)elseconst Spacer(),- if (constraints.maxWidth >= 600 &&- (search.canPreview ||- search.previewEnabled && !search.isCommandMode))- IconButton(- key: const ValueKey('swarm-search-preview-toggle'),- tooltip: [- search.previewEnabled- ? 'Hide preview'- : 'Show preview',- if (effectiveCommandHint(- context,- 'picker.preview',- contextKind: KeymapContext.picker,- )- case final hint?)- '($hint)',- ].join(' '),- onPressed: () {- search.togglePreview();- widget.onRefocus();- },- icon: Icon(- search.previewEnabled- ? Icons.visibility_outlined- : Icons.visibility_off_outlined,- size: 18,- color: Colors.white60,- ),- visualDensity: VisualDensity.compact,- ),- if (search.canAdd(selected))+ if (!search.adding &&+ search.canAdd(selected) &&+ constraints.maxWidth >= 900)TextButton(onPressed: () => widget.onChoose(search.addHere()!),style: TextButton.styleFrom(foregroundColor: Colors.white70,),- child: const _SearchActionLabel(+ child: const SwarmSearchActionLabel('Add to this swarm',command: 'picker.add_here',),@@ -537,10 +552,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {style: TextButton.styleFrom(foregroundColor: Colors.white,),- child: _SearchActionLabel(- selected == null- ? 'Go to'- : SwarmSearchController.action(selected),+ child: SwarmSearchActionLabel(+ search.actionLabel(selected),),),],@@ -555,8 +568,12 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {}}-class _SearchActionLabel extends StatelessWidget {- const _SearchActionLabel(this.label, {this.command = 'picker.accept'});+class SwarmSearchActionLabel extends StatelessWidget {+ const SwarmSearchActionLabel(+ this.label, {+ super.key,+ this.command = 'picker.accept',+ });final String label;final String command;@@ -600,86 +617,152 @@ class _SearchActionLabel extends StatelessWidget {}class _OutputPreview extends StatelessWidget {- const _OutputPreview({required this.row, required this.text});- final SwarmDestination row;+ const _OutputPreview({+ required this.row,+ required this.text,+ required this.members,+ });+ final SwarmDestination? row;final String text;+ final List<SwarmDestination> members;@override- Widget build(BuildContext context) => Container(- key: const ValueKey('swarm-search-preview'),- color: Colors.black.withValues(alpha: 0.10),- padding: const EdgeInsets.all(20),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- row.agentId == null ? 'SWARM PREVIEW' : 'AGENT PREVIEW',- style: const TextStyle(- fontSize: 10,- letterSpacing: 1.3,- color: Colors.white54,+ Widget build(BuildContext context) {+ final row = this.row;+ if (row == null) {+ return const Center(+ key: ValueKey('swarm-search-preview'),+ child: Padding(+ padding: EdgeInsets.all(24),+ child: Text(+ 'Choose an agent to preview its work.',+ textAlign: TextAlign.center,+ style: TextStyle(color: Colors.white38, fontSize: 13, height: 1.5),),),- const SizedBox(height: 18),- Row(+ );+ }+ return Container(+ key: const ValueKey('swarm-search-preview'),+ color: Colors.black.withValues(alpha: .10),+ child: SingleChildScrollView(+ primary: false,+ padding: const EdgeInsets.all(24),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,children: [- if (row.agentId == null)- const SwarmIcon(size: 20, color: Colors.white70)- else- EngineMark(engine: row.engine, size: 20),- const SizedBox(width: 10),- Expanded(- child: Text(- row.title,- maxLines: 2,- overflow: TextOverflow.ellipsis,- style: const TextStyle(- fontSize: 15,- fontWeight: FontWeight.w500,- color: Colors.white,+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (row.agentId == null)+ const SwarmIcon(size: 24, color: Colors.white70)+ else+ EngineMark(engine: row.engine, size: 24),+ const SizedBox(width: 12),+ Expanded(+ child: Text(+ row.title,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(+ fontSize: 16,+ height: 1.35,+ fontWeight: FontWeight.w600,+ color: Colors.white,+ ),+ ),),- ),+ ],),- ],- ),- const SizedBox(height: 8),- Text(- row.detail,- maxLines: 3,- overflow: TextOverflow.ellipsis,- style: const TextStyle(- fontSize: 12,- height: 1.5,- color: Colors.white60,- ),- ),- const SizedBox(height: 24),- Expanded(- child: SingleChildScrollView(- primary: false,- child: Text(- row.agentId == null- ? 'Work with the agents in this swarm side by side.'- : text.isEmpty- ? 'No recent output available.'- : text,- style: TextStyle(- fontFamily: text.isEmpty- ? grid.AppFont.sans- : grid.AppFont.mono,- fontFamilyFallback: text.isEmpty- ? grid.AppFont.sansFallback- : grid.AppFont.monoFallback,+ const SizedBox(height: 12),+ Text(+ row.detail,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 12,- height: 1.65,- color: text.isEmpty- ? Colors.white60- : Colors.white.withValues(alpha: .85),+ height: 1.5,+ color: Colors.white54,),),- ),+ const SizedBox(height: 24),+ Text(+ row.agentId != null+ ? 'Recent output'+ : row.isProject+ ? 'Agents in this project'+ : row.isMachine+ ? 'Agents on this machine'+ : 'Agents in this swarm',+ style: const TextStyle(+ fontSize: 11,+ fontWeight: FontWeight.w500,+ color: Colors.white54,+ ),+ ),+ const SizedBox(height: 10),+ if (row.agentId != null)+ Container(+ width: double.infinity,+ padding: const EdgeInsets.all(16),+ decoration: BoxDecoration(+ color: Colors.white.withValues(alpha: .035),+ borderRadius: BorderRadius.circular(8),+ border: Border.all(+ color: Colors.white.withValues(alpha: .06),+ ),+ ),+ child: Text(+ text.isEmpty ? 'No recent output yet.' : text,+ maxLines: 12,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontFamily: grid.AppFont.sans,+ fontFamilyFallback: grid.AppFont.sansFallback,+ fontSize: 13,+ height: 1.6,+ color: text.isEmpty+ ? Colors.white54+ : Colors.white.withValues(alpha: .82),+ ),+ ),+ )+ else if (members.isEmpty)+ const Text(+ 'No agents yet.',+ style: TextStyle(fontSize: 13, color: Colors.white54),+ )+ else ...[+ for (final member in members.take(5))+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: Row(+ children: [+ EngineMark(engine: member.engine, size: 18),+ const SizedBox(width: 10),+ Expanded(+ child: Text(+ member.title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(+ fontSize: 13,+ color: Colors.white70,+ ),+ ),+ ),+ ],+ ),+ ),+ if (members.length > 5)+ Text(+ '+ ${members.length - 5} more',+ style: const TextStyle(fontSize: 12, color: Colors.white54),+ ),+ ],+ ],),- ],- ),- );+ ),+ );+ }}diff --git a/desktop/lib/widgets/swarm_welcome.dart b/desktop/lib/widgets/swarm_welcome.dartindex 587add8fa..df6e19b8b 100644--- a/desktop/lib/widgets/swarm_welcome.dart+++ b/desktop/lib/widgets/swarm_welcome.dart@@ -41,12 +41,10 @@ class SwarmWelcome extends StatelessWidget {grid.AppTheme.watch(context);final app = notifier;final groups = swarmProjects(app, projects);- final firstWorkspace =- app.swarms.every((swarm) => swarm.panes.isEmpty) &&- app.closedHistory.isEmpty;- final agents = firstWorkspace ? swarmAgents(app) : const <SwarmAgentRef>[];+ // Every empty swarm offers the same actions. Available inventory can change+ // its guidance; whether another swarm was used must not change the product.+ final agents = swarmAgents(app);final noAgents =- firstWorkspace &&!app.machinesLoading &&agents.isEmpty &&groups.isEmpty &&@@ -105,7 +103,7 @@ class SwarmWelcome extends StatelessWidget {Text(noAgents? 'Choose a project folder and an agent. Add more whenever you want to work side by side.'- : 'A swarm keeps related agents together. Open a machine or project to bring its agents into this tab.',+ : 'Bring existing agents together, or start a new one. Work with them side by side in this tab.',style: const TextStyle(fontSize: 13,color: Color(0xffe0dce3),@@ -151,7 +149,7 @@ class SwarmWelcome extends StatelessWidget {crossAxisAlignment: CrossAxisAlignment.start,children: [const Text(- 'Go to an agent',+ 'Add an existing agent',style: TextStyle(fontSize: 13,fontWeight: FontWeight.w600,diff --git a/desktop/lib/widgets/task_palette.dart b/desktop/lib/widgets/task_palette.dartindex be201513f..0a8c59f41 100644--- a/desktop/lib/widgets/task_palette.dart+++ b/desktop/lib/widgets/task_palette.dart@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';import '../core/models.dart';import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';import '../state/app_state.dart';import 'engine_identity.dart';@@ -113,7 +114,7 @@ abstract final class _D {static const innerLight = Color(0x0FFFFFFF);/// The veil.- static const veil = Color(0xBD000000); // rgba(0,0,0,.74)+ static const veil = kDialogVeilTint;static const veilBlur = 3.0;/// ABOVE the middle, deliberately: the list grows downwards, and a box pinned to the centre woulddiff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 927c4e484..d66a75d78 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -111,9 +111,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {private func setKeymap(_ map: HarnessNativeKeymap) {keymap = maplet hint = map.hint(for: "navigation.quick_open", context: "workspace")- strip.searchButton.toolTip = hint.map { "Search (\($0))" } ?? "Search"- let newHint = map.hint(for: "agent.new", context: "workspace")- strip.newAgentButton.toolTip = newHint.map { "New agent (\($0))" } ?? "New agent"+ strip.searchButton.toolTip = hint.map { "Navigate (\($0))" } ?? "Navigate"if let main = NSApp.mainMenu, let window {let menu = main as? HarnessKeymapMenu ?? HarnessKeymapMenu.replacing(main)if NSApp.mainMenu !== menu { NSApp.mainMenu = menu }@@ -219,13 +217,12 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {install(agent, at: 2)rebuildHistoryMenu()- let windowIndex = main.items.firstIndex(where: { $0.title == "Window" }) ?? main.numberOfItems- install(historyMenu, at: windowIndex)+ install(historyMenu, at: 3)// Native menu hints mirror Flutter; the shared picker owns all editing.if let edit = main.item(withTitle: "Edit")?.submenu {edit.addItem(.separator())- add(edit, "Search Agents and Swarms…", "p", "jump")+ add(edit, "Navigate to Agent or Swarm…", "p", "jump")add(edit, "Search Commands…", "p", "commands", [.command, .shift])}if let view = main.item(withTitle: "View")?.submenu {@@ -235,7 +232,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {modelsMenu.autoenablesItems = falsemodelsMenu.delegate = selfrebuildModelsMenu()- install(modelsMenu, at: windowIndex + 1)+ install(modelsMenu, at: 3)installTerminalFindMenu(main)}@@ -662,7 +659,6 @@ private final class SwarmTabStrip: NSView {private let document = NSView()private let newButton = NSButton()fileprivate let searchButton = NSButton()- fileprivate let newAgentButton = NSButton()fileprivate let notificationButton = SwarmNotificationButton()private var tabs: [SwarmTabButton] = []private var activeId = ""@@ -694,11 +690,8 @@ private final class SwarmTabStrip: NSView {}button(newButton, "plus", "New swarm (⌘T)", #selector(newSwarm))newButton.isEnabled = false- button(searchButton, "magnifyingglass", "Search (⌘P)", #selector(openSearch))- button(newAgentButton, "plus", "New agent (⌘N)", #selector(newAgent))- newAgentButton.imagePosition = .imageOnly- newAgentButton.setAccessibilityLabel("New agent")- newAgentButton.isEnabled = false+ button(searchButton, "safari", "Navigate (⌘P)", #selector(openSearch))+ searchButton.setAccessibilityLabel("Navigate")button(notificationButton, "bell", "Notifications", #selector(openNotifications))searchButton.isEnabled = falsenotificationButton.isEnabled = false@@ -711,7 +704,6 @@ private final class SwarmTabStrip: NSView {guard nextPalette != palette else { return }palette = nextPalettesearchButton.contentTintColor = palette.accent- newAgentButton.contentTintColor = palette.accentnotificationButton.contentTintColor = palette.accentnewButton.contentTintColor = palette.accentfor tab in tabs { tab.palette = palette }@@ -754,7 +746,6 @@ private final class SwarmTabStrip: NSView {document.setAccessibilityChildren(tabs)newButton.isEnabled = actionsEnabled && tabs.count < 24searchButton.isEnabled = actionsEnabled- newAgentButton.isEnabled = actionsEnablednotificationButton.isEnabled = actionsEnabledlet attention = state["attention"] as? Int ?? 0notificationButton.hasAttention = attention > 0@@ -781,7 +772,7 @@ private final class SwarmTabStrip: NSView {let activeWasVisible = active.map { scroll.documentVisibleRect.intersects($0.frame) } ?? falselet previousScrollSize = scroll.frame.sizelet previousDocumentSize = document.frame.size- let available = max(132, bounds.width - 164)+ let available = max(132, bounds.width - 124)let width = min(220, max(132, available / CGFloat(max(1, tabs.count))))let occupied = min(available, CGFloat(tabs.count) * width)scroll.frame = NSRect(x: 0, y: 0, width: occupied, height: bounds.height)@@ -792,8 +783,7 @@ private final class SwarmTabStrip: NSView {}let buttonY = (bounds.height - 28) / 2newButton.frame = NSRect(x: occupied + 4, y: buttonY, width: 28, height: 28)- searchButton.frame = NSRect(x: bounds.width - 120, y: buttonY, width: 28, height: 28)- newAgentButton.frame = NSRect(x: bounds.width - 80, y: buttonY, width: 28, height: 28)+ searchButton.frame = NSRect(x: bounds.width - 80, y: buttonY, width: 28, height: 28)notificationButton.frame = NSRect(x: bounds.width - 40, y: buttonY, width: 28, height: 28)let geometryChanged = scroll.frame.size != previousScrollSize || document.frame.size != previousDocumentSizeif let active, revealActiveAfterLayout || (activeWasVisible && (geometryChanged || tabOrderChanged)) {@@ -823,11 +813,6 @@ private final class SwarmTabStrip: NSView {if actionsEnabled { emit?("notifications", nil) }}- @objc private func newAgent() {- guard actionsEnabled else { return }- emit?("newAgent", nil)- }-private func draggedTab(_ sender: NSDraggingInfo) -> SwarmTabButton? {guard actionsEnabled, sender.draggingSourceOperationMask.contains(.move),let source = sender.draggingSource as? SwarmTabButton,diff --git a/desktop/test/benchmarks/swarm_benchmark.dart b/desktop/test/benchmarks/swarm_benchmark.dartindex 36239c341..725525322 100644--- a/desktop/test/benchmarks/swarm_benchmark.dart+++ b/desktop/test/benchmarks/swarm_benchmark.dart@@ -98,7 +98,7 @@ void main() {);}- test('large live catalog CPU benchmark', () {+ test('large live catalog CPU benchmark', () async {final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession());addTearDown(app.dispose);for (var machine = 0; machine < 8; machine++) {@@ -145,12 +145,12 @@ void main() {swarmProjects(app, const []);})})}',);- // Exercise the current unified bar, including project/machine metadata,- // instead of using the older agent-only catalog as its performance proxy.+ // Exercise Add agent with all discovered project/machine metadata. Global+ // navigation is measured separately over exact, already-open locations.final cache = SwarmSearchCatalog();final entries = cache.read(app, const []);expect(entries, hasLength(2059));- final controller = SwarmSearchController(app, const []);+ final controller = SwarmSearchController(app, const [], adding: true);addTearDown(controller.dispose);final queries = <String, Object>{};for (final query in [@@ -166,21 +166,52 @@ void main() {);queries[query] = {...timing, 'results': controller.rows.length};}- controller.setQuery('');- controller.submit(entries.singleWhere((e) => e.id == 'machine:machine-3'));- expect(controller.rows, hasLength(250));- final scoped = measure(- () => controller.setQuery('agn12'),- setup: () => controller.setQuery(''),- );debugPrint(- 'SWARM_BENCH ${jsonEncode({'kind': 'headless_debug_cpu', 'operation': 'unified_search', 'agents': 2000, 'machines': 8, 'projects': 50, 'entries': entries.length, 'coldCatalog': measure(() {+ 'SWARM_BENCH ${jsonEncode({'kind': 'headless_debug_cpu', 'operation': 'add_agent_search', 'agents': 2000, 'machines': 8, 'projects': 50, 'entries': entries.length, 'coldCatalog': measure(() {SwarmSearchCatalog().read(app, const []);}), 'unchangedCatalog': measure(() {cache.read(app, const []);}), 'openAndDisposeController': measure(() {- SwarmSearchController(app, const []).dispose();- }), 'queries': queries, 'scopedQuery': scoped})}',+ SwarmSearchController(app, const [], adding: true).dispose();+ }), 'queries': queries})}',+ );+ for (var swarm = 0; swarm < 12; swarm++) {+ if (swarm != 0) app.newSwarm();+ for (var pane = 0; pane < 4; pane++) {+ app.adoptSessionForTest(+ TerminalSession(+ machineId: 'machine-${swarm % 8}',+ agentId: 'agent-${swarm * 4 + pane}',+ agentName: 'Agent ${swarm * 4 + pane}',+ engineId: 'codex',+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ )..status = TerminalSessionStatus.controlling,+ );+ }+ if (swarm == 1 || swarm == 2) {+ await app.addAgentToSwarm('machine-0', 'agent-0');+ }+ }+ final locations = SwarmLocationCatalog();+ final open = locations.read(app, const []);+ expect(open, hasLength(62));+ expect(+ open.where((r) => r.agentId == 'agent-0' && r.machineId == 'machine-0'),+ hasLength(3),+ );+ final navigator = SwarmSearchController(app, const [], navigating: true);+ addTearDown(navigator.dispose);+ debugPrint(+ 'SWARM_BENCH ${jsonEncode({'kind': 'headless_debug_cpu', 'operation': 'navigation_locations', 'discoveredAgents': 2000, 'swarms': 12, 'agentLocations': 50, 'entries': open.length, 'coldCatalog': measure(() {+ SwarmLocationCatalog().read(app, const []);+ }), 'unchangedCatalog': measure(() {+ locations.read(app, const []);+ }), 'openAndDisposeController': measure(() {+ SwarmSearchController(app, const [], navigating: true).dispose();+ }), 'query': measure(() {+ navigator.setQuery('agent 0 machine 0');+ }, setup: () => navigator.setQuery(''))})}',);});diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dartindex c1413ea99..fe98367b0 100644--- a/desktop/test/first_workspace_test.dart+++ b/desktop/test/first_workspace_test.dart@@ -159,7 +159,7 @@ void main() {for (final native in [false, true]) {testWidgets(- 'new agent toolbar ${native ? 'native' : 'Flutter'} action inherits the focused working folder',+ 'new agent ${native ? 'native menu' : 'floating picker'} action inherits the focused working folder',(tester) async {tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('harness/swarm_tabs'),@@ -193,18 +193,24 @@ void main() {await opening;} else {final search = find.byKey(const ValueKey('swarm-search-button'));- final add = find.byKey(const ValueKey('swarm-new-agent-button'));+ final add = find.byKey(const ValueKey('swarm-add-agent-button'));final bell = find.byKey(const ValueKey('swarm-notifications-button'));expect(tester.getRect(search).right,- lessThanOrEqualTo(tester.getRect(add).left),+ lessThanOrEqualTo(tester.getRect(bell).left),);+ expect(tester.getRect(add).left, greaterThan(1000));expect(- tester.getRect(add).right,- lessThanOrEqualTo(tester.getRect(bell).left),+ tester.getRect(add).top,+ greaterThan(tester.getRect(find.byKey(pane.cellKey)).bottom),);await tester.tap(add);await tester.pump();+ expect(find.byType(AlertDialog), findsNothing);+ await tester.tap(+ find.byKey(const ValueKey('swarm-search-new-agent')),+ );+ await tester.pump();}expect(find.byType(AlertDialog), findsOneWidget);expect(find.text('/work/existing'), findsOneWidget);@@ -417,7 +423,7 @@ void main() {app.dispose();});- testWidgets('existing agents open directly from an empty workspace', (+ testWidgets('every empty swarm offers the same existing-agent addition', (tester,) async {final app = _FirstUseApp();@@ -431,9 +437,28 @@ void main() {];await mount(tester, app);expect(app.panes, isEmpty);+ expect(find.text('Add an existing agent'), findsOneWidget);+ expect(find.text('Go to an agent'), findsNothing);await tester.tap(find.byKey(const ValueKey('welcome-agent:m:existing')));await tester.pump();expect(app.panes.single.agentId, 'existing');+ final source = app.activeSwarm;+ final pane = app.panes.single;+ app.newSwarm();+ await tester.pump();+ expect(find.text('Add an existing agent'), findsOneWidget);+ expect(find.text('New agent'), findsOneWidget);+ expect(find.text('Go to an agent'), findsNothing);+ await tester.tap(find.byKey(const ValueKey('welcome-agent:m:existing')));+ await tester.pump();+ expect(app.panes.single, same(pane));+ expect(source.panes.single, same(pane));+ final used = app.activeSwarmId;+ await app.closeSwarm(used);+ app.newSwarm();+ await tester.pump();+ expect(app.closedHistory, isNotEmpty);+ expect(find.text('Add an existing agent'), findsOneWidget);expect(app.launches, isEmpty);expect(find.text('Go to an agent'), findsNothing);expect(tester.takeException(), isNull);diff --git a/desktop/test/keymap_runtime_test.dart b/desktop/test/keymap_runtime_test.dartindex 655e3abe3..f6569ed26 100644--- a/desktop/test/keymap_runtime_test.dart+++ b/desktop/test/keymap_runtime_test.dart@@ -13,6 +13,7 @@ import 'package:harness/state/app_state.dart';import 'package:harness/state/swarm_catalog.dart';import 'package:harness/terminal/terminal_binary.dart';import 'package:harness/widgets/swarm_switcher.dart';+import 'package:harness/widgets/swarm_navigator.dart';import 'package:xterm/xterm.dart';import 'keymap_host_test.dart' show MemoryKeymap, key;@@ -125,9 +126,7 @@ void main() {{"keys":"down","command":null,"when":"picker"},{"keys":"ctrl+j","command":"picker.previous","when":"picker"},{"keys":"enter","command":null,"when":"picker"},- {"keys":"alt+enter","command":"picker.accept","when":"picker"},- {"keys":"cmd+i","command":null,"when":"picker"},- {"keys":"ctrl+i","command":"picker.preview","when":"picker"}+ {"keys":"alt+enter","command":"picker.accept","when":"picker"}]}''');final app = createApp();app.machineStates['m']!.nodeOnline = true;@@ -135,6 +134,7 @@ void main() {final pane = app.adoptSessionForTest(terminal('a0', frames));final original = app.activeSwarmId;app.newSwarm();+ final addingTo = app.activeSwarmId;await mount(tester, app, map);final input = find.byKey(ValueKey(@@ -148,9 +148,11 @@ void main() {}await tester.enterText(input, 'Agent');await tester.pump();- final search = tester- .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))- .search;+ final search = inline+ ? tester+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))+ .search+ : tester.widget<SwarmNavigator>(find.byType(SwarmNavigator)).search;final initial = search.cursor;await key(tester, LogicalKeyboardKey.arrowDown);expect(search.cursor, initial);@@ -158,16 +160,19 @@ void main() {expect(search.cursor, (initial - 1) % search.rows.length);await tester.enterText(input, 'Agent 0');await tester.pump();- expect(find.byTooltip('Hide preview (⌃I)'), findsOneWidget);- await key(tester, LogicalKeyboardKey.keyI, cmd: true);- expect(search.previewEnabled, isTrue);- await key(tester, LogicalKeyboardKey.keyI, ctrl: true);- expect(search.previewEnabled, isFalse);+ expect(search.previewVisible, inline);+ expect(+ find.byKey(const ValueKey('swarm-search-preview-toggle')),+ findsNothing,+ );await key(tester, LogicalKeyboardKey.enter);- expect(find.byType(SwarmSearchResults), findsOneWidget);+ expect(+ find.byType(inline ? SwarmSearchResults : SwarmNavigator),+ findsOneWidget,+ );expect(frames, isEmpty);await key(tester, LogicalKeyboardKey.enter, alt: true);- expect(app.activeSwarmId, original);+ expect(app.activeSwarmId, inline ? addingTo : original);expect(app.focusedPane, same(pane));expect(find.byType(SwarmSearchResults), findsNothing);await key(tester, LogicalKeyboardKey.arrowLeft);@@ -402,15 +407,7 @@ void main() {'Agent 0',);await tester.pump();- await native(tester, 'keymapCommand', {'command': 'picker.preview'});- await tester.pump();- expect(find.byKey(const ValueKey('swarm-search-preview')), findsNothing);- await native(tester, 'keymapCommand', {'command': 'picker.preview'});- await tester.pump();- expect(- find.byKey(const ValueKey('swarm-search-preview')),- findsOneWidget,- );+ expect(find.byType(SwarmNavigator), findsOneWidget);await native(tester, 'keymapCommand', {'command': 'picker.accept'});await tester.pump();expect(find.byType(SwarmSearchResults), findsNothing);diff --git a/desktop/test/keymap_test.dart b/desktop/test/keymap_test.dartindex 489634587..b3df22ee0 100644--- a/desktop/test/keymap_test.dart+++ b/desktop/test/keymap_test.dart@@ -18,6 +18,14 @@ KeymapMatch match(]) => map.match(context, keys.split(' ').map(KeyStroke.parse));void main() {+ test('a retired preview binding does not break other custom shortcuts', () {+ final config = KeymapConfig.parse('''{"bindings":[+ {"keys":"cmd+i","command":"picker.preview","when":"picker"},+ {"keys":"cmd+ctrl+h","command":"pane.focus_left"}+ ]}''', commands: commands);+ expect(config.bindings.single.command, 'pane.focus_left');+ });+test('dotfile accepts comments, aliases and trailing commas', () {final config = KeymapConfig.parse('''// Keep the defaults and add my preferred movement key.diff --git a/desktop/test/search_workspace_test.dart b/desktop/test/search_workspace_test.dartindex a5649e75a..1fc80612f 100644--- a/desktop/test/search_workspace_test.dart+++ b/desktop/test/search_workspace_test.dart@@ -4,7 +4,7 @@ import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/terminal/terminal_binary.dart';import 'package:harness/widgets/swarm_icon.dart';-import 'package:harness/widgets/swarm_search_input.dart';+import 'package:harness/widgets/swarm_navigator.dart';import 'keymap_host_test.dart' show MemoryKeymap, key;import 'keymap_runtime_test.dart' show mount;@@ -41,7 +41,7 @@ void main() {await key(tester, LogicalKeyboardKey.keyP, cmd: true);await tester.pump();expect(field, findsOneWidget);- expect(find.byType(SwarmSearchInput), findsOneWidget);+ expect(find.byType(SwarmNavigator), findsOneWidget);final controller = tester.widget<TextField>(field).controller!;final focus = tester.widget<TextField>(field).focusNode!;expect(focus.hasFocus, isTrue);@@ -55,15 +55,14 @@ void main() {expect(tester.widget<ListTile>(selected).key, first);await tester.enterText(field, 'Agent 0');await tester.pump();- final results = tester.getRect(- find.byKey(const ValueKey('swarm-search-result-list')),+ expect(+ find.byKey(const ValueKey('swarm-navigation-locations')),+ findsOneWidget,);- final preview = tester.getRect(+ expect(find.byKey(const ValueKey('swarm-search-preview')),+ findsNothing,);- expect(preview.left, greaterThanOrEqualTo(results.right));- expect(preview.top, results.top);- expect(find.textContaining('All checks passed'), findsOneWidget);await key(tester, LogicalKeyboardKey.keyA, cmd: true);expect(controller.selection.textInside(controller.text), 'Agent 0');await key(tester, LogicalKeyboardKey.backspace);@@ -87,6 +86,22 @@ void main() {expect(input, isEmpty);await key(tester, LogicalKeyboardKey.escape);expect(field, findsNothing);+ await tester.tap(find.byKey(const ValueKey('swarm-add-agent-button')));+ await tester.pump();+ await tester.enterText(field, 'Agent 0');+ await tester.pump();+ final results = tester.getRect(+ find.byKey(const ValueKey('swarm-search-result-list')),+ );+ final preview = tester.getRect(+ find.byKey(const ValueKey('swarm-search-preview')),+ );+ expect(preview.left, greaterThanOrEqualTo(results.right));+ expect(preview.top, results.top);+ expect(find.textContaining('All checks passed'), findsOneWidget);+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);+ expect(input, isEmpty);+ await key(tester, LogicalKeyboardKey.escape);await tester.pumpWidget(const SizedBox());app.dispose();map.dispose();diff --git a/desktop/test/swarm_add_agent_test.dart b/desktop/test/swarm_add_agent_test.dartnew file mode 100644index 000000000..c8e7889ed--- /dev/null+++ b/desktop/test/swarm_add_agent_test.dart@@ -0,0 +1,135 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/state/pane_arrangement.dart';+import 'package:harness/state/swarm_navigation.dart';+import 'package:harness/state/swarm_search.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:xterm/xterm.dart';++import 'swarm_interactions_test.dart' show chord;+import 'swarm_screen_test.dart' show mount, terminal;+import 'swarm_state_test.dart' show createApp;++void main() {+ testWidgets(+ 'floating Add agent keeps the destination and reuses the chosen session',+ (tester) async {+ final app = createApp();+ final input = <TerminalBinaryFrame>[];+ final shared = app.adoptSessionForTest(terminal('a0', input));+ final source = app.activeSwarm;+ app.newSwarm(name: 'Review');+ final existing = app.adoptSessionForTest(terminal('a1', input));+ final target = app.activeSwarm;+ await mount(tester, app);+ tester.view.physicalSize = const Size(880, 560);+ await tester.pump();+ final add = find.byKey(const ValueKey('swarm-add-agent-button'));+ expect(tester.getRect(add).left, greaterThan(780));+ expect(+ tester.getRect(add).top,+ greaterThan(tester.getRect(find.byKey(existing.cellKey)).bottom),+ );+ await tester.tap(add);+ await tester.pump();+ await tester.enterText(+ find.byKey(const ValueKey('swarm-search-input')),+ 'Agent 0',+ );+ await tester.pump();+ expect(find.text('Add to this swarm'), findsOneWidget);+ expect(find.text('Go to agent'), findsNothing);+ expect(find.byType(AlertDialog), findsNothing);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(app.activeSwarm, same(target));+ expect(target.panes, [existing, shared]);+ expect(source.panes, [shared]);+ expect(input, isEmpty);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );++ for (final axis in PaneResizeAxis.values) {+ testWidgets(+ 'split ${axis.name} chooses an existing agent and preserves its neighbors',+ (tester) async {+ final app = createApp();+ final input = <TerminalBinaryFrame>[];+ final first = app.adoptSessionForTest(terminal('a0', input));+ final neighbor = app.adoptSessionForTest(terminal('a1', input));+ final target = app.activeSwarm;+ app.newSwarm(name: 'Elsewhere');+ final shared = app.adoptSessionForTest(terminal('a2', input));+ final source = app.activeSwarm;+ app.selectSwarm(target.id);+ app.focusPane(first.id);+ await mount(tester, app);+ tester.view.physicalSize = const Size(3000, 1800);+ await tester.pump();+ final neighborRect = tester.getRect(find.byKey(neighbor.cellKey));+ final expected = app.preparePaneSplit(axis)!;+ await chord(tester, LogicalKeyboardKey.keyP);+ final inputField = find.byKey(const ValueKey('swarm-search-input'));+ await tester.enterText(+ inputField,+ axis == PaneResizeAxis.x ? '> split right' : '> split down',+ );+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(find.byType(AlertDialog), findsNothing);+ expect(app.panes, [first, neighbor]);+ await tester.enterText(inputField, 'Agent 2');+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(app.panes, [first, shared, neighbor]);+ expect(source.panes, [shared]);+ expect(app.activeSwarm.manualLayout!.tiles, expected.after.tiles);+ expect(tester.getRect(find.byKey(neighbor.cellKey)), neighborRect);+ expect(input, isEmpty);+ expect(find.byType(TerminalView), findsNWidgets(3));+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );+ }++ test(+ 'adding a group uses this swarm, skips duplicates and keeps the source',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ app.adoptSessionForTest(terminal('a0', []));+ app.adoptSessionForTest(terminal('a1', []));+ final source = app.activeSwarm;+ app.renameSwarm(source.id, 'Release');+ app.newSwarm(name: 'Review');+ final target = app.activeSwarm;+ await app.addAgentToSwarm('m', 'a0');+ final search = SwarmSearchController(app, [], adding: true);+ addTearDown(search.dispose);+ final row = search.rows.singleWhere(+ (row) => row.id == swarmDestinationId(source.id),+ );+ final choice = search.submit(row)!;+ expect(choice.action, SwarmSearchAction.addHere);+ expect(+ await activateSwarmSearchSelection(+ app,+ choice,+ destinationSwarmId: target.id,+ ),+ isTrue,+ );+ expect(app.activeSwarm, same(target));+ expect(target.panes, source.panes);+ expect(target.name, 'Review');+ expect(search.canAdd(row), isFalse);+ },+ );+}diff --git a/desktop/test/swarm_history_test.dart b/desktop/test/swarm_history_test.dartindex 1652f59ee..0adfae255 100644--- a/desktop/test/swarm_history_test.dart+++ b/desktop/test/swarm_history_test.dart@@ -317,7 +317,7 @@ void main() {await tester.pump();await settings;- // Native search opens the same centered Flutter editor and preview.+ // Native navigation opens the centered editor and exact locations.final jumping = native('jump');await tester.pump();expect(@@ -338,10 +338,7 @@ void main() {picker.center.dx,tester.view.physicalSize.width / tester.view.devicePixelRatio / 2,);- expect(- find.byKey(const ValueKey('swarm-search-preview')),- findsOneWidget,- );+ expect(find.byKey(const ValueKey('swarm-search-preview')), findsNothing);expect(otherInput, isEmpty);await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();diff --git a/desktop/test/swarm_inline_search_test.dart b/desktop/test/swarm_inline_search_test.dartindex bef56a0ad..45d87a320 100644--- a/desktop/test/swarm_inline_search_test.dart+++ b/desktop/test/swarm_inline_search_test.dart@@ -183,14 +183,15 @@ void main() {);testWidgets(- 'inline selection opens the existing agent and hands it the next key',+ 'inline selection adds the existing agent here and hands it the next key',(tester) async {final app = createApp();app.machineStates['m']!.nodeOnline = true;final frames = <TerminalBinaryFrame>[];final pane = app.adoptSessionForTest(terminal('a0', frames));- final original = app.activeSwarmId;+ final original = app.activeSwarm;app.newSwarm();+ final destination = app.activeSwarmId;await mount(tester, app);await tester.tap(_input);await tester.enterText(_input, 'Agent 0');@@ -198,7 +199,8 @@ void main() {expect(frames, isEmpty);await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();- expect(app.activeSwarmId, original);+ expect(app.activeSwarmId, destination);+ expect(original.panes.single, same(pane));expect(app.panes.single, same(pane));expect(_results, findsNothing);expect(diff --git a/desktop/test/swarm_navigator_test.dart b/desktop/test/swarm_navigator_test.dartnew file mode 100644index 000000000..b2c76984b--- /dev/null+++ b/desktop/test/swarm_navigator_test.dart@@ -0,0 +1,245 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/swarm_navigation.dart';+import 'package:harness/state/swarm_search.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/widgets/swarm_navigator.dart';+import 'package:harness/widgets/swarm_switcher.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() {+ test('each membership is an exact destination, never an implicit add or fallback', () async {+ final app = createApp();+ addTearDown(app.dispose);+ final pane = app.adoptSessionForTest(terminal('a0', []));+ final first = app.activeSwarm;+ app.renameSwarm(first.id, 'Release');+ app.newSwarm(name: 'Review');+ final second = app.activeSwarm;+ await app.addAgentToSwarm('m', 'a0');+ app.newSwarm(name: 'Research');+ final third = app.activeSwarm;+ await app.addAgentToSwarm('m', 'a0');+ final search = SwarmSearchController(app, [], navigating: true);+ addTearDown(search.dispose);+ search.setQuery('Agent 0');+ expect(search.rows.map((r) => r.swarmId).toSet(), {+ first.id,+ second.id,+ third.id,+ });+ expect(search.rows.map((r) => r.id).toSet(), hasLength(3));+ expect(search.previewVisible, isFalse);+ final exact = search.rows.singleWhere((r) => r.swarmId == second.id);+ expect(search.canAdd(exact), isFalse);+ expect(+ await activateSwarmDestination(app, exact, destinationSwarmId: third.id),+ isTrue,+ );+ expect(+ app.activeSwarmId,+ second.id,+ reason: 'The active swarm also contains this agent',+ );+ expect(app.focusedPane, same(pane));+ expect(first.panes, [pane]);+ expect(second.panes, [pane]);+ expect(third.panes, [pane]);+ await app.closeSwarm(second.id);+ final active = app.activeSwarmId;+ expect(+ await activateSwarmDestination(app, exact, destinationSwarmId: first.id),+ isFalse,+ );+ expect(+ app.activeSwarmId,+ active,+ reason: 'A removed location cannot redirect to another membership',+ );+ search.setQuery('Agent 69');+ expect(+ search.rows,+ isEmpty,+ reason: 'Discovered agents without a view belong to Add',+ );+ expect(search.submit(), isNull);+ });++ test('location search uses only its own swarm context and output reuses the catalog', () async {+ final app = createApp();+ addTearDown(app.dispose);+ final session = terminal('a0', []);+ app.adoptSessionForTest(session);+ app.renameSwarm(app.activeSwarmId, 'Release');+ app.newSwarm(name: 'Research');+ await app.addAgentToSwarm('m', 'a0');+ final catalog = SwarmLocationCatalog();+ final first = catalog.read(app, []);+ session.terminal.write('More output\r\n');+ app.dismissError();+ expect(catalog.read(app, []), same(first));+ final rows = rankSwarmLocations(first, 'Agent 0 Research');+ expect(rows, hasLength(1));+ expect(rows.single.swarmName, 'Research');+ });++ test(+ 'locations refresh discovered context and retain offline views',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ final session = terminal('a0', []);+ final pane = app.adoptSessionForTest(session);+ final catalog = SwarmLocationCatalog();+ final first = catalog.read(app, []);+ final machine = app.machineStates['m']!;+ machine.agents = const [+ Agent(+ id: 'a0',+ name: 'Changed title',+ engine: 'hermes',+ terminalAvailable: true,+ project: AgentProject(name: 'Updated project', cwd: '/work/updated'),+ ),+ ];+ final updated = catalog.read(app, []);+ expect(updated, isNot(same(first)));+ final changed = rankSwarmLocations(updated, 'Changed updated hermes');+ expect(changed, hasLength(1));+ expect(changed.single.paneId, pane.id);+ expect(changed.single.detail, contains('Updated project'));+ app.machineStates.clear();+ final retained = catalog+ .read(app, [])+ .singleWhere((r) => r.paneId != null);+ expect(retained.title, session.agentName);+ expect(retained.machineLabel, 'm');+ expect(retained.engine, session.engineId);+ expect(+ await activateSwarmDestination(+ app,+ retained,+ destinationSwarmId: app.activeSwarmId,+ ),+ isTrue,+ );+ expect(app.focusedPane, same(pane));+ },+ );++ testWidgets(+ 'navigation offers three locations and sends the next key only to the chosen agent',+ (tester) async {+ final app = createApp();+ final input = <TerminalBinaryFrame>[];+ final pane = app.adoptSessionForTest(terminal('a0', input));+ final first = app.activeSwarm;+ app.renameSwarm(first.id, 'Release');+ app.newSwarm(name: 'Review');+ final second = app.activeSwarm;+ await app.addAgentToSwarm('m', 'a0');+ app.newSwarm(name: 'Research');+ final third = app.activeSwarm;+ await app.addAgentToSwarm('m', 'a0');+ app.machineStates['m']!.nodeOnline = true;+ await mount(tester, app);+ await chord(tester, LogicalKeyboardKey.keyP);+ final field = find.byKey(const ValueKey('swarm-search-input'));+ await tester.enterText(field, 'Agent 0');+ await tester.pump();+ expect(find.byType(SwarmNavigator), findsOneWidget);+ expect(find.byType(SwarmSearchResults), findsNothing);+ expect(+ find.descendant(+ of: find.byType(SwarmNavigator),+ matching: find.text('Release'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: find.byType(SwarmNavigator),+ matching: find.text('Review'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: find.byType(SwarmNavigator),+ matching: find.text('Research'),+ ),+ findsOneWidget,+ );+ final pickerRect = tester.getRect(+ find.byKey(const ValueKey('swarm-search-results')),+ );+ await tester.tap(+ find.byKey(ValueKey(agentLocationId(second.id, pane.id))),+ );+ await tester.pump();+ expect(app.activeSwarm, same(second));+ expect(input, isEmpty);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);+ await tester.pump(const Duration(milliseconds: 10));+ expect(input.single.bytes, [27, 91, 68]);+ expect(first.panes, [pane]);+ expect(third.panes, [pane]);+ await tester.tap(find.byKey(const ValueKey('swarm-add-agent-button')));+ await tester.pump();+ expect(find.byType(SwarmNavigator), findsNothing);+ expect(find.byType(SwarmSearchResults), findsOneWidget);+ expect(+ tester+ .getRect(find.byKey(const ValueKey('swarm-search-results')))+ .width,+ greaterThan(pickerRect.width),+ );+ expect(find.text('New agent'), findsOneWidget);+ await tester.enterText(field, 'Agent 0');+ await tester.pump();+ expect(find.text('In this swarm'), findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(second.panes, [pane]);+ expect(find.byType(SwarmSearchResults), findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );++ testWidgets(+ 'an unmatched navigation query can enter Add without losing the query or changing membership',+ (tester) async {+ final app = createApp();+ final pane = app.adoptSessionForTest(terminal('a0', []));+ await mount(tester, app);+ await chord(tester, LogicalKeyboardKey.keyP);+ final input = find.byKey(const ValueKey('swarm-search-input'));+ await tester.enterText(input, 'Agent 69');+ await tester.pump();+ expect(find.textContaining('No matching open agents'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('navigation-add-agent')));+ await tester.pump();+ expect(tester.widget<TextField>(input).controller!.text, 'Agent 69');+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);+ expect(app.panes, [pane]);+ expect(find.text('New agent'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('swarm-search-preview')),+ findsOneWidget,+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );+}diff --git a/desktop/test/swarm_search_preview_test.dart b/desktop/test/swarm_search_preview_test.dartindex 213fb64c5..d072798f5 100644--- a/desktop/test/swarm_search_preview_test.dart+++ b/desktop/test/swarm_search_preview_test.dart@@ -11,6 +11,28 @@ import 'swarm_screen_test.dart' show mount, terminal;import 'swarm_state_test.dart' show createApp;void main() {+ test('preview joins wrapped prose and omits terminal decorations', () {+ final terminal = Terminal()..resize(42, 18);+ terminal.write(+ '> Simplify setup\r\n\r\n'+ ' Keep the working folder and agent choice when creation fails.\r\n'+ ' The retry can then start from the same place.\r\n\r\n'+ '— Worked for 2m 05s ─────────────────────\r\n'+ '— Conversation recap ───────────────────\r\n'+ ' Setup now preserves your choices.\r\n'+ '> ',+ );+ final before = terminal.buffer.getText();+ expect(+ SearchOutputPreview.capture(terminal).text,+ '> Simplify setup\n\n'+ 'Keep the working folder and agent choice when creation fails. '+ 'The retry can then start from the same place.\n\n'+ 'Setup now preserves your choices.',+ );+ expect(terminal.buffer.getText(), before);+ });+test('preview bounds scrollback, rows and columns without altering Unicode',() {@@ -28,7 +50,11 @@ void main() {final before = terminal.buffer.getText();final position = (terminal.buffer.cursorX, terminal.buffer.cursorY);final snapshot = SearchOutputPreview.capture(terminal).text;- expect(snapshot.split('\n').length, SearchOutputPreview.shownLines);+ expect(snapshot.split('\n\n').length, lessThanOrEqualTo(3));+ expect(+ snapshot.runes.length,+ lessThanOrEqualTo(SearchOutputPreview.shownCharacters + 1),+ );expect(snapshot, contains('木' * 96));expect(snapshot, isNot(contains('木' * 97)));expect(snapshot, contains('Recent result 😀'));@@ -42,43 +68,38 @@ void main() {},);- test(- 'preview is lazy and cached for the selection, with explicit refresh',- () {- final app = createApp();- addTearDown(app.dispose);- final output = terminal('a0', []);- output.terminal.write('Original context');- final pane = app.adoptSessionForTest(output);- final search = SwarmSearchController(app, []);- addTearDown(search.dispose);- search.setQuery('Agent 0');- expect(search.preview, isNull);- search.togglePreview();- final first = search.preview;- expect(first!.text, contains('Original context'));- output.terminal.write('\r\nNew output');- for (final query in ['Agent', 'Agent 0', 'Test host Agent 0']) {- search.setQuery(query);- expect(search.preview, same(first));- }- search.togglePreview();- expect(search.preview, isNull);- search.togglePreview();- expect(search.preview!.text, contains('New output'));- expect(pane.session, same(output));- search.setQuery('Agent 1');- expect(search.preview!.text, isEmpty);- expect(app.allPanes, [pane]);- search.setQuery('>');- expect(search.previewVisible, isFalse);- expect(search.preview, isNull);- },- );+ test('preview is always on and cached until selection changes', () {+ final app = createApp();+ addTearDown(app.dispose);+ final output = terminal('a0', []);+ output.terminal.write('Original context');+ final pane = app.adoptSessionForTest(output);+ final search = SwarmSearchController(app, []);+ addTearDown(search.dispose);+ search.setQuery('Agent 0');+ expect(search.previewVisible, isTrue);+ final first = search.preview;+ expect(first!.text, contains('Original context'));+ output.terminal.write('\r\nNew output');+ for (final query in ['Agent', 'Agent 0', 'Test host Agent 0']) {+ search.setQuery(query);+ expect(search.preview, same(first));+ }+ search.setQuery('Agent 1');+ search.setQuery('Agent 0');+ expect(search.preview!.text, contains('New output'));+ expect(pane.session, same(output));+ search.setQuery('Agent 1');+ expect(search.preview!.text, isEmpty);+ expect(app.allPanes, [pane]);+ search.setQuery('>');+ expect(search.previewVisible, isFalse);+ expect(search.preview, isNull);+ });for (final inline in [false, true]) {testWidgets(- 'optional preview keeps ${inline ? 'New swarm' : 'titlebar'} input and go-to action',+ 'always-on preview keeps ${inline ? 'New swarm' : 'floating Add'} input and add action',(tester) async {final app = createApp();app.machineStates['m']!.nodeOnline = true;@@ -86,7 +107,7 @@ void main() {final output = terminal('a0', frames);output.terminal.write('Checking the build\r\nOne useful clue\r\n');final original = app.adoptSessionForTest(output);- if (inline) app.newSwarm();+ app.newSwarm();final target = app.activeSwarm;await mount(tester, app);final input = find.byKey(@@ -95,7 +116,9 @@ void main() {),);if (!inline) {- await tester.tap(find.byKey(const ValueKey('swarm-search-button')));+ await tester.tap(+ find.byKey(const ValueKey('swarm-add-agent-button')),+ );await tester.pump();}await tester.tap(input);@@ -105,15 +128,11 @@ void main() {find.byKey(const ValueKey('swarm-search-preview')),findsOneWidget,);- await chord(tester, LogicalKeyboardKey.keyI);- await tester.pump();expect(- find.byKey(const ValueKey('swarm-search-preview')),+ find.byKey(const ValueKey('swarm-search-preview-toggle')),findsNothing,);final field = tester.widget<TextField>(input);- final controller = field.controller!;- final focus = field.focusNode!;await chord(tester, LogicalKeyboardKey.keyI);await tester.pump();expect(@@ -121,41 +140,10 @@ void main() {findsOneWidget,);expect(find.textContaining('One useful clue'), findsOneWidget);- expect(controller.text, 'Agent 0');- expect(focus.hasFocus, isTrue);+ expect(field.controller!.text, 'Agent 0');+ expect(field.focusNode!.hasFocus, isTrue);expect(app.activeSwarm, same(target));expect(frames, isEmpty);-- // Mouse toggling also keeps editing in the field that opened search.- await tester.tap(- find.byKey(const ValueKey('swarm-search-preview-toggle')),- );- await tester.pump();- expect(- find.byKey(const ValueKey('swarm-search-preview')),- findsNothing,- );- expect(focus.hasFocus, isTrue);- controller.value = const TextEditingValue(- text: 'Agent 0',- composing: TextRange(start: 0, end: 7),- );- await chord(tester, LogicalKeyboardKey.keyI);- await tester.pump();- expect(- find.byKey(const ValueKey('swarm-search-preview')),- findsNothing,- );- controller.value = const TextEditingValue(- text: 'Agent 0',- selection: TextSelection.collapsed(offset: 7),- );- await chord(tester, LogicalKeyboardKey.keyI);- await tester.pump();- expect(- find.byKey(const ValueKey('swarm-search-preview')),- findsOneWidget,- );await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();expect(app.focusedPaneId, original.id);diff --git a/desktop/test/swarm_search_test.dart b/desktop/test/swarm_search_test.dartindex 0df9dc287..6567b83f0 100644--- a/desktop/test/swarm_search_test.dart+++ b/desktop/test/swarm_search_test.dart@@ -12,7 +12,8 @@ import 'package:xterm/xterm.dart';import 'swarm_interactions_test.dart' show chord;import 'swarm_screen_test.dart' show mount, terminal;import 'swarm_state_test.dart' show createApp;-import 'swarm_switcher_test.dart' show jumpField;++final jumpField = find.byKey(const ValueKey('swarm-search-input'));void main() {testWidgets(@@ -266,7 +267,7 @@ void main() {},);- testWidgets('clicking a machine result directly opens all agents', (+ testWidgets('Add imports all agents from a machine into this swarm', (tester,) async {final app = createApp();@@ -274,7 +275,7 @@ void main() {.take(3).toList();await mount(tester, app);- await tester.tap(find.byKey(const ValueKey('swarm-search-button')));+ await tester.tap(find.byKey(const ValueKey('swarm-add-agent-button')));await tester.pump();await tester.enterText(jumpField, 'Test host');await tester.pump();@@ -289,71 +290,86 @@ void main() {app.dispose();});- testWidgets(- 'the secondary action adds a shared view here and the first key reaches it',- (tester) async {- final app = createApp();- app.machineStates['m']!.nodeOnline = true;- final firstInputs = <TerminalBinaryFrame>[];- final secondInputs = <TerminalBinaryFrame>[];- final firstSession = terminal('a0', firstInputs);- final shared = app.adoptSessionForTest(firstSession);- final original = app.activeSwarm;- app.newSwarm(name: 'Review');- app.adoptSessionForTest(terminal('a1', secondInputs));- final target = app.activeSwarm;- await mount(tester, app);- await chord(tester, LogicalKeyboardKey.keyP);- await tester.enterText(jumpField, 'Agent 0');- await tester.pump();- expect(find.text('Add to this swarm'), findsOneWidget);- await chord(tester, LogicalKeyboardKey.enter);- expect(find.byType(Dialog), findsNothing);- expect(app.activeSwarm, same(target));- expect(target.panes.last, same(shared));- expect(original.panes, [shared]);- final view = tester.widget<TerminalView>(- find.byWidgetPredicate(- (w) =>- w is TerminalView && identical(w.terminal, firstSession.terminal),- ),- );- expect(view.focusNode!.hasFocus, isTrue);- await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);- await tester.pump(const Duration(milliseconds: 10));- expect(firstInputs.single.bytes, [27, 91, 68]);- expect(secondInputs, isEmpty);- await tester.pumpWidget(const SizedBox());- app.dispose();- },- );+ testWidgets('Add keeps a shared view here and the first key reaches it', (+ tester,+ ) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final firstInputs = <TerminalBinaryFrame>[];+ final secondInputs = <TerminalBinaryFrame>[];+ final firstSession = terminal('a0', firstInputs);+ final shared = app.adoptSessionForTest(firstSession);+ final original = app.activeSwarm;+ app.newSwarm(name: 'Review');+ app.adoptSessionForTest(terminal('a1', secondInputs));+ final target = app.activeSwarm;+ await mount(tester, app);+ await tester.tap(find.byKey(const ValueKey('swarm-add-agent-button')));+ await tester.pump();+ await tester.enterText(jumpField, 'Agent 0');+ await tester.pump();+ expect(find.text('Add to this swarm'), findsOneWidget);+ await chord(tester, LogicalKeyboardKey.enter);+ expect(find.byType(Dialog), findsNothing);+ expect(app.activeSwarm, same(target));+ expect(target.panes.last, same(shared));+ expect(original.panes, [shared]);+ final view = tester.widget<TerminalView>(+ find.byWidgetPredicate(+ (w) =>+ w is TerminalView && identical(w.terminal, firstSession.terminal),+ ),+ );+ expect(view.focusNode!.hasFocus, isTrue);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);+ await tester.pump(const Duration(milliseconds: 10));+ expect(firstInputs.single.bytes, [27, 91, 68]);+ expect(secondInputs, isEmpty);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });- testWidgets(- 'Return does not open a result while the search has composing text',- (tester) async {- final app = createApp();- await mount(tester, app);- await chord(tester, LogicalKeyboardKey.keyP);- await tester.enterText(jumpField, 'Agent 0');- await tester.pump();- final controller = tester.widget<TextField>(jumpField).controller!;- controller.value = controller.value.copyWith(- composing: const TextRange(start: 0, end: 7),- );- await tester.sendKeyEvent(LogicalKeyboardKey.enter);- await tester.pump();- expect(- find.byKey(const ValueKey('swarm-search-results')),- findsOneWidget,- );- expect(find.byType(Dialog), findsNothing);- expect(app.panes, isEmpty);- controller.clearComposing();- await tester.sendKeyEvent(LogicalKeyboardKey.enter);- await tester.pump();- expect(app.panes.single.agentId, 'a0');- await tester.pumpWidget(const SizedBox());- app.dispose();- },- );+ for (final adding in [false, true]) {+ testWidgets(+ 'Return waits for composing text in ${adding ? 'Add' : 'Navigate'}',+ (tester) async {+ final app = createApp();+ app.adoptSessionForTest(terminal('a0', []));+ final original = app.activeSwarm;+ app.newSwarm();+ final target = app.activeSwarm;+ await mount(tester, app);+ if (adding) {+ await tester.tap(+ find.byKey(const ValueKey('swarm-add-agent-button')),+ );+ await tester.pump();+ } else {+ await chord(tester, LogicalKeyboardKey.keyP);+ }+ await tester.enterText(jumpField, 'Agent 0');+ await tester.pump();+ final controller = tester.widget<TextField>(jumpField).controller!;+ controller.value = controller.value.copyWith(+ composing: const TextRange(start: 0, end: 7),+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(+ find.byKey(const ValueKey('swarm-search-results')),+ findsOneWidget,+ );+ expect(find.byType(Dialog), findsNothing);+ expect(app.panes, isEmpty);+ controller.clearComposing();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(app.panes.single.agentId, 'a0');+ expect(app.activeSwarm, same(adding ? target : original));+ expect(original.panes, hasLength(1));+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );+ }}diff --git a/desktop/test/swarm_split_test.dart b/desktop/test/swarm_split_test.dartindex 78bc232d0..681c43a81 100644--- a/desktop/test/swarm_split_test.dart+++ b/desktop/test/swarm_split_test.dart@@ -225,6 +225,10 @@ void main() {await tester.pump();await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();+ expect(find.text('Split right'), findsOneWidget);+ expect(find.byType(AlertDialog), findsNothing);+ await tester.tap(find.byKey(const ValueKey('swarm-search-new-agent')));+ await tester.pump();expect(find.text('New agent to the right'), findsOneWidget);expect(find.text('/work/checkout'), findsOneWidget);expect(app.panes, [pane]);diff --git a/desktop/test/swarm_switcher_test.dart b/desktop/test/swarm_switcher_test.dartindex 7b4b745c8..6daa3f100 100644--- a/desktop/test/swarm_switcher_test.dart+++ b/desktop/test/swarm_switcher_test.dart@@ -16,7 +16,7 @@ Finder get jumpField => find.byWidgetPredicate((w) =>w is TextField &&w.key == const ValueKey('swarm-search-input') &&- w.decoration?.hintText == 'Search agents, swarms, machines, projects…',+ w.decoration?.hintText == 'Find an agent or swarm…',);Finder get selectedRow =>find.byWidgetPredicate((w) => w is ListTile && w.selected);@@ -132,7 +132,7 @@ void main() {});testWidgets(- 'search opens in one frame, owns typing, cancels, and replaces the separate Add picker',+ 'navigation opens in one frame, owns typing, cancels, and stays distinct from Add',(tester) async {final app = createApp();app.adoptSessionForTest(terminal('a0', []));@@ -149,10 +149,10 @@ void main() {expect(field.focusNode!.hasFocus, isTrue);final controller = field.controller;final results = tester.getRect(- find.byKey(const ValueKey('swarm-search-result-list')),+ find.byKey(const ValueKey('swarm-navigation-locations')),);final bar = tester.getRect(input);- expect(results.top, inInclusiveRange(bar.bottom, bar.bottom + 12));+ expect(results.top, inInclusiveRange(bar.bottom, bar.bottom + 30));final picker = tester.getRect(find.byKey(const ValueKey('swarm-search-results')),);@@ -241,9 +241,13 @@ void main() {'keyboard selection scrolls, survives discovery, and explicitly opens a view',(tester) async {final app = createApp();- app.adoptSessionForTest(terminal('a0', []));+ for (var i = 0; i < 18; i++) {+ app.adoptSessionForTest(terminal('a$i', []));+ }await mount(tester, app);await chord(tester, LogicalKeyboardKey.keyP);+ await tester.enterText(jumpField, 'Agent');+ await tester.pump();for (var i = 0; i < 12; i++) {await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);await tester.pump();@@ -273,15 +277,12 @@ void main() {await tester.pump();await tester.pump();expect(tester.widget<ListTile>(selectedRow).key, ValueKey(selectedId));- expect(find.text('Go to agent'), findsOneWidget);+ expect(find.text('Go to'), findsOneWidget);await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();- expect(app.panes, hasLength(2));+ expect(app.panes, hasLength(18));expect(- agentDestinationId(- app.focusedPane!.machineId,- app.focusedPane!.agentId!,- ),+ agentLocationId(app.activeSwarmId, app.focusedPane!.id),selectedId,);await tester.pumpWidget(const SizedBox());diff --git a/desktop/tool/keymap_native_checks.swift b/desktop/tool/keymap_native_checks.swiftindex befbcc2a9..d00434ebc 100644--- a/desktop/tool/keymap_native_checks.swift+++ b/desktop/tool/keymap_native_checks.swift@@ -37,8 +37,8 @@ try checkKeymap(changed.match([stroke("down")], context: "picker").binding == ni"Picker unbinding removes the original arrow action")try checkKeymap(changed.match([stroke("ctrl+j")], context: "picker").binding?.command == "picker.previous","Picker remapping wins")-try checkKeymap(defaults.match([stroke("cmd+i")], context: "picker").binding?.command == "picker.preview",- "The shipped optional-preview shortcut joins the catalog")+try checkKeymap(defaults.match([stroke("cmd+i")], context: "picker").binding == nil,+ "Always-on preview does not consume a hide-preview shortcut")let dispatcher = HarnessNativeKeyDispatch(changed)let field = NSObject(), otherField = NSObject()diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex 73a533615..cc8e4c442 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -40,7 +40,7 @@ private extension SwarmTabStrip {try checkTitlebar(palette == expected && searchButton.contentTintColor == expected.accent && notificationButton.contentTintColor == expected.accent &&newButton.contentTintColor == expected.accent,"Initial search and new-swarm colors use the saved palette")- try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled && !newAgentButton.isEnabled && !searchButton.isEnabled && !notificationButton.isEnabled,+ try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled && !searchButton.isEnabled && !notificationButton.isEnabled,"Initial palette setup does not create or enable workspace controls")}@@ -125,14 +125,12 @@ private extension SwarmTabStrip {try checkTitlebar(newButton.isEnabled, "New tab returns below capacity")try checkTitlebar(searchButton.toolTip?.contains("⌘P") == true, "Search advertises its keyboard shortcut")try checkTitlebar(newButton.frame.maxX + 12 <= searchButton.frame.minX, "New swarm leaves space before the search icon")- try checkTitlebar(searchButton.frame.maxX < newAgentButton.frame.minX && newAgentButton.frame.maxX < notificationButton.frame.minX, "Search, new agent and bell have separate targets in order")- try checkTitlebar(newAgentButton.title.isEmpty && newAgentButton.accessibilityLabel() == "New agent", "New agent uses an icon with an accessible label")+ try checkTitlebar(searchButton.frame.maxX < notificationButton.frame.minX, "Search and bell have separate targets in order")try checkTitlebar(!subviews.contains(where: { $0 is NSTextField }), "The titlebar has no competing text editor")events.removeAll()searchButton.performClick(nil)- newAgentButton.performClick(nil)notificationButton.performClick(nil)- try checkTitlebar(events == ["jump", "newAgent", "notifications"], "Each toolbar icon opens its shared Flutter surface once")+ try checkTitlebar(events == ["jump", "notifications"], "Each toolbar icon opens its shared Flutter surface once")try checkTitlebar(notificationButton.hasAttention, "The bell represents pending agent attention")let oldButton = searchButtonvar themedState = state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0")@@ -150,10 +148,9 @@ private extension SwarmTabStrip {events.removeAll()update(state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0", enabled: false))try original.checkEnabled(false)- try checkTitlebar(!newButton.isEnabled && !newAgentButton.isEnabled && !searchButton.isEnabled && !notificationButton.isEnabled, "Titlebar actions disable with a modal")+ try checkTitlebar(!newButton.isEnabled && !searchButton.isEnabled && !notificationButton.isEnabled, "Titlebar actions disable with a modal")original.clickBothActions()newButton.performClick(nil)- newAgentButton.performClick(nil)searchButton.performClick(nil)notificationButton.performClick(nil)try checkTitlebar(events.isEmpty, "Disabled controls emit no actions")@@ -222,7 +219,7 @@ private extension SwarmTabStrip {messenger.finishNextReply()try checkTitlebar(window.firstResponder === window.contentViewController,"The latest acknowledged tab action restores content focus")- for (button, method) in [(newAgentButton, "newAgent"), (notificationButton, "notifications")] {+ for (button, method) in [(notificationButton, "notifications")] {window.makeFirstResponder(button)let before = messenger.calls.countbutton.performClick(nil)@@ -232,7 +229,7 @@ private extension SwarmTabStrip {"The toolbar waits for Flutter's destination focus tree")messenger.finishNextReply()try checkTitlebar(window.firstResponder === window.contentViewController,- "New-agent and notification controls return keyboard ownership to Flutter")+ "Notification control returns keyboard ownership to Flutter")}messenger.holdReplies = false}@@ -391,7 +388,8 @@ private extension SwarmTitlebar {"The menu yields the remapped search shortcut to Flutter")try checkTitlebar(!main.performKeyEquivalent(with: open), "Menu equivalents defer before input dispatch")setKeymap(defaults)- try checkTitlebar(strip.searchButton.toolTip == "Search (⌘P)", "Reload refreshes the search button hint")+ try checkTitlebar(strip.searchButton.toolTip == "Navigate (⌘P)", "Reload refreshes the navigation button hint")+ try checkTitlebar(strip.searchButton.accessibilityLabel() == "Navigate", "The compass announces global navigation")try checkTitlebar(main.defersToInput(event("p", 35, .command)), "Command-P reaches the shared Flutter picker")try checkTitlebar(main.defersToInput(event("p", 35, [.command, .shift])), "Command-Shift-P reaches command search")flutterKeyContext = "picker"@@ -445,7 +443,7 @@ private extension SwarmTitlebar {try strip.checkStartupPalette(startupPalette)try checkTitlebar(window.firstResponder === window.contentViewController,"Adding toolbar buttons does not take initial keyboard focus from the workspace")- try checkTitlebar(main.items.map(\.title) == ["Harness", "Swarm", "Agent", "Edit", "View", "History", "Models", "Window", "Help"], "Swarm and Agent replace File without duplicate menus")+ try checkTitlebar(main.items.map(\.title) == ["Harness", "Swarm", "Agent", "Models", "History", "Edit", "View", "Window", "Help"], "Swarm and Agent replace File without duplicate menus")let settings = appItem.submenu!.items[0]try checkTitlebar(settings.title == "Settings…" && settings.representedObject as? String == "settings", "Settings stays in the application menu")let swarm = main.item(withTitle: "Swarm")!.submenu!diff --git a/docs/harness-v2-handoff.md b/docs/harness-v2-handoff.mdindex 44516c1c7..e07f1ac45 100644--- a/docs/harness-v2-handoff.md+++ b/docs/harness-v2-handoff.md@@ -3,8 +3,8 @@Updated September 13, 2026. **Read this first when resuming on another computer.**This is the current product contract and next-work order. It supersedes conflictinghistorical checkpoints in [the progress log](harness-v2-progress.md). The user-requested this checkpoint so another agent/session can take over; the overall-goal is still active and unfinished.+requested a portable checkpoint, then asked this session to resume building;+the overall goal is still active and unfinished.## Goal@@ -33,10 +33,13 @@ Research must lead to justified improvements, not feature accumulation.qualification remains incomplete.- Previous UI checkpoint: `ac443eb`, following `2e8d69d` (search/menu controls),`4154cf6` (Harness branding/account labels), and `06ba77c` (agent creation).-- New code checkpoint: **`26a372e`**, terminal viewport preservation and naming+- Previous code checkpoint: **`26a372e`**, terminal viewport preservation and namingan empty default swarm after its first agent.-- The following handoff commit saves this document, pending UI drafts, native- benchmark tooling, and the existing collaboration design notes.+- `744c1fe` saved the portable handoff, pending UI drafts, native benchmark+ tooling, and collaboration design notes.+- The current continuation implements distinct Navigate/Add experiences,+ consistent empty-swarm starters, command-mode focus preservation, and the+ navigation catalog performance improvement described below.- The user explicitly authorized pushing everything to this public repositoryon `app-v2`; do not ask again for routine checkpoint pushes there.- After the PR is merged, delete its branch, update `main`, and create a fresh@@ -46,7 +49,8 @@ Start with a clean checkout of the remote branch and inspect its latest commit.On an existing checkout, preserve local work before updating; use a fast-forwardpull, not a reset. The prior computer's `/private/tmp` files, installed apps,saved account state, and localhost prototype server will not transfer with Git.-All essential pending source drafts are now in [the handoff archive](handoff/app-v2-2026-09-13/README.md).+The [handoff archive](handoff/app-v2-2026-09-13/README.md) preserves older drafts;+the picker patch is now superseded by production source. Do not reapply it.## Core product rules@@ -74,7 +78,7 @@ All essential pending source drafts are now in [the handoff archive](handoff/app## Latest approved design: two different experiences-This is the next implementation priority. The user explicitly rejected using+This design is now implemented in source. The user explicitly rejected usingone global picker with only different labels/icons for navigation versus adding.Share data/search utilities where useful, but build **distinct UI and interactionflows** for these two jobs.@@ -91,11 +95,11 @@ flows** for these two jobs.### Navigate- Put a navigation icon at the top right, alongside the notification bell.- Remove the separate top-right New agent +. A compass is a reasonable visual- candidate, but the exact glyph has not yet been implemented or reviewed.+ Remove the separate top-right New agent +. The implemented glyph is a compass,+ with a Navigate tooltip and accessibility label.- Make the surface visibly about **places to go**, distinct from Add agent's- existing-agent search and creation surface. A swarm-oriented hierarchy/list- is an implementation candidate, not a separately approved mockup.+ existing-agent search and creation surface. The implemented compact directory+ groups exact agent locations under their swarm names; it has no output preview.- **If one matching agent appears in three swarms, show all three swarmdestinations and let the user choose.** Do not silently choose its latestswarm or hide the alternatives by deduplicating only on agent identity.@@ -103,10 +107,12 @@ flows** for these two jobs.selecting a swarm goes to that swarm. Navigation does not mutate membership.- Cmd-P remains the navigation shortcut. Cmd-Shift-P remains command mode.Native menu, tooltip, help, custom bindings, and actual dispatch must agree.-- The presentation for agents with no open swarm, closed swarm destinations,- and no matching agent still needs design. Resolve it deliberately: a clear- transition to Add/Create is possible, but do not turn a navigation result- into an unexpected membership change or silently create a duplicate runtime.+- Agents with no open swarm belong to Add. Navigate's explicit “Add an agent…”+ action opens that separate surface while preserving the query. Closed work+ remains in History. A missing/stale navigation location never redirects to+ another swarm or changes membership.+- Entering/leaving `>` command mode keeps the same text editor mounted, so the+ immediately following select-all/delete or typing event keeps its focus.### Add agent@@ -142,7 +148,7 @@ flows** for these two jobs.word “Account”; do not mix email and ID presentation.- Native menu order requested: **Harness · Swarm · Agent · Models · History ·Edit · View · Window · Help**. Keep standard supporting menus for native- editing/window/help behavior. The reorder is only in the saved picker draft.+ editing/window/help behavior. The reorder is implemented and checked in AppKit.- New agent has one-click Codex / Claude Code / Cursor choices plus More forthe full list, remembered choice, neat Advanced options, and a separateGitHub clone flow alongside choosing a local working folder.@@ -153,7 +159,7 @@ flows** for these two jobs.menu with split right/down. Verify their actual geometry and discoverability,not just that callbacks exist.-## Current implementation versus saved drafts+## Current implementation and remaining work**Implemented on the branch:** swarm/session retention, native tabs, layouts,closed-work History, palettes, editable centered search and command mode,@@ -163,17 +169,35 @@ precedence, and independent machine loading while account metadata loads.See [the progress log](harness-v2-progress.md) for individual checkpoints and[the developer-tool audit](harness-v2-developer-tools-research.md) for research.-**Important discrepancies still in the running/source UI:** the last built-toolbar has Search + New agent + Notifications; global and inline pickers-still share the old navigation behavior; previews remain optional/raw; Split-opens creation directly. Do not describe the new two-experience design as shipped.--**Saved, not applied to production source:** [picker and onboarding drafts](handoff/app-v2-2026-09-13/README.md).-They contain reusable work for the floating +, add/split routing, preview cleanup,-darker veils, menu order, keyboard routing, and first-use welcome. The picker draft-predates the user's final requirement for completely different Navigate/Add UIs;-adapt selected parts rather than blindly applying and shipping it. Both patches-touch SwarmScreen and must be reconciled. The onboarding draft is unverified.+**Latest source changes:** Navigate is a separate compact directory with exact+swarm/agent destinations. The floating bottom-right +, New swarm search, and+both split actions share Add results, an always-on preview, and a New agent+action. Typed matches already in the target swarm say “In this swarm” and cannot+be added twice. Group additions skip existing members. Split requests preserve+the neighbor/direction and refuse stale layouts. Previews join wrapped prose,+remove terminal rules/recap headers, and show a bounded excerpt in a reading card.+The shared modal veil is darker and the eye toggle is removed. Old custom+bindings for that retired toggle no longer invalidate the rest of the keymap.++**Empty-swarm consistency:** existing-agent suggestions now depend on discovered+inventory, not a first-workspace-only gate. Every empty tab, including one made+after closing a swarm, says “Add an existing agent” and adds to that tab. The+broader first-use education and setup simplification remain unfinished; do not+claim a verified onboarding conversion/time improvement.++**Archived drafts:** the picker draft is superseded by these changes. The+onboarding draft remains unapplied and unverified. Inspect and adapt useful+parts; do not apply it blindly over the new picker/welcome paths.++**Latest verification:** 1,256 desktop tests passed with one existing skip;+analyzer reports zero errors/warnings and 12 existing vendored infos. Native+checks passed 51 keymap decoder and 344 AppKit assertions, including hidden+window layout. Synthetic captures with real fonts were reviewed at 1280×800+and 880×560; they are not a real native-session visual or latency measurement.+Navigate/Add timings and their exact scope are in+[the performance record](harness-v2-performance.md). The new navigation catalog+build measured 0.194 ms median / 0.264 ms p95 for 50 locations across 12 swarms.+Logs: `/private/tmp/harness-two-pickers-{full-tests-final,analyze-clean,native}.log`.**Also saved:** [native benchmark tooling](../desktop/tool/native_benchmark/README.md)and [shared-swarm collaboration research](harness-collaboration-design.md), which@@ -184,7 +208,7 @@ script assumes the old `Harness V2` product name, its process check uses thatname, and its native initial-responder logic is the older version. Preserve itsisolation/focus guards. The performance notes explain the failed calibration.-## Latest terminal fix and verification+## Previous terminal fix and verificationThe user reported opening a project swarm with five terminals showing oldercontent instead of the latest output. Ordinary fresh/delayed five-pane fixtures@@ -204,7 +228,7 @@ The same checkpoint saves the existing first-agent naming change: an emptydefault “New swarm” adopts its first agent's name; custom names and other tabsare preserved. Tests cover subsequent additions and close/reopen behavior.-Final checks on the committed code:+Historical checks for that terminal checkpoint:- **1,244 desktop tests passed, one existing skip**, including the new four-caseterminal regression file and the two swarm naming tests.@@ -219,35 +243,28 @@ Final checks on the committed code:51 keymap decoder + 343 AppKit checks before it was parked. Those resultsapply to the old draft only. Its final visual treatment still needs review.-The workspace Release preview predates `26a372e`. It was last built through the-search/toolbar checkpoint. **This handoff does not rebuild or restart the user's-apps.** Tests are not proof of native visual/input latency. Prior native+The last verified workspace Release preview predates the terminal and current+Navigate/Add changes; a new release build and normal relaunch are the immediate+next step. Tests are not proof of native visual/input latency. Prior nativecomputer-use inspection failed at pipe startup; calibration failed with an-inactive/non-key benchmark window. Continue on the new computer when that-capability is actually available, not by looping the same failed attempt.+inactive/non-key benchmark window. Retry calibration only when new evidence+establishes that its isolated window can become active/key.## Plan for the next session-1. **Read this document and inspect the current source.** Confirm branch/PR state,- toolchain, and local app identity. Inspect archived drafts before editing.-2. **Implement the two approved experiences.** First define an exact navigation- destination `(swarm, agent/pane)` and location results for multi-swarm agents.- Build the distinct Navigate surface and shared Add interface. Reuse selected- draft pieces for FAB/split wiring, always-on preview, and backdrop treatment.- Complete native and Flutter entry points together so no route retains the- old confusing behavior. Keep command mode and customized keys working.-3. **Validate the full interaction matrix below**, capture actual/synthetic- visuals with real fonts, and clearly label which was verified. Commit/push- the coherent result and update this handoff/progress record.-4. **Improve genuine first use.** Start with no account/runtime/agents/projects+1. **Confirm the latest source/build checkpoint.** Build a release from the+ tested source and normally relaunch only the exact workspace preview. Review+ Navigate, Add, command mode, and the fresh terminal position in the native app+ when computer-use access works. Preserve real running agents and input.+2. **Improve genuine first use.** Start with no account/runtime/agents/projectsknowledge. Make “choose a working folder → choose an agent → start” clear;use this computer by default, reveal machine/link/project concepts whenneeded, and offer existing work prominently when discovered. Adapt the savedonboarding draft to the new Add experience. Preserve choices on failure.-5. **Recheck fresh terminal positioning and real workflows** on disposable+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.-6. **Measure native responsiveness** under representative retained/output load,+4. **Measure native responsiveness** under representative retained/output load,then close remaining visual/platform/release qualification gaps. Maintainthe draft PR and keep its description honest about what's still unverified.@@ -315,7 +332,7 @@ capability is actually available, not by looping the same failed attempt.| --- | --- || Workspace orchestration, picker routes, split/new-agent context | `desktop/lib/screens/swarm_screen.dart` || Search data, actions, destinations | `desktop/lib/state/swarm_search.dart`, `swarm_navigation.dart`, `swarm_catalog.dart` |-| Existing picker and welcome UI | `desktop/lib/widgets/swarm_switcher.dart`, `swarm_inline_search.dart`, `swarm_search_input.dart`, `swarm_welcome.dart` |+| Distinct Navigate and shared Add/welcome UI | `desktop/lib/widgets/swarm_navigator.dart`, `swarm_switcher.dart`, `swarm_inline_search.dart`, `swarm_search_input.dart`, `swarm_welcome.dart` || Preview extraction | `desktop/lib/terminal/search_output_preview.dart` || Native tabs, toolbar, menus | `desktop/macos/Runner/SwarmTitlebar.swift` || Key ownership and customization | `desktop/lib/shortcuts/`, `desktop/tool/check_keymap_native.sh` |diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.mdindex 277af45f2..e9d0e131e 100644--- a/docs/harness-v2-performance.md+++ b/docs/harness-v2-performance.md@@ -10,6 +10,57 @@ flutter test --no-pub --reporter expanded test/benchmarks/swarm_benchmark.dartIt prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in `_test.dart`, so ordinary correctness runs do not include timing measurements.+## Distinct Navigate and Add agent continuation++Navigate now indexes only existing swarm locations. The initial implementation+built Add's full discovered-agent/project catalog first, even when only a few+locations were open. It now indexes agent identities once and formats just the+open locations. Add filtering also checks membership without allocating a new+set for every candidate on every query. Both catalogs reuse unchanged snapshots;+terminal output does not rebuild or rerank their results. Previews read a bounded+excerpt only when the selected identity changes.++The updated explicit benchmark exercises the actual two controllers. Add has+2,000 discovered agents on eight machines, 50 projects and 2,059 entries.+Navigate has the same discovery inventory, with 50 agent locations across 12+swarms (62 entries), including one agent in three swarms. Each CPU distribution+has 20 warmups and 100 samples. Runs were sequential without overlapping other+checks, on the same shared workstation in the headless debug runner.++| Operation | Initial median / p95 | Final median / p95 |+| --- | ---: | ---: |+| Build navigation location catalog | 4.095 / 4.833 ms | 0.194 / 0.264 ms |+| Open/dispose navigation controller | 4.108 / 4.667 ms | 0.192 / 0.224 ms |+| Navigate query `agent 0 machine 0` | 0.021 / 0.029 ms | 0.021 / 0.024 ms |+| Add query `agent` | 1.206 / 1.312 ms | 1.025 / 1.083 ms |+| Add query `agent 12 machine 3` | 0.992 / 1.141 ms | 0.782 / 0.877 ms |+| Add fuzzy query `agn12` | 0.927 / 1.043 ms | 0.718 / 0.813 ms |+| Add query `project 12 main` | 1.321 / 1.464 ms | 1.096 / 1.200 ms |++Navigation catalog construction fell about 95% in this fixture. The unchanged+catalog check measured 0.006 ms for Navigate and 0.002 ms for Add (median and+p95). Add's final full catalog construction was 3.057 / 3.438 ms and its+controller open/dispose cycle 4.336 / 4.694 ms. Host load and JIT also affect these+observations; they do not establish a fixed saving on every machine.++The full benchmark before the final catalog-only optimization also measured:++| Terminal workload | Median | p95 |+| --- | ---: | ---: |+| Decode and parse a 16 KiB ASCII frame | 0.555 ms | 0.776 ms |+| Decode and parse a 16 KiB Unicode frame | 0.346 ms | 0.421 ms |+| Tab switch and pump: 4 swarms / 16 terminals | 16.445 ms | 24.666 ms |+| Tab switch and pump: 12 swarms / 48 terminals | 13.066 ms | 15.784 ms |+| Pane focus and pump: 16 terminals | 6.861 ms | 9.278 ms |+| Pane focus and pump: 48 terminals | 7.090 ms | 8.850 ms |++Five benchmark cases passed, followed by the final catalog case. The widget+workloads retain 1,000 scrollback lines per terminal in a 1280×800 fixture, with+60 measured samples. These are CPU/frame-pump costs, not native input handling,+physical keypress-to-display or remote round-trip latency. The calibration gap+below remains open. Logs: `/private/tmp/harness-two-pickers-benchmark.log` and+`/private/tmp/harness-two-pickers-benchmark-final.log`.+## Concurrent machine discovery (2026-09-13)Agent inventory and terminal capability requests now start together after the machine handshake. The small capability request is sent first because the CLI dispatches frames through a per-client FIFO; it can answer that request before assembling project metadata for the agent list. The list becomes visible as soon as it arrives. Existing panes attach only when both inventory and protocol information are available, without changing focus or membership.diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdindex 38a87c584..e45e2e876 100644--- a/docs/harness-v2-progress.md+++ b/docs/harness-v2-progress.md@@ -1,10 +1,19 @@# Harness App V2 — development handoff-Updated 2026-09-13 for transfer to another computer/session. This is a working preview, not a release.+Updated 2026-09-13 after resuming the Navigate/Add implementation. This is a working preview, not a release.**Resume with [Harness v2: goal, plan, and continuation handoff](harness-v2-handoff.md).** It records the latest approved design, acceptance criteria, next-work order, and portable drafts. The checkpoints below are historical; the current handoff supersedes their conflicting toolbar, picker, preview, menu, and onboarding directions.-## Cross-computer checkpoint+## Navigate and Add agent continuation++- Implemented distinct UIs: a compact compass/Navigate directory lists every existing swarm location for a matching agent; New swarm, bottom-right floating +, and both splits share Add results with an always-on preview and New agent action. Navigate does not mutate membership. Add reuses the session and preserves source swarms, avoids duplicates, and keeps the chosen split position.+- Every empty swarm now offers the same existing-agent suggestions, including after closing earlier swarms. Removed the first-use-only gate and “Go to an agent” heading. Broader onboarding simplification remains next work.+- Cleaner bounded previews join wrapped prose, remove separator/recap decorations, and use a reading card. Removed the eye toggle, darkened shared modal veils, removed the top-right New agent +, and reordered native menus. Cmd-N and customized picker keys retain their behavior; entering/leaving command mode keeps the editor mounted to avoid losing the very next key.+- Native checks: 51 keyboard decoder + 344 AppKit assertions. Desktop: **1,256 passed, one existing skip**; analyzer: zero errors/warnings, 12 existing vendored infos. Synthetic real-font renders reviewed at 1280×800 and 880×560. Logs: `/private/tmp/harness-two-pickers-{full-tests-final,analyze-clean,native,visual-final}.log`.+- Avoided building unused agent/project metadata for Navigate and allocating membership sets for every Add candidate. Navigation catalog setup measured 4.095 → 0.194 ms median for 50 agent locations across 12 swarms. Add's 2,000-agent query measured 1.025 ms median / 1.083 ms p95. See [performance measurements and limits](harness-v2-performance.md); these are headless CPU observations, not native keypress-to-screen latency.+- The archived picker draft is superseded; do not reapply it. Its onboarding companion remains unapplied. Next: build/reopen the tested release preview, improve genuine first use, and qualify native responsiveness plus local/remote reconnect workflows. Draft PR #31 remains draft.++## Cross-computer checkpoint (historical)- Saved `26a372e`: preserve captured terminal rows until the remote resized keyframe, avoiding deletion of the latest output when a tall TUI enters a smaller pane. Fresh five-pane and delayed-snapshot regressions reach the bottom; revisited scrolled views retain their place. The user's exact live screenshot still needs rechecking.- Also committed the existing first-agent naming work: default empty New swarms adopt the first agent's name, preserving custom names and close/reopen behavior.