Skip to content

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

feat(desktop): jump to existing agents and swarms

dee63c85e9e7545
diff --git a/desktop/lib/core/fuzzy_match.dart b/desktop/lib/core/fuzzy_match.dart
new file mode 100644
index 000000000..576935a3d
--- /dev/null
+++ b/desktop/lib/core/fuzzy_match.dart
@@ -0,0 +1,14 @@
+/// The spread of a subsequence match, or null when the query does not match.
+/// Both arguments should already be normalized for case.
+int? subsequenceSpread(String text, String query) {
+ if (query.isEmpty) return 0;
+ var at = -1;
+ var first = -1;
+ for (final rune in query.runes) {
+ final found = text.indexOf(String.fromCharCode(rune), at + 1);
+ if (found < 0) return null;
+ if (first < 0) first = found;
+ at = found;
+ }
+ return at - first;
+}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 3b087ceff..7b39ec0d5 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -15,6 +15,7 @@ import '../shared/widgets/app_dialog.dart';
import '../shortcuts/app_shortcuts.dart';
import '../state/app_state.dart';
import '../state/swarm_catalog.dart';
+import '../state/swarm_navigation.dart';
import '../widgets/engine_identity.dart';
import '../widgets/layout_palette.dart';
import '../widgets/link_machine_screen.dart';
@@ -22,6 +23,7 @@ import '../widgets/new_agent_dialog.dart';
import '../widgets/pane_grid.dart';
import '../widgets/shortcuts_sheet.dart';
import '../widgets/swarm_dialogs.dart';
+import '../widgets/swarm_switcher.dart';
import '../widgets/swarm_wallpaper.dart';
import '../widgets/swarm_welcome.dart';
import '../widgets/task_palette.dart';
@@ -49,6 +51,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
SwarmProjectStore(storage: kUnderTest ? null : HarnessFileStore.shared);
StreamSubscription<SpokenTaskRequest>? _spokenTasks;
final _shellFocus = FocusNode(debugLabel: 'Swarm shell');
+ final _navigation = SwarmNavigationHistory();
bool _spokenPaletteOpen = false;
bool _dialogOpen = false;
bool _routeIsCurrent = true;
@@ -61,6 +64,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
super.initState();
app.hasNavigationRail = false;
app.railFocused = false;
+ _recordNavigation();
+ app.addListener(_recordNavigation);
FocusManager.instance.addListener(_restoreEmptyFocus);
unawaited(_projects.load());
_spokenTasks = app.spokenTasks.listen(_openSpokenTask);
@@ -82,6 +87,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
@override
void dispose() {
+ app.removeListener(_recordNavigation);
FocusManager.instance.removeListener(_restoreEmptyFocus);
_shellFocus.dispose();
unawaited(_spokenTasks?.cancel());
@@ -96,6 +102,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
super.dispose();
}
+ void _recordNavigation() => _navigation.record(app);
+
int get _attention =>
app.machineStates.values.fold(0, (n, m) => n + m.blockedAgents.length);
@@ -229,6 +237,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
swarmId: swarmId,
);
});
+ Future<void> _jump() async {
+ final target = app.activeSwarmId;
+ SwarmDestination? selected;
+ await _dialog(() async {
+ selected = await showSwarmSwitcher(context, app, _navigation);
+ });
+ if (!mounted || selected == null) return;
+ await activateSwarmDestination(app, selected!, destinationSwarmId: target);
+ }
+
Future<void> _addAgent() async {
final target = app.activeSwarmId;
bool create = false;
@@ -290,17 +308,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
Future<void> _goToAgent(String machineId, String agentId) async {
- if (app.paneOfAgent(machineId, agentId) == null) {
- final owner = app.swarms
- .where(
- (s) => s.panes.any(
- (p) => p.machineId == machineId && p.agentId == agentId,
- ),
- )
- .firstOrNull;
- if (owner != null) app.selectSwarm(owner.id);
- }
- await app.selectAgent(machineId, agentId);
+ if (app.revealAgentView(machineId, agentId)) return;
+ await app.addAgentToSwarm(machineId, agentId);
}
Future<void> _notifications() => _dialog(() async {
@@ -483,7 +492,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
ShortcutAction.previousAgent: () => app.focusPaneBy(-1),
ShortcutAction.lastPane: app.focusLastPane,
ShortcutAction.zoomPane: app.toggleZoomPane,
- ShortcutAction.switchAgent: _addAgent,
+ ShortcutAction.switchAgent: _jump,
+ ShortcutAction.addAgent: _addAgent,
ShortcutAction.closePane: () {
if (app.focusedPaneId != null) {
app.closePane(app.focusedPaneId!);
@@ -608,7 +618,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: IconButton(
tooltip: withShortcutHint(
'Add agent',
- ShortcutAction.switchAgent,
+ ShortcutAction.addAgent,
),
onPressed: _addAgent,
constraints: const BoxConstraints.tightFor(
diff --git a/desktop/lib/shared/widgets/app_dialog.dart b/desktop/lib/shared/widgets/app_dialog.dart
index cca29f521..e9faf0cfb 100644
--- a/desktop/lib/shared/widgets/app_dialog.dart
+++ b/desktop/lib/shared/widgets/app_dialog.dart
@@ -55,6 +55,7 @@ Future<T?> showAppDialog<T>({
String barrierLabel = 'Dismiss',
Color veilTint = kDialogVeilTint,
double veilBlur = kDialogVeilBlur,
+ Duration transitionDuration = const Duration(milliseconds: 140),
}) => showGeneralDialog<T>(
context: context,
// The route's own barrier draws nothing: the veil below is the barrier.
@@ -64,9 +65,7 @@ Future<T?> showAppDialog<T>({
// over a barrier it believes is there, including a tap on the dialog.
barrierDismissible: false,
barrierLabel: barrierLabel,
- // Long enough to read as a fade rather than a cut, short enough that a
- // keyboard-driven panel does not feel like it is waiting on an animation.
- transitionDuration: const Duration(milliseconds: 140),
+ transitionDuration: transitionDuration,
pageBuilder: (context, _, _) => _AppDialogVeil(
tint: veilTint,
blur: veilBlur,
@@ -105,10 +104,12 @@ class _AppDialogVeil extends StatelessWidget {
// otherwise get the click that was meant to close the panel.
behavior: HitTestBehavior.opaque,
onTap: dismissible ? () => Navigator.of(context).maybePop() : null,
- child: BackdropFilter(
- filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
- child: ColoredBox(color: tint),
- ),
+ child: blur == 0
+ ? ColoredBox(color: tint)
+ : BackdropFilter(
+ filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
+ child: ColoredBox(color: tint),
+ ),
),
),
// ⚠️ The dialog is NOT inside the GestureDetector above: nested in it,
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index 53db8e8ae..8b1c503c9 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -73,6 +73,9 @@ enum ShortcutAction {
/// Jump to any agent by name, on any machine.
switchAgent,
+ /// Add a view to the current Swarm, independently of navigation.
+ addAgent,
+
closePane,
newAgent,
routeTask,
@@ -515,11 +518,11 @@ const kSwarmShortcuts = [
AppShortcut(
action: ShortcutAction.switchAgent,
activator: SingleActivator(LogicalKeyboardKey.keyP, meta: true),
- label: 'Add an agent to this swarm',
- group: ShortcutGroup.actions,
+ label: 'Jump to an agent or swarm',
+ group: ShortcutGroup.navigate,
),
AppShortcut(
- action: ShortcutAction.switchAgent,
+ action: ShortcutAction.addAgent,
activator: SingleActivator(
LogicalKeyboardKey.keyF,
meta: true,
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index c8300a9e7..cdb526add 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -368,7 +368,7 @@ class AppNotifier extends ChangeNotifier {
selectSwarm(swarm.id);
}
- void selectSwarm(String id) {
+ void selectSwarm(String id, {bool attachPending = true}) {
if (!swarms.any((s) => s.id == id)) return;
_activeSwarmId = id;
railFocused = false;
@@ -376,10 +376,52 @@ class AppNotifier extends ChangeNotifier {
selectedMachineId = pane?.machineId;
_persistLayout();
_announceFocusToDial();
- for (final machine in machineStates.values) {
- _attachPendingPanes(machine);
+ if (attachPending) {
+ for (final machine in machineStates.values) {
+ _attachPendingPanes(machine);
+ }
+ }
+ notifyListeners();
+ }
+
+ /// Navigate to an existing view without opening, retrying or taking control
+ /// of a terminal. A shared view prefers the current Swarm, then the requested
+ /// owner. Publish the destination and its focus together, preserving layout.
+ bool revealAgentView(
+ String machineId,
+ String agentId, {
+ String? preferredSwarmId,
+ }) {
+ if (_disposed) return false;
+ bool contains(Swarm swarm) => swarm.panes.any(
+ (p) => p.machineId == machineId && p.agentId == agentId,
+ );
+ final owner = contains(activeSwarm)
+ ? activeSwarm
+ : swarms
+ .where((s) => s.id == preferredSwarmId && contains(s))
+ .firstOrNull ??
+ swarms.where(contains).firstOrNull;
+ if (owner == null) return false;
+ final pane = owner.panes.firstWhere(
+ (p) => p.machineId == machineId && p.agentId == agentId,
+ );
+ if (owner == activeSwarm) {
+ focusPane(pane.id);
+ return true;
}
+ if (owner.focusedPaneId != pane.id) {
+ owner.previousPaneId = owner.focusedPaneId;
+ owner.focusedPaneId = pane.id;
+ }
+ if (owner.zoomedPaneId != null) owner.zoomedPaneId = pane.id;
+ _activeSwarmId = owner.id;
+ railFocused = false;
+ selectedMachineId = machineId;
+ _persistLayout();
+ _announceFocusToDial();
notifyListeners();
+ return true;
}
void stepSwarm(int delta) {
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
new file mode 100644
index 000000000..c16d633e4
--- /dev/null
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -0,0 +1,278 @@
+import '../core/fuzzy_match.dart';
+import '../core/models.dart';
+import 'app_state.dart';
+import 'swarm.dart';
+
+String swarmDestinationId(String id) => 'swarm:$id';
+String agentDestinationId(String machineId, String agentId) =>
+ 'agent:$machineId\u0000$agentId';
+
+/// Session-local history contains identities only, never terminal buffers or
+/// controllers. Repeated discovery/output notifications do not reorder it.
+class SwarmNavigationHistory {
+ static const capacity = 64;
+ final _recent = <String>[];
+ (String, int?)? _location;
+ List<String> get recent => List.unmodifiable(_recent);
+
+ void record(AppNotifier app) {
+ final location = (app.activeSwarmId, app.focusedPaneId);
+ if (_location == location) return;
+ if (_location?.$1 != location.$1) {
+ _remember(swarmDestinationId(location.$1));
+ }
+ final pane = app.focusedPane;
+ if (pane?.agentId != null) {
+ _remember(agentDestinationId(pane!.machineId, pane.agentId!));
+ }
+ _location = location;
+ }
+
+ void _remember(String id) {
+ _recent.remove(id);
+ _recent.insert(0, id);
+ if (_recent.length > capacity) _recent.removeLast();
+ }
+}
+
+/// A searchable snapshot. Resolving a result again at activation prevents live
+/// discovery or a closed tab from redirecting an action to unrelated work.
+class SwarmDestination {
+ SwarmDestination({
+ required this.id,
+ required this.title,
+ required this.detail,
+ required this.swarmId,
+ required this.current,
+ this.machineId,
+ this.agentId,
+ this.engine,
+ Iterable<String?> searchFields = const [],
+ }) : fields = [
+ title.toLowerCase(),
+ ...searchFields.whereType<String>().map((s) => s.toLowerCase()),
+ ];
+
+ final String id, title, detail;
+ final String? swarmId, machineId, agentId, engine;
+ final bool current;
+ final List<String> fields;
+ bool get isSwarm => agentId == null;
+ bool get hasView => swarmId != null;
+}
+
+List<SwarmDestination> swarmDestinations(
+ AppNotifier app, {
+ List<String> recent = const [],
+}) {
+ final owners = <String, List<Swarm>>{};
+ final agents = <String, (MachineState, Agent)>{};
+ final result = <SwarmDestination>[];
+ final recency = {for (var i = 0; i < recent.length; i++) recent[i]: i};
+ for (final machine in app.machineStates.values) {
+ for (final agent in machine.agents) {
+ agents[agentDestinationId(machine.machine.machineId, agent.id)] = (
+ machine,
+ agent,
+ );
+ }
+ }
+ for (final swarm in app.swarms) {
+ final context = <String?>[];
+ for (final pane in swarm.panes) {
+ if (pane.agentId == null) continue;
+ final id = agentDestinationId(pane.machineId, pane.agentId!);
+ (owners[id] ??= []).add(swarm);
+ final row = agents[id];
+ final project = row?.$1.projectOf(row.$2);
+ context.addAll([
+ row?.$1.machine.displayName,
+ row?.$2.name ?? pane.session?.agentName,
+ project?.name,
+ project?.branch,
+ project?.cwd,
+ ]);
+ }
+ result.add(
+ SwarmDestination(
+ id: swarmDestinationId(swarm.id),
+ title: swarm.name,
+ detail:
+ '${swarm.panes.length} ${swarm.panes.length == 1 ? 'view' : 'views'}',
+ swarmId: swarm.id,
+ current: swarm.id == app.activeSwarmId,
+ searchFields: context,
+ ),
+ );
+ }
+ for (final id in {...owners.keys, ...agents.keys}) {
+ final memberships = owners[id] ?? const <Swarm>[];
+ final row = agents[id];
+ if (memberships.isEmpty && row?.$2.terminalAvailable != true) continue;
+ Swarm? owner;
+ var ownerRank = 1000;
+ for (final candidate in memberships) {
+ final rank = candidate.id == app.activeSwarmId
+ ? -1
+ : recency[swarmDestinationId(candidate.id)] ?? 999;
+ if (rank < ownerRank) {
+ owner = candidate;
+ ownerRank = rank;
+ }
+ }
+ final pane = owner?.panes
+ .where(
+ (p) =>
+ p.agentId != null &&
+ agentDestinationId(p.machineId, p.agentId!) == id,
+ )
+ .firstOrNull;
+ final machineId = row?.$1.machine.machineId ?? pane!.machineId;
+ final agentId = row?.$2.id ?? pane!.agentId!;
+ final machine = app.machineStates[machineId];
+ final project = row?.$1.projectOf(row.$2);
+ final machineName = machine?.machine.displayName ?? machineId;
+ final engine = row?.$2.engine ?? pane?.session?.engineId;
+ result.add(
+ SwarmDestination(
+ id: id,
+ title: row?.$2.name ?? pane?.session?.agentName ?? agentId,
+ detail: [
+ machineName,
+ project?.name,
+ project?.branch,
+ owner?.name,
+ if (machine?.nodeOnline == false) 'Offline',
+ ].whereType<String>().where((s) => s.isNotEmpty).join(' · '),
+ swarmId: owner?.id,
+ machineId: machineId,
+ agentId: agentId,
+ engine: engine,
+ current:
+ owner?.id == app.activeSwarmId && pane?.id == app.focusedPaneId,
+ searchFields: [
+ machineName,
+ project?.name,
+ project?.branch,
+ project?.cwd,
+ engine,
+ ...memberships.map((s) => s.name),
+ ],
+ ),
+ );
+ }
+ return result;
+}
+
+final _words = RegExp(r'\s+');
+
+/// Each word may match a different field, in either order: "mini auth" and
+/// "auth mini" both find Auth on Mac mini. Names outrank incidental metadata.
+List<SwarmDestination> rankSwarmDestinations(
+ List<SwarmDestination> all,
+ String query, {
+ List<String> recent = const [],
+}) {
+ final needle = query.trim().toLowerCase();
+ final terms = needle.isEmpty ? const <String>[] : needle.split(_words);
+ final recency = {for (var i = 0; i < recent.length; i++) recent[i]: i};
+ final ranked = <({SwarmDestination entry, int score})>[];
+ for (final entry in all) {
+ var total = 0;
+ for (final term in terms) {
+ int? best;
+ for (var i = 0; i < entry.fields.length; i++) {
+ final field = entry.fields[i];
+ final offset = field.indexOf(term);
+ final spread = offset >= 0 ? 0 : subsequenceSpread(field, term);
+ if (spread == null) continue;
+ final score =
+ (i == 0 ? 0 : 64) +
+ (field == term
+ ? 0
+ : offset == 0
+ ? 8
+ : offset > 0
+ ? 16
+ : 128 + spread);
+ if (best == null || score < best) best = score;
+ }
+ if (best == null) {
+ total = -1;
+ break;
+ }
+ total += best;
+ }
+ if (total >= 0) {
+ ranked.add((
+ entry: entry,
+ score: entry.fields.first == needle ? -1 : total,
+ ));
+ }
+ }
+ int tier(SwarmDestination e) => !e.hasView
+ ? 3
+ : e.current
+ ? 2
+ : recency.containsKey(e.id)
+ ? 0
+ : 1;
+ ranked.sort((a, b) {
+ var order = a.score.compareTo(b.score);
+ if (order == 0 && needle.isEmpty) {
+ order = tier(a.entry).compareTo(tier(b.entry));
+ }
+ if (order == 0) {
+ order = (recency[a.entry.id] ?? 999).compareTo(
+ recency[b.entry.id] ?? 999,
+ );
+ }
+ if (order == 0) {
+ order = a.entry.fields.first.compareTo(b.entry.fields.first);
+ }
+ return order == 0 ? a.entry.id.compareTo(b.entry.id) : order;
+ });
+ return [for (final row in ranked) row.entry];
+}
+
+Future<bool> activateSwarmDestination(
+ AppNotifier app,
+ SwarmDestination destination, {
+ required String destinationSwarmId,
+}) async {
+ if (destination.isSwarm) {
+ if (!app.swarms.any((s) => s.id == destination.swarmId)) return false;
+ app.selectSwarm(destination.swarmId!, attachPending: false);
+ return true;
+ }
+ if (app.revealAgentView(
+ destination.machineId!,
+ destination.agentId!,
+ preferredSwarmId: destination.swarmId,
+ )) {
+ return true;
+ }
+ // An existing-view result that disappeared must never become an Add action.
+ if (destination.hasView) return false;
+ final agent = app.machineStates[destination.machineId]?.agents
+ .where((a) => a.id == destination.agentId)
+ .firstOrNull;
+ if (agent?.terminalAvailable != true ||
+ !app.swarms.any((s) => s.id == destinationSwarmId)) {
+ return false;
+ }
+ await app.addAgentToSwarm(
+ destination.machineId!,
+ destination.agentId!,
+ swarmId: destinationSwarmId,
+ );
+ return app.swarms.any(
+ (s) =>
+ s.id == destinationSwarmId &&
+ s.panes.any(
+ (p) =>
+ p.machineId == destination.machineId &&
+ p.agentId == destination.agentId,
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/agent_switcher.dart b/desktop/lib/widgets/agent_switcher.dart
index 3093d5b24..60bc9771d 100644
--- a/desktop/lib/widgets/agent_switcher.dart
+++ b/desktop/lib/widgets/agent_switcher.dart
@@ -4,10 +4,13 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../core/models.dart';
+import '../core/fuzzy_match.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
import 'engine_identity.dart';
+export '../core/fuzzy_match.dart' show subsequenceSpread;
+
/// ⌘P — go to an agent by name, on any machine.
///
/// THE KEY THAT WAS MISSING, and it was missing for the main verb of the
@@ -68,28 +71,6 @@ class SwitcherEntry {
String get haystack => '${agent.name} $machineName'.toLowerCase();
}
-/// Subsequence match, fzf-style: every character of [query] appears in [text]
-/// in order, not necessarily together.
-///
-/// Returns the match's SPREAD — the distance from the first matched character
-/// to the last — or null when it does not match. Spread is the ranking signal
-/// because a tight run is what a person meant: `auth` against "Auth" scores 3
-/// and against "a...u...t...h" scores forty, and the first is the one they were
-/// typing at.
-int? subsequenceSpread(String text, String query) {
- if (query.isEmpty) return 0;
- var at = -1;
- var first = -1;
- for (final rune in query.runes) {
- final ch = String.fromCharCode(rune);
- final found = text.indexOf(ch, at + 1);
- if (found < 0) return null;
- if (first < 0) first = found;
- at = found;
- }
- return at - first;
-}
-
/// The agents this window can reach, ranked against [query].
///
/// Pulled out of the widget so the ranking can be tested without a screen —
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
new file mode 100644
index 000000000..a606dcdec
--- /dev/null
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -0,0 +1,215 @@
+import 'package:flutter/material.dart';
+
+import '../shared/widgets/app_dialog.dart';
+import '../state/app_state.dart';
+import '../state/swarm_navigation.dart';
+import 'engine_identity.dart';
+import 'swarm_welcome.dart';
+
+Future<SwarmDestination?> showSwarmSwitcher(
+ BuildContext context,
+ AppNotifier app,
+ SwarmNavigationHistory history,
+) => showAppDialog<SwarmDestination>(
+ context: context,
+ transitionDuration: Duration.zero,
+ veilBlur: 0,
+ veilTint: const Color(0x66000000),
+ builder: (_) => _SwarmSwitcher(app: app, recent: history.recent),
+);
+
+class _SwarmSwitcher extends StatefulWidget {
+ const _SwarmSwitcher({required this.app, required this.recent});
+ final AppNotifier app;
+ final List<String> recent;
+ @override
+ State<_SwarmSwitcher> createState() => _SwarmSwitcherState();
+}
+
+class _SwarmSwitcherState extends State<_SwarmSwitcher> {
+ final _scroll = ScrollController();
+ late List<SwarmDestination> _catalog;
+ List<SwarmDestination> _rows = [];
+ String _query = '';
+ String? _selectedId;
+ int _cursor = 0;
+ double _rowHeight = 56;
+ late final _targetName = widget.app.activeSwarm.name;
+
+ @override
+ void initState() {
+ super.initState();
+ _refreshCatalog();
+ widget.app.addListener(_onAppChanged);
+ }
+
+ void _onAppChanged() => setState(_refreshCatalog);
+
+ void _refreshCatalog() {
+ _catalog = swarmDestinations(widget.app, recent: widget.recent);
+ _filter();
+ }
+
+ void _filter() {
+ _rows = rankSwarmDestinations(_catalog, _query, recent: widget.recent);
+ final index = _rows.indexWhere((row) => row.id == _selectedId);
+ _cursor = _rows.isEmpty
+ ? 0
+ : index >= 0
+ ? index
+ : _cursor.clamp(0, _rows.length - 1);
+ _selectedId = _rows.isEmpty ? null : _rows[_cursor].id;
+ _revealSelection();
+ }
+
+ void _move(int delta) {
+ if (_rows.isEmpty) return;
+ setState(() {
+ _cursor = (_cursor + delta) % _rows.length;
+ _selectedId = _rows[_cursor].id;
+ });
+ _revealSelection();
+ }
+
+ void _revealSelection() {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || !_scroll.hasClients || _rows.isEmpty) return;
+ final top = _cursor * _rowHeight;
+ final bottom = top + _rowHeight;
+ final position = _scroll.position;
+ final offset = top < position.pixels
+ ? top
+ : bottom > position.pixels + position.viewportDimension
+ ? bottom - position.viewportDimension
+ : position.pixels;
+ final target = offset.clamp(0.0, position.maxScrollExtent);
+ if (target != position.pixels) _scroll.jumpTo(target);
+ });
+ }
+
+ void _submit() {
+ if (_rows.isNotEmpty) Navigator.pop(context, _rows[_cursor]);
+ }
+
+ @override
+ void dispose() {
+ widget.app.removeListener(_onAppChanged);
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final scale = MediaQuery.textScalerOf(context);
+ _rowHeight = (scale.scale(13) + scale.scale(11) + 32).clamp(
+ 56,
+ double.infinity,
+ );
+ final selected = _rows.isEmpty ? null : _rows[_cursor];
+ return Dialog(
+ alignment: const Alignment(0, -0.5),
+ insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 48),
+ child: SizedBox(
+ width: 620,
+ height: 480,
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: Column(
+ children: [
+ SwarmSearchField(
+ autofocus: true,
+ hintText: 'Jump to an agent or swarm…',
+ onChanged: (value) => setState(() {
+ _query = value;
+ _cursor = 0;
+ _selectedId = null;
+ _filter();
+ }),
+ onMove: _move,
+ onSubmitted: _submit,
+ ),
+ const SizedBox(height: 12),
+ Expanded(
+ child: _rows.isEmpty
+ ? const Center(
+ child: Text(
+ 'No matching agents or swarms',
+ style: TextStyle(fontSize: 13, color: Colors.white60),
+ ),
+ )
+ : ListView.builder(
+ controller: _scroll,
+ itemCount: _rows.length,
+ itemExtent: _rowHeight,
+ itemBuilder: (context, index) {
+ final row = _rows[index];
+ return ListTile(
+ key: ValueKey(row.id),
+ selected: index == _cursor,
+ selectedColor: Colors.white,
+ selectedTileColor: Colors.white10,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(8),
+ ),
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ ),
+ leading: row.isSwarm
+ ? const Icon(
+ Icons.tab,
+ size: 19,
+ color: Colors.white60,
+ )
+ : EngineMark(engine: row.engine, size: 20),
+ title: Text(
+ row.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 13),
+ ),
+ subtitle: Text(
+ row.detail,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ fontSize: 11,
+ color: Colors.white54,
+ ),
+ ),
+ trailing: Text(
+ row.current
+ ? 'Current'
+ : row.isSwarm
+ ? 'Swarm'
+ : row.hasView
+ ? 'Jump'
+ : 'Open view',
+ style: const TextStyle(
+ fontSize: 11,
+ color: Colors.white54,
+ ),
+ ),
+ onTap: () => Navigator.pop(context, row),
+ );
+ },
+ ),
+ ),
+ const SizedBox(height: 12),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ selected != null && !selected.hasView
+ ? '↵ Open view in $_targetName · Esc to close'
+ : '↑↓ or ⌃N ⌃P to choose · Return to jump · Esc to close',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 11, color: Colors.white54),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/swarm_welcome.dart b/desktop/lib/widgets/swarm_welcome.dart
index af18b5cf8..fe61f7d43 100644
--- a/desktop/lib/widgets/swarm_welcome.dart
+++ b/desktop/lib/widgets/swarm_welcome.dart
@@ -269,11 +269,13 @@ class SwarmSearchField extends StatefulWidget {
this.onSubmitted,
this.onMove,
this.autofocus = false,
+ this.hintText = 'Find an agent…',
});
final ValueChanged<String> onChanged;
final VoidCallback? onSubmitted;
final ValueChanged<int>? onMove;
final bool autofocus;
+ final String hintText;
@override
State<SwarmSearchField> createState() => _SwarmSearchFieldState();
}
@@ -327,7 +329,7 @@ class _SwarmSearchFieldState extends State<SwarmSearchField> {
onSubmitted: (_) => onSubmitted?.call(),
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
- hintText: 'Find an agent…',
+ hintText: widget.hintText,
prefixIcon: const Icon(Icons.search, size: 18),
filled: true,
fillColor: const Color(0xa6111521),
diff --git a/desktop/test/benchmarks/swarm_benchmark.dart b/desktop/test/benchmarks/swarm_benchmark.dart
index e3ba4fe17..b307e7a6f 100644
--- a/desktop/test/benchmarks/swarm_benchmark.dart
+++ b/desktop/test/benchmarks/swarm_benchmark.dart
@@ -9,6 +9,7 @@ import 'package:harness/core/config.dart';
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/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/terminal_panel.dart';
@@ -112,6 +113,7 @@ void main() {
id: 'agent-$agent',
name: 'Agent $agent',
engine: 'codex',
+ terminalAvailable: true,
project: AgentProject(
name: 'Project ${agent % 50}',
cwd: '/work/project-${agent % 50}',
@@ -123,6 +125,15 @@ void main() {
}
expect(swarmAgents(app), hasLength(2000));
expect(swarmProjects(app, const []), hasLength(50));
+ final navigation = swarmDestinations(app);
+ expect(navigation, hasLength(2001));
+ debugPrint(
+ 'SWARM_BENCH ${jsonEncode({'kind': 'headless_debug_cpu', 'operation': 'jump_catalog', 'agents': 2000, 'build': measure(() {
+ swarmDestinations(app);
+ }), 'query': measure(() {
+ rankSwarmDestinations(navigation, 'agent 12 machine 3');
+ })})}',
+ );
debugPrint(
'SWARM_BENCH ${jsonEncode({'kind': 'headless_debug_cpu', 'agents': 2000, 'machines': 8, 'search': measure(() {
swarmAgents(app, 'Agent 12 Project 12');
diff --git a/desktop/test/shortcuts_test.dart b/desktop/test/shortcuts_test.dart
index 3c7e057eb..43a434406 100644
--- a/desktop/test/shortcuts_test.dart
+++ b/desktop/test/shortcuts_test.dart
@@ -292,6 +292,8 @@ void main() {
expect(chordsFor(ShortcutAction.zoomPane), contains('⌘⏎'));
expect(chordsFor(ShortcutAction.lastPane), contains('⌘;'));
expect(chordsFor(ShortcutAction.switchAgent), contains('⌘P'));
+ expect(chordsFor(ShortcutAction.switchAgent), isNot(contains('⇧⌘F')));
+ expect(chordsFor(ShortcutAction.addAgent), ['⇧⌘F']);
});
test(
diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dart
index 38f3d16d1..ced816e54 100644
--- a/desktop/test/swarm_interactions_test.dart
+++ b/desktop/test/swarm_interactions_test.dart
@@ -67,7 +67,7 @@ void main() {
(tester) async {
final app = createApp();
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyP);
+ await chord(tester, LogicalKeyboardKey.keyF, shift: true);
await tester.pump(const Duration(milliseconds: 200));
for (var i = 0; i < 12; i++) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
diff --git a/desktop/test/swarm_navigation_test.dart b/desktop/test/swarm_navigation_test.dart
new file mode 100644
index 000000000..ed6a0250e
--- /dev/null
+++ b/desktop/test/swarm_navigation_test.dart
@@ -0,0 +1,240 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/terminal/terminal_session.dart';
+
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ test(
+ 'search matches project, branch, folder and machine in either word order',
+ () {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ const Agent(
+ id: 'auth',
+ name: 'Auth',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'Payments',
+ cwd: '/work/billing',
+ branch: 'fix-login',
+ ),
+ ),
+ const Agent(
+ id: 'loose',
+ name: 'A user testing harness',
+ terminalAvailable: true,
+ ),
+ ];
+ final catalog = swarmDestinations(app);
+ for (final query in [
+ 'HOST auth',
+ 'auth host',
+ 'payments login',
+ 'billing auth',
+ 'ath',
+ ]) {
+ expect(
+ rankSwarmDestinations(catalog, query).first.agentId,
+ 'auth',
+ reason: query,
+ );
+ }
+ expect(rankSwarmDestinations(catalog, 'AUTH').first.agentId, 'auth');
+ expect(rankSwarmDestinations(catalog, 'missing project'), isEmpty);
+ },
+ );
+
+ test('a shared agent has one result and prefers the current owner', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final first = app.activeSwarmId;
+ app.newSwarm();
+ await app.addAgentToSwarm('m', 'a0');
+ final rows = swarmDestinations(
+ app,
+ recent: [swarmDestinationId(first)],
+ ).where((r) => r.agentId == 'a0');
+ expect(rows, hasLength(1));
+ expect(rows.single.swarmId, app.activeSwarmId);
+ expect(rows.single.current, isTrue);
+ });
+
+ for (final status in [
+ TerminalSessionStatus.controlling,
+ TerminalSessionStatus.takenOver,
+ TerminalSessionStatus.error,
+ ]) {
+ test(
+ 'jump preserves $status session and publishes destination focus atomically',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final sent = <String>[];
+ final session = TerminalSession(
+ machineId: 'm',
+ agentId: 'a0',
+ agentName: 'Retained Auth',
+ engineId: 'codex',
+ send: (type, _) async {
+ sent.add(type);
+ return true;
+ },
+ sendBinary: (_) async => true,
+ )..status = TerminalSessionStatus.controlling;
+ session.terminal.write('retained scrollback\r\n');
+ final target = app.adoptSessionForTest(session);
+ final other = app.adoptSessionForTest(terminal('a1', []));
+ app.toggleZoomPane();
+ app.togglePinPane(target.id);
+ final owner = app.activeSwarm;
+ final order = [...owner.panes];
+ final pins = Map.of(owner.pinnedSlots);
+ final text = session.terminal.buffer.getText();
+ app.newSwarm();
+ session.status = status;
+ final source = app.activeSwarm;
+ final observations = <(String, int?)>[];
+ app.addListener(
+ () => observations.add((app.activeSwarmId, app.focusedPaneId)),
+ );
+ sent.clear();
+ expect(app.revealAgentView('m', 'a0'), isTrue);
+ await Future<void>.delayed(Duration.zero);
+ expect(observations, [(owner.id, target.id)]);
+ expect(owner.panes, order);
+ expect(owner.pinnedSlots, pins);
+ expect(owner.previousPaneId, other.id);
+ expect(owner.zoomedPaneId, target.id);
+ expect(source.panes, isEmpty);
+ expect(target.session, same(session));
+ expect(session.status, status);
+ expect(session.terminal.buffer.getText(), text);
+ expect(sent.where((s) => s.startsWith('terminal_')), isEmpty);
+ },
+ );
+ }
+
+ test('opening a swarm restores its saved focus and zoom', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ final focused = app.adoptSessionForTest(terminal('a1', []));
+ app.toggleZoomPane();
+ final owner = app.activeSwarm;
+ app.newSwarm();
+ final destination = swarmDestinations(app)
+ .firstWhere((r) => r.id == swarmDestinationId(owner.id));
+ await activateSwarmDestination(
+ app,
+ destination,
+ destinationSwarmId: app.activeSwarmId,
+ );
+ expect(app.focusedPaneId, focused.id);
+ expect(app.zoomedPaneId, focused.id);
+ expect(owner.panes, hasLength(2));
+ });
+
+ test('offline open work remains findable after its roster disappears', () {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ app.machineStates.clear();
+ final row = rankSwarmDestinations(
+ swarmDestinations(app),
+ 'session a0',
+ ).firstWhere((r) => !r.isSwarm);
+ expect(row.title, 'Session a0');
+ expect(row.hasView, isTrue);
+ expect(app.revealAgentView('m', 'a0'), isTrue);
+ expect(app.focusedPaneId, pane.id);
+ });
+
+ test('a vanished existing view never turns into an Add action', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final row = swarmDestinations(app).firstWhere((r) => r.agentId == 'a0');
+ await app.closePane(app.panes.single.id);
+ expect(
+ await activateSwarmDestination(
+ app,
+ row,
+ destinationSwarmId: app.activeSwarmId,
+ ),
+ isFalse,
+ );
+ expect(app.panes, isEmpty);
+ });
+
+ test('an explicit Open view captures its destination and reuses intervening work', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final target = app.activeSwarm;
+ final row = swarmDestinations(app).firstWhere((r) => r.agentId == 'a0');
+ app.newSwarm();
+ final elsewhere = app.activeSwarm;
+ await activateSwarmDestination(app, row, destinationSwarmId: target.id);
+ expect(target.panes.single.agentId, 'a0');
+ expect(elsewhere.panes, isEmpty);
+ // Selecting the old snapshot again must find that existing view.
+ await activateSwarmDestination(app, row, destinationSwarmId: elsewhere.id);
+ expect(app.activeSwarmId, target.id);
+ expect(app.allPanes, hasLength(1));
+ expect(elsewhere.panes, isEmpty);
+ });
+
+ test('recents return to previous work without notification churn or retained sessions', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final history = SwarmNavigationHistory();
+ app.addListener(() => history.record(app));
+ await app.addAgentToSwarm('m', 'a0');
+ final first = app.activeSwarm;
+ app.newSwarm();
+ await app.addAgentToSwarm('m', 'a1');
+ final before = history.recent;
+ for (var i = 0; i < 100; i++) {
+ app.dismissError();
+ }
+ expect(history.recent, before);
+ var rows = rankSwarmDestinations(
+ swarmDestinations(app),
+ '',
+ recent: history.recent,
+ );
+ expect(rows.first.agentId, 'a0');
+ await activateSwarmDestination(
+ app,
+ rows.first,
+ destinationSwarmId: app.activeSwarmId,
+ );
+ rows = rankSwarmDestinations(
+ swarmDestinations(app),
+ '',
+ recent: history.recent,
+ );
+ expect(rows.first.agentId, 'a1');
+ await app.closeSwarm(first.id);
+ rows = rankSwarmDestinations(
+ swarmDestinations(app),
+ '',
+ recent: history.recent,
+ );
+ expect(rows.where((r) => r.id == swarmDestinationId(first.id)), isEmpty);
+ expect(rows.first.hasView, isTrue);
+ for (var i = 0; i < 80; i++) {
+ app.newSwarm();
+ await app.closeSwarm(app.activeSwarmId);
+ }
+ expect(
+ history.recent.length,
+ lessThanOrEqualTo(SwarmNavigationHistory.capacity),
+ );
+ });
+}
diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dart
index c7f2b4fb9..12204b01b 100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@ -100,7 +100,7 @@ void main() {
await tester.pump();
final zoom = app.zoomedPaneId;
final before = tester.getSize(find.byType(PaneGrid));
- await tester.tap(find.byTooltip('Add agent ⌘P'));
+ await tester.tap(find.byTooltip('Add agent ⇧⌘F'));
await tester.pump(const Duration(milliseconds: 300));
expect(find.text('Add agent'), findsOneWidget);
expect(app.panes.length, 2);
diff --git a/desktop/test/swarm_switcher_test.dart b/desktop/test/swarm_switcher_test.dart
new file mode 100644
index 000000000..eaaf693a8
--- /dev/null
+++ b/desktop/test/swarm_switcher_test.dart
@@ -0,0 +1,158 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+Finder get jumpField => find.byWidgetPredicate(
+ (w) =>
+ w is TextField && w.decoration?.hintText == 'Jump to an agent or swarm…',
+);
+Finder get selectedRow =>
+ find.byWidgetPredicate((w) => w is ListTile && w.selected);
+
+void main() {
+ testWidgets(
+ 'jump opens in one frame, owns typing, cancels, and leaves Add separate',
+ (tester) async {
+ final app = createApp();
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ final membership = [...app.panes];
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.meta);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyP);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.meta);
+ await tester.pump();
+ expect(jumpField, findsOneWidget);
+ final field = tester.widget<TextField>(jumpField);
+ expect(field.focusNode!.hasFocus, isTrue);
+ expect(
+ (ModalRoute.of(
+ tester.element(jumpField),
+ ) as TransitionRoute).transitionDuration,
+ Duration.zero,
+ );
+ expect(find.byType(BackdropFilter), findsNothing);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ expect(find.byType(Dialog), findsOneWidget);
+ await tester.enterText(jumpField, 'missing');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(jumpField, findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(jumpField, findsNothing);
+ expect(app.panes, membership);
+ await chord(tester, LogicalKeyboardKey.keyF, shift: true);
+ expect(find.text('Add agent'), findsOneWidget);
+ expect(jumpField, findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
+ testWidgets(
+ 'Return jumps across swarms and a second jump returns to prior focus',
+ (tester) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final firstInput = <TerminalBinaryFrame>[];
+ final secondInput = <TerminalBinaryFrame>[];
+ final firstPane = app.adoptSessionForTest(terminal('a0', firstInput));
+ final first = app.activeSwarm;
+ await mount(tester, app);
+ app.newSwarm();
+ final secondPane = app.adoptSessionForTest(terminal('a1', secondInput));
+ app.dismissError();
+ await tester.pump();
+ final second = app.activeSwarm;
+ await chord(tester, LogicalKeyboardKey.keyP);
+ expect(
+ find.descendant(of: selectedRow, matching: find.text('Agent 0')),
+ findsOneWidget,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.activeSwarmId, first.id);
+ expect(app.focusedPaneId, firstPane.id);
+ expect(first.panes, [firstPane]);
+ expect(second.panes, [secondPane]);
+ expect(firstInput, isEmpty);
+ expect(secondInput, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(firstInput.single.bytes, [27, 91, 68]);
+ expect(secondInput, isEmpty);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ expect(
+ find.descendant(of: selectedRow, matching: find.text('Agent 1')),
+ findsOneWidget,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.activeSwarmId, second.id);
+ expect(app.focusedPaneId, secondPane.id);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(firstInput, hasLength(1));
+ expect(secondInput.single.bytes, [27, 91, 67]);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
+ testWidgets(
+ 'keyboard selection scrolls, survives discovery, and explicitly opens a view',
+ (tester) async {
+ final app = createApp();
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ for (var i = 0; i < 12; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ }
+ await tester.pump();
+ final selectedId =
+ (tester.widget<ListTile>(selectedRow).key! as ValueKey<String>).value;
+ final rowRect = tester.getRect(selectedRow);
+ final listRect = tester.getRect(find.byType(ListView));
+ expect(rowRect.top, greaterThanOrEqualTo(listRect.top));
+ expect(rowRect.bottom, lessThanOrEqualTo(listRect.bottom));
+ final machine = app.machineStates['m']!;
+ machine.agents = [
+ const Agent(
+ id: 'new',
+ name: 'A newly discovered agent',
+ terminalAvailable: true,
+ ),
+ ...machine.agents,
+ ];
+ app.dismissError();
+ await tester.pump();
+ await tester.pump();
+ expect(tester.widget<ListTile>(selectedRow).key, ValueKey(selectedId));
+ expect(find.textContaining('Open view in'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.panes, hasLength(2));
+ expect(
+ agentDestinationId(
+ app.focusedPane!.machineId,
+ app.focusedPane!.agentId!,
+ ),
+ selectedId,
+ );
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+}
diff --git a/docs/harness-v2-developer-tools-research.md b/docs/harness-v2-developer-tools-research.md
index cb72b823e..7d3b19255 100644
--- a/docs/harness-v2-developer-tools-research.md
+++ b/docs/harness-v2-developer-tools-research.md
@@ -48,7 +48,7 @@ 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. |
-| **Improve first** | `Cmd+P` currently opens **Add agent** in the Swarm screen | Make “jump to existing work” distinct from “add another view.” The present picker primarily changes membership. Add fuzzy ranking, recent destinations and Swarm matches to a navigation interface; retain an explicit Add command. |
+| **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. |
| **Improve first** | Notifications dialog shows actual blocked agents | Add direct keyboard access to waiting work and a route back to the previous focus. Use authoritative states and quiet presentation. Offer optional interruption behavior only when warranted. |
| **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. |
diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.md
index 3590d4ba8..560387243 100644
--- a/docs/harness-v2-performance.md
+++ b/docs/harness-v2-performance.md
@@ -12,7 +12,7 @@ It prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in
## Recorded measurements
-| Operation | Earlier median / p95 | Latest median / p95 |
+| Operation | Earlier median / p95 | After native/canvas polish median / p95 |
| --- | ---: | ---: |
| Search 2,000 agents across 8 machines | 1.06 / 1.13 ms | 1.16 / 1.34 ms |
| Group the same catalog into 50 projects | 1.14 / 1.27 ms | 1.31 / 1.52 ms |
@@ -21,7 +21,7 @@ It prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in
| Decode and parse a 16 KiB ASCII output frame | 0.51 / 0.68 ms | 0.55 / 0.73 ms |
| Decode and parse a 16 KiB Unicode output frame | 0.31 / 0.35 ms | 0.34 / 0.43 ms |
-The latest repetition followed the native/canvas polish while the workstation was in active use. All five benchmark cases passed and retained rebuild counts stayed at 1,491 and 1,625, but timings were higher across all workloads. This was not a controlled paired comparison, so it neither isolates a cause nor establishes unchanged user-visible performance. Preserve this result and measure under controlled load in the native release app; do not report only the faster earlier run. The latest local log is `/private/tmp/harness-v2-benchmark-polish.log`.
+That repetition followed the native/canvas polish while the workstation was in active use. All five benchmark cases passed and retained rebuild counts stayed at 1,491 and 1,625, but timings were higher across all workloads. This was not a controlled paired comparison, so it neither isolates a cause nor establishes unchanged user-visible performance. Preserve this result and measure under controlled load in the native release app; do not report only the faster earlier run. Its local log is `/private/tmp/harness-v2-benchmark-polish.log`.
Catalog operations use 20 warmups and 100 samples. Each terminal has 1,000 scrollback lines; the window is 1280 × 800 with four visible terminals. Tab checks warm up for three full cycles, then take 60 samples. They retain one renderer per session and include Flutter frame work and test-runner overhead. Network, persistence I/O, AppKit titlebar rendering and physical display latency are outside these measurements.
@@ -45,6 +45,27 @@ Ordinary output packets now decode directly from their existing byte view. Previ
In the paired headless checks, median decoding-and-parsing time fell from 0.683 to 0.514 ms for the ASCII workload and from 0.484 to 0.314 ms for Unicode. Corresponding p95 values were 1.088 to 0.680 ms and 0.686 to 0.348 ms. These measurements establish the benefit for these workloads; they do not measure user-visible latency or every terminal output pattern. Existing terminal-session regressions cover split UTF-8, compressed keyframes, parser sequences and recovery.
+## Jump navigation
+
+Cmd+P opens without a route transition or backdrop filter. Search normalizes a catalog once on opening and refreshes it on app-state changes; typing ranks that snapshot in memory without discovery, disk or network calls. List rows are built on demand. Recent-work history retains at most 64 string identities, not controllers or terminal buffers.
+
+Existing-view activation is focus-only. It changes destination Swarm and pane focus in one notification, preserves its arrangement, and never retries or takes over the terminal. Selecting a Swarm preserves its saved focus and zoom. A fresh view is an explicit action, revalidated against current membership and the originally captured destination.
+
+The continuation's headless debug run produced the following measurements in `/private/tmp/harness-v2-benchmark-jump.log`:
+
+| Operation | Median | p95 |
+| --- | ---: | ---: |
+| Build jump catalog: 2,000 agents, 8 machines | 1.424 ms | 1.689 ms |
+| Rank cached jump catalog for `agent 12 machine 3` | 1.059 ms | 1.154 ms |
+| Welcome search: same 2,000 agents | 1.119 ms | 1.236 ms |
+| Project grouping: 50 projects | 1.239 ms | 1.359 ms |
+| Switch and pump: 4 Swarms / 16 terminals | 20.420 ms | 30.016 ms |
+| Switch and pump: 12 Swarms / 48 terminals | 16.105 ms | 18.258 ms |
+| Decode and parse: 16 KiB ASCII | 0.531 ms | 0.693 ms |
+| Decode and parse: 16 KiB Unicode | 0.330 ms | 0.362 ms |
+
+All five benchmark cases passed; retained rebuild counts remained 1,491 / 1,625. This repetition was not a controlled paired comparison with the prior run. The new search measurements establish CPU cost for that query and catalog, excluding widget layout, AppKit input and physical display. Correctness checks verify the first terminal key after a jump goes only to its destination, but they do not measure native keystroke latency.
+
## Native follow-up
The optimized real-data app builds and runs locally. The desktop is now unlocked, and native visual review is underway. The tab strip uses AppKit's compact unified title bar: the old right accessory was clipped to 32 points; the container now supplies 40 points and aligns controls with the system traffic lights.
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index 407652201..21359ccc5 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -1,6 +1,6 @@
# Harness App V2 — development handoff
-Updated 2026-09-12 after the implementation continuation and live-data review. This is a working preview, not a release.
+Updated 2026-09-13 after the jump-navigation continuation. This is a working preview, not a release.
## Resume here
@@ -13,6 +13,8 @@ Updated 2026-09-12 after the implementation continuation and live-data review. T
- The desktop is now unlocked and the user is actively reviewing the app. A stale Debug build briefly ran alongside Release and obscured the latest changes. Both previews were quit normally, the stale Debug bundle was unregistered and retained as `/private/tmp/Harness V2.previous-debug-1789267673713820000.disabled`, and only the updated Release preview was relaunched. Preserve the user's current saved arrangement; do not restore an earlier snapshot or launch duplicate V2 instances.
- Latest design direction: wallpaper fills an empty New swarm only. Populated Swarms use a flat `#463746` canvas matching the selected native tab. Tab hover, spacing and alignment are being compared with the user's Chrome references.
- The user requested research into expert developers' tools and a smaller feature set. [Developer-tool research and the keep/improve/remove/defer audit](harness-v2-developer-tools-research.md) documents firsthand sources and a proposed three-part focus: durable sessions, instant navigation, and steering agents without losing concentration.
+- Cmd+P now jumps to existing agents and Swarms with fuzzy project/machine context and bounded recent-work history. Cmd+Shift+F remains Add agent. The jump dialog has no transition or backdrop blur; selecting an existing view is focus-only, including terminals controlled elsewhere. The 2,000-agent headless search check measured 1.06 ms median / 1.15 ms p95 CPU time; this is not native display latency.
+- The final Release preview was rebuilt and normally relaunched; PID **19010** was the sole V2 instance at the last check. Revalidate the process before any later restart. CUA now reports `cgWindowNotFound` when selecting that full bundle path, including after a CUA reset and a second normal rebuild/relaunch. The first relaunched process did have a 1280×840 onscreen CoreGraphics window. Bundle-ID selection was also ambiguous with the retained backup under `/Users/ab/code/harness-app-v2`; no backup was altered. Do not claim the new jump interaction was reviewed in the live native window. The actual native titlebar/canvas had been reviewed before this continuation; the new picker was visually inspected in an isolated Flutter render with native font files and engine icons loaded.
- Continue implementation here. Do not create another repository or fork for V2.
```bash
@@ -79,12 +81,14 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83
- `desktop/lib/screens/swarm_screen.dart` is wired into the authenticated case in `main.dart`.
- `widgets/swarm_welcome.dart`: live search, real machines/projects, New agent. `SwarmWallpaper` fills the empty canvas without an inset or rounded frame. It is absent from populated Swarms and evicts its own decoded image cache entry when replaced or disposed. Wallpaper rotates for a new swarm, stays stable, and supports manual next.
- `widgets/swarm_dialogs.dart`: fixed-size Add agent picker, rename, Add project, Link machine entry points.
+- `widgets/swarm_switcher.dart` and `state/swarm_navigation.dart`: immediate Cmd+P search across names, projects, branches, folders, machines and Swarms. The catalog is normalized when opened/refreshed and ranked in memory for each query. Arrows/Ctrl-N/P/Return/Escape work; live discovery preserves the highlighted identity and scrolls it into view. Recent destinations hold at most 64 string IDs for the current screen lifetime.
+- Jumping to an existing agent reuses a current/shared membership and publishes the destination Swarm and pane focus together. It preserves arrangement, pinning, zoom, scrollback and controller ownership, and performs no terminal retry. A result without a view explicitly says **Open view** and captures the destination Swarm. Revalidation reuses any intervening view; a vanished existing-view result never becomes Add. Offline retained views remain searchable even when their roster disappears.
- Add project saves an **existing folder**, via native local picker or existing remote folder browser. It does not clone a GitHub URL.
- `NewAgentDialog`: machine chooser, initial folder, captured destination swarm; local default when available. Reuses engine probes, Codex profiles, advanced permission behavior, and remote browsing. Profile/folder responses are rejected after a machine switch, including switching away and back. Launch replies are ignored after notifier disposal or machine replacement.
- `state/swarm_catalog.dart`: search, project grouping, saved folders (`swarm_projects_v1`). Group by canonical remote if supplied, otherwise owning machine and full folder path; matching basenames never establish identity.
- Project-store load/add operations are serialized, and failures are visible without claiming a project was saved.
- Search supports arrows, Ctrl-N/P, and Return, reveals the selected row, and retains the highlighted agent across live list changes. Both the welcome and picker immediately focus search; blank Return on welcome does not open an invisible first result.
-- Notifications come from real blocked agents; selecting an existing membership navigates back to its swarm.
+- Notifications come from real blocked agents; selecting an existing membership uses the same focus-only navigation without implicitly retrying the terminal.
- Spoken-task subscription/reporting/window reveal and existing linking dialogs are retained. Settings is in the title bar, with Account/sign-out restored inside Settings.
- Non-macOS/tests use a Flutter reorderable tab-strip fallback. Linux/Windows have not been built or visually reviewed.
@@ -127,7 +131,8 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83
| Reopen closed swarm | Cmd+Shift+T |
| Rename swarm | Cmd+Shift+R |
| Previous / next swarm | Cmd+Shift+[ / ], Ctrl+Shift+Tab / Ctrl+Tab |
-| Add agent picker / New agent | Cmd+Shift+F or Cmd+P / Cmd+N |
+| Jump to agent or swarm | Cmd+P |
+| Add agent picker / New agent | Cmd+Shift+F / Cmd+N |
| Focus neighboring pane | Cmd+H/J/K/L or Cmd+arrow |
| Move pane | Cmd+Shift+H/J/K/L or Cmd+Shift+arrow |
| Previous / next agent view | Cmd+[ / ] |
@@ -148,7 +153,9 @@ The reopen binding follows the documented Mac tab-recovery shortcut in [Safari](
| --- | --- |
| macOS debug build | Passed and launched from the monorepo with real saved Swarms and terminals. |
| macOS optimized local build | Passed and running with the real entry point and saved V2 state. Local ad hoc signing requires the command-line `ENABLE_HARDENED_RUNTIME=NO` override for Flutter's framework; distribution signing settings remain unchanged. The distribution Developer ID certificate is unavailable; nothing was uploaded. Normal asynchronous quit and relaunch were verified. Unlocked native review confirmed the taller tab container, edge-to-edge empty wallpaper, and the flat populated canvas joining the selected tab. The native hover rendering was also inspected in a local image. |
-| Full Flutter suite | **987 passed, 1 skipped** after persistence, modal menus, retained-terminal performance, stream dispatch, closed-Swarm recovery and output decoding changes. |
+| Full Flutter suite | **1,000 passed, 1 skipped** after the jump navigation changes, including terminal, modal, persistence and shortcut regressions. |
+| Jump navigation | 13 new state/widget checks cover fuzzy context, shared/offline views, focus-only navigation, preserved layout and terminal state, bounded recents, stale results, captured destinations, immediate focus, keyboard scrolling, live discovery and Add separation. The three widget checks also pass after adding assertions that the first terminal key reaches only the destination session. |
+| Jump visual review | Isolated render inspected with SF font files and engine icons; selected-result text now stays white on a quiet highlight. Four checks (the three widget cases plus the temporary visual fixture) passed after this contrast adjustment. Final Release build passed. Live CUA review remains unavailable with `cgWindowNotFound`. |
| Focused interaction checks | 8 passed: picker navigation/scroll/refresh, welcome keys, shared-view close, composer, native modal guard, profile and folder races. |
| Closed-Swarm recovery | 7 passed: arrangement and shared-view restoration, untouched welcome replacement, rapid close/reopen with delayed cleanup, capacity, bounded history, sign-out isolation and the keyboard command. Native command availability and modal behavior also pass in the interaction suite. |
| Local CLI discovery | 25 passed, including older-daemon folder parsing and continuous snapshots without spawning/reconnecting. |
@@ -165,8 +172,11 @@ Tests now exercise the actual V2 welcome/settings/linking flow. Usage pricing ag
Evidence on this Mac under `/private/tmp`:
-- `harness-v2-final-tests.log`: full 987-test pass.
-- `harness-v2-final-analyze.log`: latest diagnostics.
+- `harness-v2-jump-full-tests.log`: full 1,000-test pass.
+- `harness-v2-jump-tests.log`: 60 focused navigation/shortcut/interaction checks.
+- `harness-v2-jump-focus-tests.log`: three widget checks including first-key destination ownership.
+- `harness-v2-jump-visual-tests.log` and `harness-jump-review.png`: final focused checks and isolated visual fixture (not the real-data app). Temporary renderer source is `/private/tmp/harness-jump-render.dart`; no mock data or capture tooling was added to the application.
+- `harness-v2-jump-analyze.log`: latest diagnostics.
- `harness-v2-final-build.log`: real-entry debug build.
- `harness-v2-release-build.log`: optimized local build.
- `harness-v2-final-cli-check.log`, `harness-v2-final-cli-tests.log`: final metadata checks.
@@ -176,6 +186,7 @@ Evidence on this Mac under `/private/tmp`:
- `harness-v2-persistence-tests.log`: 21 state/async checks including rapid writes and bounded quit.
- `harness-v2-benchmark-final.log`: latest catalog and retained-terminal CPU measurements.
- `harness-v2-benchmark-polish.log`: subsequent five-case pass after native/canvas polish; identical retained rebuild counts, higher debug timings across workloads. Both runs and the comparison limits are recorded in the performance notes.
+- `harness-v2-benchmark-jump.log`: five-case pass after navigation changes, including the new catalog-build/query measurements; retained rebuild counts remain 1,491 / 1,625.
- `harness-v2-output-before.log`, `harness-v2-output-after.log`: paired production terminal decode-and-parse CPU measurements.
- `harness-v2-native-titlebar-tests.log`: windowless checks against the actual AppKit tab source.
- `harness-v2-native-titlebar-layout.log`: 170 component/native-container checks.
@@ -186,7 +197,7 @@ Earlier logs contain superseded failures. Temporary logs and toolchains are loca
## Remaining work
-1. Continue the unlocked native review of actual project starters and keyboard navigation. The user is actively changing window size and Swarms; re-read UI state before actions and preserve their arrangement.
+1. Restore CUA access to the current Release preview and review the new jump workflow, actual project starters and keyboard navigation. The tool currently reports `cgWindowNotFound`; the process is running. The user can change window size and Swarms; re-read UI state before actions and preserve their arrangement.
2. Audit native drag/reorder, overflow, close-last-tab, renaming and accessibility without changing the user's saved agent memberships. Keep any integration runner separate and out of the foreground review app.
3. Measure native terminal input and tab-switch responsiveness before making end-to-end latency claims. Headless CPU benchmarks are now recorded. Preserve the existing immediate first-input flush and shared retained renderers.
4. Visually confirm app-menu modal behavior and overflow accessibility in AppKit; route/shortcut behavior is covered by passing Flutter tests.