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
perf(desktop): retain hidden terminal trees and coalesce layout saves
deeb27ccea481dc
diff --git a/desktop/lib/main.dart b/desktop/lib/main.dartindex 21d28916b..e5846c83f 100644--- a/desktop/lib/main.dart+++ b/desktop/lib/main.dart@@ -1,4 +1,5 @@import 'dart:async';+import 'dart:ui' show AppExitResponse;import 'package:flutter/material.dart';import 'package:flutter/services.dart';@@ -148,33 +149,55 @@ class RootShell extends ConsumerStatefulWidget {ConsumerState<RootShell> createState() => _RootShellState();}-class _RootShellState extends ConsumerState<RootShell> {+class _RootShellState extends ConsumerState<RootShell>+ with WidgetsBindingObserver {+ bool _menuDialogOpen = false;+@overridevoid initState() {super.initState();+ WidgetsBinding.instance.addObserver(this);_appMenuChannel.setMethodCallHandler(_onAppMenu);}@overridevoid dispose() {+ WidgetsBinding.instance.removeObserver(this);_appMenuChannel.setMethodCallHandler(null);super.dispose();}+ @override+ Future<AppExitResponse> didRequestAppExit() async {+ // Save the final arrangement, with a bound so an unavailable disk cannot+ // trap the user in the app. Input and tab switching never wait for disk.+ await ref+ .read(appStateProvider)+ .flushPaneLayout()+ .timeout(const Duration(seconds: 1), onTimeout: () {});+ return AppExitResponse.exit;+ }+Future<void> _onAppMenu(MethodCall call) async {+ if (!mounted) return;switch (call.method) {case 'checkForUpdates':final app = ref.read(appStateProvider);if (!app.desktopUpdatesEnabled) return;- final result = await app.checkForUpdates();- if (!mounted) return;- await showUpdateCheckDialog(context, app, result);+ await _menuDialog(() async {+ final result = await app.checkForUpdates();+ if (!mounted) return;+ await showUpdateCheckDialog(context, app, result);+ });case 'flashFirmware':- await showFlashFirmwareDialog(context);+ await _menuDialog(() => showFlashFirmwareDialog(context));case 'showLayout':- await showLayoutPalette(context, ref.read(appStateProvider));+ if (advanceLayoutPalette()) return;+ await _menuDialog(+ () => showLayoutPalette(context, ref.read(appStateProvider)),+ );case 'showShortcuts':- await showShortcutsSheet(context);+ await _menuDialog(() => showShortcutsSheet(context));case 'increaseTerminalFontSize':await terminalFontStore.increaseSize();case 'decreaseTerminalFontSize':@@ -184,6 +207,18 @@ class _RootShellState extends ConsumerState<RootShell> {}}+ Future<void> _menuDialog(Future<void> Function() action) async {+ if (_menuDialogOpen || ModalRoute.isCurrentOf(context) == false) return;+ // Reserve before the first frame too: held menu shortcuts can arrive+ // before the new dialog has changed the route's current state.+ _menuDialogOpen = true;+ try {+ await action();+ } finally {+ _menuDialogOpen = false;+ }+ }+@overrideWidget build(BuildContext context) {final app = ref.watch(appStateProvider);diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 6f6332ca1..7c588788c 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -50,6 +50,7 @@ class _SwarmScreenState extends State<SwarmScreen> {final _shellFocus = FocusNode(debugLabel: 'Swarm shell');bool _spokenPaletteOpen = false;bool _dialogOpen = false;+ bool _routeIsCurrent = true;String? _linkDialogMachineId;String? _nativeState;AppNotifier get app => widget.notifier;@@ -69,6 +70,15 @@ class _SwarmScreenState extends State<SwarmScreen> {}}+ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final current = ModalRoute.isCurrentOf(context) ?? true;+ if (_routeIsCurrent == current) return;+ _routeIsCurrent = current;+ if (_native) _syncNative();+ }+@overridevoid dispose() {FocusManager.instance.removeListener(_restoreEmptyFocus);@@ -106,7 +116,7 @@ class _SwarmScreenState extends State<SwarmScreen> {void _syncNative() {final payload = {- 'enabled': !_dialogOpen && !_spokenPaletteOpen,+ 'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,'activeId': app.activeSwarmId,'attention': _attention,'tabs': [@@ -693,7 +703,7 @@ class _SwarmScreenState extends State<SwarmScreen> {),),IconButton(- tooltip: 'Settings',+ tooltip: withShortcutHint('Settings', ShortcutAction.showSettings),onPressed: _settings,icon: const Icon(Icons.settings_outlined, size: 18),),diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 82b5d81d2..2ee4b6800 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -3956,6 +3956,9 @@ class AppNotifier extends ChangeNotifier {int _layoutRevision = 0;+ Future<void> flushPaneLayout() =>+ _paneLayout?.flushSwarms() ?? Future<void>.value();+void _persistLayout() {_layoutRevision++;_announceOpenPanesToDial();diff --git a/desktop/lib/state/pane_layout_store.dart b/desktop/lib/state/pane_layout_store.dartindex bbfd439ff..e0f105f12 100644--- a/desktop/lib/state/pane_layout_store.dart+++ b/desktop/lib/state/pane_layout_store.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:convert';import '../core/harness_file_store.dart';@@ -44,6 +45,10 @@ class PaneLayoutStore {final LocalKeyValueStore _storage;LocalKeyValueStore get storage => _storage;+ String? _pendingSwarmSnapshot;+ Completer<void>? _swarmSave;++ Future<void> flushSwarms() => _swarmSave?.future ?? Future<void>.value();/// Failure is silent and lands on an empty layout, which is exactly the/// first-run state. A corrupt state file is a reason to open the app the way@@ -137,20 +142,43 @@ class PaneLayoutStore {List<Swarm> swarms,String activeId,int nextWallpaper,- ) async {+ ) {+ // Capture each request before yielding, but keep only the latest snapshot+ // while a write is pending. Holding a navigation key must not queue a full+ // state-file rewrite for every intermediate focus or tab selection.try {- await _storage.write(- 'swarm_layout_v1',- jsonEncode({- 'version': 1,- 'activeId': activeId,- 'nextWallpaper': nextWallpaper,- 'swarms': swarms.map((s) => s.toJson()).toList(),- }),- );+ _pendingSwarmSnapshot = jsonEncode({+ 'version': 1,+ 'activeId': activeId,+ 'nextWallpaper': nextWallpaper,+ 'swarms': swarms.map((s) => s.toJson()).toList(),+ });} catch (_) {- // Keep the current desk usable when storage is unavailable.+ return Future<void>.value();+ }+ final active = _swarmSave;+ if (active != null) return active.future;+ final completion = Completer<void>();+ _swarmSave = completion;+ unawaited(_drainSwarmSnapshots(completion));+ return completion.future;+ }++ Future<void> _drainSwarmSnapshots(Completer<void> completion) async {+ while (_pendingSwarmSnapshot != null) {+ final snapshot = _pendingSwarmSnapshot!;+ _pendingSwarmSnapshot = null;+ try {+ await _storage.write('swarm_layout_v1', snapshot);+ } catch (_) {+ // Keep the current desk usable when storage is unavailable. A newer+ // queued snapshot still gets its own attempt.+ }}+ // Clear synchronously before completing: a save requested by a completion+ // listener must start a fresh drain rather than join an already-ended one.+ _swarmSave = null;+ completion.complete();}Future<void> save(List<PaneLayoutEntry> entries) async {diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dartindex 612889250..584958597 100644--- a/desktop/lib/state/swarm.dart+++ b/desktop/lib/state/swarm.dart@@ -32,34 +32,29 @@ class Swarm {if (previousPaneId == pane.id) previousPaneId = null;}- Map<String, Object?> toJson() => {- 'id': id,- 'name': name,- 'wallpaper': wallpaper,- 'focus': panes+ Map<String, Object?> toJson() {+ final agents = panes.where((p) => p.agentId != null)- .toList()- .indexWhere((p) => p.id == focusedPaneId),- 'previousFocus': panes- .where((p) => p.agentId != null)- .toList()- .indexWhere((p) => p.id == previousPaneId),- 'zoom': panes- .where((p) => p.agentId != null)- .toList()- .indexWhere((p) => p.id == zoomedPaneId),- 'presets': {for (final e in presets.entries) '${e.key}': e.value.id},- 'panes': [- for (final p in panes)- if (p.agentId != null)+ .toList(growable: false);+ return {+ 'id': id,+ 'name': name,+ 'wallpaper': wallpaper,+ 'focus': agents.indexWhere((p) => p.id == focusedPaneId),+ 'previousFocus': agents.indexWhere((p) => p.id == previousPaneId),+ 'zoom': agents.indexWhere((p) => p.id == zoomedPaneId),+ 'presets': {for (final e in presets.entries) '${e.key}': e.value.id},+ 'panes': [+ for (final p in agents)PaneLayoutEntry(machineId: p.machineId,agentId: p.agentId!,composerVisible: p.composerVisible,pinnedSlot: pinnedSlots[p.id],).toJson(),- ],- };+ ],+ };+ }}const swarmWallpapers = [diff --git a/desktop/lib/widgets/layout_palette.dart b/desktop/lib/widgets/layout_palette.dartindex a068f300b..c8ddb20ef 100644--- a/desktop/lib/widgets/layout_palette.dart+++ b/desktop/lib/widgets/layout_palette.dart@@ -29,12 +29,13 @@ import '../theme/app_theme.dart';/// Enter takes it. That is how every cycling chord on this OS behaves, and it/// means the shape can be chosen without the hand leaving the chord it arrived/// on.-void Function()? _layoutPaletteAdvance;+bool Function()? _layoutPaletteAdvance;++/// Advance the visible palette without opening another route behind a dialog.+bool advanceLayoutPalette() => _layoutPaletteAdvance?.call() ?? false;Future<void> showLayoutPalette(BuildContext context, AppNotifier notifier) {- final open = _layoutPaletteAdvance;- if (open != null) {- open();+ if (advanceLayoutPalette()) {return Future<void>.value();}return showAppDialog<void>(@@ -133,14 +134,16 @@ class _LayoutPaletteState extends State<_LayoutPalette> {/// a direction: running off the end of a strip you can see the ends of reads/// as a mis-key. A repeated chord is a CYCLE — nobody holding ⌘S means "stop/// at the last one", they mean "show me the next".- void _advance() {+ bool _advance() {+ if (!mounted || ModalRoute.isCurrentOf(context) == false) return false;final count = widget.notifier.panes.length;final choices = PanePreset.forCount(count);- if (choices.isEmpty) return;+ if (choices.isEmpty) return true;// presetFor is keyed on the PANE COUNT, not on how many shapes that count// offers — the two are different numbers and only one of them is a key.final at = _cursorIn(choices, widget.notifier.presetFor(count));setState(() => _cursor = (at + 1) % choices.length);+ return true;}/// Which shape the arrow keys are resting on, which is NOT the same as thediff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex fcc3d1014..e85a790e6 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -89,18 +89,22 @@ class PaneGrid extends StatelessWidget {for (final pane in notifier.allPanes)if (!visible.contains(pane) && pane.lastViewSize != null)Positioned.fill(- child: Offstage(- offstage: true,- child: TickerMode(- enabled: false,- child: ExcludeFocus(- child: OverflowBox(- alignment: Alignment.topLeft,- minWidth: pane.lastViewSize!.width,- maxWidth: pane.lastViewSize!.width,- minHeight: pane.lastViewSize!.height,- maxHeight: pane.lastViewSize!.height,- child: cell(pane, visible: false),+ key: ValueKey(pane.id),+ child: _ParkedPane(+ session: pane.session,+ child: Offstage(+ offstage: true,+ child: TickerMode(+ enabled: false,+ child: ExcludeFocus(+ child: OverflowBox(+ alignment: Alignment.topLeft,+ minWidth: pane.lastViewSize!.width,+ maxWidth: pane.lastViewSize!.width,+ minHeight: pane.lastViewSize!.height,+ maxHeight: pane.lastViewSize!.height,+ child: cell(pane, visible: false),+ ),),),),@@ -230,6 +234,34 @@ class PaneGrid extends StatelessWidget {}}+/// A tab switch does not change terminals that stay hidden. Keep their widget+/// configuration as well as their renderer; rebuilding their headers, menus,+/// and gestures makes switching cost grow with every previously visited tab.+/// Session replacement still reaches the parked view. When shown, the cell's+/// GlobalKey moves it into the active layout with current agent metadata.+class _ParkedPane extends StatefulWidget {+ const _ParkedPane({required this.session, required this.child});++ final TerminalSession? session;+ final Widget child;++ @override+ State<_ParkedPane> createState() => _ParkedPaneState();+}++class _ParkedPaneState extends State<_ParkedPane> {+ late Widget _child = widget.child;++ @override+ void didUpdateWidget(_ParkedPane oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (!identical(oldWidget.session, widget.session)) _child = widget.child;+ }++ @override+ Widget build(BuildContext context) => _child;+}+/// Five or more tiles: a grid, sized by what a terminal actually needs.////// The column count is NOT ceil(sqrt(n)). A terminal is unusable below 40diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex bca5ae3fe..8f866a5d5 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -166,7 +166,6 @@ private final class SwarmTabStrip: NSView {notifications.setAccessibilityLabel(notifications.toolTip)needsLayout = truelayoutSubtreeIfNeeded()- if let active = tabs.first(where: { $0.swarmId == activeId }) { document.scrollToVisible(active.frame) }}override func layout() {@@ -182,6 +181,9 @@ private final class SwarmTabStrip: NSView {newButton.frame = NSRect(x: occupied + 3, y: 4, width: 30, height: 30)notifications.frame = NSRect(x: bounds.width - 69, y: 4, width: 30, height: 30)settings.frame = NSRect(x: bounds.width - 35, y: 4, width: 30, height: 30)+ if let active = tabs.first(where: { $0.swarmId == activeId }) {+ document.scrollToVisible(active.frame)+ }}override func mouseDown(with event: NSEvent) {if event.clickCount == 2 { window?.performZoom(nil) }@@ -203,10 +205,10 @@ private final class SwarmTabStrip: NSView {}}-private final class SwarmTabButton: NSView, NSDraggingSource {+private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidation {let swarmId: String- var name = "New swarm"- var selected = false+ var name = "New swarm" { didSet { updateAccessibility() } }+ var selected = false { didSet { updateAccessibility() } }var attention = falsevar emit: ((String, Any?) -> Void)?private let closeButton = NSButton()@@ -246,6 +248,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource {menu.addItem(item)}self.menu = menu+ updateAccessibility()}required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }override func layout() {@@ -267,12 +270,17 @@ private final class SwarmTabButton: NSView, NSDraggingSource {NSColor.systemOrange.setFill()NSBezierPath(ovalIn: NSRect(x: 4, y: 16, width: 4, height: 4)).fill()}+ }+ // Overflowed tabs might not be drawn. Their names and selection still need+ // to be available to VoiceOver and automation before they scroll into view.+ private func updateAccessibility() {setAccessibilityLabel(name)selectButton.setAccessibilityLabel("Select \(name)")selectButton.setAccessibilityValue(selected ? "Selected" : "")toolTip = "\(name) — double-click to rename"closeButton.setAccessibilityLabel("Close \(name)")}+ func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { actionsEnabled }override func mouseDown(with event: NSEvent) {guard actionsEnabled else { return }downPoint = event.locationInWindowdiff --git a/desktop/test/app_menu_test.dart b/desktop/test/app_menu_test.dartnew file mode 100644index 000000000..653050393--- /dev/null+++ b/desktop/test/app_menu_test.dart@@ -0,0 +1,118 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_riverpod/flutter_riverpod.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/main.dart';+import 'package:harness/settings/settings_screen.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_preset.dart';++import 'swarm_state_test.dart' show createApp;++Future<void> _menu(WidgetTester tester, String method) {+ final result = Completer<void>();+ const codec = StandardMethodCodec();+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(+ 'harness/app_menu',+ codec.encodeMethodCall(MethodCall(method)),+ (reply) {+ try {+ codec.decodeEnvelope(reply!);+ result.complete();+ } catch (error, stack) {+ result.completeError(error, stack);+ }+ },+ );+ return result.future;+}++Future<void> _mount(WidgetTester tester, AppNotifier app) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 800);+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ app.status = AppStatus.authenticated;+ await tester.pumpWidget(+ ProviderScope(+ overrides: [appStateProvider.overrideWithValue(app)],+ child: const DesktopApp(),+ ),+ );+ await tester.pump();+}++void main() {+ testWidgets('held app menu commands open only one dialog', (tester) async {+ final app = createApp();+ await _mount(tester, app);+ final first = _menu(tester, 'showShortcuts');+ final repeated = _menu(tester, 'showShortcuts');+ await tester.pump(const Duration(milliseconds: 300));+ await repeated;+ expect(find.byType(Dialog), findsOneWidget);+ await _menu(tester, 'showLayout');+ await _menu(tester, 'flashFirmware');+ expect(find.byType(Dialog), findsOneWidget);+ Navigator.of(tester.element(find.byType(Dialog))).pop();+ await tester.pump(const Duration(milliseconds: 300));+ await first;+ expect(find.byType(Dialog), findsNothing);+ final reopened = _menu(tester, 'showShortcuts');+ await tester.pump(const Duration(milliseconds: 300));+ expect(find.byType(Dialog), findsOneWidget);+ Navigator.of(tester.element(find.byType(Dialog))).pop();+ await tester.pump(const Duration(milliseconds: 300));+ await reopened;+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });++ testWidgets('repeated layout menu shortcut cycles the visible palette', (+ tester,+ ) async {+ final app = createApp();+ for (var i = 0; i < 3; i++) {+ await app.addAgentToSwarm('m', 'a$i');+ }+ await _mount(tester, app);+ final before = app.presetFor(3);+ final opened = _menu(tester, 'showLayout');+ final beforeFirstFrame = _menu(tester, 'showLayout');+ await tester.pump(const Duration(milliseconds: 300));+ await beforeFirstFrame;+ await _menu(tester, 'showLayout');+ await _menu(tester, 'showShortcuts');+ await tester.pump();+ expect(find.byType(Dialog), findsOneWidget);+ expect(app.presetFor(3), before);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump(const Duration(milliseconds: 300));+ await opened;+ expect(app.presetFor(3), PanePreset.forCount(3)[1]);+ expect(find.byType(Dialog), findsNothing);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });++ testWidgets('app menu dialogs do not open over Settings', (tester) async {+ final app = createApp();+ await _mount(tester, app);+ await tester.tap(find.byTooltip('Settings ⌘,'));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 300));+ expect(find.byType(SettingsScreen), findsOneWidget);+ for (final method in ['showShortcuts', 'showLayout', 'flashFirmware']) {+ await _menu(tester, method);+ }+ await tester.pump();+ expect(find.byType(Dialog), findsNothing);+ expect(find.byType(SettingsScreen), findsOneWidget);+ Navigator.of(tester.element(find.byType(SettingsScreen))).pop();+ await tester.pump(const Duration(milliseconds: 300));+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+}diff --git a/desktop/test/benchmarks/swarm_benchmark.dart b/desktop/test/benchmarks/swarm_benchmark.dartnew file mode 100644index 000000000..85a14ea6e--- /dev/null+++ b/desktop/test/benchmarks/swarm_benchmark.dart@@ -0,0 +1,150 @@+// Run explicitly: flutter test test/benchmarks/swarm_benchmark.dart --reporter expanded+// These are headless CPU measurements, not network or display latency claims.+import 'dart:convert';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/widgets/terminal_panel.dart';++import '../swarm_screen_test.dart' show mount;+import '../swarm_state_test.dart' show createApp;++Map<String, num> distribution(List<int> microseconds) {+ microseconds.sort();+ return {+ 'samples': microseconds.length,+ 'medianMs': microseconds[microseconds.length ~/ 2] / 1000,+ 'p95Ms': microseconds[(microseconds.length * 0.95).ceil() - 1] / 1000,+ };+}++Map<String, num> measure(void Function() operation) {+ for (var i = 0; i < 20; i++) {+ operation();+ }+ final times = <int>[];+ for (var i = 0; i < 100; i++) {+ final watch = Stopwatch()..start();+ operation();+ times.add(watch.elapsedMicroseconds);+ }+ return distribution(times);+}++void main() {+ test('large live catalog CPU benchmark', () {+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession());+ addTearDown(app.dispose);+ for (var machine = 0; machine < 8; machine++) {+ final id = 'machine-$machine';+ app.machineStates[id] =+ MachineState(+ Machine(+ machineId: id,+ authMode: MachineAuthMode.remote,+ name: 'Machine $machine',+ ),+ )+ ..agents = [+ for (var agent = 0; agent < 250; agent++)+ Agent(+ id: 'agent-$agent',+ name: 'Agent $agent',+ engine: 'codex',+ project: AgentProject(+ name: 'Project ${agent % 50}',+ cwd: '/work/project-${agent % 50}',+ remote: 'example.invalid/team/project-${agent % 50}',+ branch: 'main',+ ),+ ),+ ];+ }+ expect(swarmAgents(app), hasLength(2000));+ expect(swarmProjects(app, const []), hasLength(50));+ debugPrint(+ 'SWARM_BENCH ${jsonEncode({'kind': 'headless_debug_cpu', 'agents': 2000, 'machines': 8, 'search': measure(() {+ swarmAgents(app, 'Agent 12 Project 12');+ }), 'projectGrouping': measure(() {+ swarmProjects(app, const []);+ })})}',+ );+ });++ for (final swarmCount in [4, 12]) {+ testWidgets('tab-switch CPU benchmark with $swarmCount retained swarms', (+ tester,+ ) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final first = app.activeSwarmId;+ for (var swarm = 0; swarm < swarmCount; swarm++) {+ if (swarm != 0) app.newSwarm();+ for (var pane = 0; pane < 4; pane++) {+ final id = 'a${swarm * 4 + pane}';+ final session =+ TerminalSession(+ machineId: 'm',+ agentId: id,+ agentName: 'Agent $id',+ engineId: 'codex',+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 'stream-$id';+ session.terminal.write(+ List.generate(+ 1000,+ (line) =>+ '\x1b[32m$line\x1b[0m terminal output with project context\r\n',+ ).join(),+ );+ app.adoptSessionForTest(session);+ }+ }+ app.selectSwarm(first);+ await mount(tester, app);+ for (var warmup = 0; warmup < swarmCount * 3; warmup++) {+ app.stepSwarm(1);+ await tester.pump();+ }+ final times = <int>[];+ for (var sample = 0; sample < 60; sample++) {+ final watch = Stopwatch()..start();+ app.stepSwarm(1);+ await tester.pump();+ times.add(watch.elapsedMicroseconds);+ }+ expect(find.byType(TerminalPanel), findsNWidgets(4));+ expect(+ find.byType(TerminalPanel, skipOffstage: false),+ findsNWidgets(swarmCount * 4),+ );+ final rebuilds = <String, int>{};+ debugOnRebuildDirtyWidget = (element, _) {+ final type = element.widget.runtimeType.toString();+ rebuilds.update(type, (count) => count + 1, ifAbsent: () => 1);+ };+ try {+ app.stepSwarm(1);+ await tester.pump();+ } finally {+ debugOnRebuildDirtyWidget = null;+ }+ final largest = rebuilds.entries.toList()+ ..sort((a, b) => b.value.compareTo(a.value));+ debugPrint(+ 'SWARM_BENCH ${jsonEncode({'kind': 'headless_debug_cpu', 'swarms': swarmCount, 'terminals': swarmCount * 4, 'scrollbackLinesPerTerminal': 1000, 'viewport': '1280x800', 'tabSwitchAndFrame': distribution(times), 'rebuildsPerSwitch': rebuilds.values.fold(0, (total, count) => total + count), 'mostRebuiltWidgets': Map.fromEntries(largest.take(12))})}',+ );+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+ }+}diff --git a/desktop/test/boot_flow_widget_test.dart b/desktop/test/boot_flow_widget_test.dartindex eba164fed..52916036d 100644--- a/desktop/test/boot_flow_widget_test.dart+++ b/desktop/test/boot_flow_widget_test.dart@@ -798,7 +798,7 @@ void main() {),);await tester.pumpAndSettle();- await tester.tap(find.byTooltip('Settings'));+ await tester.tap(find.byTooltip(RegExp(r'^Settings')));await tester.pumpAndSettle();await tester.tap(find.text('Account'));await tester.pumpAndSettle();diff --git a/desktop/test/swarm_async_test.dart b/desktop/test/swarm_async_test.dartindex 489feb6d9..e8753edd3 100644--- a/desktop/test/swarm_async_test.dart+++ b/desktop/test/swarm_async_test.dart@@ -1,8 +1,13 @@import 'dart:async';import 'dart:convert';+import 'dart:ui' show AppExitResponse;+import 'package:flutter/material.dart';+import 'package:flutter_riverpod/flutter_riverpod.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/main.dart';+import 'package:harness/state/app_state.dart';import 'package:harness/state/swarm_catalog.dart';import 'package:harness/ws/ws_conn.dart';@@ -55,7 +60,91 @@ class _DelayedStore extends MemoryStore {}}+class _PendingWriteStore extends MemoryStore {+ final release = Completer<void>();+ final snapshots = <String>[];+ bool failFirst = false;+ @override+ Future<void> write(String key, String value) async {+ if (key == 'swarm_layout_v1') {+ snapshots.add(value);+ if (snapshots.length == 1) {+ await release.future;+ if (failFirst) throw StateError('Busy fixture disk');+ }+ }+ await super.write(key, value);+ }+}+void main() {+ for (final failFirst in [false, true]) {+ test(+ 'rapid tab changes save only the final queued layout after ${failFirst ? 'a failed' : 'a slow'} write',+ () async {+ final storage = _PendingWriteStore()..failFirst = failFirst;+ final app = createApp(store: storage);+ addTearDown(app.dispose);+ app.newSwarm();+ for (var i = 0; i < 100; i++) {+ app.stepSwarm(1);+ }+ app.renameSwarm(app.activeSwarmId, 'Final arrangement');+ expect(storage.snapshots, hasLength(1));+ final saving = app.flushPaneLayout();+ storage.release.complete();+ await saving;+ expect(storage.snapshots, hasLength(2));+ final saved = jsonDecode(storage.values['swarm_layout_v1']!) as Map;+ expect(saved['activeId'], app.activeSwarmId);+ expect((saved['swarms'] as List).last['name'], 'Final arrangement');+ app.renameSwarm(app.activeSwarmId, 'After completion');+ await app.flushPaneLayout();+ expect(storage.snapshots, hasLength(3));+ expect(storage.snapshots.last, contains('After completion'));+ },+ );+ }++ for (final timedOut in [false, true]) {+ testWidgets(+ 'quit ${timedOut ? 'stays available with a stalled disk' : 'waits for the latest saved arrangement'}',+ (tester) async {+ final storage = _PendingWriteStore();+ final app = createApp(store: storage)..status = AppStatus.authenticated;+ app.newSwarm();+ app.renameSwarm(app.activeSwarmId, 'Before quit');+ await tester.pumpWidget(+ ProviderScope(+ overrides: [appStateProvider.overrideWithValue(app)],+ child: const DesktopApp(),+ ),+ );+ await tester.pump();+ final observer =+ tester.state(find.byType(RootShell)) as WidgetsBindingObserver;+ var completed = false;+ final quitting = observer.didRequestAppExit().then((result) {+ completed = true;+ return result;+ });+ await tester.pump();+ expect(completed, isFalse);+ if (timedOut) {+ await tester.pump(const Duration(seconds: 1));+ expect(completed, isTrue);+ }+ storage.release.complete();+ await tester.pump();+ expect(await quitting, AppExitResponse.exit);+ await app.flushPaneLayout();+ expect(storage.values['swarm_layout_v1'], contains('Before quit'));+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );+ }+for (final change in ['switch', 'close', 'dispose']) {test('an agent launch stays with its destination after $change during the RPC',diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dartindex 12daef093..334fbd75d 100644--- a/desktop/test/swarm_interactions_test.dart+++ b/desktop/test/swarm_interactions_test.dart@@ -226,6 +226,19 @@ void main() {await tester.pump(const Duration(milliseconds: 300));await opening;expect(updates.last['enabled'], isTrue);+ // Root app-menu dialogs enter outside SwarmScreen's own dialog helper.+ final external = showDialog<void>(+ context: tester.element(find.byType(SwarmScreen)),+ builder: (_) => const AlertDialog(title: Text('External menu dialog')),+ );+ await tester.pump(const Duration(milliseconds: 300));+ expect(updates.last['enabled'], isFalse);+ await native('new');+ expect(app.swarms.single.id, 'swarm-1');+ Navigator.of(tester.element(find.byType(AlertDialog))).pop();+ await tester.pump(const Duration(milliseconds: 300));+ await external;+ expect(updates.last['enabled'], isTrue);await tester.pumpWidget(const SizedBox());projects.dispose();app.dispose();diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dartindex c1e8ba0a9..c7f2b4fb9 100644--- a/desktop/test/swarm_screen_test.dart+++ b/desktop/test/swarm_screen_test.dart@@ -197,6 +197,94 @@ void main() {},);+ testWidgets(+ 'parked terminals keep output, selection, scroll and fresh metadata on return',+ (tester) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final session = terminal('a0', []);+ session.terminal.write(+ List.generate(200, (i) => 'saved line $i\r\n').join(),+ );+ app.adoptSessionForTest(session);+ final first = app.activeSwarmId;+ await mount(tester, app);+ final renderer = tester.state(find.byType(TerminalView));+ final view = tester.widget<TerminalView>(find.byType(TerminalView));+ view.scrollController!.jumpTo(100);+ view.controller!.setSelection(+ session.terminal.buffer.createAnchor(0, 3),+ session.terminal.buffer.createAnchor(5, 3),+ );+ await tester.pump();+ final selection = session.terminal.buffer.getText(+ view.controller!.selection,+ );+ final scroll = view.scrollController!.offset;+ app.newSwarm();+ await tester.pump();+ // A second switch leaves the first terminal parked in the same slot.+ app.newSwarm();+ session.terminal.write('arrived while hidden\r\n');+ await app.handleEventForTest('m', {+ 'type': 'agent_renamed',+ 'payload': {'agentId': 'a0', 'name': 'Renamed while hidden'},+ });+ await tester.pump();+ expect(find.byType(TerminalView), findsNothing);+ expect(view.scrollController!.offset, scroll);+ app.selectSwarm(first);+ await tester.pump();+ expect(tester.state(find.byType(TerminalView)), same(renderer));+ expect(find.text('Renamed while hidden'), findsOneWidget);+ expect(+ session.terminal.buffer.getText(),+ contains('arrived while hidden'),+ );+ expect(+ session.terminal.buffer.getText(view.controller!.selection),+ selection,+ );+ expect(view.scrollController!.offset, scroll);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );++ testWidgets(+ 'a replacement session reaches its parked view before the tab is shown',+ (tester) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final original = terminal('a0', []);+ final pane = app.adoptSessionForTest(original);+ final first = app.activeSwarmId;+ await mount(tester, app);+ app.newSwarm();+ await tester.pump();+ final replacement = terminal('a0', [])+ ..terminal.write('replacement stream');+ pane.session = replacement;+ app.newSwarm();+ await tester.pump();+ final parked = tester.widget<TerminalPanel>(+ find.byType(TerminalPanel, skipOffstage: false),+ );+ expect(parked.session, same(replacement));+ expect(parked.visible, isFalse);+ original.removeListener(app.notifyListeners);+ original.dispose();+ app.selectSwarm(first);+ await tester.pump();+ expect(+ tester.widget<TerminalPanel>(find.byType(TerminalPanel)).session,+ same(replacement),+ );+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );+testWidgets('notifications show only current questions and navigate to their originating swarm',(tester) async {diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.mdnew file mode 100644index 000000000..926d0c79e--- /dev/null+++ b/docs/harness-v2-performance.md@@ -0,0 +1,36 @@+# Harness V2 performance checks++Measured on 2026-09-12 with Apple M2 Max, macOS 26.6.2, Flutter 3.47.2 and Dart 3.13.2.++The explicit benchmark runs in the headless Flutter test runner with isolated synthetic sessions. It never opens a sample-data app or connects to a real agent. Run it from `desktop/`:++```bash+flutter test --no-pub --reporter expanded test/benchmarks/swarm_benchmark.dart+```++It prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in `_test.dart`, so ordinary correctness runs do not include timing measurements.++## Current measurements++| Operation | Median CPU time | p95 CPU time |+| --- | ---: | ---: |+| Search 2,000 agents across 8 machines | 1.06 ms | 1.13 ms |+| Group the same catalog into 50 projects | 1.14 ms | 1.27 ms |+| Switch tab and pump a frame: 4 swarms, 16 terminals | 18.45 ms | 25.88 ms |+| Switch tab and pump a frame: 12 swarms, 48 terminals | 14.51 ms | 16.95 ms |++Catalog operations use 20 warmups and 100 samples. Each terminal has 1,000 scrollback lines; the window is 1280 × 800 with four visible terminals. Tab checks warm up for three full cycles, then take 60 samples. They retain one renderer per session and include Flutter frame work and test-runner overhead. Network, persistence I/O, AppKit titlebar rendering and physical display latency are outside these measurements.++These are **debug CPU measurements**, not end-to-end input latency or release frame budgets. JIT warming and host load affect timings; the later 12-swarm case being faster does not establish that more tabs make the app faster. Use the structural counts below to assess the specific optimization.++## Reduced work when switching tabs++Previously, switching between two swarms rebuilt headers, gestures and menus for terminals in every previously visited swarm. Hidden panes now retain their widget configuration as well as their renderer, with stable identities in the parked list. Session replacement updates a parked view; showing it applies current machine and agent metadata.++With 16 retained terminals, one switch went from **2,480 to 1,491 widget rebuilds**, a 40% reduction. With 48 retained terminals, it rebuilt 1,625 widgets. Background output continues reaching the session buffer. Regression checks cover renderer identity, hidden geometry, input ownership, selection, scroll position, renaming while hidden and session replacement.++Rapid navigation also coalesces pending arrangement writes. While the first write is in flight, only the latest subsequent snapshot is retained. Tests with 100 rapid tab changes verify that the first and final snapshots are written, including recovery after the first write fails. Normal quit waits for the final snapshot with a one-second bound for stalled storage.++## Native follow-up++The optimized real-data app builds and runs locally. Measure release input-to-display and tab-switch latency in the unlocked native window before making latency claims. The screen was locked during this pass, so native drag, overflow and visual inspection remain in the development handoff.diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdindex b547dc479..9244cd3d2 100644--- a/docs/harness-v2-progress.md+++ b/docs/harness-v2-progress.md@@ -54,6 +54,7 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83- Seeding records membership synchronously before awaiting attachments. Agent creation captures its destination before the RPC completes, so tab switching cannot redirect results.- Limits: 24 swarms, 64 panes per swarm. Add, seed, and dial paths report capacity explicitly without silently evicting a view; legacy migration retains the nine-pane storage limit.- `PaneLayoutStore` writes `swarm_layout_v1`: tab order/selection/names, wallpaper, pane intent, focus/zoom, presets, per-swarm pins, composer visibility.+- Pending writes coalesce to the latest snapshot during rapid navigation. Normal quit waits for the final arrangement with a one-second limit if storage stalls. Snapshot encoding reuses one filtered pane list per Swarm.- Restore pools shared pane identity, keeps disconnected memberships, and defers initial attachment of inactive panes until shown. Previous focus is persisted; grid columns remain measured runtime geometry. Revision guards cover every asynchronous legacy restore read.- Focus follows zoom and wraps without an invisible sidebar. Legacy `HomeScreen`/rail code remains but is no longer the authenticated V2 shell.- Agent comparison considers project and launch-state metadata so polling can refresh those details.@@ -61,6 +62,7 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83### Retained terminal views- `PaneGrid` swarm mode parks previously displayed inactive terminal widgets under Offstage with ticking/focus disabled and their last visible dimensions preserved.+- Parked panes retain their widget configuration while hidden, so tab changes do not rebuild unrelated terminal headers and controls. A replaced session still updates its parked view; returning to a tab uses current metadata. The 16-terminal benchmark dropped from 2,480 to 1,491 widget rebuilds per switch; see `docs/harness-v2-performance.md` for measurements and limits.- `TerminalPane.lastViewSize` retains geometry. Hidden `TerminalPanel` views stop auto-resizing/reporting viewport and release input focus.- Compact headers remove routine transport/status/pin clutter, retaining exceptional states and offline/unavailable placeholders.- Existing terminal sessions/transports/renderer and patched `third_party/xterm` are retained. One regression verifies renderer identity, hidden geometry during window resize, and input going only to the active view.@@ -86,6 +88,7 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83- `NSTitlebarAccessoryViewController` with native scrollable tabs, new button, notification bell, settings. Automatic native window tabbing disabled; Flutter content begins below title bar.- Method channel `harness/swarm_tabs`: Dart sends tab ID/name/selection/attention; Swift sends new/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.+- Accessibility names/selection update with state, including overflowed tabs that have never painted. Tab context menus obey modal-disabled state. Layout reveals the selected tab after window resize.- Native Swarm menu includes new/close/rename, previous/next, Add agent, close agent view, Settings.- Real tabs alongside traffic lights were visually verified. Native selection, new tabs, modal-disabled controls, and independently accessible select/close buttons were checked. Drag/reorder, overflow, and a wider keyboard/accessibility audit remain.@@ -126,21 +129,22 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83| Settings / shortcut sheet | Cmd+, / Cmd+/ || Close agent view | Cmd+Shift+W |-Swarm shortcuts, help, and tooltips now read the same catalog in `shortcuts/app_shortcuts.dart`. The retained legacy HomeScreen explicitly opts into its old bindings. Native Swarm actions and controls are blocked while Swarm dialogs or Settings are open. Clipboard/select-all and shell/TUI keys remain owned by the terminal. Do not add AppKit menu equivalents that intercept Cmd+H/J before Flutter.+Swarm shortcuts, help, and tooltips now read the same catalog in `shortcuts/app_shortcuts.dart`. The retained legacy HomeScreen explicitly opts into its old bindings. Native Swarm actions and controls are blocked whenever another route is above the shell, including root app-menu dialogs. Held Layout/Shortcuts/Firmware menu commands cannot stack dialogs; repeated Cmd+S still cycles the visible Layout palette. Clipboard/select-all and shell/TUI keys remain owned by the terminal. Do not add AppKit menu equivalents that intercept Cmd+H/J before Flutter.## Verification and limits| Check | Result || --- | --- || macOS debug build | Passed and launched from the monorepo with real saved Swarms and terminals. |-| macOS optimized local build | Passed with ad hoc signing and the real entry point. The distribution Developer ID certificate is unavailable; nothing was uploaded. The Mac locked before visual review, and the running debug app declined a normal quit request, so it was left running. |-| Full Flutter suite | **968 passed, 1 skipped** after live-project discovery, keyboard navigation, and multi-machine folder-race fixes. |+| macOS optimized local build | Passed and running with the real entry point and saved V2 state. Local ad hoc signing requires the command-line `ENABLE_HARDENED_RUNTIME=NO` override for Flutter's framework; distribution signing settings remain unchanged. The distribution Developer ID certificate is unavailable; nothing was uploaded. Normal asynchronous quit and relaunch were verified. The screen remains locked, so final native visual review is pending. |+| Full Flutter suite | **977 passed, 1 skipped** after persistence, modal menus and retained-terminal performance changes. || Focused interaction checks | 8 passed: picker navigation/scroll/refresh, welcome keys, shared-view close, composer, native modal guard, profile and folder races. || Local CLI discovery | 25 passed, including older-daemon folder parsing and continuous snapshots without spawning/reconnecting. || CLI typecheck | `npm run typecheck` passed. || CLI targeted tests | 135 passed across project/frame, registry/restore, and terminal recovery files. Project/frame tests rerun after port normalization: 9 passed. || Flutter analyzer | **0 errors, 0 warnings, 12 existing vendored xterm infos**; passes with `--no-fatal-infos`. |-| Remote terminals / production release | No remote takeover, release, installer, or production CLI update/restart. Cross-platform and latency measurements remain. |+| Headless performance | 3 explicit benchmarks passed: 2,000-agent catalog and 16/48 retained terminals. Reproducible command and limits in `docs/harness-v2-performance.md`. |+| Remote terminals / production release | No remote takeover, release, installer, or production CLI update/restart. Cross-platform and end-to-end latency measurements remain. |Tests now exercise the actual V2 welcome/settings/linking flow. Usage pricing again explains a partial estimate as a lower bound. Small offline panes avoid overflowing the full connection guide. No remaining full-suite failures are being dismissed as baseline.@@ -148,22 +152,25 @@ Tests now exercise the actual V2 welcome/settings/linking flow. Usage pricing agEvidence on this Mac under `/private/tmp`:-- `harness-v2-final-tests.log`: full 968-test pass.+- `harness-v2-final-tests.log`: full 977-test pass.- `harness-v2-final-analyze.log`: latest diagnostics.- `harness-v2-final-build.log`: real-entry debug build.- `harness-v2-release-build.log`: optimized local build.- `harness-v2-final-cli-check.log`, `harness-v2-final-cli-tests.log`: final metadata checks.- `harness-v2-resume-cli-tests.log`: 135-test CLI pass.- `harness-v2-keyboard-tests.log`, `harness-v2-local-project-tests.log`: focused interaction/discovery checks.+- `harness-v2-retained-tests.log`: 27 terminal/menu/layout checks.+- `harness-v2-persistence-tests.log`: 21 state/async checks including rapid writes and bounded quit.+- `harness-v2-benchmark-final.log`: latest catalog and retained-terminal CPU measurements.Earlier logs contain superseded failures. Temporary logs and toolchains are local conveniences, not committed artifacts.## Remaining work-1. Launch the completed optimized real-data build after the Mac is unlocked; verify actual local project starters and keyboard navigation in the native shell.+1. Review the running optimized real-data build after the Mac is unlocked; verify actual local project starters and keyboard navigation in the native shell.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 terminal input and tab-switch responsiveness before making latency claims. Preserve the existing immediate first-input flush and shared retained renderers.-4. Audit app-menu modal interactions (the older `harness/app_menu` path also opens Layout/Shortcuts/Firmware dialogs).+3. Measure native terminal input and tab-switch responsiveness before making end-to-end latency claims. Headless CPU benchmarks are now recorded. Preserve the existing immediate first-input flush and shared retained renderers.+4. Visually confirm app-menu modal behavior and overflow accessibility in AppKit; route/shortcut behavior is covered by passing Flutter tests.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. Continue the agreed goal autonomously. The user has stepped away; lack of immediate replies is not a reason to stop independent implementation, checks, or app-v2 publishing.