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.

13.0 KB
Raw Blame
import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/widgets/app_menu.dart';
import 'package:harness/super_tabs/backlog_view.dart';
import 'package:harness/super_tabs/pull_request_facts.dart';

import 'box_render_preview_test.dart' show loadPreviewFonts;
import 'support/super_tab_fixture.dart';

/// Set to a folder to write the PR's screenshots there.
final shots = Platform.environment['SUPER_TAB_BACKLOG_SHOTS'];

/// Set to measure how long the Backlog takes to build with 300 tasks.
final bench = Platform.environment['SUPER_TAB_BACKLOG_BENCH'] != null;

/// Manage ▸ Backlog as the PR shows it (Scholes, task #2355): a Swarm with a
/// task in every group, in both appearances, all of it, Mine, and one project.
void main() {
  setUpAll(() async {
    if (shots != null) await loadPreviewFonts();
  });

  /// [projects] projects, [perProject] tasks in each, cycling through the
  /// states; Scholes asked for every third.
  ConversationServer swarm({int projects = 2, int perProject = 4}) {
    final server = ConversationServer();
    const names = ['openharness', 'lampos', 'website', 'firmware'];
    server.state['projects'] = [
      for (var p = 0; p < projects; p++)
        projectFixture(
          'p$p',
          p < names.length ? names[p] : 'project-$p',
          'chat-$p',
        ),
    ];
    (server.state['people'] as List).addAll([
      {
        'id': 'scholes',
        'email': '[email protected]',
        'username': 'scholes',
        'role': 'collaborator',
      },
      {
        'id': 'huy',
        'email': '[email protected]',
        'username': 'huy',
        'role': 'collaborator',
      },
    ]);
    server.state['agents'] = [
      for (final (id, name, machine) in const [
        ('thorne', 'Thorne', 'pro9'),
        ('lyra', 'Lyra', 'pro9'),
        ('quill', 'Quill', 'studio'),
      ])
        {
          'id': id,
          'name': name,
          'displayName': name,
          'machineId': machine,
          'harnessId': 'h-$id',
          'contributorId': 'owner',
          'configuration': {'engine': 'claude'},
        },
    ];
    server.state['machines'] = [
      {'machineId': 'pro9', 'name': 'MacBook Pro-9'},
      {'machineId': 'studio', 'name': 'Mac Studio'},
    ];
    // Two marked with a priority, as the PM writes it into a title (#2774).
    const titles = [
      'New session starts on the last project',
      'URGENT: sidebar task groups lose their counts',
      'Machine names in every row',
      'Thread reply bar (Scholes, high)',
      'Status menu fixture',
      'GitHub setup line clears in seconds',
    ];
    final now = DateTime(2026, 11, 3, 17).millisecondsSinceEpoch;
    final conversations = server.state['conversations'] as List;
    conversations.removeWhere((g) => (g as Map)['id'] == 'offline');
    var number = 2300;
    for (var p = 0; p < projects; p++) {
      conversations.add({
        ...conversationFixture('chat-$p', 'chat'),
        'projectId': 'p$p',
      });
      for (var i = 0; i < perProject; i++) {
        final state = (number - 2300) % 6;
        final agent = const ['thorne', 'lyra', 'quill'][number % 3];
        conversations.add(<String, dynamic>{
          ...conversationFixture('t$number', titles[state]),
          'projectId': 'p$p',
          'number': number,
          'requesterId': const ['scholes', 'huy', 'owner'][number % 3],
          'agentIds': [if (state > 0) agent],
          if (state > 0)
            'assignment': {
              'id': 'a$number',
              'agentId': agent,
              'status': const [
                '',
                'working',
                'working',
                'review',
                'done',
                'done',
              ][state],
              'progressAt': now,
            },
          if (state == 2)
            'liveness': {
              'state': 'waiting',
              'why': 'person',
              'personId': 'scholes',
              'since': now,
            },
          if (state >= 4) 'shippedAt': now,
          if (state > 0)
            'pullRequestUrls': [
              'https://github.com/autonomous-ai/openharness/pull/${number + 400}',
            ],
          if (state == 5)
            'cards': {
              'pullRequests': [
                {
                  'url':
                      'https://github.com/autonomous-ai/openharness/pull/${number + 400}',
                  'messageId': 'card-$number',
                  'mergedAt': now,
                },
              ],
            },
        });
        number++;
      }
    }
    return server;
  }

  /// [server]'s Swarm as Scholes met it: the reader has nothing open, and what
  /// they asked for shipped and was archived.
  void nothingOpenWithArchived(ConversationServer server) {
    final conversations = server.state['conversations'] as List;
    for (final g in conversations.cast<Map>()) {
      if (g['requesterId'] == 'owner') g['requesterId'] = 'huy';
    }
    final shipped = DateTime(2026, 11, 3, 17).millisecondsSinceEpoch;
    conversations.addAll(<Map<String, dynamic>>[
      for (final (i, title) in const [
        'Thread tags in the sidebar',
        'Round dial fix',
        'Machine row menu',
      ].indexed)
        {
          ...conversationFixture('shipped-$i', title),
          'projectId': 'p0',
          'number': 2200 - i,
          'requesterId': 'owner',
          'archived': true,
          'agentIds': ['thorne'],
          'assignment': {'id': 'a-s$i', 'agentId': 'thorne', 'status': 'done'},
          'shippedAt': shipped,
          'pullRequestUrls': [
            'https://github.com/autonomous-ai/openharness/pull/${2600 + i}',
          ],
          'cards': {
            'pullRequests': [
              {
                'url':
                    'https://github.com/autonomous-ai/openharness/pull/${2600 + i}',
                'messageId': 'card-$i',
                'mergedAt': shipped,
              },
            ],
          },
        },
    ]);
  }

  /// [count] more shipped tasks, an hour apart, so Shipped folds the rest
  /// under Show N more (#2774).
  void manyShipped(ConversationServer server, int count) {
    final shipped = DateTime(2026, 11, 3, 16).millisecondsSinceEpoch;
    (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
      for (var i = 0; i < count; i++)
        {
          ...conversationFixture('more-$i', 'Shipped work number ${i + 1}'),
          'projectId': 'p${i % 2}',
          'number': 2100 - i,
          'requesterId': 'owner',
          'agentIds': ['quill'],
          'assignment': {'id': 'a-m$i', 'agentId': 'quill', 'status': 'done'},
          'shippedAt': shipped - i * 3600000,
          'pullRequestUrls': [
            'https://github.com/autonomous-ai/openharness/pull/${2500 + i}',
          ],
          'cards': {
            'pullRequests': [
              {
                'url':
                    'https://github.com/autonomous-ai/openharness/pull/${2500 + i}',
                'messageId': 'card-m$i',
                'mergedAt': shipped,
              },
            ],
          },
        },
    ]);
  }

  Future<void> show(
    WidgetTester tester,
    ConversationServer server, {
    Brightness brightness = Brightness.light,
    GlobalKey? picture,
    Stopwatch? firstFrame,
    SuperTabPullRequestFacts? facts,
  }) async {
    final c = server.controller();
    addTearDown(c.dispose);
    await c.refresh();
    // Reads wait, so the first frame is timed alone.
    if (firstFrame != null) server.holdReads = Completer<void>();
    grid.AppTheme.brightness.value = brightness;
    addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
    await tester.binding.setSurfaceSize(const Size(1280, 1900));
    addTearDown(() => tester.binding.setSurfaceSize(null));
    firstFrame?.start();
    await tester.pumpWidget(
      MaterialApp(
        theme: grid.buildAppTheme(brightness: brightness),
        builder: (context, child) => picture == null
            ? child!
            : RepaintBoundary(key: picture, child: child),
        home: Scaffold(
          body: ListenableBuilder(
            listenable: c,
            builder: (context, _) => SuperTabBacklogView(
              controller: c,
              facts: facts,
              onOpenConversation: (_) {},
              now: () => (c.groupChangedAt('t2301') ?? DateTime(2026)).add(
                const Duration(minutes: 7),
              ),
            ),
          ),
        ),
      ),
    );
    firstFrame?.stop();
    await tester.pumpAndSettle();
  }

  for (final brightness in Brightness.values) {
    for (final scene in [
      'all',
      'many-shipped',
      'mine',
      'project',
      'mine-nothing-open',
      'mine-empty',
    ]) {
      testWidgets('screenshots for review ($scene, ${brightness.name})', (
        tester,
      ) async {
        final picture = GlobalKey();
        final server = swarm(perProject: 3);
        if (scene == 'mine-nothing-open') {
          // Scholes's 72 (#2885): nothing open, and Shipped still lists.
          nothingOpenWithArchived(server);
          manyShipped(server, 69);
        }
        if (scene == 'mine-empty') {
          // Nothing open and nothing shipped: the one empty message.
          for (final g in (server.state['conversations'] as List).cast<Map>()) {
            if (g['requesterId'] == 'owner') g['requesterId'] = 'huy';
          }
        }
        if (scene == 'many-shipped') manyShipped(server, 12);
        // GitHub's answer for the open pull requests: checks passed on the
        // one in review, and its approval; checks running on the others.
        final facts = SuperTabPullRequestFacts(
          (urls) async => {
            'account': 'scholes',
            'rows': [
              for (final url in urls)
                {
                  'url': url,
                  'status': 'found',
                  'title': 'PR',
                  'state': 'Open',
                  'reviewDecision': url.endsWith('/2703') ? 'APPROVED' : '',
                  'checks': url.endsWith('/2703')
                      ? {'passed': 8, 'failed': 0, 'pending': 0, 'total': 8}
                      : {'passed': 3, 'failed': 0, 'pending': 5, 'total': 8},
                },
            ],
          },
        );
        addTearDown(facts.dispose);
        await show(
          tester,
          server,
          brightness: brightness,
          picture: picture,
          facts: facts,
        );
        if (scene.startsWith('mine')) {
          await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));
          await tester.pumpAndSettle();
        } else if (scene == 'project') {
          await tester.tap(find.byKey(const ValueKey('super-backlog-project')));
          await tester.pumpAndSettle();
          await tester.tap(find.widgetWithText(AppMenuItem, 'lampos').last);
          await tester.pumpAndSettle();
        }
        await tester.runAsync(() async {
          final boundary =
              picture.currentContext!.findRenderObject()!
                  as RenderRepaintBoundary;
          final image = await boundary.toImage(pixelRatio: 2);
          final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
          await Directory(shots!).create(recursive: true);
          await File('$shots/backlog-$scene-${brightness.name}.png')
              .writeAsBytes(bytes!.buffer.asUint8List());
          image.dispose();
        });
      }, skip: shots == null);
    }
  }

  testWidgets('300 open and 300 closed tasks across 30 projects: times', (
    tester,
  ) async {
    final server = swarm(projects: 30, perProject: 10);
    final shipped = DateTime(2026, 11, 3, 17).millisecondsSinceEpoch;
    (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
      for (var p = 0; p < 30; p++)
        for (var i = 0; i < 10; i++)
          {
            ...conversationFixture('closed-$p-$i', 'Shipped and archived'),
            'projectId': 'p$p',
            'number': 1000 + p * 10 + i,
            'requesterId': 'owner',
            'archived': true,
            'assignment': {
              'id': 'c$p$i',
              'agentId': 'thorne',
              'status': 'done',
            },
            'shippedAt': shipped,
          },
    ]);
    final first = Stopwatch();
    await show(tester, server, firstFrame: first);
    final settled = Stopwatch()..start();
    server.holdReads!.complete();
    server.holdReads = null;
    await tester.pumpAndSettle();
    settled.stop();
    final rebuild = Stopwatch()..start();
    await tester.tap(find.byKey(const ValueKey('super-backlog-mine')));
    await tester.pump();
    rebuild.stop();
    // ignore: avoid_print
    print(
      'Backlog: first frame ${first.elapsedMilliseconds} ms, then '
      '${settled.elapsedMilliseconds} ms to settle (closed reads on the fake '
      'server included), filter rebuild ${rebuild.elapsedMilliseconds} ms '
      '(headless debug VM)',
    );
  }, skip: !bench);
}