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
feat(desktop): preserve terminal context and refine swarm navigation
dee72d3e5018f2f
diff --git a/desktop/lib/core/local_git_projects.dart b/desktop/lib/core/local_git_projects.dartnew file mode 100644index 000000000..90916cf47--- /dev/null+++ b/desktop/lib/core/local_git_projects.dart@@ -0,0 +1,214 @@+import 'dart:async';+import 'dart:io';++import 'package:path/path.dart' as p;++import 'models.dart';++/// Compatibility for this computer's older daemon. Reads only Git metadata;+/// directory watches invalidate the cache when a checkout or remote changes.+/// No Git processes, network calls, terminal reads, or work on the render path.+class LocalGitProjects {+ LocalGitProjects({required this.onChanged});+ final void Function() onChanged;+ final _entries = <String, _LocalGitEntry>{};+ bool _disposed = false;++ AgentProject? cached(String cwd) => _entries[cwd]?.project;++ Future<void> read(String cwd) {+ if (_disposed || !p.isAbsolute(cwd)) return Future.value();+ final existing = _entries[cwd];+ if (existing != null) {+ if (existing.pending != null) return existing.pending!;+ if (existing.watchers.isNotEmpty ||+ DateTime.now().difference(existing.checkedAt) <+ const Duration(minutes: 1)) {+ return Future.value();+ }+ return existing.pending = _resolve(cwd, existing);+ }+ if (_entries.length >= 256) {+ _entries.remove(_entries.keys.first)?.dispose();+ }+ final entry = _LocalGitEntry();+ _entries[cwd] = entry;+ return entry.pending = _resolve(cwd, entry);+ }++ Future<void> _resolve(String cwd, _LocalGitEntry entry) async {+ try {+ var root = p.normalize(cwd);+ String? gitDir;+ for (var depth = 0; depth < 32; depth++) {+ final marker = p.join(root, '.git');+ final type = await FileSystemEntity.type(marker);+ if (type == FileSystemEntityType.directory) {+ gitDir = marker;+ break;+ }+ if (type == FileSystemEntityType.file) {+ final pointer = await _text(marker);+ if (pointer?.startsWith('gitdir: ') == true) {+ gitDir = p.normalize(p.join(root, pointer!.substring(8).trim()));+ }+ break;+ }+ final parent = p.dirname(root);+ if (parent == root) break;+ root = parent;+ }+ if (gitDir == null) {+ if (!_disposed && !entry.disposed && entry.project != null) {+ entry.project = null;+ onChanged();+ }+ return;+ }+ final shared = await _text(p.join(gitDir, 'commondir'));+ final common = shared == null+ ? gitDir+ : p.normalize(p.join(gitDir, shared.trim()));+ final head = (await _text(p.join(gitDir, 'HEAD')))?.trim();+ final config = await _text(p.join(common, 'config'));+ if (_disposed || entry.disposed) return;+ final branch = head?.startsWith('ref: refs/heads/') == true+ ? head!.substring(16)+ : head != null && RegExp(r'^[a-fA-F0-9]{40,64}$').hasMatch(head)+ ? 'Detached ${head.substring(0, 7)}'+ : null;+ final project = AgentProject.fromJson({+ 'name': p.basename(root),+ 'cwd': cwd,+ 'root': root,+ 'remote': _origin(config),+ 'branch': branch,+ });+ if (entry.watchers.isEmpty) {+ for (final directory in {gitDir, common}) {+ try {+ entry.watchers.add(+ Directory(directory).watch().listen((event) {+ if (!{+ 'HEAD',+ 'config',+ 'commondir',+ }.contains(p.basename(event.path))) {+ return;+ }+ entry.debounce?.cancel();+ entry.debounce = Timer(const Duration(milliseconds: 100), () {+ if (!_disposed && !entry.disposed) {+ entry.pending = _resolve(cwd, entry);+ }+ });+ }, onError: (Object _) {}),+ );+ } on FileSystemException {+ // Metadata is still useful when the filesystem cannot watch it.+ }+ }+ }+ if (entry.project != project) {+ entry.project = project;+ onChanged();+ }+ } on FileSystemException {+ // A removed/unreadable working folder must not interfere with discovery.+ } finally {+ entry.checkedAt = DateTime.now();+ entry.pending = null;+ }+ }++ Future<String?> _text(String path) async {+ final file = File(path);+ try {+ if (await file.length() > 64 * 1024) return null;+ return await file.readAsString();+ } on FileSystemException {+ return null;+ } on FormatException {+ return null;+ }+ }++ String? _origin(String? config) {+ if (config == null) return null;+ var origin = false;+ for (final line in config.split('\n')) {+ final text = line.trim();+ if (text.startsWith('[')) {+ origin = RegExp(+ r'^\[remote\s+"origin"\]$',+ caseSensitive: false,+ ).hasMatch(text);+ } else if (origin) {+ final match = RegExp(+ r'^url\s*=\s*(.+)$',+ caseSensitive: false,+ ).firstMatch(text);+ if (match != null) return canonicalGitRemote(match.group(1)!);+ }+ }+ return null;+ }++ void dispose() {+ _disposed = true;+ for (final entry in _entries.values) {+ entry.dispose();+ }+ _entries.clear();+ }+}++String? canonicalGitRemote(String raw) {+ raw = raw.trim();+ if (raw.startsWith('"') && raw.endsWith('"')) {+ raw = raw.substring(1, raw.length - 1);+ }+ final scp = RegExp(r'^(?:[^@/\s]+@)?([^:/\s]+):([^\s]+)$').firstMatch(raw);+ final uri = Uri.tryParse(+ scp != null && !raw.contains('://')+ ? 'ssh://${scp.group(1)}/${scp.group(2)}'+ : raw,+ );+ if (uri == null ||+ !{'ssh', 'https', 'http', 'git'}.contains(uri.scheme) ||+ uri.host.isEmpty) {+ return null;+ }+ var path = uri.path+ .replaceAll(RegExp(r'^/+|/+$'), '')+ .replaceFirst(RegExp(r'\.git$', caseSensitive: false), '');+ if (path.isEmpty || RegExp(r'[\x00-\x20]').hasMatch(path)) return null;+ final host = uri.host.toLowerCase();+ if (host == 'github.com' || host == 'bitbucket.org') {+ path = path.toLowerCase();+ }+ final defaultPort = switch (uri.scheme) {+ 'ssh' => 22,+ 'git' => 9418,+ 'https' => 443,+ _ => 80,+ };+ final port = uri.hasPort && uri.port != defaultPort ? ':${uri.port}' : '';+ return '$host$port/$path';+}++class _LocalGitEntry {+ DateTime checkedAt = DateTime.now();+ AgentProject? project;+ Future<void>? pending;+ final watchers = <StreamSubscription<FileSystemEvent>>[];+ Timer? debounce;+ bool disposed = false;+ void dispose() {+ disposed = true;+ debounce?.cancel();+ for (final watcher in watchers) {+ unawaited(watcher.cancel());+ }+ }+}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 499bd72c2..e855a9441 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -23,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_project_agents.dart';import '../widgets/swarm_attention.dart';import '../widgets/swarm_switcher.dart';import '../widgets/swarm_wallpaper.dart';@@ -135,6 +136,18 @@ class _SwarmScreenState extends State<SwarmScreen> {'canReopen': app.canReopenClosedSwarm,'canFind': _canFindTerminal,'canClosePane': app.focusedPane != null,+ 'canChangeWallpaper': app.panes.isEmpty,+ 'canGoBack': _navigation.canGoBack(app),+ 'canGoForward': _navigation.canGoForward(app),+ 'closedHistory': [+ for (final entry in closedSwarmDestinations(app))+ {+ 'id': entry.id,+ 'title': entry.title,+ 'detail': entry.detail,+ 'swarm': true,+ },+ ],'attention': _attention,'history': [for (final entry in _navigation.menuDestinations(app))@@ -182,6 +195,16 @@ class _SwarmScreenState extends State<SwarmScreen> {app.newSwarm();case 'reopen':app.reopenClosedSwarm();+ case 'reopenHistory':+ if (args['id'] is String) app.reopenClosedSwarm(historyId: args['id']);+ case 'historyBack':+ _stepHistory(-1);+ case 'historyForward':+ _stepHistory(1);+ case 'showHistory':+ await _jump(historyOnly: true);+ case 'nextWallpaper':+ if (app.panes.isEmpty) app.nextSwarmWallpaper();case 'select':if (args['id'] is String) app.selectSwarm(args['id']);case 'close':@@ -283,17 +306,32 @@ class _SwarmScreenState extends State<SwarmScreen> {swarmId: swarmId,);});- Future<void> _jump() async {+ Future<void> _jump({bool historyOnly = false}) async {final target = app.activeSwarmId;SwarmDestination? selected;await _dialog(() async {- selected = await showSwarmSwitcher(context, app, _navigation);+ selected = await showSwarmSwitcher(+ context,+ app,+ _navigation,+ historyOnly: historyOnly,+ );});if (!mounted || selected == null) return;_preparePaneFocus();await activateSwarmDestination(app, selected!, destinationSwarmId: target);}+ void _stepHistory(int direction) {+ if (direction < 0+ ? !_navigation.canGoBack(app)+ : !_navigation.canGoForward(app)) {+ return;+ }+ _preparePaneFocus();+ _navigation.step(app, direction);+ }+void _preparePaneFocus() {// The closing picker otherwise restores its previous terminal, whose focus// callback can overwrite the chosen destination during this same frame.@@ -361,6 +399,11 @@ class _SwarmScreenState extends State<SwarmScreen> {}}+ Future<void> _projectAgents(SwarmProjectGroup group) => _dialog(() async {+ final project = await showSwarmProjectAgents(context, app, group);+ if (project != null) await _projects.add(project);+ });+Future<void> _notifications() async {final target = app.activeSwarmId;SwarmAttentionEntry? selected;@@ -460,8 +503,9 @@ class _SwarmScreenState extends State<SwarmScreen> {app.movePaneDirection(dx: 0, dy: -1),ShortcutAction.movePaneDown: () =>app.movePaneDirection(dx: 0, dy: 1),- ShortcutAction.nextAgent: () => app.focusPaneBy(1),- ShortcutAction.previousAgent: () => app.focusPaneBy(-1),+ ShortcutAction.nextAgent: () => _stepHistory(1),+ ShortcutAction.previousAgent: () => _stepHistory(-1),+ ShortcutAction.showHistory: () => _jump(historyOnly: true),ShortcutAction.findTerminal: () =>app.focusedPane?.session?.find(TerminalFindAction.open),ShortcutAction.findNext: () =>@@ -579,6 +623,7 @@ class _SwarmScreenState extends State<SwarmScreen> {),onMachine: _machine,onProject: _project,+ onProjectAgents: _projectAgents,onAgent: (entry) => app.addAgentToSwarm(entry.machineId,entry.agent.id,diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dartindex dc3edb346..fd0c8ece0 100644--- a/desktop/lib/shortcuts/app_shortcuts.dart+++ b/desktop/lib/shortcuts/app_shortcuts.dart@@ -48,6 +48,7 @@ enum ShortcutAction {newSwarm,closeSwarm,reopenClosedSwarm,+ showHistory,renameSwarm,nextSwarm,previousSwarm,@@ -350,20 +351,18 @@ const List<AppShortcut> kAppShortcuts = [// --- agents ---------------------------------------------------------------//- // THE BRACKETS MEAN ONE THING NOW. They used to carry three: ⌘[ ] walked- // panes, ⇧⌘[ ] walked agents and ⌥⌘[ ] moved panes — three verbs told apart- // only by which modifiers were down. Panes moved to hjkl and arrows, so the- // brackets keep the one job they are good at: stepping along a list.+ // In Swarms, brackets follow Chrome's Back/Forward history. Directional+ // pane movement keeps its own keys; Shift-brackets step through tabs.AppShortcut(action: ShortcutAction.previousAgent,activator: SingleActivator(LogicalKeyboardKey.bracketLeft, meta: true),- label: 'Previous agent',+ label: 'Back',group: ShortcutGroup.navigate,),AppShortcut(action: ShortcutAction.nextAgent,activator: SingleActivator(LogicalKeyboardKey.bracketRight, meta: true),- label: 'Next agent',+ label: 'Forward',group: ShortcutGroup.navigate,),// ⌘P — "go to", the way VS Code's quick-open spells it, because that is what@@ -477,6 +476,12 @@ List<AppShortcut> appShortcuts({bool swarmMode = true}) => [/// Swarm bindings replace the old workspace navigation in the retained legacy/// screen. Live Swarm bindings, tooltips, and help all use this same catalog.const kSwarmShortcuts = [+ AppShortcut(+ action: ShortcutAction.showHistory,+ activator: SingleActivator(LogicalKeyboardKey.keyY, meta: true),+ label: 'Show full history',+ group: ShortcutGroup.navigate,+ ),AppShortcut(action: ShortcutAction.newSwarm,activator: SingleActivator(LogicalKeyboardKey.keyT, meta: true),diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex b727e4b6c..252768318 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -16,6 +16,8 @@ import '../core/config.dart';import '../core/build_identity.dart';import '../core/engine_availability.dart';import '../core/local_hostname.dart';+import '../core/local_git_projects.dart';+import '../core/test_run.dart';import '../core/models.dart';import '../core/retry.dart';import '../settings/config_store.dart';@@ -104,6 +106,7 @@ class MachineState {/// local machine never falls back to cloud E2EE while that identity exists.bool localOnly = false;LocalCliEndpoint? localEndpoint;+ Map<String, AgentProject> localProjects = const {};// Set when the local CLI's relay reports NO_PEER_LINK for this (non-local) machine — it needs// `harness link connect <machineId>` (the other machine's remote password) before it can// connect. The CLI owns E2EE entirely now; this is just "is trust established yet", not a@@ -162,7 +165,9 @@ class MachineState {bool get usesLocalTransport => localEndpoint != null;AgentProject? projectOf(Agent agent) =>- agent.project ?? localEndpoint?.agentProjects[agent.id];+ agent.project ??+ localProjects[agent.id] ??+ localEndpoint?.agentProjects[agent.id];Agent? get activeAgent {for (final agent in agents) {@@ -328,6 +333,9 @@ class AppNotifier extends ChangeNotifier {// now, not just this computer's own one (see src/lib/remoteRelay.ts in the harness CLI repo: a// foreign machineId is relayed to backend transparently, so the app never dials backend directly).LocalCliEndpoint? _cliEndpoint;+ late final _localGitProjects = LocalGitProjects(+ onChanged: _applyLocalGitProjects,+ );AppStatus status = AppStatus.bootstrapping;CurrentUserProfile? currentUser;@@ -344,6 +352,9 @@ class AppNotifier extends ChangeNotifier {static const maxSwarms = 24;static const maxClosedSwarms = 24;final List<ClosedSwarm> _closedSwarms = [];+ int _nextClosedSwarmId = 1;+ List<ClosedSwarm> get closedSwarms =>+ List.unmodifiable(_closedSwarms.reversed);bool get canReopenClosedSwarm =>_closedSwarms.isNotEmpty && swarms.length < maxSwarms;Swarm get activeSwarm => swarms.firstWhere(@@ -477,7 +488,12 @@ class AppNotifier extends ChangeNotifier {swarms.add(replacement);}_closedSwarms.add(- ClosedSwarm(removed, index: index, replacement: replacement),+ ClosedSwarm(+ removed,+ historyId: 'closed-${_nextClosedSwarmId++}',+ index: index,+ replacement: replacement,+ ),);if (_closedSwarms.length > maxClosedSwarms) _closedSwarms.removeAt(0);if (_activeSwarmId == id) {@@ -495,9 +511,13 @@ class AppNotifier extends ChangeNotifier {}}- void reopenClosedSwarm() {+ void reopenClosedSwarm({String? historyId}) {if (_disposed || !canReopenClosedSwarm) return;- final saved = _closedSwarms.removeLast();+ final index = historyId == null+ ? _closedSwarms.length - 1+ : _closedSwarms.indexWhere((entry) => entry.historyId == historyId);+ if (index < 0) return;+ final saved = _closedSwarms.removeAt(index);if (swarms.length == 1 && saved.replacesUntouchedWelcome(swarms.single)) {swarms.clear();}@@ -1634,12 +1654,36 @@ class AppNotifier extends ChangeNotifier {var changed = false;for (final machine in machineStates.values) {final previous = machine.localEndpoint;- if (previous == null ||- previous.computerId != endpoint.computerId ||- mapEquals(previous.agentProjects, endpoint.agentProjects)) {+ if (previous == null || previous.computerId != endpoint.computerId) {continue;}- machine.localEndpoint = endpoint;+ if (!mapEquals(previous.agentProjects, endpoint.agentProjects)) {+ machine.localEndpoint = endpoint;+ changed = true;+ }+ if (!kUnderTest) {+ for (final project in endpoint.agentProjects.values) {+ unawaited(_localGitProjects.read(project.cwd));+ }+ }+ }+ _applyLocalGitProjects();+ if (changed) notifyListeners();+ }++ void _applyLocalGitProjects() {+ if (_disposed) return;+ var changed = false;+ for (final machine in machineStates.values) {+ final projects = <String, AgentProject>{+ for (final entry+ in (machine.localEndpoint?.agentProjects ??+ const <String, AgentProject>{})+ .entries)+ entry.key: ?_localGitProjects.cached(entry.value.cwd),+ };+ if (mapEquals(machine.localProjects, projects)) continue;+ machine.localProjects = Map.unmodifiable(projects);changed = true;}if (changed) notifyListeners();@@ -2040,6 +2084,7 @@ class AppNotifier extends ChangeNotifier {unawaited(_applyNodeStatus(state, reportedOnline));}}+ if (localEndpoint != null) _updateLocalProjectSnapshot(localEndpoint);_autoConnectAndLoadMachines();notifyListeners();}@@ -3499,11 +3544,9 @@ class AppNotifier extends ChangeNotifier {terminal.status != TerminalSessionStatus.controlling &&terminal.status != TerminalSessionStatus.resyncing) {if (!_canAttachPane(existing)) return;- // A healthy pane is focus-only: opening the same daemon controller a- // second time would take over its own first stream. A frozen/closed- // pane is different — the explicit retry action needs a fresh session.- await _detachSession(existing, sendClose: true);- await _attachSession(existing);+ // Retry the dead stream in place so its output and view context remain+ // available until the next keyframe. Healthy panes stay focus-only.+ await terminal.reopen();}return;}@@ -3676,15 +3719,15 @@ class AppNotifier extends ChangeNotifier {}if (agent == null || !agent.terminalAvailable) return;- final connection = _conn(pane.machineId);final terminal = TerminalSession(machineId: pane.machineId,agentId: agent.id,agentName: agent.name,engineId: agent.engine,- send: connection.sendTerminalFrame,+ send: (type, payload) =>+ _conn(pane.machineId).sendTerminalFrame(type, payload),sendBinary: (frame) => _sendTerminalBinary(pane.machineId, frame),- onOpenStalled: connection.forceReconnect,+ onOpenStalled: () => _conn(pane.machineId).forceReconnect(),);pane.session = terminal;terminal.addListener(notifyListeners);@@ -4256,15 +4299,16 @@ class AppNotifier extends ChangeNotifier {};}- /// Throw away a tile's dead stream and open a fresh one for the same agent.- ///- /// `sendClose: false` — the stream being replaced is one the machine has- /// already lost or closed, so a close addressed to it would at best be- /// ignored and at worst land on whatever took its place.+ /// Reopen a dead stream in its existing session, keeping its rendered output.+ /// An already-lost stream needs no close addressed to its previous owner.Future<void> _reattachPane(TerminalPane pane) async {if (!_canAttachPane(pane)) return;- await _detachSession(pane, sendClose: false);- await _attachSession(pane);+ final session = pane.session;+ if (session == null) {+ await _attachSession(pane);+ } else {+ await session.reopen();+ }}bool _canAttachPane(TerminalPane pane) {@@ -4611,6 +4655,7 @@ class AppNotifier extends ChangeNotifier {@overridevoid dispose() {+ _localGitProjects.dispose();_disposed = true;_closedSwarms.clear();_daemonSupervisionTimer?.cancel();diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dartindex b7a371d0a..5de60c002 100644--- a/desktop/lib/state/swarm.dart+++ b/desktop/lib/state/swarm.dart@@ -60,28 +60,32 @@ 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 {- ClosedSwarm(Swarm swarm, {required this.index, Swarm? replacement})- : id = swarm.id,- name = swarm.name,- wallpaper = swarm.wallpaper,- gridColumns = swarm.gridColumns,- focus = swarm.panes.indexWhere((p) => p.id == swarm.focusedPaneId),- previousFocus = swarm.panes.indexWhere(- (p) => p.id == swarm.previousPaneId,- ),- zoom = swarm.panes.indexWhere((p) => p.id == swarm.zoomedPaneId),- presets = Map.unmodifiable(swarm.presets),- panes = List.unmodifiable([- for (final pane in swarm.panes)- (- machineId: pane.machineId,- agentId: pane.agentId,- composerVisible: pane.composerVisible,- pinnedSlot: swarm.pinnedSlots[pane.id],- ),- ]),- replacementId = replacement?.id,- replacementWallpaper = replacement?.wallpaper;+ ClosedSwarm(+ Swarm swarm, {+ required this.historyId,+ required this.index,+ Swarm? replacement,+ }) : id = swarm.id,+ name = swarm.name,+ wallpaper = swarm.wallpaper,+ gridColumns = swarm.gridColumns,+ focus = swarm.panes.indexWhere((p) => p.id == swarm.focusedPaneId),+ previousFocus = swarm.panes.indexWhere(+ (p) => p.id == swarm.previousPaneId,+ ),+ zoom = swarm.panes.indexWhere((p) => p.id == swarm.zoomedPaneId),+ presets = Map.unmodifiable(swarm.presets),+ panes = List.unmodifiable([+ for (final pane in swarm.panes)+ (+ machineId: pane.machineId,+ agentId: pane.agentId,+ composerVisible: pane.composerVisible,+ pinnedSlot: swarm.pinnedSlots[pane.id],+ ),+ ]),+ replacementId = replacement?.id,+ replacementWallpaper = replacement?.wallpaper;final String id;final String name;@@ -97,6 +101,7 @@ class ClosedSwarm {>panes;final String? replacementId;+ final String historyId;final int? replacementWallpaper;bool replacesUntouchedWelcome(Swarm swarm) =>diff --git a/desktop/lib/state/swarm_catalog.dart b/desktop/lib/state/swarm_catalog.dartindex 7a12a2a6d..681ea1999 100644--- a/desktop/lib/state/swarm_catalog.dart+++ b/desktop/lib/state/swarm_catalog.dart@@ -39,15 +39,24 @@ class SavedSwarmProject {required this.machineId,required this.path,required this.name,+ this.members = const [],});final String machineId;final String path;final String name;++ /// Explicit membership also works with daemons that predate project metadata.+ final List<({String machineId, String agentId})> members;String get id => '$machineId\u0000$path';- Map<String, String> toJson() => {+ Map<String, Object> toJson() => {'machineId': machineId,'path': path,'name': name,+ if (members.isNotEmpty)+ 'members': [+ for (final member in members)+ {'machineId': member.machineId, 'agentId': member.agentId},+ ],};}@@ -67,7 +76,11 @@ List<SwarmProjectGroup> swarmProjects() {final groups = <String, SwarmProjectGroup>{};final folders = <String, String>{};- for (final entry in swarmAgents(app)) {+ final agents = swarmAgents(app);+ final byId = {+ for (final a in agents) (machineId: a.machineId, agentId: a.agent.id): a,+ };+ for (final entry in agents) {final project = entry.project;if (project == null) continue;final id = project.identity(entry.machineId);@@ -83,10 +96,17 @@ List<SwarmProjectGroup> swarmProjects(}for (final item in saved) {final id = folders[item.id] ?? 'folder:${item.machineId}:${item.path}';- groups- .putIfAbsent(id, () => SwarmProjectGroup(id: id, name: item.name))- .saved =- item;+ final group = groups.putIfAbsent(+ id,+ () => SwarmProjectGroup(id: id, name: item.name),+ );+ group.saved = item;+ for (final member in item.members) {+ final agent = byId[member];+ if (agent != null && !group.agents.contains(agent)) {+ group.agents.add(agent);+ }+ }}return groups.values.toList()..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));@@ -125,6 +145,19 @@ class SwarmProjectStore extends ChangeNotifier {machineId: row['machineId'],path: row['path'],name: row['name'],+ members: {+ if (row['members'] is List)+ for (final member in (row['members'] as List).take(256))+ if (member is Map &&+ member['machineId'] is String &&+ member['agentId'] is String &&+ (member['machineId'] as String).isNotEmpty &&+ (member['agentId'] as String).isNotEmpty)+ (+ machineId: member['machineId'] as String,+ agentId: member['agentId'] as String,+ ),+ }.toList(growable: false),);if (item.path.isEmpty ||item.name.isEmpty ||diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dartindex 0444d4c15..93f9072cd 100644--- a/desktop/lib/state/swarm_navigation.dart+++ b/desktop/lib/state/swarm_navigation.dart@@ -15,6 +15,9 @@ class SwarmNavigationHistory {static const capacity = 64;final _recent = <String>[];(String, int?)? _location;+ final _trail = <(String, int?)>[];+ int _cursor = -1;+ bool _traversing = false;int _revision = 0;List<Object?>? _menuPresentation;List<SwarmDestination> _menuDestinations = const [];@@ -23,6 +26,12 @@ class SwarmNavigationHistory {void record(AppNotifier app) {final location = (app.activeSwarmId, app.focusedPaneId);if (_location == location) return;+ if (!_traversing) {+ _trail.removeRange(_cursor + 1, _trail.length);+ _trail.add(location);+ if (_trail.length > capacity * 2) _trail.removeAt(0);+ _cursor = _trail.length - 1;+ }_revision++;if (_location?.$1 != location.$1) {_remember(swarmDestinationId(location.$1));@@ -34,6 +43,43 @@ class SwarmNavigationHistory {_location = location;}+ int? _next(AppNotifier app, int direction) {+ for (+ var i = _cursor + direction;+ i >= 0 && i < _trail.length;+ i += direction+ ) {+ final (swarmId, paneId) = _trail[i];+ final swarm = app.swarms.where((s) => s.id == swarmId).firstOrNull;+ if (swarm == null ||+ (paneId == null && swarm.panes.isNotEmpty) ||+ (paneId != null && !swarm.panes.any((p) => p.id == paneId))) {+ continue;+ }+ if ((swarmId, paneId) != _location) return i;+ }+ return null;+ }++ bool canGoBack(AppNotifier app) => _next(app, -1) != null;+ bool canGoForward(AppNotifier app) => _next(app, 1) != null;++ /// Changes focus only; closed views are skipped without attaching a stream.+ void step(AppNotifier app, int direction) {+ if (direction != -1 && direction != 1) return;+ final index = _next(app, direction);+ if (index == null) return;+ final (swarmId, paneId) = _trail[index];+ _cursor = index;+ _traversing = true;+ try {+ app.selectSwarm(swarmId, attachPending: false);+ if (paneId != null) app.focusPane(paneId, reveal: true);+ } finally {+ _traversing = false;+ }+ }+void _remember(String id) {_recent.remove(id);_recent.insert(0, id);@@ -60,6 +106,7 @@ class SwarmNavigationHistory {machine.agents,machine.agents.length,machine.localEndpoint?.agentProjects,+ machine.localProjects,),];if (listEquals(_menuPresentation, presentation)) return _menuDestinations;@@ -86,6 +133,7 @@ class SwarmDestination {this.machineId,this.agentId,this.engine,+ this.closedId,Iterable<String?> searchFields = const [],}) : fields = [title.toLowerCase(),@@ -94,12 +142,26 @@ class SwarmDestination {final String id, title, detail;final String? swarmId, machineId, agentId, engine;+ final String? closedId;final bool current;final List<String> fields;bool get isSwarm => agentId == null;bool get hasView => swarmId != null;}+List<SwarmDestination> closedSwarmDestinations(AppNotifier app) => [+ for (final entry in app.closedSwarms)+ SwarmDestination(+ id: entry.historyId,+ closedId: entry.historyId,+ title: entry.name,+ detail:+ '${entry.panes.length} ${entry.panes.length == 1 ? 'view' : 'views'} · Recently closed',+ swarmId: null,+ current: false,+ ),+];+List<SwarmDestination> swarmDestinations(AppNotifier app, {List<String> recent = const [],@@ -279,6 +341,14 @@ Future<bool> activateSwarmDestination(SwarmDestination destination, {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;+ }if (destination.isSwarm) {if (!app.swarms.any((s) => s.id == destination.swarmId)) return false;app.selectSwarm(destination.swarmId!, attachPending: false);diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dartindex 787f3594a..713cc8f39 100644--- a/desktop/lib/terminal/terminal_session.dart+++ b/desktop/lib/terminal/terminal_session.dart@@ -141,6 +141,7 @@ class TerminalSession extends ChangeNotifier {int _autoReopenAttempts = 0;bool _openStallRecovered = false;bool _disposed = false;+ int _generation = 0;bool _remoteCursorVisible = true;bool _cursorBlinkPhaseVisible = true;List<int> _utf8Tail = const [];@@ -190,15 +191,47 @@ class TerminalSession extends ChangeNotifier {initialRows: initialRows,waitForViewportSize: waitForViewportSize,resetRecovery: true,+ preserveTerminal: false,);+ /// Reconnect the same agent without discarding its last usable screen.+ /// Input resumes only after the replacement stream's first keyframe.+ Future<void> reopen() async {+ if (_disposed ||+ status == TerminalSessionStatus.opening ||+ status == TerminalSessionStatus.controlling ||+ status == TerminalSessionStatus.resyncing) {+ return;+ }+ await _open(+ initialCols: _measuredViewport?.cols ?? cols,+ initialRows: _measuredViewport?.rows ?? rows,+ waitForViewportSize: false,+ resetRecovery: true,+ preserveTerminal: true,+ );+ }++ bool _isCurrent(int generation) => !_disposed && generation == _generation;+Future<void> _open({required int initialCols,required int initialRows,required bool waitForViewportSize,required bool resetRecovery,+ required bool preserveTerminal,}) async {+ if (_disposed) return;+ final generation = ++_generation;_cancelTimers();+ _abortActiveUpload();+ _inputBytes.clear();+ _pendingScrollUp = null;+ _pendingScrollLines = 0;+ _lastInputFlushAt = null;+ _lastResizeFlushAt = null;+ _renderTail = Future<void>.value();+ _inputSendTail = Future<void>.value();streamId = null;linkMode = null;errorCode = null;@@ -221,7 +254,7 @@ class TerminalSession extends ChangeNotifier {}cols = _clampCols(initialCols);rows = _clampRows(initialRows);- terminal = _newTerminal()..resize(cols, rows);+ if (!preserveTerminal) terminal = _newTerminal()..resize(cols, rows);status = TerminalSessionStatus.opening;_openRequestId ='term_${DateTime.now().microsecondsSinceEpoch}_${Random.secure().nextInt(1 << 31)}';@@ -232,9 +265,13 @@ class TerminalSession extends ChangeNotifier {final measured = await _viewportSize.future.timeout(const Duration(seconds: 2),);+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening) {+ return;+ }cols = _clampCols(measured.cols);rows = _clampRows(measured.rows);- terminal.resize(cols, rows);+ if (!preserveTerminal) terminal.resize(cols, rows);notifyListeners();} on TimeoutException {// Keep the conservative fallback when the terminal viewport cannot be@@ -242,6 +279,10 @@ class TerminalSession extends ChangeNotifier {}}+ if (!_isCurrent(generation) || status != TerminalSessionStatus.opening) {+ return;+ }+final openPayload = {'protocolVersion': protocolVersion,'requestId': _openRequestId,@@ -251,21 +292,34 @@ class TerminalSession extends ChangeNotifier {'compression': const ['zlib', 'none'],};var sent = await send('terminal_open', openPayload);+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return;+ }if (!sent) {// Most commonly transient: the local transport is mid-reconnect at this exact instant (e.g.// right after the app itself just started, or another machine's relay hiccupped a moment ago).- sent = await _recoverAndResend(openPayload);+ sent = await _recoverAndResend(openPayload, generation);+ }+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return;}if (!sent) {transportLost('Could not send terminal_open');return;}+ // An immediate ready/keyframe can arrive before send() resolves. Its+ // watchdog or live stream must not be replaced by an open timeout.+ if (status != TerminalSessionStatus.opening || streamId != null) return;// Armed unconditionally (not just on reopen attempts): a `terminal_open` sent through a silently// stale relay session never gets ANY reply — nothing else would ever notice or recover from that._resyncTimer?.cancel();_resyncTimer = Timer(resyncTimeout,- () => unawaited(_handleOpenTimeout(openPayload)),+ () => unawaited(_handleOpenTimeout(openPayload, generation)),);}@@ -273,14 +327,26 @@ class TerminalSession extends ChangeNotifier {/// itself succeeded — the relay session was silently stale (ciphertext for a dead E2EE session gets/// dropped, not rejected). Force a fresh dial and resend the SAME open request (same `requestId`, so/// a late reply for the original still matches) before giving up.- Future<void> _handleOpenTimeout(Map<String, dynamic> openPayload) async {- if (status != TerminalSessionStatus.opening || streamId != null) return;- final sent = await _recoverAndResend(openPayload);+ Future<void> _handleOpenTimeout(+ Map<String, dynamic> openPayload,+ int generation,+ ) async {+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return;+ }+ final sent = await _recoverAndResend(openPayload, generation);+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return;+ }if (sent) {_resyncTimer?.cancel();_resyncTimer = Timer(resyncTimeout,- () => unawaited(_handleOpenTimeout(openPayload)),+ () => unawaited(_handleOpenTimeout(openPayload, generation)),);return;}@@ -298,7 +364,10 @@ class TerminalSession extends ChangeNotifier {/// `forceReconnect()` resolving only means the redial STARTED, not that the transport is ready again./// Bounded by [_openStallRecovered] (one forced reconnect per open) and a fixed poll budget, so a/// persistently broken connection still fails closed instead of retrying forever.- Future<bool> _recoverAndResend(Map<String, dynamic> openPayload) async {+ Future<bool> _recoverAndResend(+ Map<String, dynamic> openPayload,+ int generation,+ ) async {final recover = onOpenStalled;if (_openStallRecovered || recover == null) return false;_openStallRecovered = true;@@ -308,7 +377,11 @@ class TerminalSession extends ChangeNotifier {// Still worth polling for readiness even if the forced reconnect itself errored.}for (var attempt = 0; attempt < 10; attempt++) {- if (_disposed || status != TerminalSessionStatus.opening) return false;+ if (!_isCurrent(generation) ||+ status != TerminalSessionStatus.opening ||+ streamId != null) {+ return false;+ }if (await send('terminal_open', openPayload)) return true;await Future.delayed(const Duration(milliseconds: 300));}@@ -317,6 +390,7 @@ class TerminalSession extends ChangeNotifier {/// Returns true when [type] belongs to this session's protocol.Future<bool> handleFrame(String type, Map<String, dynamic> payload) async {+ if (_disposed) return false;switch (type) {case 'terminal_ready':if (status != TerminalSessionStatus.opening ||@@ -386,6 +460,7 @@ class TerminalSession extends ChangeNotifier {return true;case 'terminal_closed':if (!_matchesStream(payload)) return true;+ _generation++;_cancelTimers();final code = payload['code']?.toString();final takenOver = code == 'TERMINAL_TAKEN_OVER';@@ -398,6 +473,7 @@ class TerminalSession extends ChangeNotifier {: payload['reason']?.toString();streamId = null;linkMode = null;+ _abortActiveUpload();notifyListeners();return true;case 'terminal_error':@@ -470,9 +546,11 @@ class TerminalSession extends ChangeNotifier {}Future<void> handleBinary(TerminalBinaryFrame frame) async {- if (frame.streamId != streamId) return;+ if (_disposed || frame.streamId != streamId) return;+ final generation = _generation;_renderTail = _renderTail.then((_) async {+ if (!_isCurrent(generation) || frame.streamId != streamId) return;final bytes = _decodeBinaryBytes(frame);if (bytes == null) {await _requestResync('TERMINAL_BINARY_DECODE_FAILED');@@ -485,16 +563,19 @@ class TerminalSession extends ChangeNotifier {await _requestResync('TERMINAL_KEYFRAME_INVALID');return;}+ // Publish a complete screen atomically. A damaged snapshot must+ // leave the retained screen available while resync recovers.+ final decoded = _decodeUtf8(_prepareKeyframeBytes(bytes));+ final replacement = _newTerminal(bindCallbacks: false)+ ..resize(_clampCols(nextCols), _clampRows(nextRows))+ ..write(decoded.text);+ _bindTerminal(replacement);+ terminal = replacement;cols = _clampCols(nextCols);rows = _clampRows(nextRows);- _utf8Tail = const [];- _remoteCursorVisible = true;+ _utf8Tail = decoded.tail;+ _remoteCursorVisible = terminal.cursorVisibleMode;_cursorBlinkPhaseVisible = true;- terminal = _newTerminal()..resize(cols, rows);- if (!_writeBytes(_prepareKeyframeBytes(bytes))) {- await _requestResync('TERMINAL_UTF8_DECODE_FAILED');- return;- }_expectedSeq = frame.seq + 1;_lastRenderedSeq = frame.seq;_resyncRequested = false;@@ -545,6 +626,7 @@ class TerminalSession extends ChangeNotifier {_markForAck(bytes.length);}).catchError((Object error, StackTrace stackTrace) async {+ if (!_isCurrent(generation)) return;debugPrint('[terminal-session] renderer failed for ''$machineId/$agentId: $error\n$stackTrace',@@ -630,6 +712,13 @@ class TerminalSession extends ChangeNotifier {// Most packets end on a scalar boundary. Decode their existing byte view// directly; only a split UTF-8 scalar needs a joined buffer.final combined = _utf8Tail.isEmpty ? bytes : <int>[..._utf8Tail, ...bytes];+ final decoded = _decodeUtf8(combined);+ if (decoded.text.isNotEmpty) _writeTerminalText(decoded.text);+ _utf8Tail = decoded.tail;+ return true;+ }++ ({String text, List<int> tail}) _decodeUtf8(List<int> combined) {for (var tailLength = 0;tailLength <= min(3, combined.length);@@ -641,12 +730,13 @@ class TerminalSession extends ChangeNotifier {0,combined.length - tailLength,);- if (text.isNotEmpty) _writeTerminalText(text);- _utf8Tail = tailLength == 0- ? const []- : combined.sublist(combined.length - tailLength);- return true;- } catch (_) {+ return (+ text: text,+ tail: tailLength == 0+ ? const []+ : combined.sublist(combined.length - tailLength),+ );+ } on FormatException {// A UTF-8 scalar can span at most four bytes; retain only a trailing// partial scalar before falling back to replacement rendering below.}@@ -656,10 +746,7 @@ class TerminalSession extends ChangeNotifier {// at the start of the post-cut frame. Real terminals render malformed UTF-8// as U+FFFD; resyncing the entire screen creates a second keyframe race and// cannot recover the missing pre-cut byte anyway.- final text = utf8.decode(combined, allowMalformed: true);- if (text.isNotEmpty) _writeTerminalText(text);- _utf8Tail = const [];- return true;+ return (text: utf8.decode(combined, allowMalformed: true), tail: const []);}List<int> _prepareKeyframeBytes(Uint8List bytes) {@@ -686,7 +773,7 @@ class TerminalSession extends ChangeNotifier {return <int>[...alternateBuffer, ...bytes];}- Terminal _newTerminal() {+ Terminal _newTerminal({bool bindCallbacks = true}) {final result = Terminal(maxLines: 10000,platform: TerminalTargetPlatform.macos,@@ -695,9 +782,13 @@ class TerminalSession extends ChangeNotifier {// circular-buffer bug when a remote/local switch changes viewport size.reflowEnabled: false,);+ if (bindCallbacks) _bindTerminal(result);+ return result;+ }++ void _bindTerminal(Terminal result) {result.onOutput = _onTerminalOutput;result.onResize = (width, height, _, _) => resize(width, height);- return result;}/// Sends a composed message as one turn.@@ -741,6 +832,7 @@ class TerminalSession extends ChangeNotifier {if (text.isEmpty) return false;final currentStreamId = streamId;if (currentStreamId == null) return false;+ final generation = _generation;final frame = TerminalBinaryFrame(kind: TerminalBinaryKind.paste,streamId: currentStreamId,@@ -752,7 +844,9 @@ class TerminalSession extends ChangeNotifier {compressed: false,);final sent = await sendBinary(frame);- if (!sent) transportLost('Terminal paste was not sent');+ if (!sent && _isCurrent(generation)) {+ transportLost('Terminal paste was not sent');+ }return sent;}@@ -833,6 +927,9 @@ class TerminalSession extends ChangeNotifier {if (currentStreamId == null) return false;final upload = _ActiveUpload();+ final generation = _generation;+ bool current() =>+ _isCurrent(generation) && identical(_activeUpload, upload);_activeUpload = upload;uploadProgress = UploadProgress(label: filename ?? 'image',@@ -847,6 +944,7 @@ class TerminalSession extends ChangeNotifier {'totalBytes': bytes.length,'filename': ?filename,});+ if (!current()) return false;if (!sentBegin) {transportLost('Terminal upload request was not sent');_clearUpload();@@ -857,7 +955,8 @@ class TerminalSession extends ChangeNotifier {const Duration(seconds: 10),onTimeout: () => false,);- if (!accepted || !identical(_activeUpload, upload)) {+ if (!current()) return false;+ if (!accepted) {_clearUpload();return false;}@@ -874,8 +973,8 @@ class TerminalSession extends ChangeNotifier {compressed: false,);final sentChunk = await sendBinary(frame);- if (!sentChunk || !identical(_activeUpload, upload)) {- if (sentChunk) return false; // upload was cancelled/cleared out from under us mid-send+ if (!current()) return false;+ if (!sentChunk) {transportLost('Terminal upload chunk was not sent');_clearUpload();return false;@@ -888,7 +987,8 @@ class TerminalSession extends ChangeNotifier {const Duration(minutes: 2),onTimeout: () => false,);- if (identical(_activeUpload, upload)) _clearUpload();+ if (!current()) return false;+ _clearUpload();return finished;}@@ -948,8 +1048,13 @@ class TerminalSession extends ChangeNotifier {_lastInputFlushAt = DateTime.now();final currentStreamId = streamId;if (currentStreamId == null) return;+ final generation = _generation;final queued = _inputSendTail.then((_) async {- if (!acceptsInput || streamId != currentStreamId) return;+ if (!_isCurrent(generation) ||+ !acceptsInput ||+ streamId != currentStreamId) {+ return;+ }// Numbered HERE, on the tail, not when the flush was asked for. A frame// the guard above drops — the session went `resyncing` while an earlier// send was still in flight — must not consume a seq: the daemon wants@@ -965,6 +1070,11 @@ class TerminalSession extends ChangeNotifier {offset < bytes.length;offset += kInputFrameMaxBytes) {+ if (!_isCurrent(generation) ||+ !acceptsInput ||+ streamId != currentStreamId) {+ return;+ }final end = min(offset + kInputFrameMaxBytes, bytes.length);final frame = TerminalBinaryFrame(kind: TerminalBinaryKind.input,@@ -974,6 +1084,7 @@ class TerminalSession extends ChangeNotifier {compressed: false,);final sent = await sendBinary(frame);+ if (!_isCurrent(generation)) return;if (!sent) {transportLost('Terminal input was not sent');return;@@ -981,9 +1092,9 @@ class TerminalSession extends ChangeNotifier {}});_inputSendTail = queued.catchError((_) {- transportLost('Terminal input was not sent');+ if (_isCurrent(generation)) transportLost('Terminal input was not sent');});- await queued;+ await _inputSendTail;}/// A finger on the dial moved — scroll whatever this session is showing.@@ -1042,12 +1153,14 @@ class TerminalSession extends ChangeNotifier {cols = nextCols;rows = nextRows;_lastResizeFlushAt = DateTime.now();+ final generation = _generation;final sent = await send('terminal_resize', {'streamId': streamId,'resizeSeq': _resizeSeq++,'cols': cols,'rows': rows,});+ if (!_isCurrent(generation)) return;if (!sent) transportLost('Terminal resize was not sent');notifyListeners();}@@ -1111,17 +1224,23 @@ class TerminalSession extends ChangeNotifier {}_framesSinceAck = 0;_renderedSinceAckBytes = 0;+ final generation = _generation;final sent = await send('terminal_ack', {'streamId': streamId,'lastSeq': _lastRenderedSeq,});- if (!sent) transportLost('Terminal ACK was not sent');+ if (!sent && _isCurrent(generation)) {+ transportLost('Terminal ACK was not sent');+ }}Future<void> _sendHeartbeat() async {if (!acceptsInput) return;+ final generation = _generation;final sent = await send('terminal_alive', {'streamId': streamId});- if (!sent) transportLost('Terminal heartbeat was not sent');+ if (!sent && _isCurrent(generation)) {+ transportLost('Terminal heartbeat was not sent');+ }}Future<void> _requestResync(String reason) async {@@ -1152,6 +1271,7 @@ class TerminalSession extends ChangeNotifier {Future<void> _sendResyncAttempt() async {final currentStream = streamId;+ final generation = _generation;if (!_resyncRequested || currentStream == null) return;if (_resyncAttempts >= 3) {await _recoverByReopen();@@ -1167,6 +1287,11 @@ class TerminalSession extends ChangeNotifier {'attempt': _resyncAttempts,'reason': errorCode,});+ if (!_isCurrent(generation) ||+ streamId != currentStream ||+ !_resyncRequested) {+ return;+ }if (!sent) {transportLost('Could not request terminal resync');return;@@ -1208,16 +1333,19 @@ class TerminalSession extends ChangeNotifier {initialRows: rows,waitForViewportSize: false,resetRecovery: false,+ preserveTerminal: true,);}Future<void> close() async {+ _generation++;final closingStream = streamId;_cancelTimers();_inputBytes.clear();streamId = null;linkMode = null;status = TerminalSessionStatus.closed;+ _abortActiveUpload();notifyListeners();if (closingStream != null) {await send('terminal_close', {'streamId': closingStream});@@ -1231,10 +1359,12 @@ class TerminalSession extends ChangeNotifier {// may reopen a stream someone else claimed. A WS hiccup must not quietly overwrite that into// `error`, which auto-reattach WOULD pick back up — that is exactly the two-machine tug-of-war// this status exists to prevent.- if (status == TerminalSessionStatus.closed ||+ if (_disposed ||+ status == TerminalSessionStatus.closed ||status == TerminalSessionStatus.takenOver) {return;}+ _generation++;_cancelTimers();_inputBytes.clear();streamId = null;@@ -1247,6 +1377,8 @@ class TerminalSession extends ChangeNotifier {}void _fail(String code, String? message) {+ if (_disposed) return;+ _generation++;_cancelTimers();_inputBytes.clear();streamId = null;@@ -1298,6 +1430,7 @@ class TerminalSession extends ChangeNotifier {@overridevoid dispose() {_disposed = true;+ _generation++;_cancelTimers();super.dispose();}diff --git a/desktop/lib/terminal/terminal_snapshot.dart b/desktop/lib/terminal/terminal_snapshot.dartnew file mode 100644index 000000000..44cfe8e63--- /dev/null+++ b/desktop/lib/terminal/terminal_snapshot.dart@@ -0,0 +1,46 @@+import 'package:xterm/xterm.dart';++/// Rebase the few locations a reader is using when an authoritative screen+/// replaces a buffer. Matching neighbors distinguish repeated log lines.+/// Only requested rows retain text; the replacement is scanned once.+Map<int, int> remapTerminalRows(+ Buffer before,+ Buffer after,+ Iterable<int> rows,+) {+ final wanted = rows+ .where((row) => row >= 0 && row < before.lines.length)+ .toSet();+ if (wanted.isEmpty || after.lines.length == 0) return {};+ String? text(Buffer buffer, int row) => row >= 0 && row < buffer.lines.length+ ? buffer.lines[row].getText()+ : null;+ final context = {+ for (final row in wanted)+ row: (text(before, row - 1), text(before, row), text(before, row + 1)),+ };+ final byText = <String, List<int>>{};+ for (final row in wanted) {+ (byText[context[row]!.$2!] ??= []).add(row);+ }+ final matches = <int, ({int row, int score})>{};+ String? previous;+ var current = text(after, 0);+ for (var row = 0; row < after.lines.length; row++) {+ final next = text(after, row + 1);+ for (final old in byText[current] ?? const <int>[]) {+ final neighbors = context[old]!;+ final score =+ (neighbors.$1 == previous ? 1 : 0) + (neighbors.$3 == next ? 1 : 0);+ final best = matches[old];+ if (best == null ||+ score > best.score ||+ (score == best.score && (row - old).abs() < (best.row - old).abs())) {+ matches[old] = (row: row, score: score);+ }+ }+ previous = current;+ current = next;+ }+ return {for (final entry in matches.entries) entry.key: entry.value.row};+}diff --git a/desktop/lib/widgets/swarm_project_agents.dart b/desktop/lib/widgets/swarm_project_agents.dartnew file mode 100644index 000000000..eb3b41adc--- /dev/null+++ b/desktop/lib/widgets/swarm_project_agents.dart@@ -0,0 +1,142 @@+import 'package:flutter/material.dart';++import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../state/swarm_catalog.dart';+import 'swarm_welcome.dart';++Future<SavedSwarmProject?> showSwarmProjectAgents(+ BuildContext context,+ AppNotifier app,+ SwarmProjectGroup group,+) => showAppDialog<SavedSwarmProject>(+ context: context,+ transitionDuration: Duration.zero,+ veilBlur: 0,+ builder: (_) => _ProjectAgents(app: app, group: group),+);++class _ProjectAgents extends StatefulWidget {+ const _ProjectAgents({required this.app, required this.group});+ final AppNotifier app;+ final SwarmProjectGroup group;+ @override+ State<_ProjectAgents> createState() => _ProjectAgentsState();+}++class _ProjectAgentsState extends State<_ProjectAgents> {+ late final _members = {...?widget.group.saved?.members};+ late final _automatic = {+ for (final a in widget.group.agents)+ if (a.project?.identity(a.machineId) == widget.group.id)+ (machineId: a.machineId, agentId: a.agent.id),+ };+ String _query = '';++ void _save() {+ final original = widget.group.saved;+ final anchor = widget.group.agents+ .where((a) => a.project != null)+ .firstOrNull;+ if (original == null && anchor == null) return;+ Navigator.pop(+ context,+ SavedSwarmProject(+ machineId: original?.machineId ?? anchor!.machineId,+ path: original?.path ?? anchor!.project!.root ?? anchor!.project!.cwd,+ name: original?.name ?? widget.group.name,+ members: List.unmodifiable(_members),+ ),+ );+ }++ @override+ Widget build(BuildContext context) => Dialog(+ child: SizedBox(+ width: 620,+ height: 520,+ child: Padding(+ padding: const EdgeInsets.all(20),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ widget.group.name,+ style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w500),+ ),+ const SizedBox(height: 8),+ const Text(+ 'Include agents from any machine. Matching repositories are included automatically.',+ style: TextStyle(fontSize: 12),+ ),+ const SizedBox(height: 16),+ SwarmSearchField(+ autofocus: true,+ hintText: 'Find an agent or machine…',+ onChanged: (value) => setState(() => _query = value),+ ),+ const SizedBox(height: 12),+ Expanded(+ child: ListenableBuilder(+ listenable: widget.app,+ builder: (context, _) {+ final rows = swarmAgents(widget.app, _query);+ if (rows.isEmpty) {+ return const Center(child: Text('No matching agents'));+ }+ return ListView.builder(+ itemCount: rows.length,+ itemBuilder: (context, index) {+ final agent = rows[index];+ final id = (+ machineId: agent.machineId,+ agentId: agent.agent.id,+ );+ final automatic = _automatic.contains(id);+ return CheckboxListTile(+ controlAffinity: ListTileControlAffinity.leading,+ contentPadding: EdgeInsets.zero,+ value: automatic || _members.contains(id),+ title: Text(+ agent.agent.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 13),+ ),+ subtitle: Text(+ '${agent.machine.machine.displayName}${automatic ? ' · Repository match' : ''}',+ style: const TextStyle(fontSize: 11),+ ),+ onChanged: automatic+ ? null+ : (selected) => setState(() {+ if (selected == true) {+ _members.add(id);+ } else {+ _members.remove(id);+ }+ }),+ );+ },+ );+ },+ ),+ ),+ const SizedBox(height: 12),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Cancel'),+ ),+ const SizedBox(width: 8),+ FilledButton(onPressed: _save, child: const Text('Save')),+ ],+ ),+ ],+ ),+ ),+ ),+ );+}diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dartindex 3efb02e61..d6aac2207 100644--- a/desktop/lib/widgets/swarm_switcher.dart+++ b/desktop/lib/widgets/swarm_switcher.dart@@ -9,19 +9,25 @@ import 'swarm_welcome.dart';Future<SwarmDestination?> showSwarmSwitcher(BuildContext context,AppNotifier app,- SwarmNavigationHistory history,-) => showAppDialog<SwarmDestination>(+ SwarmNavigationHistory history, {+ bool historyOnly = false,+}) => showAppDialog<SwarmDestination>(context: context,transitionDuration: Duration.zero,veilBlur: 0,veilTint: const Color(0x66000000),- builder: (_) => _SwarmSwitcher(app: app, recent: history.recent),+ builder: (_) => _SwarmSwitcher(+ app: app,+ recent: history.recent,+ history: historyOnly ? history : null,+ ),);class _SwarmSwitcher extends StatefulWidget {- const _SwarmSwitcher({required this.app, required this.recent});+ const _SwarmSwitcher({required this.app, required this.recent, this.history});final AppNotifier app;final List<String> recent;+ final SwarmNavigationHistory? history;@overrideState<_SwarmSwitcher> createState() => _SwarmSwitcherState();}@@ -47,7 +53,12 @@ class _SwarmSwitcherState extends State<_SwarmSwitcher> {void _onAppChanged() => setState(_refreshCatalog);void _refreshCatalog() {- _catalog = swarmDestinations(widget.app, recent: widget.recent);+ _catalog = widget.history == null+ ? swarmDestinations(widget.app, recent: widget.recent)+ : [+ ...widget.history!.menuDestinations(widget.app),+ ...closedSwarmDestinations(widget.app),+ ];_filter();}@@ -126,9 +137,30 @@ class _SwarmSwitcherState extends State<_SwarmSwitcher> {padding: const EdgeInsets.all(16),child: Column(children: [+ if (widget.history != null) ...[+ const Row(+ children: [+ Text(+ 'History',+ style: TextStyle(+ fontSize: 20,+ fontWeight: FontWeight.w500,+ ),+ ),+ Spacer(),+ Text(+ 'This session',+ style: TextStyle(fontSize: 11, color: Colors.white54),+ ),+ ],+ ),+ const SizedBox(height: 16),+ ],SwarmSearchField(autofocus: true,- hintText: 'Jump to an agent or swarm…',+ hintText: widget.history == null+ ? 'Jump to an agent or swarm…'+ : 'Search history…',onChanged: (value) => setState(() {_query = value;_cursor = 0;@@ -187,7 +219,9 @@ class _SwarmSwitcherState extends State<_SwarmSwitcher> {),),trailing: Text(- row.current+ row.closedId != null+ ? 'Reopen'+ : row.current? 'Current': row.isSwarm? 'Swarm'@@ -208,7 +242,9 @@ class _SwarmSwitcherState extends State<_SwarmSwitcher> {Align(alignment: Alignment.centerLeft,child: Text(- selected != null && !selected.hasView+ selected?.closedId != null+ ? '↵ Reopen swarm · Esc to close'+ : selected != null && !selected.hasView? '↵ Open view in $_targetName · Esc to close': '↑↓ or ⌃N ⌃P to choose · Return to jump · Esc to close',maxLines: 1,diff --git a/desktop/lib/widgets/swarm_welcome.dart b/desktop/lib/widgets/swarm_welcome.dartindex fe61f7d43..4df255e08 100644--- a/desktop/lib/widgets/swarm_welcome.dart+++ b/desktop/lib/widgets/swarm_welcome.dart@@ -21,6 +21,7 @@ class SwarmWelcome extends StatefulWidget {required this.onMachine,required this.onProject,required this.onAgent,+ this.onProjectAgents,});final AppNotifier notifier;final List<SavedSwarmProject> projects;@@ -29,6 +30,7 @@ class SwarmWelcome extends StatefulWidget {final VoidCallback onLinkMachine;final ValueChanged<MachineState> onMachine;final ValueChanged<SwarmProjectGroup> onProject;+ final ValueChanged<SwarmProjectGroup>? onProjectAgents;final ValueChanged<SwarmAgentRef> onAgent;@overrideState<SwarmWelcome> createState() => _SwarmWelcomeState();@@ -37,201 +39,224 @@ class SwarmWelcome extends StatefulWidget {class _SwarmWelcomeState extends State<SwarmWelcome> {String _query = '';final _selection = SwarmAgentSelection();+ Future<void> _wallpaperMenu(TapUpDetails details) async {+ final swarmId = widget.notifier.activeSwarmId;+ final overlay =+ Overlay.of(context).context.findRenderObject()! as RenderBox;+ final point = overlay.globalToLocal(details.globalPosition);+ final selected = await showMenu<String>(+ context: context,+ position: RelativeRect.fromRect(+ Rect.fromLTWH(point.dx, point.dy, 0, 0),+ Offset.zero & overlay.size,+ ),+ items: const [+ PopupMenuItem(value: 'next', child: Text('Next wallpaper')),+ ],+ );+ if (mounted &&+ selected == 'next' &&+ widget.notifier.activeSwarmId == swarmId &&+ widget.notifier.panes.isEmpty) {+ widget.notifier.nextSwarmWallpaper();+ }+ }+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);final app = widget.notifier;final groups = swarmProjects(app, widget.projects);final results = swarmAgents(app, _query);- return Stack(- fit: StackFit.expand,- children: [- LayoutBuilder(- builder: (context, constraints) => SingleChildScrollView(- child: ConstrainedBox(- constraints: BoxConstraints(minHeight: constraints.maxHeight),- child: Center(- child: Container(- constraints: const BoxConstraints(maxWidth: 1000),- padding: const EdgeInsets.fromLTRB(56, 40, 56, 62),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- const Text(- 'Start a swarm',- style: TextStyle(- fontSize: 32,- fontWeight: FontWeight.w500,- letterSpacing: -0.7,- color: Colors.white,- shadows: [- Shadow(blurRadius: 16, color: Colors.black54),- ],+ return GestureDetector(+ onSecondaryTapUp: _wallpaperMenu,+ child: Stack(+ fit: StackFit.expand,+ children: [+ LayoutBuilder(+ builder: (context, constraints) => SingleChildScrollView(+ child: ConstrainedBox(+ constraints: BoxConstraints(minHeight: constraints.maxHeight),+ child: Center(+ child: Container(+ constraints: const BoxConstraints(maxWidth: 1000),+ padding: const EdgeInsets.fromLTRB(56, 40, 56, 62),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const Text(+ 'Start a swarm',+ style: TextStyle(+ fontSize: 32,+ fontWeight: FontWeight.w500,+ letterSpacing: -0.7,+ color: Colors.white,+ shadows: [+ Shadow(blurRadius: 16, color: Colors.black54),+ ],+ ),),- ),- const SizedBox(height: 10),- const Text(- 'Choose a machine or project, or add agents individually.',- style: TextStyle(- fontSize: 13,- color: Color(0xffe0dce3),+ const SizedBox(height: 10),+ const Text(+ 'Choose a machine or project, or add agents individually.',+ style: TextStyle(+ fontSize: 13,+ color: Color(0xffe0dce3),+ ),),- ),- const SizedBox(height: 28),- Row(- children: [- Expanded(- child: SwarmSearchField(- autofocus: true,- onChanged: (v) => setState(() {- _query = v;- _selection.reset();- }),- onMove: (delta) {- if (_query.trim().isNotEmpty) {- setState(- () => _selection.move(results, delta),- );- }- },- onSubmitted: () {- final selected = _selection.selected(results);- if (_query.trim().isNotEmpty &&- selected != null) {- widget.onAgent(selected);- }- },+ const SizedBox(height: 28),+ Row(+ children: [+ Expanded(+ child: SwarmSearchField(+ autofocus: true,+ onChanged: (v) => setState(() {+ _query = v;+ _selection.reset();+ }),+ onMove: (delta) {+ if (_query.trim().isNotEmpty) {+ setState(+ () => _selection.move(results, delta),+ );+ }+ },+ onSubmitted: () {+ final selected = _selection.selected(results);+ if (_query.trim().isNotEmpty &&+ selected != null) {+ widget.onAgent(selected);+ }+ },+ ),),- ),- const SizedBox(width: 12),- FilledButton.icon(- onPressed: widget.onNewAgent,- icon: const Icon(Icons.add, size: 17),- label: const Text('New agent'),- style: FilledButton.styleFrom(- minimumSize: const Size(126, 44),- backgroundColor: grid.AppPalette.swarmAccent,- foregroundColor: grid.AppPalette.swarmTabBar,+ const SizedBox(width: 12),+ FilledButton.icon(+ onPressed: widget.onNewAgent,+ icon: const Icon(Icons.add, size: 17),+ label: const Text('New agent'),+ style: FilledButton.styleFrom(+ minimumSize: const Size(126, 44),+ backgroundColor: grid.AppPalette.swarmAccent,+ foregroundColor: grid.AppPalette.swarmTabBar,+ ),),- ),- ],- ),- const SizedBox(height: 34),- _Glass(- child: _query.trim().isNotEmpty- ? SizedBox(- height: 300,- child: SwarmAgentRows(- notifier: app,- agents: results,- selectedIndex: _selection.index(results),- onAgent: widget.onAgent,- ),- )- : LayoutBuilder(- builder: (context, size) {- final machines = _section(- 'Machines',- 'Link machine',- widget.onLinkMachine,- [- if (app.machinesLoading &&- app.machineStates.isEmpty)- const SkeletonList(rows: 3),- for (final machine- in app.machineStates.values)- _StarterRow(- icon: Icons.computer_outlined,- name: machine.machine.displayName,- note: machine.needsLink- ? 'Link required'- : machine.nodeOnline == false- ? 'Offline'- : machine.isLocalMachine- ? 'Local'- : null,- count: machine.agents.length,- onTap: () =>- widget.onMachine(machine),- ),- if (!app.machinesLoading &&- app.machineStates.isEmpty)- const Padding(- padding: EdgeInsets.symmetric(- vertical: 18,+ ],+ ),+ const SizedBox(height: 34),+ _Glass(+ child: _query.trim().isNotEmpty+ ? SizedBox(+ height: 300,+ child: SwarmAgentRows(+ notifier: app,+ agents: results,+ selectedIndex: _selection.index(results),+ onAgent: widget.onAgent,+ ),+ )+ : LayoutBuilder(+ builder: (context, size) {+ final machines = _section(+ 'Machines',+ 'Link machine',+ widget.onLinkMachine,+ [+ if (app.machinesLoading &&+ app.machineStates.isEmpty)+ const SkeletonList(rows: 3),+ for (final machine+ in app.machineStates.values)+ _StarterRow(+ icon: Icons.computer_outlined,+ name: machine.machine.displayName,+ note: machine.needsLink+ ? 'Link required'+ : machine.nodeOnline == false+ ? 'Offline'+ : machine.isLocalMachine+ ? 'Local'+ : null,+ count: machine.agents.length,+ onTap: () =>+ widget.onMachine(machine),),- child: Text(- 'Link a machine to find its agents.',+ if (!app.machinesLoading &&+ app.machineStates.isEmpty)+ const Padding(+ padding: EdgeInsets.symmetric(+ vertical: 18,+ ),+ child: Text(+ 'Link a machine to find its agents.',+ ),),- ),- ],- );- final projects = _section(- 'Projects',- 'Add project',- widget.onAddProject,- [- for (final group in groups)- _StarterRow(- icon: Icons.folder_outlined,- name: group.name,- count: group.agents.length,- onTap: () => widget.onProject(group),- ),- if (groups.isEmpty)- const Padding(- padding: EdgeInsets.symmetric(- vertical: 18,+ ],+ );+ final projects = _section(+ 'Projects',+ 'Add project',+ widget.onAddProject,+ [+ for (final group in groups)+ _StarterRow(+ icon: Icons.folder_outlined,+ name: group.name,+ count: group.agents.length,+ onTap: () =>+ widget.onProject(group),+ onManage:+ widget.onProjectAgents == null+ ? null+ : () => widget.onProjectAgents!(+ group,+ ),),- child: Text(- 'Add a working folder to start a project.',- style: TextStyle(- color: Color(0xffc5bece),- fontSize: 12,+ if (groups.isEmpty)+ const Padding(+ padding: EdgeInsets.symmetric(+ vertical: 18,+ ),+ child: Text(+ 'Add a working folder to start a project.',+ style: TextStyle(+ color: Color(0xffc5bece),+ fontSize: 12,+ ),),),- ),- ],- );- return size.maxWidth < 570- ? Column(- children: [- machines,- const SizedBox(height: 24),- projects,- ],- )- : Row(- crossAxisAlignment:- CrossAxisAlignment.start,- children: [- Expanded(child: machines),- const SizedBox(width: 36),- Expanded(child: projects),- ],- );- },- ),- ),- ],+ ],+ );+ return size.maxWidth < 570+ ? Column(+ children: [+ machines,+ const SizedBox(height: 24),+ projects,+ ],+ )+ : Row(+ crossAxisAlignment:+ CrossAxisAlignment.start,+ children: [+ Expanded(child: machines),+ const SizedBox(width: 36),+ Expanded(child: projects),+ ],+ );+ },+ ),+ ),+ ],+ ),),),),),),- ),- Positioned(- right: 14,- bottom: 10,- child: TextButton.icon(- onPressed: app.nextSwarmWallpaper,- icon: const Icon(Icons.wallpaper_outlined, size: 14),- label: const Text('Next wallpaper', style: TextStyle(fontSize: 11)),- style: TextButton.styleFrom(foregroundColor: Colors.white70),- ),- ),- ],+ ],+ ),);}@@ -497,12 +522,14 @@ class _StarterRow extends StatelessWidget {required this.count,required this.onTap,this.note,+ this.onManage,});final IconData icon;final String name;final int count;final VoidCallback onTap;final String? note;+ final VoidCallback? onManage;@overrideWidget build(BuildContext context) => Tooltip(message: name,@@ -536,7 +563,28 @@ class _StarterRow extends StatelessWidget {style: const TextStyle(fontSize: 11, color: Colors.white54),),const SizedBox(width: 8),- const Icon(Icons.chevron_right, size: 14, color: Colors.white54),+ if (onManage == null)+ const Icon(Icons.chevron_right, size: 14, color: Colors.white54)+ else+ PopupMenuButton<String>(+ tooltip: 'Project options for $name',+ padding: EdgeInsets.zero,+ constraints: const BoxConstraints(minWidth: 180),+ icon: const Icon(+ Icons.more_horiz,+ size: 16,+ color: Colors.white54,+ ),+ style: IconButton.styleFrom(+ minimumSize: const Size(24, 24),+ maximumSize: const Size(24, 24),+ padding: EdgeInsets.zero,+ ),+ itemBuilder: (_) => const [+ PopupMenuItem(value: 'agents', child: Text('Choose agents…')),+ ],+ onSelected: (_) => onManage!(),+ ),],),),diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 257a1d4b3..d95c2a76f 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -16,6 +16,7 @@ import 'rename_agent_dialog.dart';import 'terminal_composer.dart';import 'terminal_find_bar.dart';import '../terminal/terminal_search.dart';+import '../terminal/terminal_snapshot.dart';import '../terminal/terminal_binary.dart';import '../terminal/terminal_font_store.dart';import '../terminal/terminal_link_opener.dart';@@ -316,6 +317,41 @@ class _TerminalPanelState extends State<TerminalPanel>void _syncTerminal(Terminal terminal) {if (identical(_viewTerminal, terminal)) return;+ final previous = _viewTerminal.buffer;+ final next = terminal.buffer;+ final render = _laidOutTerminalView()?.renderTerminal;+ final lineHeight = render?.lineHeight;+ final position = _scrollController.hasClients+ ? _scrollController.position+ : null;+ final viewportRow = position != null && lineHeight != null+ ? (position.pixels / lineHeight).floor()+ : null;+ final viewportFraction = position != null && lineHeight != null+ ? position.pixels / lineHeight - viewportRow!+ : 0.0;+ final atEnd =+ position == null || position.maxScrollExtent - position.pixels < 1;+ final originRow = _findOriginLine?.attached == true+ ? _findOriginLine!.y+ : null;+ final originFraction = _findOriginFraction;+ final originAtEnd = _findOriginAtEnd;+ final match =+ _find?.match?.begin ??+ (_lastFindAnchor?.attached == true ? _lastFindAnchor!.offset : null);+ final selection = _controller.selection;+ final selectedText = selection == null ? null : previous.getText(selection);+ final locations = remapTerminalRows(previous, next, [+ if (!atEnd) ?viewportRow,+ ?originRow,+ ?match?.y,+ ?selection?.begin.y,+ ?selection?.end.y,+ ]);+ int row(int old) => locations[old] ?? old.clamp(0, next.lines.length - 1);+ CellOffset location(CellOffset old) =>+ CellOffset(old.x.clamp(0, terminal.viewWidth - 1), row(old.y));final wasFinding = _find != null;_closeFind(restore: false, focus: false, rebuild: false);_clearLastFind();@@ -328,19 +364,52 @@ class _TerminalPanelState extends State<TerminalPanel>_pressedLink = null;_hoveredLink = null;_observeLinkModifiers(false);- _terminalViewKey = GlobalKey<TerminalViewState>();_cancelDialInertia();_alternateScrollRemainder = 0;_cursorBlinkVisible = true;widget.session.setCursorBlinkPhase(true);+ if (position != null &&+ lineHeight != null &&+ !atEnd &&+ viewportRow != null) {+ // Correct before the retained renderer lays out the replacement, so its+ // first frame already shows the reader's location without a scroll flash.+ position.correctPixels(+ (row(viewportRow) + viewportFraction) * lineHeight,+ );+ }+ if (match != null) {+ _lastFindBuffer = next;+ _lastFindAnchor = next.createAnchorFromOffset(location(match));+ }+ if (selection != null &&+ locations.containsKey(selection.begin.y) &&+ locations.containsKey(selection.end.y)) {+ final range = selection is BufferRangeBlock+ ? BufferRangeBlock(location(selection.begin), location(selection.end))+ : BufferRangeLine(location(selection.begin), location(selection.end));+ if (next.getText(range) == selectedText) {+ _controller.setSelection(+ next.createAnchorFromOffset(range.begin),+ next.createAnchorFromOffset(range.end),+ );+ }+ }if (wasFinding) {- _findOriginBuffer = terminal.buffer;- _findOriginAtEnd = true;+ _findOriginBuffer = next;+ _findOriginAtEnd = originAtEnd;+ _findOriginFraction = originFraction;+ if (originRow != null) {+ _findOriginLine = next.createAnchor(0, row(originRow));+ }_findRevealPending = true;- _find = TerminalSearch(terminal)..addListener(_onFindChanged);+ _find = TerminalSearch(+ terminal,+ origin: match == null ? null : location(match),+ )..addListener(_onFindChanged);_find!.setQuery(_lastFindQuery, caseSensitive: _lastFindCaseSensitive);}- _afterTerminalMounted(clearSelection: true);+ _afterTerminalMounted(scrollToEnd: false);}/// Typing in the composer focuses the tile, exactly like clicking into the terminal does.@@ -465,7 +534,10 @@ class _TerminalPanelState extends State<TerminalPanel>}}- void _afterTerminalMounted({bool clearSelection = false}) {+ void _afterTerminalMounted({+ bool clearSelection = false,+ bool scrollToEnd = true,+ }) {WidgetsBinding.instance.addPostFrameCallback((_) {if (!mounted || !widget.visible) return;if (clearSelection) _controller.clearSelection();@@ -480,7 +552,7 @@ class _TerminalPanelState extends State<TerminalPanel>renderSize.height ~/ cellSize.height,);}- if (_scrollController.hasClients) {+ if (scrollToEnd && _scrollController.hasClients) {_scrollController.jumpTo(_scrollController.position.maxScrollExtent);}// Never over the composer: a rebuild that re-focuses this tile while someone is typing into@@ -1267,177 +1339,211 @@ class _TerminalHeader extends StatelessWidget {.where((a) => a.id == session.agentId).firstOrNull;final project = agent == null ? null : machine?.projectOf(agent);- final contextLabel = [- if (project != null) project.name,- if (project?.branch != null) project!.branch!,- ].join(' / ');+ final machineName = machine?.machine.displayName ?? session.machineId;+ final identityDetail = [+ session.agentName,+ machineName,+ if (project != null) project.cwd,+ if (project?.branch != null) 'Branch: ${project!.branch}',+ if (profile != null) 'Codex profile: $profile',+ 'Double-click to rename',+ ].join('\n');final strip = SizedBox(height: compact ? 38 : 46,child: Padding(padding: const EdgeInsets.symmetric(horizontal: _stripPadding),- child: Row(- children: [- EngineMark(engine: session.engineId, size: 17),- const SizedBox(width: 8),- Expanded(- // Double click the NAME to rename — the same dialog the rail's- // row opens, so one name has one way to change wherever it is- // shown. Scoped to the text rather than the whole strip: the- // strip is the drag handle, and a double click that both renamed- // and looked like the start of a drag would be two answers to one- // gesture.- child: GestureDetector(- behavior: HitTestBehavior.opaque,- onDoubleTap: () => unawaited(- showAgentRenameDialog(- context,- notifier,- session.machineId,- session.agentId,- session.agentName,+ child: LayoutBuilder(+ builder: (context, constraints) => Row(+ children: [+ EngineMark(engine: session.engineId, size: 17),+ const SizedBox(width: 10),+ Expanded(+ // Double click the NAME to rename — the same dialog the rail's+ // row opens, so one name has one way to change wherever it is+ // shown. Scoped to the text rather than the whole strip: the+ // strip is the drag handle, and a double click that both renamed+ // and looked like the start of a drag would be two answers to one+ // gesture.+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onDoubleTap: () => unawaited(+ showAgentRenameDialog(+ context,+ notifier,+ session.machineId,+ session.agentId,+ session.agentName,+ ),),- ),- child: Tooltip(- message: profile == null- ? 'Double-click to rename'- : 'Codex profile: $profile\nDouble-click to rename',- waitDuration: const Duration(milliseconds: 700),- child: Text(- // The profile path's basename used to trail the name here, but for the- // default profile that basename is literally the hidden `.codex` folder —- // meaningless clutter on every ordinary codex agent. The tooltip above still- // carries the full path for whoever actually needs it.- session.agentName,- overflow: TextOverflow.ellipsis,- style: TextStyle(- color: AppColors.text,- fontFamily: AppFonts.sans,- fontSize: 13,- fontWeight: FontWeight.w600,+ child: Tooltip(+ message: identityDetail,+ waitDuration: const Duration(milliseconds: 700),+ child: Text(+ // The profile path's basename used to trail the name here, but for the+ // default profile that basename is literally the hidden `.codex` folder —+ // meaningless clutter on every ordinary codex agent. The tooltip above still+ // carries the full path for whoever actually needs it.+ session.agentName,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: AppColors.text,+ fontFamily: AppFonts.sans,+ fontSize: 13,+ fontWeight: FontWeight.w600,+ ),),),),),- ),- if (compact && status == null && project != null) ...[- const SizedBox(width: 12),- Flexible(- child: Tooltip(- message:- '${project.cwd}\n${project.remote ?? project.root ?? ""}',- child: Text(- contextLabel,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(fontSize: 11, color: AppColors.textSoft),+ if (compact && status == null && project?.branch != null) ...[+ const SizedBox(width: 16),+ Tooltip(+ message: '${project!.branch}\n${project.cwd}',+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(+ LucideIcons.gitBranch,+ size: 12,+ color: AppColors.mutedStrong,+ ),+ const SizedBox(width: 5),+ ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: math.min(112, constraints.maxWidth * .22),+ ),+ child: Text(+ project.branch!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontSize: 11,+ color: AppColors.textSoft,+ ),+ ),+ ),+ ],),),- ),- ],- if (compact && status == null) ...[- const SizedBox(width: 12),- Flexible(- child: Tooltip(- message: machine?.machine.displayName ?? session.machineId,- child: Text(- machine?.machine.displayName ?? session.machineId,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- fontSize: 11,- color: AppColors.mutedStrong,- ),+ ],+ if (compact && status == null) ...[+ const SizedBox(width: 16),+ ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: math.min(156, constraints.maxWidth * .28),),- ),- ),- ],- const SizedBox(width: 6),- if (status != null)- Flexible(- fit: FlexFit.tight,- child: Align(- alignment: Alignment.centerRight,child: Tooltip(- message: status.detail,- child: TextButton(- onPressed: canReconnect- ? () => notifier.selectAgent(- session.machineId,- session.agentId,- )- : null,- style: TextButton.styleFrom(- foregroundColor: color,- disabledForegroundColor: AppColors.textSoft,- minimumSize: Size.zero,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- padding: const EdgeInsets.symmetric(- horizontal: 6,- vertical: 4,- ),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(status.icon, size: 14),- const SizedBox(width: 6),- Flexible(- child: Text(- status.label,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: const TextStyle(fontSize: 11),+ message: machineName,+ child: constraints.maxWidth < 380 && project?.branch != null+ ? Icon(+ machine?.isLocalMachine == true+ ? Icons.laptop_mac+ : Icons.desktop_mac,+ size: 14,+ color: AppColors.mutedStrong,+ )+ : Text(+ machineName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontSize: 11,+ color: AppColors.mutedStrong,),),- ],+ ),+ ),+ ],+ const SizedBox(width: 8),+ if (status != null)+ ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: constraints.maxWidth * .42,+ ),+ child: Align(+ alignment: Alignment.centerRight,+ child: Tooltip(+ message: status.detail,+ child: TextButton(+ onPressed: canReconnect+ ? () => notifier.selectAgent(+ session.machineId,+ session.agentId,+ )+ : null,+ style: TextButton.styleFrom(+ foregroundColor: color,+ disabledForegroundColor: AppColors.textSoft,+ minimumSize: Size.zero,+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ padding: const EdgeInsets.symmetric(+ horizontal: 6,+ vertical: 4,+ ),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(status.icon, size: 14),+ const SizedBox(width: 6),+ Flexible(+ child: Text(+ status.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 11),+ ),+ ),+ ],+ ),),),),+ )+ else if (!compact)+ Padding(+ padding: const EdgeInsets.all(4),+ child: Icon(Icons.circle, size: 8, color: color),),- )- else if (!compact)- Padding(- padding: const EdgeInsets.all(4),- child: Icon(Icons.circle, size: 8, color: color),- ),- // Which of the three paths carries this pane's bytes. Absent for a local machine's own- // terminal, which has no such distinction and so gets no badge.- //- // The wire word and the word a person reads differ for the middle state, deliberately:- // the CLI sends 'turn' (it is a TURN allocation) but both middle and last are relays to- // a reader, so they read as "relay" and "ws". 'relay' on the wire kept its original- // meaning — the backend WebSocket — so an older CLI is never mislabelled.- if (!compact && session.linkMode != null)- Padding(- padding: const EdgeInsets.symmetric(horizontal: 2),- child: _LinkModeMark(mode: session.linkMode!),- ),- // Before the close button: pinning is the rarer act, and a control- // that appears to the LEFT of the one people aim for by muscle- // memory cannot shift it under their pointer.- if (!compact && onTogglePin != null)- PanePinButton(pinned: pinned, onPressed: onTogglePin!),- if (compact && onToggleComposer != null)- IconButton(- tooltip: composerVisible- ? 'Hide message composer'- : 'Show message composer',- onPressed: onToggleComposer,- icon: Icon(- Icons.edit_note,- size: 18,- color: composerVisible- ? AppColors.text- : AppColors.mutedStrong,+ // Which of the three paths carries this pane's bytes. Absent for a local machine's own+ // terminal, which has no such distinction and so gets no badge.+ //+ // The wire word and the word a person reads differ for the middle state, deliberately:+ // the CLI sends 'turn' (it is a TURN allocation) but both middle and last are relays to+ // a reader, so they read as "relay" and "ws". 'relay' on the wire kept its original+ // meaning — the backend WebSocket — so an older CLI is never mislabelled.+ if (!compact && session.linkMode != null)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 2),+ child: _LinkModeMark(mode: session.linkMode!),),- constraints: const BoxConstraints.tightFor(- width: 28,- height: 28,+ // Before the close button: pinning is the rarer act, and a control+ // that appears to the LEFT of the one people aim for by muscle+ // memory cannot shift it under their pointer.+ if (!compact && onTogglePin != null)+ PanePinButton(pinned: pinned, onPressed: onTogglePin!),+ if (compact && onToggleComposer != null)+ IconButton(+ tooltip: composerVisible+ ? 'Hide message composer'+ : 'Show message composer',+ onPressed: onToggleComposer,+ icon: Icon(+ Icons.edit_note,+ size: 18,+ color: composerVisible+ ? AppColors.text+ : AppColors.mutedStrong,+ ),+ constraints: const BoxConstraints.tightFor(+ width: 28,+ height: 28,+ ),+ padding: EdgeInsets.zero,),- padding: EdgeInsets.zero,- ),- if (onClose != null) PaneCloseButton(onPressed: onClose!),- ],+ if (onClose != null) PaneCloseButton(onPressed: onClose!),+ ],+ ),),),);diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 6677150db..c9d5389b5 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -15,9 +15,12 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {private var canFind = falseprivate var canClosePane = falseprivate var canCreateSwarm = false- private let recentAgentsMenu = NSMenu(title: "Recent Agents")- private let recentSwarmsMenu = NSMenu(title: "Recent Swarms")+ private let historyMenu = NSMenu(title: "History")+ private var canGoBack = false+ private var canGoForward = false+ private var canChangeWallpaper = falseprivate var history: [SwarmHistoryEntry] = []+ private var closedHistory: [SwarmHistoryEntry] = []init(window: NSWindow, messenger: FlutterBinaryMessenger) {self.window = window@@ -36,8 +39,11 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {self.canReopen = state["canReopen"] as? Bool == trueself.canFind = state["canFind"] as? Bool == trueself.canClosePane = state["canClosePane"] as? Bool == true+ self.canGoBack = state["canGoBack"] as? Bool == true+ self.canGoForward = state["canGoForward"] as? Bool == true+ self.canChangeWallpaper = state["canChangeWallpaper"] as? Bool == trueself.canCreateSwarm = (state["tabs"] as? [Any] ?? []).count < 24- self.updateHistory(state["history"] as? [[String: Any]] ?? [])+ self.updateHistory(state["history"] as? [[String: Any]] ?? [], closed: state["closedHistory"] as? [[String: Any]] ?? [])self.strip.update(state)result(nil)default: result(FlutterMethodNotImplemented)@@ -115,6 +121,7 @@ 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, "Add Agent to Swarm…", "f", "addAgent", [.command, .shift])file.addItem(.separator())add(file, "Link Machine…", "", "linkMachine")@@ -124,22 +131,12 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {add(file, "Close Swarm", "w", "closeActive")install(file, at: 1)- let historyMenu = NSMenu(title: "History")- add(historyMenu, "Jump to Agent or Swarm…", "p", "jump")- historyMenu.addItem(.separator())- for menu in [recentAgentsMenu, recentSwarmsMenu] {- let item = NSMenuItem(title: menu.title, action: nil, keyEquivalent: "")- item.submenu = menu- historyMenu.addItem(item)- }- populateHistoryMenu(recentAgentsMenu, entries: history.filter { !$0.swarm }, empty: "No Recent Agents")- populateHistoryMenu(recentSwarmsMenu, entries: history.filter(\.swarm), empty: "No Recent Swarms")- historyMenu.addItem(.separator())- add(historyMenu, "Reopen Closed Swarm", "t", "reopen", [.command, .shift])+ rebuildHistoryMenu()let windowIndex = main.items.firstIndex(where: { $0.title == "Window" }) ?? main.numberOfItemsinstall(historyMenu, at: windowIndex)let swarm = NSMenu(title: "Swarm")+ add(swarm, "Jump to Agent or Swarm…", "p", "jump")add(swarm, "Rename Swarm…", "r", "renameActive", [.command, .shift])swarm.addItem(.separator())add(swarm, "Next Swarm", "]", "next", [.command, .shift])@@ -147,33 +144,64 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {swarm.addItem(.separator())add(swarm, "Agents Needing Input…", "i", "notifications", [.command, .shift])install(swarm, at: windowIndex + 1)+ if let view = main.item(withTitle: "View")?.submenu {+ view.addItem(.separator())+ add(view, "Next Wallpaper", "", "nextWallpaper")+ }installTerminalFindMenu(main)}- private func updateHistory(_ rows: [[String: Any]]) {+ private func updateHistory(_ rows: [[String: Any]], closed: [[String: Any]] = []) {let entries = rows.prefix(64).compactMap(SwarmHistoryEntry.init)- guard entries != history else { return }+ let closedEntries = closed.prefix(24).compactMap(SwarmHistoryEntry.init)+ guard entries != history || closedEntries != closedHistory else { return }history = entries- populateHistoryMenu(recentAgentsMenu, entries: entries.filter { !$0.swarm }, empty: "No Recent Agents")- populateHistoryMenu(recentSwarmsMenu, entries: entries.filter(\.swarm), empty: "No Recent Swarms")+ closedHistory = closedEntries+ rebuildHistoryMenu()+ }++ private func rebuildHistoryMenu() {+ historyMenu.removeAllItems()+ func command(_ title: String, _ key: String, _ action: String) {+ let item = NSMenuItem(title: title, action: #selector(menuAction(_:)), keyEquivalent: key)+ item.target = self+ item.representedObject = action+ item.keyEquivalentModifierMask = [.command]+ historyMenu.addItem(item)+ }+ command("Back", "[", "historyBack")+ command("Forward", "]", "historyForward")+ historyMenu.addItem(.separator())+ appendHistorySection("Recently Closed", entries: Array(closedHistory.prefix(10)), closed: true)+ historyMenu.addItem(.separator())+ appendHistorySection("Recently Visited", entries: Array(history.prefix(15)), closed: false)+ historyMenu.addItem(.separator())+ command("Show Full History", "y", "showHistory")}- private func populateHistoryMenu(_ menu: NSMenu, entries: [SwarmHistoryEntry], empty: String) {- menu.removeAllItems()- for entry in entries.prefix(12) {- let item = NSMenuItem(title: entry.title, action: #selector(historyAction(_:)), keyEquivalent: "")+ private func appendHistorySection(_ title: String, entries: [SwarmHistoryEntry], closed: Bool) {+ if #available(macOS 14.0, *) {+ historyMenu.addItem(NSMenuItem.sectionHeader(title: title))+ } else {+ let label = NSMenuItem(title: title, action: nil, keyEquivalent: "")+ label.isEnabled = false+ historyMenu.addItem(label)+ }+ for entry in entries {+ let title = entry.title.count > 76 ? String(entry.title.prefix(48)) + "…" + String(entry.title.suffix(24)) : entry.title+ let item = NSMenuItem(title: title, action: closed ? #selector(closedHistoryAction(_:)) : #selector(historyAction(_:)), keyEquivalent: "")item.target = selfitem.representedObject = entry.id- item.toolTip = entry.detail+ item.toolTip = entry.title + "\n" + entry.detailitem.state = entry.current ? .on : .offitem.image = NSImage(systemSymbolName: entry.swarm ? "rectangle.split.2x2" : "terminal",accessibilityDescription: nil)- menu.addItem(item)+ historyMenu.addItem(item)}- if menu.items.isEmpty {- let item = NSMenuItem(title: empty, action: nil, keyEquivalent: "")+ if entries.isEmpty {+ let item = NSMenuItem(title: closed ? "No Recently Closed Swarms" : "No Recent Visits", action: nil, keyEquivalent: "")item.isEnabled = false- menu.addItem(item)+ historyMenu.addItem(item)}}@@ -202,7 +230,12 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {if menuItem.action == #selector(historyAction(_:)) {return actionsEnabled && history.contains(where: { $0.id == action })}+ if menuItem.action == #selector(closedHistoryAction(_:)) {+ return actionsEnabled && canReopen && closedHistory.contains(where: { $0.id == action })+ }return actionsEnabled && (action != "reopen" || canReopen) &&+ (action != "nextWallpaper" || canChangeWallpaper) &&+ (action != "historyBack" || canGoBack) && (action != "historyForward" || canGoForward) &&(action != "new" || canCreateSwarm) && (action != "closePane" || canClosePane) &&(!["findTerminal", "findNext", "findPrevious"].contains(action) || canFind)}@@ -216,6 +249,11 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {guard validateMenuItem(sender), let id = sender.representedObject as? String else { return }channel.invokeMethod("historyDestination", arguments: ["id": id])}++ @objc private func closedHistoryAction(_ sender: NSMenuItem) {+ guard validateMenuItem(sender), let id = sender.representedObject as? String else { return }+ channel.invokeMethod("reopenHistory", arguments: ["id": id])+ }}private struct SwarmHistoryEntry: Equatable {diff --git a/desktop/pubspec.lock b/desktop/pubspec.lockindex e396a461f..63fb6b771 100644--- a/desktop/pubspec.lock+++ b/desktop/pubspec.lock@@ -400,7 +400,7 @@ packages:source: hostedversion: "4.1.0"path:- dependency: transitive+ dependency: "direct main"description:name: pathsha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yamlindex 6121f1f5d..01292b708 100644--- a/desktop/pubspec.yaml+++ b/desktop/pubspec.yaml@@ -61,6 +61,7 @@ dependencies:# read".sqlite3: ^2.4.0desktop_drop: ^0.8.4+ path: ^1.9.1dev_dependencies:flutter_test:diff --git a/desktop/test/local_git_projects_test.dart b/desktop/test/local_git_projects_test.dartnew file mode 100644index 000000000..e3abdf348--- /dev/null+++ b/desktop/test/local_git_projects_test.dart@@ -0,0 +1,76 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/local_git_projects.dart';++void main() {+ test('local Git metadata shares repository identity and watches worktree branches', () async {+ final fixture = await Directory.systemTemp.createTemp(+ 'harness-git-context-',+ );+ final root = fixture.path;+ final main = Directory('$root/repo/.git');+ await main.create(recursive: true);+ await File(+ '${main.path}/config',+ ).writeAsString('[remote "origin"]\n url = [email protected]:Team/Repo.git\n');+ await File('${main.path}/HEAD').writeAsString('ref: refs/heads/main\n');+ await Directory('$root/repo/src').create();+ final tree = Directory('$root/feature');+ await tree.create();+ final meta = Directory('${main.path}/worktrees/feature');+ await meta.create(recursive: true);+ await File('${tree.path}/.git').writeAsString('gitdir: ${meta.path}\n');+ await File('${meta.path}/commondir').writeAsString('../..\n');+ await File('${meta.path}/HEAD')+ .writeAsString('ref: refs/heads/feature/login\n');+ final changed = Completer<void>();+ late LocalGitProjects reader;+ reader = LocalGitProjects(+ onChanged: () {+ if (reader.cached(tree.path)?.branch == 'feature/fix' &&+ !changed.isCompleted) {+ changed.complete();+ }+ },+ );+ addTearDown(() async {+ reader.dispose();+ await fixture.delete(recursive: true);+ });+ await Future.wait([reader.read('$root/repo/src'), reader.read(tree.path)]);+ final project = reader.cached('$root/repo/src')!;+ expect(project.root, '$root/repo');+ expect(project.branch, 'main');+ expect(project.remote, 'github.com/team/repo');+ expect(reader.cached(tree.path)!.remote, project.remote);+ expect(reader.cached(tree.path)!.branch, 'feature/login');+ await reader.read(tree.path);+ expect(reader.cached('$root/repo/src'), same(project));+ await File('${meta.path}/HEAD')+ .writeAsString('ref: refs/heads/feature/fix\n');+ await changed.future.timeout(const Duration(seconds: 4));+ expect(reader.cached(tree.path)!.branch, 'feature/fix');+ expect(reader.cached('$root/repo/src'), same(project));+ });++ test(+ 'remote identity removes credentials and respects host and port semantics',+ () {+ expect(+ canonicalGitRemote('https://user:[email protected]/TEAM/Repo.git'),+ 'github.com/team/repo',+ );+ expect(+ canonicalGitRemote('ssh://[email protected]:2222/Team/Repo.git'),+ 'example.org:2222/Team/Repo',+ );+ expect(+ canonicalGitRemote('[email protected]:Team/Repo.git'),+ 'example.org/Team/Repo',+ );+ expect(canonicalGitRemote('file:///private/repo'), isNull);+ },+ );+}diff --git a/desktop/test/shortcuts_deck_test.dart b/desktop/test/shortcuts_deck_test.dartindex c8d64981b..6083babf3 100644--- a/desktop/test/shortcuts_deck_test.dart+++ b/desktop/test/shortcuts_deck_test.dart@@ -88,7 +88,7 @@ void main() {// ⌘] is two caps. Ctrl+Tab switches swarms.final next = find.ancestor(- of: find.text('Next agent'),+ of: find.text('Forward'),matching: find.byType(Row),);expect(@@ -150,7 +150,7 @@ void main() {await pumpDeck(tester, 900);- final label = tester.renderObject<RenderBox>(find.text('Next agent'));+ final label = tester.renderObject<RenderBox>(find.text('Forward'));expect(label.size.height,lessThan(KeyCap.height),diff --git a/desktop/test/swarm_history_test.dart b/desktop/test/swarm_history_test.dartindex a25ffa8b8..55f3064eb 100644--- a/desktop/test/swarm_history_test.dart+++ b/desktop/test/swarm_history_test.dart@@ -16,6 +16,57 @@ import 'swarm_state_test.dart' show createApp;import 'swarm_switcher_test.dart' show jumpField;void main() {+ test('Back and Forward retain exact pane locations and discard a branched future', () async {+ final app = createApp();+ addTearDown(app.dispose);+ final history = SwarmNavigationHistory();+ app.addListener(() => history.record(app));+ final first = app.adoptSessionForTest(terminal('a0', []));+ history.record(app);+ final original = app.activeSwarmId;+ final second = app.adoptSessionForTest(terminal('a1', []));+ history.record(app);+ app.newSwarm(name: 'Other');+ final other = app.activeSwarmId;+ await app.addAgentToSwarm('m', 'a0');+ history.step(app, -1);+ expect(app.activeSwarmId, original);+ expect(app.focusedPaneId, second.id);+ expect(history.canGoForward(app), isTrue);+ history.step(app, 1);+ expect(app.activeSwarmId, other);+ history.step(app, -1);+ app.focusPane(first.id);+ expect(history.canGoForward(app), isFalse);+ await app.closePane(second.id);+ history.step(app, -1);+ expect(app.focusedPaneId, isNot(second.id));+ expect(app.allPanes.where((p) => p.agentId == 'a1'), isEmpty);+ });++ test(+ 'a chosen closed Swarm restores independently and stale tokens stay inert',+ () async {+ final app = createApp();+ addTearDown(app.dispose);+ final first = app.activeSwarmId;+ app.renameSwarm(first, 'First');+ app.newSwarm(name: 'Second');+ final second = app.activeSwarmId;+ app.newSwarm(name: 'Keep');+ await app.closeSwarm(first);+ final restoreFirst = app.closedSwarms.single.historyId;+ await app.closeSwarm(second);+ app.reopenClosedSwarm(historyId: restoreFirst);+ expect(app.activeSwarm.name, 'First');+ expect(app.closedSwarms.single.name, 'Second');+ await app.closeSwarm(first);+ final before = app.swarms.toList();+ app.reopenClosedSwarm(historyId: restoreFirst);+ expect(app.swarms, before);+ expect(app.closedSwarms, hasLength(2));+ },+ );test('recent menus retain snapshots through output and refresh live identities',() async {@@ -157,6 +208,26 @@ void main() {await tester.pump(const Duration(milliseconds: 10));expect(otherInput.single.bytes, [27, 91, 68]);+ await native('historyBack');+ await tester.pump();+ expect(app.focusedPaneId, first.id);+ await native('historyForward');+ await tester.pump();+ expect(app.focusedPaneId, second.id);+ final historyView = native('showHistory');+ await tester.pump();+ final historyField = find.byWidgetPredicate(+ (w) => w is TextField && w.decoration?.hintText == 'Search history…',+ );+ expect(historyField, findsOneWidget);+ await tester.enterText(historyField, 'Agent 0');+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ await historyView;+ expect(app.focusedPaneId, first.id);+ app.focusPane(second.id);+await app.closePane(first.id);await tester.pump();await native('historyDestination', {'id': id});diff --git a/desktop/test/swarm_project_members_test.dart b/desktop/test/swarm_project_members_test.dartnew file mode 100644index 000000000..af797941d--- /dev/null+++ b/desktop/test/swarm_project_members_test.dart@@ -0,0 +1,103 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/ws/local_cli_discovery.dart';++import 'swarm_state_test.dart' show createApp, MemoryStore;++void main() {+ testWidgets(+ 'project membership includes an older remote daemon and survives reopening',+ (tester) async {+ tester.view.physicalSize = const Size(1280, 900);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ final app = createApp();+ app.machineStates['m']!.localEndpoint = LocalCliEndpoint(+ computerId: 'local',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ agentProjects: const {+ 'a0': AgentProject(name: 'Workshop', cwd: '/work/workshop'),+ 'a1': AgentProject(name: 'Workshop', cwd: '/work/workshop'),+ },+ );+ app.machineStates['remote'] =+ MachineState(+ const Machine(+ machineId: 'remote',+ name: 'iMac Home',+ authMode: MachineAuthMode.remote,+ ),+ )+ ..agents = [+ const Agent(+ id: 'chess',+ name: 'Chess Set',+ terminalAvailable: true,+ ),+ const Agent(+ id: 'unrelated',+ name: 'Other work',+ terminalAvailable: true,+ ),+ ];+ final memory = MemoryStore();+ final projects = SwarmProjectStore(storage: memory);+ await projects.load();+ await tester.pumpWidget(+ MaterialApp(+ home: SwarmScreen(+ notifier: app,+ nativeTabs: false,+ projectStore: projects,+ ),+ ),+ );+ await tester.pump();+ await tester.tap(find.byTooltip('Project options for Workshop'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Choose agents…'));+ await tester.pumpAndSettle();+ await tester.enterText(+ find.byWidgetPredicate(+ (w) =>+ w is TextField &&+ w.decoration?.hintText == 'Find an agent or machine…',+ ),+ 'Chess Set',+ );+ await tester.pump();+ await tester.tap(find.widgetWithText(CheckboxListTile, 'Chess Set'));+ await tester.tap(find.text('Save'));+ await tester.pumpAndSettle();+ final restored = SwarmProjectStore(storage: memory);+ await restored.load();+ final group = swarmProjects(app, restored.projects).single;+ expect(group.agents.map((a) => a.agent.id), ['a0', 'a1', 'chess']);+ expect(+ app.panes,+ isEmpty,+ reason:+ 'Editing project membership does not attach or take over terminals',+ );+ await tester.tap(find.text('Workshop'));+ await tester.pump(const Duration(milliseconds: 100));+ expect(app.panes.map((p) => (p.machineId, p.agentId)), [+ ('m', 'a0'),+ ('m', 'a1'),+ ('remote', 'chess'),+ ]);+ expect(app.activeSwarm.name, 'Workshop');+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ projects.dispose();+ restored.dispose();+ },+ );+}diff --git a/desktop/test/terminal_pane_test.dart b/desktop/test/terminal_pane_test.dartindex cfca5baa6..66825607e 100644--- a/desktop/test/terminal_pane_test.dart+++ b/desktop/test/terminal_pane_test.dart@@ -405,9 +405,20 @@ void main() {final connection = _TerminalConnection();final app = _notifier(connectionForTest: (_) => connection);final machine = _machine(app, 'm1', ['a']);- final pane = app.adoptSessionForTest(_session('m1', 'a'));+ machine.nodeOnline = true;+ machine.terminalCapabilityAvailable = true;+ final attaching = app.addAgentToSwarm('m1', 'a');+ final pane = app.panes.single;+ pane.session!.reportViewport(120, 40);+ await attaching;+ expect(+ connection.sent.where((type) => type == 'terminal_open'),+ hasLength(1),+ );+ connection.sent.clear();final dead = pane.session!;dead.transportLost('Harness reconnected; restoring terminal…');+ machine.nodeOnline = false;dead.terminal.write('Last useful result');await app.selectAgent('m1', 'a');@@ -418,7 +429,7 @@ void main() {machine.terminalCapabilityAvailable = true;final retry = app.selectAgent('m1', 'a');await Future<void>.delayed(Duration.zero);- expect(pane.session, isNot(same(dead)));+ expect(pane.session, same(dead));pane.session!.reportViewport(120, 40);await retry;expect(diff --git a/desktop/test/terminal_panel_presentation_test.dart b/desktop/test/terminal_panel_presentation_test.dartindex 323a2bd05..a54de682a 100644--- a/desktop/test/terminal_panel_presentation_test.dart+++ b/desktop/test/terminal_panel_presentation_test.dart@@ -54,7 +54,8 @@ void main() {revision.value = 2;await tester.pump();expect(find.text('Renamed terminal'), findsOneWidget);- expect(find.text('Terminal project / fast-focus'), findsOneWidget);+ expect(find.text('fast-focus'), findsOneWidget);+ expect(find.byTooltip('fast-focus\n/work/terminal'), findsOneWidget);session.status = TerminalSessionStatus.takenOver;revision.value = 3;await tester.pump();diff --git a/desktop/test/terminal_reconnect_race_test.dart b/desktop/test/terminal_reconnect_race_test.dartnew file mode 100644index 000000000..95c8ce2d4--- /dev/null+++ b/desktop/test/terminal_reconnect_race_test.dart@@ -0,0 +1,158 @@+import 'dart:async';+import 'dart:convert';+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_session.dart';++class _Peer {+ final sent = <({String type, Map<String, dynamic> payload})>[];+ final binary = <TerminalBinaryFrame>[];+ Completer<bool>? oldInput;+ Completer<bool>? oldUpload;+ late final session = TerminalSession(+ machineId: 'fixture',+ agentId: 'agent',+ agentName: 'Fixture',+ engineId: 'codex',+ send: (type, payload) {+ sent.add((type: type, payload: Map.of(payload)));+ if (type == 'terminal_chunked_upload_begin' && oldUpload != null) {+ final pending = oldUpload!;+ oldUpload = null;+ return pending.future;+ }+ return Future.value(true);+ },+ sendBinary: (frame) {+ binary.add(frame);+ if (frame.kind == TerminalBinaryKind.input && oldInput != null) {+ final pending = oldInput!;+ oldInput = null;+ return pending.future;+ }+ return Future.value(true);+ },+ );++ Future<void> ready(String stream) async {+ await session.handleFrame('terminal_ready', {+ 'requestId': sent+ .lastWhere((f) => f.type == 'terminal_open')+ .payload['requestId'],+ 'protocolVersion': 3,+ 'agentId': 'agent',+ 'streamId': stream,+ });+ await session.handleBinary(+ TerminalBinaryFrame(+ kind: TerminalBinaryKind.keyframe,+ streamId: stream,+ seq: 0,+ bytes: utf8.encode('Screen $stream'),+ compressed: false,+ cols: 80,+ rows: 24,+ ),+ );+ }+}++void main() {+ test('late output and input failure cannot repaint or freeze a replacement stream', () async {+ final peer = _Peer();+ final session = peer.session;+ addTearDown(session.dispose);+ await session.open();+ await peer.ready('old');+ final oldSend = Completer<bool>();+ peer.oldInput = oldSend;+ session.terminal.textInput('old input');+ await Future<void>.delayed(Duration.zero);+ expect(peer.binary, hasLength(1));+ final oldOutput = session.handleBinary(+ TerminalBinaryFrame(+ kind: TerminalBinaryKind.output,+ streamId: 'old',+ seq: 1,+ bytes: utf8.encode('stale repaint'),+ compressed: false,+ ),+ );+ session.transportLost();+ await session.reopen();+ await oldOutput;+ expect(session.terminal.buffer.getText(), isNot(contains('stale repaint')));+ await peer.ready('new');+ session.terminal.textInput('new input');+ await Future<void>.delayed(Duration.zero);+ expect(+ peer.binary,+ hasLength(2),+ reason: 'New input is not queued behind the old transport',+ );+ expect(peer.binary.last.streamId, 'new');+ expect(peer.binary.last.seq, 0);+ expect(utf8.decode(peer.binary.last.bytes), 'new input');+ oldSend.complete(false);+ await Future<void>.delayed(Duration.zero);+ expect(session.status, TerminalSessionStatus.controlling);+ expect(session.terminal.buffer.getText(), contains('Screen new'));+ expect(+ peer.binary,+ hasLength(2),+ reason: 'Old keystrokes are never replayed',+ );+ });++ test(+ 'a late upload failure cannot cancel a new upload after reconnect',+ () async {+ final peer = _Peer();+ final session = peer.session;+ addTearDown(session.dispose);+ await session.open();+ await peer.ready('old');+ final oldBegin = Completer<bool>();+ peer.oldUpload = oldBegin;+ final oldUpload = session.pasteImage(Uint8List.fromList([1, 2]));+ session.transportLost();+ await session.reopen();+ await peer.ready('new');+ final newUpload = session.pasteImage(Uint8List.fromList([3, 4]));+ await Future<void>.delayed(Duration.zero);+ oldBegin.complete(false);+ expect(await oldUpload, isFalse);+ expect(session.uploadProgress, isNotNull);+ await session.handleFrame('terminal_chunked_upload_begin_result', {+ 'streamId': 'new',+ 'accepted': true,+ });+ await Future<void>.delayed(Duration.zero);+ expect(peer.binary.single.streamId, 'new');+ expect(peer.binary.single.bytes, [3, 4]);+ await session.handleFrame('terminal_paste_image_result', {+ 'streamId': 'new',+ });+ expect(await newUpload, isTrue);+ expect(session.uploadProgress, isNull);+ expect(session.status, TerminalSessionStatus.controlling);+ },+ );++ test(+ 'closing a pane during viewport measurement never sends a delayed open',+ () async {+ final peer = _Peer();+ final session = peer.session;+ addTearDown(session.dispose);+ final opening = session.open(waitForViewportSize: true);+ await session.close();+ session.reportViewport(100, 30);+ await opening;+ expect(peer.sent.where((f) => f.type == 'terminal_open'), isEmpty);+ expect(session.status, TerminalSessionStatus.closed);+ },+ );+}diff --git a/desktop/test/terminal_reconnect_view_test.dart b/desktop/test/terminal_reconnect_view_test.dartnew file mode 100644index 000000000..fcc91b633--- /dev/null+++ b/desktop/test/terminal_reconnect_view_test.dart@@ -0,0 +1,184 @@+import 'dart:convert';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/widgets/terminal_composer.dart';+import 'package:harness/widgets/terminal_find_bar.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_interactions_test.dart' show chord;+import 'swarm_screen_test.dart' show mount;+import 'swarm_state_test.dart' show createApp;+import 'terminal_find_test.dart' show findField, finishFind, terminalView;++class _Connection extends WsConn {+ _Connection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final sent = <({String type, Map<String, dynamic> payload})>[];+ final input = <Uint8List>[];+ @override+ Future<bool> sendTerminalFrame(+ String type,+ Map<String, dynamic> payload,+ ) async {+ sent.add((type: type, payload: Map.of(payload)));+ return true;+ }++ @override+ Future<bool> sendTerminalBinary(Uint8List bytes) async {+ input.add(bytes);+ return true;+ }++ @override+ Future<void> forceReconnect() async {}+ Map<String, dynamic> get latestOpen =>+ sent.lastWhere((f) => f.type == 'terminal_open').payload;+}++Future<void> _ready(AppNotifier app, _Connection connection, String stream) =>+ app.handleMachineEventForTest('m', {+ 'type': 'terminal_ready',+ 'payload': {+ 'requestId': connection.latestOpen['requestId'],+ 'agentId': 'a0',+ 'streamId': stream,+ 'protocolVersion': 3,+ },+ });++Future<void> _screen(+ AppNotifier app,+ _Connection connection,+ String stream,+ int start,+) => app.handleTerminalBinaryForTest(+ 'm',+ encodeTerminalLocal(+ TerminalBinaryFrame(+ kind: TerminalBinaryKind.keyframe,+ streamId: stream,+ seq: 0,+ compressed: false,+ cols: connection.latestOpen['cols'] as int,+ rows: connection.latestOpen['rows'] as int,+ bytes: utf8.encode(+ List.generate(200, (i) => 'Retained marker ${start + i}\r\n').join(),+ ),+ ),+ )!,+);++void main() {+ testWidgets(+ 'reconnect keeps output, Find location and draft until the replacement screen',+ (tester) async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ final machine = app.machineStates['m']!+ ..nodeOnline = true+ ..terminalCapabilityAvailable = true;+ final attaching = app.addAgentToSwarm('m', 'a0');+ await mount(tester, app);+ await attaching;+ final pane = app.panes.single;+ final session = pane.session!;+ const firstStream = '00000000-0000-0000-0000-000000000001';+ const nextStream = '00000000-0000-0000-0000-000000000002';+ await _ready(app, connection, firstStream);+ await _screen(app, connection, firstStream, 0);+ app.toggleComposer(pane.id);+ await tester.pump();+ final composer = find.descendant(+ of: find.byType(TerminalComposer),+ matching: find.byType(TextField),+ );+ await tester.enterText(composer, 'Unsent direction');+ final draft = tester.widget<TextField>(composer).controller!;+ draft.selection = const TextSelection.collapsed(offset: 5);+ final renderer = terminalView(tester, session);+ final scroll = renderer.widget.scrollController!;+ final lineHeight = renderer.renderTerminal.lineHeight;+ scroll.jumpTo(20.25 * lineHeight);+ await tester.pump();+ await chord(tester, LogicalKeyboardKey.keyF);+ await tester.enterText(findField, 'marker');+ await finishFind(tester);+ final field = tester.widget<TextField>(findField).controller!;+ field.selection = const TextSelection.collapsed(offset: 3);+ final search = tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search;+ final matchedRow = search.match!.begin.y;+ final matchedText = session.terminal.buffer.lines[matchedRow].getText();+ final before = session.terminal;+ final offset = scroll.offset;+ session.transportLost();+ machine.nodeOnline = false;+ app.dismissError();+ await tester.pump();+ machine.nodeOnline = true;+ final retry = app.selectAgent('m', 'a0');+ await tester.pump();+ await retry;+ expect(+ pane.session,+ same(session),+ reason: 'Reconnection preserves the owning session',+ );+ expect(session.terminal, same(before));+ expect(terminalView(tester, session), same(renderer));+ expect(scroll.offset, offset);+ expect(tester.widget<TextField>(findField).controller, same(field));+ expect(tester.widget<TextField>(composer).controller, same(draft));+ expect(tester.widget<TextField>(composer).enabled, isFalse);+ expect(session.acceptsInput, isFalse);+ await _ready(app, connection, nextStream);+ await tester.pump();+ expect(+ session.terminal,+ same(before),+ reason: 'Ready without a keyframe must not blank the screen',+ );+ expect(session.acceptsInput, isFalse);+ await _screen(app, connection, nextStream, 10);+ await tester.pump();+ await finishFind(tester);+ expect(session.status, TerminalSessionStatus.controlling);+ expect(terminalView(tester, session), same(renderer));+ final restored = tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search;+ expect(+ session.terminal.buffer.lines[restored.match!.begin.y].getText(),+ matchedText,+ );+ expect(tester.widget<TextField>(findField).controller, same(field));+ expect(field.selection.baseOffset, 3);+ expect(draft.text, 'Unsent direction');+ expect(draft.selection.baseOffset, 5);+ expect(tester.widget<TextField>(composer).enabled, isTrue);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(scroll.offset, closeTo(10.25 * lineHeight, 0.01));+ expect(connection.input, isEmpty);+ expect(connection.sent.where((f) => f.type == 'message'), isEmpty);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ await connection.close();+ },+ );+}diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex b64b92bc6..c2a9380fd 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -153,10 +153,10 @@ private extension SwarmTitlebar {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", "addAgent", "linkMachine", "addProject", "closePane", "closeActive"], "File exposes creation, connection and view-closing actions")- let jump = historyMenu.items.first(where: { $0.representedObject as? String == "jump" })!+ try checkTitlebar(file.items.compactMap { $0.representedObject as? String } == ["new", "newAgent", "reopen", "addAgent", "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(jump.keyEquivalent == "p" && jump.keyEquivalentModifierMask == [.command], "Command-P has a native menu owner while a terminal has focus")- let reopen = historyMenu.items.first(where: { $0.representedObject as? String == "reopen" })!+ let reopen = file.items.first(where: { $0.representedObject as? String == "reopen" })!actionsEnabled = truecanReopen = falsetry checkTitlebar(!validateMenuItem(reopen), "Closed-Swarm recovery is disabled with an empty history")@@ -175,12 +175,30 @@ private extension SwarmTitlebar {let recentRows: [[String: Any]] = (0..<20).map {["id": "agent:\($0)", "title": "Agent \($0) — Machine", "detail": "Project \($0)", "current": $0 == 0]} + [["id": "swarm:recent", "title": "Recent Swarm", "swarm": true]]- updateHistory(recentRows)- try checkTitlebar(recentAgentsMenu.numberOfItems == 12 && recentSwarmsMenu.numberOfItems == 1, "Recent menus stay bounded and separate agents from Swarms")- let recent = recentAgentsMenu.items[0]- try checkTitlebar(recent.state == .on && recent.toolTip == "Project 0", "Recent work includes current selection and project context")- updateHistory(recentRows)- try checkTitlebar(recentAgentsMenu.items[0] === recent, "Unchanged history retains native menu items")+ let closedRows: [[String: Any]] = (0..<14).map {+ ["id": "closed-\($0)", "title": "Closed Swarm \($0)", "detail": "3 views", "swarm": true]+ }+ updateHistory(recentRows, closed: closedRows)+ let recentItems = historyMenu.items.filter { $0.action == #selector(historyAction(_:)) }+ let closedItems = historyMenu.items.filter { $0.action == #selector(closedHistoryAction(_:)) }+ try checkTitlebar(recentItems.count == 15 && closedItems.count == 10, "Chrome-style direct History sections remain bounded")+ try checkTitlebar(historyMenu.items.filter { !$0.isSeparatorItem }.prefix(2).map(\.title) == ["Back", "Forward"], "History begins with Back and Forward")+ try checkTitlebar(historyMenu.items.last?.title == "Show Full History" && historyMenu.items.last?.keyEquivalent == "y", "Full History uses Command-Y")+ 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.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")+ canReopen = true+ let back = historyMenu.items[0]+ let forward = historyMenu.items[1]+ canGoBack = false+ canGoForward = true+ try checkTitlebar(!validateMenuItem(back) && validateMenuItem(forward), "Back and Forward have independent navigation availability")try checkTitlebar(validateMenuItem(recent), "Recent navigation is available in the shell")actionsEnabled = falsetry checkTitlebar(!validateMenuItem(recent) && !validateMenuItem(jump) && !validateMenuItem(settings), "History, jump and Settings cannot act behind a modal")@@ -190,7 +208,8 @@ private extension SwarmTitlebar {actionsEnabled = trueupdateHistory([])try checkTitlebar(!validateMenuItem(recent), "A stale recent menu item cannot dispatch after its view disappears")- try checkTitlebar(recentAgentsMenu.items[0].action == nil && !recentAgentsMenu.items[0].isEnabled, "An empty recent menu is an inert placeholder")+ 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,let attention = menu.items.first(where: { $0.representedObject as? String == "notifications" }) else {throw TitlebarCheckFailure(message: "Swarm menu exposes agents needing input")diff --git a/docs/harness-v2-developer-tools-research.md b/docs/harness-v2-developer-tools-research.mdindex 1187833e8..0eff3de0c 100644--- a/docs/harness-v2-developer-tools-research.md+++ b/docs/harness-v2-developer-tools-research.md@@ -14,9 +14,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; recent agents and Swarms; native Cmd+P routing. Menus and picker typing verified live; focus/input regression tests pass. |-| Next | Preserve Find, scroll and draft context through the actual reconnect/keyframe handoff. |+| 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; wallpaper control moved to View/context menus; Workshop now 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. || Next | Live keyboard/tab/drag review and native input-to-display measurements under output load. |+| 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. || Keep deferred | Workflow canvases, autonomous manager layers, a full IDE/Git client and a marketplace. |## What people actually describe using@@ -67,8 +69,8 @@ The opportunity for Harness is to make movement among real agents across real ma| **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. |-| **Implemented in the preview** | Native File/History menus; redundant Settings gear removed | Settings stays in the macOS app menu with `Cmd+,`. File groups creation, linking and closing views. History exposes Cmd+P, recent agents/Swarms and closed-Swarm recovery. Recent lists are bounded, session-local and contain open views only; selecting a stale item cannot recreate a closed view. The non-macOS toolbar retains Settings access. |-| **Reduce prominence** | “Next wallpaper” button and repeated metadata | Keep appearance choices in a secondary location and machine identity legible where needed to distinguish remote work. These remaining reductions are proposals. |+| **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. || **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. |@@ -80,7 +82,13 @@ 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.-Safari places recent visits and closed-tab recovery in [History](https://support.apple.com/en-mide/guide/safari/ibrw1009/mac). Harness applies that navigation pattern to existing agent views and Swarms. It does not collect terminal commands, prompts or output as navigation history. Current history is limited to this app session: at most 64 identities, with 12 recent agents and 12 recent Swarms shown in the native menus. Closed-Swarm recovery uses the existing in-memory recovery list for this app session.+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.++## Reductions and prototype follow-up++[The prototype review](harness-v2-prototype-review.md) covers all six variants in `harness-new-ui` at `19ced37`. Keep the terminal canvas and chosen Swarms; borrow optional contextual preview, explicit splits and exact return selectively. Leave out V3's primary/supporting hierarchy, persistent shelf, extra status/footer/context rows, model dashboard, and V4's default replacement of the active pane. Do not copy its Ctrl+B prefix over a real tmux session.++The fzf follow-up is one improvement to Cmd+P: match highlights, a bounded preview of already-retained context, and precise filters where names are ambiguous. It must perform no network work or terminal attachment while navigating results. Ordinary-shell creation, remappable keys/passthrough, editor/diff handoff, and structured prompt/output navigation remain important gaps to verify. They are not all new features to build at once; reliability and measured interaction performance come first.## The next small product milestonediff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.mdindex d52487424..66be7b6b4 100644--- a/docs/harness-v2-performance.md+++ b/docs/harness-v2-performance.md@@ -179,19 +179,31 @@ The reported Cmd+P bug reproduced in isolated tests. Closing the picker could reRetained terminals stay mounted while offline, unlinked or temporarily missing from discovery. Their header carries read-only status, so no overlay blocks output or changes terminal dimensions. Cached presentation includes availability and error details; unchanged offline panels can reuse their widget tree too. The optional composer stays mounted and disabled, preserving its unsent draft. Native Find remains enabled for retained buffers. Neither navigation nor unavailable retry attempts discard the session or start a replacement stream.-The full desktop suite passes 1,039 tests with one skip; the final combined suite and isolated render passes 1,040 with one skip. Focus regressions cover repeated and same-Swarm jumps, zoom, offscreen/cross-Swarm targets, the first input frame and unavailable destinations. Offline checks preserve renderer identity, dimensions, selection, scroll, Find and composer text while refusing input. The ready retry fixture verifies that an explicit retry still opens a fresh stream when prerequisites return. Actual reattachment still replaces the session before its first keyframe; retaining context through that handoff remains follow-up work. These are behavior and frame-order checks, not physical-display latency measurements.+At this checkpoint the full desktop suite passed 1,039 tests with one skip; the combined suite and isolated render passed 1,040 with one skip. Focus regressions covered repeated and same-Swarm jumps, zoom, offscreen/cross-Swarm targets, the first input frame and unavailable destinations. Offline checks preserved renderer identity, dimensions, selection, scroll, Find and composer text while refusing input. Actual reattachment still replaced the session at this stage; the later reconnect continuation below removes that replacement. These are behavior and frame-order checks, not physical-display latency measurements.-## Native menu update+## Native menu update — first passHistory shares the 64-identity session-local navigation record and shows at most 12 recent agents and 12 recent Swarms. Navigation and discovery refresh its lightweight destination snapshots; ordinary terminal notifications reuse them. Unchanged state sends no native update and AppKit retains identical menu items. Menu selection resolves its identity against current open views before focusing, and cannot recreate a closed pane. Cmd+P now has an explicit native menu owner in History, sharing the tested picker handoff. The macOS Settings gear is removed, leaving that space for tabs while keeping Settings in the app menu.The full desktop suite passes 1,041 tests with one skip; 221 AppKit checks pass, including native menu order, shortcut ownership, stale history actions and modal guards. These checks establish behavior and avoidance of redundant work, not measured native input-to-display latency.+## Reconnect, Chrome History and context cleanup++Explicit reconnect now reuses the session and the mounted terminal view. Keyframes are constructed before publishing their replacement emulator; manual viewport, Find and selection remapping runs only when those contexts exist. The ordinary tail-following path skips the row scan. A generation guard prevents delayed work from an old stream repainting, freezing, clearing an upload or holding up new input. Tests cover late output, blocked old input, old upload completion, closed opening waits and the real keyframe handoff through AppNotifier.++Chrome-style History keeps a separate bounded 128-location Back/Forward trail alongside the existing 64 recent identities and 24 closed-Swarm records. Native sections show 10 closed and 15 visited destinations. Back/Forward changes focus without attachment or network waits; identical menu snapshots retain native item instances. Show Full History reuses the existing immediate search dialog, with a clear session-only scope.++Local Git compatibility reads only bounded metadata files asynchronously, deduplicates pending reads and caches at most 256 folders. Directory events debounce metadata refresh by 100 ms; that delay updates branch context and never gates typing, pane focus or navigation. The permanent wallpaper button and repeated header project text are removed. No additional wallpaper memory or native input-to-display measurement is claimed for this pass.++The full suite passes **1,050 tests with one skip**; hidden AppKit checks pass **229 assertions**. Analyzer output is back to zero errors/warnings and 12 existing vendored infos. The pane header was also rendered with isolated fixtures at three widths. These establish correctness and bounded work, not a measured zero-latency experience. The [prototype review](harness-v2-prototype-review.md) preserves the same constraint for a future Cmd+P preview: bounded retained context, no attachment, network request or transcript scan across the catalog while moving through results.++The Release rebuild succeeded. Live review verified real branch labels, the simplified welcome, Workshop's three-member project association, native History and Back, and Cmd+P → Return focusing an existing local pane followed by a quick return to the original pane. No real-agent input or remote interruption was used for these checks. Native physical input-to-display timing remains unmeasured.+## Native follow-upThe optimized real-data app builds and runs locally. The native tab/canvas polish was visually reviewed before the navigation and retained-canvas continuations; CUA access returned after the pane-focus Release rebuild. The empty wallpaper and tab strip were captured. After the native-menu build, live checks verified File/History, Cmd+P opening, immediate focused search typing and Escape return. At that point no agent views were open, so live terminal destination/input checks remain pending; fake-session regression tests cover them. 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.-The native check covers overflow, resizing, accessibility order and disabled actions. `bash tool/check_swarm_titlebar.sh /path/to/flutter --window-layout` adds actual container checks in a hidden window at three widths, for 221 assertions total, including File/History menus, modal/stale-action guards, hover separators and native Find/attention shortcuts and modal guards. No Flutter engine, account or terminal is accessed.+The native check covers overflow, resizing, accessibility order and disabled actions. `bash tool/check_swarm_titlebar.sh /path/to/flutter --window-layout` adds actual container checks in a hidden window at three widths, now for 229 assertions total, including File/History menus, modal/stale-action guards, hover separators and native Find/attention shortcuts. No Flutter engine, account or terminal is accessed.Wallpaper is built only for the empty New swarm. Populated Swarms paint a flat color matching the selected native tab, and the disposed wallpaper evicts its own decoded cache entry. This removes wallpaper painting/cache retention from the active terminal canvas; no process-memory reduction has been measured yet.diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdindex eb9aa86fe..6b68bef89 100644--- a/docs/harness-v2-progress.md+++ b/docs/harness-v2-progress.md@@ -1,6 +1,20 @@# Harness App V2 — development handoff-Updated 2026-09-13 after the pane-focus, disconnected-terminal and native-menu continuations. This is a working preview, not a release.+Updated 2026-09-13 after reconnect continuity, Chrome History, project/header cleanup, and the six-prototype review. This is a working preview, not a release.++## Latest continuation++- The user asked to review all prototypes in `autonomous-ai/harness-new-ui`, keeping only a few durable ideas. [The review](harness-v2-prototype-review.md) covers all six running variants and source at `19ced37`. Keep durable sessions, fast navigation, explicit layout changes, and exact return. Next small addition: optional cached Cmd+P preview/highlights. Do not adopt the permanent shelf, primary/supporting hierarchy, extra footer/context row, model dashboard, generic handoff system, or a default Ctrl+B prefix that conflicts with tmux.+- Reconnect reuses the `TerminalSession` and mounted `TerminalView`. A replacement keyframe restores a matching viewport, Find bookmark/match and exact surviving selection; composer text/caret and Find controllers remain. Generation guards isolate stale output, input, resize, upload, heartbeat and open/recovery completions. No stale queued input is replayed. Atomic keyframe construction leaves retained output intact until replacement succeeds. Arbitrary IME preedit continuity and a real remote interruption still need native validation.+- Chrome is now the primary menu reference. History has Back/Forward (`Cmd+[` / `Cmd+]`), up to 10 Recently Closed Swarms, 15 Recently Visited destinations and Show Full History (`Cmd+Y`). Cmd+P is in Swarm; Reopen Closed Swarm is in File. The searchable History view is explicitly **This session**: 64 recent identities, a 128-location exact-pane trail, and 24 recoverable closed Swarms. It does not persist an all-time browsing log or terminal text.+- The pane header now has one agent title, a visible available branch, machine and right-aligned controls. Repeated project-name text is removed. Full checkout context remains in the tooltip; narrow headers use a machine icon with its full name. Isolated renders were inspected at 740, 480 and 280 points.+- The permanent Next wallpaper button is removed. Use native View → Next Wallpaper or the empty New swarm context menu. The View action disables for populated Swarms. Active canvases retain the flat selected-tab color.+- The Workshop issue was traced to older daemons returning agent lists without project/cwd metadata. Local `/api/status` supplies real folders; the old remote list does not. Project options → Choose agents now persists explicit cross-machine associations without attaching a terminal. Automatic grouping still uses canonical repository remote, or machine plus folder when no remote is known. Branches/worktrees do not split a repository project.+- A local compatibility reader resolves Git root/origin/HEAD asynchronously, caches at most 256 folders and watches Git metadata for branch changes; no shell process, network call or rendering-path read is used. Daemon-supplied metadata remains authoritative. The lightweight parser does not implement Git include/includeIf or URL rewrite semantics, and older remote daemons still cannot provide branch labels through this fallback.+- After normally quitting PID 50524, the requested iMac Home Workshop association was saved through `HarnessFileStore`; every other state value was verified unchanged. This updates project starters, not the membership of already-created Swarms. No production daemon was restarted or upgraded.+- Validation: **1,050 Flutter tests pass, one existing skip; 229 AppKit checks pass**, including hidden native window layout and Chrome menu behavior. Analyzer: no errors/warnings and 12 existing vendored infos after cleaning all new diagnostics. New project-launch, exact-pane History, local Git worktree/watch and reconnect view/race regressions pass.+- Release build succeeded and the sole preview was normally relaunched as **PID 88567**; revalidate its PID before any later restart. Live CUA review confirmed compact headers with the actual local `main` branch, full New swarm wallpaper with no permanent button, View → Next Wallpaper, Chrome History/its searchable session view, and native Back returning to the same Workshop pane. Cmd+P search → Return visibly focused the other existing Workshop pane; Cmd+P → Return restored the original pane. No input was sent to an agent. A direct bracket-key request was unsupported by the CUA key-name API; native Back was checked through its menu instead, with shortcut routing covered by isolated checks.+- The live New swarm project count is **3** for Workshop. Project options show the two automatic local repository matches plus the checked **Workshop: NYC Chess Set — iMac -Home** association. The settings dialog was canceled after inspection, and the original Workshop Swarm/focus was restored. The existing Swarm remains its chosen two-pane arrangement; project starters include all three when invoked. No extra review Swarms, terminal attachments or agent messages were created by this verification.## Resume here@@ -23,7 +37,7 @@ Updated 2026-09-13 after the pane-focus, disconnected-terminal and native-menu c- The latest hover pass uses 13-point native titles, 14-point leading space inside the 28-point hover shape, a 12-point corner radius and a 10-point close symbol. Both neighboring separators disappear on hover. The title layout is cached across hover redraws. Native selected shoulders still meet the flat canvas. Isolated native before/after images were inspected. CUA later captured the real strip and wallpaper; pointer-hover/drag review still needs an uninterrupted live window.- The user reported that Cmd+P did not focus the selected agent. New tests reproduced two failures: the closing picker could restore the old terminal and overwrite the selected pane, and an offscreen result stayed outside the viewport. Both pickers now clear that stale focus restoration before activating their result. Explicit jumps refocus even the currently selected pane and reveal it before paint, accounting for changed canvas padding when leaving New swarm. Checks cover same-Swarm, repeated, zoomed, offscreen and cross-Swarm jumps, including the first key arriving only at the destination.- Retained sessions now keep the same terminal renderer through offline, missing-machine, link-required and unavailable-agent presentation. The large frozen overlay and redundant connection overlays are removed; status and explicit Reconnect/Take control actions occupy the header. Offline output stays selectable/searchable, and disabled composer text remains intact. Tab switches no longer retry existing dead streams; unavailable retries keep the old session. A never-attached pane still shows setup guidance.-- The user asked for File/History menus like Safari/Chrome and removal of the duplicate Settings gear. The macOS menu order is now Harness, File, Edit, View, History, Swarm, Window, Help. File groups existing creation/link/project/close actions. History owns native Cmd+P, 12 recent agents (with machine names), 12 recent Swarms and existing closed-Swarm recovery. Settings stays in the app menu; non-macOS fallback keeps its Settings control. History reuses the bounded 64-identity session-local navigation record, caches presentation across output notifications, and revalidates open-view identities on selection. It does not store terminal text or recreate stale closed views. Native/channel focus, modal, cache and stale-action checks pass.+- The first native-menu pass removed the duplicate Settings gear and established Harness, File, Edit, View, History, Swarm, Window, Help. The latest continuation above replaces its separate recent-agent/Swarm submenus with Chrome-style sections and exact-pane Back/Forward. Settings stays in the app menu; non-macOS fallback keeps its Settings control. History caches presentation across output notifications and revalidates destination identities on selection.- The user asked where the research suggestions live and whether implementation follows them. The developer-tool audit now starts with a compact status/next-work table; keep it current alongside this handoff.- Continue implementation here. Do not create another repository or fork for V2.@@ -55,7 +69,7 @@ Harness is one place to work with all your agents. Swarms are named, chosen coll- Notifications reflect actual pending questions, never fabricated sample statuses.- New agent uses real engine discovery, working folders, Codex profiles, and permissions. An agent name is not a submitted task prompt.-Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83b32338f44dd675e2ad668519e6d429342d9ff` on `ui-prototype`, pushed to `autonomous-ai/harness-app-landing-page`. Its `HARNESS.md` and `research/conversation-history.md` record product decisions. Six wallpapers were copied from `public/`. This reference informs the existing native Flutter app implementation.+Original reference: `/Users/ab/code/harness-new-ui` at `f83b32338f44dd675e2ad668519e6d429342d9ff`; six wallpapers came from `public/`. The user's newly requested review inspected this repository at `19ced37`, with origin `autonomous-ai/harness-new-ui`, and all six live variants. Its historical contracts are comparison material; [the selective V2 review](harness-v2-prototype-review.md) and current user direction govern what to keep.## Implementation map@@ -104,14 +118,14 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83- 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.- `widgets/swarm_attention.dart` and `state/swarm_attention.dart` replace the mouse-only notifications list with **Needs input** (Cmd+Shift+I). It opens with no transition or blur, searches live prompts plus agent/project/machine context using the existing fuzzy ranker, and builds rows on demand. Blank search keeps the time each question was first heard; live updates preserve the selected agent and remove resolved questions. Unavailable terminals remain visible and cannot create an unknown view. Activation revalidates the same pending request before using focus-only navigation or explicitly opening a view in the captured Swarm. It never answers a question or retries/takes over an existing terminal. Cmd+P, Return restores prior work, including across Swarms. Keyboard movement in both pickers now scrolls before paint, avoiding a second frame for an offscreen selection.-- 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.+- Spoken-task subscription/reporting/window reveal and existing linking dialogs are retained. Settings is in the native app menu, with Account/sign-out inside Settings; the non-macOS toolbar retains its entry.- Settings opens/closes immediately and switches sections without cross-fades. The former 170/120 ms route and 200/90 ms section transitions are removed.- Non-macOS/tests use a Flutter reorderable tab-strip fallback. Linux/Windows have not been built or visually reviewed.### Native macOS tabs- `desktop/macos/Runner/SwarmTitlebar.swift`, registered in Xcode and owned by `MainFlutterWindow`.-- `NSTitlebarAccessoryViewController` with native scrollable tabs, new button, notification bell, settings. Automatic native window tabbing disabled; Flutter content begins below title bar.+- `NSTitlebarAccessoryViewController` with native scrollable tabs, new button and Needs input bell. The redundant Settings button is removed on macOS. Automatic native window tabbing is disabled; Flutter content begins below the title bar.- An empty native toolbar with `.unifiedCompact` supplies a single 40-point title row. A `.right` accessory cannot set its own height; the prior standalone view was clipped to 32 points. AppKit now owns height, traffic lights align with the tab controls, and the selected tab has flared lower shoulders at the canvas edge. The selected fill matches Dart's `#463746` exactly. Hover rectangles, measured text and close controls share one vertical center, with balanced horizontal padding.- Method channel `harness/swarm_tabs`: Dart sends tab ID/name/selection/attention and recovery availability; Swift sends new/reopen/select/close/rename/reorder/navigation/settings/notifications.- Native tab click, double-click rename, context menu, close, drag/drop reorder. Tab button instances are retained across refreshes.@@ -153,7 +167,8 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83| 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+[ / ] |+| History Back / Forward | Cmd+[ / ] |+| Show Full History (this session) | Cmd+Y || Zoom / previous focus | Cmd+Enter / Cmd+; || Focus index | Cmd+1 through Cmd+9 || Layout / pin | Cmd+S / Cmd+Shift+P |@@ -254,13 +269,13 @@ Earlier logs contain superseded failures. Temporary logs and toolchains are loca## Remaining work-1. Continue live CUA review of an existing-agent jump, stable canvas, restored output/caret, project starters and keyboard navigation. Cmd+P opening/filtering/Escape and the File/History menus are now verified in the real app. Access returned after the pane-focus rebuild. The user is actively changing window size and Swarms; re-read UI state before actions and preserve their arrangement.+1. Measure native terminal input and tab-switch responsiveness under output load, including p50/p95/p99 and cold/warm paths. Live Cmd+P destination focus/quick return, branch headers, project associations, New swarm cleanup and native History are verified. Keep typing/transport measurements in disposable fixtures; the user's real agent terminals are not test inputs.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.+3. Verify real remote reconnect, nested tmux/Vim, paste, selection and IME against disposable local/remote processes. The AppNotifier/keyframe and stale completion regressions now pass; they do not prove every network or native editing condition. Preserve 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.5. Build/review Linux and Windows when their toolchains are available. Remote full project/branch metadata requires daemons running the new wire format; do not upgrade them automatically.-6. Preserve the retained buffer, Find context and composer draft through an actual stream reattachment until its replacement keyframe arrives. This pass preserves them while unavailable and during navigation; a ready retry still creates a new TerminalSession. Exercise actual reconnect ordering with a disposable local protocol fixture, never a real agent.-7. Continue the agreed goal and apply the latest steering. The research proposes a focused roadmap and specific subtraction candidates; do not mistake proposals for already-implemented removals.+6. Follow the bounded prototype recommendation: optional retained-context preview/highlights in Cmd+P, then deliberate right/down splits with compatible layout persistence. Verify ordinary-shell creation, remappable keys and prefix passthrough before promising a complete terminal replacement. Keep the rejected shelf/hierarchy/dashboard/manager surfaces absent.+7. Audit local Git watch failure/removal and relocated-worktree invalidation before broadening that compatibility path. It deliberately reads a small subset of Git metadata; prefer richer daemon metadata as available. Continue the active goal using the current research status list, distinguishing shipped reductions from proposed follow-ups.## Toolchain and workflowdiff --git a/docs/harness-v2-prototype-review.md b/docs/harness-v2-prototype-review.mdnew file mode 100644index 000000000..7fe88ed8c--- /dev/null+++ b/docs/harness-v2-prototype-review.md@@ -0,0 +1,68 @@+# What V2 should borrow from the Harness prototypes++Reviewed 2026-09-13. The source is the clean local checkout of [autonomous-ai/harness-new-ui](https://github.com/autonomous-ai/harness-new-ui) at `19ced37`, with its matching origin. The public GitHub page could not be fetched by the web tool; the source and running `http://127.0.0.1:5173/` were inspected directly.++**Keep the scope small: durable terminals, immediate navigation, and a dependable way to handle an interruption and return.** The prototypes provide useful interaction experiments. They do not establish native terminal correctness, measured performance, or what exceptional developers universally prefer.++## What was reviewed++All six live variants were inspected at the existing desktop viewport: Harness, Harness + Grid, Swarms, Swarms v3, Swarms v4, and Swarms + Models. The walkthrough exercised V4 search and its contextual preview, Needs you and Return, V3 Find and a temporary Daily Report preview, and the Models inventory. It did not submit mock instructions, send handoffs, create agents, or alter pane membership. The original V4 comparison selection was restored.++Source review covered `App.tsx`, `SwarmsV4Workspace.tsx`, `data/swarmsV4.ts`, `HARNESS.md`, the V3/V4 notes, the earlier Swarms review, and product-direction history. The V4 notes clearly label their developer walkthroughs as **AI simulations**, not visits or endorsements from the people used as inspiration. Earlier proposed contracts remain historical evidence; the user's current V2 decisions govern implementation.++| Prototype | Useful lesson | Decision for V2 |+| --- | --- | --- |+| Harness | Related work can span machines and branches. Its permanent tree compresses the terminal canvas, and repeated context truncates titles. | Keep searchable project/branch/machine context and machine/project starters. Keep the permanent tree absent. |+| Harness + Grid | Execution machine and inference provider are different concepts. Adding both to every pane makes identification harder. | Preserve accurate machine identity. Leave model routing and compute administration outside this milestone. |+| Swarms | A chosen working set and ordinary tabs are easy to understand; mixed machines need no extra hierarchy. | Keep the native tab/canvas foundation, explicit membership, and close-view semantics. Preserve the newer Chrome geometry rather than copying the browser mockup's strip. |+| Swarms v3 | A large readable terminal helps; temporary inspection can preserve the originating workspace. Primary/supporting/shelf roles introduce extra arrangement decisions. | Keep zoom and exact return. Do not adopt the role hierarchy, two-supporting-pane limit, promotion controls, or persistent shelf. |+| Swarms v4 | Stable sessions, explicit right/down splits, contextual search preview, draft/caret recovery, and an attention round trip address daily friction. | Borrow these behaviors selectively. Do not inherit its permanent session strip, footer, second metadata row, or default replacement of the focused pane. |+| Swarms + Models | Model/account details can be inspected on demand, but per-pane model controls and a top-level library compete with the work. | Keep the dashboard absent. Existing usage and hardware capabilities stay secondary; they do not justify a new daily navigation surface. |++## The three promises, with concrete changes++### 1. Work stays where you left it++The durable idea shared with tmux is session identity independent of the view. V2 already shares controllers across Swarms and closes views without ending agents. Finish reconnect preservation, scroll/search/draft continuity and close/reopen behavior before widening the feature set.++Borrow V4's **explicit split right/down** interaction as the next layout improvement. A split should add beside the chosen pane, with user-controlled resizing and no eviction or automatic rearrangement when an agent's state changes. This requires a deliberate extension of V2's layout model; it is not implemented merely because the prototype can draw a split tree. Retain existing arrangements and provide a compatible migration before changing their representation.++Do not copy V4's default "open here" behavior into Cmd+P: that replaces the current pane when a session is not visible. In V2, Return should continue to focus the existing destination; adding a view remains explicitly labeled. Stable behavior matters more than reducing one click by surprising the user.++### 2. Reach the right work immediately++The strongest small addition is an **optional preview inside the existing Cmd+P picker**. V4's `workshop` query demonstrated why: a result named `zsh` becomes recognizable when its folder, branch, and recent output are visible. No second global finder or permanent sidebar is needed.++Carry the following into one bounded follow-up:++- Highlight matched text, including the machine/project/branch field responsible for a match; retain deterministic ranking and the highlighted identity during discovery updates.+- Allow a keyboard-controlled preview using already-retained output and metadata only. Bound the excerpt, show unavailable context honestly, and never attach, reconnect, acquire control, or scan every transcript as the selection moves.+- Add precise machine/project/branch filters when they remove ambiguity. These are navigation filters, not a new organizational hierarchy.++This follows [fzf's incremental narrowing and preview design](https://github.com/junegunn/fzf). `git ls-files | fzf` illustrates its small composable contract: receive candidates, narrow them, return the chosen value. Harness should reuse that interaction model, not run shell preview commands on every search keystroke. V4's own scorer is a small custom fuzzy matcher, not an embedded fzf runtime.++The prototype's `>` command mode could eventually expose the existing app command catalog in the same picker. Defer a second registry or a large command system; first verify that people cannot already find the relevant command through native menus and the shortcut sheet.++### 3. Handle a decision and return to the same place++Borrow the V3/V4 **temporary inspection and explicit Return** behavior. V2 already has Needs input and previous-destination navigation; strengthen the same loop instead of adding a new inbox, dashboard, or mandatory arrival screen. The return target includes the Swarm, pane, zoom, reading position, unsent draft, caret and actual focus.++Keep a question distinct from a reported result and an unverified completion. Status comes from real events, with freshness and unavailable-state handling. The preview's generic reply box is not a safe substitute for an agent's native approval semantics. Route the developer to the actual agent interaction unless a supported adapter can identify and answer the exact request.++V4's editable handoff is an interesting later idea. A production version needs an explicit recipient, actual checkout/change evidence, reviewable text and delivery confirmation. Start with ordinary copy/paste and an editor/diff handoff; do not build a generic orchestrator or infer that storing text means another agent received it.++## What stays out, or becomes smaller++- **No mandatory primary/supporting hierarchy, session shelf, extra footer, duplicate project tree or permanent context row.** Use the terminal area for output; disclose context in the compact header, picker, tooltip and menu.+- **No copied Ctrl+B prefix by default.** A real nested tmux session already uses it. Configurable keymaps and deliberate passthrough need runtime tests; the browser's prefix simulation cannot prove compatibility.+- **No model/compute dashboard, marketplace, autonomous manager, full IDE/Git client or generic handoff system in this milestone.** Existing agents, shells and editors already perform much of this work.+- **No backdrop blur, artificial transition delay, replaying output animation or repeated healthy-state spinner.** A quiet working surface and measured response are more valuable than constant signs of activity.+- **Wallpaper remains in empty New swarm only.** Appearance controls belong in View/context menus. Active Swarms keep one flat color continuous with the selected tab.++## Remaining foundations the prototypes cannot prove++An ordinary local/remote shell must be easy to open in the correct directory. Remappable commands must coexist with Vim, zsh, tmux, IME and accessibility keys. [Ghostty's shell integration](https://ghostty.org/docs/features/shell-integration) offers useful examples of directory inheritance, prompt navigation and output selection; these should use real terminal signals rather than guessed screen text. CLI/API operations should use the same stable session identities as the UI.++Those are gaps to verify and prioritize, not a checklist to implement all at once. Current order: finish the reliability/menu/header/project work; measure real input and navigation under output load; then add the bounded Cmd+P preview/highlight improvement. Explicit splits and keymap/shell compatibility follow with their own focused validation. The [working queue](harness-v2-developer-tools-research.md) remains the single status list.++Success means fewer wrong destinations, no surprise layout changes, no lost editing or reading context, and less effort to resume work. Real daily use with local and remote agents must establish that result; attractive sample screens and simulated reviewers cannot.