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.

94.5 KB
Raw Blame
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:clock/clock.dart';
import 'package:cryptography/dart.dart' show DartSha256;
import 'package:dio/dio.dart' show CancelToken;
import 'package:harness/state/harness_attachments.dart';
import 'package:harness/super_tabs/attachment_upload.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/reading.dart';

/// A signed link as the backend's private avatar bucket hands it out (avatarLinks.ts).
String superTabSignedAvatar(String id) =>
    'https://storage.googleapis.com/avatars/$id?X-Goog-Expires=3600&X-Goog-Signature=fixture';

Map<String, dynamic> conversationFixture(String id, String title) => {
  'id': id,
  'title': title,
  'leadId': null,
  'agentIds': <String>[],
  'archived': false,
  'brief': '',
  'checks': <dynamic>[],
  'assignment': null,
  'lastMessageSequence': 0,
};

Map<String, dynamic> projectFixture(
  String id,
  String name,
  String leadConversationId, {
  String visibility = 'public',
}) => {
  'id': id,
  'name': name,
  'ownerId': 'owner',
  'leadConversationId': leadConversationId,
  'visibility': visibility,
  'members': <dynamic>[],
  'updateMinutes': 5,
};

/// What the backend's Swarm reads answer (docs/design/2026-10-26-swarm-state-parts.md, section 4), worked out from
/// a test's whole-Swarm state. Each read compares every part with what it held: a part whose JSON changed gets the
/// next version and a new `changedAt`, a part that is gone gets a tombstone. Tests keep changing the state as they
/// did; the reads see exactly those changes.
class SwarmPartsBackend {
  /// A broken server that sends groups the reader may not read, so a test can
  /// prove the app keeps them off screen itself.
  bool leaksHiddenGroups = false;

  /// The server's clock, one tick per change; a cursor is a tick.
  int clock = 1000;
  int _version = 100;

  /// The visibility epoch: a test moves it to have the next change read answer a reload.
  int epoch = 1;

  /// A backend with the summary etag (backend read/derivedEtag.ts, #2906). Off, it is one from before it, or one rolled
  /// back: no etag is sent, and a change read naming one is refused by its strict query.
  bool stampsDerived = true;

  /// Change reads answered without the summary, its etag still matching.
  int unchangedSummaries = 0;

  static const _markFields = {
    'readMarks',
    'unreadMarks',
    'threadMarks',
    'chatSettings',
  };

  /// The summary without the reader's marks, as one string: equal summaries, equal etag.
  static String _etag(Map<String, dynamic> derived) => jsonEncode({
    for (final entry in derived.entries)
      if (!_markFields.contains(entry.key)) entry.key: entry.value,
  }).hashCode.toRadixString(36);

  /// The ticks a change read sends again, as the 30 s overlap does.
  int overlap = 3;

  /// Every read answered, by path, in order.
  final reads = <String>[];

  /// The size of each first load and change read answered, in JSON bytes.
  final bytes = <String, List<int>>{};

  final _parts = <String, _HeldPart>{};

  /// The parts of [state], by `kind:key`. Groups marked dormant leave the active set.
  static Map<String, Map<String, dynamic>> split(Map<String, dynamic> state) {
    final parts = <String, Map<String, dynamic>>{};
    parts['head:head'] = {
      for (final entry in state.entries)
        if (!const {
          'people',
          'agents',
          'conversations',
          'machines',
          'starts',
          'mentionsWaiting',
          'decisionsWaiting',
          'decisionsDigest',
          'promptsWaiting',
          'otherProjectsWork',
          'githubApp',
          'readMarks',
          'unreadMarks',
          'threadMarks',
          'chatSettings',
          'activityDigest',
          'remindersDigest',
          'teamAccounts',
          'threadSessions',
          'sessionsFromChat',
          'swarmBuddy',
        }.contains(entry.key))
          entry.key: entry.value,
    };
    void each(String kind, String list, String id) {
      for (final row in state[list] as List? ?? const []) {
        final data = Map<String, dynamic>.from(row as Map);
        parts['$kind:${data[id]}'] = data;
      }
    }

    each('members', 'people', 'id');
    each('agents', 'agents', 'id');
    each('groups', 'conversations', 'id');
    each('machines', 'machines', 'machineId');
    each('starts', 'starts', 'id');
    return parts;
  }

  /// Whether this backend leaves [group] out of the active set: archived by
  /// hand, or marked dormant as the backend's sweep marks finished, quiet work.
  static bool dormant(Map<String, dynamic> group) =>
      group['dormant'] == true || group['archived'] == true;

  void _sync(Map<String, dynamic> state) {
    final now = split(jsonDecode(jsonEncode(state)) as Map<String, dynamic>);
    for (final entry in now.entries) {
      final json = jsonEncode(entry.value);
      final held = _parts[entry.key];
      if (held != null && !held.deleted && held.json == json) continue;
      _parts[entry.key] = _HeldPart(
        version: ++_version,
        changedAt: ++clock,
        json: json,
        ordinal: held?.ordinal ?? _parts.length,
      );
    }
    for (final entry in _parts.entries.toList()) {
      if (entry.value.deleted || now.containsKey(entry.key)) continue;
      _parts[entry.key] = _HeldPart(
        version: ++_version,
        changedAt: ++clock,
        json: entry.value.json,
        ordinal: entry.value.ordinal,
        deleted: true,
      );
    }
  }

  Map<String, dynamic> _envelope(String id, _HeldPart part) => {
    'key': id.substring(id.indexOf(':') + 1),
    'version': part.version,
    'changedAt': part.changedAt,
    if (part.deleted)
      'deleted': true
    else if (id.startsWith('groups:') && dormant(part.data))
      'dormant': true
    else
      'data': part.data,
  };

  String _cursor(int tick) => 'c${tick}e$epoch';

  Map<String, dynamic> _derived(Map<String, dynamic> state, String? reader) => {
    'agents': <String, dynamic>{},
    'machines': <String, dynamic>{},
    if (state['mentionsWaiting'] != null)
      'mentionsWaiting': state['mentionsWaiting'],
    if (state['mentionsDigest'] != null)
      'mentionsDigest': state['mentionsDigest'],
    if (state['decisionsWaiting'] != null)
      'decisionsWaiting': state['decisionsWaiting'],
    if (state['decisionsDigest'] != null)
      'decisionsDigest': state['decisionsDigest'],
    if (state['promptsWaiting'] != null)
      'promptsWaiting': state['promptsWaiting'],
    if (state['otherProjectsWork'] != null)
      'otherProjectsWork': state['otherProjectsWork'],
    // Each project's board pulse (backend superTabs/pulse.ts, task #3384).
    if (state['pulse'] != null) 'pulse': state['pulse'],
    if (state['releaseTimes'] != null) 'releaseTimes': state['releaseTimes'],
    if (state['avatars'] != null) 'avatars': state['avatars'],
    // Only where the server does not try Team accounts (backend read/views.ts).
    if (state['teamAccounts'] == false) 'teamAccounts': false,
    // A server that takes a thread reply's New session (backend read/views.ts).
    if (state['threadSessions'] == true) 'threadSessions': true,
    if (state['sessionsFromChat'] == true) 'sessionsFromChat': true,
    // A server with one Buddy per person for the whole Swarm.
    if (state['swarmBuddy'] == true) 'swarmBuddy': true,
    // A server that makes several Buddies per person (#3818).
    if (state['buddyCap'] case final int cap) 'buddyCap': cap,
    // The reader's own read marks alone, as backend readMarks.ts sends them.
    if ((state['readMarks'] as Map?)?[reader ?? 'owner'] case final Map marks)
      'readMarks': Map<String, dynamic>.from(marks),
    // The reader's marks whose last move was a Mark unread (backend
    // readMarks.ts lowerReadMark), absent when none.
    if ((state['unreadMarks'] as Map?)?[reader ?? 'owner'] case final Map marks
        when marks.isNotEmpty)
      'unreadMarks': Map<String, dynamic>.from(marks),
    // Their own Activity digest and chat settings (backend activity.ts,
    // chatSettings.ts): every setting on every read, which the app keeps.
    if (state['activityDigest'] != null)
      'activityDigest': state['activityDigest'],
    if (state['remindersDigest'] != null)
      'remindersDigest': state['remindersDigest'],
    if ((state['chatSettings'] as Map?)?[reader ?? 'owner'] case final Map set
        when set.isNotEmpty)
      'chatSettings': Map<String, dynamic>.from(set),
    // Their own thread marks alone, by conversation, absent when none.
    if ((state['threadMarks'] as Map?)?[reader ?? 'owner'] case final Map marks
        when marks.isNotEmpty)
      'threadMarks': {
        for (final MapEntry(:key, :value) in marks.entries)
          key: Map<String, dynamic>.from(value as Map),
      },
  };

  List<MapEntry<String, _HeldPart>> _ordered() =>
      _parts.entries.toList()
        ..sort((a, b) => a.value.ordinal.compareTo(b.value.ordinal));

  /// Whether [reader] may not read [part]: a private conversation is read only
  /// by its audience (and the project's Lead, an agent), owners included, and
  /// by each person only at the membership generation they were listed with
  /// (backend projects.ts canReadGroup), when [state] gives them one.
  bool _hides(
    String id,
    _HeldPart part,
    String? reader,
    Map<String, dynamic> state,
  ) => !leaksHiddenGroups && _hidden(id, part, reader, state);

  static bool _hidden(
    String id,
    _HeldPart part,
    String? reader,
    Map<String, dynamic> state,
  ) {
    if (reader == null || part.deleted || !id.startsWith('groups:')) {
      return false;
    }
    // A Buddy chat is read by its person alone (backend Buddies, 10-28).
    if (part.data['kind'] == 'buddy') {
      return part.data['buddyOwnerId'] != reader;
    }
    final audience = part.data['audience'];
    if (audience is! Map) return false;
    final generation = (state['people'] as List?)
        ?.cast<Map>()
        .where((p) => p['id'] == reader)
        .firstOrNull?['generation'];
    return !(audience['people'] as List).any(
      (p) =>
          (p as Map)['id'] == reader &&
          (generation == null || p['generation'] == generation),
    );
  }

  /// The answer to a Swarm read of [state] at [path] by [reader], or null for a path that is not one. With no
  /// reader, every group is read.
  Map<String, dynamic>? read(
    String path,
    Map<String, dynamic> state, {
    String? reader,
  }) {
    final uri = Uri.parse(path);
    final segments = uri.pathSegments;
    if (segments.length < 4 || segments[0] != 'api') return null;
    final route = segments[3];
    // Time passes between reads, changed or not.
    clock++;
    if (segments.length == 4 && route == 'parts') {
      _sync(state);
      reads.add(path);
      final answer = <String, dynamic>{
        'format': 2,
        'tabId': state['id'],
        'cursor': _cursor(clock - overlap),
        'serverTime': clock,
        'lastChangedAt': _lastChangedAt(),
        'epoch': epoch,
        'githubApp': state['githubApp'] ?? false,
        'head': _envelope('head:head', _parts['head:head']!),
        for (final kind in _kinds) kind: <dynamic>[],
        'derived': _derived(state, reader),
      };
      if (stampsDerived) {
        answer['derivedEtag'] = _etag(
          answer['derived'] as Map<String, dynamic>,
        );
      }
      for (final entry in _ordered()) {
        final kind = entry.key.substring(0, entry.key.indexOf(':'));
        if (kind == 'head' || entry.value.deleted) continue;
        if (kind == 'groups' && dormant(entry.value.data)) continue;
        if (_hides(entry.key, entry.value, reader, state)) continue;
        (answer[kind] as List).add(_envelope(entry.key, entry.value));
      }
      return _measured('parts', answer);
    }
    if (segments.length == 4 && route == 'changes') {
      reads.add(path);
      final held = uri.queryParameters['derivedEtag'];
      if (held != null && !stampsDerived) {
        throw const SuperTabFailure(
          'VALIDATION_ERROR',
          'Unrecognized key(s) in object: \'derivedEtag\'',
          statusCode: 400,
        );
      }
      final cursor = RegExp(r'^c(\d+)e(\d+)$')
          .firstMatch(uri.queryParameters['cursor'] ?? '');
      if (cursor == null || int.parse(cursor.group(2)!) != epoch) {
        return _measured('changes', {'reload': true});
      }
      final since = int.parse(cursor.group(1)!);
      final start = clock;
      _sync(state);
      final answer = <String, dynamic>{
        'format': 2,
        'reload': false,
        'cursor': _cursor(start - overlap),
        'serverTime': clock,
        'lastChangedAt': _lastChangedAt(),
        'epoch': epoch,
        'head': null,
        for (final kind in _kinds) kind: <dynamic>[],
        'derived': _derived(state, reader),
      };
      if (stampsDerived) {
        final derived = answer['derived'] as Map<String, dynamic>;
        final etag = answer['derivedEtag'] = _etag(derived);
        if (held == etag) {
          unchangedSummaries++;
          answer['derivedUnchanged'] = true;
          answer['derived'] = {
            for (final entry in derived.entries)
              if (_markFields.contains(entry.key)) entry.key: entry.value,
          };
        }
      }
      for (final entry in _ordered()) {
        if (entry.value.changedAt <= since) continue;
        if (_hides(entry.key, entry.value, reader, state)) continue;
        final kind = entry.key.substring(0, entry.key.indexOf(':'));
        if (kind == 'head') {
          answer['head'] = _envelope(entry.key, entry.value);
        } else {
          (answer[kind] as List).add(_envelope(entry.key, entry.value));
        }
      }
      return _measured('changes', answer);
    }
    if (route == 'groups') {
      _sync(state);
      reads.add(path);
      if (segments.length == 5) {
        final held = _parts['groups:${segments[4]}'];
        if (held == null ||
            held.deleted ||
            _hides('groups:${segments[4]}', held, reader, state)) {
          throw const SuperTabFailure(
            'NOT_FOUND',
            'Conversation not found.',
            statusCode: 404,
          );
        }
        return {'group': _dormantEnvelope('groups:${segments[4]}', held)};
      }
      final projectId = uri.queryParameters['projectId'];
      final before = uri.queryParameters['before'];
      final groups = [
        for (final entry in _ordered().reversed)
          if (entry.key.startsWith('groups:') &&
              !entry.value.deleted &&
              dormant(entry.value.data) &&
              !_hides(entry.key, entry.value, reader, state) &&
              (projectId == null ||
                  (entry.value.data['projectId'] ?? 'lead') == projectId))
            entry,
      ];
      final from = before == null
          ? 0
          : groups.indexWhere((e) => e.key == 'groups:$before') + 1;
      final page = groups.skip(from).take(dormantPage).toList();
      return {
        'groups': [for (final e in page) _dormantEnvelope(e.key, e.value)],
        'next': from + page.length < groups.length
            ? page.last.key.substring('groups:'.length)
            : null,
      };
    }
    return null;
  }

  /// Groups per page of the dormant list.
  int dormantPage = 50;

  Map<String, dynamic> _dormantEnvelope(String id, _HeldPart part) => {
    'key': id.substring(id.indexOf(':') + 1),
    'version': part.version,
    'changedAt': part.changedAt,
    'data': {...part.data, if (dormant(part.data)) 'dormant': true},
  };

  Map<String, dynamic> _measured(String kind, Map<String, dynamic> answer) {
    final copy = jsonDecode(jsonEncode(answer)) as Map<String, dynamic>;
    (bytes[kind] ??= []).add(utf8.encode(jsonEncode(copy)).length);
    return copy;
  }

  int _lastChangedAt() => _parts.values.fold(0, (t, p) => max(t, p.changedAt));

  /// What a command reply says it wrote: the parts that changed since [tick].
  List<Map<String, dynamic>> writtenSince(
    int tick,
    Map<String, dynamic> state,
  ) {
    _sync(state);
    return [
      for (final entry in _ordered())
        if (entry.value.changedAt > tick)
          {
            'kind': switch (entry.key.substring(0, entry.key.indexOf(':'))) {
              'members' => 'member',
              'agents' => 'agent',
              'groups' => 'group',
              'machines' => 'machine',
              'starts' => 'start',
              final kind => kind,
            },
            'key': entry.key.substring(entry.key.indexOf(':') + 1),
            'version': entry.value.version,
          },
    ];
  }

  static const _kinds = [
    'members',
    'agents',
    'groups',
    'machines',
    'starts',
    'progress',
  ];
}

class _HeldPart {
  _HeldPart({
    required this.version,
    required this.changedAt,
    required this.json,
    required this.ordinal,
    this.deleted = false,
  });
  final int version, changedAt, ordinal;
  final String json;
  final bool deleted;
  Map<String, dynamic> get data => jsonDecode(json) as Map<String, dynamic>;
}

/// What the backend answers an old whole-Swarm read with (section 4.11).
const superTabUpdateRequired = SuperTabFailure(
  'UPDATE_REQUIRED',
  'Update Harness to keep using this Swarm.',
  statusCode: 426,
);

/// The backend's `stableId(...parts)`: the first 24 hex of
/// sha256(JSON.stringify(parts)) (backend/src/superTabs/model.ts).
String _backendId(List<String> parts) => const DartSha256()
    .hashSync(utf8.encode(jsonEncode(parts)))
    .bytes
    .map((b) => b.toRadixString(16).padLeft(2, '0'))
    .join()
    .substring(0, 24);

class ConversationServer {
  int revision = 0;

  /// The Swarm reads this server answers, worked out from [state].
  final parts = SwarmPartsBackend();

  /// Messages per page, as the backend pages them.
  int messagePage = 100;

  /// Where the ask at each thread's root stands, by root: what the backend's
  /// summaries say (threads.ts).
  final threadAsks = <String, String>{};

  /// Whether messages are written with threads, as backends from threads on
  /// write them (backend threads.ts).
  bool threads = false;

  /// Told of every messages read, by path.
  void Function(String path)? onRead;
  bool loseReply = false, reject = false, failSave = false, failReads = false;

  /// Fails, as if offline, each read whose path holds this.
  String? failReadsOf;

  /// Names a person's message as the backend does: a hash of the Swarm, the
  /// sender and the send's receipt id (backend model.ts `stableId`, used by
  /// `message.send` in commands.ts), not `message-N`.
  bool hashedIds = false;

  /// Conversations whose single-message reads (`?messageId=`) the backend
  /// refuses, as it does for one the reader may not read.
  final forbidMessageReads = <String>{};

  /// How many of the next single-message reads fail as if offline.
  int failMessageReads = 0;
  Map<String, dynamic>? saved;
  // While set, every read waits for it: a slow server.
  Completer<void>? holdReads;
  // While set, a thread's older pages (`thread` and `before`) wait for it, and
  // nothing else does: a slow older read while the page reloads.
  Completer<void>? holdThreadPages;
  // Makes every command answer with this refusal: {code, message}, with
  // [refuseStatus] as its HTTP status.
  Map<String, String>? refuse;

  /// Commands the server refuses as a backend from before them does: its
  /// strict schema answers `VALIDATION_ERROR` with a 400.
  bool Function(Map command)? unknownCommand;
  // While set, every command waits for it before it answers: a slow server.
  Completer<void>? holdCommands;

  int refuseStatus = 409;

  /// How many re-sends of an operation already answered lose their reply
  /// too, as a second dropped connection does.
  int loseResentReplies = 0;

  /// Machines whose `machine.contribute` the server refuses, with its message.
  final refuseContributions = <String, String>{};
  // Added to every successful command's result, as a newer backend adds
  // fields such as `credentialNotice`.
  final commandResult = <String, dynamic>{};
  // Each agent's screen as an `agent.screen` request reads it (backend
  // terminal.ts): absent, its host answers that it failed.
  final screens = <String, String>{};
  // `agent.screen` is refused, as mayDrive refuses a reader who may not read
  // the terminal (a Harness Team account's agent, for anyone but its owner).
  bool refuseScreens = false;
  // The screen requests sent, by request id, with their agent.
  final screenRequests = <String, String>{};
  final posts = <Map<String, dynamic>>[];

  /// Notification settings sent (backend chatSettings.ts), in order; while
  /// [failNotify], each is refused as if offline; [holdNotify] keeps each
  /// waiting.
  final notifyPosts = <Map<String, dynamic>>[];
  bool failNotify = false;
  Completer<void>? holdNotify;

  /// The Activity list answered (backend activity.ts); null answers 404, as a
  /// server before it. [activityStatus], when not 0, fails each read with it.
  Map<String, dynamic>? activity = {'items': <dynamic>[], 'more': false};
  int activityStatus = 0;
  Completer<void>? holdActivity;
  final activityReads = <String>[];
  final activityReadPosts = <Map<String, dynamic>>[];

  /// Refuses the next lead.start with this code and message, as the backend
  /// refuses a machine that cannot take the Product Manager (leadStart.ts).
  Map<String, String>? leadRefusal;
  final receipts = <String, Map<String, dynamic>>{};

  /// As the backend (store.ts): a request id used again for another command is
  /// refused with OPERATION_REUSED instead of answered from its receipt. Off by
  /// default, as most tests resend one request id freely.
  bool refuseReusedOperations = false;
  final receiptCommands = <String, String>{};
  final messages = <Map<String, dynamic>>[];
  // Route decisions by id, answered by GET .../route-decisions/:id.
  final routeDecisions = <String, Map<String, dynamic>>{};

  /// The leaderboard read's answer; reads of it are listed in [leaderboardReads].
  Map<String, dynamic>? leaderboard;

  /// A Member's own chat that agent.new opens is left out of a Swarm's first load, as a big Swarm's read can leave out
  /// a quiet chat (hotfix #4647): only a read of the chat itself finds it.
  bool newAgentChatsDormant = false;

  /// A read of a chat's messages the Swarm no longer has answers 404; off, the older tests' reads of chats they never
  /// listed keep their empty pages.
  bool chatsGoneAreNotFound = false;
  final leaderboardReads = <String>[];

  /// Answers by the read's path instead of [leaderboard], as a server does.
  Map<String, dynamic> Function(String path)? leaderboardAnswer;

  /// Holds the next reads' answers until it completes.
  Future<void>? leaderboardGate;

  /// How many leaderboard reads fail as a server that is down does, before
  /// they answer again.
  var failLeaderboardReads = 0;
  // The reader's tags, newest last, answered by GET .../mentions?state=.
  final mentions = <Map<String, dynamic>>[];

  /// The followed-threads read's answer (backend read/followedThreads.ts):
  /// `{unread, read, more}`; null answers 404, as a server before it does,
  /// and the inbox ([inbox]) is read instead.
  Map<String, dynamic>? followedThreads;

  /// Refuses the followed-threads read's `read` query, as a backend before
  /// task #2835 does.
  bool refuseThreadsRead = false;

  /// The inbox read's answer (backend read/inbox.ts): `{threads, latest,
  /// more}`; null answers 404.
  Map<String, dynamic>? inbox;

  /// Every followed-threads and inbox read, by path.
  final threadListReads = <String>[];

  /// While set, followed-threads reads wait for it: an answer that arrives
  /// late.
  Completer<void>? holdThreadLists;

  /// Followed-threads reads fail as offline, or with [threadListStatus].
  bool failThreadLists = false;
  int threadListStatus = 503;

  /// The Follow and Unfollow writes, in order: {conversationId, root, follow}.
  final followPosts = <Map<String, dynamic>>[];
  bool failFollows = false;
  // Decisions asked of the reader, newest last, answered by GET .../decisions?state=.
  final decisions = <Map<String, dynamic>>[];
  // How many times a decisions list was read (open and answered each count).
  int decisionReads = 0;
  // While set, every read of a decisions list waits for it.
  Completer<void>? holdDecisions;
  // Every read of a decisions list fails, as offline.
  bool failDecisions = false;
  // The most each decisions list returns, newest first, as the backend caps
  // it; set, a list also says whether it left others out, as the backend does.
  int? decisionPage;
  // A backend from before Let <coordinator> decide: no list of every answered one.
  bool settledMissing = false;
  // A backend from before the decisions digest: it sends the count alone.
  bool decisionsDigestMissing = false;
  // How many times the mentions list was read.
  int mentionReads = 0;
  // A backend from before tags: it has no list route.
  bool mentionsMissing = false;
  // While set, every read of the mentions list waits for it.
  Completer<void>? holdMentions;
  // Every read of the mentions list fails, as offline.
  bool failMentions = false;
  // The effective routing policy answered by GET .../routing-policy.
  Map<String, dynamic>? routingPolicy;

  /// Each project's instructions as GET .../projects/:id/instructions answers them (backend store.ts
  /// `instructions`), by project id; a project missing here reads as unavailable.
  final instructions = <String, Map<String, dynamic>>{};

  /// Each project's kept revisions, newest first, each with its `text`: the history read leaves the text out, the
  /// read of one revision has it.
  final instructionRevisions = <String, List<Map<String, dynamic>>>{};

  /// False answers the instructions reads as a backend from before them: a 404 without the backend's own code.
  bool instructionsRoute = true;

  /// Every instructions read, by path.
  final instructionReads = <String>[];

  /// Each project's rules record as GET .../projects/:id/rules answers it (backend store.ts `projectRules`), by
  /// project id; a project missing here reads as unavailable. False [rulesRoute] answers as a backend from before it.
  final projectRules = <String, Map<String, dynamic>>{};
  bool rulesRoute = true;
  final rulesReads = <String>[];
  final state = <String, dynamic>{
    'version': 1,
    'id': 'tab',
    'name': 'Pilot',
    'ownerId': 'owner',
    'paused': false,
    'people': <dynamic>[
      {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
    ],
    'agents': <dynamic>[],
    'invitations': <dynamic>[],
    'conversations': [
      conversationFixture('lead', 'Lead'),
      conversationFixture('offline', 'Offline editing'),
    ],
  };
  // The files fully uploaded, in order, bytes included.
  final uploads = <Map<String, dynamic>>[];
  // Makes the upload of the file with this name fail with failUploadCode.
  String? failUpload;
  String failUploadCode = 'ATTACHMENT_TOO_LARGE';
  Future<void> save(Map<String, dynamic> value) async {
    if (failSave) throw StateError('Disk full');
    saved = jsonDecode(jsonEncode(value)) as Map<String, dynamic>;
  }

  void append(
    String text, {
    String conversationId = 'lead',
    List<Map<String, dynamic>> attachments = const [],
    // An agent's message: it moves no lastPersonSequence (backend parts/commit.ts, #2427).
    bool agent = false,
  }) {
    revision++;
    messages.add({
      'id': 'message-$revision',
      'conversationId': conversationId,
      'sequence': revision,
      // A top-level message is its own thread's root, as the backend writes
      // it; without [threads], a message from before threads.
      if (threads) 'thread': 'message-$revision',
      'text': text,
      'attachments': attachments,
      'createdAt': '2026-10-18T00:00:00Z',
      'author': agent
          ? {'kind': 'agent', 'id': 'lead', 'name': 'Lead'}
          : {'kind': 'person', 'id': 'owner', 'name': '[email protected]'},
      'deliveries': <dynamic>[],
    });
    final group = (state['conversations'] as List)
        .cast<Map<String, dynamic>>()
        .firstWhere((g) => g['id'] == conversationId);
    group['lastMessageSequence'] = revision;
    if (!agent) group['lastPersonSequence'] = revision;
  }

  /// Each project's unanswered Buddy proposals, as the backend's proposals
  /// read answers them (task #2569), by project id; [proposalReads] records
  /// each read's path. With [proposalsUnsupported], it answers 404 as a
  /// backend from before the read does.
  final proposals = <String, List<Map<String, dynamic>>>{};
  final proposalReads = <String>[];
  bool proposalsUnsupported = false;

  /// The read marks this device sent, in order: {conversationId, sequence}.
  final readMarkPosts = <Map<String, dynamic>>[];

  /// Every fresh file-link read (backend fileLinks.ts), by path. [fileLink]
  /// answers one, by attachment id: an attachment row, or a throw; unset, it
  /// answers as a server that no longer shows the reader that message.
  final fileLinkReads = <String>[];
  FutureOr<Map<String, dynamic>> Function(String attachmentId)? fileLink;

  /// Every read-mark write fails, as offline.
  bool failReadMarks = false;

  /// A read mark [reader] made on another device, as the backend keeps it.
  void markReadElsewhere(
    String conversationId,
    int sequence, {
    String reader = 'owner',
  }) => _keepReadMark(conversationId, sequence, reader);

  int _keepReadMark(String conversationId, int sequence, String reader) {
    final marks =
        ((state['readMarks'] ??= <String, dynamic>{}) as Map).putIfAbsent(
          reader,
          () => <String, dynamic>{},
        ) as Map;
    final held = marks[conversationId] as int? ?? 0;
    // A mark moved forward is no longer one Mark unread left.
    if (sequence > held) _unreadMarksOf(reader).remove(conversationId);
    return marks[conversationId] = max(held, sequence);
  }

  Map _unreadMarksOf(String reader) =>
      ((state['unreadMarks'] ??= <String, dynamic>{}) as Map).putIfAbsent(
        reader,
        () => <String, dynamic>{},
      ) as Map;

  /// The reader's reminders (backend reminders.ts), as its list answers each;
  /// its read lists those due by `clock.now()` and the next time after.
  final reminders = <Map<String, dynamic>>[];

  /// Whether the server has reminders: without, each route answers 404.
  bool remindersServed = true;
  final reminderReads = <String>[];

  /// Every reminder set or cleared, in order: {method, conversationId,
  /// messageId, at}.
  final reminderWrites = <Map<String, dynamic>>[];
  int _reminderTurn = 0;

  /// [message] as a reminder due [at] lists it.
  Map<String, dynamic> remindOf(Map<String, dynamic> message, DateTime at) {
    final group = (state['conversations'] as List)
        .cast<Map<String, dynamic>>()
        .firstWhere((g) => g['id'] == message['conversationId']);
    final thread = message['thread'] as String?;
    return {
      'id': 'reminder-${message['id']}',
      'conversationId': message['conversationId'],
      'conversationTitle': group['title'],
      'projectName': 'Harness',
      'messageId': message['id'],
      'messageSequence': message['sequence'],
      'threadId': thread != null && thread != message['id'] ? thread : null,
      'author': message['author'],
      'text': message['text'],
      'dueAt': at.toUtc().toIso8601String(),
    };
  }

  /// A reminder of [messageId] the reader set on another device, due [at].
  void remindElsewhere(String messageId, DateTime at) {
    reminders.add(
      remindOf(messages.firstWhere((m) => m['id'] == messageId), at),
    );
    state['remindersDigest'] = 'r${++_reminderTurn}';
  }

  /// The Mark unread writes this device sent, in order: {conversationId,
  /// sequence} with the message's own sequence.
  final unreadPosts = <Map<String, dynamic>>[];

  /// Every Mark unread write fails, as offline.
  bool failUnread = false;

  /// [reader] marked [conversationId] unread from message [sequence] on
  /// another device, as the backend keeps it.
  void markUnreadElsewhere(
    String conversationId,
    int sequence, {
    String reader = 'owner',
  }) => _lowerReadMark(conversationId, sequence, reader);

  /// The backend's Mark unread (readMarks.ts lowerReadMark): the mark goes to
  /// just before the message, never forward.
  int _lowerReadMark(String conversationId, int sequence, String reader) {
    final marks =
        ((state['readMarks'] ??= <String, dynamic>{}) as Map).putIfAbsent(
          reader,
          () => <String, dynamic>{},
        ) as Map;
    final held = marks[conversationId] as int?;
    final target = sequence - 1;
    if (held != null && held <= target) return held;
    marks[conversationId] = target;
    _unreadMarksOf(reader)[conversationId] = target;
    return target;
  }

  /// The thread marks this device sent, in order: {conversationId, root,
  /// sequence}.
  final threadMarkPosts = <Map<String, dynamic>>[];

  /// Every thread-mark write fails: as offline, or with [oldServer] as a
  /// backend without thread marks answers (no such route).
  bool failThreadMarks = false;
  bool oldServer = false;

  /// While set, thread-mark writes wait for it: an answer that arrives late.
  Completer<void>? holdThreadMarks;

  /// A thread mark [reader] made on another device, as the backend keeps it.
  void markThreadReadElsewhere(
    String conversationId,
    String root,
    int sequence, {
    String reader = 'owner',
  }) => _keepThreadMark(conversationId, root, sequence, reader);

  int _keepThreadMark(
    String conversationId,
    String root,
    int sequence,
    String reader,
  ) {
    final marks =
        (((state['threadMarks'] ??= <String, dynamic>{}) as Map).putIfAbsent(
          reader,
          () => <String, dynamic>{},
        ) as Map).putIfAbsent(conversationId, () => <String, dynamic>{}) as Map;
    final kept = max(marks[root] as int? ?? 0, sequence);
    return marks[root] = kept;
  }

  Future<Map<String, dynamic>> _markThreadRead(
    String conversationId,
    String root,
    int sequence,
    String? reader,
  ) async {
    threadMarkPosts.add({
      'conversationId': conversationId,
      'root': root,
      'sequence': sequence,
    });
    if (holdThreadMarks case final hold?) await hold.future;
    if (oldServer) {
      throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
    }
    if (failThreadMarks) {
      throw const SuperTabFailure('OFFLINE', 'No connection.', statusCode: 503);
    }
    final newest =
        (state['conversations'] as List)
                .cast<Map<String, dynamic>>()
                .firstWhere(
                  (g) => g['id'] == conversationId,
                )['lastMessageSequence']
            as int? ??
        0;
    return {
      'sequence': _keepThreadMark(
        conversationId,
        root,
        min(sequence, newest),
        reader ?? 'owner',
      ),
    };
  }

  /// The backend's read-mark route (readMarks.ts): forward only, never past
  /// the conversation's newest message.
  Map<String, dynamic> _markRead(
    String conversationId,
    int sequence,
    String? reader,
  ) {
    readMarkPosts.add({'conversationId': conversationId, 'sequence': sequence});
    if (failReadMarks) {
      throw const SuperTabFailure('OFFLINE', 'No connection.', statusCode: 503);
    }
    final newest =
        (state['conversations'] as List)
                .cast<Map<String, dynamic>>()
                .firstWhere(
                  (g) => g['id'] == conversationId,
                )['lastMessageSequence']
            as int? ??
        0;
    return {
      'sequence': _keepReadMark(
        conversationId,
        min(sequence, newest),
        reader ?? 'owner',
      ),
    };
  }

  /// The summaries of the threads [page]'s rows are in, as the backend's
  /// pages carry them (threads.ts).
  List<Map<String, dynamic>> _threads(
    String conversationId,
    List<Map<String, dynamic>> page,
  ) => [
    for (final root in {
      for (final m in page)
        if (m['thread'] case final String root) root,
    })
      if (messages
              .where(
                (m) =>
                    m['conversationId'] == conversationId &&
                    m['thread'] == root,
              )
              .toList()
          case final thread when thread.length > 1)
        {
          'id': root,
          'ask': ?threadAsks[root],
          'replies': thread.length - 1,
          'lastSequence': thread.last['sequence'],
          'lastAt': thread.last['createdAt'],
          'authors': [
            ...{
              for (final m in thread.skip(1).toList().reversed)
                '${(m['author'] as Map)['kind']}:${(m['author'] as Map)['id']}':
                    m['author'],
            }.values,
          ].take(3).toList(),
          'people': [
            ...{
              for (final m in thread) ...[
                if ((m['author'] as Map)['kind'] == 'person')
                  (m['author'] as Map)['id'],
                ...(m['mentions'] as List? ?? const []),
              ],
            },
          ],
        },
  ];

  // Avatar pictures uploaded, as the backend's avatar route keeps them.
  final avatarUploads = <Uint8List>[];

  /// What the backend's avatar route does with a picture.
  Future<Map<String, dynamic>> uploadAvatar({
    required String tabId,
    required Uint8List png,
  }) async {
    avatarUploads.add(png);
    final id = 'avatar-${avatarUploads.length}';
    return {
      'avatar': {'id': id},
    };
  }

  /// A person's own status, username or avatar, or an agent's avatar, as the
  /// backend stores it (profile.ts, usernames.ts).
  void _profile(Map command, String reader) {
    final (key, id) = command['type'] == 'agent.avatar'
        ? ('agents', command['agentId'])
        : ('people', reader);
    // An upload's record says only that there is one; its link comes signed with each read (backend avatarLinks.ts).
    Map<String, dynamic> avatar(Map choice) {
      if (choice['kind'] != 'upload') return Map<String, dynamic>.from(choice);
      final links = state['avatars'] ??= <String, dynamic>{};
      (links as Map)['${key == 'agents' ? 'agent' : 'person'}:$id'] =
          superTabSignedAvatar(choice['id'] as String);
      return {'kind': 'upload'};
    }

    state[key] = <dynamic>[
      for (final row in state[key] as List)
        if ((row as Map)['id'] != id)
          row
        else
          <String, dynamic>{
            ...row,
            if (command['type'] == 'member.status')
              'status': command['status']
            else if (command['type'] == 'member.timeZone')
              'timeZone': command['timeZone']
            else if (command['type'] == 'member.username')
              'username': (command['username'] as String?)?.toLowerCase()
            else if (command['type'] == 'member.name')
              'name': (command['name'] as String?)?.replaceAll(
                RegExp(r'\s+'),
                ' ',
              )
            else
              'avatar': command['avatar'] == null
                  ? null
                  : avatar(command['avatar'] as Map),
          },
    ];
    revision++;
  }

  /// A reaction as the backend keeps it (reactions.ts): one per reactor and
  /// emoji, and the group bumped only on a change.
  bool _react(Map command, String reader) {
    final message = messages.firstWhere((m) => m['id'] == command['messageId']);
    final counts = [
      for (final row in message['reactions'] as List? ?? const [])
        Map<String, dynamic>.from(row as Map),
    ];
    final row = counts.where((r) => r['emoji'] == command['emoji']).firstOrNull;
    final by = [...(row?['by'] as List? ?? const [])];
    final mine = by.any((who) => (who as Map)['id'] == reader);
    if (mine == command['on']) return false;
    if (command['on'] == true) {
      by.add({'kind': 'person', 'id': reader});
    } else {
      by.removeWhere((who) => (who as Map)['id'] == reader);
    }
    counts.removeWhere((r) => r['emoji'] == command['emoji']);
    if (by.isNotEmpty) {
      counts.add({'emoji': command['emoji'], 'count': by.length, 'by': by});
    }
    message['reactions'] = counts;
    final group = (state['conversations'] as List)
        .cast<Map<String, dynamic>>()
        .firstWhere((g) => g['id'] == command['conversationId']);
    group['reactionSeq'] = ((group['reactionSeq'] as int?) ?? 0) + 1;
    revision++;
    return true;
  }

  /// An edit as the backend keeps it (messageEdits.ts): the new text, when it
  /// changed, and the group's `reactionSeq` moved. False for the same text.
  bool editMessage(String messageId, String text) {
    final message = messages.firstWhere((m) => m['id'] == messageId);
    if (message['text'] == text) return false;
    message
      ..['text'] = text
      ..['editedAt'] = '2026-10-18T00:05:00Z';
    _messageChanged(message['conversationId'] as String);
    return true;
  }

  /// A delete as the backend keeps it (messageEdits.ts): a message with
  /// replies stays as its tombstone, any other goes from every page. Whether
  /// it was kept.
  bool deleteMessage(String messageId) {
    final message = messages.firstWhere((m) => m['id'] == messageId);
    final kept = messages.any(
      (m) => m['thread'] == messageId && m['id'] != messageId,
    );
    if (kept) {
      message
        ..['text'] = 'This message was deleted.'
        ..['deletedAt'] = '2026-10-18T00:06:00Z'
        ..['attachments'] = <dynamic>[]
        ..['mentions'] = <dynamic>[]
        ..['reactions'] = <dynamic>[];
    } else {
      messages.remove(message);
    }
    _messageChanged(message['conversationId'] as String);
    return kept;
  }

  void _messageChanged(String conversationId) {
    final group = (state['conversations'] as List)
        .cast<Map<String, dynamic>>()
        .firstWhere((g) => g['id'] == conversationId);
    group['reactionSeq'] = ((group['reactionSeq'] as int?) ?? 0) + 1;
    revision++;
  }

  /// What the backend does with a file sent to its upload route.
  Future<Map<String, dynamic>> upload({
    required String tabId,
    required String conversationId,
    required String name,
    required String mime,
    required HarnessAttachment file,
    required CancelToken cancel,
    required void Function(double sent) onProgress,
  }) async {
    if (name == failUpload) {
      throw SuperTabFailure(
        failUploadCode,
        'The file is too large.',
        statusCode: 413,
      );
    }
    onProgress(.5);
    final id = 'attachment-${uploads.length + 1}';
    uploads.add({
      'conversationId': conversationId,
      'name': name,
      'mime': mime,
      'file': await file.readBytes(),
      'id': id,
    });
    onProgress(1);
    return {'attachment': _attachment(id)};
  }

  Map<String, dynamic> _attachment(String id) {
    final upload = uploads.firstWhere((u) => u['id'] == id);
    return {
      'id': id,
      'name': upload['name'],
      'mime': upload['mime'],
      'size': (upload['file'] as List).length,
      'url': 'https://cdn.harness.autonomous.ai/$id/${upload['name']}',
    };
  }

  /// Answers [path] as the backend answers the account of the [controller]
  /// asking ([_reader]); with none, as it answers someone who reads every
  /// conversation.
  Future<Map<String, dynamic>> request(
    String method,
    String path, {
    Map<String, dynamic>? body,
  }) async {
    final reader = Zone.current[_reader] as String?;
    final read = method == 'POST'
        ? RegExp(r'/conversations/([^/]+)/read$').firstMatch(path)
        : null;
    if (read != null) {
      return _markRead(read.group(1)!, body!['sequence'] as int, reader);
    }
    final reminder = RegExp(
      r'/conversations/([^/]+)/messages/([^/]+)/reminder$',
    ).firstMatch(path);
    // A POST, as the daemon forwards only GET and POST: a time sets it, none
    // clears it.
    if (reminder != null && method == 'POST') {
      final conversationId = Uri.decodeComponent(reminder.group(1)!);
      final messageId = Uri.decodeComponent(reminder.group(2)!);
      final clears = body?['at'] == null;
      reminderWrites.add({
        'method': clears ? 'clear' : 'set',
        'conversationId': conversationId,
        'messageId': messageId,
        if (body?['at'] case final at?) 'at': at,
      });
      if (!remindersServed) {
        throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
      }
      final id = 'reminder-$messageId';
      final held = reminders.indexWhere((r) => r['id'] == id);
      if (clears) {
        if (held >= 0) reminders.removeAt(held);
        state['remindersDigest'] = 'r${++_reminderTurn}';
        return {'cleared': held >= 0};
      }
      final message = messages.firstWhere((m) => m['id'] == messageId);
      final row = remindOf(message, DateTime.parse(body!['at'] as String));
      if (held >= 0) {
        reminders[held] = row;
      } else {
        reminders.add(row);
      }
      state['remindersDigest'] = 'r${++_reminderTurn}';
      return {'id': id, 'dueAt': row['dueAt']};
    }
    final unread = method == 'POST'
        ? RegExp(r'/conversations/([^/]+)/unread$').firstMatch(path)
        : null;
    if (unread != null) {
      final id = Uri.decodeComponent(unread.group(1)!);
      final sequence = body!['sequence'] as int;
      unreadPosts.add({'conversationId': id, 'sequence': sequence});
      if (failUnread) {
        throw const SuperTabFailure(
          'OFFLINE',
          'No connection.',
          statusCode: 503,
        );
      }
      return {'sequence': _lowerReadMark(id, sequence, reader ?? 'owner')};
    }
    final threadRead = method == 'POST'
        ? RegExp(r'/conversations/([^/]+)/threads/([^/]+)/read$')
              .firstMatch(path)
        : null;
    final follow = method == 'POST'
        ? RegExp(r'/conversations/([^/]+)/threads/([^/]+)/follow$')
              .firstMatch(path)
        : null;
    final notify = method == 'POST'
        ? RegExp(r'/conversations/([^/]+)/notifications$').firstMatch(path)
        : null;
    if (notify != null) {
      final id = Uri.decodeComponent(notify.group(1)!);
      notifyPosts.add({'conversationId': id, 'notify': body!['notify']});
      if (holdNotify case final hold?) await hold.future;
      if (failNotify) {
        throw const SuperTabFailure(
          'OFFLINE',
          'No connection.',
          statusCode: 503,
        );
      }
      final settings = (state['chatSettings'] ??= <String, dynamic>{}) as Map;
      ((settings[reader ?? 'owner'] ??= <String, dynamic>{}) as Map)[id] =
          body['notify'];
      return {'notify': body['notify']};
    }
    if (method == 'POST' && path.endsWith('/activity/read')) {
      activityReadPosts.add(Map<String, dynamic>.from(body!));
      return {'marked': 1};
    }
    if (follow != null) {
      followPosts.add({
        'conversationId': Uri.decodeComponent(follow.group(1)!),
        'root': Uri.decodeComponent(follow.group(2)!),
        'follow': body!['follow'],
      });
      if (failFollows) {
        throw const SuperTabFailure(
          'OFFLINE',
          'No connection.',
          statusCode: 503,
        );
      }
      return {'follow': body['follow']};
    }
    if (threadRead != null) {
      return _markThreadRead(
        Uri.decodeComponent(threadRead.group(1)!),
        Uri.decodeComponent(threadRead.group(2)!),
        body!['sequence'] as int,
        reader,
      );
    }
    if (method == 'POST') {
      posts.add(Map<String, dynamic>.from(body!));
      if (holdCommands case final hold?) await hold.future;
      if (reject) {
        throw const SuperTabFailure(
          'INVALID_RECIPIENT',
          'Choose an agent in this conversation.',
          statusCode: 400,
        );
      }
      if (unknownCommand?.call(body['command'] as Map? ?? const {}) ?? false) {
        throw const SuperTabFailure(
          'VALIDATION_ERROR',
          'Invalid request.',
          statusCode: 400,
        );
      }
      if (refuse case final refusal?) {
        throw SuperTabFailure(
          refusal['code']!,
          refusal['message']!,
          statusCode: refuseStatus,
        );
      }
      if (body['command']
          case {'type': 'machine.contribute', 'machineId': final String id}
          when refuseContributions.containsKey(id)) {
        throw SuperTabFailure(
          'MACHINE_NOT_FOUND',
          refuseContributions[id]!,
          statusCode: refuseStatus,
        );
      }
      final operationId = body['operationId'] as String;
      final earlier = refuseReusedOperations
          ? receiptCommands[operationId]
          : null;
      if (earlier != null && earlier != jsonEncode(body['command'])) {
        throw const SuperTabFailure(
          'OPERATION_REUSED',
          'Use a new operation ID for a different request.',
          statusCode: 400,
        );
      }
      if (receipts[operationId] case final receipt?) {
        if (loseResentReplies > 0) {
          loseResentReplies--;
          throw StateError('Connection lost again');
        }
        return receipt;
      }
      final tick = parts.clock;
      final command = body['command'] as Map;
      final output = <String, dynamic>{};
      if (command['type'] == 'message.send') {
        append(
          command['text'] as String,
          conversationId: command['conversationId'] as String,
          attachments: [
            for (final id in command['attachmentIds'] as List? ?? const [])
              _attachment(id as String),
          ],
        );
        messages.last['replyTo'] = command['replyTo'];
        // The people it tags, as the backend keeps them (commands.ts).
        if (command['mentions'] case final List tagged) {
          messages.last['mentions'] = [...tagged];
        }
        // A reply joins its message's thread at the root; one to a message
        // written before threads stays inline (backend commands.ts).
        final target = messages
            .where((m) => m['id'] == command['replyTo'])
            .firstOrNull;
        if (target?['thread'] case final String root) {
          messages.last['thread'] = root;
          if (command['alsoSend'] == true) messages.last['alsoInChat'] = true;
        }
        if (hashedIds) {
          final id = _backendId([
            state['id'] as String,
            'person:${reader ?? 'owner'}',
            operationId,
          ]);
          if (messages.last['thread'] == messages.last['id']) {
            messages.last['thread'] = id;
          }
          messages.last['id'] = id;
        }
        output['messageId'] = messages.last['id'];
        // New session starts the thread's own session (backend commands.ts
        // routeBuddySession): a top-level message roots its own thread.
        if (command['newSession'] == true) {
          final sent = messages.last;
          final thread = (sent['thread'] ?? sent['id']) as String;
          sent['buddySession'] = true;
          final chat = (state['conversations'] as List).cast<Map>().firstWhere(
            (c) => c['id'] == command['conversationId'],
          );
          chat['buddySessions'] = [
            ...(chat['buddySessions'] as List? ?? const []),
            {'thread': thread, 'startId': operationId, 'at': 1},
          ];
          output['startId'] = operationId;
        }
      } else if (command['type'] == 'member.status' ||
          command['type'] == 'member.timeZone' ||
          command['type'] == 'member.username' ||
          command['type'] == 'member.name' ||
          command['type'] == 'member.avatar' ||
          command['type'] == 'agent.avatar') {
        _profile(command, reader ?? 'owner');
      } else if (command['type'] == 'message.react') {
        output['changed'] = _react(command, reader ?? 'owner');
      } else if (command['type'] == 'message.edit') {
        output['changed'] = editMessage(
          command['messageId'] as String,
          command['text'] as String,
        );
      } else if (command['type'] == 'message.delete') {
        output['changed'] = true;
        output['kept'] = deleteMessage(command['messageId'] as String);
      } else if (command['type'] == 'agent.screen') {
        if (refuseScreens) {
          throw const SuperTabFailure(
            'TERMINAL_PRIVATE',
            'Only its project\'s owner reads its screen.',
            statusCode: 403,
          );
        }
        screenRequests[operationId] = command['agentId'] as String;
        output['requestId'] = operationId;
      } else if (command['type'] == 'decision.answer') {
        final id = command['decisionId'] as String;
        if (command['delegate'] == true) {
          // Left to the PM: the backend takes the recommended option.
          final asked = decisions.firstWhere((d) => d['id'] == id);
          answerDecision(id, asked['recommended'] as int, delegated: true);
        } else if (command['choice'] case final int choice) {
          answerDecision(id, choice);
        } else {
          // A typed answer: its words, with no option (decisions.ts).
          answerDecision(id, null, note: command['note'] as String);
        }
      } else if (command['type'] == 'mention.done') {
        mentions.firstWhere((m) => m['id'] == command['mentionId'])
          ..['resolvedAt'] = '2026-10-24T06:00:00Z'
          ..['resolvedBy'] = 'done';
        state['mentionsWaiting'] = (state['mentionsWaiting'] as int) - 1;
        revision++;
      } else if (command['type'] == 'machine.contribute') {
        // As the backend: the reader's machine is in the Swarm, whole.
        state['machines'] = <dynamic>[
          ...state['machines'] as List? ?? const [],
          {
            'machineId': command['machineId'],
            'name': command['name'],
            'contributorId': reader ?? 'owner',
            'scope': command['scope'],
            'engines': command['engines'],
            'maxAgents': command['maxAgents'],
            'availableSlots': command['maxAgents'],
          },
        ];
        revision++;
      } else if (command['type'] == 'buddy.create' &&
          command['name'] is String &&
          command['conversationId'] == null) {
        // As #3818 makes one of several: a new Buddy in a chat of its own, up to the Swarm's cap.
        final person = reader ?? 'owner';
        final conversations = (state['conversations'] as List)
            .cast<Map<String, dynamic>>();
        final count = conversations
            .where(
              (g) => g['kind'] == 'swarm-buddy' && g['buddyOwnerId'] == person,
            )
            .length;
        if (count >= (state['buddyCap'] as int? ?? 5)) {
          throw SuperTabFailure(
            'BUDDY_CAP',
            'You have $count Buddies, the most this Swarm allows. Remove one '
                'to add another.',
            statusCode: 409,
          );
        }
        revision++;
        final chatId = 'swarm-buddy-$person-$revision';
        conversations.add({
          ...conversationFixture(chatId, command['name'] as String),
          'kind': 'swarm-buddy',
          'projectId': null,
          'buddyOwnerId': person,
          'buddyName': command['name'],
          'agentIds': <String>[],
        });
        output
          ..['startId'] = 'start-$revision'
          ..['conversationId'] = chatId;
      } else if (command['type'] == 'buddy.default') {
        final person = reader ?? 'owner';
        for (final g
            in (state['conversations'] as List).cast<Map<String, dynamic>>()) {
          if (g['kind'] == 'swarm-buddy' && g['buddyOwnerId'] == person) {
            g['buddyDefault'] = g['id'] == command['conversationId'];
          }
        }
        revision++;
      } else if (command['type'] == 'buddy.create') {
        // As the backend's Buddy create: a start for the reader's Buddy and
        // its chat, fixed per person and project. The fixture's host starts it
        // at once.
        final person = reader ?? 'owner';
        // With no project, the reader's one Buddy for the Swarm (backend
        // buddy.create since 10-31): its chat is in no project.
        final swarm = command['projectId'] == null;
        final projectId = command['projectId'] as String? ?? '';
        bool mine(Object? a) =>
            a is Map &&
            (a['buddyOf'] as Map?)?['personId'] == person &&
            (swarm ? a['buddyScope'] == 'swarm' : a['projectId'] == projectId);
        // As the backend: one Buddy per person and project. A running one
        // refuses another; a down one is replaced.
        if ((state['agents'] as List).any(
          (a) => mine(a) && (a as Map)['downSince'] == null,
        )) {
          throw const SuperTabFailure(
            'BUDDY_EXISTS',
            'You already have a Buddy in this project.',
            statusCode: 409,
          );
        }
        revision++;
        final agentId = 'buddy-$revision';
        final chatId = swarm
            ? 'swarm-buddy-$person'
            : 'buddy-$person-$projectId';
        final machine = (state['machines'] as List? ?? const [])
            .cast<Map>()
            .where((m) => m['machineId'] == command['machineId'])
            .firstOrNull;
        final owner = (state['people'] as List? ?? const [])
            .cast<Map>()
            .where((p) => p['id'] == person)
            .firstOrNull;
        // A test's lists may be typed literals: copy into plain lists.
        state['agents'] = <dynamic>[
          for (final a in state['agents'] as List)
            if (!mine(a)) a,
        ];
        state['starts'] = <dynamic>[...state['starts'] as List? ?? const []];
        (state['starts'] as List).add({
          'id': 'start-$revision',
          'machineOwnerId': machine?['contributorId'] ?? person,
          'request': {
            'conversationId': chatId,
            if (!swarm) 'projectId': projectId,
            if (swarm) 'buddyScope': 'swarm',
            'machineId': command['machineId'],
            'engine': command['engine'],
            'buddyOf': {'personId': person, 'generation': 'fixture'},
          },
          'harnessId': 'h-$agentId',
          'error': null,
        });
        (state['agents'] as List).add({
          'id': agentId,
          'name': 'Buddy',
          if (!swarm) 'projectId': projectId,
          if (swarm) 'buddyScope': 'swarm',
          'buddyOf': {'personId': person, 'generation': 'fixture'},
          'machineId': command['machineId'],
          'harnessId': 'h-$agentId',
          'contributorId': person,
          'machineOwnerId': machine?['contributorId'] ?? person,
          'confidential': true,
          'configuration': {'engine': command['engine'], 'model': 'default'},
        });
        final conversations = (state['conversations'] as List)
            .cast<Map<String, dynamic>>();
        final chat = conversations.where((g) => g['id'] == chatId).firstOrNull;
        if (chat != null) {
          chat['agentIds'] = [agentId];
        } else {
          final name = (owner?['email'] as String? ?? person).split('@').first;
          conversations.add({
            ...conversationFixture(chatId, "$name's Buddy"),
            'kind': swarm ? 'swarm-buddy' : 'buddy',
            'projectId': swarm ? null : projectId,
            'buddyOwnerId': person,
            'agentIds': [agentId],
          });
        }
        output
          ..['startId'] = 'start-$revision'
          ..['conversationId'] = chatId;
      } else if (command['type'] == 'buddy.chat') {
        // As the backend's: the reader's own Buddy chat in the project, opened
        // before any Buddy, the same chat a Buddy added later joins.
        final person = reader ?? 'owner';
        final swarm = command['projectId'] == null;
        final projectId = command['projectId'] as String?;
        final chatId = swarm
            ? 'swarm-buddy-$person'
            : 'buddy-$person-$projectId';
        final conversations = (state['conversations'] as List)
            .cast<Map<String, dynamic>>();
        if (!conversations.any((g) => g['id'] == chatId)) {
          revision++;
          final owner = (state['people'] as List? ?? const [])
              .cast<Map>()
              .where((p) => p['id'] == person)
              .firstOrNull;
          final name = (owner?['email'] as String? ?? person).split('@').first;
          conversations.add({
            ...conversationFixture(chatId, "$name's Buddy"),
            'kind': swarm ? 'swarm-buddy' : 'buddy',
            'projectId': projectId,
            'buddyOwnerId': person,
            'agentIds': <String>[],
          });
        }
        output['conversationId'] = chatId;
      } else if (command['type'] == 'buddy.rename') {
        // As the backend's: the reader's own Buddy chat keeps the name, or
        // takes a fresh real one when cleared (task #4568), and its Buddy
        // shows it at once.
        final person = reader ?? 'owner';
        final chat = (state['conversations'] as List)
            .cast<Map<String, dynamic>>()
            .where(
              (g) =>
                  g['id'] == command['conversationId'] &&
                  (g['kind'] == 'buddy' || g['kind'] == 'swarm-buddy') &&
                  g['buddyOwnerId'] == person,
            )
            .firstOrNull;
        if (chat == null) {
          throw const SuperTabFailure(
            'NOT_FOUND',
            'This conversation is unavailable.',
            statusCode: 404,
          );
        }
        revision++;
        final shown = command['name'] as String? ?? 'Atlas';
        chat['buddyName'] = shown;
        chat['title'] = shown;
        for (final agent in (state['agents'] as List).cast<Map>()) {
          if ((chat['agentIds'] as List).contains(agent['id'])) {
            agent['displayName'] = shown;
          }
        }
      } else if (command['type'] == 'agent.rename') {
        // As the backend's: its contributor renames it, for every reader.
        final agent = (state['agents'] as List)
            .cast<Map<String, dynamic>>()
            .where((a) => a['id'] == command['agentId'])
            .firstOrNull;
        if (agent == null || agent['contributorId'] != (reader ?? 'owner')) {
          throw const SuperTabFailure(
            'FORBIDDEN',
            'Only the person who runs this agent can rename it.',
            statusCode: 403,
          );
        }
        revision++;
        agent['displayName'] = (command['name'] as String).trim();
      } else if (command['type'] == 'buddy.remove') {
        revision++;
        final person = reader ?? 'owner';
        (state['agents'] as List).removeWhere(
          (a) =>
              a is Map &&
              (a['buddyOf'] as Map?)?['personId'] == person &&
              (command['projectId'] == null
                  ? a['buddyScope'] == 'swarm'
                  : a['projectId'] == command['projectId']),
        );
      } else if (command['type'] == 'conversation.create') {
        revision++;
        final id = 'group-$revision';
        final projectId = command['projectId'] ?? 'lead';
        // The project's Lead is in every new group, a private one included.
        final leadConversationId =
            (state['projects'] as List?)
                ?.cast<Map<String, dynamic>>()
                .where((p) => p['id'] == projectId)
                .firstOrNull?['leadConversationId'] ??
            'lead';
        final leadId = (state['conversations'] as List)
            .cast<Map<String, dynamic>>()
            .where((g) => g['id'] == leadConversationId)
            .firstOrNull?['leadId'];
        (state['conversations'] as List).add({
          ...conversationFixture(id, command['title'] as String),
          'projectId': projectId,
          'leadId': leadId,
          'agentIds': [?leadId],
          if (command['audience'] case {'personIds': final List people})
            'audience': {
              'people': [
                for (final person in people)
                  {
                    'id': person,
                    'generation':
                        (state['people'] as List?)
                            ?.cast<Map>()
                            .where((p) => p['id'] == person)
                            .firstOrNull?['generation'] ??
                        'fixture',
                  },
              ],
            },
        });
        output['conversationId'] = id;
      } else if (command['type'] == 'lead.claim') {
        // One start of a project's Lead (backend commands.ts lead.claim):
        // another machine's claim is the one; the same machine claims again.
        final project = (state['projects'] as List?)
            ?.cast<Map<String, dynamic>>()
            .where((p) => p['id'] == command['projectId'])
            .firstOrNull;
        final held = project?['leadClaim'];
        if (held is Map && held['machineId'] != command['machineId']) {
          output['leadStart'] = 'waiting';
        } else {
          project?['leadClaim'] = {'machineId': command['machineId']};
          output['leadStart'] = 'start';
        }
      } else if (command['type'] == 'lead.start') {
        if (leadRefusal case final refusal?) {
          leadRefusal = null;
          throw SuperTabFailure(
            refusal['code']!,
            refusal['message']!,
            statusCode: 409,
          );
        }
        revision++;
        final machineId = command['machineId'] as String?;
        output.addAll(
          machineId == null
              ? {'waiting': true}
              : {'startId': 'lead-start-$revision', 'machineId': machineId},
        );
        final project = (state['projects'] as List?)
            ?.cast<Map<String, dynamic>>()
            .where((p) => p['id'] == command['projectId'])
            .firstOrNull;
        project?['lead'] = {
          'status': machineId == null ? 'waiting' : 'starting',
          'machineId': ?machineId,
          'requestedAt': revision,
        };
      } else if (command['type'] == 'agent.new' && command['local'] == true) {
        // As backend agent.new with `local` (task #4196): a Member's own chat,
        // and no start; its person's Desktop starts the agent itself.
        revision++;
        final id = 'agent-chat-$revision';
        (state['conversations'] as List).add({
          ...conversationFixture(id, command['name'] as String),
          'kind': 'agent-chat',
          'audience': {
            'people': [
              {'id': 'owner', 'generation': 'g'},
            ],
          },
          if (newAgentChatsDormant) 'dormant': true,
        });
        output['conversationId'] = id;
      } else if (command['type'] == 'project.create') {
        revision++;
        final projects = state['projects'] ??= <dynamic>[
          projectFixture('lead', state['name'] as String, 'lead'),
        ];
        final id = 'project-$revision', leadId = 'lead-$revision';
        (projects as List).add({
          ...projectFixture(
            id,
            command['name'] as String,
            leadId,
            visibility: command['visibility'] as String,
          ),
          'skillMode': 'default',
        });
        (state['conversations'] as List).add({
          ...conversationFixture(leadId, 'Lead'),
          'projectId': id,
          'brief': command['brief'] ?? '',
        });
        output.addAll({'projectId': id, 'conversationId': leadId});
      } else if (command['type'] == 'work.queue') {
        // As backend taskQueue.ts places it: right after `after` among the
        // project's open tasks, by rank or else number; null for the top.
        final groups = (state['conversations'] as List)
            .cast<Map<String, dynamic>>();
        final task = groups.firstWhere(
          (g) => g['id'] == command['conversationId'],
        );
        num key(Map<String, dynamic> g) =>
            (g['queueRank'] ?? g['number'] ?? 0) as num;
        final siblings =
            groups
                .where(
                  (g) =>
                      g['projectId'] == task['projectId'] &&
                      g['archived'] != true &&
                      g['number'] != null &&
                      g['id'] != task['id'],
                )
                .toList()
              ..sort((a, b) => key(a).compareTo(key(b)));
        final after = command['after'];
        if (after == null) {
          task['queueRank'] = siblings.isEmpty ? 1 : key(siblings.first) - 1;
        } else {
          final i = siblings.indexWhere((g) => g['id'] == after);
          final next = i + 1 < siblings.length ? siblings[i + 1] : null;
          task['queueRank'] = next == null
              ? key(siblings[i]) + 1
              : (key(siblings[i]) + key(next)) / 2;
        }
        revision++;
      } else if (command['type'] == 'work.priority') {
        // As backend taskPriority.ts sets it: the task's one field.
        (state['conversations'] as List)
                .cast<Map<String, dynamic>>()
                .firstWhere(
                  (g) => g['id'] == command['conversationId'],
                )['priority'] =
            command['priority'];
        revision++;
      } else if (command['type'] == 'project.canChat') {
        // As #3819 keeps it: the people granted Can chat, on the project.
        final project = (state['projects'] as List).cast<Map>().firstWhere(
          (p) => p['id'] == command['projectId'],
        );
        final granted = {...(project['canChat'] as List? ?? const [])};
        command['granted'] == true
            ? granted.add(command['personId'])
            : granted.remove(command['personId']);
        project['canChat'] = granted.toList();
        revision++;
      } else if (command['type'] == 'proposal.create') {
        // As #3817 makes it: a card of its own, in Proposals until the PM decides. Its schema (proposalCards.ts
        // proposalFields) takes one to five non-empty pieces of evidence, as this checks.
        final evidence = command['evidence'];
        if (evidence is! List ||
            evidence.isEmpty ||
            evidence.length > 5 ||
            evidence.any((e) => e is! String || e.trim().isEmpty)) {
          throw const SuperTabFailure(
            'VALIDATION_ERROR',
            'evidence: Array must contain at least 1 element(s)',
            statusCode: 400,
          );
        }
        final id = 'proposal-${(state['conversations'] as List).length}';
        (state['conversations'] as List).add({
          ...conversationFixture(id, command['title'] as String),
          'projectId': command['projectId'],
          'agentIds': <String>[],
          'priority': command['priority'],
          'proposal': {
            'version': 1,
            'text': command['text'],
            'goal': command['goal'],
            'why': command['why'],
            'doneWhen': command['doneWhen'],
            'evidence': command['evidence'],
            'createdAt': DateTime.now().millisecondsSinceEpoch,
            'senders': [
              {'personId': Zone.current[_reader] as String? ?? 'owner'},
            ],
            'questions': <dynamic>[],
          },
        });
        output['conversationId'] = id;
        revision++;
      } else if (command['type'] == 'proposal.answer') {
        // As #3817 records it: the question's answer, by the person asked.
        final card = (state['conversations'] as List)
            .cast<Map<String, dynamic>>()
            .firstWhere((g) => g['id'] == command['conversationId']);
        final question = ((card['proposal'] as Map)['questions'] as List)
            .cast<Map>()
            .firstWhere((q) => q['id'] == command['questionId']);
        question['answer'] = {
          'text': command['text'],
          'at': DateTime.now().millisecondsSinceEpoch,
          'by': Zone.current[_reader] as String? ?? 'owner',
        };
        revision++;
      } else if (command['type'] == 'work.pause') {
        // As #3819 keeps it: the task's `paused` while paused, absent otherwise.
        final task = (state['conversations'] as List)
            .cast<Map<String, dynamic>>()
            .firstWhere((g) => g['id'] == command['conversationId']);
        if (command['paused'] == true) {
          task['paused'] = {
            'by': Zone.current[_reader] as String? ?? 'owner',
            'at': DateTime.now().millisecondsSinceEpoch,
            'reason': ?command['reason'],
          };
        } else {
          task.remove('paused');
        }
        revision++;
      } else if (command['type'] == 'conversation.archive') {
        (state['conversations'] as List)
                .cast<Map<String, dynamic>>()
                .firstWhere(
                  (g) => g['id'] == command['conversationId'],
                )['archived'] =
            command['archived'];
        revision++;
      } else if (command['type'] == 'project.delete') {
        final projectId = command['projectId'];
        final projects =
            state['projects'] ??
            [projectFixture('lead', state['name'] as String, 'lead')];
        state['projects'] = (projects as List)
            .where((p) => p['id'] != projectId)
            .toList();
        final groups = state['conversations'] as List;
        final removed = groups
            .where((g) => (g['projectId'] ?? 'lead') == projectId)
            .map((g) => g['id'])
            .toSet();
        groups.removeWhere((g) => removed.contains(g['id']));
        messages.removeWhere((m) => removed.contains(m['conversationId']));
        revision++;
      } else if ([
        'project.rename',
        'project.cadence',
        'project.sharing',
      ].contains(command['type'])) {
        final project = (state['projects'] as List?)
            ?.cast<Map<String, dynamic>>()
            .where((p) => p['id'] == command['projectId'])
            .firstOrNull;
        if (project != null) {
          if (command['type'] == 'project.rename') {
            project['name'] = command['name'];
          } else if (command['type'] == 'project.cadence') {
            project['updateMinutes'] = command['minutes'];
          } else {
            project['visibility'] = command['visibility'];
            project['members'] = [
              for (final id in command['memberIds'] as List)
                {'id': id, 'generation': 'fixture'},
            ];
          }
          revision++;
        }
      } else if (command['type'] == 'instructions.save') {
        output.addAll(_saveInstructions(command, reader ?? 'owner'));
      } else if (command['type'] == 'note.remove') {
        _requireMember(reader ?? 'owner');
        final project = _project(command['projectId'] as String);
        final document = instructions[project['id']];
        final notes = document?['notes'] as List? ?? const [];
        if (!notes.any((n) => (n as Map)['id'] == command['noteId'])) {
          throw const SuperTabFailure(
            'NOT_FOUND',
            'This note is unavailable.',
            statusCode: 404,
          );
        }
        final notesRevision = ((project['notesRevision'] as int?) ?? 0) + 1;
        project['notesRevision'] = notesRevision;
        document!
          ..['notes'] = [
            for (final note in notes)
              if ((note as Map)['id'] != command['noteId']) note,
          ]
          ..['notesRevision'] = notesRevision;
        revision++;
      }
      output.addAll(commandResult);
      final result = {
        'result': output,
        'parts': parts.writtenSince(tick, state),
        'lastChangedAt': parts.clock,
      };
      receipts[operationId] = result;
      receiptCommands[operationId] = jsonEncode(body['command']);
      if (loseReply) {
        loseReply = false;
        throw StateError('Connection lost after commit');
      }
      return result;
    }
    if (holdReads case final hold?) await hold.future;
    if (failReads) throw StateError('Offline');
    if (failReadsOf case final part? when path.contains(part)) {
      throw StateError('Offline');
    }
    final uri = Uri.parse(path);
    // A screen request's answer (backend store.ts terminalResult).
    if (uri.pathSegments.length > 2 &&
        uri.pathSegments[uri.pathSegments.length - 2] == 'terminal') {
      final id = uri.pathSegments.last;
      final agentId = screenRequests.remove(id);
      if (agentId == null) {
        throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
      }
      final text = screens[agentId];
      return text == null
          ? {'requestId': id, 'ok': false, 'error': 'Its machine is offline.'}
          : {'requestId': id, 'ok': true, 'text': text};
    }
    if (uri.pathSegments.length > 5 &&
        uri.pathSegments[3] == 'projects' &&
        uri.pathSegments[5] == 'instructions') {
      return _readInstructions(path, uri);
    }
    if (uri.pathSegments.length == 6 &&
        uri.pathSegments[3] == 'projects' &&
        uri.pathSegments[5] == 'rules') {
      rulesReads.add(path);
      if (!rulesRoute) {
        throw const SuperTabFailure(
          'BACKEND_UNAVAILABLE',
          'Not Found',
          statusCode: 404,
        );
      }
      final rules = projectRules[uri.pathSegments[4]];
      if (rules == null) {
        throw const SuperTabFailure(
          'NOT_FOUND',
          'This project is unavailable.',
          statusCode: 404,
        );
      }
      return jsonDecode(jsonEncode(rules)) as Map<String, dynamic>;
    }
    if (uri.pathSegments.length > 2 &&
        uri.pathSegments[uri.pathSegments.length - 2] == 'attachments') {
      fileLinkReads.add(path);
      final answer = fileLink;
      if (answer == null) {
        throw const SuperTabFailure(
          'FILE_UNAVAILABLE',
          'This file is no longer available.',
          statusCode: 404,
        );
      }
      return {'attachment': await answer(uri.pathSegments.last)};
    }
    if (uri.pathSegments.last == 'proposals') {
      proposalReads.add(path);
      if (proposalsUnsupported) {
        throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
      }
      return {
        'proposals': [...?proposals[uri.queryParameters['projectId']]],
      };
    }
    if (uri.pathSegments.last == 'threads' ||
        uri.pathSegments.last == 'inbox') {
      threadListReads.add(path);
      if (holdThreadLists case final hold?) await hold.future;
      if (failThreadLists) {
        throw SuperTabFailure(
          'OFFLINE',
          'No connection.',
          statusCode: threadListStatus,
        );
      }
      // A backend before task #2835: its strict query refuses `read`.
      if (refuseThreadsRead && uri.queryParameters.containsKey('read')) {
        throw const SuperTabFailure(
          'VALIDATION_ERROR',
          'Unrecognized key: "read"',
          statusCode: 400,
        );
      }
      final answer = uri.pathSegments.last == 'threads'
          ? followedThreads
          : inbox;
      if (answer == null) {
        throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
      }
      return jsonDecode(jsonEncode(answer)) as Map<String, dynamic>;
    }
    if (uri.pathSegments.last == 'reminders' && method == 'GET') {
      reminderReads.add(path);
      if (!remindersServed) {
        throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
      }
      final now = clock.now();
      DateTime due(Map r) => DateTime.parse(r['dueAt'] as String);
      final listed = [
        for (final r in reminders)
          if (!due(r).isAfter(now)) r,
      ]..sort((a, b) => due(b).compareTo(due(a)));
      final later = [
        for (final r in reminders)
          if (due(r).isAfter(now)) due(r),
      ]..sort();
      return jsonDecode(
        jsonEncode({
          'due': listed,
          'next': later.firstOrNull?.toUtc().toIso8601String(),
        }),
      ) as Map<String, dynamic>;
    }
    if (uri.pathSegments.last == 'activity') {
      activityReads.add(path);
      // Worked out when asked, as a server does: a slow answer is the one
      // it had then.
      final asked = activity;
      if (holdActivity case final hold?) await hold.future;
      if (activityStatus != 0) {
        throw SuperTabFailure(
          'OFFLINE',
          'No connection.',
          statusCode: activityStatus,
        );
      }
      if (asked == null) {
        throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
      }
      return jsonDecode(jsonEncode(asked)) as Map<String, dynamic>;
    }
    if (uri.pathSegments.last == 'mentions') {
      mentionReads++;
      if (mentionsMissing) {
        throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
      }
      if (holdMentions case final hold?) await hold.future;
      if (failMentions) throw StateError('Offline');
      final waiting = uri.queryParameters['state'] == 'waiting';
      return jsonDecode(
        jsonEncode({
          'mentions': mentions.reversed
              .where((m) => (m['resolvedAt'] == null) == waiting)
              .toList(),
        }),
      ) as Map<String, dynamic>;
    }
    if (uri.pathSegments.last == 'leaderboard') {
      leaderboardReads.add(path);
      if (failLeaderboardReads > 0) {
        failLeaderboardReads--;
        throw const SuperTabFailure(
          'OFFLINE',
          'No connection.',
          statusCode: 503,
        );
      }
      if (leaderboardGate case final gate?) await gate;
      final board = leaderboardAnswer?.call(path) ?? leaderboard;
      if (board == null) {
        throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
      }
      return jsonDecode(jsonEncode(board)) as Map<String, dynamic>;
    }
    if (uri.pathSegments.last == 'decisions') {
      decisionReads++;
      if (holdDecisions case final hold?) await hold.future;
      if (failDecisions) throw StateError('Offline');
      final state = uri.queryParameters['state'];
      if (state == 'settled' && settledMissing) {
        throw const SuperTabFailure(
          'INVALID_REQUEST',
          'Invalid query.',
          statusCode: 400,
        );
      }
      final open = state == 'open';
      // What an older Desktop reads as answered leaves out those the PM
      // decided; `settled` has them all.
      final listed = decisions.reversed
          .where((d) => (d['answeredAt'] == null) == open)
          .where((d) => state != 'answered' || d['delegated'] != true)
          .toList();
      final page = decisionPage;
      return jsonDecode(
        jsonEncode({
          'decisions': listed.take(page ?? listed.length).toList(),
          if (page != null) 'more': listed.length > page,
        }),
      ) as Map<String, dynamic>;
    }
    if (uri.pathSegments.last == 'routing-policy') {
      final policy = routingPolicy;
      if (policy == null) {
        throw const SuperTabFailure('NOT_FOUND', 'No routing policy.');
      }
      return jsonDecode(jsonEncode(policy)) as Map<String, dynamic>;
    }
    if (uri.pathSegments.length > 2 &&
        uri.pathSegments[uri.pathSegments.length - 2] == 'route-decisions') {
      final decision = routeDecisions[uri.pathSegments.last];
      if (decision == null) {
        throw const SuperTabFailure('NOT_FOUND', 'No such decision.');
      }
      return jsonDecode(jsonEncode(decision)) as Map<String, dynamic>;
    }
    if (uri.pathSegments.last == 'messages') {
      onRead?.call(path);
      final conversationId = uri.pathSegments[4];
      // A chat the Swarm no longer has is not found, as the backend answers (hotfix #4647).
      if (chatsGoneAreNotFound &&
          !(state['conversations'] as List).any(
            (g) => (g as Map)['id'] == conversationId,
          )) {
        throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);
      }
      final query = uri.queryParameters;
      final after = int.tryParse(query['after'] ?? '');
      final before = int.tryParse(query['before'] ?? '');
      final afterId = query['afterId'], beforeId = query['beforeId'];
      final messageId = query['messageId'], thread = query['thread'];
      if (thread != null && before != null && holdThreadPages != null) {
        await holdThreadPages!.future;
      }
      if (messageId != null) {
        if (forbidMessageReads.contains(conversationId)) {
          throw const SuperTabFailure(
            'FORBIDDEN',
            'Forbidden.',
            statusCode: 403,
          );
        }
        if (failMessageReads > 0) {
          failMessageReads--;
          throw StateError('Offline');
        }
      }
      // Pages run in (sequence, id) order (section 4.6).
      int order(Map<String, dynamic> a, Map<String, dynamic> b) {
        final bySequence = (a['sequence'] as int).compareTo(
          b['sequence'] as int,
        );
        return bySequence != 0
            ? bySequence
            : (a['id'] as String).compareTo(b['id'] as String);
      }

      bool past(Map<String, dynamic> m, int sequence, String? id, int sign) {
        final s = (m['sequence'] as int).compareTo(sequence) * sign;
        if (s != 0 || id == null) return s > 0;
        return (m['id'] as String).compareTo(id) * sign > 0;
      }

      var rows =
          messages
              .where(
                (m) =>
                    m['conversationId'] == conversationId &&
                    (messageId == null || m['id'] == messageId) &&
                    (thread == null || m['thread'] == thread) &&
                    (after == null || past(m, after, afterId, 1)) &&
                    (before == null || past(m, before, beforeId, -1)),
              )
              .toList()
            ..sort(order);
      if (after == null) rows = rows.reversed.toList();
      final page = rows.take(messagePage).toList();
      final next = rows.length > messagePage
          ? {'sequence': page.last['sequence'], 'id': page.last['id']}
          : null;
      return jsonDecode(
        jsonEncode({
          'messages': after == null ? page.reversed.toList() : page,
          'next': next,
          'threads': _threads(conversationId, page),
          'reactionSeq':
              (state['conversations'] as List)
                  .cast<Map>()
                  .where((g) => g['id'] == conversationId)
                  .firstOrNull?['reactionSeq'] ??
              0,
        }),
      ) as Map<String, dynamic>;
    }
    if (parts.read(path, state, reader: reader) case final answer?) {
      return answer;
    }
    if (uri.path == '/api/super-tabs/list') {
      return {
        'tabs': [
          {
            'id': state['id'],
            'name': state['name'],
            'ownerId': state['ownerId'],
            'paused': state['paused'] ?? false,
            'lastChangedAt': parts.clock,
          },
        ],
        'next': null,
      };
    }
    // The whole-Swarm reads are gone (section 4.11): nothing may still ask.
    throw superTabUpdateRequired;
  }

  /// The Lead tags the reader in [conversationId], as the backend records it.
  void tag(
    String messageId, {
    String conversationId = 'lead',
    String text = 'Please confirm the release.',
    String createdAt = '2026-10-24T05:00:00Z',
    String? leadId,
    String? threadId,
    int? messageSequence,
  }) {
    mentions.add({
      'leadId': ?leadId,
      'threadId': ?threadId,
      'messageSequence': ?messageSequence,
      'id': 'mention-${mentions.length + 1}',
      'projectId': 'lead',
      'projectName': 'web-project',
      'conversationId': conversationId,
      'conversationTitle': 'Lead',
      'messageId': messageId,
      'leadName': 'Wren',
      'text': text,
      'createdAt': createdAt,
      'resolvedAt': null,
      'resolvedBy': null,
    });
    state['mentionsWaiting'] = ((state['mentionsWaiting'] as int?) ?? 0) + 1;
    revision++;
    // The Lead's message carrying the tag moves its conversation.
    final group = (state['conversations'] as List)
        .cast<Map<String, dynamic>>()
        .where((g) => g['id'] == conversationId)
        .firstOrNull;
    group?['lastMessageSequence'] = revision;
  }

  /// The Lead asks the reader [questions] in one batch, as the backend records it.
  void ask(
    List<String> questions, {
    String conversationId = 'lead',
    String projectId = 'lead',
    int recommended = 0,
  }) {
    final batch = 'batch-${decisions.length + 1}';
    for (final question in questions) {
      decisions.add({
        'id': 'decision-${decisions.length + 1}',
        'batchId': batch,
        'projectId': projectId,
        'projectName': 'web-project',
        'conversationId': conversationId,
        'conversationTitle': 'Lead',
        'askerName': 'Wren',
        'question': question,
        'options': ['Behind a flag', 'To everyone'],
        'recommended': recommended,
        // As the backend says it: a recommended option that exists.
        'pmTakesOver': recommended >= 0 && recommended < 2,
        'unblocks': 'The release',
        'createdAt': '2026-10-27T05:00:00Z',
        'answeredAt': null,
        'choice': null,
        'note': null,
        'delegated': false,
      });
    }
    state['decisionsWaiting'] =
        ((state['decisionsWaiting'] as int?) ?? 0) + questions.length;
    _digestDecisions();
    revision++;
  }

  /// The reader answers one, here or on another device.
  void answerDecision(
    String id,
    int? choice, {
    bool delegated = false,
    String? note,
  }) {
    decisions.firstWhere((d) => d['id'] == id)
      ..['choice'] = choice
      ..['note'] = note
      ..['delegated'] = delegated
      ..['answeredAt'] = '2026-10-27T06:00:00Z';
    state['decisionsWaiting'] = (state['decisionsWaiting'] as int) - 1;
    _digestDecisions();
    revision++;
  }

  /// The reader can no longer read the conversation of decision [id]: the
  /// backend leaves it out of its lists and its count.
  void hideDecision(String id) {
    final hidden = decisions.firstWhere((d) => d['id'] == id);
    decisions.remove(hidden);
    if (hidden['answeredAt'] == null) {
      state['decisionsWaiting'] = (state['decisionsWaiting'] as int) - 1;
    }
    _digestDecisions();
    revision++;
  }

  /// Which decisions are open, as the backend digests them.
  void _digestDecisions() {
    if (decisionsDigestMissing) return;
    state['decisionsDigest'] = [
      for (final d in decisions)
        if (d['answeredAt'] == null) d['id'],
    ].join(',');
  }

  Map<String, dynamic> _project(String id) {
    final projects = state['projects'] ??= <dynamic>[
      projectFixture('lead', state['name'] as String, 'lead'),
    ];
    return (projects as List).cast<Map<String, dynamic>>().firstWhere(
      (p) => p['id'] == id,
      orElse: () => throw const SuperTabFailure(
        'NOT_FOUND',
        'This project is unavailable.',
        statusCode: 404,
      ),
    );
  }

  /// A viewer's write is refused as the backend refuses it (model.ts `author`).
  void _requireMember(String id) {
    final role = (state['people'] as List? ?? const [])
        .cast<Map>()
        .where((p) => p['id'] == id)
        .firstOrNull?['role'];
    if (role == 'viewer') {
      throw const SuperTabFailure(
        'READ_ONLY',
        'You have read-only access to this Super Tab.',
        statusCode: 403,
      );
    }
  }

  /// `instructions.save` as the backend runs it (commands.ts): on the revision the writer read, or refused
  /// `INSTRUCTIONS_STALE`; a save moves the project's `instructionsRevision` and keeps the text and a revision.
  Map<String, dynamic> _saveInstructions(Map command, String writer) {
    // What the backend's schema and access check refuse (commands.ts, instructions.ts), in the order it does.
    _requireMember(writer);
    final text = command['text'];
    final summary = command['summary'];
    if (text is! String || text.isEmpty || utf8.encode(text).length > 65536) {
      throw const SuperTabFailure(
        'VALIDATION_ERROR',
        'Project instructions are at most 64 KB, and not empty.',
        statusCode: 400,
      );
    }
    if (summary is! String ||
        summary.trim().isEmpty ||
        summary.trim().length > 200 ||
        summary.contains(RegExp(r'[\r\n]'))) {
      throw const SuperTabFailure(
        'VALIDATION_ERROR',
        'Summarize the change in one line.',
        statusCode: 400,
      );
    }
    final project = _project(command['projectId'] as String);
    final projectId = project['id'] as String;
    final current = (project['instructionsRevision'] as int?) ?? 0;
    if (command['baseRevision'] != current) {
      throw SuperTabFailure(
        'INSTRUCTIONS_STALE',
        'The instructions changed since revision ${command['baseRevision']}. '
            'Merge your change into revision $current and save again.',
        statusCode: 409,
      );
    }
    if (current > 0 && instructions[projectId]?['text'] == text) {
      return {
        'projectId': projectId,
        'revision': current,
        'hash': instructions[projectId]?['hash'],
        'unchanged': true,
      };
    }
    final next = current + 1;
    final hash = 'hash-$projectId-$next';
    project['instructionsRevision'] = next;
    instructions[projectId] = {
      'projectId': projectId,
      'notes': <dynamic>[],
      ...?instructions[projectId],
      'revision': next,
      'hash': hash,
      'text': command['text'],
      'template': false,
      'coordinatorName': project['coordinatorName'] ?? 'Product Manager',
      'notesRevision': project['notesRevision'] ?? 0,
    };
    (instructionRevisions[projectId] ??= []).insert(0, {
      'revision': next,
      'hash': hash,
      'summary': (summary).trim(),
      'writtenBy': {'kind': 'person', 'id': writer},
      'askedBy': command['askedBy'] ?? writer,
      'at': '2026-10-30T00:00:00Z',
      'text': command['text'],
    });
    revision++;
    return {'projectId': projectId, 'revision': next, 'hash': hash};
  }

  /// The three instructions reads (backend routes/superTabs.ts): the document, its kept revisions without their
  /// text, and one revision with it.
  Map<String, dynamic> _readInstructions(String path, Uri uri) {
    instructionReads.add(path);
    if (!instructionsRoute) {
      throw const SuperTabFailure(
        'BACKEND_UNAVAILABLE',
        'Not Found',
        statusCode: 404,
      );
    }
    const unavailable = SuperTabFailure(
      'NOT_FOUND',
      'This project is unavailable.',
      statusCode: 404,
    );
    final projectId = uri.pathSegments[4];
    final rest = uri.pathSegments.skip(6).toList();
    Map<String, dynamic> copy(Object value) =>
        jsonDecode(jsonEncode(value)) as Map<String, dynamic>;
    if (rest.isEmpty) {
      return copy(instructions[projectId] ?? (throw unavailable));
    }
    final kept = instructionRevisions[projectId] ?? const [];
    if (rest.length == 1 && rest.single == 'revisions') {
      return copy({
        'projectId': projectId,
        'revisions': [
          for (final row in kept) {...row}..remove('text'),
        ],
      });
    }
    final wanted = rest.length == 2 ? int.tryParse(rest.last) : null;
    final row = kept.where((r) => r['revision'] == wanted).firstOrNull;
    if (row == null) {
      throw const SuperTabFailure(
        'NOT_FOUND',
        'This revision is unavailable.',
        statusCode: 404,
      );
    }
    return copy({'projectId': projectId, ...row});
  }

  /// Who asks, for the reads a [controller] makes: a private conversation is
  /// read by its audience alone. A zone value, so that subclasses overriding
  /// [request] keep it.
  static final _reader = Object();

  SuperTabController controller({
    String tabId = 'tab',
    Map<String, dynamic>? initial,
    String account = 'owner',
    SuperTabUpload? upload,
    SuperTabReading reading = const SuperTabReading(),
  }) => SuperTabController(
    avatarUpload: uploadAvatar,
    reading: reading,
    tabId: tabId,
    accountId: account,
    request: (method, path, {body}) => runZoned(
      () => request(method, path, body: body),
      zoneValues: {_reader: account},
    ),
    save: save,
    upload: upload ?? this.upload,
    initial: initial ?? const {},
    pollInterval: Duration.zero,
  );
}