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.

57.0 KB
Raw Blame
import 'dart:async';

import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/swarm/model.dart';
import 'package:harness_mobile/swarm/swarm_conversation.dart';
import 'package:harness_mobile/swarm/swarm_outbox.dart';
import 'package:harness_mobile/swarm/swarm_read_marks.dart';
import 'package:harness_mobile/swarm/swarm_reader.dart';
import 'package:harness_mobile/swarm/swarm_request.dart';
import 'package:harness_mobile/swarm/swarm_unread.dart';

import 'swarm_fixture.dart';

/// One conversation on the phone: its messages (latest page first, older on
/// demand, new ones as the Swarm says they arrived), and what the person
/// posts to it (backend message.send, section 4.6 of the parts design).
void main() {
  const messages = '/api/super-tabs/$tab/conversations/g1/messages';

  Map<String, dynamic> message(
    String id,
    int sequence, {
    String text = 'hello',
    String authorId = 'agent-builder',
    bool fromAgent = true,
    String conversationId = 'g1',
  }) => {
    'id': id,
    'conversationId': conversationId,
    'text': text,
    'sequence': sequence,
    'author': {
      'kind': fromAgent ? 'agent' : 'person',
      'id': authorId,
      'name': fromAgent ? 'Builder' : 'me',
    },
    'createdAt': '2026-10-27T01:00:00.000Z',
  };

  /// A Swarm with conversation g1 at [sequence], and [rest] of its groups.
  ({FakeSwarm swarm, SwarmReader reader}) rig({
    int sequence = 2,
    List<String> agentIds = const ['agent-lead', 'agent-builder'],
    String role = 'owner',
    bool archived = false,
    Map<String, int> readMarks = const {},
    int? mainSequence,
  }) {
    final swarm = FakeSwarm();
    Map<String, dynamic> g1(int seq) => {
      ...groupData(
        'g1',
        title: 'Fix login',
        agentIds: agentIds,
        lastMessageSequence: seq,
      ),
      'archived': archived,
      'lastMainSequence': ?mainSequence,
    };
    swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {
      ...firstLoad(groups: [g1(sequence)], derived: {'readMarks': readMarks}),
      'members': [part(me, 1, person(me, role: role))],
    };
    swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
    final reader = SwarmReader(
      tabId: tab,
      accountId: me,
      request: swarm.request,
    );
    addTearDown(reader.dispose);
    return (swarm: swarm, reader: reader);
  }

  Future<SwarmConversation> open(SwarmReader reader) async {
    await reader.refresh();
    final conversation = SwarmConversation(reader, 'g1');
    addTearDown(conversation.dispose);
    await conversation.load();
    return conversation;
  }

  test('opening reads the latest page, oldest first', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {
      'messages': [message('m2', 2), message('m1', 1)],
      'next': {'sequence': 1, 'id': 'm1'},
    };

    final c = await open(r.reader);

    expect([for (final m in c.messages) m.id], ['m1', 'm2']);
    expect(c.hasOlder, isTrue);
    expect(r.swarm.paths.last, messages);
  });

  // The chat page redraws on what its conversation says: a read that brings
  // nothing, or a letter typed, is not news for its messages.
  test('a read that brings nothing new tells no one', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {
      'messages': [message('m2', 2), message('m1', 1)],
      'next': {'sequence': 1, 'id': 'm1'},
    };
    final c = await open(r.reader);
    final shown = c.messages;
    var told = 0;
    c.addListener(() => told++);

    await c.load();

    expect(told, 0);
    expect(c.messages, same(shown));
    expect(c.hasOlder, isTrue);
  });

  test('a draft typed is told to the composer, not to the messages', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {
      'messages': [message('m1', 1)],
      'next': null,
    };
    final c = await open(r.reader);
    var told = 0;
    c.addListener(() => told++);

    c.draft = 'Hel';
    c.draft = 'Hello';

    expect(told, 0);
    expect(c.draft, 'Hello');
  });

  test(
    'older messages are read before the oldest shown, until there are none',
    () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m5', 5)],
        'next': {'sequence': 5, 'id': 'm5'},
      };
      r.swarm.routes['$messages?before=5&beforeId=m5'] = (_) => {
        'messages': [message('m3', 3), message('m4', 4)],
        'next': null,
      };
      final c = await open(r.reader);

      await c.loadOlder();

      expect([for (final m in c.messages) m.id], ['m3', 'm4', 'm5']);
      expect(c.hasOlder, isFalse);
    },
  );

  test(
    'new messages are read when the Swarm says the conversation moved',
    () async {
      final r = rig(sequence: 2);
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m2', 2)],
        'next': null,
      };
      r.swarm.routes['$messages?after=2'] = (_) => {
        'messages': [message('m3', 3, text: 'done')],
        'next': null,
      };
      final c = await open(r.reader);

      // A change that leaves the conversation where it was reads no messages.
      await r.reader.refresh();
      await settle();
      expect(r.swarm.paths.where((p) => p.contains('after=')), isEmpty);

      r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
        cursor: 'c3',
        groups: [
          part(
            'g1',
            30,
            groupData(
              'g1',
              title: 'Fix login',
              agentIds: ['agent-lead', 'agent-builder'],
              lastMessageSequence: 3,
            ),
          ),
        ],
      );
      await r.reader.refresh();
      await settle();

      expect([for (final m in c.messages) m.text], ['hello', 'done']);
    },
  );

  // The phone has no thread view yet: a reply only in its thread is read
  // and shown in the chat, though it leaves the chat's main stream where it
  // was (PM, 10-29; desktop_parity_test).
  test('a reply only in its thread is read and shown in the chat, so nothing '
      'is lost', () async {
    final r = rig(sequence: 2);
    r.swarm.routes[messages] = (_) => {
      'messages': [message('m2', 2)],
      'next': null,
    };
    r.swarm.routes['$messages?after=2'] = (_) => {
      'messages': [
        {...message('m3', 3, text: 'in the thread'), 'thread': 'm2'},
      ],
      'next': null,
    };
    final c = await open(r.reader);

    r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
      cursor: 'c3',
      groups: [
        part('g1', 30, {
          ...groupData(
            'g1',
            title: 'Fix login',
            agentIds: ['agent-lead', 'agent-builder'],
            lastMessageSequence: 3,
          ),
          'lastMainSequence': 2,
        }),
      ],
    );
    await r.reader.refresh();
    await settle();

    expect([for (final m in c.messages) m.text], ['hello', 'in the thread']);
    expect(c.messages.last.threadReply, isTrue);
    expect(r.reader.snapshot!.conversation('g1')!.mainSequence, 2);
  });

  test(
    'a post goes to the agents mentioned in it, and clears the draft',
    () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};
      r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => {
        'result': {'messageId': 'm9'},
      };
      final c = await open(r.reader);

      c.draft = 'Please check ';
      c.mention('agent-builder');
      expect(c.draft, 'Please check @Nova ');
      c.draft = '${c.draft}the build';
      expect(await c.send(), isTrue);

      final sent = r.swarm.calls.singleWhere((call) => call.method == 'POST');
      expect(sent.body!['operationId'], isA<String>());
      expect(sent.body!['command'], {
        'type': 'message.send',
        'conversationId': 'g1',
        'text': 'Please check @Nova the build',
        'replyTo': null,
        'recipientIds': ['agent-builder'],
      });
      expect(c.draft, isEmpty);
    },
  );

  test('a mention taken out of the text addresses nobody', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};
    r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => {
      'result': <String, dynamic>{},
    };
    final c = await open(r.reader);

    c.mention('agent-builder');
    c.draft = 'never mind';
    await c.send();

    expect(r.swarm.commands.single['recipientIds'], isEmpty);
  });

  test('a refused post keeps the draft and says why', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};
    r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) =>
        throw const SuperTabFailure(
          'READ_ONLY',
          'This conversation is read only.',
          statusCode: 403,
        );
    final c = await open(r.reader);

    c.draft = 'hi';
    expect(await c.send(), isFalse);

    expect(c.draft, 'hi');
    expect(c.error, 'This conversation is read only.');
    expect(c.unconfirmed, isFalse, reason: 'refused means nothing was done');
  });

  test('a post whose answer was lost is retried as the same post', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};
    var lost = true;
    r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => lost
        ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')
        : {'result': <String, dynamic>{}};
    final c = await open(r.reader);

    c.draft = 'hi';
    expect(await c.send(), isFalse);
    expect(c.unconfirmed, isTrue);

    lost = false;
    expect(await c.send(), isTrue);

    final posts = [
      for (final call in r.swarm.calls)
        if (call.method == 'POST') call.body!['operationId'],
    ];
    expect(posts, hasLength(2));
    expect(posts.toSet(), hasLength(1), reason: 'the backend runs it once');
  });

  test('a reply carries the message it answers, and the reply goes once it '
      'is sent', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {
      'messages': [message('m1', 1, text: 'Ship it?')],
      'next': null,
    };
    r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => {
      'result': <String, dynamic>{},
    };
    final c = await open(r.reader);

    c.replyingTo = c.messages.single;
    c.draft = 'Yes';
    expect(await c.send(), isTrue);

    expect(r.swarm.commands.single['replyTo'], 'm1');
    expect(c.replyingTo, isNull);
  });

  test('a post shows at once as sending, out of the draft, until it is read '
      'back', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};
    final taken = Completer<Object?>();
    String? receipt;
    r.swarm.routes['/api/super-tabs/$tab/commands'] = (body) {
      receipt = body!['operationId'] as String;
      return taken.future;
    };
    final c = await open(r.reader);

    c.draft = 'On my way';
    final sent = c.send();
    await settle();

    expect(c.draft, isEmpty, reason: 'the field is free at once');
    expect(c.outgoing.firstOrNull?.text, 'On my way');
    expect(c.sending, isTrue);

    r.swarm.routes[messages] = (_) => {
      'messages': [
        message(
          sentId(receipt!),
          3,
          text: 'On my way',
          authorId: me,
          fromAgent: false,
        ),
      ],
      'next': null,
    };
    taken.complete({'result': <String, dynamic>{}});
    expect(await sent, isTrue);
    await settle();

    expect(c.outgoing, isEmpty);
    expect([for (final m in c.messages) m.text], ['On my way']);
  });

  test('a post whose answer was lost stays at the foot, not confirmed, and '
      'out of the draft', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};
    r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) =>
        throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');
    final c = await open(r.reader);

    c.draft = 'hi';
    expect(await c.send(), isFalse);

    expect(c.outgoing.firstOrNull?.text, 'hi');
    expect(c.sending, isFalse);
    expect(c.unconfirmed, isTrue);
    expect(c.draft, isEmpty);
  });

  test('a refused post puts its text back in the draft, with its mention and '
      'its reply', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {
      'messages': [message('m1', 1, text: 'Ship it?')],
      'next': null,
    };
    var refuse = true;
    r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => refuse
        ? throw const SuperTabFailure(
            'TOO_LONG',
            'This message is too long.',
            statusCode: 400,
          )
        : {'result': <String, dynamic>{}};
    final c = await open(r.reader);
    c.replyingTo = c.messages.single;
    c.mention('agent-builder');
    c.draft = '${c.draft}please';

    expect(await c.send(), isFalse);

    expect(c.outgoing, isEmpty);
    expect(c.draft, '@Nova please');
    expect(c.replyingTo?.id, 'm1');
    expect(c.error, 'This message is too long.');

    refuse = false;
    expect(await c.send(), isTrue);
    expect(r.swarm.commands.last['recipientIds'], ['agent-builder']);
    expect(r.swarm.commands.last['replyTo'], 'm1');
  });

  test(
    'the mention picker reads the name typed after an @ at the end',
    () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};
      final c = await open(r.reader);

      c.draft = 'hey';
      expect(c.mentionQuery, isNull);
      c.draft = 'hey @';
      expect(c.mentionQuery, '');
      c.draft = '@No';
      expect(c.mentionQuery, 'No');
      c.draft = 'mail me@home';
      expect(c.mentionQuery, isNull, reason: 'an @ inside a word is not one');
      c.draft = 'hey @No then';
      expect(c.mentionQuery, isNull);
    },
  );

  test('a name picked for the @ being typed takes its place, and the post '
      'goes to that agent', () async {
    final r = rig();
    r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};
    r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => {
      'result': <String, dynamic>{},
    };
    final c = await open(r.reader);

    c.draft = 'Can you check @No';
    c.completeMention('agent-builder');
    expect(c.draft, 'Can you check @Nova ');
    expect(c.mentionQuery, isNull);

    c.draft = '${c.draft}this';
    await c.send();
    expect(r.swarm.commands.single['recipientIds'], ['agent-builder']);
  });

  test('a viewer, or an archived conversation, cannot post', () async {
    final viewer = rig(role: 'viewer');
    viewer.swarm.routes[messages] = (_) => {
      'messages': <Object>[],
      'next': null,
    };
    final c = await open(viewer.reader);
    c.draft = 'hi';
    expect(c.canPost, isFalse);
    expect(await c.send(), isFalse);

    final archived = rig(archived: true);
    archived.swarm.routes[messages] = (_) => {
      'messages': <Object>[],
      'next': null,
    };
    final a = await open(archived.reader);
    expect(a.canPost, isFalse);
  });

  test(
    'messages of a conversation the person can no longer read are dropped',
    () async {
      final r = rig();
      var allowed = true;
      r.swarm.routes[messages] = (_) => allowed
          ? {
              'messages': [message('m1', 1)],
              'next': null,
            }
          : throw const SuperTabFailure(
              'FORBIDDEN',
              'Not yours.',
              statusCode: 403,
            );
      final c = await open(r.reader);
      expect(c.messages, hasLength(1));

      allowed = false;
      await c.load();

      expect(c.messages, isEmpty);
    },
  );

  group('a chat a full read leaves out', () {
    /// g1 as the first load lists it while [listed]; a change read answers
    /// with a reload, as when the person's access moved.
    ({FakeSwarm swarm, SwarmReader reader, void Function() leaveOut})
    reloadRig() {
      final r = rig();
      var listed = true;
      r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {
        ...firstLoad(
          groups: [
            if (listed)
              groupData(
                'g1',
                title: 'Fix login',
                agentIds: ['agent-lead', 'agent-builder'],
                audience: [me, 'person-other'],
                lastMessageSequence: 1,
              ),
          ],
        ),
        'members': [part(me, 1, person(me))],
      };
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m1', 1, text: 'private plan')],
        'next': null,
      };
      return (
        swarm: r.swarm,
        reader: r.reader,
        leaveOut: () {
          listed = false;
          r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {
            'reload': true,
          };
        },
      );
    }

    test('and the person can no longer read loses its messages, draft and '
        'unconfirmed post, and a late answer brings none back', () async {
      final r = reloadRig();
      r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) =>
          throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');
      final c = await open(r.reader);
      expect(c.messages.single.text, 'private plan');
      c.draft = 'my reply';
      await c.send();
      expect(c.unconfirmed, isTrue);
      final late = Completer<Object?>();
      r.swarm.routes['$messages?after=1'] = (_) => late.future;
      final reading = c.load();

      r.leaveOut();
      await r.reader.refresh();
      await settle();

      expect(c.conversation, isNull);
      expect(
        r.swarm.paths,
        contains('/api/super-tabs/$tab/groups/g1'),
        reason: 'a closed chat is left out too, so it is asked by id',
      );
      expect(c.messages, isEmpty);
      expect(c.draft, isEmpty);
      expect(c.unconfirmed, isFalse);

      late.complete({
        'messages': [message('m2', 2, text: 'more of the plan')],
        'next': null,
      });
      await reading;
      await settle();
      expect(c.messages, isEmpty);
    });

    test(
      'but can still read, as a closed one, keeps its draft and messages',
      () async {
        final r = reloadRig();
        r.swarm.routes['/api/super-tabs/$tab/groups/g1'] = (_) => {
          'group': part(
            'g1',
            9,
            groupData(
              'g1',
              title: 'Fix login',
              audience: [me, 'person-other'],
              lastMessageSequence: 1,
              dormant: true,
            ),
          ),
        };
        final c = await open(r.reader);
        c.draft = 'my reply';

        r.leaveOut();
        await r.reader.refresh();
        await settle();

        expect(c.conversation?.closed, isTrue);
        expect(c.messages.single.text, 'private plan');
        expect(c.draft, 'my reply');
      },
    );
  });

  group('where it stands', () {
    const lookup = '/api/super-tabs/$tab/groups/g-old';
    const old = '/api/super-tabs/$tab/conversations/g-old/messages';

    test('loading, then loaded', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m1', 1)],
        'next': null,
      };
      await r.reader.refresh();
      final c = SwarmConversation(r.reader, 'g1');
      addTearDown(c.dispose);
      expect(c.state, SwarmChatState.loading);

      await c.load();

      expect(c.state, SwarmChatState.loaded);
    });

    test('a chat no full read has is looked for, its messages read '
        'meanwhile', () async {
      final r = rig();
      final found = Completer<Object?>(), page = Completer<Object?>();
      r.swarm.routes[lookup] = (_) => found.future;
      r.swarm.routes[old] = (_) => page.future;
      await r.reader.refresh();
      final c = SwarmConversation(r.reader, 'g-old');
      addTearDown(c.dispose);

      final loading = c.load();
      await settle();

      expect(c.state, SwarmChatState.locating);
      expect(r.swarm.paths, containsAll([lookup, old]));

      page.complete({
        'messages': [
          message('m1', 1, text: 'old plan', conversationId: 'g-old'),
        ],
        'next': null,
      });
      found.complete({
        'group': part(
          'g-old',
          9,
          groupData(
            'g-old',
            title: 'Old work',
            lastMessageSequence: 1,
            dormant: true,
          ),
        ),
      });
      await loading;
      await settle();

      expect(c.conversation?.closed, isTrue);
      expect(c.messages.single.text, 'old plan');
      expect(c.state, SwarmChatState.loaded);
    });

    test('not open to the person only once the lookup refuses it', () async {
      final r = rig();
      final found = Completer<Object?>();
      r.swarm.routes[lookup] = (_) => found.future;
      r.swarm.routes[old] = (_) =>
          throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');
      await r.reader.refresh();
      final c = SwarmConversation(r.reader, 'g-old');
      addTearDown(c.dispose);
      var told = 0;
      c.addListener(() => told++);

      final loading = c.load();
      await settle();
      expect(c.state, isNot(SwarmChatState.lost));

      found.completeError(
        const SuperTabFailure('FORBIDDEN', 'Not yours.', statusCode: 403),
      );
      await loading;
      await settle();

      expect(c.state, SwarmChatState.lost);
      expect(told, greaterThan(0), reason: 'the page is told');
    });
  });

  test('reading back to a quoted message tells the chat once, not at each '
      'page', () async {
    final r = rig(sequence: 30);
    r.swarm.routes[messages] = (_) => {
      'messages': [message('m30', 30)],
      'next': {'sequence': 30, 'id': 'm30'},
    };
    for (var top = 30; top > 26; top--) {
      r.swarm.routes['$messages?before=$top&beforeId=m$top'] = (_) => {
        'messages': [message('m${top - 1}', top - 1)],
        'next': {'sequence': top - 1, 'id': 'm${top - 1}'},
      };
    }
    final c = await open(r.reader);
    var told = 0;
    c.addListener(() => told++);

    expect(await c.readBackTo('m27'), isTrue);

    expect(told, 1);
    expect([for (final m in c.messages) m.id], ['m27', 'm28', 'm29', 'm30']);
    expect(r.swarm.paths.where((p) => p.contains('?before=')), hasLength(3));

    told = 0;
    expect(await c.readBackTo('m1', pages: 1), isFalse);
    expect(told, 1);
    expect(c.hasOlder, isTrue);
  });

  group('opened again', () {
    /// g1 read once and closed.
    Future<void> readAndClose(SwarmReader reader) async {
      await reader.refresh();
      final first = SwarmConversation(reader, 'g1');
      await first.load();
      first.dispose();
    }

    test(
      'shows at once what was read, and reads only what came after',
      () async {
        final r = rig();
        r.swarm.routes[messages] = (_) => {
          'messages': [message('m2', 2), message('m1', 1)],
          'next': {'sequence': 1, 'id': 'm1'},
        };
        await readAndClose(r.reader);

        final c = SwarmConversation(r.reader, 'g1');
        addTearDown(c.dispose);

        expect([for (final m in c.messages) m.id], ['m1', 'm2']);
        expect(c.hasOlder, isTrue);
        expect(c.state, SwarmChatState.loaded);
        r.swarm.routes['$messages?after=2'] = (_) => {
          'messages': [message('m3', 3)],
          'next': null,
        };
        await c.load();
        expect(r.swarm.paths.last, '$messages?after=2');
        expect([for (final m in c.messages) m.id], ['m1', 'm2', 'm3']);
      },
    );

    test('more than a page newer reads the latest page instead', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m2', 2), message('m1', 1)],
        'next': null,
      };
      await readAndClose(r.reader);
      r.swarm.routes['$messages?after=2'] = (_) => {
        'messages': [for (var i = 3; i < 103; i++) message('m$i', i)],
        'next': {'sequence': 102, 'id': 'm102'},
      };
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m300', 300), message('m299', 299)],
        'next': {'sequence': 299, 'id': 'm299'},
      };

      final c = SwarmConversation(r.reader, 'g1');
      addTearDown(c.dispose);
      await c.load();

      expect(r.swarm.paths.last, messages);
      expect([for (final m in c.messages) m.id], ['m299', 'm300']);
      expect(c.hasOlder, isTrue);
    });
  });

  // Desktop's reactions (backend reactions.ts): the person's own emoji counts
  // at once, the backend confirms it, and a change made anywhere reads the
  // page shown again so the counts match Desktop.
  group('reactions', () {
    const commands = '/api/super-tabs/$tab/commands';

    Map<String, dynamic> reacted(
      Map<String, dynamic> row,
      Map<String, List<(String, String)>> by,
    ) => {
      ...row,
      'reactions': [
        for (final MapEntry(key: emoji, value: who) in by.entries)
          {
            'emoji': emoji,
            'count': who.length,
            'by': [
              for (final (kind, id) in who) {'kind': kind, 'id': id},
            ],
          },
      ],
    };

    /// g1 at [sequence] with its reaction counter at [reactionSeq], as a
    /// change read brings it.
    Map<String, dynamic> moved(int version, int reactionSeq) => changes(
      cursor: 'c$version',
      groups: [
        part('g1', version, {
          ...groupData(
            'g1',
            title: 'Fix login',
            agentIds: ['agent-lead', 'agent-builder'],
            lastMessageSequence: 2,
          ),
          'reactionSeq': reactionSeq,
        }),
      ],
    );

    String counts(SwarmConversation c, String id) => [
      for (final r in c.reactionsOf(c.messages.firstWhere((m) => m.id == id)))
        '${r.emoji.key}:${[for (final who in r.by) who.id].join('+')}',
    ].join(' ');

    test('reacting counts the emoji at once, sends it, and reads the page '
        'shown back', () async {
      final r = rig();
      var page = [message('m2', 2), message('m1', 1)];
      r.swarm.routes[messages] = (_) => {
        'messages': page,
        'next': null,
        'reactionSeq': 0,
      };
      final sent = Completer<Object?>();
      r.swarm.routes[commands] = (_) => sent.future;
      final c = await open(r.reader);

      final reacting = c.react(c.messages.first, SuperTabReactionEmoji.tada);

      expect(counts(c, 'm1'), 'tada:$me');
      expect(r.swarm.commands.single, {
        'type': 'message.react',
        'conversationId': 'g1',
        'messageId': 'm1',
        'emoji': 'tada',
        'on': true,
      });
      page = [
        message('m2', 2),
        reacted(message('m1', 1), {
          'tada': [('agent', 'agent-lead'), ('person', me)],
        }),
      ];
      r.swarm.routes['$messages?before=3'] = (_) => {
        'messages': page,
        'next': null,
        'reactionSeq': 2,
      };
      sent.complete({'result': <String, dynamic>{}});

      expect(await reacting, isTrue);
      expect(counts(c, 'm1'), 'tada:agent-lead+$me');
      expect(c.messages.first.reactions.single.count, 2);
    });

    test('reacting with your own emoji again takes it back', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [
          reacted(message('m1', 1), {
            'heart': [('person', me), ('agent', 'agent-lead')],
          }),
        ],
        'next': null,
        'reactionSeq': 4,
      };
      final sent = Completer<Object?>();
      r.swarm.routes[commands] = (_) => sent.future;
      final c = await open(r.reader);

      final reacting = c.react(c.messages.single, SuperTabReactionEmoji.heart);

      expect(counts(c, 'm1'), 'heart:agent-lead');
      expect(r.swarm.commands.single['on'], isFalse);
      sent.complete({'result': <String, dynamic>{}});
      await reacting;
    });

    test('a refused reaction goes back and says why', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m1', 1)],
        'next': null,
        'reactionSeq': 0,
      };
      r.swarm.routes[commands] = (_) => throw SuperTabFailure(
        'NOT_FOUND',
        'This message is unavailable.',
        statusCode: 404,
      );
      final c = await open(r.reader);
      var told = 0;
      c.addListener(() => told++);

      expect(
        await c.react(c.messages.single, SuperTabReactionEmoji.eyes),
        isFalse,
      );

      expect(counts(c, 'm1'), '');
      expect(c.error, 'This message is unavailable.');
      expect(told, greaterThan(0));
    });

    test('a person who cannot post cannot react', () async {
      final r = rig(role: 'viewer');
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m1', 1)],
        'next': null,
      };
      final c = await open(r.reader);

      expect(
        await c.react(c.messages.single, SuperTabReactionEmoji.eyes),
        isFalse,
      );
      expect(r.swarm.commands, isEmpty);
    });

    test('a reaction made elsewhere reads the page shown again; a Swarm read '
        'that moved no counter reads nothing', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m2', 2), message('m1', 1)],
        'next': null,
        'reactionSeq': 0,
      };
      final c = await open(r.reader);
      await r.reader.refresh();
      await settle();
      expect(r.swarm.paths.where((p) => p.contains('before=')), isEmpty);

      r.swarm.routes['$messages?before=3'] = (_) => {
        'messages': [
          message('m2', 2),
          reacted(message('m1', 1), {
            'rocket': [('person', 'person-ann')],
          }),
        ],
        'next': null,
        'reactionSeq': 1,
      };
      r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => moved(30, 1);
      await r.reader.refresh();
      await settle();

      expect(counts(c, 'm1'), 'rocket:person-ann');
      await r.reader.refresh();
      await settle();
      expect(
        r.swarm.paths.where((p) => p.contains('before=')),
        hasLength(1),
        reason: 'the counter it read is the one the Swarm says',
      );
    });

    test('new messages that come with a moved counter read the page shown '
        'again too', () async {
      final r = rig(sequence: 2);
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m2', 2), message('m1', 1)],
        'next': null,
        'reactionSeq': 0,
      };
      final c = await open(r.reader);
      r.swarm.routes['$messages?after=2'] = (_) => {
        'messages': [message('m3', 3)],
        'next': null,
        'reactionSeq': 1,
      };
      r.swarm.routes['$messages?before=4'] = (_) => {
        'messages': [
          message('m3', 3),
          reacted(message('m2', 2), {
            'laugh': [('agent', 'agent-lead')],
          }),
          message('m1', 1),
        ],
        'next': null,
        'reactionSeq': 1,
      };

      await c.load();

      expect([for (final m in c.messages) m.id], ['m1', 'm2', 'm3']);
      expect(counts(c, 'm2'), 'laugh:agent-lead');
    });

    test('a chat opened again reads its page again only when a reaction '
        'changed while it was closed', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m2', 2), message('m1', 1)],
        'next': null,
        'reactionSeq': 3,
      };
      await r.reader.refresh();
      var c = SwarmConversation(r.reader, 'g1');
      await c.load();
      c.dispose();

      // Opened again with nothing changed: what was kept, and new messages
      // only.
      c = SwarmConversation(r.reader, 'g1');
      await c.load();
      await settle();
      expect(r.swarm.paths.where((p) => p.contains('before=')), isEmpty);
      c.dispose();

      r.swarm.routes['$messages?after=2'] = (_) => {
        'messages': <Object>[],
        'next': null,
        'reactionSeq': 5,
      };
      r.swarm.routes['$messages?before=3'] = (_) => {
        'messages': [
          message('m2', 2),
          reacted(message('m1', 1), {
            'thumbs_up': [('person', 'person-ann')],
          }),
        ],
        'next': null,
        'reactionSeq': 5,
      };
      c = SwarmConversation(r.reader, 'g1');
      addTearDown(c.dispose);
      await c.load();
      await settle();

      expect(counts(c, 'm1'), 'thumbs_up:person-ann');
    });
  });

  // Chat threads (backend threads.ts, the desktop's main stream): a reply
  // only in its thread is read with the chat and listed in its thread alone;
  // each page names the threads its rows are in.
  group('threads', () {
    Map<String, dynamic> line(String root, int replies, int last) => {
      'id': root,
      'replies': replies,
      'lastSequence': last,
      'lastAt': '2026-10-27T01:05:00.000Z',
      'authors': [
        {'kind': 'agent', 'id': 'agent-builder', 'name': 'Builder'},
      ],
      'people': [me],
    };
    Map<String, dynamic> reply(
      String id,
      int sequence, {
      String root = 'm1',
      bool also = false,
    }) => {
      ...message(id, sequence),
      'thread': root,
      if (also) 'alsoInChat': true,
    };

    test('a reply only in its thread leaves the chat\'s list, one also sent '
        'stays, and the root keeps its thread line', () async {
      final r = rig(sequence: 4);
      r.swarm.routes[messages] = (_) => {
        'messages': [
          {...message('m1', 1), 'thread': 'm1'},
          reply('m2', 2),
          reply('m3', 3, also: true),
          {...message('m4', 4), 'thread': 'm4'},
        ],
        'next': null,
        'threads': [line('m1', 2, 3)],
      };

      final c = await open(r.reader);

      expect([for (final m in c.messages) m.id], ['m1', 'm2', 'm3', 'm4']);
      expect([for (final m in c.stream) m.id], ['m1', 'm3', 'm4']);
      expect(c.stream, same(c.stream), reason: 'made once per read');
      expect(c.thread('m1')?.replies, 2);
      expect(c.thread('m4'), isNull);
    });

    test('a read that brings only a thread reply moves its root\'s line and '
        'tells the chat, with its list as it was', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [
          {...message('m1', 1), 'thread': 'm1'},
          reply('m2', 2),
        ],
        'next': null,
        'threads': [line('m1', 1, 2)],
      };
      final c = await open(r.reader);
      var told = 0;
      c.addListener(() => told++);
      r.swarm.routes['$messages?after=2'] = (_) => {
        'messages': [reply('m3', 3)],
        'next': null,
        'threads': [line('m1', 2, 3)],
      };

      await c.load();

      expect(told, greaterThan(0));
      expect([for (final m in c.stream) m.id], ['m1']);
      expect(c.thread('m1')?.replies, 2);
    });

    test('an older thread line never replaces a newer one, and the same line '
        'again tells no one', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [
          {...message('m1', 1), 'thread': 'm1'},
        ],
        'next': null,
        'threads': [line('m1', 3, 5)],
      };
      final c = await open(r.reader);
      var told = 0;
      c.addListener(() => told++);

      c.keepThreads([line('m1', 2, 3)]);
      c.keepThreads([line('m1', 3, 5)]);

      expect(c.thread('m1')?.replies, 3);
      expect(told, 0);
      c.keepThreads([line('m1', 4, 6)]);
      expect(c.thread('m1')?.replies, 4);
      expect(told, 1);
      // Its tag draws from the line too, so a changed state is a change.
      c.keepThreads([
        {...line('m1', 4, 6), 'ask': 'proposal'},
      ]);
      expect(c.thread('m1')?.askTag, '✋ Proposal');
      expect(told, 2);
    });

    test('a chat the person can no longer read forgets its thread lines and '
        'thread drafts', () async {
      final r = rig();
      var allowed = true;
      r.swarm.routes[messages] = (_) => allowed
          ? {
              'messages': [
                {...message('m1', 1), 'thread': 'm1'},
                reply('m2', 2),
              ],
              'next': null,
              'threads': [line('m1', 1, 2)],
            }
          : throw const SuperTabFailure(
              'FORBIDDEN',
              'Not yours.',
              statusCode: 403,
            );
      final c = await open(r.reader);
      c.setThreadDraft('m1', 'Half a reply');
      expect(c.threadDraft('m1'), 'Half a reply');

      allowed = false;
      await c.load();

      expect(c.thread('m1'), isNull);
      expect(c.threadDraft('m1'), isEmpty);
      expect(c.stream, isEmpty);
    });

    test('opened again, a kept chat shows its roots\' lines at once, and only '
        'theirs', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [
          {...message('m1', 1), 'thread': 'm1'},
          reply('m2', 2),
        ],
        'next': null,
        'threads': [line('m1', 1, 2), line('gone', 4, 1)],
      };
      await r.reader.refresh();
      final first = SwarmConversation(r.reader, 'g1');
      await first.load();
      first.dispose();

      final c = SwarmConversation(r.reader, 'g1');
      addTearDown(c.dispose);

      expect(c.thread('m1')?.replies, 1);
      expect(c.thread('gone'), isNull);
      expect([for (final m in c.stream) m.id], ['m1']);
    });
  });

  group('read marks', () {
    const read = '/api/super-tabs/$tab/conversations/g1/read';

    /// [r]'s Swarm with read marks the inbox would give it, and the marks it
    /// sends.
    ({SwarmReadMarks marks, List<Object?> sent}) marked(
      ({FakeSwarm swarm, SwarmReader reader}) r,
    ) {
      final marks = SwarmReadMarks(r.reader, store: null);
      r.reader.readMarks = marks;
      addTearDown(marks.dispose);
      final sent = <Object?>[];
      r.swarm.routes[read] = (body) {
        sent.add(body!['sequence']);
        return {'sequence': body['sequence']};
      };
      return (marks: marks, sent: sent);
    }

    /// A change read in which g1 moved on to [sequence], its main stream to
    /// [main] where the server says it.
    void moveOn(FakeSwarm swarm, int sequence, {int? main}) =>
        swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
          cursor: 'c3',
          groups: [
            part('g1', 9 + sequence, {
              ...groupData(
                'g1',
                title: 'Fix login',
                agentIds: const ['agent-lead', 'agent-builder'],
                lastMessageSequence: sequence,
              ),
              'lastMainSequence': ?main,
            }),
          ],
        );

    test('an open chat is read through its newest message, and again as '
        'new ones come', () async {
      final r = rig();
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m2', 2), message('m1', 1)],
        'next': null,
      };

      await open(r.reader);
      await settle();
      expect(m.sent, [2]);

      r.swarm.routes['$messages?after=2'] = (_) => {
        'messages': [message('m3', 3)],
        'next': null,
      };
      moveOn(r.swarm, 3);
      await r.reader.refresh();
      await settle();

      expect(m.sent, [2, 3]);
      expect(m.marks.unread(r.reader.snapshot!.conversation('g1')!), isFalse);
    });

    test('a covered chat is not read until it shows again', () async {
      final r = rig();
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m2', 2), message('m1', 1)],
        'next': null,
      };
      final c = await open(r.reader);
      await settle();

      c.shown = false;
      r.swarm.routes['$messages?after=2'] = (_) => {
        'messages': [message('m3', 3)],
        'next': null,
      };
      moveOn(r.swarm, 3);
      await r.reader.refresh();
      await settle();
      expect(c.messages.last.id, 'm3');
      expect(m.sent, [2]);
      expect(m.marks.unread(r.reader.snapshot!.conversation('g1')!), isTrue);

      c.shown = true;
      await settle();

      expect(m.sent, [2, 3]);
      expect(m.marks.unread(r.reader.snapshot!.conversation('g1')!), isFalse);
    });

    test('a chat read before, opened again covered or at an earlier '
        'message, marks nothing past what is seen of what it kept', () async {
      final r = rig();
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m2', 2), message('m1', 1)],
        'next': null,
      };
      await r.reader.refresh();
      // Read while covered: kept, and not read.
      var c = SwarmConversation(r.reader, 'g1', shown: false);
      await c.load();
      c.dispose();
      await settle();
      expect(m.sent, isEmpty);

      c = SwarmConversation(r.reader, 'g1', shown: false);
      c.dispose();
      await settle();
      expect(m.sent, isEmpty, reason: 'covered from the start');

      c = SwarmConversation(r.reader, 'g1', heldAt: 'm1');
      addTearDown(c.dispose);
      await settle();
      expect(m.sent, [1], reason: 'only through the message it opened at');
    });

    test('a loaded chat whose newest message is a reply only in a thread is '
        'not bold; a message in the main stream bolds it', () async {
      final r = rig();
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m2', 2)],
        'next': null,
      };
      await r.reader.refresh();
      await settle();
      // Loaded while another screen covers it, so it marks nothing itself.
      final c = SwarmConversation(r.reader, 'g1', shown: false);
      addTearDown(c.dispose);
      await c.load();
      SuperTabConversation g1() => r.reader.snapshot!.conversation('g1')!;
      bool bold() => swarmChatNews(r.reader, null, g1()).bold;

      r.swarm.routes['$messages?after=2'] = (_) => {
        'messages': [
          {...message('m3', 3, text: 'in the thread'), 'thread': 'm2'},
        ],
        'next': null,
      };
      r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
        cursor: 'c3',
        groups: [
          part('g1', 30, {
            ...groupData('g1', title: 'Fix login', lastMessageSequence: 3),
            'lastMainSequence': 2,
          }),
        ],
      );
      await r.reader.refresh();
      await settle();

      expect(c.messages.last.threadReply, isTrue, reason: 'loaded, last');
      expect(m.marks.unread(g1()), isFalse);
      expect(bold(), isFalse);

      r.swarm.routes['$messages?after=3'] = (_) => {
        'messages': [message('m4', 4, text: 'in the chat')],
        'next': null,
      };
      r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
        cursor: 'c4',
        groups: [
          part('g1', 31, {
            ...groupData('g1', title: 'Fix login', lastMessageSequence: 4),
            'lastMainSequence': 4,
          }),
        ],
      );
      await r.reader.refresh();
      await settle();

      expect(c.messages.last.id, 'm4');
      expect(bold(), isTrue);
      expect(m.sent, isEmpty, reason: 'covered: it marked nothing');
    });

    test('an open chat whose newest message is a reply only in a thread is '
        'read through its newest message in the main stream, and a reply '
        'only in a thread arriving later marks nothing', () async {
      final r = rig(sequence: 3, readMarks: const {'g1': 1}, mainSequence: 2);
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [
          {...message('m3', 3, text: 'in the thread'), 'thread': 'm1'},
          message('m2', 2),
          {...message('m1', 1), 'thread': 'm1'},
        ],
        'next': null,
      };

      final c = await open(r.reader);
      await settle();
      expect(c.messages.last.threadReply, isTrue, reason: 'loaded, last');
      expect(m.sent, [2], reason: 'the thread reply is not on screen');
      expect(m.marks.readThrough('g1'), 2);

      r.swarm.routes['$messages?after=3'] = (_) => {
        'messages': [
          {...message('m4', 4, text: 'in the thread'), 'thread': 'm1'},
        ],
        'next': null,
      };
      moveOn(r.swarm, 4, main: 2);
      await r.reader.refresh();
      await settle();

      expect(c.messages.last.id, 'm4');
      expect(m.sent, [2]);
      expect(m.marks.readThrough('g1'), 2);
    });

    test('a chat read before, opened again with no network, is read through '
        'the newest main-stream message it kept', () async {
      final r = rig(sequence: 3, readMarks: const {'g1': 1}, mainSequence: 2);
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [
          {...message('m3', 3, text: 'in the thread'), 'thread': 'm1'},
          message('m2', 2),
          {...message('m1', 1), 'thread': 'm1'},
        ],
        'next': null,
      };
      await r.reader.refresh();
      var c = SwarmConversation(r.reader, 'g1', shown: false);
      await c.load();
      c.dispose();
      await settle();
      expect(m.sent, isEmpty);

      // Offline: the kept page shows and is read; nothing reads on.
      r.swarm.routes.remove(messages);
      r.swarm.routes[read] = (_) => throw StateError('offline');
      c = SwarmConversation(r.reader, 'g1');
      addTearDown(c.dispose);
      await settle();

      expect(c.messages.last.id, 'm3');
      expect(m.marks.readThrough('g1'), 2);
    });

    test('a chat opened at a reply only in a thread is read through the '
        'main-stream message before it', () async {
      final r = rig(sequence: 4, mainSequence: 4);
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [
          message('m4', 4),
          {...message('m3', 3, text: 'in the thread'), 'thread': 'm1'},
          message('m2', 2),
          {...message('m1', 1), 'thread': 'm1'},
        ],
        'next': null,
      };
      await r.reader.refresh();
      final c = SwarmConversation(r.reader, 'g1', heldAt: 'm3');
      addTearDown(c.dispose);
      await c.load();
      await settle();

      expect(m.sent, [2]);
    });

    test('a reply also sent to the chat is in the main stream, and moves '
        'the mark when it is the newest', () async {
      final r = rig(sequence: 3, readMarks: const {'g1': 1}, mainSequence: 3);
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [
          {
            ...message('m3', 3, text: 'also in the chat'),
            'thread': 'm1',
            'alsoInChat': true,
          },
          message('m2', 2),
          {...message('m1', 1), 'thread': 'm1'},
        ],
        'next': null,
      };

      await open(r.reader);
      await settle();

      expect(m.sent, [3]);
    });

    test('a server too old to say a chat\'s newest main-stream message is '
        'read through its newest message, as on the desktop', () async {
      final r = rig(sequence: 3, readMarks: const {'g1': 1});
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [
          {...message('m3', 3, text: 'in the thread'), 'thread': 'm1'},
          message('m2', 2),
          {...message('m1', 1), 'thread': 'm1'},
        ],
        'next': null,
      };

      await open(r.reader);
      await settle();

      expect(r.reader.snapshot!.conversation('g1')!.lastMainSequence, isNull);
      expect(m.sent, [3]);
    });

    test('a mark the server holds ahead of what the chat shows is neither '
        'sent back nor replaced', () async {
      final r = rig(sequence: 3, readMarks: const {'g1': 5});
      final m = marked(r);
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m3', 3), message('m2', 2)],
        'next': null,
      };

      await open(r.reader);
      await settle();

      expect(r.reader.snapshot!.readMarks['g1'], 5);
      expect(m.sent, isEmpty);
      expect(m.marks.readThrough('g1'), 5);
    });

    test('a Swarm without read marks marks nothing', () async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {
        'messages': [message('m1', 1)],
        'next': null,
      };

      await open(r.reader);
      await settle();

      expect(r.swarm.paths.where((p) => p.endsWith('/read')), isEmpty);
    });
  });

  group('posts on their way (Dee, 11-01)', () {
    const commands = '/api/super-tabs/$tab/commands';

    /// Chat g1, read, with nothing in it; its posts wait [timeout] for an
    /// answer.
    Future<({FakeSwarm swarm, SwarmReader reader, SwarmConversation c})> chat({
      Duration timeout = SwarmOutbox.defaultTimeout,
    }) async {
      final r = rig();
      r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};
      await r.reader.refresh();
      final c = SwarmConversation(r.reader, 'g1', sendTimeout: timeout);
      addTearDown(c.dispose);
      await c.load();
      return (swarm: r.swarm, reader: r.reader, c: c);
    }

    /// What [opening] gives, on [async]'s clock: a timeout there passes only
    /// when the test says so, never because the machine is slow.
    T onFakeClock<T>(FakeAsync async, Future<T> opening) {
      late final T opened;
      unawaited(opening.then((value) => opened = value));
      async.flushMicrotasks();
      return opened;
    }

    /// The bodies [swarm] was sent, by receipt, each answered by hand.
    Map<String, Completer<Object?>> held(FakeSwarm swarm) {
      final answers = <String, Completer<Object?>>{};
      swarm.routes[commands] = (body) =>
          (answers[body!['operationId'] as String] ??= Completer()).future;
      return answers;
    }

    Map<String, dynamic> mine(String id, int sequence, String text) =>
        message(id, sequence, text: text, authorId: me, fromAgent: false);

    test(
      'a read that brings the post back under the id the backend gives it '
      'takes its copy away at once, though its answer is still coming',
      () async {
        final r = await chat();
        final answers = held(r.swarm);
        r.c.draft = 'On it';
        final sending = r.c.send();
        await settle();
        final receipt = answers.keys.single;
        expect(r.c.outgoing.single.messageId, sentId(receipt));

        r.swarm.routes[messages] = (_) => {
          'messages': [mine(sentId(receipt), 3, 'On it')],
          'next': null,
        };
        await r.c.load();

        expect(r.c.outgoing, isEmpty, reason: 'shown once, as its message');
        expect(r.c.sending, isFalse);
        answers[receipt]!.complete({'result': <String, dynamic>{}});
        expect(await sending, isTrue);
        expect(r.c.outgoing, isEmpty);
        expect(r.c.error, isNull);
      },
    );

    test('the id in the answer is the one looked for', () async {
      final r = await chat();
      r.swarm.routes[commands] = (_) => {
        'result': {'messageId': 'server-m7'},
      };
      r.c.draft = 'On it';

      expect(await r.c.send(), isTrue);
      expect(r.c.outgoing.single.messageId, 'server-m7');
      expect(r.c.outgoing.single.state, SwarmPostState.confirmed);

      r.swarm.routes[messages] = (_) => {
        'messages': [mine('server-m7', 3, 'On it')],
        'next': null,
      };
      await r.c.load();
      expect(r.c.outgoing, isEmpty);
    });

    test('a second post goes while the first is on its way, under its own '
        'receipt, and each leaves when it is read back', () async {
      final r = await chat();
      final answers = held(r.swarm);
      r.c.draft = 'One';
      final one = r.c.send();
      await settle();
      r.c.draft = 'Two';
      expect(r.c.canSend, isTrue, reason: 'never waits on the first');
      final two = r.c.send();
      await settle();

      final [first, second] = answers.keys.toList();
      expect(first, isNot(second));
      expect([for (final p in r.c.outgoing) p.text], ['One', 'Two']);
      expect(
        r.c.outgoing.every((p) => p.state == SwarmPostState.sending),
        isTrue,
      );

      r.swarm.routes[messages] = (_) => {
        'messages': [mine(sentId(second), 3, 'Two')],
        'next': null,
      };
      answers[second]!.complete({'result': <String, dynamic>{}});
      expect(await two, isTrue);
      await settle();
      expect([for (final p in r.c.outgoing) p.text], ['One']);

      r.swarm.routes[messages] = (_) => {
        'messages': [
          mine(sentId(second), 3, 'Two'),
          mine(sentId(first), 4, 'One'),
        ],
        'next': null,
      };
      answers[first]!.complete({'result': <String, dynamic>{}});
      expect(await one, isTrue);
      await settle();
      expect(r.c.outgoing, isEmpty);
    });

    test('no answer in time says Not sent; Retry sends the same receipt, and '
        'the first answer landing late still counts', () {
      fakeAsync((async) {
        final r = onFakeClock(async, chat());
        final answers = held(r.swarm);
        r.c.draft = 'Once only';

        bool? sent;
        unawaited(r.c.send().then((value) => sent = value));
        async.elapse(SwarmOutbox.defaultTimeout);
        expect(sent, isFalse);
        final post = r.c.outgoing.single;
        expect(post.state, SwarmPostState.unconfirmed);
        expect(r.c.unconfirmed, isTrue);
        expect(r.c.error, contains('not sent'));
        expect(r.c.canSend, isFalse, reason: 'the field is empty');
        r.c.draft = 'Meanwhile';
        expect(r.c.canSend, isTrue, reason: 'a lost post holds nothing back');
        r.c.draft = '';

        bool? again;
        unawaited(r.c.retry(post).then((value) => again = value));
        async.flushMicrotasks();
        final posts = [
          for (final call in r.swarm.calls)
            if (call.path == commands) call.body!['operationId'],
        ];
        expect(posts, hasLength(2));
        expect(posts.toSet(), hasLength(1), reason: 'one post, one receipt');
        // The last moment of the retry's own wait, whatever the machine's speed.
        async.elapse(
          SwarmOutbox.defaultTimeout - const Duration(milliseconds: 1),
        );
        expect(again, isNull);
        // Both tries are one command: its one answer answers both.
        answers.values.single.complete({'result': <String, dynamic>{}});
        async.flushMicrotasks();
        expect(again, isTrue);
        expect(post.state, SwarmPostState.confirmed);
        expect(r.c.error, isNull);
      });
    });

    test('a refusal that lands after Not sent still puts the text back', () {
      fakeAsync((async) {
        final r = onFakeClock(async, chat());
        final answers = held(r.swarm);
        r.c.draft = 'Too long';

        bool? sent;
        unawaited(r.c.send().then((value) => sent = value));
        async.elapse(SwarmOutbox.defaultTimeout);
        expect(sent, isFalse);
        expect(r.c.outgoing.single.state, SwarmPostState.unconfirmed);
        expect(r.c.draft, isEmpty);

        answers.values.single.completeError(
          const SuperTabFailure('TOO_LONG', 'Too long.', statusCode: 400),
        );
        async.flushMicrotasks();
        expect(r.c.outgoing, isEmpty);
        expect(r.c.draft, 'Too long');
        expect(r.c.error, 'Too long.');
      });
    });

    test('a refused post goes back to the draft while another stays on its '
        'way', () async {
      final r = await chat();
      final answers = held(r.swarm);
      r.c.draft = 'Too long';
      final refused = r.c.send();
      await settle();
      r.c.draft = 'Fine';
      final fine = r.c.send();
      await settle();

      final [first, _] = answers.keys.toList();
      answers[first]!.completeError(
        const SuperTabFailure('TOO_LONG', 'Too long.', statusCode: 400),
      );
      expect(await refused, isFalse);

      expect(r.c.draft, 'Too long');
      expect(r.c.error, 'Too long.');
      expect([for (final p in r.c.outgoing) p.text], ['Fine']);
      answers.values.last.complete({'result': <String, dynamic>{}});
      expect(await fine, isTrue);
    });

    test('access lost while posts are on their way drops them, and their '
        'answers change nothing', () async {
      final r = await chat();
      final answers = held(r.swarm);
      r.c.draft = 'Secret plan';
      final sending = r.c.send();
      await settle();
      expect(
        await r.c.retry(r.c.outgoing.single),
        isFalse,
        reason: 'one on its way is not sent again',
      );
      expect(r.c.error, isNull);

      r.reader.revoke();
      await settle();
      expect(r.c.outgoing, isEmpty);
      expect(r.c.draft, isEmpty);

      answers.values.single.completeError(
        const SuperTabFailure('TOO_LONG', 'Too long.', statusCode: 400),
      );
      expect(await sending, isFalse);
      expect(r.c.draft, isEmpty, reason: 'nothing put back');
      expect(r.c.outgoing, isEmpty);
      expect(r.c.error, isNull);
    });

    test('an answer after the chat closed changes nothing', () async {
      final r = await chat();
      final answers = held(r.swarm);
      final c = SwarmConversation(r.reader, 'g1');
      await c.load();
      c.draft = 'Bye';
      final sending = c.send();
      await settle();

      c.dispose();
      answers.values.single.complete({'result': <String, dynamic>{}});
      expect(await sending, isFalse);
    });

    test('a first read that failed and later recovered still sends and '
        'settles', () async {
      final r = rig();
      var fail = true;
      final rows = <Map<String, dynamic>>[];
      r.swarm.routes[messages] = (_) => fail
          ? throw StateError('offline')
          : {'messages': rows.reversed.toList(), 'next': null};
      r.swarm.routes[commands] = (body) {
        rows.add(mine(sentId(body!['operationId'] as String), 3, 'Hello'));
        return {'result': <String, dynamic>{}};
      };
      await r.reader.refresh();
      final c = SwarmConversation(r.reader, 'g1');
      addTearDown(c.dispose);
      await c.load();
      expect(c.error, isNotNull);

      fail = false;
      c.draft = 'Hello';
      expect(c.canSend, isTrue);
      expect(await c.send(), isTrue);
      await settle();

      expect(c.outgoing, isEmpty);
      expect([for (final m in c.messages) m.text], ['Hello']);
    });
  });
}