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
Add Models menu, recover closed agents, and speed up search
dee2a05803da95b
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 6719dc380..1c9b9bceb 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -14,11 +14,13 @@ import '../shared/theme/app_theme.dart' as grid;import '../shortcuts/app_shortcuts.dart';import '../state/app_state.dart';import '../terminal/terminal_viewport.dart';+import '../usage/models_menu_controller.dart';import '../state/swarm_catalog.dart';import '../state/swarm_attention.dart';import '../state/swarm_navigation.dart';import '../state/swarm_search.dart';import '../widgets/layout_palette.dart';+import '../widgets/engine_identity.dart';import '../widgets/link_machine_screen.dart';import '../widgets/new_agent_dialog.dart';import '../widgets/pane_grid.dart';@@ -37,10 +39,12 @@ class SwarmScreen extends StatefulWidget {required this.notifier,this.nativeTabs,this.projectStore,+ this.modelsMenu,});final AppNotifier notifier;final bool? nativeTabs;final SwarmProjectStore? projectStore;+ final ModelsMenuController? modelsMenu;@overrideState<SwarmScreen> createState() => _SwarmScreenState();}@@ -69,6 +73,8 @@ class _SwarmScreenState extends State<SwarmScreen> {bool _routeIsCurrent = true;String? _linkDialogMachineId;String? _nativeState;+ ModelsMenuController? _modelsMenu;+ String? _modelsState;AppNotifier get app => widget.notifier;@override@@ -83,9 +89,14 @@ class _SwarmScreenState extends State<SwarmScreen> {unawaited(_projects.load());_spokenTasks = app.spokenTasks.listen(_openSpokenTask);if (_native) {+ _modelsMenu =+ widget.modelsMenu ??+ ModelsMenuController(remote: app.readRemoteUsage);+ _modelsMenu!.addListener(_syncModels);_channel.setMethodCallHandler(_onNative);app.addListener(_syncNative);_syncNative();+ _syncModels();}}@@ -115,6 +126,11 @@ class _SwarmScreenState extends State<SwarmScreen> {_shellFocus.dispose();unawaited(_spokenTasks?.cancel());if (_native) {+ _modelsMenu?.removeListener(_syncModels);+ if (widget.modelsMenu == null) _modelsMenu?.dispose();+ unawaited(+ _channel.invokeMethod<void>('modelsState', {'subscriptions': []}),+ );app.removeListener(_syncNative);_channel.setMethodCallHandler(null);unawaited(@@ -160,18 +176,21 @@ class _SwarmScreenState extends State<SwarmScreen> {final payload = {'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,'activeId': app.activeSwarmId,- 'canReopen': app.canReopenClosedSwarm,+ 'canReopen': app.canReopenLastClosed,'canFind': _canFindTerminal,'canClosePane': app.focusedPane != null,'canGoBack': _navigation.canGoBack(app),'canGoForward': _navigation.canGoForward(app),'closedHistory': [- for (final entry in closedSwarmDestinations(app))+ for (final entry in closedWorkDestinations(app)){'id': entry.id,'title': entry.title,'detail': entry.detail,- 'swarm': true,+ 'swarm': entry.isSwarm,+ 'engine': entry.engine,+ 'iconAsset': engineIdentity(entry.engine).asset,+ 'canReopen': app.canReopenClosed(entry.id),},],'attention': _attention,@@ -184,6 +203,8 @@ class _SwarmScreenState extends State<SwarmScreen> {: '${entry.title} — ${app.stateOf(entry.machineId!)?.machine.displayName ?? entry.machineId}','detail': entry.detail,'swarm': entry.isSwarm,+ 'engine': entry.engine,+ 'iconAsset': engineIdentity(entry.engine).asset,'current': entry.current,},],@@ -208,6 +229,14 @@ class _SwarmScreenState extends State<SwarmScreen> {unawaited(_channel.invokeMethod<void>('update', payload));}+ void _syncModels() {+ final payload = {'subscriptions': _modelsMenu?.rows ?? []};+ final encoded = jsonEncode(payload);+ if (encoded == _modelsState) return;+ _modelsState = encoded;+ unawaited(_channel.invokeMethod<void>('modelsState', payload));+ }+Future<void> _onNative(MethodCall call) async {if (!mounted ||_dialogOpen ||@@ -216,6 +245,10 @@ class _SwarmScreenState extends State<SwarmScreen> {return;}final args = call.arguments is Map ? call.arguments as Map : const {};+ if (call.method == 'modelsOpened') {+ await _modelsMenu?.refresh();+ return;+ }if (call.method == 'searchBegin') {_openSearch();_updateSearchGeometry(args);@@ -262,9 +295,9 @@ class _SwarmScreenState extends State<SwarmScreen> {case 'new':app.newSwarm();case 'reopen':- app.reopenClosedSwarm();+ app.reopenClosed();case 'reopenHistory':- if (args['id'] is String) app.reopenClosedSwarm(historyId: args['id']);+ if (args['id'] is String) app.reopenClosed(historyId: args['id']);case 'historyBack':_stepHistory(-1);case 'historyForward':@@ -750,7 +783,7 @@ class _SwarmScreenState extends State<SwarmScreen> {...buildShortcutBindings(handlers: {ShortcutAction.newSwarm: app.newSwarm,- ShortcutAction.reopenClosedSwarm: app.reopenClosedSwarm,+ ShortcutAction.reopenClosedSwarm: app.reopenClosed,ShortcutAction.closeSwarm: () =>app.closeSwarm(app.activeSwarmId),ShortcutAction.renameSwarm: () => _rename(app.activeSwarmId),diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dartindex a9c42668c..86c6ed509 100644--- a/desktop/lib/shortcuts/app_shortcuts.dart+++ b/desktop/lib/shortcuts/app_shortcuts.dart@@ -495,7 +495,7 @@ const kSwarmShortcuts = [meta: true,shift: true,),- label: 'Reopen closed swarm',+ label: 'Reopen last closed agent or swarm',group: ShortcutGroup.navigate,),AppShortcut(diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex 660317e8c..381c6e820 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -58,7 +58,7 @@ final harnessCommands = <HarnessCommand>[),const HarnessCommand('swarm.reopen',- 'Reopen closed swarm',+ 'Reopen last closed agent or swarm',ShortcutGroup.navigate,keys: ['cmd+shift+t'],action: ShortcutAction.reopenClosedSwarm,diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 91170c2c3..50738deb5 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -350,12 +350,42 @@ class AppNotifier extends ChangeNotifier {int _nextSwarmId = 2;static const maxSwarms = 24;static const maxClosedSwarms = 24;- final List<ClosedSwarm> _closedSwarms = [];- int _nextClosedSwarmId = 1;+ final List<ClosedWork> _closedHistory = [];+ int _nextClosedHistoryId = 1;+ List<ClosedWork> get closedHistory =>+ List.unmodifiable(_closedHistory.reversed);List<ClosedSwarm> get closedSwarms =>- List.unmodifiable(_closedSwarms.reversed);+ List.unmodifiable(_closedHistory.reversed.whereType<ClosedSwarm>());bool get canReopenClosedSwarm =>- _closedSwarms.isNotEmpty && swarms.length < maxSwarms;+ _closedHistory.any((entry) => entry is ClosedSwarm) &&+ swarms.length < maxSwarms;+ bool get canReopenLastClosed =>+ _closedHistory.isNotEmpty &&+ canReopenClosed(_closedHistory.last.historyId);++ bool canReopenClosed(String historyId) {+ if (_disposed) return false;+ final entry = _closedHistory+ .where((entry) => entry.historyId == historyId)+ .firstOrNull;+ if (entry is ClosedSwarm) return swarms.length < maxSwarms;+ if (entry is! ClosedAgent) return false;+ final target = swarms.where((s) => s.id == entry.swarmId).firstOrNull;+ return target == null+ ? swarms.length < maxSwarms+ : target.panes.length < maxPanes ||+ target.panes.any(+ (p) =>+ p.machineId == entry.machineId &&+ p.agentId == entry.agentId,+ );+ }++ void _rememberClosed(ClosedWork entry) {+ _closedHistory.add(entry);+ if (_closedHistory.length > maxClosedSwarms) _closedHistory.removeAt(0);+ }+Swarm get activeSwarm => swarms.firstWhere((s) => s.id == _activeSwarmId,orElse: () => swarms.first,@@ -472,15 +502,14 @@ class AppNotifier extends ChangeNotifier {replacement = Swarm(id: 'swarm-${_nextSwarmId++}');swarms.add(replacement);}- _closedSwarms.add(+ _rememberClosed(ClosedSwarm(removed,- historyId: 'closed-${_nextClosedSwarmId++}',+ historyId: 'closed-${_nextClosedHistoryId++}',index: index,replacement: replacement,),);- if (_closedSwarms.length > maxClosedSwarms) _closedSwarms.removeAt(0);if (_activeSwarmId == id) {_activeSwarmId = swarms[index.clamp(0, swarms.length - 1)].id;}@@ -498,11 +527,13 @@ class AppNotifier extends ChangeNotifier {void reopenClosedSwarm({String? historyId}) {if (_disposed || !canReopenClosedSwarm) return;- final index = historyId == null- ? _closedSwarms.length - 1- : _closedSwarms.indexWhere((entry) => entry.historyId == historyId);+ final index = _closedHistory.lastIndexWhere(+ (entry) =>+ entry is ClosedSwarm &&+ (historyId == null || entry.historyId == historyId),+ );if (index < 0) return;- final saved = _closedSwarms.removeAt(index);+ final saved = _closedHistory.removeAt(index) as ClosedSwarm;if (swarms.length == 1 && saved.replacesUntouchedWelcome(swarms.single)) {swarms.clear();}@@ -541,6 +572,58 @@ class AppNotifier extends ChangeNotifier {selectSwarm(restored.id);}+ /// Reopen the chosen closure, or the newest closure for Cmd-Shift-T.+ /// Membership is restored synchronously; a slow detach cannot resurrect an+ /// old controller or redirect the destination after a network wait.+ bool reopenClosed({String? historyId}) {+ final id = historyId ?? _closedHistory.lastOrNull?.historyId;+ if (id == null || !canReopenClosed(id)) return false;+ final index = _closedHistory.indexWhere((entry) => entry.historyId == id);+ final saved = _closedHistory[index];+ if (saved is ClosedSwarm) {+ reopenClosedSwarm(historyId: id);+ return true;+ }+ final agent = saved as ClosedAgent;+ _closedHistory.removeAt(index);+ var target = swarms.where((s) => s.id == agent.swarmId).firstOrNull;+ if (target == null) {+ target = Swarm(id: agent.swarmId, name: agent.swarmName);+ swarms.add(target);+ }+ final pane =+ allPanes+ .where(+ (p) =>+ p.machineId == agent.machineId && p.agentId == agent.agentId,+ )+ .firstOrNull ??+ (TerminalPane(+ id: _nextPaneId++,+ machineId: agent.machineId,+ agentId: agent.agentId,+ )..composerVisible = agent.composerVisible);+ if (!target.panes.contains(pane)) {+ target.panes.insert(agent.index.clamp(0, target.panes.length), pane);+ if (agent.pinnedSlot != null &&+ !target.pinnedSlots.containsValue(agent.pinnedSlot)) {+ target.pinnedSlots[pane.id] = agent.pinnedSlot!;+ }+ }+ if (target.focusedPaneId != pane.id) {+ target.previousPaneId = target.focusedPaneId;+ }+ target.focusedPaneId = pane.id;+ if (agent.zoomed || target.zoomedPaneId != null) {+ target.zoomedPaneId = pane.id;+ }+ _activeSwarmId = target.id;+ _settlePins();+ _paneFocusRequest++;+ selectSwarm(target.id);+ return true;+ }+/// Capture the destination before any network wait or tab change.Future<void> addAgentToSwarm(String machineId,@@ -1795,7 +1878,7 @@ class AppNotifier extends ChangeNotifier {}Future<void> login() async {- _closedSwarms.clear();+ _closedHistory.clear();_lastError = null;status = AppStatus.bootstrapping;signingIn = true;@@ -1845,7 +1928,7 @@ class AppNotifier extends ChangeNotifier {void cancelLogin() => cliLogin.cancel();Future<void> logout() async {- _closedSwarms.clear();+ _closedHistory.clear();// Best-effort and fire-and-forget: local state is cleared below regardless of whether the CLI// process could be reached, but a real `harness logout` clears its saved session so the NEXT// launch doesn't silently sign back in without ever showing the login screen.@@ -1856,7 +1939,7 @@ class AppNotifier extends ChangeNotifier {// Tiles go, the saved layout stays: signing out and back in is the same// person at the same desk, and the file is only read once machines exist.await _closeAllPanes(persist: false);- _closedSwarms.clear();+ _closedHistory.clear();await _pool?.closeAll();_pool = null;_cliEndpoint = null;@@ -4068,6 +4151,22 @@ class AppNotifier extends ChangeNotifier {Future<void> closePane(int paneId, {bool persist = true}) async {final pane = panes.where((p) => p.id == paneId).firstOrNull;if (pane == null) return;+ if (pane.agentId != null) {+ final machine = stateOf(pane.machineId);+ final agent = machine?.agents+ .where((a) => a.id == pane.agentId)+ .firstOrNull;+ _rememberClosed(+ ClosedAgent(+ pane,+ activeSwarm,+ historyId: 'closed-${_nextClosedHistoryId++}',+ name: agent?.name ?? pane.session?.agentName ?? pane.agentId!,+ machineName: machine?.machine.displayName ?? pane.machineId,+ engine: agent?.engine ?? pane.session?.engineId,+ ),+ );+ }activeSwarm.remove(pane);_settlePins();if (persist) _persistLayout();@@ -4636,7 +4735,7 @@ class AppNotifier extends ChangeNotifier {void dispose() {_localGitProjects.dispose();_disposed = true;- _closedSwarms.clear();+ _closedHistory.clear();_daemonSupervisionTimer?.cancel();_updateCheckTimer?.cancel();_environmentRecheckTimer?.cancel();diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dartindex e6545f582..e19c674b7 100644--- a/desktop/lib/state/swarm.dart+++ b/desktop/lib/state/swarm.dart@@ -55,12 +55,42 @@ class Swarm {}}-/// Session-free history for an accidental tab close. Terminal buffers and-/// controllers are released normally; a reopened view reuses any live peer.-class ClosedSwarm {+/// Session-free history: closing a view never owns the agent's lifetime.+sealed class ClosedWork {+ const ClosedWork({required this.historyId});+ final String historyId;+}++class ClosedAgent extends ClosedWork {+ ClosedAgent(+ TerminalPane pane,+ Swarm swarm, {+ required super.historyId,+ required this.name,+ required this.machineName,+ required this.engine,+ }) : swarmId = swarm.id,+ swarmName = swarm.name,+ index = swarm.panes.indexOf(pane),+ machineId = pane.machineId,+ agentId = pane.agentId!,+ composerVisible = pane.composerVisible,+ pinnedSlot = swarm.pinnedSlots[pane.id],+ zoomed = swarm.zoomedPaneId == pane.id;++ final String swarmId, swarmName, machineId, machineName, agentId, name;+ final String? engine;+ final int index;+ final bool composerVisible, zoomed;+ final int? pinnedSlot;+}++/// Terminal buffers and controllers are released normally; a reopened view+/// reuses any live peer.+class ClosedSwarm extends ClosedWork {ClosedSwarm(Swarm swarm, {- required this.historyId,+ required super.historyId,required this.index,Swarm? replacement,}) : id = swarm.id,@@ -96,7 +126,6 @@ class ClosedSwarm {>panes;final String? replacementId;- final String historyId;bool replacesUntouchedWelcome(Swarm swarm) =>swarm.id == replacementId &&diff --git a/desktop/lib/state/swarm_catalog.dart b/desktop/lib/state/swarm_catalog.dartindex 681ea1999..c488ba65b 100644--- a/desktop/lib/state/swarm_catalog.dart+++ b/desktop/lib/state/swarm_catalog.dart@@ -28,10 +28,16 @@ List<SwarmAgentRef> swarmAgents(AppNotifier app, [String query = '']) {.toLowerCase().split(RegExp(r'\s+')).where((t) => t.isNotEmpty);- return [+ final agents = [for (final machine in app.machineStates.values)for (final agent in machine.agents) SwarmAgentRef(machine, agent),- ].where((entry) => terms.every(entry.searchText.contains)).toList();+ ];+ // Catalog/group construction needs identities, not searchable strings.+ // Avoid formatting every agent's metadata just to accept an empty query.+ if (terms.isEmpty) return agents;+ return agents+ .where((entry) => terms.every(entry.searchText.contains))+ .toList();}class SavedSwarmProject {diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dartindex f5cac8555..740464d79 100644--- a/desktop/lib/state/swarm_navigation.dart+++ b/desktop/lib/state/swarm_navigation.dart@@ -205,17 +205,18 @@ class SwarmSearchCatalog {if (listEquals(_presentation, presentation)) return _entries;_presentation = presentation;final entries = swarmDestinations(app, recent: recent);- final available = {+ final agentsById = {for (final entry in entries)- if (entry.agentId != null) entry.id,+ if (entry.agentId != null) entry.id: entry,};+ final machineMembers = <String, Set<String>>{};+ for (final entry in agentsById.values) {+ (machineMembers[entry.machineId!] ??= {}).add(entry.id);+ }final groups = swarmProjects(app, projects);for (final machine in app.machineStates.values) {final id = machine.machine.machineId;- final members = {- for (final entry in entries)- if (entry.machineId == id && entry.agentId != null) entry.id,- };+ final members = machineMembers[id] ?? const <String>{};entries.add(SwarmDestination(id: 'machine:$id',@@ -238,7 +239,7 @@ class SwarmSearchCatalog {for (final group in groups) {final members = {for (final entry in group.agents)- if (available.contains(+ if (agentsById.containsKey(agentDestinationId(entry.machineId, entry.agent.id),))agentDestinationId(entry.machineId, entry.agent.id),@@ -252,21 +253,20 @@ class SwarmSearchCatalog {swarmId: null,current: false,members: Set.unmodifiable(members),- searchFields: [+ searchFields: {group.saved?.path,for (final entry in group.agents) ...[entry.machine.machine.displayName,entry.project?.cwd,entry.project?.branch,],- ],+ },),);// Explicit project associations from older daemons are searchable too.- for (final entry in entries.where(- (entry) => members.contains(entry.id),- )) {- final name = group.name.toLowerCase();+ final name = group.name.toLowerCase();+ for (final id in members) {+ final entry = agentsById[id]!;if (!entry.fields.contains(name)) entry.fields.add(name);}}@@ -352,17 +352,31 @@ String _agentCountLabel(Iterable<String?> ids) {return '$count ${count == 1 ? 'agent' : 'agents'}';}-List<SwarmDestination> closedSwarmDestinations(AppNotifier app) => [- for (final entry in app.closedSwarms)- SwarmDestination(- id: entry.historyId,- closedId: entry.historyId,- title: entry.name,- detail:- '${_agentCountLabel(entry.panes.map((pane) => pane.agentId))} · Recently closed',- swarmId: null,- current: false,- ),+List<SwarmDestination> closedWorkDestinations(AppNotifier app) => [+ for (final entry in app.closedHistory)+ if (entry is ClosedSwarm)+ SwarmDestination(+ id: entry.historyId,+ closedId: entry.historyId,+ title: entry.name,+ detail:+ '${_agentCountLabel(entry.panes.map((pane) => pane.agentId))} · Recently closed',+ swarmId: null,+ current: false,+ )+ else if (entry is ClosedAgent)+ SwarmDestination(+ id: entry.historyId,+ closedId: entry.historyId,+ title: entry.name,+ detail: '${entry.machineName} · ${entry.swarmName} · Recently closed',+ swarmId: null,+ machineId: entry.machineId,+ agentId: entry.agentId,+ engine: entry.engine,+ current: false,+ searchFields: [entry.machineName, entry.swarmName, entry.engine],+ ),];List<SwarmDestination> swarmDestinations(@@ -404,7 +418,7 @@ List<SwarmDestination> swarmDestinations(detail: _agentCountLabel(swarm.panes.map((pane) => pane.agentId)),swarmId: swarm.id,current: swarm.id == app.activeSwarmId,- searchFields: context,+ searchFields: context.toSet(),),);}@@ -481,6 +495,10 @@ List<SwarmDestination> rankSwarmDestinations(final recency = {for (var i = 0; i < recent.length; i++) recent[i]: i};final ranked = <({SwarmDestination entry, int score})>[];for (final entry in all) {+ if (entry.fields.first == needle) {+ ranked.add((entry: entry, score: -1));+ continue;+ }var total = 0;for (final term in terms) {int? best;@@ -499,6 +517,10 @@ List<SwarmDestination> rankSwarmDestinations(? 16: 128 + spread);if (best == null || score < best) best = score;+ // Every remaining field is metadata, whose best possible score is 64.+ // An exact/prefix/substring title match already beats that; an exact+ // metadata match ties it. Neither needs further field scans.+ if (best <= 64) break;}if (best == null) {total = -1;@@ -507,10 +529,7 @@ List<SwarmDestination> rankSwarmDestinations(total += best;}if (total >= 0) {- ranked.add((- entry: entry,- score: entry.fields.first == needle ? -1 : total,- ));+ ranked.add((entry: entry, score: total));}}int tier(SwarmDestination e) => !e.hasView@@ -544,12 +563,7 @@ Future<bool> activateSwarmDestination(required String destinationSwarmId,}) async {if (destination.closedId != null) {- if (!app.canReopenClosedSwarm ||- !app.closedSwarms.any((s) => s.historyId == destination.closedId)) {- return false;- }- app.reopenClosedSwarm(historyId: destination.closedId);- return true;+ return app.reopenClosed(historyId: destination.closedId);}if (destination.isSwarm) {if (!app.swarms.any((s) => s.id == destination.swarmId)) return false;diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex 072d4825c..e84cad680 100644--- a/desktop/lib/state/swarm_search.dart+++ b/desktop/lib/state/swarm_search.dart@@ -40,7 +40,7 @@ class SwarmSearchController extends ChangeNotifier {void _refresh() {final next = history == null? _cache.read(app, projects?.projects ?? const [], recent: recent)- : [...history!.menuDestinations(app), ...closedSwarmDestinations(app)];+ : [...history!.menuDestinations(app), ...closedWorkDestinations(app)];if (identical(next, _catalog)) return;_catalog = next;_filter();@@ -86,7 +86,7 @@ class SwarmSearchController extends ChangeNotifier {SwarmSearchSelection? submit([SwarmDestination? row]) {final destination = row ?? selected;- if (destination == null) return null;+ if (destination == null || !canSubmit(destination)) return null;if (!destination.isGroup) return SwarmSearchSelection(destination);_rootQuery = query;_scopeId = destination.id;@@ -98,6 +98,10 @@ class SwarmSearchController extends ChangeNotifier {return null;}+ bool canSubmit(SwarmDestination? row) =>+ row != null &&+ (row.closedId == null || app.canReopenClosed(row.closedId!));+void back() {if (!scoped) return;_selectedId = _scopeId;diff --git a/desktop/lib/usage/models_menu_controller.dart b/desktop/lib/usage/models_menu_controller.dartnew file mode 100644index 000000000..a49ca6e62--- /dev/null+++ b/desktop/lib/usage/models_menu_controller.dart@@ -0,0 +1,149 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import '../widgets/engine_identity.dart';+import 'usage_accounts.dart';+import 'usage_controller.dart';+import 'usage_window.dart';++/// Subscription readings for the native Models menu. Opening the menu reads+/// the cached snapshot immediately and refreshes at most once per minute.+/// No polling, credential reads or requests run on startup or tab changes.+class ModelsMenuController extends ChangeNotifier {+ ModelsMenuController({+ UsageController? usage,+ Future<List<MachineUsage>> Function()? remote,+ DateTime Function()? now,+ }) : _usage = usage ?? UsageController(remote: remote, autoStart: false),+ _ownsUsage = usage == null,+ _now = now ?? DateTime.now {+ _usage.addListener(_changed);+ }++ final UsageController _usage;+ final bool _ownsUsage;+ final DateTime Function() _now;+ Future<void>? _pending;+ DateTime? _lastAttempt;+ bool _failed = false;+ bool _disposed = false;++ List<Map<String, Object?>> get rows => [+ for (final account in _usage.accounts)+ _row(account, _now(), failed: _failed),+ ];++ Future<void> refresh() {+ if (_disposed) return Future.value();+ // Re-evaluate expired windows even if another request is already running.+ _changed();+ if (_pending case final pending?) return pending;+ final last = _lastAttempt;+ if (last != null && _now().difference(last) < const Duration(minutes: 1)) {+ return Future.value();+ }+ _lastAttempt = _now();+ _failed = false;+ return _pending = _refresh();+ }++ Future<void> _refresh() async {+ try {+ await _usage.refresh();+ } catch (_) {+ // A credential/source failure must never escape into a menu callback.+ // Never include a raw exception: it could contain authentication data.+ _failed = true;+ } finally {+ _pending = null;+ _changed();+ }+ }++ void _changed() {+ if (!_disposed) notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ _usage.removeListener(_changed);+ if (_ownsUsage) _usage.dispose();+ super.dispose();+ }++ static Map<String, Object?> _row(+ UsageAccount account,+ DateTime now, {+ required bool failed,+ }) {+ final reading = account.reading;+ final provider = switch (reading.provider) {+ UsageProvider.claude => 'Anthropic',+ UsageProvider.codex => 'OpenAI',+ };+ final scope = account.isLocal ? '' : account.machines.join(', ');+ final title = scope.isEmpty ? provider : '$provider · $scope';+ final windows = reading.windows;+ final expired =+ (reading.fetchedAt != null &&+ now.difference(reading.fetchedAt!) > const Duration(minutes: 2)) ||+ windows.any((w) => w.resetsAt != null && !w.resetsAt!.isAfter(now));+ final valid =+ !failed &&+ !expired &&+ reading.hasFigures &&+ windows.every((w) => w.usedPercent.isFinite);+ final String status;+ final details = <String>[];+ if (valid) {+ // Show the limit that will stop work first. Weekly-only summaries can+ // look healthy while a shorter window is already exhausted.+ final limiting = reading.tightest!;+ status = '${_remaining(limiting)} remaining';+ details.add('Limiting window: ${limiting.label}');+ for (final window in windows) {+ final reset = window.resetsInLabel(now: now);+ details.add(+ '${window.label} — ${_remaining(window)} remaining'+ '${reset == null ? '' : ' · resets in $reset'}',+ );+ }+ } else {+ status = failed || expired+ ? 'Usage unavailable'+ : switch (reading.status) {+ UsageStatus.loading => 'Checking usage…',+ UsageStatus.signedOut => 'Not signed in',+ _ => 'Usage unavailable',+ };+ details.add(+ expired+ ? 'The last reading has expired. Reopen Models to refresh.'+ : reading.message ?? status,+ );+ }+ if (account.machines.isNotEmpty) {+ details.add(+ account.isLocal+ ? 'Shared with ${account.machines.join(', ')}'+ : 'On ${account.machines.join(', ')}',+ );+ }+ return {+ 'title': title,+ 'status': status,+ 'details': details,+ 'engine': reading.provider.engineId,+ 'iconAsset': engineIdentity(reading.provider.engineId).asset,+ };+ }++ static String _remaining(UsageWindow window) {+ final left = (100 - window.usedPercent).clamp(0, 100);+ // Never round a positive remainder to zero (or a partial balance to 100).+ if (left > 0 && left < 1) return '<1%';+ return '${left.floor()}%';+ }+}diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dartindex fcaf23bd8..a0fd68fb5 100644--- a/desktop/lib/widgets/swarm_switcher.dart+++ b/desktop/lib/widgets/swarm_switcher.dart@@ -334,6 +334,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {final row = search.rows[index];return ListTile(key: ValueKey(row.id),+ enabled: search.canSubmit(row),selected: index == search.cursor,selectedColor: Colors.white,selectedTileColor: Colors.white10,@@ -344,7 +345,11 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {horizontal: 12,),leading: row.agentId != null- ? EngineMark(engine: row.engine, size: 20)+ ? EngineMark(+ engine: row.engine,+ size: 20,+ enabled: search.canSubmit(row),+ ): Icon(row.isMachine? Icons.computer_outlined@@ -378,7 +383,9 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {color: Colors.white54,),),- onTap: () => _submit(row),+ onTap: search.canSubmit(row)+ ? () => _submit(row)+ : null,);},),@@ -390,7 +397,11 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {child: Padding(padding: const EdgeInsets.symmetric(horizontal: 10),child: Text(- selected?.agentId != null && !selected!.hasView+ selected?.closedId != null+ ? search.canSubmit(selected)+ ? 'Reopen ${selected!.isSwarm ? 'swarm' : 'agent'}'+ : 'No room to reopen'+ : selected?.agentId != null && !selected!.hasView? 'Open agent in ${search.targetName}': '↑↓ choose · Esc close',maxLines: 1,diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex abb1280ff..c9c35fe5b 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -1,9 +1,10 @@import Cocoaimport FlutterMacOS+import ImageIO/// Real AppKit controls in the title bar, beside the system traffic lights./// https://developer.apple.com/documentation/appkit/nstitlebaraccessoryviewcontroller/layoutattribute-final class SwarmTitlebar: NSObject, NSMenuItemValidation {+final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {private weak var window: NSWindow?private let channel: FlutterMethodChannelprivate let accessory = NSTitlebarAccessoryViewController()@@ -20,6 +21,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {private var canGoForward = falseprivate var history: [SwarmHistoryEntry] = []private var closedHistory: [SwarmHistoryEntry] = []+ private let historyIcons = SwarmHistoryIcons()+ private let modelsMenu = NSMenu(title: "Models")+ private var subscriptions: [SwarmSubscriptionEntry] = []init(window: NSWindow, messenger: FlutterBinaryMessenger) {self.window = window@@ -34,7 +38,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {result(true)case "update":let state = call.arguments as? [String: Any] ?? [:]+ let wasEnabled = self.actionsEnabledself.actionsEnabled = state["enabled"] as? Bool == true+ if wasEnabled != self.actionsEnabled { self.updateModelsAvailability() }self.canReopen = state["canReopen"] as? Bool == trueself.canFind = state["canFind"] as? Bool == trueself.canClosePane = state["canClosePane"] as? Bool == true@@ -53,6 +59,10 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {case "closeSearch":self.strip.closeSearch()result(nil)+ case "modelsState":+ let state = call.arguments as? [String: Any] ?? [:]+ self.updateModels(state["subscriptions"] as? [[String: Any]] ?? [])+ result(nil)default: result(FlutterMethodNotImplemented)}}@@ -91,7 +101,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {accessory.view = stripwindow.addTitlebarAccessoryViewController(accessory)resize()- installSwarmMenu()+ installWorkspaceMenus()// An editable accessory must not become the window's initial input owner.window.makeFirstResponder(window.contentViewController)}@@ -103,8 +113,8 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {strip.needsLayout = true}- private func installSwarmMenu() {- guard let main = NSApp.mainMenu, main.item(withTitle: "Swarm") == nil else { return }+ private func installWorkspaceMenus() {+ guard let main = NSApp.mainMenu, main.item(withTitle: "Models") == nil else { return }// The stock Flutter nib includes a disabled Preferences placeholder. Make// the app-menu command work, and give ⌘, a single native owner.if let appMenu = main.item(at: 0)?.submenu {@@ -132,11 +142,12 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {let file = NSMenu(title: "File")add(file, "New Swarm", "t", "new")add(file, "New Agent…", "", "newAgent")- add(file, "Reopen Closed Swarm", "t", "reopen", [.command, .shift])+ add(file, "Reopen Last Closed", "t", "reopen", [.command, .shift])file.addItem(.separator())add(file, "Link Machine…", "", "linkMachine")add(file, "Add Project…", "", "addProject")file.addItem(.separator())+ add(file, "Rename Swarm…", "r", "renameActive", [.command, .shift])add(file, "Remove Agent from Swarm", "w", "closePane", [.command, .shift])add(file, "Close Swarm", "w", "closeActive")install(file, at: 1)@@ -145,18 +156,84 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {let windowIndex = main.items.firstIndex(where: { $0.title == "Window" }) ?? main.numberOfItemsinstall(historyMenu, at: windowIndex)- let swarm = NSMenu(title: "Swarm")- add(swarm, "Search Agents, Swarms, Machines and Projects…", "p", "jump")- add(swarm, "Rename Swarm…", "r", "renameActive", [.command, .shift])- swarm.addItem(.separator())- add(swarm, "Next Swarm", "]", "next", [.command, .shift])- add(swarm, "Previous Swarm", "[", "previous", [.command, .shift])- swarm.addItem(.separator())- add(swarm, "Agents Needing Input…", "i", "notifications", [.command, .shift])- install(swarm, at: windowIndex + 1)+ // Navigation chords remain in Flutter's terminal-safe shortcut table.+ // Search still needs a native owner when the titlebar field has focus.+ if let edit = main.item(withTitle: "Edit")?.submenu {+ edit.addItem(.separator())+ add(edit, "Search Agents, Swarms, Machines and Projects…", "p", "jump")+ }+ if let view = main.item(withTitle: "View")?.submenu {+ view.addItem(.separator())+ add(view, "Agents Needing Input…", "i", "notifications", [.command, .shift])+ }+ modelsMenu.autoenablesItems = false+ modelsMenu.delegate = self+ rebuildModelsMenu()+ install(modelsMenu, at: windowIndex + 1)installTerminalFindMenu(main)}+ func menuWillOpen(_ menu: NSMenu) {+ guard menu === modelsMenu, actionsEnabled else { return }+ // The native menu opens from its cache. Network/credential reads happen+ // asynchronously in Dart and never hold up AppKit's menu tracking.+ channel.invokeMethod("modelsOpened", arguments: nil)+ }++ private func updateModels(_ rows: [[String: Any]]) {+ let entries = rows.prefix(32).compactMap(SwarmSubscriptionEntry.init)+ guard entries != subscriptions else { return }+ subscriptions = entries+ rebuildModelsMenu()+ }++ private func rebuildModelsMenu() {+ modelsMenu.removeAllItems()+ func label(_ title: String, in menu: NSMenu) {+ let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")+ item.isEnabled = false+ menu.addItem(item)+ }+ func section(_ title: String) {+ if #available(macOS 14.0, *) {+ modelsMenu.addItem(NSMenuItem.sectionHeader(title: title))+ } else {+ label(title, in: modelsMenu)+ }+ }+ section("Subscription")+ for entry in subscriptions {+ let item = NSMenuItem(title: entry.title + " — " + entry.status, action: nil, keyEquivalent: "")+ item.image = historyIcons.image(engine: entry.engine, asset: entry.iconAsset)+ item.toolTip = entry.details.joined(separator: "\n")+ let detail = NSMenu(title: entry.title)+ detail.autoenablesItems = false+ for line in entry.details { label(line, in: detail) }+ item.submenu = detail+ item.isEnabled = actionsEnabled+ modelsMenu.addItem(item)+ }+ if subscriptions.isEmpty {+ label("Anthropic", in: modelsMenu)+ label("OpenAI", in: modelsMenu)+ }+ modelsMenu.addItem(.separator())+ section("API")+ label("OpenRouter API", in: modelsMenu)+ label("fal.ai API", in: modelsMenu)+ modelsMenu.addItem(.separator())+ section("Local")+ label("Local models", in: modelsMenu)+ modelsMenu.addItem(.separator())+ label("Add Model", in: modelsMenu)+ }++ private func updateModelsAvailability() {+ for item in modelsMenu.items where item.submenu != nil {+ item.isEnabled = actionsEnabled+ }+ }+private func updateHistory(_ rows: [[String: Any]], closed: [[String: Any]] = []) {let entries = rows.prefix(64).compactMap(SwarmHistoryEntry.init)let closedEntries = closed.prefix(24).compactMap(SwarmHistoryEntry.init)@@ -200,12 +277,13 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {item.representedObject = entry.iditem.toolTip = entry.title + "\n" + entry.detailitem.state = entry.current ? .on : .off- item.image = NSImage(systemSymbolName: entry.swarm ? "rectangle.split.2x2" : "terminal",- accessibilityDescription: nil)+ item.image = entry.swarm+ ? NSImage(systemSymbolName: "rectangle.split.2x2", accessibilityDescription: nil)+ : historyIcons.image(engine: entry.engine, asset: entry.iconAsset)historyMenu.addItem(item)}if entries.isEmpty {- let item = NSMenuItem(title: closed ? "No Recently Closed Swarms" : "No Recent Visits", action: nil, keyEquivalent: "")+ let item = NSMenuItem(title: closed ? "No Recently Closed Agents or Swarms" : "No Recent Visits", action: nil, keyEquivalent: "")item.isEnabled = falsehistoryMenu.addItem(item)}@@ -237,7 +315,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {return actionsEnabled && history.contains(where: { $0.id == action })}if menuItem.action == #selector(closedHistoryAction(_:)) {- return actionsEnabled && canReopen && closedHistory.contains(where: { $0.id == action })+ return actionsEnabled && closedHistory.contains(where: { $0.id == action && $0.canReopen })}return actionsEnabled && (action != "reopen" || canReopen) &&(action != "historyBack" || canGoBack) && (action != "historyForward" || canGoForward) &&@@ -261,12 +339,33 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {}}+private struct SwarmSubscriptionEntry: Equatable {+ let title: String+ let status: String+ let details: [String]+ let engine: String?+ let iconAsset: String?++ init?(_ row: [String: Any]) {+ guard let title = row["title"] as? String, !title.isEmpty,+ let status = row["status"] as? String else { return nil }+ self.title = title+ self.status = status+ details = Array((row["details"] as? [String] ?? [status]).prefix(16))+ engine = row["engine"] as? String+ iconAsset = row["iconAsset"] as? String+ }+}+private struct SwarmHistoryEntry: Equatable {let id: Stringlet title: Stringlet detail: Stringlet swarm: Boollet current: Bool+ let engine: String?+ let iconAsset: String?+ let canReopen: Boolinit?(_ row: [String: Any]) {guard let id = row["id"] as? String, let title = row["title"] as? String else { return nil }self.id = id@@ -274,6 +373,83 @@ private struct SwarmHistoryEntry: Equatable {detail = row["detail"] as? String ?? ""swarm = row["swarm"] as? Bool == truecurrent = row["current"] as? Bool == true+ engine = (row["engine"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ iconAsset = row["iconAsset"] as? String+ canReopen = row["canReopen"] as? Bool == true+ }+}++/// Reuse the same bundled engine artwork as pane headers. Each menu mark is+/// decoded once to at most 32 pixels, rather than retaining a full-size bitmap+/// or reopening assets on every history/focus update.+private final class SwarmHistoryIcons {+ private let cache = NSCache<NSString, NSImage>()+ private let assetURL: (String) -> URL?++ init(assetURL: @escaping (String) -> URL? = { asset in+ let bundle = Bundle(identifier: "io.flutter.flutter.app") ?? Bundle.main+ let key = FlutterDartProject.lookupKey(forAsset: asset, from: bundle)+ return bundle.url(forResource: key, withExtension: nil)+ }) {+ self.assetURL = assetURL+ cache.countLimit = 32+ }++ func image(engine: String?, asset: String?) -> NSImage {+ let id = engine?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? ""+ let key = "\(id):\(asset ?? "")" as NSString+ if let image = cache.object(forKey: key) { return image }+ let size = NSSize(width: 16, height: 16)+ let image: NSImage+ if let asset, asset.hasPrefix("assets/engine-icons/"),+ asset.hasSuffix(".png"), !asset.contains(".."),+ let url = assetURL(asset),+ let source = CGImageSourceCreateWithURL(url as CFURL, nil),+ let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, [+ kCGImageSourceCreateThumbnailFromImageAlways: true,+ kCGImageSourceCreateThumbnailWithTransform: true,+ kCGImageSourceThumbnailMaxPixelSize: 32,+ kCGImageSourceShouldCacheImmediately: true,+ ] as CFDictionary) {+ let bitmap = NSImage(cgImage: thumbnail, size: .zero)+ let scale = 16 / CGFloat(max(thumbnail.width, thumbnail.height))+ let width = CGFloat(thumbnail.width) * scale+ let height = CGFloat(thumbnail.height) * scale+ image = NSImage(size: size, flipped: false) { _ in+ bitmap.draw(in: NSRect(x: (16 - width) / 2, y: (16 - height) / 2, width: width, height: height))+ return true+ }+ } else if id == "claude" {+ // Same four round strokes, proportions and orange as EngineMark.+ image = NSImage(size: size, flipped: false) { _ in+ NSColor(srgbRed: 204.0 / 255, green: 124.0 / 255, blue: 94.0 / 255, alpha: 1).setStroke()+ let path = NSBezierPath()+ path.lineWidth = 16 * 0.098+ path.lineCapStyle = .round+ for i in 0..<4 {+ let angle = CGFloat(i) * .pi / 4+ let dx = 16 * 0.39 * cos(angle), dy = 16 * 0.39 * sin(angle)+ path.move(to: NSPoint(x: 8 - dx, y: 8 - dy))+ path.line(to: NSPoint(x: 8 + dx, y: 8 + dy))+ }+ path.stroke()+ return true+ }+ } else {+ image = NSImage(size: size, flipped: false) { _ in+ let initial = String(id.first ?? "A").uppercased() as NSString+ let attributes: [NSAttributedString.Key: Any] = [+ .font: NSFont.monospacedSystemFont(ofSize: 11, weight: .bold),+ .foregroundColor: NSColor.black,+ ]+ let bounds = initial.size(withAttributes: attributes)+ initial.draw(at: NSPoint(x: (16 - bounds.width) / 2, y: (16 - bounds.height) / 2), withAttributes: attributes)+ return true+ }+ image.isTemplate = true+ }+ cache.setObject(image, forKey: key)+ return image}}diff --git a/desktop/test/benchmarks/swarm_benchmark.dart b/desktop/test/benchmarks/swarm_benchmark.dartindex 5eb270a30..36239c341 100644--- a/desktop/test/benchmarks/swarm_benchmark.dart+++ b/desktop/test/benchmarks/swarm_benchmark.dart@@ -10,6 +10,7 @@ import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';import 'package:harness/state/swarm_catalog.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/terminal/terminal_session.dart';import 'package:harness/widgets/terminal_panel.dart';@@ -23,15 +24,18 @@ Map<String, num> distribution(List<int> microseconds) {'samples': microseconds.length,'medianMs': microseconds[microseconds.length ~/ 2] / 1000,'p95Ms': microseconds[(microseconds.length * 0.95).ceil() - 1] / 1000,+ 'p99Ms': microseconds[(microseconds.length * 0.99).ceil() - 1] / 1000,};}-Map<String, num> measure(void Function() operation) {+Map<String, num> measure(void Function() operation, {void Function()? setup}) {for (var i = 0; i < 20; i++) {+ setup?.call();operation();}final times = <int>[];for (var i = 0; i < 100; i++) {+ setup?.call();final watch = Stopwatch()..start();operation();times.add(watch.elapsedMicroseconds);@@ -141,6 +145,43 @@ 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.+ final cache = SwarmSearchCatalog();+ final entries = cache.read(app, const []);+ expect(entries, hasLength(2059));+ final controller = SwarmSearchController(app, const []);+ addTearDown(controller.dispose);+ final queries = <String, Object>{};+ for (final query in [+ 'agent',+ 'agent 12 machine 3',+ 'agn12',+ 'project 12 main',+ 'no-such-agent',+ ]) {+ final timing = measure(+ () => controller.setQuery(query),+ setup: () => controller.setQuery(''),+ );+ 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(() {+ SwarmSearchCatalog().read(app, const []);+ }), 'unchangedCatalog': measure(() {+ cache.read(app, const []);+ }), 'openAndDisposeController': measure(() {+ SwarmSearchController(app, const []).dispose();+ }), 'queries': queries, 'scopedQuery': scoped})}',+ );});for (final swarmCount in [4, 12]) {diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dartnew file mode 100644index 000000000..1741b2d13--- /dev/null+++ b/desktop/test/models_menu_test.dart@@ -0,0 +1,242 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/usage/models_menu_controller.dart';+import 'package:harness/usage/usage_accounts.dart';+import 'package:harness/usage/usage_controller.dart';+import 'package:harness/usage/usage_source.dart';+import 'package:harness/usage/usage_window.dart';++import 'swarm_state_test.dart' show createApp;++class _Source implements UsageSource {+ _Source(this.provider, this.answer);+ @override+ final UsageProvider provider;+ Future<ProviderUsage> Function() answer;+ int calls = 0;+ @override+ Future<ProviderUsage> read() {+ calls++;+ return answer();+ }+}++void main() {+ final instant = DateTime.utc(2026, 9, 13, 12);+ ProviderUsage reading({+ double session = 85,+ double weekly = 30,+ DateTime? reset,+ DateTime? fetched,+ String? account = 'same-account',+ }) => ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.ok,+ account: account,+ fetchedAt: fetched ?? instant,+ windows: [+ UsageWindow(label: 'Session', usedPercent: session, resetsAt: reset),+ UsageWindow(label: 'Weekly', usedPercent: weekly),+ ],+ );++ test(+ 'remaining means the limiting window, with account deduplication',+ () async {+ final source = _Source(UsageProvider.claude, () async => reading());+ final usage = UsageController(+ sources: [source],+ autoStart: false,+ remote: () async => [+ MachineUsage(machineName: 'Shared Mac', readings: [reading()]),+ MachineUsage(+ machineName: 'Other Mac',+ readings: [reading(account: 'different-account', session: 50)],+ ),+ ],+ );+ final menu = ModelsMenuController(usage: usage, now: () => instant);+ addTearDown(usage.dispose);+ addTearDown(menu.dispose);+ await menu.refresh();+ expect(menu.rows, hasLength(2));+ expect(menu.rows.first['title'], 'Anthropic');+ expect(menu.rows.first['status'], '15% remaining');+ expect(menu.rows.first['details'], contains('Weekly — 70% remaining'));+ expect(menu.rows.first['details'], contains('Shared with Shared Mac'));+ expect(menu.rows.last['title'], 'Anthropic · Other Mac');+ expect(menu.rows.last['status'], '50% remaining');+ expect(menu.rows.toString(), isNot(contains('same-account')));+ },+ );++ test(+ 'no startup work; opening coalesces and caches requests for a minute',+ () async {+ var now = instant;+ var answer = Completer<ProviderUsage>();+ final source = _Source(UsageProvider.claude, () => answer.future);+ final usage = UsageController(sources: [source], autoStart: false);+ final menu = ModelsMenuController(usage: usage, now: () => now);+ addTearDown(usage.dispose);+ addTearDown(menu.dispose);+ expect(source.calls, 0);+ final first = menu.refresh();+ expect(menu.refresh(), same(first));+ expect(source.calls, 1);+ answer.complete(reading());+ await first;+ await menu.refresh();+ expect(source.calls, 1);+ now = now.add(const Duration(minutes: 1));+ answer = Completer<ProviderUsage>();+ final second = menu.refresh();+ expect(source.calls, 2);+ answer.complete(reading());+ await second;+ },+ );++ test(+ 'unknown, expired and invalid readings never become made-up percentages',+ () async {+ ProviderUsage value = const ProviderUsage(+ provider: UsageProvider.claude,+ status: UsageStatus.signedOut,+ );+ var now = instant;+ final source = _Source(UsageProvider.claude, () async => value);+ final usage = UsageController(sources: [source], autoStart: false);+ final menu = ModelsMenuController(usage: usage, now: () => now);+ addTearDown(usage.dispose);+ addTearDown(menu.dispose);+ await menu.refresh();+ expect(menu.rows.single['status'], 'Not signed in');+ for (final next in [+ reading(reset: instant),+ reading(session: double.nan),+ reading(fetched: instant.subtract(const Duration(minutes: 3))),+ ]) {+ value = next;+ now = now.add(const Duration(minutes: 1));+ await menu.refresh();+ expect(menu.rows.single['status'], 'Usage unavailable');+ expect(menu.rows.single['details'].toString(), isNot(contains('%')));+ }+ },+ );++ test(+ 'a positive fraction of remaining usage is not rounded to zero',+ () async {+ final source = _Source(+ UsageProvider.claude,+ () async => reading(session: 99.6),+ );+ final usage = UsageController(sources: [source], autoStart: false);+ final menu = ModelsMenuController(usage: usage, now: () => instant);+ addTearDown(usage.dispose);+ addTearDown(menu.dispose);+ await menu.refresh();+ expect(menu.rows.single['status'], '<1% remaining');+ },+ );++ test(+ 'source errors and a late response after disposal are contained',+ () async {+ final answer = Completer<ProviderUsage>();+ final source = _Source(UsageProvider.codex, () => answer.future);+ final usage = UsageController(sources: [source], autoStart: false);+ final menu = ModelsMenuController(usage: usage, now: () => instant);+ addTearDown(usage.dispose);+ var notifications = 0;+ menu.addListener(() => notifications++);+ final request = menu.refresh();+ menu.dispose();+ final count = notifications;+ answer.completeError(StateError('synthetic secret must not reach UI'));+ await request;+ expect(notifications, count);+ },+ );++ testWidgets(+ 'native Models opens lazily without changing the swarm or search',+ (tester) async {+ const channel = MethodChannel('harness/swarm_tabs');+ final messenger = tester.binding.defaultBinaryMessenger;+ final messages = <MethodCall>[];+ messenger.setMockMethodCallHandler(channel, (call) async {+ messages.add(call);+ return true;+ });+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));+ final source = _Source(+ UsageProvider.codex,+ () async => const ProviderUsage(+ provider: UsageProvider.codex,+ status: UsageStatus.signedOut,+ ),+ );+ final usage = UsageController(sources: [source], autoStart: false);+ final menu = ModelsMenuController(usage: usage);+ final app = createApp();+ final original = app.activeSwarmId;+ final projects = SwarmProjectStore();+ await tester.pumpWidget(+ MaterialApp(+ home: SwarmScreen(+ notifier: app,+ nativeTabs: true,+ projectStore: projects,+ modelsMenu: menu,+ ),+ ),+ );+ expect(source.calls, 0);+ final previousUpdates = messages+ .where((c) => c.method == 'update')+ .length;+ final reply = Completer<void>();+ messenger.handlePlatformMessage(+ channel.name,+ const StandardMethodCodec().encodeMethodCall(+ const MethodCall('modelsOpened'),+ ),+ (_) => reply.complete(),+ );+ await reply.future;+ await tester.pump();+ expect(source.calls, 1);+ expect(app.activeSwarmId, original);+ expect(+ messages.where((c) => c.method == 'update').length,+ previousUpdates,+ );+ expect(messages.where((c) => c.method == 'closeSearch'), isEmpty);+ final snapshot =+ messages.lastWhere((c) => c.method == 'modelsState').arguments as Map;+ expect((snapshot['subscriptions'] as List).single['title'], 'OpenAI');+ expect(+ (snapshot['subscriptions'] as List).single['status'],+ 'Not signed in',+ );+ await tester.pumpWidget(const SizedBox());+ expect(+ (messages.lastWhere((c) => c.method == 'modelsState').arguments+ as Map)['subscriptions'],+ isEmpty,+ );+ menu.dispose();+ usage.dispose();+ app.dispose();+ projects.dispose();+ },+ );+}diff --git a/desktop/test/swarm_closed_agents_test.dart b/desktop/test/swarm_closed_agents_test.dartnew file mode 100644index 000000000..03cb46056--- /dev/null+++ b/desktop/test/swarm_closed_agents_test.dart@@ -0,0 +1,232 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/swarm.dart';+import 'package:harness/state/swarm_navigation.dart';+import 'package:harness/terminal/terminal_session.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(+ 'History interleaves closed agents and swarms with captured identities',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ app.machineStates['m']!.agents = [+ const Agent(+ id: 'a0',+ name: 'Planning',+ engine: 'claude',+ terminalAvailable: true,+ ),+ ];+ app.renameSwarm(app.activeSwarmId, 'Work');+ await app.addAgentToSwarm('m', 'a0');+ await app.closePane(app.focusedPaneId!);+ final agentId = app.closedHistory.single.historyId;+ await app.closeSwarm(app.activeSwarmId);+ final swarmId = app.closedHistory.first.historyId;+ expect(app.closedHistory.map((e) => e.runtimeType), [+ ClosedSwarm,+ ClosedAgent,+ ]);+ // Discovery can disappear without losing the closed agent's name/icon.+ app.machineStates.clear();+ final rows = closedWorkDestinations(app);+ expect(rows.map((e) => e.id), [swarmId, agentId]);+ expect(rows.last.title, 'Planning');+ expect(rows.last.engine, 'claude');+ expect(rows.last.agentId, 'a0');+ expect(rows.last.detail, contains('Test host · Work'));+ expect(rows.first.isSwarm, isTrue);+ expect(rows.last.isSwarm, isFalse);+ },+ );++ test(+ 'reopening a shared agent restores its slot and keeps the live terminal',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ final first = app.adoptSessionForTest(terminal('a0', []));+ final shared = app.adoptSessionForTest(terminal('a1', []));+ final last = app.adoptSessionForTest(terminal('a2', []));+ final work = app.activeSwarm;+ app.focusPane(shared.id);+ app.togglePinPane(shared.id);+ app.toggleZoomPane();+ app.newSwarm(name: 'Other');+ await app.addAgentToSwarm('m', 'a1');+ final other = app.activeSwarm;+ app.selectSwarm(work.id);+ await app.closePane(shared.id);+ expect(work.panes, [first, last]);+ expect(other.panes.single, same(shared));+ app.selectSwarm(other.id);+ app.toggleComposer(shared.id);+ expect(app.reopenClosed(), isTrue);+ expect(app.activeSwarm, same(work));+ expect(work.panes, [first, shared, last]);+ expect(app.focusedPaneId, shared.id);+ expect(app.zoomedPaneId, shared.id);+ expect(app.isPanePinned(shared), isTrue);+ expect(shared.composerVisible, isTrue);+ expect(other.panes.single.session, same(shared.session));+ expect(app.closedHistory, isEmpty);+ },+ );++ test('a closed parent gets a swarm when its agent alone is reopened', () async {+ final app = createApp();+ addTearDown(app.dispose);+ app.renameSwarm(app.activeSwarmId, 'Workshop');+ final origin = app.activeSwarmId;+ await app.addAgentToSwarm('m', 'a0');+ await app.addAgentToSwarm('m', 'a1');+ await app.closePane(app.panes.first.id);+ final closure = app.closedHistory.single.historyId;+ await app.closeSwarm(origin);+ expect(app.reopenClosed(historyId: closure), isTrue);+ expect(app.activeSwarmId, origin);+ expect(app.activeSwarm.name, 'Workshop');+ expect(app.panes.single.agentId, 'a0');+ expect(app.closedHistory.single, isA<ClosedSwarm>());+ expect(app.reopenClosed(historyId: closure), isFalse);+ // Restoring the separately closed group cannot duplicate a Swarm identity.+ expect(app.reopenClosed(), isTrue);+ expect(app.panes.single.agentId, 'a1');+ expect(app.swarms.map((s) => s.id).toSet().length, app.swarms.length);+ });++ test(+ 'agent recovery can fit at the tab limit when swarm recovery cannot',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ final origin = app.activeSwarmId;+ await app.closePane(app.focusedPaneId!);+ final agentId = app.closedHistory.single.historyId;+ app.newSwarm(name: 'Closed group');+ await app.closeSwarm(app.activeSwarmId);+ while (app.swarms.length < AppNotifier.maxSwarms) {+ app.newSwarm();+ }+ expect(app.canReopenLastClosed, isFalse);+ expect(app.canReopenClosed(agentId), isTrue);+ expect(app.reopenClosed(historyId: agentId), isTrue);+ expect(app.activeSwarmId, origin);+ expect(app.panes.single.agentId, 'a0');+ expect(app.swarms, hasLength(AppNotifier.maxSwarms));+ },+ );++ test(+ 'a full destination retains its closed agent until there is room',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ await app.closePane(app.focusedPaneId!);+ final id = app.closedHistory.single.historyId;+ for (var i = 1; i <= AppNotifier.maxPanes; i++) {+ await app.addAgentToSwarm('m', 'a$i');+ }+ expect(app.canReopenClosed(id), isFalse);+ expect(app.reopenClosed(historyId: id), isFalse);+ expect(app.closedHistory.single.historyId, id);+ await app.closePane(app.panes.first.id);+ expect(app.reopenClosed(historyId: id), isTrue);+ expect(app.panes, hasLength(AppNotifier.maxPanes));+ expect(app.focusedPane!.agentId, 'a0');+ },+ );++ test(+ 'manually re-added agents are focused without duplicating membership',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ await app.closePane(app.focusedPaneId!);+ await app.addAgentToSwarm('m', 'a0');+ final reopened = app.panes.single;+ expect(app.reopenClosed(), isTrue);+ expect(app.panes.single, same(reopened));+ expect(app.closedHistory, isEmpty);+ },+ );++ test('rapid close/reopen cannot reclaim the closing controller', () async {+ final app = createApp();+ addTearDown(app.dispose);+ final closed = Completer<bool>();+ final sent = <String>[];+ final session =+ TerminalSession(+ machineId: 'm',+ agentId: 'a0',+ agentName: 'Work',+ engineId: 'codex',+ send: (type, _) {+ sent.add(type);+ return type == 'terminal_close'+ ? closed.future+ : Future.value(true);+ },+ sendBinary: (_) async => true,+ )+ ..streamId = 'closing-stream'+ ..status = TerminalSessionStatus.controlling;+ final old = app.adoptSessionForTest(session);+ final closing = app.closePane(old.id);+ expect(app.reopenClosed(), isTrue);+ final restored = app.panes.single;+ expect(restored, isNot(same(old)));+ expect(restored.session, isNull);+ closed.complete(true);+ await closing;+ expect(app.panes.single, same(restored));+ expect(sent, ['terminal_close']);+ });++ test(+ 'the combined history stays bounded without retaining sessions',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ for (var i = 0; i < 30; i++) {+ await app.addAgentToSwarm('m', 'a0');+ await app.closePane(app.focusedPaneId!);+ app.renameSwarm(app.activeSwarmId, 'Work $i');+ await app.closeSwarm(app.activeSwarmId);+ }+ expect(app.closedHistory, hasLength(AppNotifier.maxClosedSwarms));+ expect(app.closedHistory.whereType<ClosedAgent>(), hasLength(12));+ expect(app.closedSwarms, hasLength(12));+ expect(app.allPanes, isEmpty);+ },+ );++ testWidgets('Cmd-Shift-T restores the last removed agent', (tester) async {+ final app = createApp();+ app.adoptSessionForTest(terminal('a0', []));+ final origin = app.activeSwarm;+ await mount(tester, app);+ await app.closePane(app.focusedPaneId!);+ await tester.pump();+ await chord(tester, LogicalKeyboardKey.keyT, shift: true);+ expect(app.activeSwarm, same(origin));+ expect(app.panes.single.agentId, 'a0');+ expect(app.closedHistory, isEmpty);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+}diff --git a/desktop/test/swarm_history_test.dart b/desktop/test/swarm_history_test.dartindex 86e335680..e212a8af6 100644--- a/desktop/test/swarm_history_test.dart+++ b/desktop/test/swarm_history_test.dart@@ -16,6 +16,73 @@ import 'swarm_state_test.dart' show createApp;import 'swarm_switcher_test.dart' show jumpField;void main() {+ testWidgets(+ 'native History restores closed agents and sends their engine icons',+ (tester) async {+ const channel = MethodChannel('harness/swarm_tabs');+ final messenger = tester.binding.defaultBinaryMessenger;+ final updates = <Map>[];+ messenger.setMockMethodCallHandler(channel, (call) async {+ if (call.method == 'update') updates.add(call.arguments as Map);+ return true;+ });+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));+ final app = createApp();+ app.machineStates['m']!.agents = [+ const Agent(+ id: 'a0',+ name: 'Planning',+ engine: 'claude',+ terminalAvailable: true,+ ),+ ];+ final pane = app.adoptSessionForTest(terminal('a0', []));+ final origin = app.activeSwarm;+ final projects = SwarmProjectStore();+ await tester.pumpWidget(+ MaterialApp(+ home: SwarmScreen(+ notifier: app,+ nativeTabs: true,+ projectStore: projects,+ ),+ ),+ );+ await tester.pump();+ final recent = (updates.last['history'] as List).cast<Map>().first;+ expect(recent['engine'], 'claude');+ await app.closePane(pane.id);+ await tester.pump();+ final closed = (updates.last['closedHistory'] as List).cast<Map>().single;+ expect(closed['swarm'], isFalse);+ expect(closed['engine'], 'claude');+ expect(closed['title'], 'Planning');+ expect(closed['canReopen'], isTrue);+ final reply = Completer<void>();+ messenger.handlePlatformMessage(+ channel.name,+ const StandardMethodCodec().encodeMethodCall(+ MethodCall('reopenHistory', {'id': closed['id']}),+ ),+ (_) => reply.complete(),+ );+ await reply.future;+ await tester.pump();+ expect(app.activeSwarm, same(origin));+ expect(app.panes.single.agentId, 'a0');+ expect(app.closedHistory, isEmpty);+ await app.closeSwarm(origin.id);+ await tester.pump();+ expect(+ (updates.last['closedHistory'] as List).cast<Map>().single['swarm'],+ isTrue,+ );+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ projects.dispose();+ },+ );+test('Back and Forward retain exact pane locations and discard a branched future', () async {final app = createApp();addTearDown(app.dispose);@@ -159,6 +226,8 @@ void main() {(row) => row['id'] == id,);expect(row['title'], 'Agent 0 — Test host');+ expect(row['engine'], 'codex');+ expect(row['iconAsset'], 'assets/engine-icons/codex.png');final before = updates.length;for (var i = 0; i < 20; i++) {app.dismissError();diff --git a/desktop/test/swarm_navigation_test.dart b/desktop/test/swarm_navigation_test.dartindex ed6a0250e..96e32def5 100644--- a/desktop/test/swarm_navigation_test.dart+++ b/desktop/test/swarm_navigation_test.dart@@ -7,6 +7,70 @@ import 'swarm_screen_test.dart' show terminal;import 'swarm_state_test.dart' show createApp;void main() {+ test('search prioritizes title matches without losing better metadata matches', () {+ SwarmDestination row(String id, String title, List<String?> fields) =>+ SwarmDestination(+ id: id,+ title: title,+ detail: '',+ swarmId: null,+ current: false,+ searchFields: fields,+ );+ final catalog = [+ row('metadata-fuzzy', 'Payments', ['a_u_t_h']),+ row('title-fuzzy', 'a_u_t_h', []),+ row('metadata-substring', 'Billing', ['my auth project']),+ row('metadata-prefix', 'Checkout', ['auth service']),+ // A later exact metadata field must still beat the fuzzy title and+ // earlier prefix metadata. Repeated and empty context cannot alter rank.+ row('metadata-exact', 'a useful thing here', [+ 'auth service',+ '',+ null,+ 'AUTH',+ 'auth',+ 'a useful thing here',+ ]),+ row('title-substring', 'Fix auth', ['Auth']),+ row('title-prefix', 'Auth server', ['Auth']),+ row('title-exact', 'Auth', ['auth service']),+ ];+ expect(rankSwarmDestinations(catalog, 'AUTH').map((e) => e.id), [+ 'title-exact',+ 'title-prefix',+ 'title-substring',+ 'metadata-exact',+ 'metadata-prefix',+ 'metadata-substring',+ 'title-fuzzy',+ 'metadata-fuzzy',+ ]);+ });++ test('search keeps Unicode subsequences and separate field boundaries', () {+ final catalog = [+ SwarmDestination(+ id: 'unicode',+ title: '🧑💻 Auth 東京',+ detail: '',+ swarmId: null,+ current: false,+ searchFields: ['Mac mini', '東京', 'MAC MINI', '', null],+ ),+ ];+ for (final query in [+ '🧑💻 ath',+ '東 mac',+ ' 東京\tAUTH ',+ '🧑💻 auth 東京',+ ]) {+ expect(rankSwarmDestinations(catalog, query).single.id, 'unicode');+ }+ expect(rankSwarmDestinations(catalog, '東京mac'), isEmpty);+ expect(rankSwarmDestinations(catalog, '京東'), isEmpty);+ });+test('search matches project, branch, folder and machine in either word order',() {diff --git a/desktop/test/swarm_reopen_test.dart b/desktop/test/swarm_reopen_test.dartindex b50c72ad4..2705248d1 100644--- a/desktop/test/swarm_reopen_test.dart+++ b/desktop/test/swarm_reopen_test.dart@@ -11,7 +11,7 @@ import 'package:harness/state/pane_preset.dart';import 'package:harness/terminal/terminal_session.dart';import 'swarm_interactions_test.dart' show chord;-import 'swarm_screen_test.dart' show mount;+import 'swarm_screen_test.dart' show mount, terminal;import 'swarm_state_test.dart' show createApp, MemoryStore;class _NoopLogin extends CliLogin {@@ -23,7 +23,7 @@ class _NoopLogin extends CliLogin {}void main() {- test('recently closed swarms do not survive sign-out', () async {+ test('recently closed agents and swarms do not survive sign-out', () async {final login = _NoopLogin();final app = AppNotifier(config: AppConfig.dev,@@ -33,11 +33,16 @@ void main() {);addTearDown(app.dispose);app.renameSwarm(app.activeSwarmId, 'Private work');+ final pane = app.adoptSessionForTest(terminal('private', []));+ await app.closePane(pane.id);await app.closeSwarm(app.activeSwarmId);+ expect(app.closedHistory, hasLength(2));expect(app.canReopenClosedSwarm, isTrue);await app.logout();expect(login.logoutCalls, 1);expect(app.canReopenClosedSwarm, isFalse);+ expect(app.closedHistory, isEmpty);+ expect(app.reopenClosed(), isFalse);app.reopenClosedSwarm();expect(app.swarms.every((s) => s.name != 'Private work'), isTrue);});diff --git a/desktop/tool/check_swarm_titlebar.sh b/desktop/tool/check_swarm_titlebar.shindex 429b7f7f8..8d1c046a2 100644--- a/desktop/tool/check_swarm_titlebar.sh+++ b/desktop/tool/check_swarm_titlebar.sh@@ -24,4 +24,4 @@ xcrun swiftc -swift-version 5 -module-cache-path "$check_dir/module-cache" \"$check_dir/main.swift" -o "$check_dir/check-titlebar"# Optional native-container checks create a hidden NSWindow. They never show# the window, boot Flutter, connect to agents or read saved app data.-"$check_dir/check-titlebar" "${2:-}"+HARNESS_TITLEBAR_ASSETS="$desktop_dir/assets" "$check_dir/check-titlebar" "${2:-}"diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex 012815520..2ea497647 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -211,13 +211,13 @@ private extension SwarmTitlebar {configure()try checkTitlebar(window.firstResponder === window.contentViewController,"Adding the search field does not take initial keyboard focus from the workspace")- try checkTitlebar(main.items.map(\.title) == ["Harness V2", "File", "Edit", "View", "History", "Swarm", "Window", "Help"], "Menus follow the familiar macOS order")+ try checkTitlebar(main.items.map(\.title) == ["Harness V2", "File", "Edit", "View", "History", "Models", "Window", "Help"], "Models replaces the redundant Swarm menu")let settings = appItem.submenu!.items[0]try checkTitlebar(settings.title == "Settings…" && settings.representedObject as? String == "settings", "Settings stays in the application menu")let file = main.item(withTitle: "File")!.submenu!let historyMenu = main.item(withTitle: "History")!.submenu!- try checkTitlebar(file.items.compactMap { $0.representedObject as? String } == ["new", "newAgent", "reopen", "linkMachine", "addProject", "closePane", "closeActive"], "File exposes creation, connection and view-closing actions")- let jump = main.item(withTitle: "Swarm")!.submenu!.items.first(where: { $0.representedObject as? String == "jump" })!+ try checkTitlebar(file.items.compactMap { $0.representedObject as? String } == ["new", "newAgent", "reopen", "linkMachine", "addProject", "renameActive", "closePane", "closeActive"], "File exposes creation, connection, renaming and closing actions")+ let jump = edit.submenu!.items.first(where: { $0.representedObject as? String == "jump" })!try checkTitlebar(jump.keyEquivalent == "p" && jump.keyEquivalentModifierMask == [.command], "Command-P has a native menu owner while a terminal has focus")let reopen = file.items.first(where: { $0.representedObject as? String == "reopen" })!actionsEnabled = true@@ -236,10 +236,10 @@ private extension SwarmTitlebar {canCreateSwarm = truetry checkTitlebar(validateMenuItem(create), "Native New Swarm returns below capacity")let recentRows: [[String: Any]] = (0..<20).map {- ["id": "agent:\($0)", "title": "Agent \($0) — Machine", "detail": "Project \($0)", "current": $0 == 0]+ ["id": "agent:\($0)", "title": "Agent \($0) — Machine", "detail": "Project \($0)", "current": $0 == 0, "engine": $0 == 0 ? "claude" : "codex"]} + [["id": "swarm:recent", "title": "Recent Swarm", "swarm": true]]let closedRows: [[String: Any]] = (0..<14).map {- ["id": "closed-\($0)", "title": "Closed Swarm \($0)", "detail": "3 agents", "swarm": true]+ ["id": "closed-\($0)", "title": "Closed Swarm \($0)", "detail": "3 agents", "swarm": true, "canReopen": true]}updateHistory(recentRows, closed: closedRows)let recentItems = historyMenu.items.filter { $0.action == #selector(historyAction(_:)) }@@ -250,12 +250,19 @@ private extension SwarmTitlebar {try checkTitlebar(historyMenu.items.allSatisfy { $0.submenu == nil }, "Recent work is available without nested menus")let recent = recentItems[0]let closed = closedItems[0]+ try checkTitlebar(recent.image?.size == NSSize(width: 16, height: 16) && recent.image?.isTemplate == false,+ "History uses the colored Claude mark at native menu size")try checkTitlebar(recent.state == .on && recent.toolTip == "Agent 0 — Machine\nProject 0", "Recent work includes its complete title and project context")updateHistory(recentRows, closed: closedRows)try checkTitlebar(historyMenu.items.contains(where: { $0 === recent }), "Unchanged history retains native menu items")try checkTitlebar(validateMenuItem(closed), "A specific closed Swarm can be restored")canReopen = false- try checkTitlebar(!validateMenuItem(closed), "Specific restore respects the open-tab capacity")+ try checkTitlebar(validateMenuItem(closed), "A chosen closure uses its own capacity, independently of the latest closure")+ var unavailableRows = closedRows+ unavailableRows[0]["canReopen"] = false+ updateHistory(recentRows, closed: unavailableRows)+ try checkTitlebar(!validateMenuItem(closed), "Specific restore respects its destination capacity")+ updateHistory(recentRows, closed: closedRows)canReopen = truelet back = historyMenu.items[0]let forward = historyMenu.items[1]@@ -273,9 +280,9 @@ private extension SwarmTitlebar {try checkTitlebar(!validateMenuItem(recent), "A stale recent menu item cannot dispatch after its view disappears")try checkTitlebar(!validateMenuItem(closed), "A stale closed entry cannot restore another Swarm")try checkTitlebar(historyMenu.items.first(where: { $0.title == "No Recent Visits" })?.isEnabled == false, "An empty history is an inert placeholder")- guard let menu = main.items.first(where: { $0.title == "Swarm" })?.submenu,+ guard let menu = main.items.first(where: { $0.title == "View" })?.submenu,let attention = menu.items.first(where: { $0.representedObject as? String == "notifications" }) else {- throw TitlebarCheckFailure(message: "Swarm menu exposes agents needing input")+ throw TitlebarCheckFailure(message: "View menu exposes agents needing input")}try checkTitlebar(attention.title == "Agents Needing Input…", "Native command names its destination")try checkTitlebar(attention.keyEquivalent == "i" && attention.keyEquivalentModifierMask == [.command, .shift], "Native attention shortcut matches Flutter")@@ -284,6 +291,46 @@ private extension SwarmTitlebar {try checkTitlebar(!validateMenuItem(attention), "Native attention shortcut is disabled behind a modal")actionsEnabled = truetry checkTitlebar(validateMenuItem(attention), "Native attention shortcut returns when the modal closes")+ try checkTitlebar(main.items.compactMap(\.submenu).flatMap(\.items).allSatisfy {+ !["Next Swarm", "Previous Swarm"].contains($0.title)+ }, "Next and Previous Swarm have no redundant menu rows")+ let modelRows: [[String: Any]] = [+ ["title": "Anthropic", "status": "12% remaining", "engine": "claude",+ "details": ["Limiting window: Session", "Session — 12% remaining · resets in 2h"]],+ ["title": "OpenAI", "status": "Not signed in", "engine": "codex",+ "details": ["Sign in to Codex to see usage"]],+ ]+ updateModels(modelRows)+ let models = main.item(withTitle: "Models")!.submenu!+ try checkTitlebar(models.items.filter { !$0.isSeparatorItem }.map(\.title) == [+ "Subscription", "Anthropic — 12% remaining", "OpenAI — Not signed in",+ "API", "OpenRouter API", "fal.ai API", "Local", "Local models", "Add Model"+ ], "Models has the three requested sections and Add Model last")+ try checkTitlebar(models.items.filter(\.isSeparatorItem).count == 3,+ "Native separators distinguish the sections and future Add Model action")+ for title in ["OpenRouter API", "fal.ai API", "Local models", "Add Model"] {+ let item = models.item(withTitle: title)!+ try checkTitlebar(!item.isEnabled && item.action == nil && item.target == nil && item.submenu == nil,+ "\(title) is greyed out and cannot dispatch or open anything")+ }+ let subscription = models.items.first(where: { $0.submenu != nil })!+ try checkTitlebar(subscription.isEnabled && subscription.image?.isTemplate == false,+ "Subscription rows have colored provider marks and accessible details")+ try checkTitlebar(subscription.submenu?.items.last?.title == modelRows[0]["details"].flatMap { ($0 as? [String])?.last },+ "The native submenu exposes the measured window and reset time")+ updateModels(modelRows)+ try checkTitlebar(models.items.contains(where: { $0 === subscription }),+ "Unchanged subscription data reuses native menu items")+ actionsEnabled = false+ updateModelsAvailability()+ try checkTitlebar(!subscription.isEnabled, "Subscription details respect a covered workspace")+ actionsEnabled = true+ updateModelsAvailability()+ try checkTitlebar(subscription.isEnabled && models.item(withTitle: "Add Model")?.isEnabled == false,+ "Only implemented subscription details become available again")+ updateModels([])+ try checkTitlebar(models.items.allSatisfy { !$0.title.contains("12%") && $0.submenu == nil },+ "Signing out clears cached native account readings")let findItems = find.submenu?.items ?? []try checkTitlebar(findItems.map(\.title) == ["Find in Terminal…", "Find Next", "Find Previous"], "Find replaces the unused editor actions with terminal commands")try checkTitlebar(findItems.map(\.keyEquivalent) == ["f", "g", "g"], "Native find shortcuts match Flutter")@@ -323,6 +370,21 @@ let titlebarCheckApp = NSApplication.sharedtitlebarCheckApp.setActivationPolicy(.prohibited)titlebarCheckApp.appearance = NSAppearance(named: .darkAqua)do {+ var assetReads = 0+ let icons = SwarmHistoryIcons(assetURL: { asset in+ assetReads += 1+ guard let root = ProcessInfo.processInfo.environment["HARNESS_TITLEBAR_ASSETS"] else { return nil }+ return URL(fileURLWithPath: root).appendingPathComponent(String(asset.dropFirst("assets/".count)))+ })+ for engine in ["codex", "grok", "cursor", "opencode"] {+ let asset = "assets/engine-icons/\(engine).png"+ let icon = icons.image(engine: engine, asset: asset)+ try checkTitlebar(icon.size == NSSize(width: 16, height: 16) && !icon.isTemplate, "\(engine) uses its colored bundled mark")+ try checkTitlebar(icons.image(engine: engine, asset: asset) === icon, "Repeated \(engine) history reuses its decoded icon")+ }+ try checkTitlebar(assetReads == 4, "Native history loads each bundled mark only once")+ let unknown = icons.image(engine: "custom", asset: nil)+ try checkTitlebar(unknown.isTemplate && unknown.size == NSSize(width: 16, height: 16), "Unknown engines have a native-size adaptive initial")let strip = SwarmTabStrip(frame: NSRect(x: 0, y: 0, width: 900, height: 40))try strip.runChecks()try checkTitlebar(titlebarCheckApp.windows.isEmpty, "Checks never open an application window")diff --git a/docs/harness-v2-developer-tools-research.md b/docs/harness-v2-developer-tools-research.mdindex 13a0fca57..e36ffb825 100644--- a/docs/harness-v2-developer-tools-research.md+++ b/docs/harness-v2-developer-tools-research.md@@ -15,9 +15,11 @@ Updated 2026-09-13. This is the working list; [the progress log](harness-v2-prog| In the preview | Real machine/project data; native Swarm tabs; wallpaper only in New swarm; Cmd+P jump, Needs input and terminal Find. || Fixed and rebuilt | Cmd+P stale focus/offscreen targets; retained offline output and composer drafts; blocking frozen overlays removed. || In the rebuilt preview | Settings gear removed on macOS; native File/History menus and Cmd+P routing. Menus and picker typing verified live; focus/input regression tests pass. |-| Rebuilt and reviewed live | Chrome-style Back/Forward, Recently Closed/Visited and full session History; compact branch-aware headers; Workshop now includes its requested iMac Home agent. |+| Rebuilt; native menu reviewed live | Models replaces Swarm; Subscription shows existing account limits, while API, Local and Add Model are disabled placeholders. History uses provider icons and restores both closed agents and closed Swarms. Recovery is covered with isolated sessions; live agents were not closed to test it. |+| Rebuilt and reviewed live | Chrome-style Back/Forward, Recently Closed/Visited and full session History; compact branch-aware headers; Workshop includes its requested iMac Home agent. || In the rebuilt preview; regression verified | Preserve the session, terminal view, Find, viewport, selection and draft context through reconnect/keyframe replacement. Stale output/input/upload completions cannot affect the replacement stream. A real remote interruption remains to be validated. |-| Rebuilt; live search/project review passed | One top-right Cmd-P search for agents, Swarms, machines and projects, with Focus/Open and explicit Add here actions; machine/project browsing and explicit group opening. Separate Add picker, floating pane + and titlebar bell removed. New swarm uses only the selected mountain/lake wallpaper; rotation and other assets removed. A group-click focus correction passes isolated tests; its final native Escape check is pending because the user resumed using the preview. |+| Rebuilt; live search/project review passed | One top-right Cmd-P search for agents, Swarms, machines and projects, with Focus/Open and explicit Add here actions; machine/project browsing and explicit group opening. Separate Add picker, floating pane + and titlebar bell removed. New swarm uses only the selected mountain/lake wallpaper; rotation and other assets removed. Native typing, Cmd-P select-all and Escape were verified from an existing empty New swarm after the focus correction. |+| Implemented; measured in isolation | Unified search construction and ranking avoid repeated scans/metadata work. Median catalog construction fell 50% in the 2,059-destination debug fixture; native input-to-display measurement remains separate. || In progress | [Audit all shortcuts and implement a coherent terminal-friendly key system with file-first remapping](harness-v2-keyboard-system.md). Config parser/resolver and live reload core pass isolated tests. Apart from the unified search change, new defaults remain proposed until dispatch, native menus and help are integrated and verified. || Calibration in progress; foreground runs paused | Native Release input/navigation fixture with synthetic terminals. No validated latency result yet; resume after the keyboard work stabilizes. Live keyboard/tab/drag and real remote interruption checks remain. || Next small addition | Optional cached preview and match highlighting in the existing Cmd+P picker. [The six-prototype review](harness-v2-prototype-review.md) records what to borrow and what stays out. |@@ -65,17 +67,17 @@ The opportunity for Harness is to make movement among real agents across real ma| --- | --- | --- || **Keep and finish** | Native Swarm tabs, terminal panes, directional focus, zoom, last-pane and close/reopen | These already support a small working set. Finish native alignment, overflow, accessibility and measured interaction latency. || **Keep and harden** | Shared terminal controllers, saved membership, reconnect and local/remote discovery | This is the foundation. Preserve input ownership, scrollback and chosen arrangements through interruption. Validate remote failures on real linked machines; do not infer that a disconnected agent stopped. |-| **Implemented; verify in daily use** | `Cmd+P` jumps to agents and Swarms; `Cmd+Shift+F` opens **Add agent** | Fuzzy search covers name/project/branch/folder/machine context, with recent destinations and shared-view reuse. Existing-view navigation preserves focus/layout and terminal ownership without retrying a stream. No dialog fade or backdrop blur. Unopened agents explicitly offer **Open view** in the captured Swarm. |+| **Implemented; verify in daily use** | One `Cmd+P` search for agents, Swarms, machines and projects | Fuzzy search covers name/project/branch/folder/machine context, with recent destinations and shared-terminal reuse. Enter focuses/opens work; explicit Add here adds it to the captured Swarm. The separate `Cmd+Shift+F` picker is removed. Navigation preserves focus/layout and terminal ownership without retrying a stream. No dialog fade or backdrop blur. || **Implemented; verify in daily use** | **Needs input** replaces the notifications list; `Cmd+Shift+I` opens it | Search live questions and agent/project/machine context; jump without changing ownership or chosen membership. `Cmd+P`, Return goes back to prior work. Resolved/replaced questions cannot trigger stale navigation. Unavailable terminals remain explicit. Opens on request with no fade, blur or polling. || **Implemented; verify in daily use** | Terminal Find with `Cmd+F`, `Cmd+G` and `Cmd+Shift+G` | Search retained output and move between literal matches without sending input. Escape restores the previous scroll position and prompt focus. The compact field uses the existing header, then disappears. These familiar bindings are documented by [Apple Terminal](https://support.apple.com/en-euro/guide/terminal/trmlshtcts/mac) and [Chrome](https://support.google.com/chrome/answer/157179?co=GENIE.Platform%3DDesktop&hl=en). Retained offline panes now remain searchable; never-attached panes retain setup guidance. || **Removed blocking chrome** | Full-pane frozen and reconnect overlays | Read-only status and explicit Reconnect/Take control actions live in the header. Retained output, selection, search and unsent composer text survive unavailable-machine presentation. Ordinary tab navigation never retries a dead stream. || **Preserve compatibility** | Real agent terminals and user shell environments | Verify selection, multiline/image paste, scrollback, nested tmux/Vim and escape/control keys. Before promising a full terminal replacement, verify a straightforward ordinary-shell workflow too; the current New agent UI centers on detected agent engines. || **Remove from active work — implemented** | Wallpaper behind populated Swarms | Use `#463746`, matching the selected native tab. Wallpaper fills only an empty New swarm canvas and its decoded cache entry is evicted when that view is disposed. |-| **In the rebuilt preview** | Chrome-style History; redundant Settings gear removed | Settings stays in the macOS app menu with `Cmd+,`. File groups creation, linking, closing and Reopen Closed Swarm. History exposes Back/Forward, Recently Closed, Recently Visited and Show Full History (`Cmd+Y`). Cmd+P stays in Swarm. Lists are bounded and session-local; stale destinations cannot become unintended new views. The non-macOS toolbar retains Settings access. |-| **In the rebuilt preview** | “Next wallpaper” button and repeated metadata | The permanent wallpaper button is removed; use native View or the New swarm context menu. Headers show one agent title, available branch, machine and controls. Repeated project-name text is removed; full folder/branch context remains on demand. Narrow panes use a machine icon with its full-name tooltip. |+| **In the rebuilt preview** | Chrome-style History, Models menu and Settings in the app menu | Settings stays in the macOS app menu with `Cmd+,`. File groups creation, linking, renaming, closing and Reopen Last Closed. History includes closed agents and Swarms, with provider icons for agents. Cmd+P lives in Edit, Needs Input in View. Models has live Subscription usage and explicitly disabled API/Local/Add Model placeholders. Lists are bounded and session-local. The non-macOS toolbar retains Settings access. |+| **In the rebuilt preview** | Wallpaper rotation and repeated metadata removed | The selected mountain/lake image is the only wallpaper; rotation button, menu actions and other assets are removed. Headers show one agent title, available branch, machine and controls. Repeated project-name text is removed; full folder/branch context remains on demand. Narrow panes use a machine icon with its full-name tooltip. || **Removed avoidable waiting** | Settings route transitions and section cross-fades | Implemented: Settings now opens/closes and switches sections immediately. Removed the 170/120 ms route and 200/90 ms section fades; existing route/modal checks pass. Reserve animation for feedback that helps understanding. || **Keep optional; stop expanding** | Usage ledger and hardware/dial settings | Usage can answer a real cost question; hardware supports existing users. Keep these away from the main work loop. Do not delete capabilities or data merely because they were absent from this small research sample. |-| **Keep absent** | Models/Grid dashboard, permanent workspace sidebar, pane footers | The authenticated V2 shell already removed these. Avoid introducing equivalent clutter through new agent-management panels. |+| **Keep absent** | Grid dashboard, permanent workspace sidebar, pane footers | The authenticated V2 shell already removed these. The user now explicitly requested a compact Models menu; this does not authorize restoring the Grid dashboard or model setup flows. API, Local and Add Model remain disabled by request. || **Defer** | Workflow canvases, autonomous manager-of-managers, social features, a plugin marketplace, a full IDE or a new Git client | None is required to prove the first three promises. Add only after repeated daily-use evidence identifies a concrete need. |Source inspection: `desktop/lib/screens/swarm_screen.dart`, `widgets/swarm_dialogs.dart`, `state/swarm_catalog.dart`, `shortcuts/app_shortcuts.dart`, `settings/settings_screen.dart`, `settings/settings_section.dart`, `widgets/new_agent_dialog.dart`, and `macos/Runner/SwarmTitlebar.swift`. Existing checks and implementation details are recorded in [the handoff](harness-v2-progress.md) and [performance notes](harness-v2-performance.md).@@ -84,7 +86,7 @@ Source inspection: `desktop/lib/screens/swarm_screen.dart`, `widgets/swarm_dialoApple's [native menu documentation](https://developer.apple.com/documentation/swiftui/building-and-customizing-the-menu-bar-with-swiftui) shows File handling New Message, Close and opening a conversation in a window. File represents creating/opening/closing the app's work, beyond documents on disk. For Harness, the corresponding work is a Swarm or agent view. Keep Edit's standard text actions, View's layout/font controls, and the system Window menu.-Chrome is the user's primary interaction reference. Chromium's [menu definition](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/ui/cocoa/main_menu_builder.mm) and [History bridge](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/ui/cocoa/history_menu_bridge.mm) inform Back/Forward, direct Recently Closed/Recently Visited sections, and Show Full History. Harness shows up to 10 closed Swarms and 15 recent destinations there. Navigation retains at most 64 recent identities, a 128-entry exact-pane Back/Forward trail, and the existing 24-close recovery list. Show Full History searches those recoverable destinations and explicitly says **This session**. History does not persist across app exit or collect terminal commands, prompts or output. These bounded session records are not a durable all-time browser history.+Chrome is the user's primary interaction reference. Chromium's [menu definition](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/ui/cocoa/main_menu_builder.mm) and [History bridge](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/ui/cocoa/history_menu_bridge.mm) inform Back/Forward, direct Recently Closed/Recently Visited sections, and Show Full History. Harness shows up to 10 closed agents or Swarms and 15 recent destinations there. Navigation retains at most 64 recent identities, a 128-entry exact-pane Back/Forward trail, and a combined 24-close recovery list. Show Full History searches those recoverable destinations and explicitly says **This session**. History does not persist across app exit or collect terminal commands, prompts or output. These bounded session records are not a durable all-time browser history.## Reductions and prototype follow-updiff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.mdindex 66be7b6b4..0fd3602cb 100644--- a/docs/harness-v2-performance.md+++ b/docs/harness-v2-performance.md@@ -10,6 +10,54 @@ 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.+## Unified search catalog and typing (2026-09-13)++The catalog benchmark now also exercises the production `SwarmSearchController`:+2,000 agents across eight machines and 50 projects, producing 2,059 searchable+destinations. It measures opening/disposing the controller, changing queries,+and searching inside one machine. Each operation uses 20 warmups and 100 samples;+resetting the query happens outside the measured interval. No widgets, sockets,+real agents, disk discovery, native field editor or display are involved.++Catalog construction now indexes machine membership and agent identities once,+instead of scanning all destinations again for every machine and project.+Aggregate project/Swarm metadata excludes repeated fields. Building an unfiltered+agent list no longer formats searchable text for every agent. Ranking stops+checking metadata after a title match that already outranks it, while continuing+past fuzzy title matches that better metadata can outrank. Exact whole-title+matches retain their first-place priority; recency and deterministic ties remain.++Sequential headless debug measurements on the same workstation:++| Operation | Before median / p95 / p99 (ms) | After median / p95 / p99 (ms) |+| --- | ---: | ---: |+| Build unified catalog | 6.776 / 7.482 / 7.810 | 3.405 / 3.846 / 4.238 |+| Open and dispose search controller | 8.212 / 9.121 / 9.469 | 4.637 / 4.980 / 5.357 |+| Query `agent` | 1.696 / 1.854 / 1.904 | 1.067 / 1.160 / 1.302 |+| Query `agent 12 machine 3` | 1.425 / 1.621 / 1.655 | 0.743 / 0.856 / 0.912 |+| Fuzzy query `agn12` | 0.915 / 1.068 / 1.141 | 0.676 / 0.789 / 0.866 |+| Query `project 12 main` | 1.525 / 1.659 / 1.746 | 1.019 / 1.204 / 1.332 |+| Query with no matches | 0.638 / 0.786 / 0.804 | 0.446 / 0.608 / 0.685 |+| Fuzzy query inside one machine | 0.115 / 0.135 / 0.171 | 0.122 / 0.147 / 0.260 |++Median catalog construction fell by 50%, and the controller open/dispose cycle+by 44%. Result counts stayed identical for every measured query. The scoped query+did not improve; its unchanged filtering path and higher tail observation are+retained here. Welcome text filtering was also effectively unchanged (median+1.210 → 1.217 ms), while project grouping fell from 1.457 to 0.615 ms by avoiding+unused search strings. An unchanged catalog still reuses the same snapshot.++These are shared-workstation debug CPU observations, not native keystroke or+physical-display latency. Host load and JIT affect them; 100 samples provide only+a limited tail estimate. This change makes no tab-switch latency claim. The+baseline and final logs are `/private/tmp/harness-v2-search-perf-before.log` and+`/private/tmp/harness-v2-search-perf-final.log`; the intermediate measurement is+preserved in `/private/tmp/harness-v2-search-perf-after.log`.++```bash+flutter test --no-pub --concurrency=1 --reporter expanded test/benchmarks/swarm_benchmark.dart --plain-name 'large live catalog CPU benchmark'+```+## Recorded measurements| Operation | Earlier median / p95 | After native/canvas polish median / p95 |diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdindex ccfa77bcf..535812430 100644--- a/docs/harness-v2-progress.md+++ b/docs/harness-v2-progress.md@@ -1,17 +1,30 @@# Harness App V2 — development handoff-Updated 2026-09-13 after polishing the editable search bar and making Swarm terminology consistent. This is a working preview, not a release.+Updated 2026-09-13 with Models, combined closed-work History and faster unified search. This is a working preview, not a release.-## Current continuation: search polish and agent terminology+## Current continuation: Models, closed agents and search performance-- **Menu organization is discussion only.** The user asked to study Terminal/iTerm2 and explicitly requested no menu-bar changes yet. Discussed replacing File with Swarm, putting focused-session actions under Agent, retaining Edit/View/Window/Help and keeping Models/Machines/Projects out of separate menus for now. No proposed reorganization is approved or implemented. The agent-removal wording below was already in the preview before this instruction.+- **Latest scope:** the user authorized replacing the redundant Swarm menu with Models. Models has Subscription, API and Local sections, then Add Model. Subsequent instructions explicitly make **API, Local and Add Model disabled placeholders**. No provider connection, key entry, local discovery, download or benchmark runs from those placeholders.+- Subscription reads the existing Claude/OpenAI usage sources and grouped remote accounts on demand. A native cached menu opens immediately; requests coalesce and are limited to one refresh per minute, with no startup or background polling. Rows show remaining allowance for the most constrained reported window, with individual windows/reset times in a native submenu. Unknown, failed, expired and non-finite readings never become invented percentages. Distinct remote accounts retain machine context; account identifiers/credentials are not sent to AppKit.+- Search retains its native Cmd-P owner in Edit; Rename Swarm moves to File; Needs Input moves to View. Next/Previous Swarm menu rows are removed; the existing keyboard bindings remain. API shows disabled OpenRouter API and fal.ai API rows; Local has a disabled Local models row; Add Model has no action or shortcut.+- History now uses provider artwork for agent entries, including Claude's orange mark. PNG assets decode once to bounded native-menu thumbnails and are cached. Recently Closed records both individual agent removals and complete Swarm closures in one chronological, session-local list of at most 24. Closing a Swarm makes one group record, not additional child records. Cmd-Shift-T and File > Reopen Last Closed restore whichever kind was closed most recently.+- Agent restoration reuses a surviving shared terminal or reattaches the existing agent, restores its original Swarm/index/pin/focus where possible, handles missing parent Swarms and capacity, and rejects stale entries. Closure records retain metadata only, not terminal buffers. New synthetic regressions cover slow close/reopen, duplicate prevention, live composer preservation, full destinations, mixed history and sign-out cleanup. No live agents were closed to test recovery.+- Unified catalog construction now indexes membership once, avoids unused agent search strings and deduplicates aggregate metadata. Ranking stops at a decisive title match without hiding better metadata behind a fuzzy title. The paired 2,059-destination headless benchmark reduced median catalog construction 50% and controller open/dispose 44%; scoped search did not improve. See [performance evidence and limits](harness-v2-performance.md). No native display-latency claim is made.+- Checks: **1,106 full-suite tests passed with one existing skip**, plus 281 AppKit checks including hidden native window/menu checks. The 63 focused Flutter regressions also passed. Analyzer has no errors or warnings and the same 12 vendored infos. Logs use `/private/tmp/harness-v2-models-{tests,native,analyze,full-tests}.log`.+- Release build succeeded with `lib/main.dart` (`/private/tmp/harness-v2-models-build.log`). Normally quit PID 55560, rebuilt and launched one preview, **PID 511** at the last process check. Revalidate before a later restart. Live CUA verified the new menu order, local and distinct remote subscription readings, unavailable-auth state, disabled API/Local/Add Model items, History's agent entries and combined empty-closure wording. Menu screenshots were unavailable from the automation surface; native AppKit icon/section checks and the real window screenshot provide the visual evidence available. A first observation used an inactive window; after bringing it forward, cached readings and pane contents were current. Cmd-P and Escape were verified from the existing empty New swarm. Returned to that same New swarm with all five Swarms and their memberships intact; no agent was created, stopped or closed for testing.+- The user is away for approximately eight hours from 2026-09-13 14:45 UTC. Continue with the existing goal: a fast, dependable terminal workspace for directing agents across machines. Priorities after this batch: complete cohesive keyboard dispatch/file remapping/native menus/help; measure interaction and idle/background performance; improve search match visibility and focus reliability. Use isolated sessions for input testing. Keep this log and the [implementation queue](harness-v2-developer-tools-research.md) current.+- Keyboard wiring is preserved in `/private/tmp/harness-v2-keyboard-wiring-20260913-search-polish.patch`, SHA-256 `ef2841a963c4392abc612dba186c12ee2c3c05b3cfe87ad06c4ea21d580a6466`. **It must be rebased against the current combined-history handlers and Models additions before use.** It no longer passes `git apply --check`; never overwrite current work with it. The parser/dispatch foundation is committed, but runtime integration remains incomplete.++## Previous continuation: search polish and agent terminology++- At this stage the user had frozen menu reorganization for discussion. The later Models authorization above supersedes that pause; broader menu/dashboard expansion remains outside the agreed scope.- The native search bar now uses the same 13-point text size as the tabs, a 32-point field, balanced icon/text insets, and a quiet one-point inactive rim. The blue focus ring is removed. While searching, the field has rounded top corners and extends into the attached results on one matching `#3d333f` surface; the gap, separate top border and rounded top corners of the result panel are removed. The Flutter fallback follows the same sizing and connected layout. No animation, blur or additional search work was introduced.- The actual AppKit editor keeps the same text inset as the inactive field. Isolated renders covered inactive, focused, typed and resized long-query states. The first render caught a borderless native editor placing text at the upper-left corner; the cell's editing and selection rectangles now preserve the intended padding.- User-facing Swarm counts now say **0 agents / 1 agent / N agents**, including recently closed History entries. Setup panes without an agent are excluded. Search and Needs Input say **Open agent**, and File/shortcut help say **Remove Agent from Swarm**. Internal view/session names remain implementation details.- **69 focused Flutter tests and 255 AppKit checks passed**. The native regression reproduced search cancellation on window blur before the fix and now confirms query/input ownership survives app switching. Initial native window focus stays in the workspace. Search and History tests were rerun after the focus fix. Analyzer has no errors or warnings and the same 12 existing vendored infos. Release build succeeded with `lib/main.dart`. Logs: `/private/tmp/harness-v2-search-polish-tests.log`, `harness-v2-search-polish-titlebar.log`, `harness-v2-search-polish-analyze.log`, `harness-v2-search-focus-tests.log`, `harness-v2-search-focus-build.log`.- The first live typing check exposed the window-blur path: it cancelled search, restored terminal focus and put the unsent word `workshop` in the left strategies prompt. No Return was sent. The user explicitly approved removing that word; eight Backspace events removed it, and CUA verified the prompt was clear. Search now retains its query and native input owner across app switches; Escape, explicit navigation and outside clicks still close it. **Use an existing empty New swarm or isolated fixtures for any future test typing.**- Normally relaunched one final Release preview after the correction, **PID 55560** at the last process check. Live CUA verification used the existing empty New swarm: clicking the native bar, typing `workshop`, Cmd-P select-all, replacement typing `New swarm`, and Escape all stayed in the same input and showed the correct `0 agents` result. The joined field/results surface was inspected. Returned to the previously active Focus swarm; the five Swarms and their membership are intact. Revalidate the preview PID before any later restart.-- Keyboard customization remains the next track. Dispatcher, command catalog, platform validation, inherited configuration and focus-aware host work is preserved; **31 isolated foundation tests pass**. Its incomplete screen/search wiring is parked in `/private/tmp/harness-v2-keyboard-wiring-20260913-search-polish.patch` (SHA-256 `ef2841a963c4392abc612dba186c12ee2c3c05b3cfe87ad06c4ea21d580a6466`) so the preview includes only completed changes. It passes `git apply --check` against this visual update. Native menu/remap integration, command search and dynamic shortcut help still need completion before that wiring is built or shipped. Keep menu edits paused during the user's menu discussion.+- Keyboard customization remains the next track. Dispatcher, command catalog, platform validation, inherited configuration and focus-aware host work is preserved; **31 isolated foundation tests pass**. The incomplete screen/search wiring is parked in the patch identified above. It passed `git apply --check` at this historical point; the current changes require a rebase. Native menu/remap integration, command search and dynamic shortcut help still need completion before that wiring is built or shipped.- The native latency benchmark remains paused calibration work with no accepted figures. `docs/prototypes/` and `docs/harness-collaboration-design.md` are unrelated user work; leave them alone.## Previous continuation: editable title-bar search and keyboard configuration