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.

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

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/terminal/terminal_binary.dart';

import 'support/restart_connection.dart';
import 'swarm_interactions_test.dart' show chord;
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();
  late AppNotifier app;
  late RestartConnection connection;
  var disposed = false;
  const stopped = Agent(
    id: 'saved',
    name: 'Saved work',
    engine: 'codex',
    sessionId: 'original-conversation',
    status: 'stopped',
    project: AgentProject(name: 'Project', cwd: '/work/project'),
  );
  setUp(() {
    disposed = false;
    connection = RestartConnection();
    app = createApp(connectionForTest: (_) => connection, connected: true);
    app.machineStates['m']!.agents.add(stopped);
  });
  tearDown(() {
    if (!disposed) app.dispose();
  });

  SwarmDestination row() =>
      swarmDestinations(app).firstWhere((row) => row.agentId == stopped.id);

  test('stopped harnesses remain searchable alongside live ones', () {
    final rows = swarmDestinations(app);
    expect(rows.any((row) => row.agentId == 'a0'), isTrue);
    expect(row().detail, isNot(contains('Stopped')));
    expect(row().terminalDetail, isNot(contains('Stopped')));
    expect(row().promptContext?.leading, isNot('Stopped'));
    expect(SwarmSearchController.action(row()), 'Open Harness');
    final picker = SwarmSearchController(app, const [], adding: true);
    addTearDown(picker.dispose);
    expect(picker.actionLabel(row()), 'Open');
    expect(rankSwarmDestinations(rows, 'saved').single.agentId, 'saved');
    expect(app.allPanes, isEmpty);
    expect(connection.requests, isEmpty);
  });

  test(
    'an engine that exits into its shell closes the tile it was running in',
    () async {
      // Issue #262: Ctrl+C in a Codex tile. The conversation is archived under the identity that ran
      // it, the surviving shell comes back as a terminal of its own, and the tile that was watching
      // the engine must close rather than sit on "terminal unavailable" with nothing to press.
      final pane = app.adoptSessionForTest(
        terminal('a0', <TerminalBinaryFrame>[]),
      );
      expect(app.panes, [pane]);
      connection.inventory = Completer<Map<String, dynamic>>();

      await app.handleEventForTest('m', {
        'type': 'agent_deleted',
        'payload': {'agentId': 'a0', 'retained': true},
      });
      await app.handleEventForTest('m', {
        'type': 'agent_synced',
        'payload': {
          'agent': {
            'id': 'a0',
            'name': 'Saved work',
            'engine': 'codex',
            'sessionId': 'exited-conversation',
            'status': 'stopped',
            'terminal': {'available': false},
          },
        },
      });
      await app.handleEventForTest('m', {
        'type': 'agent_synced',
        'payload': {
          'agent': {
            'id': 'shell-1',
            'name': 'Terminal harness',
            'engine': 'terminal',
            'terminal': {
              'available': true,
              'runtimes': [
                {'backend': 'tmux', 'paneId': '%7'},
              ],
            },
          },
        },
      });
      connection.inventory!.complete({
        'agents': [
          {
            'id': 'a0',
            'name': 'Saved work',
            'engine': 'codex',
            'sessionId': 'exited-conversation',
            'status': 'stopped',
            'terminal': {'available': false},
          },
          {
            'id': 'shell-1',
            'name': 'Terminal harness',
            'engine': 'terminal',
            'terminal': {
              'available': true,
              'runtimes': [
                {'backend': 'tmux', 'paneId': '%7'},
              ],
            },
          },
        ],
      });
      await Future<void>.delayed(Duration.zero);

      expect(app.allPanes, isEmpty);
      final agents = app.stateOf('m')!.agents;
      expect(agents.firstWhere((agent) => agent.id == 'a0').isStopped, isTrue);
      expect(
        agents.firstWhere((agent) => agent.id == 'shell-1').terminalAvailable,
        isTrue,
      );
      expect(swarmDestinations(app).any((row) => row.agentId == 'a0'), isTrue);
    },
  );

  test(
    'a retained stop refreshes the saved row after closing its live view',
    () async {
      connection.inventory = Completer<Map<String, dynamic>>();
      await app.handleEventForTest('m', {
        'type': 'agent_deleted',
        'payload': {'agentId': 'a0', 'retained': true},
      });
      connection.inventory!.complete({
        'agents': [
          {
            'id': 'a0',
            'name': 'Stopped now',
            'engine': 'codex',
            'sessionId': 'original-conversation',
            'status': 'stopped',
            'terminal': {'available': false},
          },
        ],
      });
      await Future<void>.delayed(Duration.zero);
      expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
      expect(swarmDestinations(app).any((row) => row.agentId == 'a0'), isTrue);
      expect(app.allPanes, isEmpty);
    },
  );

  test('duplicate retained-stop events cannot erase an in-flight saved-history refresh', () async {
    connection.inventory = Completer<Map<String, dynamic>>();
    for (var event = 0; event < 2; event++) {
      await app.handleEventForTest('m', {
        'type': 'agent_deleted',
        'payload': {'agentId': 'a0', 'retained': true},
      });
    }
    connection.inventory!.complete({
      'agents': [
        {
          'id': 'a0',
          'name': 'Retained work',
          'engine': 'codex',
          'sessionId': 'original-conversation',
          'status': 'stopped',
          'terminal': {'available': false},
        },
      ],
    });
    await Future<void>.delayed(Duration.zero);
    expect(app.stateOf('m')!.agents.single.isStopped, isTrue);
    expect(swarmDestinations(app).any((row) => row.agentId == 'a0'), isTrue);
  });

  test(
    'Reopen restores and resumes saved panes without following a tab switch',
    () async {
      await app.addAgentToSwarm('m', 'saved');
      final closedId = app.activeSwarmId;
      await app.closeSwarm(closedId);
      expect(connection.requests, isEmpty);
      expect(app.reopenClosed(), isTrue);
      expect(app.activeSwarmId, closedId);
      final pane = app.panes.single;
      expect(connection.types, ['agent_resume']);
      final repeat = app.openSavedPane(pane.id);
      expect(connection.requests, hasLength(1));
      app.newSwarm();
      final otherId = app.activeSwarmId;
      connection.restartReplies.single.complete(
        restartReceipt(
          connection.requests.single['creationId'] as String,
          agentId: 'saved',
          sessionId: 'original-conversation',
        ),
      );
      await repeat;
      expect(app.activeSwarmId, otherId);
      expect(app.swarms.firstWhere((s) => s.id == closedId).panes, [pane]);
      expect(app.panes, isEmpty);
      expect(
        app
            .stateOf('m')!
            .agents
            .firstWhere((a) => a.id == 'saved')
            .terminalAvailable,
        isTrue,
      );
    },
  );

  testWidgets(
    'a restored stopped pane offers Open and retains a failed resume',
    (tester) async {
      await app.addAgentToSwarm('m', 'saved');
      await mount(tester, app);
      expect(
        find.text(
          'This harness is stopped. Open it to continue your saved conversation.',
        ),
        findsOneWidget,
      );
      expect(
        find.text('terminal unavailable (no verified terminal pane)'),
        findsNothing,
      );
      await tester.tap(find.widgetWithText(TextButton, 'Open'));
      await tester.pump();
      expect(connection.types, ['agent_resume']);
      expect(find.text('Opening saved conversation…'), findsOneWidget);
      connection.restartReplies.single.complete({
        'creationId': connection.requests.single['creationId'],
        'state': 'failed',
        'failure': {
          'code': 'RESUME_UNAVAILABLE',
          'detail': 'Conversation missing',
        },
      });
      await tester.pumpAndSettle();
      expect(app.panes.single.agentId, 'saved');
      expect(find.widgetWithText(TextButton, 'Open'), findsOneWidget);
      expect(find.text('Conversation missing'), findsWidgets);
      await tester.pumpWidget(const SizedBox());
    },
  );

  test('closing a pane while resume is pending cannot recreate it', () async {
    await app.addAgentToSwarm('m', 'saved');
    final pane = app.panes.single;
    final opening = app.openSavedPane(pane.id);
    await app.closePane(pane.id);
    connection.restartReplies.single.complete(
      restartReceipt(
        connection.requests.single['creationId'] as String,
        agentId: 'saved',
        sessionId: 'original-conversation',
      ),
    );
    await opening;
    expect(app.allPanes, isEmpty);
    expect(connection.requests, hasLength(1));
  });

  testWidgets('a stopped pane with retained output also offers Open', (
    tester,
  ) async {
    app.adoptSessionForTest(terminal('saved', []));
    await mount(tester, app);
    expect(
      find.text(
        'Open to continue your saved conversation. Retained output is read only.',
      ),
      findsOneWidget,
    );
    expect(find.text('Open'), findsOneWidget);
    await tester.pumpWidget(const SizedBox());
  });

  for (final placement in HarnessPlacement.values) {
    test('Enter resumes directly before opening ${placement.name}', () async {
      final target = app.activeSwarmId;
      final opening = activateSwarmSearchSelection(
        app,
        SwarmSearchSelection(row()),
        destinationSwarmId: target,
        placement: placement,
      );
      expect(connection.requests, hasLength(1));
      final request = connection.requests.single;
      expect(connection.types, ['agent_resume']);
      expect(request['agentId'], 'saved');
      expect(app.allPanes, isEmpty);
      connection.restartReplies.single.complete(
        restartReceipt(
          request['creationId'] as String,
          agentId: 'saved',
          sessionId: 'original-conversation',
        ),
      );
      expect(await opening, isTrue);
      expect(app.allPanes.single.agentId, 'saved');
      expect(
        app.stateOf('m')!.agents.firstWhere((a) => a.id == 'saved').isStopped,
        isFalse,
      );
    });
  }

  test(
    'a failed resume retains saved work and allocates no empty tab',
    () async {
      final tabs = app.swarms.length;
      final opening = activateSwarmSearchSelection(
        app,
        SwarmSearchSelection(row()),
        destinationSwarmId: app.activeSwarmId,
        placement: HarnessPlacement.newTab,
      );
      final refusal = expectLater(opening, throwsA(isA<SwarmResumeFailure>()));
      connection.restartReplies.single.complete({
        'creationId': connection.requests.single['creationId'],
        'state': 'failed',
        'failure': {
          'code': 'RESUME_UNAVAILABLE',
          'detail': 'Conversation missing',
        },
      });
      await refusal;
      expect(app.swarms, hasLength(tabs));
      expect(app.allPanes, isEmpty);
      expect(row().agentId, 'saved');
      expect(connection.requests, hasLength(1));
    },
  );

  test(
    'Enter on a running harness attaches without a restart request',
    () async {
      final active = swarmDestinations(app)
          .firstWhere((row) => row.agentId == 'a0');
      expect(
        await activateSwarmSearchSelection(
          app,
          SwarmSearchSelection(active),
          destinationSwarmId: app.activeSwarmId,
          placement: HarnessPlacement.currentTab,
        ),
        isTrue,
      );
      expect(app.allPanes.single.agentId, 'a0');
      expect(connection.requests, isEmpty);
    },
  );

  test(
    'repeated Enter joins one request; a lost reply checks its receipt',
    () async {
      final first = app.resumeAgent('m', 'saved');
      final second = app.resumeAgent('m', 'saved');
      expect(identical(first, second), isTrue);
      expect(connection.types, ['agent_resume']);
      final creationId = connection.requests.single['creationId'];
      connection.restartReplies.single.completeError(
        Exception('lost response'),
      );
      expect((await first).error, isNotNull);
      final checking = app.resumeAgent('m', 'saved');
      expect(connection.types, ['agent_resume']);
      expect(connection.checks, hasLength(1));
      expect(connection.checks.single['creationId'], creationId);
      connection.checkReplies.single.complete(
        restartReceipt(
          creationId as String,
          agentId: 'saved',
          sessionId: 'original-conversation',
        ),
      );
      expect((await checking).error, isNull);
    },
  );

  test('native login or hook review is visible while conversation confirmation is pending', () async {
    final opening = activateSwarmSearchSelection(
      app,
      SwarmSearchSelection(row()),
      destinationSwarmId: app.activeSwarmId,
      placement: HarnessPlacement.currentTab,
    );
    await app.handleEventForTest('m', {
      'type': 'agent_synced',
      'payload': {
        'agent': {
          'id': 'saved',
          'name': 'Saved work',
          'engine': 'codex',
          'sessionId': 'original-conversation',
          'launch': {'state': 'starting'},
          'terminal': {'available': true},
        },
      },
    });
    expect(await opening, isTrue);
    expect(app.allPanes.single.agentId, 'saved');
    expect(connection.restartReplies.single.isCompleted, isFalse);
    connection.restartReplies.single.complete(
      restartReceipt(
        connection.requests.single['creationId'] as String,
        agentId: 'saved',
        sessionId: 'original-conversation',
      ),
    );
    await Future<void>.delayed(Duration.zero);
    expect(connection.types, ['agent_resume']);
  });

  test(
    'a different conversation push cannot open an unconfirmed resume',
    () async {
      final opening = activateSwarmSearchSelection(
        app,
        SwarmSearchSelection(row()),
        destinationSwarmId: app.activeSwarmId,
        placement: HarnessPlacement.newTab,
      );
      final failed = expectLater(opening, throwsA(isA<SwarmResumeFailure>()));
      await app.handleEventForTest('m', {
        'type': 'agent_synced',
        'payload': {
          'agent': {
            'id': 'saved',
            'name': 'Different work',
            'engine': 'codex',
            'sessionId': 'other-conversation',
            'launch': {'state': 'starting'},
            'terminal': {'available': true},
          },
        },
      });
      expect(app.allPanes, isEmpty);
      connection.restartReplies.single.complete({
        'creationId': connection.requests.single['creationId'],
        'state': 'failed',
        'failure': {'code': 'RESUME_SESSION_MISMATCH'},
      });
      await failed;
      expect(app.allPanes, isEmpty);
    },
  );

  test('never accepts a fresh conversation as a successful resume', () async {
    final opening = app.resumeAgent('m', 'saved');
    connection.restartReplies.single.complete(
      restartReceipt(
        connection.requests.single['creationId'] as String,
        agentId: 'saved',
        sessionId: 'unexpected-conversation',
      ),
    );
    expect((await opening).error, isNotNull);
    expect(
      app.stateOf('m')!.agents.firstWhere((a) => a.id == 'saved').sessionId,
      'original-conversation',
    );
    expect(app.allPanes, isEmpty);
  });

  test(
    'retained-session pushes preserve existing pane intent and searchability',
    () async {
      await app.handleEventForTest('m', {
        'type': 'agent_synced',
        'payload': {
          'agent': {
            'id': 'saved',
            'name': 'Saved work',
            'engine': 'codex',
            'sessionId': 'original-conversation',
            'status': 'stopped',
            'terminal': {'available': false},
          },
        },
      });
      expect(row().agentId, 'saved');
      expect(connection.requests, isEmpty);
    },
  );

  for (final key in [LogicalKeyboardKey.keyP, LogicalKeyboardKey.keyT]) {
    testWidgets(
      '${key.keyLabel} opens retained work with Enter and preserves other panes',
      (tester) async {
        final existing = app.adoptSessionForTest(terminal('a0', []));
        final originalTab = app.activeSwarmId;
        await mount(tester, app);
        await chord(tester, key);
        if (key == LogicalKeyboardKey.keyT) {
          await openHarnessPicker(tester);
        }
        await tester.pump();
        await tester.enterText(
          find.byKey(const ValueKey('swarm-search-input')),
          'Saved work',
        );
        await tester.pump();
        expect(find.textContaining('Stopped'), findsNothing);
        await tester.sendKeyEvent(LogicalKeyboardKey.enter);
        await tester.pump();
        expect(connection.types, ['agent_resume']);
        expect(find.byType(AlertDialog), findsNothing);
        connection.restartReplies.single.complete(
          restartReceipt(
            connection.requests.single['creationId'] as String,
            agentId: 'saved',
            sessionId: 'original-conversation',
          ),
        );
        await tester.pump();
        await tester.pump(const Duration(milliseconds: 100));
        expect(app.allPanes.any((pane) => pane.agentId == 'saved'), isTrue);
        expect(app.allPanes.contains(existing), isTrue);
        expect(
          app.activeSwarmId == originalTab,
          key == LogicalKeyboardKey.keyP,
        );
        expect(connection.types, ['agent_resume']);
        await tester.pumpWidget(const SizedBox());
        app.dispose();
        disposed = true;
      },
    );
  }

  testWidgets(
    'Enter submits resume immediately and its failure notice expires',
    (tester) async {
      await mount(tester, app);
      await chord(tester, LogicalKeyboardKey.keyT);
      await openHarnessPicker(tester);
      await tester.pump();
      await tester.enterText(
        find.byKey(const ValueKey('swarm-search-input')),
        'Saved work',
      );
      await tester.pump();
      // The preview offers the same action for pointer users; Return submits
      // directly from search without first opening a confirmation dialog.
      expect(find.widgetWithText(TextButton, 'Open'), findsOneWidget);
      expect(find.byType(AlertDialog), findsNothing);
      expect(connection.types, isEmpty);
      await tester.sendKeyEvent(LogicalKeyboardKey.enter);
      await tester.pump();
      expect(connection.types, ['agent_resume']);
      expect(find.byType(AlertDialog), findsNothing);
      connection.restartReplies.single.complete({
        'creationId': connection.requests.single['creationId'],
        'state': 'failed',
        'failure': {
          'code': 'RESUME_UNAVAILABLE',
          'detail': 'Conversation missing',
        },
      });
      await tester.pump();
      expect(find.text('Conversation missing'), findsOneWidget);
      expect(find.text('Start New Conversation'), findsOneWidget);
      expect(find.byTooltip('Dismiss notice'), findsOneWidget);
      expect(app.allPanes, isEmpty);
      // Let the notice finish appearing, then check both sides of its timeout.
      await tester.pumpAndSettle();
      await tester.pump(const Duration(seconds: 9));
      expect(find.text('Conversation missing'), findsOneWidget);
      expect(find.text('Start New Conversation'), findsOneWidget);
      await tester.pump(const Duration(seconds: 1));
      await tester.pumpAndSettle();
      expect(find.text('Conversation missing'), findsNothing);
      expect(find.text('Start New Conversation'), findsNothing);
      expect(find.byTooltip('Dismiss notice'), findsNothing);
      expect(connection.types, ['agent_resume']);
      expect(app.allPanes, isEmpty);
      await tester.pumpWidget(const SizedBox());
    },
  );
}