Skip to content

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

29.0 KB
Raw Blame
import 'support/open_harness.dart';

import 'package:harness/widgets/swarm_switcher.dart';

import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/windows_status_tray.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/terminal_pane.dart';
import 'package:harness/store/store_mark.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/pane_grid.dart';
import 'package:harness/widgets/terminal_panel.dart';
import 'package:harness/ws/local_cli_discovery.dart';
import 'package:xterm/xterm.dart';

import 'swarm_state_test.dart' show createApp;
import 'swarm_interactions_test.dart' show chord;

Future<void> mount(
  WidgetTester tester,
  AppNotifier app, {
  SwarmProjectStore? projects,
  bool nativeTabs = false,
  WindowsStatusTray? statusTray,
}) async {
  tester.view.devicePixelRatio = 1;
  tester.view.physicalSize = const Size(1280, 800);
  addTearDown(tester.view.resetPhysicalSize);
  addTearDown(tester.view.resetDevicePixelRatio);
  await tester.pumpWidget(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: grid.buildAppTheme(brightness: Brightness.dark),
      home: SwarmScreen(
        notifier: app,
        nativeTabs: nativeTabs,
        projectStore: projects ?? SwarmProjectStore(),
        statusTray: statusTray,
      ),
    ),
  );
  await tester.pump(const Duration(milliseconds: 100));
}

/// Whether the native icon loader (`SwarmHistoryIcons` in
/// macos/Runner/SwarmTitlebar.swift) opens [asset]: an exact path it names, or
/// one under a folder it names. Read from the source because no Dart test can
/// run the Swift, and the channel carrying a path the loader then refuses is
/// exactly the break this guards.
bool nativeIconLoaderOpens(String asset) {
  final swift = File('macos/Runner/SwarmTitlebar.swift').readAsStringSync();
  final start = swift.indexOf('class SwarmHistoryIcons');
  expect(start, isNonNegative, reason: 'SwarmHistoryIcons moved');
  final body = swift.substring(start, swift.indexOf('\n}\n', start));
  final exact = RegExp(r'asset == "([^"]+)"')
      .allMatches(body)
      .map((m) => m[1]!);
  final folders = RegExp(r'hasPrefix\("([^"]+/)"\)')
      .allMatches(body)
      .map((m) => m[1]!);
  return !asset.contains('..') &&
      (exact.contains(asset) || folders.any(asset.startsWith));
}

TerminalSession terminal(String id, List<TerminalBinaryFrame> input) =>
    TerminalSession(
        machineId: 'm',
        agentId: id,
        agentName: 'Session $id',
        engineId: 'codex',
        send: (_, _) async => true,
        sendBinary: (frame) async {
          if (frame.kind == TerminalBinaryKind.input) input.add(frame);
          return true;
        },
      )
      ..status = TerminalSessionStatus.controlling
      ..streamId = 'stream-$id';

void main() {
  testWidgets(
    'tabs reveal Command hints and hover close, and preserve Command-W',
    (tester) async {
      final app = createApp();
      final first = app.activeSwarm;
      app.renameSwarm(first.id, 'First tab');
      app.newSwarm(name: 'Second tab');
      final second = app.activeSwarm;
      await mount(tester, app);
      final close = find.byKey(ValueKey('tab-close:${second.id}'));
      expect(close.hitTestable(), findsNothing);
      final label = find.byKey(ValueKey('tab-label:${second.id}'));
      final tab = find.byKey(ValueKey(second.id));
      final nameBounds = tester.getRect(label);
      expect(nameBounds.left, greaterThan(tester.getRect(tab).left));
      expect(nameBounds.center.dx, closeTo(tester.getCenter(tab).dx, .01));
      expect(find.text('2:Second tab'), findsNothing);
      final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
      await mouse.addPointer(location: const Offset(1200, 700));
      await mouse.moveTo(tester.getCenter(label));
      await tester.pumpAndSettle();
      expect(close.hitTestable(), findsOneWidget);
      // Hover reveals ×; hints wait for Command, and a name with room keeps
      // its place.
      expect(find.text('⌘1'), findsNothing);
      expect(find.text('⌘2'), findsNothing);
      expect(tester.getRect(label), nameBounds);
      await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
      await tester.pump();
      expect(find.text('⌘1'), findsOneWidget);
      expect(find.text('⌘2'), findsOneWidget);
      expect(
        find.byKey(ValueKey('tab-close:${first.id}')).hitTestable(),
        findsNothing,
      );
      expect(close.hitTestable(), findsOneWidget);
      expect(app.activeSwarm, same(second));
      await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
      await tester.pump();
      expect(find.text('⌘1'), findsNothing);
      expect(find.text('⌘2'), findsNothing);
      expect(close.hitTestable(), findsOneWidget);
      await tester.sendKeyDownEvent(LogicalKeyboardKey.metaRight);
      await tester.pump();
      expect(find.text('⌘1'), findsOneWidget);
      tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
      await tester.pump();
      expect(find.text('⌘1'), findsNothing, reason: 'focus loss clears hints');
      tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
      await tester.sendKeyUpEvent(LogicalKeyboardKey.metaRight);
      await tester.pump();
      await mouse.removePointer();
      await tester.pump();
      expect(close.hitTestable(), findsNothing);
      Focus.of(tester.element(label)).requestFocus();
      await tester.pumpAndSettle();
      await chord(tester, LogicalKeyboardKey.keyW);
      await tester.pumpAndSettle();
      expect(app.swarms.map((swarm) => swarm.id), [first.id]);
      await tester.pumpWidget(const SizedBox());
      app.dispose();
    },
  );

  for (final native in [false, true]) {
    testWidgets(
      'New Tab keeps opening tabs past two dozen, as Chrome does (native=$native)',
      (tester) async {
        const channel = MethodChannel('harness/swarm_tabs');
        tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
          channel,
          (_) async => true,
        );
        addTearDown(
          () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
            channel,
            null,
          ),
        );
        final app = createApp(connected: true);
        for (var i = 1; i < 30; i++) {
          app.newSwarm(name: 'Project $i');
        }
        app.selectSwarm(app.swarms.first.id);
        await app.addAgentToSwarm('m', 'a0');
        expect(app.swarms, hasLength(30));
        await mount(tester, app, nativeTabs: native);
        if (native) {
          // What Swift sends for File ▸ New Tab, ⌘T and the strip's plus. Not awaited: the handler
          // waits on a frame, which only the pumps below produce.
          tester.binding.defaultBinaryMessenger.handlePlatformMessage(
            'harness/swarm_tabs',
            const StandardMethodCodec().encodeMethodCall(
              const MethodCall('new'),
            ),
            (_) {},
          );
        } else {
          await chord(tester, LogicalKeyboardKey.keyT);
        }
        await tester.pump();
        await tester.pump(const Duration(milliseconds: 300));
        expect(app.swarms, hasLength(31));
        expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
        await openHarnessPicker(tester);
        final input = find.byKey(const ValueKey('swarm-search-input'));
        await tester.enterText(input, 'Agent 1');
        await tester.pump();
        await tester.sendKeyEvent(LogicalKeyboardKey.enter);
        await tester.pump();
        expect(app.swarms, hasLength(31));
        expect(app.panes.single.agentId, 'a1');
        await tester.pumpWidget(const SizedBox());
        app.dispose();
      },
    );
  }

  for (final native in [false, true]) {
    testWidgets('the store tab has a compact text label (native=$native)', (
      tester,
    ) async {
      const channel = MethodChannel('harness/swarm_tabs');
      final updates = <Map>[];
      tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
        call,
      ) async {
        if (call.method == 'update') updates.add(call.arguments as Map);
        return true;
      });
      addTearDown(
        () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
          channel,
          null,
        ),
      );
      final app = createApp();
      final tab = app.activeSwarm;
      await mount(tester, app, nativeTabs: native);
      app.openStore();
      await tester.pump();
      expect(tab.isStore, isTrue);
      if (native) {
        final row = (updates.last['tabs'] as List).single as Map;
        expect(row['kind'], 'store');
        expect(row['agentCount'], 0);
        expect(row['engine'], 'store');
        expect(row['iconAsset'], kStoreMarkAsset);
        // Sending the path is half of it: SwarmTitlebar.swift draws an initial
        // for any asset its loader does not open, which is how the native
        // strip came to show an "S" beside Harness Store.
        expect(
          nativeIconLoaderOpens(kStoreMarkAsset),
          isTrue,
          reason: 'SwarmHistoryIcons must open $kStoreMarkAsset',
        );
        expect(nativeIconLoaderOpens('assets/engine-icons/codex.png'), isTrue);
        expect(
          nativeIconLoaderOpens('assets/harness_device_studio.jpg'),
          isFalse,
        );
      } else {
        expect(find.text('store'), findsOneWidget);
      }
    });

    testWidgets(
      'a harness tab — its agent and that agent\'s viewer — uses the harness type (native=$native)',
      (tester) async {
        const channel = MethodChannel('harness/swarm_tabs');
        final updates = <Map>[];
        tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
          channel,
          (call) async {
            if (call.method == 'update') updates.add(call.arguments as Map);
            return true;
          },
        );
        addTearDown(
          () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
            channel,
            null,
          ),
        );
        final app = createApp();
        final machine = app.stateOf('m')!;
        machine.agents = [
          ...machine.agents,
          const Agent(
            id: 'deck',
            name: 'Quarterly deck',
            engine: 'claude',
            dsh: 'autonomous/marp',
            dshName: 'Marp',
            terminalAvailable: true,
          ),
        ];
        final tab = app.activeSwarm;
        await mount(tester, app, nativeTabs: native);
        await app.addAgentToSwarm('m', 'deck');
        tab.panes.insert(
          0,
          TerminalPane(
            id: 900,
            machineId: 'm',
            kind: PaneKind.web,
            ownerAgentId: 'deck',
            url: 'http://127.0.0.1:1/',
          ),
        );
        app.renameSwarm(tab.id, 'Quarterly deck');
        await tester.pump();
        if (native) {
          final row = (updates.last['tabs'] as List).single as Map;
          expect(row['kind'], 'harness');
          expect(row['agentCount'], 1);
          expect(
            row['engine'],
            'autonomous/marp',
            reason: 'the harness, not the engine under it',
          );
          expect(row['iconAsset'], 'assets/engine-icons/marp.png');
        } else {
          expect(
            find.descendant(
              of: find.byKey(ValueKey(tab.id)),
              matching: find.text('Quarterly deck'),
            ),
            findsOneWidget,
          );
        }

        // An agent the machine no longer lists is drawn as its session's engine,
        // and one with neither is a plain tab.
        final other = TerminalPane(id: 901, machineId: 'm', agentId: 'gone');
        app.newSwarm(name: 'Leftovers');
        final leftovers = app.activeSwarm;
        leftovers.panes.add(other);
        // Back to the harness tab: the strip draws every tab, shown or not.
        app.selectSwarm(tab.id);
        await tester.pump();
        if (native) {
          final row = (updates.last['tabs'] as List).cast<Map>().last;
          expect(row['agentCount'], 1);
          expect(row['engine'], isNull);
          expect(row['iconAsset'], isNull);
        } else {
          expect(find.text('Leftovers'), findsOneWidget);
        }
        final session = terminal('gone', []);
        other.session = session;
        app.renameSwarm(leftovers.id, 'Leftovers again');
        await tester.pump();
        if (native) {
          final row = (updates.last['tabs'] as List).cast<Map>().last;
          expect(row['engine'], 'codex');
          expect(row['iconAsset'], 'assets/engine-icons/codex.png');
        } else {
          expect(find.text('Leftovers again'), findsOneWidget);
        }
        tab.panes.removeWhere((pane) => pane.id == 900);
        leftovers.panes.clear();
        await tester.pumpWidget(const SizedBox());
        app.dispose();
      },
    );

    testWidgets(
      'the store opens past forty tabs, and is still one tab (native=$native)',
      (tester) async {
        const channel = MethodChannel('harness/swarm_tabs');
        final updates = <Map>[];
        tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
          channel,
          (call) async {
            if (call.method == 'update') updates.add(call.arguments as Map);
            return true;
          },
        );
        addTearDown(
          () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
            channel,
            null,
          ),
        );
        final app = createApp();
        await mount(tester, app, nativeTabs: native);
        await app.addAgentToSwarm('m', 'a0');
        for (var i = 0; i < 40; i++) {
          app.newSwarm(name: 'Project $i');
        }
        app.openStore();
        await tester.pump();
        final store = app.activeSwarm;
        expect(store.isStore, isTrue);
        expect(app.swarms, hasLength(42));
        app.selectSwarm(app.swarms.first.id);
        app.openStore();
        await tester.pump();
        expect(app.activeSwarm, same(store));
        expect(app.swarms.where((swarm) => swarm.isStore), hasLength(1));
        if (native) {
          final rows = (updates.last['tabs'] as List).cast<Map>();
          expect(rows, hasLength(42));
          expect(rows.where((row) => row['kind'] == 'store'), hasLength(1));
          expect(rows.last['engine'], 'store');
          expect(updates.last['activeId'], store.id);
        } else {
          // The strip is the one horizontal list; the store is its last tab.
          final strip = find
              .byWidgetPredicate(
                (widget) =>
                    widget is Scrollable &&
                    widget.axisDirection == AxisDirection.right,
              )
              .first;
          // Scrolled, not dragged: a drag on a tab reorders it.
          final position = tester.state<ScrollableState>(strip).position;
          position.jumpTo(position.maxScrollExtent);
          await tester.pump();
          expect(find.text('store'), findsOneWidget);
        }
        await tester.pumpWidget(const SizedBox());
        app.dispose();
      },
    );

    testWidgets('tab identity follows its agent count (native=$native)', (
      tester,
    ) async {
      const channel = MethodChannel('harness/swarm_tabs');
      final updates = <Map>[];
      tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
        call,
      ) async {
        if (call.method == 'update') updates.add(call.arguments as Map);
        return true;
      });
      addTearDown(
        () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
          channel,
          null,
        ),
      );
      final app = createApp();
      final tab = app.activeSwarm;
      await mount(tester, app, nativeTabs: native);
      expect(tab.name, 'New Tab');
      expect(
        find.byKey(const ValueKey('harness-start-search')),
        findsOneWidget,
      );

      await app.addAgentToSwarm('m', 'a0');
      await tester.pump();
      if (native) {
        final row = (updates.last['tabs'] as List).single as Map;
        expect(row['agentCount'], 1);
        expect(row['engine'], 'codex');
        expect(row['iconAsset'], 'assets/engine-icons/codex.png');
      } else {
        expect(find.text('code'), findsOneWidget);
      }

      // A harness's viewer beside its agent is the same agent: still its mark, not a group.
      tab.panes.add(
        TerminalPane(
          id: 900,
          machineId: 'm',
          kind: PaneKind.web,
          ownerAgentId: 'a0',
          url: 'http://127.0.0.1:1/',
        ),
      );
      app.renameSwarm(tab.id, 'New Tab');
      await tester.pump();
      if (native) {
        final row = (updates.last['tabs'] as List).single as Map;
        expect(row['agentCount'], 1);
        expect(row['engine'], 'codex');
      } else {
        expect(find.text('New Tab'), findsOneWidget);
        expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsNothing);
      }
      tab.panes.removeWhere((pane) => pane.id == 900);

      await app.addAgentToSwarm('m', 'a1');
      await tester.pump();
      if (native) {
        final row = (updates.last['tabs'] as List).single as Map;
        expect(row['agentCount'], 2);
        expect(row['engine'], isNull);
      } else {
        expect(find.text('New Tab'), findsOneWidget);
      }

      await app.closePane(app.panes.last.id);
      await tester.pump();
      if (native) {
        expect(
          ((updates.last['tabs'] as List).single as Map)['engine'],
          'codex',
        );
      } else {
        expect(find.text('New Tab'), findsOneWidget);
        expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsNothing);
      }
      expect(app.activeSwarm, same(tab));
      await tester.pumpWidget(const SizedBox());
      app.dispose();
    });
  }

  testWidgets(
    'an older daemon working folder is searchable and seeds its real agents',
    (tester) async {
      final app = createApp(connected: true);
      app.machineStates['m']!.localEndpoint = LocalCliEndpoint(
        computerId: 'local-computer',
        wsUri: Uri.parse('ws://fixture.invalid'),
        protocolVersion: 1,
        terminalProtocolVersion: 3,
        agentProjects: const {
          'a0': AgentProject(name: 'Existing project', cwd: '/work/existing'),
          'a1': AgentProject(name: 'Existing project', cwd: '/work/existing'),
        },
      );
      await mount(tester, app);
      expect(find.text('Existing project'), findsNothing);
      await openHarnessPicker(tester);
      await tester.pump();
      await tester.enterText(
        find.byKey(const ValueKey('swarm-search-input')),
        '/work/existing',
      );
      await tester.pump();
      expect(
        find.byKey(ValueKey(agentDestinationId('m', 'a0'))),
        findsOneWidget,
      );
      expect(
        find.byKey(ValueKey(agentDestinationId('m', 'a1'))),
        findsOneWidget,
      );
      expect(find.byKey(ValueKey(agentDestinationId('m', 'a2'))), findsNothing);
      expect(
        tester
            .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
            .search
            .rows
            .where((row) => row.isProject),
        isEmpty,
      );
      await tester.tap(find.byKey(ValueKey(agentDestinationId('m', 'a0'))));
      await tester.pump(const Duration(milliseconds: 100));
      expect(app.panes.map((p) => p.agentId), ['a0']);
      await tester.pumpWidget(const SizedBox());
      app.dispose();
    },
  );

  testWidgets(
    'welcome, search and picker cancellation leave layout and zoom intact',
    (tester) async {
      final app = createApp(connected: true);
      await mount(tester, app);
      expect(
        find.byKey(const ValueKey('harness-start-search')),
        findsOneWidget,
      );
      expect(find.byKey(const ValueKey('swarm-search-button')), findsOneWidget);
      expect(find.text('Machines'), findsNothing);
      await tester.tap(find.byKey(const ValueKey('swarm-search-button')));
      await tester.pump();
      await tester.enterText(
        find.byKey(const ValueKey('swarm-search-input')),
        'Agent 1',
      );
      await tester.pump();
      expect(find.text('Agent 1').last, findsOneWidget);
      await tester.tap(find.byKey(ValueKey(agentDestinationId('m', 'a1'))));
      await tester.pump();
      await app.addAgentToSwarm('m', 'a2');
      app.toggleZoomPane();
      // New Pane overlays the workspace without resizing its terminals.
      await tester.pump(const Duration(milliseconds: 200));
      final zoom = app.zoomedPaneId;
      final before = tester.getSize(find.byType(PaneGrid));
      await openHarnessPicker(tester);
      await tester.pump(const Duration(milliseconds: 300));
      expect(
        find.byKey(const ValueKey('swarm-search-results')),
        findsOneWidget,
      );
      expect(find.byType(Dialog), findsNothing);
      expect(app.panes.length, 2);
      expect(app.zoomedPaneId, zoom);
      expect(tester.getSize(find.byType(PaneGrid)), before);
      await tester.sendKeyEvent(LogicalKeyboardKey.escape);
      await tester.pump(const Duration(milliseconds: 300));
      expect(app.zoomedPaneId, zoom);
      expect(app.panes.length, 2);
      await tester.pumpWidget(const SizedBox());
      app.dispose();
    },
  );

  testWidgets(
    'tab and zoom switches retain one renderer per session and preserve hidden geometry',
    (tester) async {
      final app = createApp();
      app.machineStates['m']!.nodeOnline = true;
      final framesA = <TerminalBinaryFrame>[];
      final framesB = <TerminalBinaryFrame>[];
      final a = terminal('a0', framesA);
      final b = terminal('a1', framesB);
      app.adoptSessionForTest(a);
      app.adoptSessionForTest(b);
      final first = app.activeSwarmId;
      await mount(tester, app);
      await tester.pump(const Duration(milliseconds: 100));
      final rendererA = tester.state(
        find.byWidgetPredicate(
          (w) => w is TerminalView && w.terminal == a.terminal,
        ),
      );
      final rendererB = tester.state(
        find.byWidgetPredicate(
          (w) => w is TerminalView && w.terminal == b.terminal,
        ),
      );
      final geometryB = (b.terminal.viewWidth, b.terminal.viewHeight);
      app.newSwarm();
      await app.addAgentToSwarm('m', 'a0');
      await tester.pump(const Duration(milliseconds: 80));
      expect(find.byType(TerminalPanel), findsOneWidget);
      expect(find.byType(TerminalPanel, skipOffstage: false), findsNWidgets(2));
      expect(
        tester.state(
          find.byWidgetPredicate(
            (w) => w is TerminalView && w.terminal == a.terminal,
          ),
        ),
        same(rendererA),
      );
      expect((b.terminal.viewWidth, b.terminal.viewHeight), geometryB);
      tester.view.physicalSize = const Size(1000, 700);
      await tester.pump(const Duration(milliseconds: 80));
      expect((b.terminal.viewWidth, b.terminal.viewHeight), geometryB);
      framesA.clear();
      framesB.clear();
      expect(tester.testTextInput.hasAnyClients, isTrue);
      tester.testTextInput.updateEditingValue(
        const TextEditingValue(
          text: 'x',
          selection: TextSelection.collapsed(offset: 1),
        ),
      );
      await tester.pump(const Duration(milliseconds: 30));
      expect(utf8.decode(framesA.expand((f) => f.bytes).toList()), 'x');
      expect(framesB, isEmpty);
      app.selectSwarm(first);
      await tester.pump(const Duration(milliseconds: 80));
      expect(
        tester.state(
          find.byWidgetPredicate(
            (w) => w is TerminalView && w.terminal == b.terminal,
          ),
        ),
        same(rendererB),
      );
      app.toggleZoomPane();
      await tester.pump(const Duration(milliseconds: 60));
      expect(find.byType(TerminalPanel, skipOffstage: false), findsNWidgets(2));
      app.toggleZoomPane();
      await tester.pump(const Duration(milliseconds: 60));
      expect(
        tester.state(
          find.byWidgetPredicate(
            (w) => w is TerminalView && w.terminal == a.terminal,
          ),
        ),
        same(rendererA),
      );
      await tester.pumpWidget(const SizedBox());
      app.dispose();
    },
  );

  testWidgets(
    'parked terminals keep output and selection and reveal the latest 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,
        view.scrollController!.position.maxScrollExtent,
      );
      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.notifyListeners();
      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(
    'attention shortcut opens current questions in Harnesses and their originating tab',
    (tester) async {
      final app = createApp();
      app.machineStates['m']!
        ..nodeOnline = true
        ..connectionStatus = ConnectionStatus.connected;
      await app.addAgentToSwarm('m', 'a0');
      final first = app.activeSwarmId;
      app.newSwarm();
      await app.handleEventForTest('m', {
        'type': 'commander_question',
        'payload': {
          'agentId': 'a0',
          'requestId': 'question',
          'questions': [
            {
              'q': 'Which folder?',
              'options': ['A', 'B'],
            },
          ],
        },
      });
      await mount(tester, app);
      await chord(tester, LogicalKeyboardKey.keyI, shift: true);
      await tester.pump(const Duration(milliseconds: 300));
      expect(find.text('Which folder?'), findsOneWidget);
      await tester.tap(find.byKey(ValueKey(agentDestinationId('m', 'a0'))));
      await tester.pump(const Duration(milliseconds: 300));
      expect(app.activeSwarmId, first);
      expect(app.focusedPane?.agentId, 'a0');
      await app.handleEventForTest('m', {
        'type': 'commander_question_close',
        'payload': {'agentId': 'a0', 'requestId': 'question'},
      });
      await chord(tester, LogicalKeyboardKey.keyI, shift: true);
      await tester.pump(const Duration(milliseconds: 300));
      expect(find.text('No harnesses need your input'), findsOneWidget);
      await tester.pumpWidget(const SizedBox());
      app.dispose();
    },
  );
}