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.

227 KB
Raw Blame
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:math';

import 'package:clock/clock.dart';
import 'package:cryptography/dart.dart' show DartSha256;
import 'package:dio/dio.dart' show CancelToken, DioException, DioExceptionType;
import 'package:flutter/foundation.dart';

import '../logging/app_log.dart';
import '../measurement/speed_marks.dart';
import '../state/harness_attachments.dart';
import 'attachment_upload.dart';
import 'avatar_upload.dart';
import 'backlog.dart' show SuperTabTaskPriority;
import 'message_link.dart';
import 'identity.dart' show superTabMachineName;
import 'machine_status.dart' show kSuperTabMachineOfflineAfter;
import 'model.dart';
import 'task_groups.dart';
import 'buddy_chat.dart';
import 'project_github.dart';
import 'parts.dart';
import 'tasks/personal_tasks.dart';
import 'read_marks.dart';
import 'reading.dart';
import 'linked_tasks.dart';
import 'local_time_zone.dart';
import 'task_steps.dart';

/// A messages read started beside a state read, and what it asked for.
typedef _EarlyRead = ({
  String query,
  Future<Map<String, dynamic>> page,
  // Running since the page was asked for, so its wait is measured whole.
  Stopwatch clock,
});

typedef SuperTabRequest = Future<Map<String, dynamic>> Function(
  String method,
  String path, {
  Map<String, dynamic>? body,
});

String superTabOperationId() {
  final random = Random.secure();
  return List.generate(
    16,
    (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'),
  ).join();
}

/// Runs [task] for each of [items], two at a time, and returns the results in
/// order. Every Swarm command rewrites the whole Swarm row, so twenty at once
/// hit SWARM_BUSY (503); two keep a batch moving without that.
Future<List<R>> superTabTwoAtATime<T, R>(
  Iterable<T> items,
  Future<R> Function(T item) task,
) async {
  final queue = items.toList();
  final results = List<R?>.filled(queue.length, null);
  var next = 0;
  Future<void> worker() async {
    while (next < queue.length) {
      final at = next++;
      results[at] = await task(queue[at]);
    }
  }

  await Future.wait([worker(), worker()]);
  return [for (final r in results) r as R];
}

/// The id the backend gives the message a person sends with receipt
/// [operationId]: `stableId(state.id, actorKey(actor), operationId)`, the
/// first 24 hex of sha256 over the JSON of those parts (backend
/// superTabs/commands.ts `message.send`, model.ts `stableId`).
String superTabMessageId({
  required String tabId,
  required String accountId,
  required String operationId,
}) => const DartSha256()
    .hashSync(
      utf8.encode(jsonEncode([tabId, 'person:$accountId', operationId])),
    )
    .bytes
    .map((b) => b.toRadixString(16).padLeft(2, '0'))
    .join()
    .substring(0, 24);

/// The most pages of closed groups one read goes through (50 a page), so a
/// Swarm whose old groups all changed lately cannot read without an end.
const _closedSincePages = 40;

/// Saved for a text still queued when the window closed. Older versions read
/// and show it; this one knows it by [_unsentKey] and shows Not sent alone.
const _unsentReason = 'Not sent before this window closed.';
const _unsentKey = 'unsent';

/// What a thread reply refused for New session says: the server does not
/// take it yet (an older backend, or one of its servers during a release).
const superTabSessionsUnavailable =
    "New sessions aren't available yet; send without it?";

/// What a message refused for its form says, in place of the schema's own
/// words ('command: Unrecognized key: ...'), which name fields, not causes.
const superTabRefusedAsSent = "The server couldn't take this message.";

/// The schema's own words, as a refusal saved before this version kept them.
final _schemaWords = RegExp(r'Unrecognized key|^command(\.\w+)*: ');

class SuperTabFailure implements Exception {
  const SuperTabFailure(
    this.code,
    this.message, {
    this.statusCode = 0,
    this.settled = false,
  });
  final String code, message;
  final int statusCode;

  /// No wait changes this answer, whatever its code ([SuperTabReading.retriesFirstRead]): a Team
  /// computer that may not speak as the person, beside a computer that is only still starting.
  final bool settled;
  @override
  String toString() => message;
}

/// Where a message the reader sent stands while the transcript does not
/// show it yet.
enum SuperTabOutgoingState {
  /// On its way, or accepted and not read back yet.
  sending,

  /// Accepted by the server, while its transcript refresh is still pending.
  confirmed,

  /// Sent with no answer: it may or may not have arrived. Retry checks and
  /// sends it once.
  unconfirmed,

  /// The backend refused it; nothing was posted.
  refused,
}

/// A message the backend refused, with the tags it was sent with.
typedef _Refused = ({
  String operationId,
  Map<String, dynamic> command,
  Map<String, String> mentions,
  String error,
});

typedef _QueuedSend = ({
  String operationId,
  Map<String, dynamic> command,
  Completer<Map<String, dynamic>?> result,
});

/// A message the reader sent that the transcript does not hold yet.
class SuperTabOutgoing {
  const SuperTabOutgoing({
    required this.conversationId,
    required this.text,
    required this.state,
    this.operationId,
    this.replyTo,
    this.thread,
    this.alsoSend = false,
    this.error,
    this.confirmedAt,
  });
  final String conversationId, text;

  /// The thread root a reply goes to, null for a top-level or inline reply.
  final String? thread;

  /// A thread reply also sent to the main stream.
  final bool alsoSend;
  bool get inMainStream => thread == null || alsoSend;

  /// The send's receipt id, while it is not confirmed.
  final String? operationId;
  final String? replyTo;
  final SuperTabOutgoingState state;

  /// Why it was refused, as the backend said it.
  final String? error;
  final String? confirmedAt;
}

/// Personal navigation/drafts live on this client. Membership, work and messages
/// live on the backend; refreshing never selects another person's conversation.
/// WS roadmap Phase 2a: a server that pushes Swarm changes (backend
/// lib/swarmClientPushes.ts) says so every 4 minutes. Without that word for
/// this long (an older server, a rollback, Redis down) a Swarm polls as
/// before.
const kSwarmPushLease = Duration(minutes: 5);

/// How often a pushing server repeats that word on one socket (backend lib/swarmClientPushes.ts
/// `PUSHES_REPEAT_MS`). A word off this beat is a socket that (re)connected.
const kSwarmPushRepeat = Duration(minutes: 4);

/// While the server pushes, a Swarm nothing was said of is still read this
/// often: the safety net for a push lost on the way.
const kSwarmPushSafetyNet = Duration(seconds: 60);

/// While the server pushes, which Swarms the account is in is still read this
/// often; a change to one asks for a read at once (`SuperTabClient`).
const kSwarmDiscoverySafetyNet = Duration(minutes: 2);

/// While a Swarm's reads are refused, the account's Swarm list is read for it
/// at most this often to learn whether it is gone (task #2767).
const kSwarmListRecheckEvery = Duration(minutes: 1);

/// The files waiting in a Swarm's boxes: by conversation, and by a thread's
/// conversation and root.
typedef SuperTabKeptFiles = ({
  Map<String, List<HarnessAttachment>> chats,
  Map<(String, String), List<HarnessAttachment>> threads,
});

class SuperTabController extends ChangeNotifier {
  SuperTabController({
    required this.tabId,
    required this.accountId,
    required this.request,
    required this.save,
    this.upload = refuseUpload,
    this.avatarUpload = refuseAvatarUpload,
    this.uploadTimeout = const Duration(minutes: 2),
    Map<String, dynamic> initial = const {},
    this.pollInterval = const Duration(seconds: 3),
    SuperTabReading reading = const SuperTabReading(),
    this.stillListed,
  }) : _policy = reading {
    if (initial['tabId'] == tabId && initial['accountId'] == accountId) {
      final order = initial['sendOrder'];
      if (order is List) _sendOrder.addAll(order.whereType<String>());
      _savedSelection = initial['selectedId'] is String;
      expandedMachines.addAll(
        (initial['expandedMachines'] as List? ?? const []).whereType<String>(),
      );
      _decisionsAside.addAll(
        (initial['decisionsAside'] as List? ?? const []).whereType<String>(),
      );
      devicesSelected = initial['devicesSelected'] == true;
      unreadOnly = initial['unreadOnly'] == true;
      machinesGroupOpen = initial['machinesGroupOpen'] as bool? ?? true;
      buddiesGroupOpen = initial['buddiesGroupOpen'] as bool? ?? true;
      agentsGroupOpen = initial['agentsGroupOpen'] as bool? ?? true;
      modelsGroupOpen = initial['modelsGroupOpen'] as bool? ?? true;
      offlineMachinesOpen = initial['offlineMachinesOpen'] as bool? ?? false;
      sessionProjectId = initial['sessionProjectId'] as String? ?? '';
      selectedId = initial['selectedId'] as String? ?? 'lead';
      final drafts = initial['drafts'];
      if (drafts is Map) {
        for (final entry in drafts.entries) {
          if (entry.key is String && entry.value is String) {
            _drafts[entry.key as String] = entry.value as String;
          }
        }
      }
      final read = initial['readAt'];
      final terminals = initial['terminals'];
      if (terminals is Map) {
        for (final entry in terminals.entries) {
          if (entry.key is String && entry.value is String) {
            _terminals[entry.key as String] = entry.value as String;
          }
        }
      }
      final mentions = initial['mentions'];
      if (mentions is Map) {
        for (final group in mentions.entries) {
          if (group.key is String && group.value is Map) {
            _mentions[group.key as String] = {
              for (final mention in (group.value as Map).entries)
                if (mention.key is String && mention.value is String)
                  mention.key as String: mention.value as String,
            };
          }
        }
      }
      if (read is Map) {
        for (final entry in read.entries) {
          if (entry.key is String && entry.value is num) {
            _readAt[entry.key as String] = (entry.value as num).toInt();
          }
        }
      }
      if (initial['threadSeen'] case final Map seen) {
        for (final MapEntry(:key, :value) in seen.entries) {
          if (key is String && value is num) _threadSeen[key] = value.toInt();
        }
      }
      if (initial['openThreads'] case final Map saved) {
        for (final MapEntry(:key, :value) in saved.entries) {
          if (key is String && value is String && value.isNotEmpty) {
            _rememberOpenThread(key, value);
          }
        }
      }
      // Read the single-thread shape written by older Desktop builds.
      if (initial['openThread'] case {
        'conversationId': final String conversation,
        'root': final String root,
      }) {
        if (!_openThreads.containsKey(conversation)) {
          _rememberOpenThread(conversation, root);
        }
      }
      if (_openThreads[selectedId] case final root?) {
        openedThread = (conversationId: selectedId, root: root);
        _reopenThread = true;
        _threadUnshown = true;
      }
      if (initial['threadDrafts'] case final Map saved) {
        for (final MapEntry(key: root, value: draft) in saved.entries) {
          if (root is! String || draft is! Map) continue;
          final conversation = draft['conversationId'], text = draft['text'];
          if (conversation is! String || text is! String || text.isEmpty) {
            continue;
          }
          _threadDrafts[root] = text;
          _threadDraftConversations[root] = conversation;
          if (draft['mentions'] case final Map mentions) {
            final tags = {
              for (final MapEntry(:key, :value) in mentions.entries)
                if (key is String && value is String) key: value,
            };
            if (tags.isNotEmpty) _threadMentions[(conversation, root)] = tags;
          }
        }
      }
      final refused = initial['refused'];
      if (refused is Map) {
        for (final MapEntry(:key, :value) in refused.entries) {
          if (key is! String || value is! List) continue;
          final kept = [
            for (final row in value)
              if (row is Map &&
                  row['operationId'] is String &&
                  row['command'] is Map &&
                  row['error'] is String)
                (
                  operationId: row['operationId'] as String,
                  command: superTabMap(row['command']),
                  mentions: {
                    for (final MapEntry(key: agent, value: token)
                        in superTabMap(row['mentions']).entries)
                      if (token is String) agent: token,
                  },
                  error: row[_unsentKey] == true
                      ? ''
                      : _schemaWords.hasMatch(row['error'] as String)
                      ? superTabRefusedAsSent
                      : row['error'] as String,
                ),
          ];
          if (kept.isNotEmpty) _refused[key] = kept;
        }
      }
      if (initial['pending'] is Map) {
        final value = superTabMap(initial['pending']);
        if (value['operationId'] is String && value['command'] is Map) {
          _pending = value;
          _failOperation(
            'Check the pending action before sending it again.',
            command: superTabMap(value['command']),
          );
        }
      }
    }
  }

  final String tabId, accountId;
  final SuperTabRequest request;
  final Future<void> Function(Map<String, dynamic> state) save;
  final Duration pollInterval;

  /// Sends one file to the backend.
  final SuperTabUpload upload;

  /// Sends an avatar picture (profile_actions.dart).
  final SuperTabAvatarUpload avatarUpload;

  /// How long an upload may go without a byte moving before the send gives up.
  final Duration uploadTimeout;
  SuperTabSnapshot? snapshot;
  String selectedId = 'lead';

  /// Counts the reader's moves ([_moveView]), so a slow [select] cannot land
  /// over a newer choice.
  int _selectRequest = 0;

  /// Every move of what the reader looks at goes through here: a [select]
  /// still reading its conversation then knows it was overtaken.
  void _moveView({String? to, bool devices = false}) {
    _selectRequest++;
    devicesSelected = devices;
    if (to != null && to != selectedId) {
      _leftAt[selectedId] = clock.now();
      // Marked unread while open: once left, it reads as any chat does.
      _unreadHeld.remove(selectedId);
      if (openedThread case final open?
          when open.conversationId == selectedId) {
        _rememberOpenThread(selectedId, open.root);
      }
      selectedId = to;
      final root = _openThreads[to];
      openedThread = root == null ? null : (conversationId: to, root: root);
      threadTarget = null;
      _threadUnshown = root != null;
      _reopenThread = false;
    }
  }

  /// The newest change of the Swarm this tab has read, in epoch milliseconds: what tells the app and the tag list
  /// that it changed (spec ruling 8).
  int lastChangedAt = -1;

  /// The backend no longer serves this build's reads (HTTP 426): the tab says
  /// to update Harness and waits for an explicit Retry (section 5.1).
  bool updateRequired = false;

  /// What the tab says once [updateRequired] (docs/naming-system.md).
  static const updateMessage = 'Update Harness to keep using this Swarm.';

  /// Told when only what machines report moved (a heartbeat): the controller's
  /// own listeners hear nothing of it. Whatever shows a machine's readings
  /// listens to this too.
  Listenable get machinesChanged => _machinesChanged;
  final _machinesChanged = ValueNotifier<int>(0);

  /// The Swarm's parts as last read: what the next read asks changes for, and what [snapshot] is built from.
  SuperTabParts? _parts;

  SuperTabPersonalTasks? get personalTasks => _parts?.personalTasks;

  Future<bool>? _olderPersonalTasks;

  /// Reads the next older page of the person's Tasks (backend #4203), one read at a time. False when it failed.
  Future<bool> loadOlderPersonalTasks() => _olderPersonalTasks ??=
      _readOlderPersonalTasks().whenComplete(() => _olderPersonalTasks = null);

  Future<bool> _readOlderPersonalTasks() async {
    final parts = _parts;
    final cursor = parts?.personalTasks.olderCursor;
    if (parts == null || cursor == null) return true;
    try {
      final page = await request(
        'GET',
        '$_path/personal-tasks?before=${Uri.encodeComponent(cursor)}',
      );
      if (_disposed || !identical(parts, _parts)) return true;
      if (parts.personalTasks.applyOlder(page, from: cursor)) _changed();
      return true;
    } catch (failure) {
      if (_isUpdateRequired(failure)) _requireUpdate();
      return false;
    }
  }

  /// The visibility epoch of the last read: it moves when who may read what changes (backend parts/commit.ts
  /// `visibilityChanged`). Null before a read.
  int? get visibilityEpoch => _parts?.epoch;
  String? error, operationError, operationErrorCode;

  /// Why the files of each conversation's last send did not go up. Kept apart
  /// from [operationError] so it shows only under its own conversation.
  final _uploadErrors = <Object, String>{};

  /// The conversation the last action that set [operationError] was for, or
  /// null when it was for none (a machine, a member, the Swarm).
  String? _operationErrorFor;

  /// What the composer of [conversationId] says went wrong: the last action's
  /// [operationError] when it was for this conversation or for none, else its
  /// own upload failure. An action still unconfirmed blocks every composer's
  /// send, so its error shows in each, with Retry.
  String? composerError(String conversationId) {
    final failure = operationError;
    if (failure != null &&
        (_operationErrorFor == null ||
            _operationErrorFor == conversationId ||
            _pending != null)) {
      return failure;
    }
    return _uploadErrors[conversationId];
  }

  /// Takes the last action's refusal for a caller that says it in its own place, the instructions panel's Save (task
  /// #3652): no composer says it after. An action whose answer was lost keeps it, since every composer waits on it
  /// with Retry.
  String? takeOperationError() {
    final failure = operationError;
    if (failure == null || _pending != null) return failure;
    operationError = null;
    operationErrorCode = null;
    _operationErrorFor = null;
    _operationErrorRoot = null;
    _changed();
    return failure;
  }

  /// The thread the last failed reply was going to: the thread of the message
  /// it answers, or that message itself, as the backend files a reply. Null
  /// when the failure was not a reply.
  String? _operationErrorRoot;

  /// Sets [operationError] for [command], remembering its conversation and,
  /// for a reply, its thread.
  void _failOperation(
    String message, {
    required Map<String, dynamic> command,
    String? code,
  }) {
    operationError = message;
    operationErrorCode = code;
    final id = command['conversationId'];
    _operationErrorFor = id is String ? id : null;
    final replyTo = command['replyTo'];
    _operationErrorRoot = id is String && replyTo is String
        ? _threadOf(id, replyTo) ?? replyTo
        : null;
  }

  /// The same for the reply box of [root]'s thread in [conversationId]: the
  /// last action's [operationError] when it was a reply in this thread, for
  /// no conversation, or is still unconfirmed; else the thread's own upload
  /// failure. A failure in another chat, or in this chat's main stream, is
  /// not said here.
  String? threadComposerError(String conversationId, String root) {
    final failure = operationError;
    if (failure != null &&
        (_operationErrorFor == null ||
            (_operationErrorFor == conversationId &&
                _operationErrorRoot == root) ||
            _pending != null)) {
      return failure;
    }
    return _uploadErrors[(conversationId, root)];
  }

  /// One line for the sender after a command succeeds, from the backend: that a
  /// credential was removed from what they sent and should be revoked.
  String? operationNotice;
  bool loading = false, saving = false, uploading = false;
  bool accessRevoked = false;
  bool _disposed = false;
  Timer? _poll, _draftSave, _graceEnd;
  Future<void>? _refreshing;

  /// How this tab keeps itself current; Desktop's unless a host sets another.
  SuperTabReading get reading => _policy;
  set reading(SuperTabReading value) {
    if (identical(value, _policy)) return;
    _policy = value;
    if (_startedAt != null) _schedule();
  }

  SuperTabReading _policy;
  DateTime? _startedAt, _lastFullRead;

  /// Until when the server is known to push this Swarm's changes
  /// ([kSwarmPushLease]); set by [SuperTabClient] as it hears the server.
  DateTime? pushUntil;

  /// Told of a change since the last read began: one of its main parts, or a
  /// machine's reading alone; and the change times told lately, to know a
  /// push heard again ([_kToldTimes] of them).
  bool _toldMain = false, _toldMachine = false;
  final _toldTimes = <int>{};
  static const _kToldTimes = 64;

  bool get _pushing {
    final until = pushUntil;
    return until != null && clock.now().isBefore(until);
  }

  /// The server said this Swarm changed, at [at] when it names the commit's
  /// time. Only an exact repeat is dropped: a time already told, or the one
  /// the last read returned. A phone hears each push once per machine socket
  /// (review of #2121). An older time is not a repeat: each server stamps a
  /// commit from its own clock as the command starts, so a later commit can
  /// carry an earlier time (re-check of #2121). The rest is read on the next allowed read: now if the old poll
  /// would have read by now, else on the tick that would ([_readGap]), so a
  /// busy Swarm reads no more often than before pushes. A machine's reading
  /// alone always waits for the tick. Not on screen while the reading pauses,
  /// nothing is read until it is shown again, which reads at once.
  void told({required bool main, int? at}) {
    if (_disposed || accessRevoked || updateRequired) return;
    if (main && at != null) {
      if (at == lastChangedAt || !_toldTimes.add(at)) return;
      if (_toldTimes.length > _kToldTimes) _toldTimes.remove(_toldTimes.first);
    }
    if (main) {
      // A wait for a machine's report may be the slow one: this one is not.
      if (!_toldMain) {
        _toldRead?.cancel();
        _toldRead = null;
      }
      _toldMain = true;
    } else {
      _toldMachine = true;
    }
    _readWhenAllowed();
  }

  /// One read at the next allowed moment for what it was told: now if the
  /// gap since the last read has passed, else when it does; after a read
  /// under way, for a change heard while it was out.
  Timer? _toldRead;
  void _readWhenAllowed() {
    if (_toldRead != null || _disposed || !(_toldMain || _toldMachine)) return;
    if (_policy.pausesAway && _away) return;
    // A read under way reads again, if it must, once it ends (refresh).
    if (_refreshing != null) return;
    final last = _lastFullRead;
    final wait = last == null
        ? Duration.zero
        : _toldGap - clock.now().difference(last);
    if (wait <= Duration.zero) {
      unawaited(refresh());
      return;
    }
    _toldRead = Timer(wait, () {
      _toldRead = null;
      if (_disposed || accessRevoked || updateRequired) return;
      if (!(_toldMain || _toldMachine) || (_policy.pausesAway && _away)) {
        return;
      }
      if (_refreshing == null) unawaited(refresh());
    });
  }

  /// How often the idle poll reads: every [pollInterval], or
  /// [SuperTabReading.awayPoll] while the Swarm is away (never more often
  /// than [pollInterval]). A push is not an idle poll: [_readGap] keeps
  /// reading a told change at [pollInterval], so a tag reaches an away
  /// Swarm's badge and notice as fast as before.
  Duration get _every {
    final away = _policy.awayPoll;
    if (away == null || !_away) return pollInterval;
    return away > pollInterval ? away : pollInterval;
  }

  /// How often the poll read before pushes: every [pollInterval], or
  /// [SuperTabReading.quietPoll] once the person has been quiet a while.
  Duration get _readGap {
    final quiet = _policy.quietPoll;
    if (quiet != null &&
        clock.now().difference(_lastActivity) >= _policy.quietAfter) {
      return quiet;
    }
    return pollInterval;
  }

  /// How long what the reader was told waits since the last read. A change
  /// to the Swarm: [_readGap], on screen or off. A machine's report alone says
  /// nothing a Swarm not on screen shows: its slow pace ([_every]).
  Duration get _toldGap => _toldMain || _every < _readGap ? _readGap : _every;

  bool get _gapPassed {
    final last = _lastFullRead;
    return last == null || clock.now().difference(last) >= _toldGap;
  }

  /// Whether this poll reads. Always, unless the server pushes: then only when
  /// told and the old poll would have read by now, or when the safety net is
  /// due. A receipt, which no push names, is read on its own
  /// ([_checkReceipt]).
  bool get _pollDue {
    if (!_pushing) return true;
    if ((_toldMain || _toldMachine) && _gapPassed) return true;
    final last = _lastFullRead;
    return last == null || clock.now().difference(last) >= kSwarmPushSafetyNet;
  }

  /// How often the person's newest message in the open conversation is read
  /// again while its delivery is open, and for how long (the phone's, mobile
  /// swarm_conversation.dart): a receipt moves on the delivery's own record,
  /// which neither a push nor the conversation's counters name. One row
  /// every 30 s, not the page every poll (spec 2026-11-02-poll-cost, Part 2).
  static const _receiptReadEvery = Duration(seconds: 30);
  static const _receiptReadFor = Duration(minutes: 10);

  /// How long a claimed or unconfirmed delivery is read again: as long as the
  /// backend lets it stand, an hour (`deliverySettle.ts` `HOLD_LIMIT_MS`,
  /// `UNCERTAIN_LIMIT_MS`).
  static const _heldReadFor = Duration(minutes: 60);

  /// The deliveries read again: queued, taken by its computer (it may come
  /// back unconfirmed), or unconfirmed until a person settles it. Past them
  /// the receipt changes with an answer, which is a new message.
  static const _openDeliveries = {'queued', 'claimed', 'uncertain'};

  /// The own message whose receipt is followed, since when, and when it was
  /// last read.
  String? _receiptOf;
  DateTime? _receiptSince, _receiptAsked;

  /// The person's newest message in [id], written by them and not by an
  /// agent or a terminal: the only one that can carry a delivery line.
  SuperTabMessage? _latestOwn(String id) {
    SuperTabMessage? own;
    for (final m in _messages[id] ?? const <SuperTabMessage>[]) {
      if (m.fromAgent || m.fromTerminal || m.authorId != accountId) continue;
      if (own == null || m.sequence > own.sequence) own = m;
    }
    return own;
  }

  /// [messageId]'s row was just read: its receipt is as new as can be.
  void _receiptRead(String messageId) {
    final now = clock.now();
    if (_receiptOf != messageId) {
      _receiptOf = messageId;
      _receiptSince = now;
    }
    _receiptAsked = now;
  }

  /// The person's latest message in [id] waits for its delivery
  /// ([_openDeliveries]), and has not waited past its bound since this
  /// device saw it waiting.
  bool _receiptOpen(String id) {
    final own = _latestOwn(id);
    final status = own?.receiptDelivery?.status;
    if (own == null || !_openDeliveries.contains(status)) return false;
    final now = clock.now();
    if (_receiptOf != own.id) {
      _receiptOf = own.id;
      _receiptSince = now;
      _receiptAsked = null;
    }
    final bound = status == 'queued' ? _receiptReadFor : _heldReadFor;
    return now.difference(_receiptSince!) < bound;
  }

  /// At each poll: reads the open conversation's [_receiptOpen] message again,
  /// one row, at most every [_receiptReadEvery]. Not while away, where nobody
  /// sees it, nor beside a read of the conversation, which brings it.
  void _checkReceipt() {
    final id = selectedId;
    if (_disposed || accessRevoked || updateRequired || _away) return;
    if (_reading.containsKey((id, false)) || !_receiptOpen(id)) return;
    final asked = _receiptAsked;
    if (asked != null && clock.now().difference(asked) < _receiptReadEvery) {
      return;
    }
    unawaited(_readReceipt(id, _latestOwn(id)!));
  }

  /// Replaces [shown]'s row in [id] with the one read now. Dropped when
  /// another read replaced the row meanwhile: its answer is as new.
  Future<void> _readReceipt(String id, SuperTabMessage shown) async {
    final messageId = shown.id;
    _receiptRead(messageId);
    bool stale() =>
        _disposed ||
        accessRevoked ||
        snapshot?.conversation(id) == null ||
        !(_messages[id]?.any((m) => identical(m, shown)) ?? false);
    try {
      final answer = await request(
        'GET',
        '${_messagesPath(id)}?messageId=${Uri.encodeComponent(messageId)}',
      );
      if (stale()) return;
      final rows = (answer['messages'] as List)
          .map((m) => SuperTabMessage.fromJson(superTabMap(m)))
          .toList();
      if (rows.length > 1 ||
          rows.any((m) => m.id != messageId || m.conversationId != id)) {
        throw const FormatException(
          'A different message receipt was returned.',
        );
      }
      if (rows.isEmpty || _sameMessages([shown], rows)) return;
      _messages[id] = [
        for (final m in _messages[id]!) identical(m, shown) ? rows.single : m,
      ];
      _keepRows(id, answer['messages'] as List);
      if (id == selectedId) _viewVersion++;
      _changed();
    } catch (failure) {
      if (stale()) return;
      // Said as a messages read says it; the next check tries again.
      if (!_inConnectGrace(failure)) _readFailure(failure, revokeTab: false);
      _changed();
    }
  }

  /// When the parts held were last read: how old a [savedView] of them is.
  DateTime? _partsReadAt;

  /// When the Swarm was last read (Manage ▸ Backlog's "Synced", #2774).
  DateTime? get syncedAt => _partsReadAt;

  /// The rows each conversation's messages were read from, kept only to save
  /// the view ([SuperTabReading.drawsSaved]).
  final _rows = <String, Map<String, Map<String, dynamic>>>{};

  /// A saved view is on screen and no read has replaced it yet.
  bool get showingSaved => _showingSaved;
  bool _showingSaved = false;

  @visibleForTesting
  set showingSavedForTest(bool value) => _showingSaved = value;

  /// Moves when what a [savedView] holds changes: the state as read, or the
  /// open conversation and its page. Not for what only the page around them
  /// does (read marks, open groups), which needs no new copy kept.
  int get viewVersion => _viewVersion;
  int _viewVersion = 0;

  /// The last time the person did something here, or a new message reached
  /// the open conversation: what keeps the full poll ([SuperTabReading.quietPoll]).
  DateTime _lastActivity = clock.now();

  /// The saved state named the open conversation before any read.
  bool _savedSelection = false;

  /// The first reads found no machine connected, within the grace
  /// ([SuperTabReading.connectGrace]): still loading rather than failed.
  bool _waitingForMachine = false;
  Object? _graceFailure;
  Timer? _firstReadRetry;
  int _firstReadTries = 0;

  /// Not on screen: another tab is shown, or the page is hidden. Only a
  /// reading that [SuperTabReading.pausesAway] stops polling for it; coming
  /// back reads at once.
  bool get away => _away;
  bool _away = false;

  /// The page or window is hidden ([SuperTabClient.pageVisible]), set before [away]. While the
  /// server pushes, a hidden Swarm reads only what it is told (task #2953): its safety net waits
  /// for the return, which reads at once.
  bool pageHidden = false;

  bool get _restsHidden =>
      pageHidden && _pushing && !(_toldMain || _toldMachine);
  set away(bool value) {
    if (_away == value) return;
    _away = value;
    // The machines list's clock runs only while it shows.
    if (!_disposed) _machinesChanged.value++;
    if (_startedAt == null || _disposed) return;
    if (!_policy.pausesAway) {
      // Going away slows the poll; coming back reads at once unless a poll
      // just did ([SuperTabReading.awayPoll]).
      if (_policy.awayPoll == null) return;
      final last = _lastFullRead;
      if (!value &&
          (last == null || clock.now().difference(last) >= pollInterval)) {
        unawaited(refresh());
      }
      _schedule();
      return;
    }
    if (value) {
      _poll?.cancel();
      return;
    }
    _acted();
    unawaited(refresh());
    _schedule();
  }

  /// The latest read of the Swarm's state failed (and the tab is still ours). While it is, what the
  /// machines last reported cannot be told from what they report now: a machine is neither online nor
  /// offline, and the Swarm says its backend is unreachable instead of calling machines offline.
  bool get backendUnreachable =>
      _refreshFailing && !accessRevoked && !updateRequired;
  bool _refreshFailing = false;

  /// Since when the reads have been failing, while [backendUnreachable]: the first failure of this run of them.
  DateTime? unreachableSince;

  /// While [backendUnreachable], no read has been answered yet since this Swarm opened: nothing was
  /// lost, so it says Connecting rather than Reconnecting.
  bool get stillConnecting => backendUnreachable && stateReads == 0;

  /// How many reads of the Swarm's state have been answered. A sidebar that is waiting for a new reading (back from
  /// the background) knows it has one when this moves.
  int stateReads = 0;
  Future<void> _persisting = Future.value();
  Map<String, dynamic>? _pending;
  final _queuedSends = <_QueuedSend>[];
  bool _drainingSends = false;

  /// Who holds [saving] now: a send gives it up at its answer, so the next
  /// one may take it while the first still reads.
  Object? _lane;
  final _sendAcknowledgements = <String, Completer<void>>{};
  final _sendOrder = <String>[];

  /// Text can queue behind another text send; other actions and attachments
  /// retain their existing single-action flow.
  bool get canQueueText =>
      !_disposed &&
      canWrite &&
      !uploading &&
      (_pending == null ||
          (saving && pendingCommand?['type'] == 'message.send'));

  /// Sends the backend took, by message id, until the transcript holds them.
  final _sent = <String, Map<String, dynamic>>{};
  final _sendIdentities =
      <String, ({String operationId, String conversationId})>{};

  /// A local row keeps its identity even if the service assigns a different id.
  String messageIdentity(String id) =>
      _sendIdentities[id]?.operationId ?? _onTheirWay[id] ?? id;

  /// The messages on their way, by the id the backend gives each, so one a
  /// read brings before its answer is the same message (and the same row).
  Map<String, String> get _onTheirWay {
    final receipts = [
      if (pendingCommand?['type'] == 'message.send')
        _pending!['operationId'] as String,
      for (final queued in _queuedSends) queued.operationId,
    ];
    if (!listEquals(receipts, _onTheirWayFor)) {
      _onTheirWayFor = receipts;
      _onTheirWayIds = {
        for (final receipt in receipts) _messageIdOf(receipt): receipt,
      };
    }
    return _onTheirWayIds;
  }

  List<String> _onTheirWayFor = const [];
  Map<String, String> _onTheirWayIds = const {};
  String _messageIdOf(String receipt) => superTabMessageId(
    tabId: tabId,
    accountId: accountId,
    operationId: receipt,
  );

  /// The tags of each message on its way, by operation id, for a refusal to
  /// give back.
  final _sendingMentions = <String, Map<String, String>>{};

  /// Per conversation, oldest first, the messages the backend refused, each
  /// kept until it is sent again or deleted.
  final _refused = <String, List<_Refused>>{};
  final _drafts = <String, String>{};
  final _terminals = <String, String>{};
  final _mentions = <String, Map<String, String>>{};
  final _readAt = <String, int>{};

  /// Per conversation, each thread's summary as the newest page said it.
  final _threads = <String, Map<String, SuperTabThread>>{};

  /// Per thread root, the newest reply the reader has seen.
  final _threadSeen = <String, int>{};

  /// Each thread's rows as its own read brought them.
  final _threadRows = <String, List<SuperTabMessage>>{};

  /// The open thread each conversation should restore when selected again.
  final _openThreads = <String, String>{};

  static const _keptOpenThreads = 500;

  void _rememberOpenThread(String conversationId, String root) {
    _openThreads
      ..remove(conversationId)
      ..[conversationId] = root;
    if (_openThreads.length > _keptOpenThreads) {
      _openThreads.remove(_openThreads.keys.first);
    }
  }

  /// Where each thread's earlier replies continue, while there are more.
  final _threadBefore = <String, Map<String, dynamic>>{};
  final _threadDrafts = <String, String>{};

  /// Which conversation each draft in [_threadDrafts] is for, so what this
  /// computer keeps of it goes when that conversation does.
  final _threadDraftConversations = <String, String>{};

  /// The people and agents picked with `@` in each thread's reply box, by its
  /// conversation and root, as [_mentions] holds the chat's own.
  final _threadMentions = <(String, String), Map<String, String>>{};

  /// The thread open beside the chat.
  ({String conversationId, String root})? openedThread;

  /// The reply the open thread was opened at, to bring into view lit once
  /// its panel holds it ([SuperTabThreadPanel] takes it); null otherwise.
  ({String root, String messageId})? threadTarget;

  /// A thread restored open, whose replies its first read of the Swarm brings.
  bool _reopenThread = false;

  /// The open thread's pane is not on screen: restored open and not yet seen,
  /// or hidden since ([threadPaneHidden]). The read mark is the account's on
  /// every device, and this controller keeps reading with nothing shown, so
  /// nothing counts as read until [threadPaneShown].
  bool _threadUnshown = false;

  /// Whether the open thread's pane is on screen, as its read mark counts it:
  /// its replies are being read.
  bool get threadPaneOnScreen => openedThread != null && !_threadUnshown;

  /// The pane of the open thread is on screen.
  void threadPaneShown() {
    if (!_threadUnshown) return;
    _threadUnshown = false;
    if (openedThread case final open?) _seeThread(open.root);
    _changed();
  }

  /// The pane of the open thread left the screen: the app went to the
  /// background, another Swarm came to the front, or something covers it.
  /// Called from a build or a dispose, so listeners are told after it.
  void threadPaneHidden() {
    if (_threadUnshown) return;
    _threadUnshown = true;
    if (openedThread != null) scheduleMicrotask(_changed);
  }

  /// The root of the thread open beside the selected conversation, which the
  /// round dial's face follows; null when none is. Open, not on screen: a
  /// hidden pane (app in the background, another Swarm in front) is still the
  /// person's open thread, and the daemon drops the dial out of a thread that
  /// is not named. Read marks stay gated by [_threadUnshown], not this.
  String? get threadOnScreen => switch (openedThread) {
    final open? when open.conversationId == selectedId => open.root,
    _ => null,
  };

  final _attachments = <String, HarnessAttachments>{};

  /// The files waiting to go with the next reply of each thread, by its
  /// conversation and root: a root id alone is not enough to keep two
  /// conversations' files apart.
  final _threadAttachments = <(String, String), HarnessAttachments>{};
  // Files already uploaded for the message being sent, so a retry sends their
  // ids rather than uploading them again.
  final _uploaded = <HarnessAttachment, String>{};
  final _progress = <HarnessAttachment, double>{};
  CancelToken? _cancel;
  ({
    String conversationId,
    HarnessAttachments owner,
    List<HarnessAttachment> files,
  })?
  _sending;
  int _uploadRun = 0;
  final _messages = <String, List<SuperTabMessage>>{};

  /// Originals of replies quoted from outside the pages read, one message
  /// each, never part of the list: null when it is gone or refused.
  final _quoted = <String, Map<String, SuperTabMessage?>>{};

  /// The originals asked for, with how many reads of each failed (not refused).
  final _quoting = <String, Map<String, int>>{};
  final _quoteRetries = <Timer>{};
  static const _quoteTries = 3;
  static const _quoteRetryAfter = Duration(seconds: 3);

  /// Where each conversation's older history continues: the oldest message
  /// read, as the backend's page cursor names it (section 4.6). Null at the
  /// start of the conversation.
  final _before = <String, SuperTabPage?>{};

  /// At most this many messages are held of a conversation whose reader is at
  /// its end: a busy one left open all day reads, sorts and folds no more
  /// each poll. The rows cut are read again by scrolling up.
  static const _heldMessages = 500;

  /// Per conversation, the message its view lays its list out from (its
  /// dividing row): from it on, no row is cut, since cutting them moves the
  /// rows on screen. Rows before it may be cut.
  final _cutBefore = <String, SuperTabMessage>{};

  /// The view of [id] lays its list out from [message] on ([_cutBefore]).
  void keepFrom(String id, SuperTabMessage message) => _cutBefore[id] = message;

  /// When the reader left each conversation they opened, until it is open
  /// again or its messages are dropped ([_dropLeft]).
  final _leftAt = <String, DateTime>{};

  /// A conversation left this long holds no messages: opening it again reads
  /// its latest page, as the first open did. Longer than going back and forth
  /// between a few groups; short enough that a day of browsing holds only the
  /// ones read lately.
  static const _keepLeft = Duration(minutes: 15);

  /// Conversations opened again over messages held from an earlier visit,
  /// until a read of their newest messages lands: the held copy may end
  /// before what arrived meanwhile ([awaitsNewest]).
  final _staleHeld = <String>{};

  /// Whether [id]'s view waits for its newest messages before it places the
  /// New messages line, follows the end or marks anything read: reopened
  /// over a held copy whose read has not landed yet. A read that failed
  /// keeps it waiting while the held copy ends before the conversation's
  /// newest main-stream message; the next poll reads it again.
  bool awaitsNewest(String id) => _staleHeld.contains(id);

  /// A read of [id]'s newest messages landed, or failed: it waits no more,
  /// unless it failed with the held copy short of the newest message.
  /// Whether this ended a wait.
  bool _settleHeld(String id, {required bool read}) {
    if (!read && _heldBehind(id)) return false;
    return _staleHeld.remove(id);
  }

  /// Whether [id]'s held messages end before its newest main-stream message
  /// as the Swarm's state last said it.
  bool _heldBehind(String id) {
    final group = snapshot?.conversation(id);
    final tail = _messages[id]?.lastOrNull?.sequence;
    if (group == null || tail == null) return false;
    return tail < (group.lastMainSequence ?? group.lastMessageSequence);
  }

  /// Each conversation's reads under way, newest and older apart: an older
  /// page asked for during a poll's read is a read of its own.
  final _reading = <(String, bool), Future<void>>{};
  final expandedMachines = <String>{};
  bool devicesSelected = false;
  bool machinesGroupOpen = true;

  /// The sidebar's Buddies and Models, collapsed and remembered like Projects
  /// and Machines (Dee, 2026-10-30: every section the same).
  bool buddiesGroupOpen = true, modelsGroupOpen = true;

  /// Whether the left pane's My agents is open (task #4192): open until the reader closes it.
  bool agentsGroupOpen = true;

  bool isMachineExpanded(String id) => expandedMachines.contains(id);

  void toggleMachineExpanded(String id) {
    if (!expandedMachines.remove(id)) expandedMachines.add(id);
    _saveSoon();
    _changed();
  }

  /// Devices is personal navigation inside this Swarm. The selected workgroup,
  /// its draft and terminal choice stay available when the person returns.
  void selectDevices() {
    if (_disposed || accessRevoked || devicesSelected) return;
    _moveView(devices: true);
    _saveSoon();
    _changed();
  }

  /// The devices pane gives way to what was open under it.
  void leaveDevices() {
    if (_disposed || !devicesSelected) return;
    _moveView();
    _saveSoon();
    _changed();
  }

  /// Whether the Machines group's "Offline · N" disclosure is open; it starts closed.
  bool offlineMachinesOpen = false;

  /// The project last chosen for a New session in the reader's Buddy chat on
  /// this device, `''` for All projects (task #2347). The next New session
  /// starts on it, while the reader can still read it.
  String sessionProjectId = '';

  void chooseSessionProject(String projectId) {
    if (sessionProjectId == projectId) return;
    sessionProjectId = projectId;
    _saveSoon();
    _changed();
  }

  /// Open decisions the reader set aside in their Buddy chat (Not now, Hide):
  /// saved on this computer for this reader, so they stay folded after a
  /// restart. A decision asked later is not among them, so it shows.
  final _decisionsAside = <String>{};
  Set<String> get decisionsAside => UnmodifiableSetView(_decisionsAside);

  void setDecisionsAside(Iterable<String> ids, {required bool aside}) {
    var changed = false;
    for (final id in ids) {
      changed |= aside ? _decisionsAside.add(id) : _decisionsAside.remove(id);
    }
    if (!changed) return;
    _saveSoon();
    _changed();
  }

  /// Forgets the set-aside decisions known answered or [gone], so the saved
  /// set holds only what may still wait.
  void forgetDecisionsAside(bool Function(String id) gone) {
    final before = _decisionsAside.length;
    _decisionsAside.removeWhere(gone);
    if (_decisionsAside.length != before) _saveSoon();
  }

  void toggleMachinesGroup() {
    machinesGroupOpen = !machinesGroupOpen;
    _saveSoon();
    _changed();
  }

  void toggleAgentsGroup() {
    agentsGroupOpen = !agentsGroupOpen;
    _saveSoon();
    _changed();
  }

  void toggleBuddiesGroup() {
    buddiesGroupOpen = !buddiesGroupOpen;
    _saveSoon();
    _changed();
  }

  void toggleModelsGroup() {
    modelsGroupOpen = !modelsGroupOpen;
    _saveSoon();
    _changed();
  }

  void toggleOfflineMachines() {
    offlineMachinesOpen = !offlineMachinesOpen;
    _saveSoon();
    _changed();
  }

  String get _path => '/api/super-tabs/${Uri.encodeComponent(tabId)}';
  SuperTabConversation? get selected => snapshot?.conversation(selectedId);
  bool get isOwner => snapshot?.ownerId == accountId;
  bool get canWrite =>
      !_disposed &&
      !accessRevoked &&
      (snapshot?.people.where((p) => p.id == accountId).firstOrNull?.canWrite ??
          false);
  bool get hasPendingAction => _pending != null;
  Map<String, dynamic>? get pendingCommand =>
      _pending == null ? null : superTabMap(_pending!['command']);
  String draft(String id) => _drafts[id] ?? '';

  /// The files waiting to go with the next message in a conversation. They
  /// stay in memory: only the text of a draft is saved.
  HarnessAttachments attachments(String id) =>
      _attachments.putIfAbsent(id, () => _newFiles(id, id));

  /// The files waiting to go, for the next controller of this Swarm: bytes are
  /// never saved, so the running app hands them on ([SuperTabClient.release]).
  /// Nothing once access has gone.
  SuperTabKeptFiles get keptFiles => (
    chats: {
      if (!accessRevoked)
        for (final MapEntry(key: id, value: files) in _attachments.entries)
          if (!files.isEmpty) id: files.files,
    },
    threads: {
      if (!accessRevoked)
        for (final MapEntry(key: thread, value: files)
            in _threadAttachments.entries)
          if (!files.isEmpty) thread: files.files,
    },
  );

  /// Takes the files the last controller of this Swarm left ([keptFiles]). The
  /// first read lets go of those for a conversation no longer read.
  void adoptFiles(SuperTabKeptFiles kept) {
    for (final MapEntry(key: id, value: files) in kept.chats.entries) {
      attachments(id).add(files);
    }
    for (final MapEntry(key: thread, value: files) in kept.threads.entries) {
      threadAttachments(thread.$1, thread.$2).add(files);
    }
  }

  /// The files waiting to go with the next reply of [root]'s thread in
  /// [conversationId]. Like [attachments], they stay in memory, and they are
  /// forgotten with the thread when access to the conversation goes.
  HarnessAttachments threadAttachments(String conversationId, String root) =>
      _threadAttachments.putIfAbsent((
        conversationId,
        root,
      ), () => _newFiles(conversationId, (conversationId, root)));

  /// An empty set of files for a message to [conversationId] whose upload
  /// failures are kept under [errorKey].
  HarnessAttachments _newFiles(String conversationId, Object errorKey) {
    final files = HarnessAttachments(
      limitBytes: kSuperTabAttachmentMaxBytes,
      limitFiles: kSuperTabAttachmentMaxFiles,
      // A heavier file stays on disk until it goes, straight to storage.
      readUpTo: kSuperTabFormAttachmentMaxBytes,
    );
    files.addListener(() {
      // Changing the files answers a refused upload.
      if (_uploadErrors.remove(errorKey) != null) _changed();
      // Taking a chip off while its files go up gives the upload up.
      if (uploading &&
          identical(_sending?.owner, files) &&
          !files.files.toSet().containsAll(_sending!.files)) {
        cancelUpload();
      }
    });
    return files;
  }

  /// Whether [file] is still on its way to the backend in a send.
  bool isUploading(HarnessAttachment file) =>
      uploading && !_uploaded.containsKey(file);

  /// How much of [file] has gone up, from 0 to 1, while it is going up.
  double? uploadProgress(HarnessAttachment file) => _progress[file];

  SuperTabAgent? terminalAgent(String conversationId) {
    return terminalAgents(conversationId).firstOrNull;
  }

  List<SuperTabAgent> terminalAgents(String conversationId) {
    if (accessRevoked || devicesSelected) return const [];
    final id = _terminals[conversationId];
    if (id == null) return const [];
    // An agent asked for by name, as its card's Open terminal asks: an older
    // one a project chat still holds is not among the panes the chat opens.
    final group = snapshot?.conversation(conversationId);
    if (id != '*' && group?.agentIds.contains(id) == true) {
      final panes = snapshot!.paneAgentIds(conversationId);
      if (!panes.contains(id)) {
        return snapshot!.agents.where((agent) => agent.id == id).toList();
      }
    }
    final panes = snapshot?.paneAgentIds(conversationId) ?? const <String>[];
    if (panes.isEmpty) return const [];
    return snapshot!.agents.where((agent) => panes.contains(agent.id)).toList();
  }

  /// Whether [conversationId]'s terminals are open as a group ([term]).
  bool groupTerminalsOpen(String conversationId) =>
      !accessRevoked && !devicesSelected && _terminals[conversationId] == '*';

  void selectGroupTerminals(String conversationId) {
    if (_disposed ||
        accessRevoked ||
        snapshot?.conversation(conversationId) == null) {
      return;
    }
    _terminals[conversationId] = '*';
    _moveView();
    _saveSoon();
    _changed();
  }

  void selectTerminal(String conversationId, String? agentId) {
    if (_disposed || accessRevoked) return;
    if (agentId != null &&
        snapshot?.conversation(conversationId)?.agentIds.contains(agentId) !=
            true) {
      return;
    }
    if (_terminals[conversationId] == agentId && !devicesSelected) {
      return;
    }
    _moveView();
    if (agentId == null) {
      _terminals.remove(conversationId);
    } else {
      _terminals[conversationId] = agentId;
    }
    _saveSoon();
    _changed();
  }

  /// The original [messageId] of a reply in [id] whose page is not read:
  /// read by itself the first time it is asked for. Null until it is known;
  /// a record holding null when the conversation no longer has it.
  ({SuperTabMessage? message})? quoted(String id, String messageId) {
    final known = _quoted[id];
    if (known != null && known.containsKey(messageId)) {
      return (message: known[messageId]);
    }
    if (!(_quoting[id] ??= {}).containsKey(messageId)) {
      _quoting[id]![messageId] = 0;
      scheduleMicrotask(() => _readQuoted(id, messageId));
    }
    return null;
  }

  /// Whether the original [messageId] of [id] could not be read after every
  /// try, so it is told apart from one still being read.
  bool quoteGaveUp(String id, String messageId) =>
      (_quoting[id]?[messageId] ?? 0) >= _quoteTries;

  /// What the backend last said of each project's GitHub access (backend github/projectAccess.ts), and when.
  final Map<String, ({SuperTabProjectGitHub value, DateTime at})> _github = {};
  final Set<String> _githubReading = {};

  /// When each project's GitHub access was last asked for, answered or not: a failed read is not asked again on every
  /// rebuild either.
  final Map<String, DateTime> _githubAsked = {};

  /// The project's GitHub revision each read was asked at ([SuperTabProject.githubRevision]): another one in the
  /// Swarm read means the access may have changed, so it is read again at once (task #2316).
  final Map<String, int> _githubRevisionAsked = {};

  /// Whether teammates' agents can push to [projectId]'s repository, as last read; null before a read, or from a
  /// server too old to say.
  SuperTabProjectGitHub? githubAccessOf(String projectId) =>
      _github[projectId]?.value;

  /// Reads [projectId]'s GitHub access, at most every 5 minutes unless the project's GitHub revision moved since the
  /// last read (someone allowed its repository or installed the app: read again at once); [refresh]: a person checks
  /// again (the server asks GitHub at once, at most every 15 seconds per repository, and records the answer). A moved
  /// revision asks GitHub again too, since another server may still keep "not installed", but records nothing. An
  /// older server has no such read: nothing is shown.
  Future<void> readGitHubAccess(
    String projectId, {
    bool refresh = false,
  }) async {
    final revision =
        snapshot?.projects
            .where((p) => p.id == projectId)
            .firstOrNull
            ?.githubRevision ??
        0;
    final readAt = _githubRevisionAsked[projectId];
    // Read again because the revision moved: asks GitHub again, but records nothing (`record=0`), so servers whose caches
    // differ cannot move it back and forth (review of #2713). A person's own check records.
    final moved = !refresh && readAt != null && readAt != revision;
    final asked = _githubAsked[projectId];
    if (_disposed ||
        accessRevoked ||
        (!refresh &&
            !moved &&
            asked != null &&
            clock.now().difference(asked) < const Duration(minutes: 5))) {
      return;
    }
    // A read already out finishes first; the revision it was asked at still differs, so the next call reads again.
    if (!_githubReading.add(projectId)) return;
    _githubAsked[projectId] = clock.now();
    _githubRevisionAsked[projectId] = revision;
    try {
      final answer = await request(
        'GET',
        '$_path/projects/${Uri.encodeComponent(projectId)}/github${refresh
            ? '?refresh=1'
            : moved
            ? '?refresh=1&record=0'
            : ''}',
      );
      _github[projectId] = (
        value: SuperTabProjectGitHub.fromJson(answer),
        at: clock.now(),
      );
      _changed();
    } catch (error) {
      appLog.debug('super-tabs', 'project GitHub access not read: $error');
      // A server without the route (an older backend) shows nothing, as before. Any other failure says it could not
      // check, and is asked again after 30 seconds, not 5 minutes: a Swarm read in its first seconds came back
      // empty and Project details showed no GitHub access at all (2026-10-28).
      final absent =
          error is SuperTabFailure &&
          (error.statusCode == 404 || error.code == 'NOT_FOUND');
      if (absent || _github[projectId] == null) {
        _github[projectId] = (
          value: SuperTabProjectGitHub.fromJson({
            'state': absent ? 'unavailable' : 'unread',
          }),
          at: clock.now(),
        );
      }
      if (!absent) {
        _githubAsked[projectId] = clock.now().subtract(
          const Duration(minutes: 5) - const Duration(seconds: 30),
        );
      }
      _changed();
    } finally {
      _githubReading.remove(projectId);
    }
  }

  /// Starts approving [projectId]'s repository for teammates' agents ([scope] `project`, or `swarm` for every project):
  /// the links that sign the person in to GitHub through the Harness GitHub App, or install it there first. GitHub sends
  /// them back to the backend, which checks they can push to the repository (backend github/approvals.ts).
  Future<({String authorizeUrl, String? installUrl})> approveGitHub(
    String projectId,
    String scope,
  ) async {
    final answer = await request(
      'POST',
      '$_path/projects/${Uri.encodeComponent(projectId)}/github/approve',
      body: {'scope': scope},
    );
    return (
      authorizeUrl: answer['authorizeUrl'] as String,
      installUrl: answer['installUrl'] as String?,
    );
  }

  /// Reads one message of [id] only: the backend checks the reader may read
  /// that conversation, as for its pages. A refusal is recorded as the message
  /// being gone; any other failure is read again after 3 s and 6 s, then left
  /// ([quoteGaveUp]).
  Future<void> _readQuoted(String id, String messageId) async {
    if (_disposed ||
        accessRevoked ||
        snapshot?.conversation(id) == null ||
        _quoting[id]?.containsKey(messageId) != true) {
      return;
    }
    try {
      final answer = await request(
        'GET',
        '${_messagesPath(id)}?messageId=${Uri.encodeComponent(messageId)}',
      );
      if (_disposed ||
          accessRevoked ||
          snapshot?.conversation(id) == null ||
          _quoting[id]?.containsKey(messageId) != true) {
        return;
      }
      final rows = (answer['messages'] as List)
          .map((m) => SuperTabMessage.fromJson(superTabMap(m)))
          .toList();
      if (rows.length > 1 ||
          rows.any((m) => m.id != messageId || m.conversationId != id)) {
        return;
      }
      // A row the list never lists is no original to quote either.
      (_quoted[id] ??= {})[messageId] = rows.where(_listed).firstOrNull;
      _changed();
    } catch (failure) {
      _quoteFailed(id, messageId, failure);
    }
  }

  void _quoteFailed(String id, String messageId, Object failure) {
    final asked = _quoting[id];
    if (_disposed || asked == null || !asked.containsKey(messageId)) return;
    if (failure is SuperTabFailure &&
        const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
      (_quoted[id] ??= {})[messageId] = null;
      _changed();
      return;
    }
    final tries = asked[messageId] = asked[messageId]! + 1;
    if (tries >= _quoteTries) {
      _changed();
      return;
    }
    late final Timer retry;
    retry = Timer(_quoteRetryAfter * tries, () {
      _quoteRetries.remove(retry);
      unawaited(_readQuoted(id, messageId));
    });
    _quoteRetries.add(retry);
  }

  /// [root]'s thread summary in conversation [id], once a page named it.
  SuperTabThread? thread(String id, String root) => _threads[id]?[root];

  /// Whether [thread] has a reply the reader has not seen, from someone else,
  /// in a thread they wrote in or were tagged in.
  bool threadUnread(SuperTabThread thread) {
    final last = thread.authors.firstOrNull;
    return thread.people.contains(accountId) &&
        thread.lastSequence > threadReadMark(thread.id) &&
        !(last?['kind'] == 'person' && last?['id'] == accountId);
  }

  /// How far the reader has read [root]'s thread: the higher of this
  /// device's mark and the server's, from any of their devices (backend
  /// readMarks.ts), which reads a thread opened only elsewhere as read here.
  int threadReadMark(String root) =>
      max(_threadSeen[root] ?? 0, _serverThreadMark(root));

  /// The server's thread marks by root, from the snapshot's by conversation;
  /// worked out again only when a read brings new ones.
  Map<String, Map<String, int>>? _threadMarksFrom;
  var _threadMarksByRoot = const <String, int>{};

  int _serverThreadMark(String root) {
    final marks = snapshot?.threadMarks;
    if (marks == null || marks.isEmpty) return 0;
    if (!identical(marks, _threadMarksFrom)) {
      _threadMarksFrom = marks;
      _threadMarksByRoot = {for (final threads in marks.values) ...threads};
    }
    return _threadMarksByRoot[root] ?? 0;
  }

  void _keepThreads(String id, Object? rows) {
    if (rows is! List) return;
    final held = _threads[id] ??= {};
    for (final row in rows) {
      final thread = SuperTabThread.fromJson(superTabMap(row));
      if ((held[thread.id]?.lastSequence ?? -1) > thread.lastSequence) continue;
      held[thread.id] = thread;
      // A thread first seen here is read as far as the conversation is,
      // here or on another device: replies the reader passed before threads
      // were counted stay read.
      _threadSeen.putIfAbsent(
        thread.id,
        () => min(readMark(id), thread.lastSequence),
      );
      if (openedThread?.root == thread.id) _seeThread(thread.id);
    }
  }

  void _seeThread(String root) {
    if (_threadUnshown) return;
    final open = openedThread;
    final last = max(
      (open == null ? null : _threads[open.conversationId]?[root])
              ?.lastSequence ??
          0,
      threadMessages(root).lastOrNull?.sequence ?? 0,
    );
    if (open != null &&
        open.root == root &&
        !accessRevoked &&
        last > 0 &&
        snapshot?.conversation(open.conversationId) != null) {
      _serverThreadMarks.mark(
        (open.conversationId, root),
        last,
        kept: snapshot?.threadMarks[open.conversationId]?[root] ?? 0,
      );
    }
    if ((_threadSeen[root] ?? 0) >= last) return;
    // Moved to the end: the newest marks are the ones a save keeps.
    _threadSeen.remove(root);
    _threadSeen[root] = last;
    _saveSoon();
  }

  /// [root]'s thread in [conversationId] was read through [sequence] outside
  /// the thread pane (the Threads view): kept here and sent to the server,
  /// so it reads as read on every device. Nothing once access is gone.
  void markThreadRead(String conversationId, String root, int sequence) {
    if (_disposed ||
        accessRevoked ||
        sequence <= 0 ||
        snapshot?.conversation(conversationId) == null) {
      return;
    }
    _serverThreadMarks.mark(
      (conversationId, root),
      sequence,
      kept: snapshot?.threadMarks[conversationId]?[root] ?? 0,
    );
    if ((_threadSeen[root] ?? 0) >= sequence) return;
    _threadSeen.remove(root);
    _threadSeen[root] = sequence;
    _saveSoon();
    _changed();
  }

  /// The root and replies of [root]'s thread in the selected conversation,
  /// oldest first: what its own read brought, and replies polled since.
  List<SuperTabMessage> threadMessages(String root) {
    final id = openedThread?.conversationId ?? selectedId;
    final rows = {
      for (final m in _threadRows[root] ?? const <SuperTabMessage>[]) m.id: m,
      for (final m in _messages[id] ?? const <SuperTabMessage>[])
        if (m.thread == root) m.id: m,
    };
    return rows.values.toList()..sort(superTabMessageOrder);
  }

  /// The thread [messageId] is in, from the rows held of [id].
  String? _threadOf(String id, String? messageId) {
    if (messageId == null) return null;
    for (final m in [
      ..._messages[id] ?? const <SuperTabMessage>[],
      for (final rows in _threadRows.values) ...rows,
    ]) {
      if (m.id == messageId) return m.thread;
    }
    return null;
  }

  /// Forgets what was read of threads in conversations [keep] refuses (all,
  /// without it), as the transcript is forgotten when access goes.
  void _forgetThreads([bool Function(String conversationId)? keep]) {
    bool gone(String id) => keep == null || !keep(id);
    _openThreads.removeWhere((id, _) => gone(id));
    _threads.removeWhere((id, _) => gone(id));
    final roots = {
      for (final MapEntry(key: root, value: rows) in _threadRows.entries)
        if (rows.any((m) => gone(m.conversationId))) root,
    };
    _threadRows.removeWhere((root, _) => roots.contains(root));
    _threadBefore.removeWhere((root, _) => roots.contains(root));
    final forgotten = <HarnessAttachments>[];
    _threadAttachments.removeWhere((key, files) {
      if (!gone(key.$1)) return false;
      forgotten.add(files);
      return true;
    });
    for (final files in forgotten) {
      // Files on their way for a conversation that is gone are given up.
      if (identical(_sending?.owner, files)) cancelUpload();
      files.dispose();
    }
    _uploadErrors.removeWhere(
      (key, _) => key is (String, String) && gone(key.$1),
    );
    _threadMentions.removeWhere((key, _) => gone(key.$1));
    if (openedThread case final open? when gone(open.conversationId)) {
      openedThread = null;
    }
  }

  /// Whether [root]'s thread has replies before those read.
  bool hasEarlierReplies(String root) => _threadBefore.containsKey(root);
  bool readingEarlierReplies = false;

  /// Lets go of the empty file sets of threads that are not open, which only
  /// reading a thread's reply box made.
  void _pruneThreadFiles() {
    final open = openedThread;
    _threadAttachments.removeWhere((key, files) {
      // A picker, drop or paste still reading for a box will add to it.
      if (!files.isEmpty ||
          files.isReading ||
          (key.$1 == open?.conversationId && key.$2 == open?.root) ||
          identical(_sending?.owner, files)) {
        return false;
      }
      files.dispose();
      return true;
    });
  }

  /// Opens [root]'s thread of the selected conversation beside the chat.
  /// [shown] false opens it with its pane not on screen (the dial opened it
  /// in a background tab): nothing reads until [threadPaneShown].
  /// [at] names a reply to open the thread at, lit, as a link to it does.
  void openThread(String root, {bool shown = true, String? at}) {
    if (accessRevoked) return;
    openedThread = (conversationId: selectedId, root: root);
    _rememberOpenThread(selectedId, root);
    _reopenThread = false;
    threadTarget = at == null ? null : (root: root, messageId: at);
    _threadUnshown = !shown;
    _pruneThreadFiles();
    _seeThread(root);
    _saveSoon();
    _changed();
    unawaited(loadThread());
  }

  void closeThread() {
    if (openedThread == null) return;
    _openThreads.remove(selectedId);
    openedThread = null;
    _reopenThread = false;
    threadTarget = null;
    _pruneThreadFiles();
    _saveSoon();
    _changed();
  }

  /// Drops a restored thread when its root can no longer be read.
  void _discardOpenThread(({String conversationId, String root}) open) {
    _openThreads.remove(open.conversationId);
    if (openedThread != open) return;
    openedThread = null;
    threadTarget = null;
    _threadUnshown = false;
    _reopenThread = false;
    _pruneThreadFiles();
    _saveSoon();
    _changed();
  }

  String threadDraft(String root) => _threadDrafts[root] ?? '';
  void setThreadDraft(String root, String text, {String? conversationId}) {
    // Removed first, so the newest is last and the cap in [_localState] keeps it.
    _threadDrafts.remove(root);
    if (text.isEmpty) {
      _threadDraftConversations.remove(root);
    } else {
      _threadDrafts[root] = text;
      _threadDraftConversations[root] =
          conversationId ??
          (openedThread?.root == root ? openedThread!.conversationId : null) ??
          _threadDraftConversations[root] ??
          selectedId;
    }
    // A tag the text no longer says is no longer picked.
    for (final MapEntry(key: thread, value: tags) in _threadMentions.entries) {
      if (thread.$2 == root) {
        tags.removeWhere((_, token) => !containsMention(text, token));
      }
    }
    _threadMentions.removeWhere((_, tags) => tags.isEmpty);
    _saveSoon();
  }

  /// The tags picked in the reply box of [root]'s thread in [conversationId].
  Map<String, String> threadMentions(String conversationId, String root) =>
      Map.unmodifiable(_threadMentions[(conversationId, root)] ?? const {});

  /// [id] picked as [token] in the open thread's reply box, or [to]'s (the
  /// Threads view), while its draft says it.
  void threadMention(
    String id,
    String token, {
    ({String conversationId, String root})? to,
  }) {
    final open = to ?? openedThread;
    if (open == null || accessRevoked) return;
    if (!containsMention(threadDraft(open.root), token)) return;
    (_threadMentions[(open.conversationId, open.root)] ??= {})[id] = token;
    _changed();
  }

  /// How many pages a thread reads when it opens; past them "Show earlier
  /// replies" reads on, a page at a time.
  static const threadPagesOnOpen = 5;

  /// The read of earlier replies under way ([readingEarlierReplies]).
  Future<void>? _earlierRead;

  /// Reads the open thread: from its newest reply back through
  /// [threadPagesOnOpen] pages, or with [earlier] the page before those read,
  /// and its root when no page brought it. With [earlier] while a read of
  /// them is under way, that read: a caller waiting for the page gets it.
  Future<void> loadThread({bool earlier = false}) {
    if (earlier && readingEarlierReplies) {
      return _earlierRead ?? Future.value();
    }
    final read = _loadThread(earlier: earlier);
    if (earlier) _earlierRead = read;
    return read;
  }

  Future<void> _loadThread({bool earlier = false}) async {
    final open = openedThread;
    if (open == null || _disposed || accessRevoked) return;
    if (earlier && (!hasEarlierReplies(open.root) || readingEarlierReplies)) {
      return;
    }
    final path = _messagesPath(open.conversationId);
    final thread = Uri.encodeQueryComponent(open.root);
    // Still open, still readable: an answer that comes back after access went
    // or the thread closed is not kept.
    bool current() =>
        !_disposed &&
        !accessRevoked &&
        openedThread == open &&
        snapshot?.conversation(open.conversationId) != null;
    List<SuperTabMessage> rowsOf(Map<String, dynamic> page) => [
      for (final row in page['messages'] as List)
        if (SuperTabMessage.fromJson(superTabMap(row)) case final m
            when m.conversationId == open.conversationId &&
                (m.thread == open.root || m.id == open.root))
          m,
    ];
    readingEarlierReplies = earlier;
    try {
      final rows = {
        if (earlier)
          for (final m in _threadRows[open.root] ?? const <SuperTabMessage>[])
            m.id: m,
      };
      Map<String, dynamic>? from = earlier ? _threadBefore[open.root] : null;
      Object? threads;
      for (var page = 0; page < (earlier ? 1 : threadPagesOnOpen); page++) {
        final answer = await request(
          'GET',
          from == null
              ? '$path?thread=$thread'
              : '$path?thread=$thread&before=${from['sequence']}&beforeId=${Uri.encodeQueryComponent(from['id'] as String)}',
        );
        if (!current()) return;
        threads ??= answer['threads'];
        for (final m in rowsOf(answer)) {
          rows[m.id] = m;
        }
        from = answer['next'] is Map ? superTabMap(answer['next']) : null;
        if (from == null) break;
      }
      // A long thread's pages read so far start after its root.
      if (!rows.containsKey(open.root) &&
          !(_messages[open.conversationId] ?? const []).any(
            (m) => m.id == open.root,
          )) {
        final root = await request(
          'GET',
          '$path?messageId=${Uri.encodeQueryComponent(open.root)}',
        );
        if (!current()) return;
        for (final m in rowsOf(root)) {
          if (m.id == open.root) rows[m.id] = m;
        }
      }
      if (!rows.containsKey(open.root) &&
          !(_messages[open.conversationId] ?? const []).any(
            (m) => m.id == open.root,
          )) {
        _discardOpenThread(open);
        return;
      }
      _threadRows[open.root] = rows.values.toList();
      if (from == null) {
        _threadBefore.remove(open.root);
      } else {
        _threadBefore[open.root] = from;
      }
      _keepThreads(open.conversationId, threads);
      _seeThread(open.root);
      _changed();
    } catch (failure) {
      if (!current()) return;
      if (failure case SuperTabFailure(:final code)
          when const {'FORBIDDEN', 'NOT_FOUND'}.contains(code)) {
        _discardOpenThread(open);
        return;
      }
      _readFailure(failure, revokeTab: false);
      _changed();
    } finally {
      if (earlier) readingEarlierReplies = false;
    }
  }

  /// Sends the open thread's draft and files to its root, or [to]'s (the
  /// Threads view replies without opening the thread); [alsoSend] shows it in
  /// the main stream too. [onSending] is told when the reply is on its way,
  /// which is after its files have gone up.
  Future<Map<String, dynamic>?> sendThreadReply({
    bool alsoSend = false,
    bool newSession = false,
    VoidCallback? onSending,
    ({String conversationId, String root})? to,
    bool plain = false,
    List<String> recipients = const [],
  }) async {
    final open = to ?? openedThread;
    if (open == null || accessRevoked) return null;
    final text = threadDraft(open.root).trim();
    final owner = threadAttachments(open.conversationId, open.root);
    final files = owner.files;
    final group = snapshot?.conversation(open.conversationId);
    if ((text.isEmpty && files.isEmpty) ||
        group == null ||
        group.archived ||
        !canWrite ||
        uploading ||
        saving ||
        _pending != null) {
      return null;
    }
    final thread = (open.conversationId, open.root);
    // The tags as picked when sent: the box may take new ones meanwhile.
    final picked = Map<String, String>.of(_threadMentions[thread] ?? const {});
    final (:tagged, :addressed) = _tagsSaid(picked, text);
    // The thread's own chat: a reply from the Threads view goes to a chat
    // that may not be the one selected, or none may be.
    final failure = addressed.any((id) => !group.agentIds.contains(id))
        ? 'A mentioned agent is no longer in this conversation. Remove its mention or choose another agent.'
        // Only its own session hears a session's thread (backend
        // routeBuddySession): another agent's tag there would be refused.
        : addressed.isNotEmpty &&
              (newSession || threadSession(open.root) != null)
        ? 'Only this thread\'s session hears a reply here. Remove the agent\'s mention.'
        : null;
    if (failure != null) {
      _failOperation(
        failure,
        command: {'conversationId': open.conversationId, 'replyTo': open.root},
      );
      _changed();
      return null;
    }
    final ids = await _uploadAll(open.conversationId, owner, thread);
    if (ids == null) return null;
    final before = _pending;
    final operationId = superTabOperationId();
    final sending = command(operationId: operationId, {
      'type': 'message.send',
      'conversationId': open.conversationId,
      'text': text,
      // With [plain], a message of [to]'s conversation, not a reply in a thread.
      'replyTo': plain ? null : open.root,
      'recipientIds': addressed.isEmpty ? recipients : addressed,
      if (tagged.isNotEmpty) 'mentions': tagged,
      // A session's thread stays in the thread: never also sent.
      if (alsoSend && !newSession) 'alsoSend': true,
      if (newSession) 'newSession': true,
      if (ids.isNotEmpty) 'attachmentIds': ids,
      // As the chat's own send: the server refuses it in an earlier chat.
      if (oneBuddy) 'oneBuddy': true,
    });
    if (_pending case final pending? when !identical(pending, before)) {
      _sendingMentions[pending['operationId'] as String] = picked;
      // Only a draft still holding what went: more may have been typed since.
      if (_threadDrafts[open.root]?.trim() == text) {
        _threadDrafts.remove(open.root);
        _threadDraftConversations.remove(open.root);
        _threadMentions.remove(thread);
      }
      onSending?.call();
      _changed();
    }
    final result = await sending;
    _forgetRefusedUploads(result);
    if (result == null && newSession) {
      _restoreSessionRefusal(open.conversationId, open.root, operationId);
    }
    return result;
  }

  /// A message the server refused only for New session goes back into its
  /// box (the thread of [root], or the chat's own when null), ready to send
  /// without it, when nothing was typed there since and it carries no files;
  /// else it stays Not sent, and its Retry goes without New session.
  void _restoreSessionRefusal(
    String conversationId,
    String? root,
    String operationId,
  ) {
    final kept = _refused[conversationId];
    final i = kept?.indexWhere((r) => r.operationId == operationId) ?? -1;
    if (i < 0) return;
    final refused = kept![i];
    final files = refused.command['attachmentIds'];
    if (refused.error != superTabSessionsUnavailable ||
        (files is List && files.isNotEmpty) ||
        (root == null ? draft(conversationId) : threadDraft(root))
            .trim()
            .isNotEmpty) {
      return;
    }
    kept.removeAt(i);
    if (kept.isEmpty) _refused.remove(conversationId);
    _sendOrder.remove(operationId);
    final text = refused.command['text'] as String? ?? '';
    if (root == null) {
      _drafts[conversationId] = text;
      if (refused.mentions.isNotEmpty) {
        _mentions[conversationId] = refused.mentions;
      }
    } else {
      _threadDrafts[root] = text;
      _threadDraftConversations[root] = conversationId;
      if (refused.mentions.isNotEmpty) {
        _threadMentions[(conversationId, root)] = refused.mentions;
      }
    }
    unawaited(
      _persist().catchError((Object _) {
        error = 'Could not save this change on this computer.';
        _changed();
      }),
    );
    _changed();
  }

  // ── Buddy thread sessions (spec 2026-10-30-buddy-thread-sessions) ───────

  /// When the server last refused a reply's New session as a field it does not
  /// know, though it said it takes them (one of its servers older during a
  /// release): New session is not offered for [_sessionsRefusedFor] after.
  DateTime? _sessionsRefusedAt;
  static const _sessionsRefusedFor = Duration(minutes: 10);

  /// Whether this Swarm's server takes New session: it says so in its reads,
  /// and has not just refused one.
  bool get _serverTakesThreadSessions {
    if (snapshot?.threadSessions != true) return false;
    final refused = _sessionsRefusedAt;
    return refused == null ||
        clock.now().difference(refused) >= _sessionsRefusedFor;
  }

  /// The open thread's chat when it is the reader's own Buddy chat, where a
  /// thread may have a session of its own; null anywhere else.
  SuperTabConversation? get _ownBuddyChat =>
      _ownBuddyChatOf(openedThread?.conversationId ?? selectedId);

  /// Chat [id] when it is the reader's own Buddy chat; null anywhere else.
  SuperTabConversation? _ownBuddyChatOf(String id) {
    final chat = snapshot?.conversation(id);
    return chat != null &&
            chat.isBuddyChat &&
            chat.buddyOwnerId == accountId &&
            !accessRevoked
        ? chat
        : null;
  }

  /// Whether the selected chat's own composer shows New session: the reader's
  /// own Buddy chat, with a Buddy, on a server that takes New session on a
  /// top-level message. It may still show disabled, saying why
  /// ([threadSessionBlocked]).
  bool get offersChatSessions {
    final chat = _ownBuddyChatOf(selectedId);
    return chat != null &&
        snapshot?.sessionsFromChat == true &&
        _serverTakesThreadSessions &&
        buddy(chat.projectId) != null;
  }

  /// Whether the open chat's thread composer shows New session: the reader's
  /// own Buddy chat, with a Buddy, or in [root]'s thread that had a session
  /// (its reply must start a new one). It may still show disabled, saying why
  /// ([threadSessionBlocked]).
  bool offersThreadSessions([String? root]) {
    final chat = _ownBuddyChat;
    if (chat == null || !_serverTakesThreadSessions) return false;
    return buddy(chat.projectId) != null || (root != null && _hadSession(root));
  }

  /// Why the open Buddy chat cannot start a session now, as the disabled
  /// choice says it; null when it can, as far as this computer can tell (the
  /// server still decides, and its refusal shows in the composer).
  String? get threadSessionBlocked {
    final chat = _ownBuddyChat;
    if (chat == null) return null;
    if (snapshot?.paused == true) return 'New work is paused in this Swarm';
    final main = buddy(chat.projectId);
    if (main == null || main.downSince != null) return 'Start your Buddy first';
    if (main.engine != 'claude') return 'Sessions need a Claude Code Buddy';
    // The host says what it can run in its report; a machine this computer
    // has no report of is left to the server.
    final pool = snapshot?.pool(main.machineId);
    final observation = pool?['observation'];
    if (observation is Map) {
      final capabilities = observation['capabilities'];
      if (capabilities is! List || !capabilities.contains('buddySessions')) {
        return 'Update Harness on ${sessionMachineName(main.machineId) ?? 'your Buddy\'s computer'} to start sessions';
      }
    }
    return null;
  }

  /// The Swarm's name for [machineId], as people read it; null when unknown.
  String? sessionMachineName(String machineId) {
    final name = snapshot?.pool(machineId)?['name'];
    return name is String && name.isNotEmpty ? superTabMachineName(name) : null;
  }

  /// Whether [root]'s thread has a reply from or to a thread session.
  bool _hadSession(String root) =>
      threadMessages(root).any((m) => m.buddySession);

  /// The live or starting session answering [root] in the reader's own Buddy
  /// chat; null when none does, or anywhere else.
  SuperTabBuddySession? threadSession(String root) =>
      _ownBuddyChat?.sessionFor(root);

  /// The session agent of [session], once it started.
  SuperTabAgent? sessionAgent(SuperTabBuddySession session) =>
      session.agentId == null ? null : snapshot?.agent(session.agentId!);

  /// The row saying [root]'s last session ended (its ended line, else its
  /// last session reply), while no session answers there: a plain reply
  /// would be refused, so a new one must start. Any session reply locks it,
  /// ended line or not.
  SuperTabMessage? threadSessionEnded(String root) {
    if (_ownBuddyChat == null || threadSession(root) != null) return null;
    final messages = threadMessages(root);
    return messages.where((m) => m.sessionEnded).lastOrNull ??
        messages.where((m) => m.buddySession).lastOrNull;
  }

  /// Ends [root]'s session in the reader's own Buddy chat. Closing the thread
  /// pane only hides it; this stops it. False when refused or not sent.
  Future<bool> endThreadSession(String root) async {
    final chat = _ownBuddyChat;
    if (chat == null || chat.sessionFor(root) == null) return false;
    return await command({
          'type': 'buddy.sessionEnd',
          'conversationId': chat.id,
          'thread': root,
          'reason': 'ended',
        }) !=
        null;
  }

  List<SuperTabMessage> messages(String id) => List.unmodifiable(
    (_messages[id] ?? const <SuperTabMessage>[]).where(_listed),
  );

  /// What [messages] lists, newest first, read lazily from what is held: no
  /// copy, so a caller that stops at the first it needs reads only that far.
  /// For a read on every build (the Buddy bar's Start again, task #3256): a
  /// copy of a long held history there made each rebuild slower. Read it
  /// before the next change to what is held, as within one build.
  Iterable<SuperTabMessage> newestFirst(String id) =>
      (_messages[id] ?? const <SuperTabMessage>[]).reversed.where(_listed);

  static bool _listed(SuperTabMessage m) =>
      m.source['kind'] != 'update-request' &&
      !m.terminalPrompt &&
      !m.terminalGap &&
      !m.instructionsSave;

  /// [id]'s messages with its steps' rows merged in by time (task steps
  /// design): each step keeps its own conversation, shown inside its task.
  List<SuperTabMessage> taskMessages(String id) {
    final state = snapshot;
    final task = state?.conversation(id);
    final steps = state == null || task == null
        ? const <SuperTabConversation>[]
        : superTabStepsOf(state, task);
    if (steps.isEmpty) return messages(id);
    // Merged from the rows held, as they are held: an unchanged chat is the
    // same list, not sorted again on each of a build's reads of it.
    final merged = (_merges[id] ??= SuperTabStepsMerge()).of(
      _messages[id] ?? const [],
      {for (final step in steps) step.id: _messages[step.id] ?? const []},
    );
    return merged.every(_listed)
        ? merged
        : List.unmodifiable(merged.where(_listed));
  }

  final _merges = <String, SuperTabStepsMerge>{};

  /// A number that moves when [id] or one of its steps has something new.
  int? taskProgress(String id) {
    final state = snapshot;
    final task = state?.conversation(id);
    if (state == null || task == null) return null;
    return superTabStepsOf(state, task).fold<int>(
      task.lastMessageSequence,
      (sum, step) => sum + step.lastMessageSequence,
    );
  }

  /// Reads a task that is not the selected conversation, with its steps.
  Future<void> loadTaskMessages(String id) async {
    await loadMessages(id);
    if (!_disposed) _readSteps(id, light: false);
  }

  /// The name of the step [message] was written in; null for a task's own.
  String? stepNameOf(SuperTabMessage message) {
    final group = snapshot?.conversation(message.conversationId);
    return group != null && superTabIsStep(group)
        ? superTabStepName(group)
        : null;
  }

  /// [group]'s linked tasks with their checks' results ([superTabLinkedLine]);
  /// null without any.
  String? linkedLine(SuperTabConversation? group) {
    final state = snapshot;
    return group == null || state == null
        ? null
        : superTabLinkedLine(state, group);
  }

  bool hasOlder(String id) => _before[id] != null;

  /// Conversations whose reader is scrolled up ([readingBack]).
  final _readingBack = <String>{};

  /// Conversations with messages after the newest held that no read has
  /// brought yet ([hasNewer]).
  final _newer = <String>{};

  /// Conversations whose next read takes the latest page whole
  /// ([showLatest]).
  final _latestWanted = <String>{};

  /// How many pages joined below the rows of a reader scrolled up, by
  /// conversation.
  final _pagesBelow = <String, int>{};

  /// At most this many pages join below a reader scrolled up: past them the
  /// rest waits for [showLatest], so a long burst is not all held.
  static const _pagesBelowReader = 3;

  /// Whether [id]'s reader is scrolled up with all the pages that join below
  /// them held: the rest waits for [showLatest], so no poll reads it.
  bool _holding(String id) =>
      _readingBack.contains(id) &&
      _newer.contains(id) &&
      !_latestWanted.contains(id) &&
      (_pagesBelow[id] ?? 0) >= _pagesBelowReader;

  /// Forgets reading back in [id], or in every conversation.
  void _forgetNewer([String? id]) {
    for (final kept in [_readingBack, _newer, _latestWanted]) {
      id == null ? kept.clear() : kept.remove(id);
    }
    id == null ? _pagesBelow.clear() : _pagesBelow.remove(id);
  }

  /// The reader of [id] scrolled up, or back to its end. While they read
  /// back, a read that finds more than a page new keeps the rows they are
  /// reading and adds the next page below; [showLatest] reads the rest.
  void readingBack(String id, bool reading) =>
      reading ? _readingBack.add(id) : _readingBack.remove(id);

  /// Whether more messages came after the newest held than reads brought.
  bool hasNewer(String id) => _newer.contains(id);

  /// Brings [id]'s newest messages: when more are waiting than reads
  /// brought, or [replace] asks it, the latest page replaces what is held;
  /// otherwise what came after it is read. Its own read: one already under
  /// way may have asked for less (the rows held below a reader scrolled up).
  /// [replace] is Jump to latest from far up (task #3630): the rows read back
  /// go, and earlier history is read again from the latest page.
  Future<void> showLatest(String id, {bool replace = false}) async {
    _readingBack.remove(id);
    for (
      var under = _reading[(id, false)];
      under != null;
      under = _reading[(id, false)]
    ) {
      await under;
    }
    if (_disposed) return;
    if (replace || _newer.contains(id)) _latestWanted.add(id);
    await _readMessages(id);
  }

  /// At most this many older pages are read to reach a reader's read mark;
  /// past them the page just after the mark is read instead.
  static const _pagesToMark = 3;

  /// Whether [id]'s held messages reach back to [mark], or nothing older is
  /// left to read.
  bool heldBackTo(String id, int mark) {
    final held = _messages[id];
    return held == null ||
        held.isEmpty ||
        held.first.sequence <= mark ||
        !hasOlder(id);
  }

  /// Holds [id]'s messages back to the reader's [mark], so its first unread
  /// is among them: older pages while the mark is at most [_pagesToMark]
  /// pages back, else the page just after it alone, with the newer ones
  /// waiting for [showLatest] as under a reader scrolled up. Whether they
  /// reach it now; a read that failed throws, and nothing counts as read.
  /// A try again after one failed passes [olderPages] 0: the pages read the
  /// first time stay, and it goes straight to the page after the mark.
  Future<bool> loadBackTo(String id, int mark, {int? olderPages}) async {
    for (var page = 0; page < (olderPages ?? _pagesToMark); page++) {
      if (_disposed || heldBackTo(id, mark)) return heldBackTo(id, mark);
      await _readMessages(id, older: true);
    }
    if (_disposed || heldBackTo(id, mark)) return heldBackTo(id, mark);
    return _readAfterMark(id, mark);
  }

  /// Moves when a read back replaces what a conversation holds: a read of
  /// newer messages that set out before then would join across the gap.
  final _heldGeneration = <String, int>{};

  /// Replaces what [id] holds with the page just after [mark]; whether it
  /// did. A read of newer messages under way finishes first, and one that
  /// sets out meanwhile is dropped when it lands ([_heldGeneration]).
  Future<bool> _readAfterMark(String id, int mark) async {
    for (
      var under = _reading[(id, false)];
      under != null;
      under = _reading[(id, false)]
    ) {
      await under;
    }
    if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {
      return false;
    }
    final answer = await request('GET', '${_messagesPath(id)}?after=$mark');
    if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {
      return false;
    }
    final rows = answer['messages'] as List;
    final page = [
      for (final row in rows) SuperTabMessage.fromJson(superTabMap(row)),
    ]..sort(superTabMessageOrder);
    // Nothing after the mark: everything held is read.
    if (page.isEmpty) return true;
    if (page.any((m) => m.conversationId != id)) {
      throw const FormatException('A different conversation was returned.');
    }
    _heldGeneration[id] = (_heldGeneration[id] ?? 0) + 1;
    // Read up to the page's end, not past it: the polls join the next pages.
    _readMessageSeq.remove(id);
    _rows.remove(id);
    _keepRows(id, rows);
    _messages[id] = page;
    _staleHeld.remove(id);
    _before[id] = SuperTabPage.of(page.first);
    if (answer['next'] != null) {
      _readingBack.add(id);
      _newer.add(id);
      _pagesBelow[id] = 1;
    }
    _viewVersion++;
    _changed();
    return true;
  }

  /// Each conversation's reaction counter as its last page said it.
  final _reactionSeq = <String, int>{};

  /// The newest message held for [id] that reading the chat reads: one in
  /// its main stream. A reply only in its thread is read in that thread, as in
  /// Slack, so the chat's mark stops short of it and the thread stays unread
  /// (backend read/inbox.ts counts replies past the chat's mark). From a
  /// server before main-stream numbers, any row, as before.
  int _loadedMessageSequence(String id) {
    final mainOnly = snapshot?.conversation(id)?.lastMainSequence != null;
    return _messages[id]?.reversed
            .where(
              (m) =>
                  m.source['kind'] != 'update-request' &&
                  (!mainOnly || m.inMainStream),
            )
            .firstOrNull
            ?.sequence ??
        0;
  }

  /// How far the reader has read [id]: the higher of the mark kept on the
  /// server, from any of their devices, and this device's own, which stands
  /// in while the server is out of reach.
  int readMark(String id) =>
      max(_readAt[id] ?? 0, snapshot?.readMarks[id] ?? 0);

  /// A fresh short-lived link to one file of one message (backend
  /// fileLinks.ts), answered only while the reader may read that message.
  Future<SuperTabAttachment> readFileLink(
    String conversationId,
    String messageId,
    String attachmentId,
  ) async => SuperTabAttachment.fromJson(
    superTabMap(
      superTabMap(
        await request(
          'GET',
          '$_path/conversations/${Uri.encodeComponent(conversationId)}'
              '/messages/${Uri.encodeComponent(messageId)}'
              '/attachments/${Uri.encodeComponent(attachmentId)}',
        ),
      )['attachment'],
    ),
  );

  late final _serverMarks = SuperTabReadMarkSender<String>(
    (id, sequence) => request(
      'POST',
      '$_path/conversations/${Uri.encodeComponent(id)}/read',
      body: {'sequence': sequence},
    ),
  );

  /// Sends the marks of threads read here, by conversation and root. A server
  /// without thread marks refuses them; this device's own mark stands, and a
  /// refused mark waits a minute before it is tried again.
  late final _serverThreadMarks = SuperTabReadMarkSender<(String, String)>(
    (thread, sequence) => request(
      'POST',
      '$_path/conversations/${Uri.encodeComponent(thread.$1)}'
          '/threads/${Uri.encodeComponent(thread.$2)}/read',
      body: {'sequence': sequence},
    ),
    retryAfter: const Duration(minutes: 1),
    now: clock.now,
  );

  /// Whether [group] has a message in its main stream past the reader's
  /// mark. A reply only in its thread leaves the chat as it was: it lights its
  /// thread's reply line instead ([threadUnread]). The server's newest
  /// main-stream message covers a chat not held here; an older server's
  /// newest message, and the newest held, stand in for it.
  /// Held through the server's newest message, the rows held say it, so a
  /// row the chat does not list (a terminal's prompt) is nothing new.
  bool unread(SuperTabConversation group) {
    final held = _messages[group.id];
    final heldAll =
        held != null &&
        held.isNotEmpty &&
        held.last.sequence >= group.lastMessageSequence;
    return max(
          heldAll ? 0 : group.lastMainSequence ?? group.lastMessageSequence,
          held?.reversed
                  .where((m) => _listed(m) && m.inMainStream)
                  .firstOrNull
                  ?.sequence ??
              0,
        ) >
        readMark(group.id);
  }

  void start() {
    if (_disposed) return;
    _startedAt = _lastActivity = clock.now();
    unawaited(refresh());
    _schedule();
  }

  /// [after] is what is left of the poll once a read took the rest of it.
  void _schedule([Duration? after]) {
    _poll?.cancel();
    if (_disposed || updateRequired || pollInterval <= Duration.zero) return;
    if (!_policy.adapts) {
      _poll = Timer.periodic(_every, (_) {
        if (_pollDue && !_restsHidden) unawaited(refresh());
        _checkReceipt();
      });
      return;
    }
    if (accessRevoked || (_policy.pausesAway && _away)) return;
    final wait = after ?? _every;
    _poll = Timer(
      wait > Duration.zero ? wait : Duration.zero,
      () => unawaited(_tick()),
    );
  }

  /// One adaptive poll: the full read when it is due, else only the open
  /// conversation's new messages and its own unsettled receipt. The next one
  /// comes a poll after this one began, however long its answer took.
  Future<void> _tick() async {
    final began = clock.now();
    if (_pollDue) {
      // Told of a change: the whole Swarm, not only the open conversation.
      await (_fullReadDue || _toldMain || _toldMachine
          ? refresh()
          : _readMessages(selectedId, light: true));
    }
    _checkReceipt();
    _schedule(_every - clock.now().difference(began));
  }

  bool get _fullReadDue {
    final quiet = _policy.quietPoll;
    if (quiet == null || snapshot == null || _refreshFailing) return true;
    final now = clock.now();
    if (now.difference(_lastActivity) < _policy.quietAfter) return true;
    final last = _lastFullRead;
    return last == null || now.difference(last) >= quiet;
  }

  void _acted() => _lastActivity = clock.now();

  /// Drops the messages held of each conversation left [_keepLeft] ago.
  /// Kept for now: one being read, which would land on nothing and lose where
  /// earlier history continues, and one whose unread count its held messages
  /// give, which would read "1" until read again.
  void _dropLeft() {
    final now = clock.now();
    _leftAt.removeWhere((id, left) {
      if (id == selectedId) return true;
      final group = snapshot?.conversation(id);
      if (now.difference(left) < _keepLeft ||
          _reading.keys.any((read) => read.$1 == id) ||
          (group != null && unreadCount(group) > 1)) {
        return false;
      }
      _messages.remove(id);
      _staleHeld.remove(id);
      _rows.remove(id);
      _before.remove(id);
      _quoted.remove(id);
      _quoting.remove(id);
      _reactionSeq.remove(id);
      _readMessageSeq.remove(id);
      _forgetNewer(id);
      return true;
    });
  }

  /// How many rows of [id] are kept for the saved view.
  @visibleForTesting
  int heldRows(String id) => _rows[id]?.length ?? 0;

  void _keepRows(String id, List rows) {
    if (!_policy.drawsSaved) return;
    _recentChats
      ..remove(id)
      ..insert(0, id);
    final kept = _rows[id] ??= {};
    for (final row in rows) {
      final map = superTabMap(row);
      kept[map['id'] as String] = map;
    }
  }

  /// The view to keep on this device ([SuperTabReading.drawsSaved]): the
  /// Swarm's parts as last read, with the cursor the next read starts at,
  /// and the open conversation's last page; or null.
  Map<String, dynamic>? get savedView {
    final parts = _parts, readAt = _partsReadAt;
    if (!_policy.drawsSaved ||
        parts == null ||
        readAt == null ||
        accessRevoked ||
        _showingSaved) {
      return null;
    }
    final id = selectedId;
    final shown = _messages[id] ?? const <SuperTabMessage>[];
    final page = shown.length > _savedPage
        ? shown.sublist(shown.length - _savedPage)
        : shown;
    final rows = [for (final message in page) ?_rows[id]?[message.id]];
    return {
      if (_savedChatsOf(id) case final chats when chats.isNotEmpty)
        'chats': chats,
      'format': superTabReadFormat,
      'savedAt': readAt.millisecondsSinceEpoch,
      'lastChangedAt': lastChangedAt,
      'parts': parts.toJson(),
      'conversationId': id,
      'messages': rows,
      'next': page.length < shown.length
          ? SuperTabPage.of(page.first).toJson()
          : _before[id]?.toJson(),
    };
  }

  /// A conversation's page as the backend reads it.
  static const _savedPage = 100;

  /// How many other chats a saved view keeps the last rows of, newest read first, and how many rows of each: every chat then
  /// opens from this device, and its first read replaces them (Quiet Swarm, Speed). Inside the view, so they are this account's
  /// alone and go when it does; one over its limit drops the oldest chats first ([SuperTabSavedViews.write]).
  static const _savedChats = 5, _savedChatRows = 30;

  /// The chats this device read, newest first.
  final _recentChats = <String>[];

  List<Map<String, dynamic>> _savedChatsOf(String open) {
    final chats = <Map<String, dynamic>>[];
    for (final id in _recentChats) {
      if (chats.length == _savedChats) break;
      final shown = _messages[id];
      if (id == open ||
          shown == null ||
          shown.isEmpty ||
          snapshot?.conversation(id) == null)
        continue;
      final page = shown.length > _savedChatRows
          ? shown.sublist(shown.length - _savedChatRows)
          : shown;
      final rows = [for (final message in page) ?_rows[id]?[message.id]];
      if (rows.isNotEmpty) {
        chats.add({
          'id': id,
          'messages': rows,
          'next': SuperTabPage.of(page.first).toJson(),
        });
      }
    }
    return chats;
  }

  /// Draws the other chats of a saved view, each only if the saved state lists it and all its rows are its own; a broken one is
  /// skipped. Each one's first read takes the latest page whole, as the saved page may be short of what came since.
  void _drawSavedChats(Object? chats, SuperTabSnapshot saved, String open) {
    if (chats is! List) return;
    // Saved newest first, and each one drawn goes to the front.
    for (final chat in chats.reversed) {
      try {
        final map = superTabMap(chat);
        final id = map['id'] as String;
        if (id == open || saved.conversation(id) == null) continue;
        final rows = [
          for (final row in map['messages'] as List) superTabMap(row),
        ];
        final messages = rows.map(SuperTabMessage.fromJson).toList();
        if (messages.isEmpty || messages.any((m) => m.conversationId != id))
          continue;
        _messages[id] = messages..sort(superTabMessageOrder);
        _keepRows(id, rows);
        _before[id] = SuperTabPage.read(map['next']);
        _latestWanted.add(id);
      } on FormatException {
        continue;
      } on TypeError {
        continue;
      }
    }
  }

  /// What the first read says this reader no longer has: its kept chats go with it.
  void _dropLostChats() {
    final state = snapshot;
    if (state == null) return;
    for (final id in _messages.keys.toList()) {
      if (id == selectedId || state.conversation(id) != null) continue;
      _messages.remove(id);
      _rows.remove(id);
      _before.remove(id);
      _latestWanted.remove(id);
      _recentChats.remove(id);
    }
  }

  /// How long a saved view's cursor is good for: the backend keeps
  /// tombstones 7 days and reloads older cursors an hour before that.
  static const _savedFor = Duration(days: 6, hours: 23);

  /// Draws a [savedView] kept from an earlier visit while the first read is
  /// on its way, and holds its parts: the first read asks only for what
  /// changed since, and replaces it. With [SuperTabReading.confirmsSaved] and
  /// not [SuperTabReading.drawsSavedAtOnce] it only holds them, for that read
  /// to draw. One for another Swarm, one too
  /// old for its cursor, one that no longer parses, or one after a read has
  /// landed or been refused, draws nothing.
  void drawSaved(Map<String, dynamic> view) {
    if (!_policy.drawsSaved ||
        accessRevoked ||
        snapshot != null ||
        stateReads > 0) {
      return;
    }
    try {
      if (view['format'] != superTabReadFormat) return;
      final savedAt = DateTime.fromMillisecondsSinceEpoch(
        (view['savedAt'] as num).toInt(),
      );
      if (clock.now().difference(savedAt) >= _savedFor) return;
      final parts = SuperTabParts.fromJson(superTabMap(view['parts']));
      final saved = SuperTabSnapshot.fromJson(parts.state);
      if (saved.id != tabId) return;
      final id = view['conversationId'];
      final rows = [
        for (final row in view['messages'] as List? ?? const [])
          superTabMap(row),
      ];
      final messages = rows.map(SuperTabMessage.fromJson).toList();
      final changedAt = (view['lastChangedAt'] as num).toInt();
      if (_policy.confirmsSaved && !_policy.drawsSavedAtOnce) {
        // Held for the first read to start from, drawn once it answers; the
        // conversation it showed is read beside it.
        _parts = parts;
        _partsReadAt = savedAt;
        if (id == selectedId) _savedSelection = true;
        return;
      }
      snapshot = saved;
      lastChangedAt = changedAt;
      _parts = parts;
      _partsReadAt = savedAt;
      if (id == selectedId &&
          saved.conversation(id as String) != null &&
          messages.every((m) => m.conversationId == id)) {
        _messages[id] = messages..sort(superTabMessageOrder);
        _dropShownSends(id);
        _keepRows(id, rows);
        _before[id] = SuperTabPage.read(view['next']);
      }
      _drawSavedChats(view['chats'], saved, id is String ? id : selectedId);
      _showingSaved = true;
      loading = false;
      if (_startedAt != null) _changed();
    } on FormatException {
      _dropSaved();
    } on TypeError {
      _dropSaved();
    }
  }

  /// A view from an older shape: draw nothing, read as usual.
  void _dropSaved() {
    snapshot = null;
    lastChangedAt = -1;
    _parts = null;
    _partsReadAt = null;
    _messages.clear();
    _staleHeld.clear();
    _quoted.clear();
    _quoting.clear();
    _forgetThreads();
    _rows.clear();
    _before.clear();
  }

  /// A machine able to serve Swarm reads just connected: read now instead of
  /// at the next poll ([SuperTabReading.readsOnConnect]). Joins a read under way.
  Future<void> machineAvailable() {
    if (!_policy.readsOnConnect ||
        _disposed ||
        accessRevoked ||
        (_policy.pausesAway && _away)) {
      return Future.value();
    }
    return refresh();
  }

  void _changed() {
    if (!_disposed) notifyListeners();
  }

  /// Open dialogs and native panes lose their content immediately, before
  /// account cleanup waits for an in-flight read or a draft write.
  ///
  /// With [keepSaved] (Desktop), what is saved on this computer stays as it
  /// was: this account's own refused, unsent and unconfirmed messages are
  /// there for its next sign-in (saved state is kept per account), and an
  /// unconfirmed one is checked against the backend by its receipt id then.
  /// The web clears what an account leaves behind, so it keeps nothing.
  void revokeAccess(String message, {bool keepSaved = false}) {
    if (_disposed) return;
    if (keepSaved) {
      _pruneSendOrder();
      _savedAtRevoke ??=
          jsonDecode(jsonEncode(_localState())) as Map<String, dynamic>;
    }
    accessRevoked = true;
    devicesSelected = false;
    _forgetClosedShipped();
    _forgetAttention();
    error = message;
    snapshot = null;
    _showingSaved = false;
    _parts = null;
    _messages.clear();
    _staleHeld.clear();
    _forgetNewer();
    _quoted.clear();
    _quoting.clear();
    _forgetThreads();
    _sent.clear();
    _sendIdentities.clear();
    _pending = null;
    _sendingMentions.clear();
    _refused.clear();
    _sendOrder.clear();
    for (final queued in _queuedSends) {
      queued.result.complete(null);
    }
    _queuedSends.clear();
    _poll?.cancel();
    // A file on its way stops: a large one would go on to storage for an
    // account that no longer reads this Swarm.
    cancelUpload();
    _changed();
  }

  Map<String, dynamic> _localState() => {
    'tabId': tabId,
    'accountId': accountId,
    'selectedId': selectedId,
    'expandedMachines': expandedMachines.toList(),
    'decisionsAside': _decisionsAside.toList(),
    'devicesSelected': devicesSelected,
    'unreadOnly': unreadOnly,
    'machinesGroupOpen': machinesGroupOpen,
    'buddiesGroupOpen': buddiesGroupOpen,
    'agentsGroupOpen': agentsGroupOpen,
    'modelsGroupOpen': modelsGroupOpen,
    'offlineMachinesOpen': offlineMachinesOpen,
    'sessionProjectId': sessionProjectId,
    'drafts': Map<String, String>.of(_drafts),
    'terminals': Map<String, String>.of(_terminals),

    'mentions': {
      for (final entry in _mentions.entries)
        entry.key: Map<String, String>.of(entry.value),
    },
    'readAt': Map<String, int>.of(_readAt),
    // ponytail: the newest 500 threads' marks; an older one forgotten shows
    // read again through the conversation's read mark ([_keepThreads]).
    'threadSeen': Map<String, int>.fromEntries(
      _threadSeen.entries.skip(max(0, _threadSeen.length - 500)),
    ),
    if (_openThreads.isNotEmpty)
      'openThreads': Map<String, String>.of(_openThreads),
    if (openedThread case final open?)
      'openThread': {'conversationId': open.conversationId, 'root': open.root},
    // ponytail: the newest 500, as threadSeen.
    if (_threadDrafts.isNotEmpty)
      'threadDrafts': {
        for (final MapEntry(key: root, value: text)
            in _threadDrafts.entries.skip(max(0, _threadDrafts.length - 500)))
          if (_threadDraftConversations[root] case final conversation?)
            root: {
              'conversationId': conversation,
              'text': text,
              if (_threadMentions[(conversation, root)] case final tags?)
                'mentions': Map<String, String>.of(tags),
            },
      },
    if (_pending != null) 'pending': _pending,
    if (_sendOrder.isNotEmpty) 'sendOrder': List<String>.of(_sendOrder),
    if (_refused.isNotEmpty || _queuedSends.isNotEmpty)
      'refused': {
        for (final key in {
          ..._refused.keys,
          ..._queuedSends.map((q) => q.command['conversationId'] as String),
        })
          key: [
            for (final refused in _refused[key] ?? const <_Refused>[])
              {
                'operationId': refused.operationId,
                'command': refused.command,
                'mentions': refused.mentions,
                'error': refused.error.isEmpty ? _unsentReason : refused.error,
                if (refused.error.isEmpty) _unsentKey: true,
              },
            // Persist unsent queue entries in the existing recovery format:
            // older clients also retain their text and require explicit Retry.
            for (final queued in _queuedSends)
              if (queued.command['conversationId'] == key)
                {
                  'operationId': queued.operationId,
                  'command': queued.command,
                  'mentions': _sendingMentions[queued.operationId] ?? const {},
                  'error': _unsentReason,
                  _unsentKey: true,
                },
          ],
      },
  };

  /// The state saved once access is revoked ([revokeAccess]): every later
  /// write, an autosave queued before or a send answering after, writes it, so
  /// the emptied screen never overwrites what this account kept here.
  Map<String, dynamic>? _savedAtRevoke;

  void _pruneSendOrder() {
    final active = {
      if (_pending != null) _pending!['operationId'],
      ..._sent.keys,
      for (final refused in _refused.values)
        ...refused.map((r) => r.operationId),
      ..._queuedSends.map((q) => q.operationId),
    };
    _sendOrder.removeWhere((id) => !active.contains(id));
  }

  Future<void> _persist() {
    if (_savedAtRevoke == null) _pruneSendOrder();
    // Serial writes prevent an older autosave from restoring a resolved receipt.
    final next = _persisting
        .catchError((Object _) {})
        .then((_) => save(_savedAtRevoke ?? _localState()));
    _persisting = next;
    return next;
  }

  void _saveSoon() {
    _draftSave?.cancel();
    _draftSave = Timer(const Duration(milliseconds: 200), () {
      unawaited(
        _persist().catchError((Object _) {
          error = 'Could not save this draft on this computer.';
          _changed();
        }),
      );
    });
  }

  void setDraft(String conversationId, String value) {
    _acted();
    _drafts[conversationId] = value;
    _mentions[conversationId]?.removeWhere(
      (_, token) => !containsMention(value, token),
    );
    _saveSoon();
  }

  /// The tags of [picked] that [text] still says: a person's is a tag, an
  /// agent's makes it a recipient.
  ({List<String> tagged, List<String> addressed}) _tagsSaid(
    Map<String, String> picked,
    String text,
  ) {
    final said = picked.entries
        .where((entry) => containsMention(text, entry.value))
        .map((entry) => entry.key);
    bool isPerson(String id) => snapshot?.people.any((p) => p.id == id) == true;
    return (
      tagged: said.where(isPerson).toList(),
      addressed: said.where((id) => !isPerson(id)).toList(),
    );
  }

  static bool containsMention(String text, String token) =>
      RegExp('(?:^|\\s)${RegExp.escape(token)}(?=\$|\\s|[.,!?;:])')
          .hasMatch(text);

  void mention(String conversationId, String agentId, String token) {
    if (containsMention(draft(conversationId), token)) {
      (_mentions[conversationId] ??= {})[agentId] = token;
      _saveSoon();
      _changed();
    }
  }

  /// What the reader sent to conversation [id] that its transcript does not
  /// hold yet, oldest first.
  List<SuperTabOutgoing> outgoing(String id) {
    final held = {for (final m in _messages[id] ?? const []) m.id};
    // The receipts of what is on its way that a read already brought.
    final onTheirWay = _onTheirWay;
    final arrived = {for (final messageId in held) ?onTheirWay[messageId]};
    SuperTabOutgoing of(
      Map<String, dynamic> command,
      SuperTabOutgoingState state, {
      String? operationId,
      String? error,
    }) => SuperTabOutgoing(
      conversationId: id,
      text: command['text'] as String? ?? '',
      replyTo: command['replyTo'] as String?,
      thread: _threadOf(id, command['replyTo'] as String?),
      alsoSend: command['alsoSend'] == true,
      state: state,
      operationId: operationId,
      error: error,
      confirmedAt: command['confirmedAt'] as String?,
    );
    final pending = _pending,
        command = pending == null
            ? const <String, dynamic>{}
            : superTabMap(pending['command']);
    final rows = <SuperTabOutgoing>[
      for (final refused in _refused[id] ?? const <_Refused>[])
        of(
          refused.command,
          SuperTabOutgoingState.refused,
          operationId: refused.operationId,
          // Left unsent at close: Not sent says it all.
          error: refused.error.isEmpty ? null : refused.error,
        ),
      for (final MapEntry(key: messageId, value: sent) in _sent.entries)
        if (sent['conversationId'] == id && !held.contains(messageId))
          of(
            sent,
            SuperTabOutgoingState.confirmed,
            operationId: messageIdentity(messageId),
          ),
      // The backend names a person's message by a hash of its send's
      // receipt, so one read back before its answer is not shown twice.
      if (command['type'] == 'message.send' &&
          command['conversationId'] == id &&
          !arrived.contains(pending!['operationId']))
        of(
          command,
          saving
              ? SuperTabOutgoingState.sending
              : SuperTabOutgoingState.unconfirmed,
          operationId: pending['operationId'] as String?,
        ),
      for (final queued in _queuedSends)
        if (queued.command['conversationId'] == id &&
            !arrived.contains(queued.operationId))
          of(
            queued.command,
            SuperTabOutgoingState.sending,
            operationId: queued.operationId,
          ),
    ];
    int order(SuperTabOutgoing row) =>
        _sendOrder.indexOf(row.operationId ?? '');
    rows.sort((a, b) => order(a).compareTo(order(b)));
    return rows;
  }

  /// Sends failed [message] again: one with no answer under its own receipt
  /// id, so it is posted once; a refused one as it was, tags and reply too.
  Future<Map<String, dynamic>?> retryOutgoing(SuperTabOutgoing message) async {
    if (message.state == SuperTabOutgoingState.unconfirmed) {
      return _pending?['operationId'] == message.operationId ? retry() : null;
    }
    if (saving || _pending != null) return null;
    final refused = _takeRefused(message);
    if (refused == null) return null;
    _sendingMentions[refused.operationId] = refused.mentions;
    _pending = {'operationId': refused.operationId, 'command': refused.command};
    return retry();
  }

  /// Removes failed [message] from its chat: a refused one, or one sent
  /// without an answer. The second may have arrived after all; then the next
  /// read shows it, once.
  void discardOutgoing(SuperTabOutgoing message) {
    final command = _pending == null
        ? const <String, dynamic>{}
        : superTabMap(_pending!['command']);
    final unconfirmed =
        message.state == SuperTabOutgoingState.unconfirmed &&
        !saving &&
        command['type'] == 'message.send' &&
        _pending!['operationId'] == message.operationId;
    if (!unconfirmed && _takeRefused(message) == null) return;
    if (unconfirmed) {
      _sendingMentions.remove(_pending!['operationId']);
      _pending = null;
    }
    _sendOrder.remove(message.operationId);
    operationError = null;
    operationErrorCode = null;
    unawaited(
      _persist().catchError((Object _) {
        error = 'Could not save this change on this computer.';
        _changed();
      }),
    );
    _changed();
  }

  Map<String, String> mentions(String conversationId) =>
      Map.unmodifiable(_mentions[conversationId] ?? const {});

  /// Makes conversation [id] part of [snapshot]: one not held (a closed
  /// group a link or Work details names) is read by id. False when it cannot
  /// be read.
  Future<bool> loadGroup(String id) async {
    if (snapshot == null) return false;
    if (snapshot!.conversation(id) != null) return true;
    final parts = _parts;
    try {
      if (parts == null || !await _readGroup(parts, id)) return false;
    } catch (failure) {
      _readFailure(failure, revokeTab: false);
      _changed();
      return false;
    }
    _redraw();
    return !_disposed && snapshot?.conversation(id) != null;
  }

  /// When group [groupId] last changed, a message included (parts.dart
  /// `groupChangedAt`); null for one this reader does not hold.
  DateTime? groupChangedAt(String groupId) =>
      switch (_parts?.groupChangedAt(groupId)) {
        final int at => DateTime.fromMillisecondsSinceEpoch(at),
        null => null,
      };

  /// [projectId]'s conversations, open and closed, in the snapshot's order.
  List<SuperTabConversation> projectConversations(String projectId) =>
      _indexed()?.byProject[projectId] ?? const [];

  /// [snapshot]'s conversations by project, and each project's [buddyChat],
  /// worked out once per snapshot: the sidebar asks for them on every
  /// rebuild, and a snapshot is replaced, never changed, when the Swarm moves.
  ({
    SuperTabSnapshot of,
    Map<String, List<SuperTabConversation>> byProject,
    Map<String, SuperTabConversation> buddyChats,
  })?
  _index;

  ({
    SuperTabSnapshot of,
    Map<String, List<SuperTabConversation>> byProject,
    Map<String, SuperTabConversation> buddyChats,
  })?
  _indexed() {
    final snapshot = this.snapshot;
    if (snapshot == null) return null;
    if (_index case final index? when identical(index.of, snapshot)) {
      return index;
    }
    final byProject = <String, List<SuperTabConversation>>{};
    final buddyChats = <String, SuperTabConversation>{};
    for (final g in snapshot.conversations) {
      byProject.putIfAbsent(g.projectId, () => []).add(g);
      if (g.isBuddyChat && g.buddyOwnerId == accountId) {
        // Of several Buddies (#3818) the default is the one the app opens; with none flagged, the first.
        if (g.buddyDefault) {
          buddyChats[g.projectId] = g;
        } else {
          buddyChats.putIfAbsent(g.projectId, () => g);
        }
      }
    }
    return _index = (
      of: snapshot,
      byProject: {
        for (final MapEntry(:key, :value) in byProject.entries)
          key: List.unmodifiable(value),
      },
      buddyChats: buddyChats,
    );
  }

  /// The key the reader's one Buddy for the whole Swarm goes by in [buddyChat],
  /// [buddy], [buddyStart], [addBuddy] and [removeBuddy]: its chat and agent
  /// belong to no project, as the Product Managers' conversation does (spec
  /// 2026-10-31-one-buddy-per-swarm).
  static const kSwarmBuddyKey = '';

  /// Whether this Swarm gives each person one Buddy for the whole Swarm: the
  /// sidebar's # buddy row in place of a Buddies section.
  bool get oneBuddy => snapshot?.swarmBuddy == true;

  /// Whether [group] is the reader's older Buddy chat in a project, where the
  /// Swarm gives one Buddy for the whole Swarm: its history reads here, and
  /// its person talks to their Buddy in # buddy (spec: history).
  bool isEarlierBuddyChat(SuperTabConversation? group) =>
      oneBuddy && group != null && group.isBuddyChat && !group.isSwarmBuddyChat;

  /// The signed-in person's chat with their Buddy in [projectId], where the
  /// PM's private lines to them land too: Buddies replaced Chat with PM in
  /// every Swarm (Ken, 10-29). It is there before any Buddy is
  /// ([openBuddyChat]), and stays after one is removed.
  SuperTabConversation? buddyChat(String projectId) =>
      _indexed()?.buddyChats[projectId];

  /// The signed-in person's Buddies, each its own chat (#3818), the default first ([buddyChat]); one, or none, from
  /// a backend before several Buddies.
  List<SuperTabConversation> buddies([String projectId = kSwarmBuddyKey]) {
    final first = buddyChat(projectId);
    return [
      ?first,
      for (final g in projectConversations(projectId))
        if (g.isBuddyChat && g.buddyOwnerId == accountId && g.id != first?.id)
          g,
    ];
  }

  /// The signed-in person's Buddy in [projectId]; null when they have none.
  /// Its main session only: a thread's own session is never "the Buddy".
  SuperTabAgent? buddy(String projectId) => snapshot?.agents
      .where(
        (a) =>
            a.isMainBuddy && a.buddyOf == accountId && a.projectId == projectId,
      )
      .firstOrNull;

  /// The newest start of the reader's Buddy in [projectId]: under way while
  /// it has neither a harness nor an error, failed with an error.
  Map<String, dynamic>? buddyStart(String projectId) {
    // The index itself: the sidebar has asked [buddyChat] once already.
    final chat = _indexed()?.buddyChats[projectId]?.id;
    return snapshot?.buddyStarts.reversed.where((start) {
      final request = superTabMap(start['request']);
      // A thread session's start is its thread's, never the Buddy's own.
      if (request['buddySession'] != null) return false;
      return superTabMap(request['buddyOf'])['personId'] == accountId &&
          (request['projectId'] == projectId ||
              (chat != null && request['conversationId'] == chat) ||
              // The one Buddy's start, before its chat is read here.
              (projectId == kSwarmBuddyKey &&
                  request['buddyScope'] == 'swarm'));
    }).firstOrNull;
  }

  /// Adds the reader's Buddy in [projectId] on [machineId] with [engine], and
  /// opens its chat. [setup] is sent for one of their own machines outside the
  /// Swarm (prepareBuddyMachine). False when refused: [operationError] says
  /// why.
  Future<bool> addBuddy({
    required String projectId,
    required String machineId,
    required String engine,
    Map<String, dynamic>? setup,
    String? name,
  }) async {
    final result = await command({
      'type': 'buddy.create',
      if (projectId != kSwarmBuddyKey) 'projectId': projectId,
      'machineId': machineId,
      'engine': engine,
      'setup': ?setup,
      // A name and no chat: a new Buddy in a chat of its own (#3818).
      'name': ?name,
    });
    if (result == null) return false;
    final id = result['conversationId'];
    if (id is String) await select(id);
    return true;
  }

  /// Removes the reader's Buddy in [projectId], or the one of [conversationId] of several (#3818); its chat stays.
  Future<bool> removeBuddy(String projectId, {String? conversationId}) async =>
      await command({
        'type': 'buddy.remove',
        if (conversationId != null)
          'conversationId': conversationId
        else if (projectId != kSwarmBuddyKey)
          'projectId': projectId,
      }) !=
      null;

  /// Makes the Buddy of [conversationId] the reader's default of several (#3818): it opens first and takes what is
  /// addressed to them. False when refused: [operationError] says why.
  Future<bool> setDefaultBuddy(String conversationId) async =>
      await command({
        'type': 'buddy.default',
        'conversationId': conversationId,
      }) !=
      null;

  /// Names the reader's Buddy in [projectId] from its chat, or clears the
  /// name for the default when [name] is empty. Everyone in the Swarm sees it.
  /// False when refused: [operationError] says why.
  Future<bool> renameBuddy(
    String projectId,
    String name, {
    String? conversationId,
  }) async {
    final chat = conversationId == null
        ? buddyChat(projectId)
        : snapshot?.conversation(conversationId);
    if (chat == null) return false;
    final trimmed = name.trim();
    return await command({
          'type': 'buddy.rename',
          'conversationId': chat.id,
          'name': trimmed.isEmpty ? null : trimmed,
        }) !=
        null;
  }

  /// Renames the agent [agentId] for everyone in the Swarm (backend
  /// `agent.rename`): only the person who runs it, or its machine's owner, may.
  /// Null once the server took it; otherwise why it did not.
  Future<String?> renameAgent(String agentId, String name) async {
    final done = await command({
      'type': 'agent.rename',
      'agentId': agentId,
      'name': name.trim(),
    });
    return done != null
        ? null
        : operationError ?? 'Another change is on its way. Try again.';
  }

  /// Moves [taskId] right after [after] in its project's shared Next up, or to
  /// its top when [after] is null, for everyone (backend taskQueue.ts). Null
  /// once the server took it; otherwise why it did not.
  Future<String?> queueTask(String taskId, {required String? after}) async {
    final done = await command({
      'type': 'work.queue',
      'conversationId': taskId,
      'after': after,
    });
    return done != null
        ? null
        : operationError ?? 'Another change is on its way. Try again.';
  }

  /// Sets task [taskId]'s priority for everyone (backend `work.priority`,
  /// task #3117): null once done, else why it was refused. Only a person or
  /// the project's PM may; an older server refuses the command as unknown.
  Future<String?> setTaskPriority(
    String taskId,
    SuperTabTaskPriority priority,
  ) async {
    final done = await command({
      'type': 'work.priority',
      'conversationId': taskId,
      'priority': priority.badge,
    });
    return done != null
        ? null
        : operationError ?? 'Another change is on its way. Try again.';
  }

  /// Pauses [taskId], or resumes it (#3819, a project on the Board): the server lets its project's owner, the Swarm's
  /// owner and its decider do it. Null when done, else the server's sentence.
  Future<String?> setTaskPaused(String taskId, {required bool paused}) async {
    // One command both ways: `work.resume` resumes lost work (#3819).
    final done = await command({
      'type': 'work.pause',
      'conversationId': taskId,
      'paused': paused,
    });
    return done != null
        ? null
        : operationError ?? 'Another change is on its way. Try again.';
  }

  /// Proposes work to [projectId] from its Board (#3817 `proposal.create`), for a person with or without a Buddy.
  /// Null when done, else the server's sentence (what is missing, or who may set P0).
  Future<String?> propose(
    String projectId, {
    required String title,
    required String goal,
    required String why,
    required String doneWhen,
    required List<String> evidence,
    required SuperTabTaskPriority priority,
  }) async {
    final done = await command({
      'type': 'proposal.create',
      'projectId': projectId,
      'title': title,
      // What the person wrote is the proposal's words: its goal.
      'text': goal,
      'goal': goal,
      'why': why,
      'doneWhen': doneWhen,
      'evidence': evidence,
      'priority': priority.badge,
    });
    return done != null
        ? null
        : operationError ?? 'Another change is on its way. Try again.';
  }

  /// Grants or takes back Can chat in [projectId] for [personId] (#3819 `project.canChat`): its owner or the Swarm's
  /// owner does. Null when done, else the server's sentence.
  Future<String?> setCanChat(
    String projectId,
    String personId, {
    required bool granted,
  }) async {
    final done = await command({
      'type': 'project.canChat',
      'projectId': projectId,
      'personId': personId,
      'granted': granted,
    });
    return done != null
        ? null
        : operationError ?? 'Another change is on its way. Try again.';
  }

  /// Whether the reader may write in [group]: in a project on the Board its chat takes only its owner, the Swarm's
  /// owner and people granted Can chat (#3819); everything else is as today.
  bool mayChatIn(SuperTabConversation? group) {
    if (group == null) return true;
    final project = snapshot?.projectById(group.projectId);
    if (project == null || project.leadConversationId != group.id) return true;
    return project.canChat(accountId, swarmOwner: isOwner);
  }

  /// Answers the question [questionId] the PM asked the reader on the card [conversationId] (#3817). Null when done,
  /// else the server's sentence.
  Future<String?> answerQuestion(
    String conversationId,
    String questionId,
    String text,
  ) async {
    final done = await command({
      'type': 'proposal.answer',
      'conversationId': conversationId,
      'questionId': questionId,
      'text': text,
    });
    return done != null
        ? null
        : operationError ?? 'Another change is on its way. Try again.';
  }

  /// Whether the reader may set P0 and pause or resume any task of [project] (spec "Who may do what on the Board").
  bool maySteer(SuperTabProject project) =>
      project.canSteer(accountId, swarmOwner: isOwner);

  /// Whether the reader may give [task] [priority]: anyone who may write, in a project not on the Board; on the
  /// Board, P1 to P3 on their own card, and anything when they steer ([maySteer]). The server decides (#3819).
  bool mayPrioritize(SuperTabConversation task, SuperTabTaskPriority priority) {
    if (!canWrite) return false;
    final project = snapshot?.projectById(task.projectId);
    if (project == null || !project.boardMode) return true;
    if (maySteer(project)) return true;
    return task.requesterId == accountId && priority != SuperTabTaskPriority.p0;
  }

  /// Moves the reader's one Buddy onto [gridModel], a model shared in the
  /// Swarm, or back to their own subscription when null (backend
  /// buddyModel.ts). Its machine carries it out; the Buddy's `modelRequest`
  /// shows it under way. False when refused: [operationError] says why.
  Future<bool> switchBuddyModel(String? gridModel) async =>
      await command({'type': 'buddy.model', 'gridModel': gridModel}) != null;

  /// Requests a handoff on the Buddy's own machine, keeping its chat and
  /// folder. The host's switchRequest remains visible until it settles.
  Future<bool> switchBuddyEngine(
    String engine, {
    String? conversationId,
  }) async =>
      await command({
        'type': 'buddy.engine',
        'engine': engine,
        'conversationId': ?conversationId,
      }) !=
      null;

  /// Whether [group] is out of the app: there is no private channel to the
  /// PM (Ken, 10-29), so no private chat but a Buddy chat is listed or opened,
  /// the reader's old Chat with PM that an older server still sends included.
  bool hiddenByBuddies(SuperTabConversation group) =>
      group.audience != null && !group.isBuddyChat && !group.isAgentChat;

  /// Where opening conversation [id] lands: itself, unless the app hides it.
  String landsOn(String id) => _shownFor(id);

  /// Where conversation [id] opens: a chat [hiddenByBuddies] opens its
  /// project's chat, where the PM is talked to; any other opens itself.
  String _shownFor(String id) {
    final group = snapshot?.conversation(id);
    if (group == null || !hiddenByBuddies(group)) return id;
    return snapshot!.projects
            .where((p) => p.id == group.projectId)
            .firstOrNull
            ?.leadConversationId ??
        id;
  }

  /// How many of [group]'s messages from others came after the reader's read
  /// mark: exact once the messages held reach back to the mark
  /// ([_heldSinceRead]), else a lower bound, one at least, while more are read
  /// ([_readUnreadBuddyChats]).
  int unreadCount(SuperTabConversation group) {
    if (!unread(group)) return 0;
    final readAt = readMark(group.id);
    final count = messages(group.id)
        .where((m) => m.sequence > readAt && m.inMainStream && !isOwn(m))
        .length;
    return _heldSinceRead(group) ? count : max(count, 1);
  }

  /// Whether [m] is the reader's own: written by them, not by an agent, a
  /// terminal or the server in their name.
  bool isOwn(SuperTabMessage m) =>
      !m.fromAgent &&
      !m.fromTerminal &&
      !m.postedForAuthor &&
      m.authorId == accountId;

  /// Whether what [id]'s main stream gained since sequence [after] is all the reader's own, sent from
  /// any device. Unsure is no: a message that can't be read is told about, never lost.
  Future<bool> onlyOwnSince(String id, int after) async {
    try {
      final answer = await request('GET', '${_messagesPath(id)}?after=$after');
      if (answer['next'] != null) return false;
      final main = (answer['messages'] as List)
          .map((row) => SuperTabMessage.fromJson(superTabMap(row)))
          .where((message) => message.inMainStream);
      return main.isNotEmpty && main.every(isOwn);
    } catch (_) {
      return false;
    }
  }

  /// Whether the messages held of [group] run from its read mark (or its
  /// first message) to its newest, update requests included.
  bool _heldSinceRead(SuperTabConversation group) {
    final held = _messages[group.id];
    if (held == null || held.isEmpty) return false;
    return held.last.sequence >= group.lastMessageSequence &&
        (held.first.sequence <= readMark(group.id) || !hasOlder(group.id));
  }

  /// The reader's Buddy chats that count toward the Swarm badge: the one
  /// Buddy's chat where the Swarm gives one Buddy for the whole Swarm (its
  /// older project Buddy chats are copies of its lines, so they never count
  /// twice), else each project's.
  Iterable<SuperTabConversation> get _countedBuddyChats sync* {
    if (oneBuddy) {
      if (buddyChat(kSwarmBuddyKey) case final chat?) yield chat;
      return;
    }
    for (final project in snapshot?.projects ?? const <SuperTabProject>[]) {
      if (buddyChat(project.id) case final chat?) yield chat;
    }
  }

  /// The unread messages in the reader's own Buddy chats, the PM's private
  /// lines among them, for the Swarm badge.
  int get buddyUnread => [
    for (final chat in _countedBuddyChats)
      // A muted chat never counts (Slack).
      if (notifyOf(chat.id) != SuperTabNotify.muted) unreadCount(chat),
  ].fold(0, (a, b) => a + b);

  /// Reads each Buddy chat whose count is still open ([_countOpen]), page by
  /// page, so the count is exact up to [kCountCap]; nothing once every chat's
  /// count is known.
  void _readUnreadBuddyChats() {
    for (final chat in _countedBuddyChats) {
      if (!_countOpen(chat) || !_counting.add(chat.id)) continue;
      unawaited(
        _countChat(chat.id).whenComplete(() {
          _counting.remove(chat.id);
        }),
      );
    }
  }

  final _counting = <String>{};

  /// A Buddy chat off screen, unread, under [kCountCap] and not held back to its
  /// read mark: past the cap the badge says "99+" whatever the rest holds, so
  /// a device with no read mark never reads the whole history.
  bool _countOpen(SuperTabConversation chat) =>
      chat.id != selectedId &&
      unread(chat) &&
      unreadCount(chat) < kCountCap &&
      !_heldSinceRead(chat);

  /// Newer pages until the newest message is held, then older ones back to
  /// the read mark; stops when a read brings nothing (no more, or it failed:
  /// the next state read tries again).
  Future<void> _countChat(String id) async {
    while (!_disposed) {
      final chat = snapshot?.conversation(id);
      if (chat == null || !_countOpen(chat)) return;
      final held = _messages[id];
      final before = (held?.firstOrNull?.sequence, held?.lastOrNull?.sequence);
      final newer =
          held == null ||
          held.isEmpty ||
          held.last.sequence < chat.lastMessageSequence;
      await _readMessages(id, older: !newer, light: newer);
      final after = _messages[id];
      if ((after?.firstOrNull?.sequence, after?.lastOrNull?.sequence) ==
          before) {
        return;
      }
    }
  }

  /// The project of the conversation on screen, else the first one.
  String? get currentProjectId {
    final state = snapshot;
    if (state == null) return null;
    final selected = state.conversation(selectedId)?.projectId;
    return state.projects.any((p) => p.id == selected)
        ? selected
        : state.projects.firstOrNull?.id;
  }

  /// A tag or decision the menu bar asked to open ([openNotice]), until the
  /// Swarm view on screen takes it.
  ({String kind, String id})? noticeRequest;

  /// Opens the reader's tag (`mention`) at its message, or shows their
  /// decisions (`decision`) where they are answered, in the view on screen,
  /// or the one shown next.
  void openNotice(String kind, String id) {
    noticeRequest = (kind: kind, id: id);
    notifyListeners();
  }

  /// The agent whose terminal a Waiting on you notice asked to open
  /// ([openAgentTerminal]), until the Swarm workspace on screen takes it.
  ({String agentId, String? conversationId})? agentTerminalRequest;

  /// Opens [agentId]'s terminal, focused, beside the chat it waits in
  /// ([conversationId] when the notice names one), in the workspace on screen
  /// or the one shown next.
  void openAgentTerminal(String agentId, {String? conversationId}) {
    agentTerminalRequest = (agentId: agentId, conversationId: conversationId);
    notifyListeners();
  }

  /// A message the reader asked to open by its link ([openMessageLink]), until
  /// the Swarm view on screen takes it.
  ({String conversationId, String messageId})? messageRequest;

  /// Asks the Swarm view to open [link]'s message, in the view on screen or
  /// the one shown next. A link to another Swarm is not this one's to open.
  bool openMessageLink(SwarmMessageLink link) {
    if (link.tabId != tabId) return false;
    messageRequest = (
      conversationId: link.conversationId,
      messageId: link.messageId,
    );
    notifyListeners();
    return true;
  }

  /// Conversations a link named that the Swarm did not hold, when each was
  /// last asked for by id (the backend decides who may read it) and which are
  /// being asked for now. A refusal is asked again after a minute, in case the
  /// reader has since been let in.
  final _linkGroupAsked = <String, DateTime>{};
  final _linkGroupReading = <String>{};
  static const _linkGroupRetry = Duration(minutes: 1);

  /// What [link] points at for this reader: null when it is not a message they
  /// may read (another Swarm, a conversation the backend will not give them, a
  /// message gone); `message` null while it is being read. A conversation the
  /// Swarm does not hold (a closed one) is asked for by id, once a minute at
  /// most, so a link reveals nothing the backend does not already let them read.
  ({SuperTabMessage? message})? linkTarget(SwarmMessageLink link) {
    final id = link.conversationId;
    if (link.tabId != tabId || accessRevoked || snapshot == null) return null;
    if (snapshot!.conversation(id) == null) {
      if (_linkGroupReading.contains(id)) return (message: null);
      final asked = _linkGroupAsked[id];
      if (asked != null && clock.now().difference(asked) < _linkGroupRetry) {
        return null;
      }
      _linkGroupAsked[id] = clock.now();
      _linkGroupReading.add(id);
      unawaited(
        loadGroup(id).whenComplete(() {
          _linkGroupReading.remove(id);
          _changed();
        }),
      );
      return (message: null);
    }
    // A chat the app hides (an old Chat with PM, with Buddies on) is not one
    // a link can open, so it is not previewed either.
    if (landsOn(id) != id) return null;
    final held = messages(id).where((m) => m.id == link.messageId).firstOrNull;
    final read = held != null ? (message: held) : quoted(id, link.messageId);
    // Still being read, unless every try failed.
    if (read == null) {
      return quoteGaveUp(id, link.messageId) ? null : (message: null);
    }
    final message = read.message;
    // A waiting notice is never announced, so it is not previewed either.
    return message == null || message.source['kind'] == 'delivery-hold'
        ? null
        : (message: message);
  }

  /// Set by the Swarm view on screen: opens a project's Buddy chat in front
  /// of whatever covers the conversation, Notifications or a terminal.
  Future<bool> Function(String projectId)? buddyChatOpener;

  /// Opens the [currentProjectId]'s Buddy chat, through the view on screen
  /// ([buddyChatOpener]) when there is one, else [openBuddyChat].
  Future<bool> openCurrentBuddyChat() async {
    final project = currentProjectId;
    return project != null && await (buddyChatOpener ?? openBuddyChat)(project);
  }

  /// Opens the reader's [buddyChat] in [projectId], opening it on the server
  /// first when they have none: every person has one in each project before
  /// any Buddy (backend buddy.chat), so the PM's private lines never drop.
  /// The request is one per person, membership and project, so a second click
  /// or another window gets the same chat back.
  Future<bool> openBuddyChat(String projectId) async {
    if (buddyChat(projectId) case final chat?) return select(chat.id);
    // Where the reader is now: the server may answer late, and by then they may have opened another chat or a terminal.
    final from = _selectRequest;
    final me = snapshot?.people.where((p) => p.id == accountId).firstOrNull;
    // The empty id is the reader's one Buddy chat for the Swarm (spec
    // 2026-10-31-one-buddy-per-swarm), which names no project.
    final result = await command({
      'type': 'buddy.chat',
      if (projectId != kSwarmBuddyKey) 'projectId': projectId,
    }, operationId: _buddyChatOperation(projectId, me?.generation));
    final id = result?['conversationId'];
    // The chat is made either way; only a reader still where they were when they asked is taken to it (task #4704).
    return id is String && from == _selectRequest && await select(id);
  }

  String _buddyChatOperation(String projectId, String? generation) {
    final id = 'buddy-chat-$projectId-$accountId-${generation ?? ''}';
    // The backend's operation ids are at most 160 characters.
    return id.length > 160 ? id.substring(0, 160) : id;
  }

  /// Opens conversation [id], reading it first when it is not held
  /// ([loadGroup]); false when it cannot be read, or another was opened while
  /// it was.
  Future<bool> select(String id) async {
    final ask = ++_selectRequest;
    // A held group is selected at once, before this returns.
    if (snapshot?.conversation(id) == null) {
      if (!await loadGroup(id)) return false;
      // The reader moved on while this was read: it must not pull them back.
      if (ask != _selectRequest) return false;
    }
    id = _shownFor(id);
    if (id == selectedId && !devicesSelected) return true;
    _acted();
    final group = snapshot!.conversation(id)!;
    // A task's project's closed tasks, read once: the quick switcher finds an
    // archived one by its number (#N). A Buddy chat reads none.
    if (!snapshot!.isProjectLead(id) && !group.isBuddyChat) {
      unawaited(loadDormant(group.projectId));
    }
    _moveView(to: id);
    // Held from an earlier visit: what arrived meanwhile is not among them.
    if (_messages[id]?.isNotEmpty ?? false) {
      _staleHeld.add(id);
    } else {
      _staleHeld.remove(id);
    }
    _pruneThreadFiles();
    _viewVersion++;
    operationNotice = null;
    _saveSoon();
    _changed();
    unawaited(loadMessages(id));
    if (openedThread != null) unawaited(loadThread());
    return true;
  }

  /// The reader's notification setting for [id] (backend chatSettings.ts):
  /// the one being sent, else the server's, else Mentions only.
  SuperTabNotify notifyOf(String id) =>
      _notifySending[id] ??
      _notifyKept[id]?.$1 ??
      snapshot?.chatSettings[id] ??
      SuperTabNotify.mentions;

  /// Settings sent and not yet seen back in a read, newest choice per chat.
  final _notifySending = <String, SuperTabNotify>{};
  int _notifyAsked = 0;

  /// Whether [group] shows as unread in the sidebar: unread, and not muted.
  /// A muted chat stays listed, greyed, and never counts (Slack).
  bool unreadShown(SuperTabConversation group) =>
      notifyOf(group.id) != SuperTabNotify.muted && unread(group);

  /// A person wrote in [group]'s main stream since the reader's mark, and it
  /// is not muted: what makes a project's or a task's sidebar row bold, with
  /// a tag of the reader or a wait on a person (Huy, 11-03, #2427). Agents'
  /// progress messages and system rows leave it, so a busy Swarm's sidebar
  /// does not read all bold.
  bool unreadForPeople(SuperTabConversation group) =>
      notifyOf(group.id) != SuperTabNotify.muted &&
      group.lastPersonSequence > readMark(group.id);

  /// Keeps [level] for [id] on every device of the reader. Shown at once;
  /// false, and the old setting back, when the server did not keep it. A
  /// later choice for the same chat wins over an earlier one still on its way.
  Future<bool> setNotify(String id, SuperTabNotify level) async {
    if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {
      return false;
    }
    final asked = ++_notifyAsked;
    final epoch = visibilityEpoch;
    _notifySending[id] = level;
    _changed();
    var kept = false;
    try {
      final answer = await request(
        'POST',
        '$_path/conversations/${Uri.encodeComponent(id)}/notifications',
        body: {'notify': level.name},
      );
      return kept = SuperTabNotify.parse(answer['notify'] as String?) == level;
    } catch (_) {
      return false;
    } finally {
      // Only the newest choice for this chat settles it; a read since
      // carries the server's, which [notifyOf] reads once this is gone.
      if (!_disposed && asked == _notifyAsked) {
        _notifySending.remove(id);
        if (kept && !accessRevoked && visibilityEpoch == epoch) {
          _notifyKept[id] = (level, _readSerial);
        }
        _changed();
      }
    }
  }

  /// Settings the server answered for, until a read carries them: without
  /// it a chat would flick back to the last read's setting meanwhile.
  /// With the number of the newest read started when the answer came: a
  /// read started after it carries the setting, and replaces it.
  final _notifyKept = <String, (SuperTabNotify, int)>{};

  /// Reads started, in order ([_read]).
  int _readSerial = 0;

  /// The one Mark all read that waits for its Undo, if any.
  SuperTabMarkAll? _markAll;

  /// How long Mark all read waits before the marks go to the server: read
  /// marks never move back there, so Undo works by not sending them yet.
  static const markAllHold = Duration(seconds: 6);

  /// Marks every chat of this Swarm the sidebar shows unread as read (Slack's
  /// Shift+Esc): at once on this device, on the server once [markAllHold]
  /// passes without [SuperTabMarkAll.undo]. Null when nothing is unread. A
  /// second one sends the first's marks before it starts.
  SuperTabMarkAll? markAllRead() {
    final snapshot = this.snapshot;
    if (_disposed || accessRevoked || snapshot == null) return null;
    _markAll?._commit();
    _unreadHeld.clear();
    final before = <String, int?>{}, through = <String, int>{};
    for (final group in snapshot.conversations) {
      if (group.dormant || !unreadShown(group)) continue;
      final top = max(
        group.lastMainSequence ?? group.lastMessageSequence,
        _loadedMessageSequence(group.id),
      );
      before[group.id] = _readAt[group.id];
      through[group.id] = top;
      _readAt[group.id] = max(_readAt[group.id] ?? 0, top);
    }
    if (through.isEmpty) return null;
    final epoch = visibilityEpoch;
    late final SuperTabMarkAll held;
    held = _markAll = SuperTabMarkAll._(
      count: through.length,
      commit: () {
        if (_markAll == held) _markAll = null;
        if (_disposed || accessRevoked || visibilityEpoch != epoch) return;
        for (final MapEntry(key: id, value: top) in through.entries) {
          if (snapshot.conversation(id) == null) continue;
          _serverMarks.mark(id, top, kept: this.snapshot?.readMarks[id] ?? 0);
        }
      },
      undo: () {
        if (_markAll == held) _markAll = null;
        if (_disposed) return;
        for (final MapEntry(key: id, value: was) in before.entries) {
          // Only what this Mark all read moved: a chat read since keeps it.
          if (_readAt[id] != through[id]) continue;
          if (was == null) {
            _readAt.remove(id);
          } else {
            _readAt[id] = was;
          }
        }
        _saveSoon();
        _changed();
      },
      hold: markAllHold,
    );
    _saveSoon();
    _changed();
    return held;
  }

  /// The sidebar lists only chats with something unread (and the open one):
  /// Slack's unread filter, kept on this computer.
  bool unreadOnly = false;

  void toggleUnreadOnly() {
    unreadOnly = !unreadOnly;
    _saveSoon();
    _changed();
  }

  /// A visible transcript passes the boundary it displayed. The loaded messages
  /// are authoritative: snapshots can arrive either before or after their tail.
  /// While the open chat is held unread ([markUnread]) only an [explicit] read
  /// (Esc) reads it.
  void markRead(String id, {int? through, bool explicit = false}) {
    if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {
      return;
    }
    if (explicit) {
      _unreadHeld.remove(id);
    } else if (_unreadHeld.contains(id)) {
      return;
    }
    final loaded = _loadedMessageSequence(id);
    var last = min(through ?? loaded, loaded);
    // Rows the chat does not list (a terminal's prompt) just after what was
    // read are read with it, so another device does not show them unread.
    for (final m in _messages[id] ?? const <SuperTabMessage>[]) {
      if (m.sequence <= last || !m.inMainStream) continue;
      if (_listed(m) || m.sequence > loaded) break;
      last = m.sequence;
    }
    _serverMarks.mark(id, last, kept: snapshot?.readMarks[id] ?? 0);
    if ((_readAt[id] ?? 0) >= last) return;
    _readAt[id] = last;
    _saveSoon();
    _changed();
  }

  /// [id] was read through [sequence] outside its chat (Activity's Mark read
  /// on a tag): kept here and sent to the server, as [markThreadRead] does for
  /// a thread. Unlike [markRead] it does not stop at the loaded messages, as
  /// the chat may not be open; it stops at the chat's newest message.
  void markReadThrough(String id, int sequence) {
    final group = snapshot?.conversation(id);
    if (_disposed || accessRevoked || group == null || sequence <= 0) return;
    final last = min(
      sequence,
      max(
        group.lastMainSequence ?? group.lastMessageSequence,
        _loadedMessageSequence(id),
      ),
    );
    _unreadHeld.remove(id);
    _serverMarks.mark(id, last, kept: snapshot?.readMarks[id] ?? 0);
    if ((_readAt[id] ?? 0) >= last) return;
    _readAt[id] = last;
    _saveSoon();
    _changed();
  }

  /// The open chat the reader marked unread: nothing reads it again until they
  /// leave it, as in Slack.
  final _unreadHeld = <String>{};

  /// Marks [id] unread from [message] on: the read mark goes to just before it
  /// (backend readMarks.ts lowerReadMark), on every device of the reader, and
  /// never forward. A message only in its thread has its thread's mark, not
  /// this one. False when the server did not keep it; this device's mark is
  /// then as it was.
  Future<bool> markUnread(String id, SuperTabMessage message) async {
    if (_disposed ||
        accessRevoked ||
        snapshot?.conversation(id) == null ||
        !message.inMainStream ||
        message.sequence <= 0) {
      return false;
    }
    final target = message.sequence - 1;
    if (readMark(id) <= target) return true;
    final was = _readAt[id], wasServer = snapshot?.readMarks[id];
    if (id == selectedId) _unreadHeld.add(id);
    _readAt[id] = target;
    _parts?.lowerReadMark(id, target);
    _serverMarks.forget(id);
    _saveSoon();
    _redraw();
    try {
      final answer = superTabMap(
        await request(
          'POST',
          '$_path/conversations/${Uri.encodeComponent(id)}/unread',
          body: {'sequence': message.sequence},
        ),
      );
      // A read that raised the held mark while this was sent: the server's
      // answer is where it stands.
      if ((answer['sequence'] as num?)?.toInt() case final stored?) {
        _parts?.lowerReadMark(id, stored);
        _redraw();
      }
      return true;
    } catch (_) {
      if (_disposed) return false;
      _unreadHeld.remove(id);
      if (was == null) {
        _readAt.remove(id);
      } else {
        _readAt[id] = was;
      }
      if (wasServer != null) _parts?.raiseReadMark(id, wasServer);
      _saveSoon();
      _redraw();
      return false;
    }
  }

  /// Marks a Mark unread moved back elsewhere: this device's own mark follows.
  void _takeLowered(Map<String, int> lowered) {
    for (final MapEntry(key: id, value: sequence) in lowered.entries) {
      if ((_readAt[id] ?? 0) > sequence) _readAt[id] = sequence;
      _serverMarks.forget(id);
    }
    if (lowered.isNotEmpty) _saveSoon();
  }

  /// The zone this app last told the Swarm, or tried to: told once per zone
  /// and session, so an older backend's refusal is not sent again.
  String? _zoneTold;

  /// Tells the Swarm the reader's time zone when it differs from the one it
  /// keeps for them (backend `member.timeZone`), for the local time on their
  /// card. Quietly: a refusal (an older backend) leaves their card without a
  /// time, which is what it shows anyway.
  void _reportTimeZone(SuperTabSnapshot next) {
    final zone = superTabLocalTimeZone();
    if (zone == null || zone == _zoneTold) return;
    final me = next.people.where((p) => p.id == accountId).firstOrNull;
    if (me == null || me.timeZone == zone) return;
    _zoneTold = zone;
    unawaited(
      request(
        'POST',
        '/api/super-tabs/${Uri.encodeComponent(tabId)}/commands',
        body: {
          'operationId': superTabOperationId(),
          'command': {'type': 'member.timeZone', 'timeZone': zone},
        },
      ).then<void>(
        (_) {},
        onError: (Object error) =>
            appLog.debug('swarm', 'time zone not told: $error'),
      ),
    );
  }

  /// Rechecks a compatibility refusal only when the person presses Retry.
  /// Leo's reconnect once returned an update refusal that survived until quit.
  Future<void> retryRead() async {
    if (_disposed || accessRevoked) return;
    final stopped = updateRequired;
    updateRequired = false;
    await refresh();
    if (stopped) _schedule();
  }

  Future<void> refresh() {
    if (_disposed || accessRevoked || updateRequired) return Future.value();
    return _refreshing ??= _read().whenComplete(() {
      _refreshing = null;
      // A change heard while it was out: read on the next allowed read.
      if (_pushing) _readWhenAllowed();
    });
  }

  Future<void> _read() async {
    // An adapting read that changes nothing redraws nothing: on a phone each
    // redraw of the whole tab is a long frame, every poll.
    // So does a read for a machine's report alone (a heartbeat every 15 s per
    // machine): if it brings more, the state moving says so below.
    final beat = _toldMachine && !_toldMain;
    final quiet = (_policy.adapts || beat) && snapshot != null;
    final serial = ++_readSerial;
    var before = _shown;
    var stateChanged = false;
    loading = snapshot == null;
    if (!quiet) _changed();
    _lastFullRead = clock.now();
    // Taken as the read starts: a push heard while it is out reads once more,
    // on the next allowed read, unless it repeats a time already told.
    _toldMain = _toldMachine = false;
    final took = Stopwatch()..start();
    // A first open's conversation, asked for beside the state
    // ([SuperTabReading.messagesWithState]); dropped if the state moves the
    // selection elsewhere. After it, the messages wait for the state to say
    // the conversation's own counters moved (spec 2026-11-02-poll-cost, Part
    // 2): asked for beside every push, they were read on any change in the
    // Swarm, a machine's reading included.
    final earlyId = selectedId;
    final earlyQuery = stateReads == 0 ? _earlyQuery(earlyId) : null;
    final early = earlyQuery == null
        ? null
        : (request('GET', '${_messagesPath(earlyId)}$earlyQuery')..ignore());
    // A conversation the state already has takes its answer as it comes, so
    // a reply shows without waiting for the state.
    final messagesRead = early != null && snapshot != null
        ? (_readMessages(
            earlyId,
            early: (query: earlyQuery!, page: early, clock: took),
          )..ignore())
        : null;
    try {
      final heldSaved = _parts != null && stateReads == 0;
      final read = await _readParts();
      if (_disposed || accessRevoked) return;
      final stateMs = took.elapsedMilliseconds;
      final parts = _parts!;
      _refreshFailing = false;
      unreachableSince = null;
      _waitingForMachine = false;
      _graceEnd?.cancel();
      _firstReadRetry?.cancel();
      stateReads++;
      speedMarks.launch('swarm state read');
      // How long the Swarm took to answer, and nothing it said: the log shows a slow or failing
      // backend, which the sidebar's ages and the machines' states otherwise only hint at.
      appLog.debug(
        'swarm',
        'state read in ${took.elapsedMilliseconds} ms '
            '(${read.full ? 'first load' : 'changes'}, last changed ${parts.lastChangedAt})',
      );
      // A part or a value worked out at read time (an agent seen down, a
      // limit that ran out) changed: the snapshot is built again. The first
      // read over a saved view wins, whatever it saved.
      // Only what a machine reports moved: the machines are new and nothing
      // else is, so only what shows them hears of it.
      final machinesOnly =
          read.machinesOnly && !_showingSaved && snapshot != null;
      final moved =
          !machinesOnly && (read.changed || _showingSaved || snapshot == null);
      if (machinesOnly) {
        snapshot!.replaceMachines(parts.machines);
        _machinesChanged.value++;
      }
      if (moved) {
        // A closed group named by the saved selection is read by id: a first
        // load has only the active groups.
        if (read.full && !parts.holdsGroup(selectedId)) {
          await _readGroup(parts, selectedId);
          if (_disposed || accessRevoked) return;
        }
        final raw = parts.state;
        if (beat) stateChanged = true;
        if (_policy.adapts) {
          stateChanged = true;
          // A read mark moving is the page around the view: no new copy kept.
          if (!read.marksOnly) _viewVersion++;
        }
        final next = SuperTabSnapshot.fromJson(raw);
        if (next.id != tabId) {
          throw const FormatException('A different Swarm was returned.');
        }
        snapshot = next;
        _takeLowered(parts.takeLowered());
        _reportTimeZone(next);
        _notifyKept.removeWhere((_, kept) => kept.$2 < serial);
        final allowed = next.conversations.map((c) => c.id).toSet();
        // What this device keeps of a group goes with the group itself (a
        // tombstone), not when a read leaves it out: a closed group is out of
        // every first load and still has its drafts and read marks.
        final removed = read.removed;
        final localAccessChanged =
            !allowed.contains(selectedId) ||
            [
              ..._drafts.keys,
              ..._terminals.keys,
              ..._mentions.keys,
              ..._readAt.keys,
              ..._refused.keys,
              ..._threadDraftConversations.values,
            ].any(removed.contains);
        _messages.removeWhere((id, _) => !allowed.contains(id));
        _staleHeld.removeWhere((id) => !allowed.contains(id));
        _quoted.removeWhere((id, _) => !allowed.contains(id));
        _quoting.removeWhere((id, _) => !allowed.contains(id));
        _forgetThreads(allowed.contains);
        _rows.removeWhere((id, _) => !allowed.contains(id));
        _drafts.removeWhere((id, _) => removed.contains(id));
        _threadDrafts.removeWhere(
          (root, _) => removed.contains(_threadDraftConversations[root]),
        );
        _threadDraftConversations.removeWhere(
          (_, conversation) => removed.contains(conversation),
        );
        _attachments.removeWhere((id, files) {
          if (allowed.contains(id)) return false;
          files.dispose();
          return true;
        });
        _terminals.removeWhere((id, _) => removed.contains(id));
        _mentions.removeWhere((id, _) => removed.contains(id));
        _sent.removeWhere(
          (_, sent) => !allowed.contains(sent['conversationId']),
        );
        _refused.removeWhere((id, _) => removed.contains(id));
        _before.removeWhere((id, _) => !allowed.contains(id));
        _readAt.removeWhere((id, _) => removed.contains(id));
        if (!allowed.contains(selectedId)) {
          _moveView(
            to: next.projects.firstOrNull?.leadConversationId ?? 'lead',
          );
          if (openedThread != null) unawaited(loadThread());
        }
        selectedId = _shownFor(selectedId);
        if (localAccessChanged) _saveSoon();
        if (_reopenThread) {
          _reopenThread = false;
          // Still open: a conversation this read leaves out closed it above.
          unawaited(loadThread());
        }
        // A new store holds no closed groups yet, nor one a saved view drew:
        // the open projects read theirs.
        if (read.full || stateReads == 1) {
          // A read for the parts before has nothing to give these.
          _dormantPages.clear();
          _dormantReads.clear();
          if (_closedShippedSince case final since?) {
            _forgetClosedShipped();
            unawaited(readClosedShipped(since));
          }
        }
      }
      // A first open draws its sidebar now, not once its chat answers.
      if (stateReads == 1) _changed();
      _watchMachineSilence();
      final sidebarMs = took.elapsedMilliseconds;
      lastChangedAt = parts.lastChangedAt;
      // A machine's report moves the newest change, and no conversation or
      // anything else that is shown (the open conversation's messages follow
      // its own counters, [_messagesCurrent]).
      if (machinesOnly) {
        before = (
          lastChangedAt: lastChangedAt,
          error: before.error,
          failing: before.failing,
          revoked: before.revoked,
          loading: before.loading,
        );
      }
      // Every state read, a quiet one too: a count a failed read left open is
      // finished; one that is known reads nothing.
      _dropLeft();
      _readUnreadBuddyChats();
      _partsReadAt = clock.now();
      error = null;
      // Counters that did not move have no news for the conversation,
      // whatever else changed: no read of it (spec 2026-11-02-poll-cost,
      // Part 2). Its task's steps keep their own counters.
      if (early != null || !_messagesCurrent(selectedId)) {
        await (selectedId == earlyId && messagesRead != null
            ? messagesRead
            : _readMessages(
                selectedId,
                early: selectedId == earlyId && early != null
                    ? (query: earlyQuery!, page: early, clock: took)
                    : null,
              ));
      } else {
        _readSteps(selectedId, light: false);
      }
      if (stateReads == 1) {
        // Where a first open's time went, from the tab asking to the chat it shows.
        appLog.debug(
          'swarm',
          'first open: sidebar after $sidebarMs ms, chat after ${took.elapsedMilliseconds} ms '
              '(state read $stateMs ms, ${read.full ? 'first load' : 'changes since the saved view'}'
              '${heldSaved ? '' : ', no saved view'})',
        );
      }
      if (_showingSaved) {
        // Read now: the saved view, and its Updating line, give way.
        _showingSaved = false;
        _dropLostChats();
        stateChanged = true;
      }
    } catch (failure) {
      if (_inConnectGrace(failure)) {
        _waitingForMachine = true;
        _graceFailure = failure;
        _retryFirstRead();
      } else {
        _waitingForMachine = false;
        _readFailure(failure);
      }
      if (!_disposed && !accessRevoked) {
        _refreshFailing = true;
        unreachableSince ??= DateTime.now();
      }
      // The kind and code of the failure, never its message: a refusal can quote what was sent.
      appLog.warn(
        'swarm',
        'state read failed after ${took.elapsedMilliseconds} ms: '
            '${failure is SuperTabFailure ? '${failure.code} (status ${failure.statusCode})' : failure.runtimeType}',
      );
    } finally {
      // A saved view stays drawn through the grace; only an empty pane waits on a spinner.
      loading = _waitingForMachine && snapshot == null;
      if (!quiet || stateChanged || _shown != before) _changed();
    }
  }

  /// The machines whose last report is too old to call them online, as last
  /// worked out. A machine going silent sends nothing, and another's heartbeat
  /// no longer redraws: everything that reads a machine's age (agent marks,
  /// the terminal's notice) redraws when this set changes, which is rare.
  Set<String>? _silentMachines;
  Timer? _silenceWatch;

  void _watchMachineSilence() {
    _silenceWatch?.cancel();
    final rows = snapshot?.machines;
    if (_disposed || rows == null || _startedAt == null) return;
    final now = clock.now();
    final silent = <String>{};
    DateTime? next;
    for (final m in rows) {
      final observation = m['observation'];
      final at = observation is Map ? observation['receivedAt'] : null;
      final passes = at is num
          ? DateTime.fromMillisecondsSinceEpoch(at.toInt())
                .add(kSuperTabMachineOfflineAfter)
          : null;
      if (passes == null || !passes.isAfter(now)) {
        silent.add(m['machineId'] as String);
      } else if (next == null || passes.isBefore(next)) {
        next = passes;
      }
    }
    final before = _silentMachines;
    _silentMachines = silent;
    if (before != null && !setEquals(before, silent)) _changed();
    if (next != null) {
      _silenceWatch = Timer(next.difference(now), _watchMachineSilence);
    }
  }

  /// One read of the Swarm's parts: changes since the cursor once a first load
  /// is held, else a first load. A reload answer, or a change read refused (the
  /// Swarm or the reader's access moved), reads in full at once.
  Future<
    ({
      bool full,
      bool changed,
      bool machinesOnly,
      bool marksOnly,
      Set<String> removed,
    })
  >
  _readParts() async {
    final held = _parts;
    if (held != null) {
      try {
        final answer = await request(
          'GET',
          '$_path/changes?${held.changesQuery}',
        );
        if (answer['reload'] != true) {
          final SuperTabPartsChange change;
          try {
            change = held.apply(answer);
          } catch (_) {
            // Half merged: the next read starts again from a first load.
            if (identical(_parts, held)) _parts = null;
            rethrow;
          }
          final refreshed = await _refreshStale(held);
          return (
            full: false,
            changed: change.changed || refreshed,
            machinesOnly: change.machinesOnly && !refreshed,
            marksOnly: change.readMarksOnly && !refreshed,
            removed: change.removedGroups,
          );
        }
      } on SuperTabFailure catch (failure) {
        // A backend rolled back to one without the summary etag refuses it
        // (#2906): read in full, which holds none.
        final etagRefused =
            failure.code == 'VALIDATION_ERROR' && held.derivedEtag != null;
        if (!etagRefused &&
            !const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
          rethrow;
        }
      }
      _parts = null;
    }
    final parts = SuperTabParts.firstLoad(await request('GET', '$_path/parts'));
    if (parts.state['id'] != tabId) {
      throw const FormatException('A different Swarm was returned.');
    }
    _parts = parts;
    return (
      full: true,
      changed: true,
      machinesOnly: false,
      marksOnly: false,
      removed: const <String>{},
    );
  }

  /// A stub says a held group closed, not how: its data is read again by id.
  /// Best effort, after the change read is merged: a failed read leaves the
  /// group as it was and is tried at the next read; only an update answer
  /// stops the tab. True when a group's data was read.
  Future<bool> _refreshStale(SuperTabParts parts) async {
    var read = false;
    for (final id in parts.staleGroups) {
      try {
        if (await _readGroup(parts, id)) {
          read = true;
        } else {
          // Gone or no longer the reader's: its tombstone or a reload follows.
          parts.forgetStale(id);
        }
      } catch (failure) {
        if (_isUpdateRequired(failure)) rethrow;
        appLog.warn(
          'swarm',
          'closed group read failed: '
              '${failure is SuperTabFailure ? '${failure.code} (status ${failure.statusCode})' : failure.runtimeType}',
        );
      }
    }
    return read;
  }

  /// Reads group [id] by id into [parts], active or closed (section 4.5).
  /// False when the reader cannot read it (gone, or no longer theirs).
  Future<bool> _readGroup(SuperTabParts parts, String id) async {
    try {
      final answer = await request(
        'GET',
        '$_path/groups/${Uri.encodeComponent(id)}',
      );
      if (!identical(parts, _parts) && _parts != null) return false;
      parts.addDormant([answer['group']]);
      return true;
    } on SuperTabFailure catch (failure) {
      if (const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) return false;
      rethrow;
    }
  }

  /// The closed groups read for each project: where the next earlier page
  /// starts, null when there is none. A project not here has not been read.
  final _dormantPages = <String, String?>{};
  final _dormantReads = <String, Future<void>>{};

  /// Whether [projectId]'s closed groups have been read.
  bool dormantLoaded(String projectId) => _dormantPages.containsKey(projectId);

  /// Whether a read of [projectId]'s closed groups is under way.
  bool dormantLoading(String projectId) => _dormantReads.containsKey(projectId);

  /// Whether [projectId] has closed groups older than those read.
  bool hasEarlierDormant(String projectId) => _dormantPages[projectId] != null;

  /// Reads [projectId]'s closed groups, newest first, a page at a time: the
  /// first page once, [earlier] the next one. Joins a read under way.
  Future<void> loadDormant(String projectId, {bool earlier = false}) {
    if (_disposed || accessRevoked || _parts == null) return Future.value();
    if (_dormantReads[projectId] case final reading?) return reading;
    if (earlier ? !hasEarlierDormant(projectId) : dormantLoaded(projectId)) {
      return Future.value();
    }
    _changed();
    late final Future<void> reading;
    reading = _readDormant(projectId, earlier).whenComplete(() {
      if (identical(_dormantReads[projectId], reading)) {
        _dormantReads.remove(projectId);
      }
      _changed();
    });
    return _dormantReads[projectId] = reading;
  }

  Future<void> _readDormant(String projectId, bool earlier) async {
    final parts = _parts!;
    final before = earlier ? _dormantPages[projectId] : null;
    try {
      final answer = await request(
        'GET',
        '$_path/groups?dormant=1&projectId=${Uri.encodeQueryComponent(projectId)}'
            '${before == null ? '' : '&before=${Uri.encodeQueryComponent(before)}'}',
      );
      if (_disposed || accessRevoked || !identical(parts, _parts)) return;
      final change = parts.addDormant(answer['groups'] as List);
      _dormantPages[projectId] = answer['next'] as String?;
      // Nothing new read changes nothing drawn, nor the view kept.
      if (change.changed) _redraw();
    } catch (failure) {
      if (_isUpdateRequired(failure)) {
        _requireUpdate();
        return;
      }
      // Not read: the next open of the list asks again.
      appLog.warn(
        'swarm',
        'closed groups read failed: '
            '${failure is SuperTabFailure ? '${failure.code} (status ${failure.statusCode})' : failure.runtimeType}',
      );
    }
  }

  /// Closed tasks read for the Backlog whose `shippedAt` falls in the read's
  /// window, by id; the Backlog places them, as some wait for their merge. Kept here so an open of the tab reads nothing again: a task
  /// that closes later is one this reader holds, and [snapshot] keeps it. They
  /// join no snapshot, which is built again on every change, and no project's
  /// "Closed" count.
  final _closedShipped = <String, SuperTabConversation>{};
  final _closedShippedProjects = <String>{};
  final _closedShippedChanged = ValueNotifier<int>(0);
  Future<void>? _closedShippedRead;
  DateTime? _closedShippedSince;
  int _closedShippedEpoch = 0;

  /// Whether a project's closed tasks could not be read; [readClosedShipped]
  /// tries it again.
  bool closedShippedFailed = false;

  Iterable<SuperTabConversation> get closedShipped => _closedShipped.values;

  /// Tells of a change to [closedShipped] or [closedShippedFailed], and nobody
  /// else who watches this controller: a page changes only the Backlog.
  Listenable get closedShippedChanged => _closedShippedChanged;

  /// Reads the closed tasks shipped since [since] of each project not read yet.
  /// Joins a read under way.
  Future<void> readClosedShipped(DateTime since) {
    if (_disposed || accessRevoked || _parts == null) return Future.value();
    if (_closedShippedRead case final reading?) return reading;
    late final Future<void> reading;
    reading = _readClosedShipped(since, _closedShippedEpoch).whenComplete(() {
      if (identical(_closedShippedRead, reading)) _closedShippedRead = null;
    });
    return _closedShippedRead = reading;
  }

  Future<void> _readClosedShipped(DateTime since, int epoch) async {
    _closedShippedSince = since;
    if (closedShippedFailed) {
      closedShippedFailed = false;
      _closedShippedChanged.value++;
    }
    final projects = snapshot?.projects ?? const <SuperTabProject>[];
    for (final project in projects) {
      if (_closedShippedProjects.contains(project.id)) continue;
      try {
        await _readProjectClosedShipped(project.id, since, epoch);
        if (epoch != _closedShippedEpoch) return;
        _closedShippedProjects.add(project.id);
      } catch (failure) {
        if (_disposed || epoch != _closedShippedEpoch) return;
        if (_isUpdateRequired(failure)) return _requireUpdate();
        appLog.warn(
          'swarm',
          'closed tasks read failed: '
              '${failure is SuperTabFailure ? '${failure.code} (status ${failure.statusCode})' : failure.runtimeType}',
        );
        closedShippedFailed = true;
        _closedShippedChanged.value++;
      }
    }
  }

  /// One project's closed groups, newest first, a page at a time: by project,
  /// as only a project's list has an index that serves its order. A page whose
  /// last group last changed before [since] is the last read, since those after
  /// it were last active earlier still.
  Future<void> _readProjectClosedShipped(
    String projectId,
    DateTime since,
    int epoch,
  ) async {
    String? before;
    for (var page = 0; page < _closedSincePages; page++) {
      final answer = await request(
        'GET',
        '$_path/groups?dormant=1&projectId=${Uri.encodeQueryComponent(projectId)}'
            '${before == null ? '' : '&before=${Uri.encodeQueryComponent(before)}'}',
      );
      if (_disposed || accessRevoked || epoch != _closedShippedEpoch) return;
      final groups = answer['groups'] as List;
      var added = false;
      for (final raw in groups) {
        final task = SuperTabConversation.fromJson(
          superTabMap(superTabMap(raw)['data']),
        );
        if (task.shippedAt case final at? when !at.isBefore(since)) {
          _closedShipped[task.id] = task;
          added = true;
        }
      }
      if (added) _closedShippedChanged.value++;
      before = answer['next'] as String?;
      final last = groups.lastOrNull;
      if (before == null || last == null) return;
      final changedAt = superTabMap(last)['changedAt'];
      if (changedAt is num && changedAt < since.millisecondsSinceEpoch) return;
    }
    appLog.warn(
      'swarm',
      'closed tasks read stopped at $_closedSincePages pages',
    );
  }

  /// Each project's Buddy proposals the PM has not answered, oldest first, as
  /// last read (backend proposals read, #2867's rule, task #2569), and the
  /// project chat's last sequence that read saw: the next read waits for the
  /// chat to move, as only a message there can answer or add one, and for a
  /// minute since the last (the PM, 2026-11-04: the read looks through the
  /// whole chat, and repeated reads are the backend's biggest cost).
  final _proposals = <String, List<SuperTabProposal>>{};
  final _proposalsAt = <String, int>{};
  final _proposalsReadAt = <String, DateTime>{};
  final _proposalReads = <String, Future<void>>{};
  final _proposalsLater = <String, Timer>{};
  static const proposalsEvery = Duration(minutes: 1);

  List<SuperTabProposal> proposalsOf(String projectId) =>
      _proposals[projectId] ?? const [];

  /// Reads [projectId]'s open proposals once its chat has moved since the last
  /// read; joins a read under way. A failed read keeps what was shown and is
  /// tried again when the chat next moves.
  Future<void> readProposals(String projectId) {
    final project = snapshot?.projectById(projectId);
    if (_disposed || accessRevoked || project == null) return Future.value();
    final at =
        snapshot!
            .conversation(project.leadConversationId)
            ?.lastMessageSequence ??
        0;
    if (_proposalsAt[projectId] == at) return Future.value();
    if (_proposalReads[projectId] case final reading?) return reading;
    final last = _proposalsReadAt[projectId];
    final wait = last == null
        ? Duration.zero
        : proposalsEvery - clock.now().difference(last);
    if (wait > Duration.zero) {
      // One read for every move in the minute, once it is up.
      _proposalsLater[projectId] ??= Timer(wait, () {
        _proposalsLater.remove(projectId);
        unawaited(readProposals(projectId));
      });
      return Future.value();
    }
    _proposalsReadAt[projectId] = clock.now();
    late final Future<void> reading;
    reading = _readProposals(projectId, at).whenComplete(() {
      if (identical(_proposalReads[projectId], reading)) {
        _proposalReads.remove(projectId);
      }
    });
    return _proposalReads[projectId] = reading;
  }

  Future<void> _readProposals(String projectId, int at) async {
    _proposalsAt[projectId] = at;
    try {
      final answer = await request(
        'GET',
        '$_path/proposals?projectId=${Uri.encodeQueryComponent(projectId)}',
      );
      if (_disposed || accessRevoked) return;
      _proposals[projectId] = List.unmodifiable([
        for (final raw in answer['proposals'] as List? ?? const [])
          if (raw is Map && raw['messageId'] is String)
            SuperTabProposal.fromJson(superTabMap(raw)),
      ]);
      _changed();
    } catch (failure) {
      if (_disposed) return;
      if (_isUpdateRequired(failure)) return _requireUpdate();
      // A backend from before the read has none to give (404): said once.
      appLog.warn(
        'swarm',
        'proposals read failed: '
            '${failure is SuperTabFailure ? '${failure.code} (status ${failure.statusCode})' : failure.runtimeType}',
      );
    }
  }

  void _forgetClosedShipped() {
    _closedShippedEpoch++;
    _closedShippedRead = null;
    _closedShipped.clear();
    _closedShippedProjects.clear();
    closedShippedFailed = false;
    if (!_disposed) _closedShippedChanged.value++;
  }

  /// Builds the snapshot again from the parts held, after a read on demand.
  void _redraw() {
    final parts = _parts;
    if (parts == null || snapshot == null) return;
    snapshot = SuperTabSnapshot.fromJson(parts.state);
    _viewVersion++;
    _changed();
  }

  /// What a state read can change on screen, beside the messages.
  ({int lastChangedAt, String? error, bool failing, bool revoked, bool loading})
  get _shown => (
    lastChangedAt: lastChangedAt,
    error: error,
    failing: _refreshFailing,
    revoked: accessRevoked,
    loading: loading,
  );

  /// A first read that found no machine connected, before the grace
  /// ([SuperTabReading.connectGrace]) runs out: its error waits for the grace.
  bool _inConnectGrace(Object failure) {
    final since = _startedAt;
    if (stateReads > 0 || since == null || !_graceCovers(failure)) {
      return false;
    }
    final left = _policy.connectGrace - clock.now().difference(since);
    if (left <= Duration.zero) return false;
    _graceEnd ??= Timer(left, () {
      if (_disposed || !_waitingForMachine) return;
      _waitingForMachine = false;
      _readFailure(_graceFailure!);
      loading = false;
      _changed();
    });
    return true;
  }

  bool _graceCovers(Object failure) {
    final code = failure is SuperTabFailure ? failure.code : null;
    if (!_policy.retriesFirstRead) return code == 'MACHINE_UNAVAILABLE';
    if (_isUpdateRequired(failure)) return false;
    // In passing: no answer at all, a 5xx, or a read before this computer has its row, which a
    // Swarm restored at launch can make. A refusal (401, 403, 404) is the server's word.
    return failure is! SuperTabFailure ||
        (!failure.settled &&
            (failure.statusCode == 0 || failure.statusCode >= 500));
  }

  /// Bounded by [SuperTabReading.firstReadRetryDelays]; the grace's end then says what failed.
  void _retryFirstRead() {
    final delays = SuperTabReading.firstReadRetryDelays;
    if (!_policy.retriesFirstRead ||
        _disposed ||
        accessRevoked ||
        _firstReadTries >= delays.length) {
      return;
    }
    _firstReadRetry?.cancel();
    _firstReadRetry = Timer(delays[_firstReadTries++], () {
      if (!_disposed && !accessRevoked && stateReads == 0) unawaited(refresh());
    });
  }

  /// The same messages with the same receipts: posted text does not change.
  /// Whether [answer] says a reaction changed in [id] since its rows were
  /// last refreshed: a poll then reads the page shown again (backend
  /// reactions.ts). The first answer only records where it stands.
  bool _reactionsMoved(String id, Map<String, dynamic> answer) {
    final seq = answer['reactionSeq'];
    final known = _reactionSeq[id];
    return seq is int && known != null && known != seq;
  }

  /// The rows of [held] that [page], read whole, no longer has: from its
  /// oldest row on (from the start when it reached it) and before [before]
  /// (to the end when null). Each was deleted since it was read.
  static Set<String> _deletedFrom(
    Iterable<SuperTabMessage> held,
    Map<String, dynamic> page,
    int? before,
  ) {
    final rows = [
      for (final row in page['messages'] as List)
        SuperTabMessage.fromJson(superTabMap(row)),
    ];
    if (page['next'] != null && rows.isEmpty) return {};
    final ids = {for (final m in rows) m.id};
    final oldest = page['next'] == null
        ? null
        : rows.reduce((a, b) => superTabMessageOrder(a, b) <= 0 ? a : b);
    return {
      for (final m in held)
        if (!ids.contains(m.id) &&
            (before == null || m.sequence < before) &&
            (oldest == null || superTabMessageOrder(m, oldest) >= 0))
          m.id,
    };
  }

  /// Where a query's page ends: its `before`, or null for the latest page.
  static int? _beforeOf(String query) => int.tryParse(
    Uri.splitQueryString(
          query.startsWith('?') ? query.substring(1) : query,
        )['before'] ??
        '',
  );

  static bool _sameMessages(
    List<SuperTabMessage>? shown,
    List<SuperTabMessage> next,
  ) {
    if (shown == null || shown.length != next.length) return false;
    for (var i = 0; i < next.length; i++) {
      final a = shown[i], b = next[i];
      if (a.id != b.id ||
          a.text != b.text ||
          a.editedAt != b.editedAt ||
          a.deletedAt != b.deletedAt ||
          a.deliveries.length != b.deliveries.length ||
          !_sameReactions(a.reactions, b.reactions)) {
        return false;
      }
      for (var j = 0; j < b.deliveries.length; j++) {
        if (!mapEquals(a.deliveries[j], b.deliveries[j])) return false;
      }
    }
    return true;
  }

  static bool _sameReactions(
    List<SuperTabReactionCount> a,
    List<SuperTabReactionCount> b,
  ) =>
      a.length == b.length &&
      [
        for (var i = 0; i < a.length; i++)
          a[i].emoji == b[i].emoji &&
              listEquals(
                [for (final who in a[i].by) '${who.kind}:${who.id}'],
                [for (final who in b[i].by) '${who.kind}:${who.id}'],
              ),
      ].every((same) => same);

  String _messagesPath(String id) =>
      '$_path/conversations/${Uri.encodeComponent(id)}/messages';

  /// What a read of [id]'s messages asks for: the page before the oldest
  /// shown, what came after the newest, or the latest page.
  String _query(String id, {bool older = false}) {
    if (older) {
      final page = _before[id]!;
      return '?before=${page.sequence}&beforeId=${Uri.encodeQueryComponent(page.id)}';
    }
    // A saved page may be stale in its receipts as well as short of new
    // messages: the first read after it takes the latest page whole.
    if (_showingSaved || _latestWanted.contains(id)) return '';
    final tail = _messages[id]?.lastOrNull?.sequence;
    // Holding: the rows shown, for their receipts and reactions.
    if (tail != null && _holding(id)) return '?before=${tail + 1}';
    return tail != null ? '?after=$tail' : '';
  }

  /// How far [id]'s messages were read: the conversation's
  /// `lastMessageSequence` as the state said it when the read was asked, or
  /// the newest row it brought if that is later. A message the reader may
  /// not see moves the counter too; remembered, it costs one empty read, not
  /// one a poll.
  final _readMessageSeq = <String, int>{};

  /// What [id]'s messages were read up to: [_readMessageSeq], else the newest
  /// held.
  int _readUpTo(String id) =>
      _readMessageSeq[id] ?? _messages[id]?.lastOrNull?.sequence ?? 0;

  /// [id]'s messages are as new as its own counters say (spec
  /// 2026-11-02-poll-cost, Part 2): no message after those read, no reaction
  /// changed since its page, no saved page, no newer page asked for. A reader
  /// scrolled up holding the pages below waits for [showLatest]: only a
  /// reaction reads their rows again. `lastMessageSequence` rather than the
  /// main stream's, because a read of what came after brings thread replies
  /// too.
  bool _messagesCurrent(String id) {
    final group = snapshot?.conversation(id);
    if (!_policy.messagesWhenChanged ||
        _showingSaved ||
        group == null ||
        _messages[id] == null ||
        _latestWanted.contains(id) ||
        group.reactionSeq != (_reactionSeq[id] ?? 0)) {
      return false;
    }
    return _holding(id) || group.lastMessageSequence <= _readUpTo(id);
  }

  /// The query of [id]'s messages read to start beside a state read, or null.
  /// On first open only for the conversation the saved state named; after
  /// that, for a conversation the state has and no read of it under way.
  String? _earlyQuery(String id) {
    if (!_policy.messagesWithState || _reading.containsKey((id, false))) {
      return null;
    }
    final known = snapshot == null
        ? _savedSelection
        : snapshot!.conversation(id) != null;
    return known ? _query(id) : null;
  }

  /// A refusal that says this build is too old for the backend.
  static bool _isUpdateRequired(Object failure) =>
      failure is SuperTabFailure &&
      (failure.statusCode == 426 ||
          (failure.code == 'UPDATE_REQUIRED' && failure.statusCode != 400));

  /// Says to update Harness and stops background reads until an explicit Retry.
  void _requireUpdate() {
    updateRequired = true;
    error = updateMessage;
    _poll?.cancel();
  }

  /// Whether the account's Swarm list still names this Swarm: true while it
  /// does, false once a list read that answered leaves it out; it throws when
  /// the list cannot be read. Null: a refused read is final at once.
  final Future<bool> Function()? stillListed;
  bool _checkingListed = false;

  void _readFailure(Object failure, {bool revokeTab = true}) {
    if (_disposed) return;
    if (_isUpdateRequired(failure)) return _requireUpdate();
    error = failure is SuperTabFailure
        ? failure.message
        : 'Could not refresh this conversation. Try again.';
    if (revokeTab &&
        failure is SuperTabFailure &&
        const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
      // A backend restarting under an open Swarm can refuse a read it answers
      // a moment later (Dee's "autonomous.ai", 2026-11-04). Only the list says
      // the Swarm is gone: until it does, this is a failed read like any
      // other, and the Swarm keeps what it shows and says Reconnecting.
      if (stillListed case final listed?) {
        unawaited(_takeAwayUnlessListed(listed));
        return;
      }
      _takeAway();
    }
  }

  Future<void> _takeAwayUnlessListed(Future<bool> Function() listed) async {
    if (_checkingListed) return;
    _checkingListed = true;
    bool? still;
    try {
      still = await listed();
    } catch (_) {
      still = null;
    } finally {
      _checkingListed = false;
    }
    if (_disposed || accessRevoked || still != false) return;
    _takeAway();
    _changed();
  }

  /// The Swarm is not this account's any more: nothing of it is kept or read.
  void _takeAway() {
    accessRevoked = true;
    devicesSelected = false;
    _forgetClosedShipped();
    _forgetAttention();
    snapshot = null;
    _showingSaved = false;
    _parts = null;
    _messages.clear();
    _staleHeld.clear();
    _forgetNewer();
    _quoted.clear();
    _quoting.clear();
    _forgetThreads();
    _poll?.cancel();
    _firstReadRetry?.cancel();
    cancelUpload();
  }

  /// Joins a read of [id] in the same direction already under way, so a
  /// caller can wait for it.
  Future<void> loadMessages(String id, {bool older = false}) {
    if (older) _acted();
    return _readMessages(id, older: older);
  }

  /// [light] asks only for new messages, and nothing under a reader holding
  /// the pages below, whose rows a full read asks for again; [early] is a
  /// read already asked for.
  Future<void> _readMessages(
    String id, {
    bool older = false,
    bool light = false,
    _EarlyRead? early,
  }) {
    final read = _reading[(id, older)] ??=
        _loadMessages(
          id,
          older: older,
          light: light,
          early: early,
        ).whenComplete(() {
          // A block: whenComplete would wait on the removed future, itself.
          _reading.remove((id, older));
        });
    // The open task's steps are read with it: its chat shows their rows.
    if (!older && id == selectedId) _readSteps(id, light: light);
    return read;
  }

  void _readSteps(String id, {required bool light}) {
    final state = snapshot;
    final task = state?.conversation(id);
    if (state == null || task == null) return;
    for (final step in superTabStepsOf(state, task)) {
      // Read again only when the Swarm says the step moved past what was read
      // (final review, minor 8: every poll read every step); a step with no
      // message yet is read once.
      if (_messages[step.id] != null &&
          step.lastMessageSequence <= _readUpTo(step.id)) {
        continue;
      }
      unawaited(_readMessages(step.id, light: light));
    }
  }

  Future<void> _loadMessages(
    String id, {
    required bool older,
    bool light = false,
    _EarlyRead? early,
  }) async {
    if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {
      return;
    }
    if (older && !hasOlder(id)) return;
    // A light check asks only for new messages, which wait while holding.
    if (light && _holding(id)) return;
    final generation = _heldGeneration[id];
    // A first page asked for beside the state has been out since then.
    final readClock = early?.clock ?? (Stopwatch()..start());
    var requestMs = 0;
    // How far the Swarm's state said the conversation went when this read
    // was asked for.
    final askedUpTo = snapshot!.conversation(id)!.lastMessageSequence;
    // What [id] held was replaced while newer messages were on their way.
    bool replaced() => !older && _heldGeneration[id] != generation;
    try {
      final known = _messages[id];
      final tail = known != null && known.isNotEmpty
          ? known.last.sequence
          : null;
      final holding = !older && _holding(id);
      final query = _query(id, older: older);
      final latest = !older && _latestWanted.remove(id);
      final from = _before[id];
      final first = early != null && early.query == query ? early.page : null;
      var answer = first != null
          ? await first.catchError(
              (Object _) => request('GET', '${_messagesPath(id)}$query'),
            )
          : await request('GET', '${_messagesPath(id)}$query');
      requestMs = readClock.elapsedMilliseconds;
      final arrived =
          !older &&
          !holding &&
          tail != null &&
          (answer['messages'] as List).isNotEmpty;
      final reacted = !older && _reactionsMoved(id, answer);
      // Recorded only once the rows are refreshed: a read that fails leaves
      // the change for the next poll.
      final reactionSeq = older ? null : answer['reactionSeq'];
      // More than a page arrived after the newest held (back from another
      // conversation, or from sleep): the page after it would show messages
      // from hours ago as the newest. The latest page replaces what is held,
      // unless the reader is scrolled up: their rows stay, the page joins
      // below them, and the rest waits for [showLatest].
      final skipped = query.startsWith('?after=') && answer['next'] != null;
      final keepPlace = skipped && _readingBack.contains(id);
      // A page read whole, latest or before a point: it holds every row
      // from its oldest on, so a held row it lacks was deleted (an edit or a
      // delete moves `reactionSeq` as a reaction does).
      ({Map<String, dynamic> page, int? before})? whole =
          older || query.startsWith('?after=')
          ? null
          : (page: answer, before: _beforeOf(query));
      if (!_disposed && skipped && !keepPlace) {
        answer = await request('GET', _messagesPath(id));
        whole = (page: answer, before: null);
      } else if (!_disposed && keepPlace) {
        // A changed reaction refreshes the page ending at the newest held:
        // the latest page, under rows read back, would leave a gap.
        final page = reacted
            ? await request('GET', '${_messagesPath(id)}?before=${tail! + 1}')
            : null;
        if (page != null) whole = (page: page, before: tail! + 1);
        answer = {
          ...answer,
          'messages': [
            ...page?['messages'] as List? ?? const [],
            ...answer['messages'] as List,
          ],
        };
      } else if (!_disposed &&
          reacted &&
          tail != null &&
          (answer['messages'] as List).isEmpty) {
        // No new text, but a reaction changed in the page shown: its counts
        // are read again. Never for receipts alone (spec 2026-11-02-poll-cost,
        // Part 2): the person's own one is read by itself ([_checkReceipt]).
        answer = await request(
          'GET',
          '$_path/conversations/${Uri.encodeComponent(id)}/messages?before=${tail + 1}',
        );
        whole = (page: answer, before: tail + 1);
      } else if (!_disposed && reacted && arrived) {
        // New messages and a changed reaction at once: the rows already shown
        // need their counts too, so the latest page is read with the new ones.
        final page = await request('GET', _messagesPath(id));
        whole = (page: page, before: null);
        answer = {
          ...answer,
          'messages': [
            ...page['messages'] as List,
            ...answer['messages'] as List,
          ],
        };
      }
      if (_disposed ||
          accessRevoked ||
          snapshot?.conversation(id) == null ||
          replaced()) {
        return;
      }
      // A read replacing the saved page moved where earlier continues while
      // this page was on its way: under the new page it would leave a gap.
      // Read on from where earlier continues now.
      if (older &&
          (_before[id]?.sequence != from?.sequence ||
              _before[id]?.id != from?.id)) {
        return await _loadMessages(id, older: true);
      }
      final incoming = (answer['messages'] as List)
          .map((m) => SuperTabMessage.fromJson(superTabMap(m)))
          .toList();
      if (incoming.any((m) => m.conversationId != id)) {
        throw const FormatException('A different conversation was returned.');
      }
      // The first read over a saved page replaces it: merged, the saved
      // page would leave a gap when more than a page arrived since.
      final replacing =
          (_showingSaved || latest || (skipped && !keepPlace)) && !older;
      if (replacing) _rows.remove(id);
      _keepRows(id, answer['messages'] as List);
      _keepThreads(id, answer['threads']);
      final combined = {
        if (!replacing)
          for (final m in _messages[id] ?? <SuperTabMessage>[]) m.id: m,
        for (final m in incoming) m.id: m,
      };
      final own = combined.values
          .where(
            (m) => !m.fromAgent && !m.fromTerminal && m.authorId == accountId,
          )
          .fold<SuperTabMessage?>(
            null,
            (latest, m) =>
                latest == null || m.sequence > latest.sequence ? m : latest,
          );
      final ownRead = own != null && incoming.any((m) => m.id == own.id);
      if (!older &&
          own != null &&
          own.deliveries.isNotEmpty &&
          own.deliveries.any(
            (d) => !const {
              'answered',
              'cancelled',
              'superseded',
            }.contains(d['status']),
          ) &&
          incoming.isNotEmpty &&
          !ownRead) {
        // New replies (or a long stream of agent updates) otherwise leave the
        // original row outside this page and its inline receipt stuck at Sent.
        // Only when something came: one may answer it; with nothing new its
        // receipt is read by itself, if at all ([_checkReceipt]).
        final receipt = await request(
          'GET',
          '$_path/conversations/${Uri.encodeComponent(id)}/messages?messageId=${Uri.encodeComponent(own.id)}',
        );
        if (_disposed ||
            accessRevoked ||
            snapshot?.conversation(id) == null ||
            replaced()) {
          return;
        }
        final rows = (receipt['messages'] as List)
            .map((m) => SuperTabMessage.fromJson(superTabMap(m)))
            .toList();
        if (rows.length > 1 ||
            rows.any((m) => m.id != own.id || m.conversationId != id)) {
          throw const FormatException(
            'A different message receipt was returned.',
          );
        }
        for (final row in rows) {
          combined[row.id] = row;
        }
        _keepRows(id, receipt['messages'] as List);
        if (id == selectedId) _receiptRead(own.id);
      } else if (ownRead && id == selectedId) {
        _receiptRead(own.id);
      }
      // An older page read meanwhile (during the receipt read above) stays:
      // what is held now, under what this read brought.
      if (!replacing) {
        for (final m in _messages[id] ?? <SuperTabMessage>[]) {
          combined.putIfAbsent(m.id, () => m);
        }
      }
      if (whole != null) {
        final gone = _deletedFrom(combined.values, whole.page, whole.before)
          ..removeAll(incoming.map((m) => m.id));
        combined.removeWhere((messageId, _) => gone.contains(messageId));
        _rows[id]?.removeWhere((messageId, _) => gone.contains(messageId));
      }
      final sorted = combined.values.toList()..sort(superTabMessageOrder);
      // Past the cap the oldest rows go, where earlier history continues;
      // never under a reader scrolled up, nor from an older page they asked
      // for, nor from where the view lays its list out.
      final floor = _cutBefore[id];
      final below = floor == null
          ? -1
          : sorted.indexWhere((m) => superTabMessageOrder(m, floor) >= 0);
      final cut = older || _readingBack.contains(id)
          ? 0
          : max(
              0,
              min(
                sorted.length - _heldMessages,
                below < 0 ? sorted.length : below,
              ),
            );
      final next = cut > 0 ? sorted.sublist(cut) : sorted;
      // An adapting read that found nothing new changes nothing on screen.
      final same = _policy.adapts && _sameMessages(_messages[id], next);
      _messages[id] = next;
      final settled = !older && _settleHeld(id, read: true);
      if (keepPlace) {
        _newer.add(id);
        _pagesBelow[id] = (_pagesBelow[id] ?? 0) + 1;
      } else if (!older && !holding) {
        _newer.remove(id);
        _pagesBelow.remove(id);
      }
      _dropShownSends(id);
      if (reactionSeq is int) _reactionSeq[id] = reactionSeq;
      // A page joined below a reader scrolled up leaves the rest to read.
      if (!older && !holding) {
        final newest = next.lastOrNull?.sequence ?? 0;
        // An early page went out before the state this read joins: a
        // message committed in between moved the state's counter but is not
        // on the page, so the page vouches only for what it holds.
        _readMessageSeq[id] = keepPlace || first != null
            ? newest
            : max(askedUpTo, newest);
      }
      if (older || replacing || !_before.containsKey(id)) {
        _before[id] = SuperTabPage.read(answer['next']);
      }
      if (cut > 0) {
        _before[id] = SuperTabPage.of(next.first);
        final kept = {for (final m in next) m.id};
        _rows[id]?.removeWhere((messageId, _) => !kept.contains(messageId));
      }
      // Something new in the conversation on screen keeps the full poll.
      if (arrived && id == selectedId) _acted();
      if (!same || settled) {
        if (id == selectedId) _viewVersion++;
        _changed();
      }
      // Speed marks (task #3176): a chat opening and each page read back; a
      // poll for new messages is not one of them.
      if (older || replacing || (tail == null && incoming.isNotEmpty)) {
        speedMarks.messages(
          kind: older ? 'older' : 'latest',
          rows: incoming.length,
          requestMs: requestMs,
          totalMs: readClock.elapsedMilliseconds,
        );
      }
    } catch (failure) {
      if (!older) _settleHeld(id, read: false);
      // The state read waits for a machine within the grace: so do these.
      if (!_inConnectGrace(failure)) _readFailure(failure, revokeTab: false);
      if (failure is SuperTabFailure &&
          const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
        _messages.remove(id);
        _staleHeld.remove(id);
        _forgetNewer(id);
        _quoted.remove(id);
        _quoting.remove(id);
        unawaited(refresh());
      }
      _changed();
    }
  }

  /// Sends [command] once, under [operationId] when the caller fixes one so
  /// that a repeat is the same request (a new one by default).
  Future<Map<String, dynamic>?> command(
    Map<String, dynamic> command, {
    String? operationId,
  }) async {
    if (_disposed || !_maySend(command) || saving || _pending != null) {
      return null;
    }
    _acted();
    _pending = {
      'operationId': operationId ?? superTabOperationId(),
      'command': Map<String, dynamic>.of(command),
    };
    return retry();
  }

  Future<Map<String, dynamic>?> retry() async {
    final pending = _pending;
    if (_disposed ||
        saving ||
        pending == null ||
        !_maySend(superTabMap(pending['command']))) {
      return null;
    }
    saving = true;
    final lane = _lane = Object();
    operationError = null;
    operationErrorCode = null;
    operationNotice = null;
    _changed();
    try {
      // The receipt ID reaches durable local storage before the request can reach the server.
      await _persist();
      if (_disposed || accessRevoked) return null;
      final answer = await request('POST', '$_path/commands', body: pending);
      if (_disposed || accessRevoked) return null;
      final result = superTabMap(answer['result']);
      final command = superTabMap(pending['command']);
      final notice = result['credentialNotice'];
      operationNotice = notice is String && notice.isNotEmpty ? notice : null;
      if (command['type'] == 'message.send') {
        final id = command['conversationId'] as String;
        _sendingMentions.remove(pending['operationId']);
        // Kept confirmed until the transcript holds it, so it never leaves
        // the chat between the answer and the read that brings it.
        final messageId =
            result['messageId'] as String? ?? pending['operationId'] as String;
        _sendIdentities[messageId] = (
          operationId: pending['operationId'] as String,
          conversationId: id,
        );
        _sent[messageId] = {
          ...command,
          'confirmedAt': clock.now().toUtc().toIso8601String(),
        };
        if (_drafts[id]?.trim() == command['text']) {
          _drafts.remove(id);
          _mentions.remove(id);
        }
        // Only what went with this message: more may have been added since.
        final sent = command['attachmentIds'];
        if (sent is List) {
          for (final entry in _uploaded.entries.toList()) {
            if (sent.contains(entry.value)) {
              _attachments[id]?.remove(entry.key);
              for (final MapEntry(:key, :value) in _threadAttachments.entries) {
                if (key.$1 == id) value.remove(entry.key);
              }
              _uploaded.remove(entry.key);
            }
          }
        }
      }
      if (command['type'] == 'conversation.create' &&
          result['conversationId'] is String) {
        // A successful create selects its confirmed destination even when the
        // following read is offline. Never leave the old group's composer active.
        _moveView(to: result['conversationId'] as String);
      }
      _pending = null;
      _changed();
      try {
        await _persist();
      } catch (_) {
        _pending = pending;
        rethrow;
      }
      if (command['type'] == 'message.send') {
        // A refresh is read-only work. It must not hold the send lane after
        // the command and its durable receipt have both been confirmed.
        _release(lane);
        _sendAcknowledgements[pending['operationId']]?.complete();
        _changed();
      }
      // What the command wrote is in the next change read.
      await refresh();
      return result;
    } catch (failure) {
      if (!_disposed && !accessRevoked && _isUpdateRequired(failure)) {
        _requireUpdate();
        _failOperation(
          updateMessage,
          command: superTabMap(pending['command']),
          code: 'UPDATE_REQUIRED',
        );
        // Refused by the backend: nothing was done, nothing to retry.
        _refuse(pending, operationError!);
        _pending = null;
        try {
          await _persist();
        } catch (_) {
          _pending = pending;
        }
      } else if (!_disposed && !accessRevoked) {
        final command = superTabMap(pending['command']);
        _failOperation(
          failure is SuperTabFailure
              ? _refusalText(failure, command)
              : 'The action is not confirmed. Retry to check it.',
          command: command,
          code: failure is SuperTabFailure ? failure.code : null,
        );
        if (failure is SuperTabFailure &&
            failure.statusCode >= 400 &&
            failure.statusCode < 500 &&
            !const {408, 429}.contains(failure.statusCode)) {
          // A definitive rejection made no change. Keep the message for the
          // person to correct; a lost reply retains its exact receipt ID.
          // One refused for New session is kept without it: its Retry, or
          // its text back in the box, sends a plain reply.
          final unsupported = operationError == superTabSessionsUnavailable;
          if (unsupported) _sessionsRefusedAt = clock.now();
          _refuse(
            unsupported
                ? {
                    ...pending,
                    'command': Map<String, dynamic>.of(command)
                      ..remove('newSession'),
                  }
                : pending,
            operationError!,
          );
          _pending = null;
          try {
            await _persist();
          } catch (_) {
            _pending = pending;
          }
        }
        if (failure is SuperTabFailure &&
            const {
              'FORBIDDEN',
              'NOT_FOUND',
              'READ_ONLY',
            }.contains(failure.code)) {
          await refresh();
        }
      }
      return null;
    } finally {
      _release(lane);
      _changed();
      if (_pending == null) {
        unawaited(_drainSends());
      } else if (identical(_pending, pending) &&
          !_drainingSends &&
          !_disposed &&
          !accessRevoked &&
          _queuedSends.isNotEmpty) {
        // A send the queue did not start (a file, a Retry) ended unsure: what
        // waits behind it is kept to send again, as the queue's own does.
        _refuseQueued();
        unawaited(
          _persist().catchError((Object _) {
            error = 'Could not save these messages on this computer.';
            _changed();
          }),
        );
      }
    }
  }

  /// What a person reads for [failure] of [command]: the server's own words,
  /// except where a message was refused for its form (`VALIDATION_ERROR`, the
  /// schema naming fields): a reply whose New session the server does not know
  /// says so; any other says it plainly.
  static String _refusalText(
    SuperTabFailure failure,
    Map<String, dynamic> command,
  ) {
    if (command['type'] != 'message.send' ||
        failure.code != 'VALIDATION_ERROR') {
      return failure.message;
    }
    // Only the field itself unknown means the server can't start sessions;
    // a reply refused for anything else (too many files) keeps New session.
    return command['newSession'] == true &&
            failure.message.contains('Unrecognized key') &&
            failure.message.contains('newSession')
        ? superTabSessionsUnavailable
        : superTabRefusedAsSent;
  }

  static String _excerpt(String text) {
    final line = text.trim().replaceAll(RegExp(r'\s+'), ' ');
    return line.length <= 80 ? line : '${line.substring(0, 79)}…';
  }

  /// Gives up [saving] if [lane] still holds it.
  void _release(Object lane) {
    if (!identical(_lane, lane)) return;
    _lane = null;
    saving = false;
  }

  /// Keeps every queued text for Retry: an earlier one needs confirmation.
  void _refuseQueued() {
    for (final queued in _queuedSends) {
      _refuse({
        'operationId': queued.operationId,
        'command': queued.command,
      }, 'An earlier message needs confirmation.');
      if (!queued.result.isCompleted) queued.result.complete(null);
    }
    _queuedSends.clear();
  }

  /// Keeps a refused [pending] message, with its tags, for Retry.
  void _refuse(Map<String, dynamic> pending, String error) {
    final command = superTabMap(pending['command']);
    final mentions = _sendingMentions.remove(pending['operationId']);
    if (command['type'] != 'message.send') return;
    (_refused[command['conversationId'] as String] ??= []).add((
      operationId: pending['operationId'] as String,
      command: command,
      mentions: mentions ?? const {},
      error: error,
    ));
  }

  /// Removes refused [message] from what is kept, and returns it.
  _Refused? _takeRefused(SuperTabOutgoing message) {
    if (message.state != SuperTabOutgoingState.refused) return null;
    final kept = _refused[message.conversationId];
    final i =
        kept?.indexWhere((r) => r.operationId == message.operationId) ?? -1;
    if (i < 0) return null;
    final refused = kept!.removeAt(i);
    if (kept.isEmpty) _refused.remove(message.conversationId);
    return refused;
  }

  /// Drops the sends the transcript of [id] holds now.
  void _dropShownSends(String id) {
    final held = {for (final m in _messages[id] ?? const []) m.id};
    _sent.removeWhere((messageId, _) => held.contains(messageId));
    _sendOrder.removeWhere(
      (operationId) => held.any((id) => messageIdentity(id) == operationId),
    );
    _sendIdentities.removeWhere(
      (messageId, identity) =>
          identity.conversationId == id &&
          !held.contains(messageId) &&
          !_sent.containsKey(messageId),
    );
  }

  bool _maySend(Map<String, dynamic> command) =>
      canWrite ||
      (!accessRevoked &&
          snapshot != null &&
          command['type'] == 'member.remove' &&
          command['userId'] == accountId);

  /// Sends the selected conversation's draft. [onSending] is told when the
  /// message is on its way and shows in [outgoing].
  ///
  /// With [newSession], in the reader's own Buddy chat, the message starts its
  /// own thread's session (a top-level one roots that thread), and the thread
  /// opens once the server took it, if this chat is still the one shown.
  Future<Map<String, dynamic>?> send({
    String? replyTo,
    List<String> recipients = const [],
    VoidCallback? onSending,
    bool newSession = false,
    String? sessionProjectId,
  }) async {
    final text = draft(selectedId).trim();
    final files = attachments(selectedId).files;
    if ((text.isEmpty && files.isEmpty) ||
        selected == null ||
        selected!.archived ||
        !canWrite ||
        uploading ||
        (newSession && !offersChatSessions) ||
        ((saving || _pending != null) &&
            (files.isNotEmpty || newSession || !canQueueText))) {
      return null;
    }
    final said = _tagsSaid(mentions(selectedId), text);
    final tagged = said.tagged;
    final addressed = recipients.isEmpty ? said.addressed : recipients;
    if (addressed.any((id) => !selected!.agentIds.contains(id))) {
      _failOperation(
        'A mentioned agent is no longer in this conversation. Remove its mention or choose another agent.',
        command: {'conversationId': selectedId},
      );
      _changed();
      return null;
    }
    final conversationId = selectedId;
    // A text alone waits in the queue; one that starts a session goes now,
    // so its answer can open its thread.
    if (files.isEmpty && !newSession) {
      final operationId = superTabOperationId();
      _sendOrder.add(operationId);
      final result = Completer<Map<String, dynamic>?>();
      _sendingMentions[operationId] = Map.of(
        _mentions[conversationId] ?? const {},
      );
      _queuedSends.add((
        operationId: operationId,
        command: {
          'type': 'message.send',
          'conversationId': conversationId,
          'text': text,
          'replyTo': replyTo,
          'recipientIds': addressed,
          if (tagged.isNotEmpty) 'mentions': tagged,
          if (oneBuddy) 'oneBuddy': true,
        },
        result: result,
      ));
      _drafts.remove(conversationId);
      _mentions.remove(conversationId);
      onSending?.call();
      _changed();
      unawaited(_drainSends());
      return result.future;
    }
    // Read before the upload's wait: another chat may be open by its end, and
    // this session belongs to the chat it was sent from.
    final inSwarmBuddyChat = selected?.isSwarmBuddyChat == true;
    final ids = await _uploadAll(
      conversationId,
      attachments(conversationId),
      conversationId,
    );
    if (ids == null) return null;
    final before = _pending;
    final tags = Map<String, String>.of(_mentions[conversationId] ?? const {});
    // In the order it was sent, as text is.
    final operationId = superTabOperationId();
    _sendOrder.add(operationId);
    final sending = command(operationId: operationId, {
      'type': 'message.send',
      'conversationId': conversationId,
      'text': text,
      'replyTo': replyTo,
      'recipientIds': addressed,
      if (tagged.isNotEmpty) 'mentions': tagged,
      if (ids.isNotEmpty) 'attachmentIds': ids,
      if (newSession) 'newSession': true,
      // An app that knows one Buddy per Swarm says so: the server then
      // refuses its write into an older Buddy chat (security review 1 of
      // #2435). Older apps and phones say nothing and still write there.
      if (oneBuddy) 'oneBuddy': true,
      // A New session in one project of the reader's one Buddy chat (spec
      // 2026-10-31-one-buddy-per-swarm).
      if (newSession && sessionProjectId != null && inSwarmBuddyChat)
        'sessionProjectId': sessionProjectId,
    });
    // On its way: the message shows in the chat, and the draft is free for
    // the next one. Both are in the save made before the request.
    if (_pending case final pending? when !identical(pending, before)) {
      _sendingMentions[pending['operationId'] as String] = tags;
      if (_drafts[conversationId]?.trim() == text) {
        _drafts.remove(conversationId);
        _mentions.remove(conversationId);
      }
      onSending?.call();
      _changed();
    }
    final result = await sending;
    _forgetRefusedUploads(result);
    if (newSession && result == null) {
      _restoreSessionRefusal(conversationId, null, operationId);
    } else if (result?['messageId'] case final String id
        when newSession &&
            !_disposed &&
            !accessRevoked &&
            selectedId == conversationId) {
      // Its thread opens beside the chat: the session answers there. A top-
      // level message is its own thread's root.
      openThread(_threadOf(conversationId, replyTo) ?? replyTo ?? id);
    }
    return result;
  }

  /// Sends [message], which names a box's files already [uploaded], as
  /// [send] sends its own: they leave their box only once the server takes
  /// the message, so a refused or unanswered one keeps them there, and a
  /// refusal of the files themselves sends them up again next time.
  Future<Map<String, dynamic>?> sendWithUploads(
    Map<String, dynamic> message,
    Map<HarnessAttachment, String> uploaded,
  ) async {
    _uploaded.addAll(uploaded);
    final result = await command(message);
    _forgetRefusedUploads(result);
    return result;
  }

  /// A refusal of the files themselves sends them up once more; one of the
  /// message (a mention, a recipient) leaves them uploaded.
  void _forgetRefusedUploads(Map<String, dynamic>? result) {
    if (result == null &&
        _pending == null &&
        operationErrorCode?.contains('ATTACHMENT') == true) {
      _uploaded.clear();
    }
  }

  Future<void> _drainSends() async {
    if (_drainingSends || saving || _pending != null || _disposed) return;
    _drainingSends = true;
    final gone = <String>[];
    try {
      while (_queuedSends.isNotEmpty && !_disposed && !accessRevoked) {
        final queued = _queuedSends.removeAt(0);
        final id = queued.command['conversationId'] as String;
        final group = snapshot?.conversation(id);
        if (group == null && canWrite) {
          // Its conversation is gone: no chat can show it, so it is dropped
          // and the sender told.
          _sendingMentions.remove(queued.operationId);
          _sendOrder.remove(queued.operationId);
          gone.add(queued.command['text'] as String? ?? '');
          queued.result.complete(null);
          await _persist();
        } else if (canWrite && group != null && !group.archived) {
          _pending = {
            'operationId': queued.operationId,
            'command': queued.command,
          };
          final advance = Completer<void>();
          _sendAcknowledgements[queued.operationId] = advance;
          unawaited(
            retry().then((result) {
              if (!queued.result.isCompleted) queued.result.complete(result);
              if (!advance.isCompleted) advance.complete();
              _sendAcknowledgements.remove(queued.operationId);
            }),
          );
          await advance.future;
        } else {
          _refuse({
            'operationId': queued.operationId,
            'command': queued.command,
          }, 'This conversation is no longer writable.');
          queued.result.complete(null);
          await _persist();
        }
        if (_pending != null) break;
      }
      if (gone.isNotEmpty && !_disposed && !accessRevoked) {
        operationNotice = gone.length == 1
            ? 'Not sent: “${_excerpt(gone.single)}”. Its conversation is no longer available.'
            : 'Not sent: ${gone.length} messages. Their conversation is no longer available.';
      }
      // An uncertain send keeps its receipt for Retry. Later messages have
      // not reached the server and remain explicitly retryable, not lost.
      if (!_disposed && !accessRevoked && _queuedSends.isNotEmpty) {
        _refuseQueued();
        await _persist();
      }
    } catch (_) {
      // The queue remains in the recovery state when a local write fails.
      error = 'Could not save these messages on this computer.';
      for (final queued in _queuedSends) {
        _refuse({
          'operationId': queued.operationId,
          'command': queued.command,
        }, 'Could not save this message on this computer.');
        if (!queued.result.isCompleted) queued.result.complete(null);
      }
      _queuedSends.clear();
    } finally {
      _drainingSends = false;
      _changed();
    }
  }

  /// Uploads each of [files] that has not gone up yet and returns their ids,
  /// or null with [operationError] set when one could not. The draft and the
  /// files stay where they are.
  Future<List<String>?> _uploadAll(
    String conversationId,
    HarnessAttachments owner,
    Object errorKey,
  ) async {
    final files = owner.files;
    // Any send from this box answers its last refused upload.
    _uploadErrors.remove(errorKey);
    if (files.isEmpty) return const [];
    final run = ++_uploadRun;
    uploading = true;
    operationError = null;
    _sending = (conversationId: conversationId, owner: owner, files: files);
    _uploaded.removeWhere((file, _) => !files.contains(file));
    _changed();
    try {
      final ids = <String>[];
      for (final file in files) {
        var id = _uploaded[file];
        if (id == null) {
          final answer = await uploadFile(conversationId, file);
          if (run != _uploadRun) return null;
          id = superTabMap(answer['attachment'])['id'] as String;
          _uploaded[file] = id;
        }
        ids.add(id);
      }
      return ids;
    } catch (failure) {
      if (!_disposed && run == _uploadRun) {
        // Into the conversation the files were for, whichever is shown now.
        _uploadErrors[errorKey] = failure is SuperTabFailure
            ? failure.message
            : failure is TimeoutException
            ? 'The upload stopped moving. Try again.'
            : 'Could not upload ${files.length == 1 ? 'the file' : 'the files'}. Try again.';
      }
      return null;
    } finally {
      if (run == _uploadRun) {
        uploading = false;
        _sending = null;
        _progress.clear();
        _changed();
      }
    }
  }

  /// Sends [file] to the backend and returns its attachment. Gives up when no
  /// byte has moved for [uploadTimeout], or when the upload is cancelled.
  Future<Map<String, dynamic>> uploadFile(
    String conversationId,
    HarnessAttachment file,
  ) async {
    final token = _cancel = CancelToken();
    Timer? watchdog;
    var stalled = false;
    void watch() {
      watchdog?.cancel();
      watchdog = Timer(uploadTimeout, () {
        stalled = true;
        token.cancel('stalled');
      });
    }

    watch();
    try {
      // The token also ends a transport that ignores it.
      return await Future.any([
        upload(
          tabId: tabId,
          conversationId: conversationId,
          name: file.name,
          mime: mimeForName(file.name),
          file: file,
          cancel: token,
          onProgress: (sent) {
            watch();
            _progress[file] = sent;
            _changed();
          },
        ),
        token.whenCancel.then<Map<String, dynamic>>(
          (cancelled) => throw cancelled,
        ),
      ]);
    } on DioException catch (failure) {
      if (stalled && failure.type == DioExceptionType.cancel) {
        throw TimeoutException('The upload stopped moving.');
      }
      rethrow;
    } finally {
      watchdog?.cancel();
    }
  }

  /// Gives up the files on their way, whether they are stalled or not wanted
  /// any more: the composer is free again, and the draft and files stay.
  void cancelUpload() {
    if (!uploading) return;
    _cancel?.cancel('given up');
    _uploadRun++;
    uploading = false;
    _sending = null;
    _changed();
  }

  Future<void> flush() async {
    // Closing or changing account is no Undo: held marks go now.
    _markAll?._commit();
    _draftSave?.cancel();
    await _persist();
  }

  /// Access went: a held Mark all read sends nothing, and settings on their
  /// way or answered belong to the access that is gone.
  void _forgetAttention() {
    _markAll?._cancel();
    _markAll = null;
    _notifySending.clear();
    _notifyKept.clear();
    _notifyAsked++;
  }

  /// Runs [then] when this controller is disposed: a helper that keeps a
  /// timer of its own (attention.dart) stops with it.
  void onDispose(VoidCallback then) => _onDispose.add(then);
  final _onDispose = <VoidCallback>[];

  @override
  void dispose() {
    // Closing the Swarm is no Undo: the held marks go before anything stops.
    _markAll?._commit();
    _disposed = true;
    _machinesChanged.dispose();
    _closedShippedChanged.dispose();
    _silenceWatch?.cancel();
    for (final later in _proposalsLater.values) {
      later.cancel();
    }
    for (final then in _onDispose) {
      then();
    }
    _onDispose.clear();
    // Closing the tab or signing out stops a file on its way.
    cancelUpload();
    for (final queued in _queuedSends) {
      queued.result.complete(null);
    }
    _queuedSends.clear();
    _serverMarks.dispose();
    _serverThreadMarks.dispose();
    _poll?.cancel();
    _toldRead?.cancel();
    _graceEnd?.cancel();
    _firstReadRetry?.cancel();
    _draftSave?.cancel();
    for (final retry in _quoteRetries) {
      retry.cancel();
    }
    for (final files in _attachments.values) {
      files.dispose();
    }
    // The owner awaits flush when changing account or closing the tab.
    super.dispose();
  }
}

/// One Mark all read waiting for its Undo ([SuperTabController.markAllRead]).
class SuperTabMarkAll {
  SuperTabMarkAll._({
    required this.count,
    required void Function() commit,
    required void Function() undo,
    required Duration hold,
  }) : _onCommit = commit,
       _onUndo = undo {
    _timer = Timer(hold, _commit);
  }

  /// How many chats it marked read.
  final int count;
  final void Function() _onCommit, _onUndo;
  late final Timer _timer;
  bool _done = false;

  /// Whether its marks went to the server, or it was undone or dropped.
  bool get done => _done;

  /// Puts every chat it marked back as it was, if the marks are not sent yet.
  void undo() {
    if (_done) return;
    _done = true;
    _timer.cancel();
    _onUndo();
  }

  void _commit() {
    if (_done) return;
    _done = true;
    _timer.cancel();
    _onCommit();
  }

  void _cancel() {
    _done = true;
    _timer.cancel();
  }
}