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.

38.2 KB
Raw Blame
import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/attention.dart';
import 'package:harness/super_tabs/activity.dart';
import 'package:harness/super_tabs/buddy_rows.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/project_sidebar.dart';
import 'package:harness/widgets/desktop_chrome.dart';

import 'super_tab_activity_lists_test.dart' show SuperTabActivityTotals;
import 'support/super_tab_fixture.dart';

/// A message from the Lead agent, never the reader's own.
void fromLead(
  ConversationServer server,
  String text, {
  String conversationId = 'lead',
}) {
  server.append(text, conversationId: conversationId);
  server.messages.last['author'] = {
    'kind': 'agent',
    'id': 'lead-agent',
    'name': 'Lead',
  };
}

Map<String, dynamic> conversation(ConversationServer server, String id) =>
    (server.state['conversations'] as List)
        .cast<Map<String, dynamic>>()
        .firstWhere((g) => g['id'] == id);

/// One project, "web-project", whose chat is `lead` and whose workgroup is
/// `offline`.
ConversationServer projectServer() {
  final server = ConversationServer()..threads = true;
  server.state['projects'] = [projectFixture('lead', 'web-project', 'lead')];
  conversation(server, 'offline')
    ..['projectId'] = 'lead'
    ..['number'] = 12;
  return server;
}

Map<String, dynamic> preview(String id, int sequence, String text) => {
  'id': id,
  'sequence': sequence,
  'author': {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'},
  'text': text,
  'createdAt': '2026-10-31T01:00:00Z',
  'attachments': 0,
};

Map<String, dynamic> unreadThread(
  String root,
  int lastReply, {
  String conversationId = 'lead',
  int unread = 1,
  String text = 'Root text',
}) => {
  'conversationId': conversationId,
  'rootId': root,
  'root': preview(root, 1, text),
  'lastReplyAt': '2026-10-31T02:00:00Z',
  'lastReplySequence': lastReply,
  'lastReplier': {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'},
  'unreadReplies': unread,
  'follow': null,
};

Map<String, dynamic> readThread(
  String root,
  int lastReply, {
  String conversationId = 'lead',
  String text = 'Older root',
  bool? follow,
}) => {
  'conversationId': conversationId,
  'rootId': root,
  'root': preview(root, 1, text),
  'replies': 3,
  'lastReplyAt': '2026-10-30T02:00:00Z',
  'lastReplySequence': lastReply,
  'lastReplier': null,
  'follow': follow,
};

/// A controller for a widget test, closed by [close] inside the test so no
/// save is left pending.
Future<SuperTabController> openHere(ConversationServer server) async {
  final c = server.controller();
  await c.refresh();
  return c;
}

Future<void> close(WidgetTester tester, SuperTabController c) async {
  await tester.pumpWidget(const SizedBox());
  await c.flush();
  c.dispose();
}

Future<SuperTabController> open(ConversationServer server) async {
  final c = server.controller();
  addTearDown(() async {
    await c.flush();
    c.dispose();
  });
  await c.refresh();
  return c;
}

/// Lets the tag, decision and thread reads the last state read set off
/// answer.
Future<void> settle(SuperTabController c) async {
  for (var i = 0; i < 5; i++) {
    await pumpEventQueue();
  }
}

Future<void> pumpSidebar(
  WidgetTester tester,
  SuperTabController c,
  SuperTabAttention attention, {
  Brightness brightness = Brightness.dark,
}) async {
  await tester.binding.setSurfaceSize(const Size(300, 900));
  addTearDown(() => tester.binding.setSurfaceSize(null));
  await tester.pumpWidget(
    MaterialApp(
      theme: grid.buildAppTheme(brightness: brightness),
      home: Scaffold(
        body: ListenableBuilder(
          listenable: c,
          builder: (context, _) => ProjectSidebar(
            controller: c,
            onSelect: c.select,
            attention: attention,
          ),
        ),
      ),
    ),
  );
  await tester.pumpAndSettle();
}

Finder inRow(String key, Finder finder) =>
    find.descendant(of: find.byKey(ValueKey(key)), matching: finder);

Text rowText(WidgetTester tester, String key, String text) =>
    tester.widget<Text>(inRow(key, find.text(text)));

void main() {
  group('the red number counts only what is for the reader', () {
    // Dee: the 7, 7 and 3 on project rows never cleared, and opening them showed none of what they counted.
    // Task #2927 (Dee, 11-04: "I'm pretty sure I read all of them"): a project's number is its own chat's tags,
    // which opening the chat clears (Slack's channel badge); the rest is in Activity.
    group('a project row counts only what opening its chat clears', () {
      Future<(SuperTabController, SuperTabAttention, SuperTabActivity)> opened(
        ConversationServer server,
      ) async {
        final c = await openHere(server);
        final attention = SuperTabAttention.of(c);
        final activity = SuperTabActivity.of(c);
        await attention.mentions.load();
        await attention.decisions.load();
        await attention.load();
        await activity.mentions.load();
        return (c, attention, activity);
      }

      Finder projectNumber() => inRow(
        'super-group-lead',
        find.byKey(const ValueKey('super-mentions-lead')),
      );

      testWidgets('a tag in the project chat counts, and opening the chat '
          'clears it there and in Activity', (tester) async {
        final server = projectServer();
        server.tag('message-1', messageSequence: 1);
        fromLead(server, 'Please look');
        final (c, attention, activity) = await opened(server);
        await pumpSidebar(tester, c, attention);
        expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
        expect(activity.count, 1);
        c.select('lead');
        await tester.pumpAndSettle();
        c.markRead('lead');
        await tester.pumpAndSettle();
        expect(projectNumber(), findsNothing);
        expect(activity.count, 0);
        await close(tester, c);
      });

      testWidgets('a tag in a task conversation raises Activity, not the '
          'project row; the unread filter keeps it, and the row is bold only '
          'for its own chat (task #2638)', (tester) async {
        final server = projectServer();
        fromLead(server, 'Please look', conversationId: 'offline');
        server.tag('message-1', conversationId: 'offline', messageSequence: 1);
        final (c, attention, activity) = await opened(server);
        await pumpSidebar(tester, c, attention);
        expect(projectNumber(), findsNothing);
        expect(activity.count, 1);
        expect(
          rowText(tester, 'super-group-lead', 'web-project').style?.fontWeight,
          isNot(FontWeight.w600),
        );
        c.toggleUnreadOnly();
        await tester.pumpAndSettle();
        expect(find.byKey(const ValueKey('super-group-lead')), findsOneWidget);
        // Opening the task clears it from Activity.
        c.select('offline');
        await tester.pumpAndSettle();
        c.markRead('offline');
        await tester.pumpAndSettle();
        expect(activity.count, 0);
        await close(tester, c);
      });

      testWidgets('a tag in a reply that lives only in a project chat '
          'thread raises Activity and its thread, not the project row; '
          'reading the thread clears it', (tester) async {
        final server = projectServer();
        server.followedThreads = {
          'unread': [unreadThread('message-1', 2, conversationId: 'lead')],
          'read': [],
          'more': false,
        };
        server.tag('message-1', threadId: 'message-1', messageSequence: 2);
        final (c, attention, activity) = await opened(server);
        await pumpSidebar(tester, c, attention);
        expect(attention.threadMentions, 1);
        expect(attention.hasUnreadTagInThread('lead', 'message-1'), isTrue);
        expect(activity.newReplies, hasLength(1));
        expect(activity.needsYou, isEmpty);
        expect(activity.count, 1);
        expect(projectNumber(), findsNothing);
        c.markThreadRead('lead', 'message-1', 2);
        await tester.pumpAndSettle();
        expect(activity.count, 0);
        expect(find.byType(SuperTabCountBadge), findsNothing);
        await close(tester, c);
      });

      testWidgets('a decision asked in the project chat raises Activity, '
          'not the project row, even while the chat is unread', (tester) async {
        final server = projectServer();
        fromLead(server, 'Which way?');
        server.ask(['Ship it?'], conversationId: 'lead');
        final (c, attention, activity) = await opened(server);
        await pumpSidebar(tester, c, attention);
        expect(activity.needsYou, hasLength(1));
        expect(activity.count, 1);
        expect(projectNumber(), findsNothing);
        await attention.decisions.answer(attention.decisions.open.single, 0);
        await tester.pumpAndSettle();
        expect(activity.count, 0);
        await close(tester, c);
      });

      testWidgets('the project badge says it counts tags, and only the '
          "chat's own", (tester) async {
        final server = projectServer();
        server.followedThreads = {'unread': [], 'read': [], 'more': false};
        fromLead(server, 'News', conversationId: 'offline');
        server.tag('message-1', conversationId: 'offline');
        server.tag(
          'message-1',
          conversationId: 'offline',
          threadId: 'message-1',
        );
        server.tag('message-1');
        server.tag('message-1');
        server.ask(['Ship it?'], conversationId: 'lead');
        final (c, attention, _) = await opened(server);
        await pumpSidebar(tester, c, attention);
        expect(inRow('super-group-lead', find.text('2')), findsOneWidget);
        expect(
          tester.widget<SuperTabCountBadge>(projectNumber()).tooltip,
          '2 tags',
        );
        await close(tester, c);
      });

      testWidgets('every number shown clears by opening what it counts', (
        tester,
      ) async {
        final server = projectServer();
        fromLead(server, 'In the task', conversationId: 'offline');
        server.tag('message-1', conversationId: 'offline', messageSequence: 1);
        server.tag('message-1', messageSequence: 1);
        fromLead(server, 'In the chat');
        final (c, attention, activity) = await opened(server);
        await pumpSidebar(tester, c, attention);
        // The project chat's tag on the row; both tags in Activity.
        expect(inRow('super-group-lead', find.text('1')), findsOneWidget);
        expect(activity.count, 2);
        c.select('lead');
        await tester.pumpAndSettle();
        c.markRead('lead');
        await tester.pumpAndSettle();
        expect(projectNumber(), findsNothing);
        expect(activity.count, 1);
        c.select('offline');
        await tester.pumpAndSettle();
        c.markRead('offline');
        await tester.pumpAndSettle();
        expect(activity.count, 0);
        expect(find.byType(SuperTabCountBadge), findsNothing);
        await close(tester, c);
      });

      // Dee, 11-04: Activity cleared to 1, yet openharness showed 3 while it
      // was open: the row added tasks waiting on anyone and a task's decision,
      // which opening the chat never clears.
      testWidgets('Activity at 1 and the project chat open: the project shows '
          'no number, never more than Activity', (tester) async {
        final server = projectServer();
        (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
          for (final (id, number) in [('stuck', 20), ('asks', 21)])
            {
              ...conversationFixture(id, id),
              'projectId': 'lead',
              'number': number,
              'assignment': {
                'agentId': 'a1',
                'status': 'needs_human',
                'progressAt': 1,
              },
              'liveness': {'state': 'waiting', 'why': 'person', 'since': 1},
            },
        ]);
        server.ask(['Ship it?'], conversationId: 'offline');
        final (c, attention, activity) = await opened(server);
        await pumpSidebar(tester, c, attention);
        c.select('lead');
        await tester.pumpAndSettle();
        expect(activity.count, 1);
        // Before #2927 the row said 3: the task's decision and two tasks
        // waiting on no one named.
        expect(projectNumber(), findsNothing);
        await close(tester, c);
      });

      testWidgets('a muted project chat shows no number', (tester) async {
        final server = projectServer();
        server.tag('message-1', messageSequence: 1);
        fromLead(server, 'Please look');
        final (c, attention, _) = await opened(server);
        await c.setNotify('lead', SuperTabNotify.muted);
        await pumpSidebar(tester, c, attention);
        expect(projectNumber(), findsNothing);
        await close(tester, c);
      });
    });

    testWidgets('a task\'s tags in its chat and thread and its decision make '
        'it a task that needs the reader, not a number on its project; plain '
        'unread is bold with no number', (tester) async {
      final server = projectServer();
      server.followedThreads = {
        'unread': [unreadThread('message-1', 2, conversationId: 'offline')],
        'read': [],
        'more': false,
      };
      fromLead(server, 'Plain news', conversationId: 'offline');
      server.tag('message-1', conversationId: 'offline');
      server.tag('message-1', conversationId: 'offline', threadId: 'message-1');
      server.ask(['Ship it?'], conversationId: 'offline');
      fromLead(server, 'Plain news in the project chat');
      final c = await openHere(server);
      final attention = SuperTabAttention.of(c);
      await attention.mentions.load();
      await attention.decisions.load();
      await attention.load();
      await pumpSidebar(tester, c, attention);
      // The workgroup: one tag in its chat, one in its thread, and one
      // decision; its card needs the reader.
      expect(attention.mentionsIn('offline'), 3);
      // The unread thread is still available in Activity's New replies.
      expect(attention.threadMentions, 1);
      // The project chat: unread, nothing for the reader in it.
      expect(
        inRow(
          'super-group-lead',
          find.byKey(const ValueKey('super-mentions-lead')),
        ),
        findsNothing,
      );
      expect(
        rowText(tester, 'super-group-lead', 'web-project').style?.fontWeight,
        grid.AppFont.semibold,
      );
      await close(tester, c);
    });
  });

  test('Unfollow is kept on the server and the list read again', () async {
    final server = projectServer();
    server.followedThreads = {
      'unread': [],
      'read': [readThread('message-9', 7)],
      'more': false,
    };
    final c = await open(server);
    final attention = SuperTabAttention.of(c);
    await attention.load();
    final reads = server.threadListReads.length;
    expect(await attention.setFollow(attention.read.single, false), isTrue);
    await pumpEventQueue();
    expect(server.followPosts.single, {
      'conversationId': 'lead',
      'root': 'message-9',
      'follow': false,
    });
    expect(server.threadListReads.length, greaterThan(reads));
  });

  group('read rows are muted, unread rows full strength and bold', () {
    for (final brightness in Brightness.values) {
      testWidgets('in $brightness', (tester) async {
        final server = projectServer();
        server.followedThreads = {
          'unread': [unreadThread('message-1', 2)],
          'read': [],
          'more': false,
        };
        // A second project with news, and a third open on screen, so the
        // first project's row is neither selected nor unread.
        for (final id in ['news', 'open']) {
          (server.state['projects'] as List).add(
            projectFixture(id, '$id-project', id),
          );
          (server.state['conversations'] as List).add({
            ...conversationFixture(id, id),
            'projectId': id,
          });
        }
        fromLead(server, 'Read news');
        server.markReadElsewhere('lead', server.revision);
        fromLead(server, 'Unread news', conversationId: 'news');
        final c = await openHere(server);
        final attention = SuperTabAttention.of(c);
        await attention.load();
        c.select('open');
        await pumpSidebar(tester, c, attention, brightness: brightness);
        final read = rowText(tester, 'super-group-lead', 'web-project');
        expect(read.style?.color, DesktopChrome.muted);
        expect(read.style?.fontWeight, isNot(grid.AppFont.semibold));
        final unread = rowText(tester, 'super-group-news', 'news-project');
        expect(unread.style?.color, DesktopChrome.foreground);
        expect(unread.style?.fontWeight, grid.AppFont.semibold);
        await close(tester, c);
      });
    }
  });

  testWidgets('a project row lights whole on hover, as wide as its selected '
      'highlight', (tester) async {
    final server = projectServer();
    server.followedThreads = {'unread': [], 'read': [], 'more': false};
    // Another project's chat open, so this row is not highlighted: a project
    // shows as selected while one of its tasks is open.
    (server.state['projects'] as List).add(
      projectFixture('other', 'other-project', 'other'),
    );
    (server.state['conversations'] as List).add({
      ...conversationFixture('other', 'other'),
      'projectId': 'other',
    });
    final c = await openHere(server);
    final attention = SuperTabAttention.of(c);
    c.select('other');
    await pumpSidebar(tester, c, attention);
    final row = find.byKey(const ValueKey('super-group-lead'));
    final groundFinder = find
        .ancestor(of: row, matching: find.byType(Material))
        .first;
    Material ground() => tester.widget<Material>(groundFinder);
    expect(ground().color, Colors.transparent);
    final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
    addTearDown(mouse.removePointer);
    await mouse.addPointer(location: Offset.zero);
    await mouse.moveTo(tester.getRect(row).centerRight - const Offset(4, 0));
    await tester.pumpAndSettle();
    // The whole row's ground, out to its end.
    expect(ground().color, grid.AppSurface.hoverFill);
    await mouse.moveTo(
      tester.getCenter(inRow('super-group-lead', find.text('web-project'))),
    );
    await tester.pumpAndSettle();
    expect(ground().color, grid.AppSurface.hoverFill);
    final hovered = tester.getRect(groundFinder);
    expect(hovered.right, greaterThanOrEqualTo(tester.getRect(row).right));
    c.select('lead');
    await tester.pumpAndSettle();
    expect(ground().color, grid.AppSurface.selectedFill);
    expect(tester.getRect(groundFinder), hovered);
    await close(tester, c);
  });

  group('review of 99b8018', () {
    test('a thread read during the visit keeps its new-reply count after '
        'the list is read again', () async {
      final server = projectServer();
      server.followedThreads = {
        'unread': [unreadThread('message-1', 3, unread: 2)],
        'read': [],
        'more': false,
      };
      final c = await open(server);
      final attention = SuperTabAttention.of(c)..opened();
      await attention.load();
      final thread = attention.shown.single;
      expect(attention.newCount(thread), 2);
      // Read now: the server lists it among the read ones, with no count.
      server.followedThreads = {
        'unread': [],
        'read': [readThread('message-1', 3)],
        'more': false,
      };
      await attention.load();
      final reloaded = attention.shown.single;
      expect(attention.isNew(reloaded), isTrue);
      expect(attention.newCount(reloaded), 2);
      attention.closed();
      expect(attention.newCount(reloaded), 0);
    });

    test('a change inside the gap is read once the gap is over, and the '
        'wait stops with the controller', () {
      fakeAsync((async) {
        var now = DateTime(2026, 10, 31, 9);
        final server = projectServer();
        server.followedThreads = {'unread': [], 'read': [], 'more': false};
        final c = server.controller();
        unawaited(c.refresh());
        async.flushMicrotasks();
        final attention = SuperTabAttention.forTest(c, now: () => now);
        // On screen, as the sidebar shows it.
        void shown() {}
        attention.addListener(shown);
        async.flushMicrotasks();
        final reads = server.threadListReads.length;
        expect(reads, greaterThan(0));
        // A change 5 s after the read: inside the 15 s gap.
        now = now.add(const Duration(seconds: 5));
        async.elapse(const Duration(seconds: 5));
        fromLead(server, 'News');
        unawaited(c.refresh());
        async.flushMicrotasks();
        expect(server.threadListReads.length, reads);
        // The gap ends: the change is read without another one.
        now = now.add(const Duration(seconds: 11));
        async.elapse(const Duration(seconds: 11));
        expect(server.threadListReads.length, reads + 1);
        // Another change in the next gap, then the controller goes.
        now = now.add(const Duration(seconds: 1));
        fromLead(server, 'More');
        unawaited(c.refresh());
        async.flushMicrotasks();
        expect(async.pendingTimers, isNotEmpty);
        // Nothing shows it any more: nothing is waited for.
        attention.removeListener(shown);
        expect(async.pendingTimers, isEmpty);
        attention.addListener(shown);
        fromLead(server, 'Again');
        unawaited(c.refresh());
        async.flushMicrotasks();
        expect(async.pendingTimers, isNotEmpty);
        unawaited(c.flush());
        async.flushMicrotasks();
        c.dispose();
        expect(async.pendingTimers, isEmpty);
        async.elapse(const Duration(seconds: 30));
        expect(server.threadListReads.length, reads + 1);
        expect(attention.unread, isEmpty);
      });
    });

    test('no red number once access is gone, nor for a tag in a chat the '
        'Swarm no longer lists', () async {
      final server = projectServer();
      server.followedThreads = {
        'unread': [unreadThread('message-1', 2)],
        'read': [],
        'more': false,
      };
      server.tag('message-1', threadId: 'message-1', messageSequence: 2);
      server.tag(
        'message-9',
        conversationId: 'gone',
        threadId: 'message-9',
        messageSequence: 2,
      );
      server.tag('message-1', conversationId: 'offline', messageSequence: 2);
      var revoked = false;
      final c = SuperTabController(
        tabId: 'tab',
        accountId: 'owner',
        request: (method, path, {body}) {
          if (revoked &&
              (path.contains('/parts') || path.contains('/changes'))) {
            throw const SuperTabFailure(
              'FORBIDDEN',
              'No access.',
              statusCode: 403,
            );
          }
          return server.request(method, path, body: body);
        },
        save: server.save,
        pollInterval: Duration.zero,
      );
      addTearDown(() async {
        await c.flush();
        c.dispose();
      });
      await c.refresh();
      final attention = SuperTabAttention.of(c);
      await attention.mentions.load();
      await attention.load();
      // The tag in a chat the Swarm does not list counts nowhere.
      expect(attention.threadMentions, 1);
      expect(attention.mentionsIn('offline'), 1);
      // The moment access is gone, before anything is cleared.
      c.accessRevoked = true;
      expect(attention.threadMentions, 0);
      expect(attention.mentionsIn('offline'), 0);
      c.accessRevoked = false;
      revoked = true;
      fromLead(server, 'After access went');
      await c.refresh();
      expect(c.accessRevoked, isTrue);
      expect(attention.threadMentions, 0);
      expect(attention.mentionsIn('offline'), 0);
    });

    test(
      'an open decision stays on the sidebar count until answered',
      () async {
        final server = projectServer();
        server.ask(['Ship it?'], conversationId: 'lead');
        final c = await open(server);
        final attention = SuperTabAttention.of(c);
        final activity = SuperTabActivity.of(c);
        await attention.decisions.load();
        expect(activity.needsYou, hasLength(1));
        // Reading the chat does not answer the question.
        c.markRead('lead');
        expect(attention.mentionsIn('lead'), 1);
        expect(attention.decisionsIn('lead'), 1);
        expect(
          await attention.decisions.answer(attention.decisions.open.single, 0),
          isTrue,
        );
        await attention.decisions.load();
        expect(attention.mentionsIn('lead'), 0);
        expect(activity.needsYou, isEmpty);
      },
    );

    test('a tag stops counting after reading, but a decision waits for an '
        'answer', () async {
      final server = projectServer();
      server.followedThreads = {
        'unread': [],
        'read': [readThread('message-1', 2, follow: true)],
        'more': false,
      };
      fromLead(server, 'Please look', conversationId: 'offline');
      server.tag(
        'message-1',
        conversationId: 'offline',
        messageSequence: server.revision,
      );
      server.ask(['Ship it?'], conversationId: 'offline');
      final c = await open(server);
      final attention = SuperTabAttention.of(c);
      await attention.mentions.load();
      await attention.decisions.load();
      await attention.load();
      expect(attention.mentionsIn('offline'), 2);
      // Read on another device, past the tagged message.
      server.markReadElsewhere('offline', server.revision);
      await c.refresh();
      expect(attention.mentions.waiting, hasLength(1));
      expect(attention.mentionsIn('offline'), 1);
      expect(
        await attention.decisions.answer(attention.decisions.open.single, 0),
        isTrue,
      );
      await attention.decisions.load();
      expect(attention.mentionsIn('offline'), 0);
      // A tag in a thread clears once the thread is read past it.
      server.tag(
        'message-1',
        threadId: 'message-1',
        messageSequence: server.revision,
      );
      await c.refresh();
      await attention.mentions.load();
      await attention.load();
      expect(attention.threadMentions, 1);
      server.markThreadReadElsewhere('lead', 'message-1', server.revision);
      await c.refresh();
      expect(attention.threadMentions, 0);
    });
  });

  group('the Threads number counts only threads the Threads view lists', () {
    // Scholes 11-02: the sidebar said Threads 1 while the page said "No
    // threads yet" and "Older threads are not listed."
    test('a tag in a thread the list leaves out (past the server\'s bounds) '
        'counts nothing, and the sidebar row shows no number', () async {
      final server = projectServer();
      server.followedThreads = {'unread': [], 'read': [], 'more': true};
      server.tag('message-1', threadId: 'message-1', messageSequence: 2);
      final c = await open(server);
      final attention = SuperTabAttention.of(c);
      await attention.mentions.load();
      await attention.load();
      expect(attention.loaded, isTrue);
      expect(attention.shown, isEmpty);
      expect(attention.more, isTrue);
      // The tag is waiting, but the thread is not listed: no number.
      expect(attention.mentions.waiting, hasLength(1));
      expect(attention.threadMentions, 0);
    });

    test('a tag in a thread the reader unfollowed (never listed) counts '
        'nothing; in a thread the list shows it counts', () async {
      final server = projectServer();
      server.followedThreads = {
        'unread': [],
        'read': [readThread('message-1', 2, follow: true)],
        'more': false,
      };
      server.tag('message-1', threadId: 'message-1', messageSequence: 2);
      server.tag('message-7', threadId: 'message-7', messageSequence: 3);
      final c = await open(server);
      final attention = SuperTabAttention.of(c);
      await attention.mentions.load();
      await attention.load();
      expect(attention.mentions.waiting, hasLength(2));
      expect(attention.threadMentions, 1);
    });

    test('a thread with the same root id in another chat is not the listed '
        'one', () async {
      final server = projectServer();
      server.followedThreads = {
        'unread': [unreadThread('message-1', 2)],
        'read': [],
        'more': false,
      };
      server.tag(
        'message-1',
        conversationId: 'offline',
        threadId: 'message-1',
        messageSequence: 2,
      );
      final c = await open(server);
      final attention = SuperTabAttention.of(c);
      await attention.mentions.load();
      await attention.load();
      expect(attention.threadMentions, 0);
    });

    test('no number before the list has answered; a failed first read that '
        'recovers then counts', () async {
      final server = projectServer()..failThreadLists = true;
      server.followedThreads = {
        'unread': [unreadThread('message-1', 2)],
        'read': [],
        'more': false,
      };
      server.tag('message-1', threadId: 'message-1', messageSequence: 2);
      final c = await open(server);
      final attention = SuperTabAttention.of(c);
      await attention.mentions.load();
      expect(attention.threadMentions, 0);
      await attention.load();
      expect(attention.error, isNotNull);
      expect(attention.threadMentions, 0);
      server.failThreadLists = false;
      await attention.load();
      expect(attention.error, isNull);
      expect(attention.threadMentions, 1);
    });

    test('when who may read what changes, the number is gone until the list '
        'is read again; access lost clears it at once', () async {
      final server = projectServer();
      server.followedThreads = {
        'unread': [unreadThread('message-1', 2)],
        'read': [],
        'more': false,
      };
      server.tag('message-1', threadId: 'message-1', messageSequence: 2);
      final c = await open(server);
      final attention = SuperTabAttention.of(c);
      await attention.mentions.load();
      await attention.load();
      expect(attention.threadMentions, 1);
      // The next read answers with the thread gone from the list.
      server.followedThreads = {'unread': [], 'read': [], 'more': false};
      await attention.load();
      expect(attention.threadMentions, 0);
      c.accessRevoked = true;
      expect(attention.threadMentions, 0);
    });
  });

  group('the Threads list', () {
    test('a thread in a chat the reader no longer has is not listed', () async {
      final server = projectServer();
      server.followedThreads = {
        'unread': [unreadThread('message-1', 3, conversationId: 'elsewhere')],
        'read': [readThread('message-2', 3, conversationId: 'gone')],
        'more': false,
      };
      final c = await open(server);
      final attention = SuperTabAttention.of(c);
      await attention.load();
      expect(attention.loaded, isTrue);
      expect(attention.shown, isEmpty);
    });

    test(
      'access lost clears the list, and an answer on its way is dropped',
      () async {
        final server = projectServer();
        server.followedThreads = {
          'unread': [unreadThread('message-1', 3)],
          'read': [],
          'more': false,
        };
        var revoked = false;
        final c = SuperTabController(
          tabId: 'tab',
          accountId: 'owner',
          request: (method, path, {body}) {
            if (revoked &&
                (path.contains('/parts') || path.contains('/changes'))) {
              throw const SuperTabFailure(
                'FORBIDDEN',
                'No access.',
                statusCode: 403,
              );
            }
            return server.request(method, path, body: body);
          },
          save: server.save,
          pollInterval: Duration.zero,
        );
        addTearDown(() async {
          await c.flush();
          c.dispose();
        });
        await c.refresh();
        final attention = SuperTabAttention.of(c);
        await attention.load();
        expect(attention.unread, hasLength(1));
        server.holdThreadLists = Completer<void>();
        final late = attention.load();
        await pumpEventQueue();
        // The Swarm refuses the reader: their access is gone.
        revoked = true;
        fromLead(server, 'After access went');
        await c.refresh();
        expect(c.accessRevoked, isTrue);
        expect(attention.unread, isEmpty);
        expect(attention.loaded, isFalse);
        server.holdThreadLists!.complete();
        await late;
        expect(attention.unread, isEmpty);
        expect(attention.threadsUnread, isFalse);
      },
    );

    test('an answer from before the audience changed is dropped, and the '
        'list is read again', () async {
      final server = projectServer();
      server.followedThreads = {
        'unread': [unreadThread('message-1', 3)],
        'read': [],
        'more': false,
      };
      final c = await open(server);
      final attention = SuperTabAttention.of(c);
      await attention.load();
      final first = server.holdThreadLists = Completer<void>();
      final stale = attention.load();
      await pumpEventQueue();
      // Who may read what changes: the next state read reloads under a new
      // epoch, which clears the list and asks for it again.
      server.parts.epoch++;
      await c.refresh();
      await settle(c);
      expect(attention.unread, isEmpty);
      // The read asked before the change answers with the old list, while
      // the one asked after it is still out.
      final second = server.holdThreadLists = Completer<void>();
      first.complete();
      await settle(c);
      expect(attention.unread, isEmpty);
      expect(attention.loaded, isFalse);
      second.complete();
      await stale;
      await settle(c);
      expect(attention.loaded, isTrue);
      expect(attention.unread, hasLength(1));
    });

    test(
      'a failed first read shows the failure, and a later read recovers',
      () async {
        final server = projectServer()..failThreadLists = true;
        server.followedThreads = {
          'unread': [unreadThread('message-1', 3)],
          'read': [],
          'more': false,
        };
        final c = await open(server);
        final attention = SuperTabAttention.of(c);
        await attention.load();
        expect(attention.loaded, isFalse);
        expect(attention.error, isNotNull);
        server.failThreadLists = false;
        await attention.load();
        expect(attention.error, isNull);
        expect(attention.loaded, isTrue);
        expect(attention.threadsUnread, isTrue);
      },
    );

    test('asked too often, it waits before reading again, even with the '
        'Threads view open', () async {
      var now = DateTime(2026, 10, 31, 9);
      final server = projectServer()
        ..failThreadLists = true
        ..threadListStatus = 429;
      server.followedThreads = {'unread': [], 'read': [], 'more': false};
      final c = await open(server);
      final attention = SuperTabAttention.forTest(c, now: () => now);
      addTearDown(attention.dispose);
      // The view open reads every few seconds as the Swarm moves.
      attention.opened();
      await settle(c);
      expect(attention.error, isNotNull);
      final reads = server.threadListReads.length;
      server.failThreadLists = false;
      // Past the open view's pace, short of the wait the refusal asked for.
      now = now.add(const Duration(seconds: 4));
      fromLead(server, 'More');
      await c.refresh();
      await settle(c);
      expect(server.threadListReads.length, reads);
      now = now.add(const Duration(seconds: 2));
      fromLead(server, 'More again');
      await c.refresh();
      await settle(c);
      expect(server.threadListReads.length, reads + 1);
      expect(attention.error, isNull);
    });
  });

  test('reading a chat leaves a reply that lives only in its thread unread: '
      'the chat\'s mark stops at its newest main-stream message', () async {
    final server = projectServer();
    fromLead(server, 'Root');
    conversation(server, 'lead')['lastMainSequence'] = 1;
    fromLead(server, 'Reply only in the thread');
    server.messages.last['thread'] = 'message-1';
    final c = await open(server);
    await c.loadMessages('lead');
    c.markRead('lead');
    await pumpEventQueue();
    expect(server.readMarkPosts.last, {
      'conversationId': 'lead',
      'sequence': 1,
    });
  });

  group('tags from the Threads view (merge check of 67c32a3)', () {
    /// Kestrel is an agent of "offline", not of "lead"; "offline" has a
    /// thread at message-1 with a new reply.
    ConversationServer tagged() {
      final server = projectServer();
      server.state['agents'] = [
        {
          'id': 'kestrel',
          'name': 'Builder',
          'displayName': 'Kestrel',
          'machineId': 'host',
          'harnessId': 'session',
          'contributorId': 'owner',
          'configuration': {'engine': 'codex'},
        },
      ];
      conversation(server, 'offline')['agentIds'] = ['kestrel'];
      fromLead(server, 'Root', conversationId: 'offline');
      fromLead(server, 'Reply', conversationId: 'offline');
      server.messages.last['thread'] = 'message-1';
      conversation(server, 'offline')['lastMainSequence'] = 1;
      server.followedThreads = {
        'unread': [
          unreadThread('message-1', 2, conversationId: 'offline', text: 'Root'),
        ],
        'read': [],
        'more': false,
      };
      return server;
    }

    test('a reply tagging an agent of the thread\'s own chat goes, whichever '
        'chat is selected', () async {
      final server = tagged();
      final c = await open(server);
      c.select('lead');
      const to = (conversationId: 'offline', root: 'message-1');
      c.setThreadDraft('message-1', '@Kestrel please look');
      c.threadMention('kestrel', '@Kestrel', to: to);
      expect(c.threadMentions('offline', 'message-1'), {'kestrel': '@Kestrel'});
      await c.sendThreadReply(to: to);
      expect(c.operationError, isNull);
      final sent = server.posts.last['command'] as Map;
      expect(sent['conversationId'], 'offline');
      expect(sent['replyTo'], 'message-1');
      expect(sent['recipientIds'], ['kestrel']);
    });
  });
}