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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Phone: Threads row and page with Follow/Unfollow, read on open (Tony) (#2463)
harness-for-autonomous[bot]8a31b6c36fe4
diff --git a/mobile/lib/swarm/swarm_asks.dart b/mobile/lib/swarm/swarm_asks.dartindex a358dedcc..56b5493d4 100644--- a/mobile/lib/swarm/swarm_asks.dart+++ b/mobile/lib/swarm/swarm_asks.dart@@ -66,7 +66,9 @@ class SuperTabMention implements SwarmAskItem {leadName = row['leadName'] as String? ?? 'Lead',text = row['text'] as String? ?? '',createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),- resolvedBy = row['resolvedBy'] as String?;+ resolvedBy = row['resolvedBy'] as String?,+ threadId = row['threadId'] as String?,+ messageSequence = (row['messageSequence'] as num?)?.toInt();@overridefinal String id, projectName, conversationId, conversationTitle;final String projectId, messageId, leadName, text;@@ -75,6 +77,14 @@ class SuperTabMention implements SwarmAskItem {/// `reply` or `done` once it moved to Earlier; null while it waits.final String? resolvedBy;++ /// The thread's root when the tag is in a reply only in its thread: it+ /// counts on Threads (`SwarmThreads.threadMentions`). Null in the main+ /// stream, and from a backend before it.+ final String? threadId;++ /// The tagging message's sequence; null from a backend before it.+ final int? messageSequence;}/// The reader's open decisions and waiting tags in one Swarm, read from thediff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartindex 8352e0f0e..cd4709441 100644--- a/mobile/lib/swarm/swarm_conversation.dart+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -155,15 +155,19 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {/// Read through the newest message seen in the main stream, while it is/// [shown]: [heldAt] once it is read, else the last. A reply only in its/// thread is not on the chat's screen, so it never moves the mark (the- /// desktop's `_loadedMessageSequence`): a mark cannot move back.+ /// desktop's `_loadedMessageSequence`): a mark cannot move back. A server+ /// too old to say a chat's newest main-stream message counts any, as the+ /// desktop does there.void _markRead() {if (!_shown) return;final held = _heldAt;final at = held == null? messages.length - 1: messages.lastIndexWhere((m) => m.id == held);+ final group = conversation;+ final mainOnly = group == null || group.lastMainSequence != null;for (var i = at; i >= 0; i--) {- if (!messages[i].inMainStream) continue;+ if (mainOnly && !messages[i].inMainStream) continue;reader.readMarks?.markRead(id, messages[i].sequence);return;}diff --git a/mobile/lib/swarm/swarm_inbox.dart b/mobile/lib/swarm/swarm_inbox.dartindex 0790ed337..720af14a3 100644--- a/mobile/lib/swarm/swarm_inbox.dart+++ b/mobile/lib/swarm/swarm_inbox.dart@@ -12,6 +12,7 @@ import 'swarm_home_keeper.dart';import 'swarm_read_marks.dart';import 'swarm_reader.dart';import 'swarm_request.dart';+import 'swarm_threads.dart';import 'waiting_work.dart';/// One of the account's Swarms, as the list names it.@@ -254,6 +255,7 @@ class SwarmInbox extends ChangeNotifier {final _readers = <String, SwarmReader>{};final _asks = <String, SwarmAsks>{};+ final _threads = <String, SwarmThreads>{};/// Each Swarm's waiting work as last seen: null until its first read, whose/// waiting work is not news.@@ -280,6 +282,15 @@ class SwarmInbox extends ChangeNotifier {/// [id]'s decisions and tags, while it is listed.SwarmAsks? asks(String id) => _asks[id];+ /// [id]'s followed threads, while it is listed: made when first asked for,+ /// and read only while something shows it ([SwarmThreads]).+ SwarmThreads? threads(String id) {+ if (_disposed) return null;+ final reader = _readers[id];+ if (reader == null) return null;+ return _threads[id] ??= SwarmThreads(reader, asks: _asks[id]);+ }+bool get shown => _shown;/// One of the account's computers came up: while none could be asked, the@@ -494,6 +505,7 @@ class SwarmInbox extends ChangeNotifier {/// still holds of it is taken back ([SwarmReader.revoke]) before it is/// dropped.void _drop(String id, {bool lost = true}) {+ final threads = _threads.remove(id);_asks.remove(id)?.dispose();final reader = _readers.remove(id)?..removeListener(_relay);if (reader != null) {@@ -502,6 +514,7 @@ class SwarmInbox extends ChangeNotifier {// the inbox closing keeps them, written now, for the next one.if (!lost) marks?.dispose();reader.revoke();+ threads?.dispose();if (lost) marks?.dispose();reader.dispose();}diff --git a/mobile/lib/swarm/swarm_page.dart b/mobile/lib/swarm/swarm_page.dartindex 477b96d70..bbe928ce8 100644--- a/mobile/lib/swarm/swarm_page.dart+++ b/mobile/lib/swarm/swarm_page.dart@@ -28,6 +28,8 @@ import 'swarm_session.dart';import 'swarm_start.dart';import 'swarm_style.dart';import 'swarm_tabs.dart';+import 'swarm_threads.dart';+import 'swarm_threads_page.dart';import 'swarm_unread.dart';import 'team_glance.dart';@@ -56,7 +58,7 @@ bool swarmHomeListed(SwarmInbox inbox, String swarmId, String projectId) {/// Swarm Home, direction C (Tony's prototype C1, 2026-10-30), the Home tab:/// its title the Swarm shown, with a switcher to every Swarm, All Swarms and/// Join or create ([showSwarmSwitcher]); While you were away, once the person-/// has been gone a while ([SwarmAwayCard]); then the projects+/// has been gone a while ([SwarmAwayCard]); then Threads; then the projects/// they pinned on this phone, then the others by their latest activity,/// those quiet for a day folded under "Other projects" ([swarmHomeLists])./// Every Swarm's, or the one picked ([SwarmHomePrefs.swarmId]). A round +@@ -65,9 +67,9 @@ bool swarmHomeListed(SwarmInbox inbox, String swarmId, String projectId) {/// tab's; who they are, their models and devices, and Settings, the You/// tab's.///-/// Threads, and While you were away's new threads, wait for a read of the-/// threads with new replies across a Swarm, which the server does not have-/// yet (Lead, 2026-10-30): the phone reads no chat by chat for them.+/// Over the projects, the Threads row ([SwarmThreadsRow]): the threads the+/// person follows in the Swarms shown, bold while one has new replies.+/// While you were away's new threads still wait for their own count.////// Pushed over another page it has a back button instead of the switcher./// Reads the account's [SwarmSession] from the shell; with none, its skeleton@@ -89,6 +91,10 @@ class SwarmPage extends StatefulWidget {class _SwarmPageState extends State<SwarmPage> {SwarmSession? _session;+ /// The Threads row's threads, over the Swarms Home shows, while it is in+ /// sight: out of sight, it asks for none.+ SwarmThreadsMerge? _threads;+/// Kept out of sight under Harness ([OutOfSight]), as it was left: it is no/// Swarm screen meanwhile — a notice still tells what arrives — and draws/// nothing new. Shown again, it reads the Swarms as on any return to Home.@@ -140,7 +146,14 @@ class _SwarmPageState extends State<SwarmPage> {_hidden = hidden;_tick?.cancel();_tick = null;+ _threads?.dispose();+ _threads = null;if (hidden || session == null) return;+ _threads = swarmThreadsOf(+ session,+ shown: () => _shown(session),+ changed: session.home,+ );session.enter();unawaited(session.inbox.refresh());_tick = Timer.periodic(const Duration(minutes: 1), (_) {@@ -152,6 +165,7 @@ class _SwarmPageState extends State<SwarmPage> {void dispose() {_lifecycle.dispose();_tick?.cancel();+ _threads?.dispose();if (!_hidden) _session?.leave();super.dispose();}@@ -389,9 +403,22 @@ class _SwarmPageState extends State<SwarmPage> {: null;final now = widget.now();final away = _awayCard(context, session, shown, picked, now);+ final threads = _threads;return [?away,- ..._projects(context, session, shown, now, first: away == null),+ if (threads != null && shown.isNotEmpty)+ Padding(+ padding: EdgeInsets.only(top: away == null ? AppSpace.s : AppSpace.m),+ child: SwarmGroup(+ children: [+ SwarmThreadsRow(+ threads: threads,+ onTap: () => openSwarmThreads(context, swarmId: picked),+ ),+ ],+ ),+ ),+ ..._projects(context, session, shown, now, first: false),];}@@ -567,9 +594,7 @@ class _SwarmPageState extends State<SwarmPage> {const SizedBox(height: 8),SwarmGroup(key: ValueKey('swarm-projects-error-$id'),- children: [- SwarmRow(title: error, onTap: null),- ],+ children: [SwarmRow(title: error, onTap: null)],),],];@@ -621,7 +646,6 @@ class _SwarmPageState extends State<SwarmPage> {SwarmCaption('Projects', first: first),SwarmSkeletonRows(id: 'swarm-projects-loading', dot: true),];-}/// A Swarm's tile on its way.diff --git a/mobile/lib/swarm/swarm_threads.dart b/mobile/lib/swarm/swarm_threads.dartnew file mode 100644index 000000000..5063553a1--- /dev/null+++ b/mobile/lib/swarm/swarm_threads.dart@@ -0,0 +1,706 @@+import 'dart:async';+import 'dart:math';++import 'package:flutter/foundation.dart';++import 'model.dart';+import 'swarm_asks.dart';+import 'swarm_inbox.dart' show SwarmListing;+import 'swarm_reader.dart';+import 'swarm_request.dart';++/// One thread the reader follows, as the server lists it (backend+/// read/followedThreads.ts, or read/inbox.ts on a server before it): its+/// root's preview and its newest reply. The desktop's `SuperTabFollowedThread`.+class SwarmFollowedThread {+ SwarmFollowedThread.fromJson(Map<String, dynamic> row)+ : conversationId = row['conversationId'] as String,+ rootId = row['rootId'] as String,+ root = superTabMap(row['root'] ?? const {}),+ lastReplyAt = DateTime.tryParse(row['lastReplyAt'] as String? ?? ''),+ lastReplySequence = (row['lastReplySequence'] as num?)?.toInt() ?? 0,+ lastReplier = row['lastReplier'] is Map+ ? superTabMap(row['lastReplier'])+ : null,+ unreadReplies = (row['unreadReplies'] as num?)?.toInt() ?? 0,+ replies = (row['replies'] as num?)?.toInt(),+ follow = row['follow'] as bool?;++ final String conversationId, rootId;++ /// The root's preview: `id`, `sequence`, `author`, `text` (cut by the+ /// server), `createdAt`.+ final Map<String, dynamic> root;+ final DateTime? lastReplyAt;+ final int lastReplySequence, unreadReplies;++ /// How many replies it has; null in an unread entry from an older server.+ final int? replies;++ /// The reader's own Follow (true) or Unfollow (false); null when it follows+ /// from taking part (started it, replied, tagged).+ final bool? follow;+ final Map<String, dynamic>? lastReplier;++ String get key => '$conversationId/$rootId';+ String get rootText => root['text'] as String? ?? '';+ Map<String, dynamic> get rootAuthor =>+ root['author'] is Map ? superTabMap(root['author']) : const {};+ DateTime? get rootAt => DateTime.tryParse(root['createdAt'] as String? ?? '');+}++/// The threads the reader follows in one Swarm ([reader]) and which have+/// replies they have not read, the desktop's `SuperTabAttention` threads+/// (#2434, #2455): the Threads row and page. Read from the server's+/// followed-threads route when the Swarm moves, at most every [quietGap]+/// (every [openGap] while the page is open), and only while something shows+/// it: a phone with every Swarm on Home asks for none it does not draw.+///+/// Rows of chats the Swarm's read does not list for the reader are never+/// shown, on the server's word alone. Access lost, or who may read what+/// changed ([SwarmReader.generation]), takes everything read away, and an+/// answer on its way then is dropped.+class SwarmThreads extends ChangeNotifier {+ SwarmThreads(this.reader, {this.asks, DateTime Function()? now})+ : _now = now ?? DateTime.now {+ reader.addListener(_changed);+ reader.reads.addListener(_changed);+ asks?.addListener(_told);+ reader.readMarks?.addListener(_told);+ }++ final SwarmReader reader;++ /// The reader's waiting tags here, for [threadMentions]; null counts none.+ final SwarmAsks? asks;+ final DateTime Function() _now;++ static const quietGap = Duration(seconds: 15);+ static const openGap = Duration(seconds: 3);++ /// Busy (429): the next read waits this long.+ static const busyWait = Duration(seconds: 5);++ /// How many replies show under a new thread's root, its newest.+ static const shownReplies = 5;++ /// Followed threads with replies the reader has not read, newest reply+ /// first; and those read, newest reply first.+ List<SwarmFollowedThread> unread = const [], read = const [];++ /// Whether a read has answered since the Swarm was opened or its audience+ /// last changed.+ bool loaded = false;+ String? error;++ /// The server keeps Follow and Unfollow; false on one before them (it+ /// answered 404), which lists only unread threads. Asked again at the next+ /// visit of the page.+ bool followSupported = true;++ /// The server stopped short of everything (its bounds).+ bool more = false;++ /// New replies under each unread thread's root, read when the page showed+ /// it; by [SwarmFollowedThread.key].+ final Map<String, List<SuperTabMessage>> newReplies = {};++ /// Threads whose Follow is being sent.+ final Set<String> following = {};++ /// Threads shown as new in this visit of the page: they stay new until the+ /// page is left, though opening them marked them read.+ final Set<String> _newThisVisit = {};++ /// The new-reply count each thread showed when this visit first listed it+ /// as new: a thread read meanwhile comes back with none, and keeps saying+ /// what it had.+ final Map<String, int> _counts = {};+ final Set<String> _readingReplies = {};++ /// Threads whose replies failed to read this visit: not asked again until+ /// the next one, so a failing read is not repeated on every redraw.+ final Set<String> _repliesFailed = {};++ bool _open = false;++ /// Moves each time the page opens or closes: replies read for one visit+ /// mark nothing once it is over.+ int _visit = 0;+ int? _generation;+ int _lastChangedAt = -1;+ DateTime? _lastRead, _waitUntil;+ Timer? _trailing;+ Future<void>? _loading;+ bool _dirty = false, _disposed = false;+ int _asked = 0, _shown = 0;++ String get _path => '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}';++ /// Whether a followed thread has replies the reader has not read: the+ /// Threads row is bold.+ bool get threadsUnread => unread.isNotEmpty;++ /// The Threads row's number: tags of the reader inside threads they have+ /// not read past, in chats this Swarm lists for them. A muted chat's+ /// threads never count (#2455). None until the phone's marks are back.+ int get threadMentions {+ final snapshot = reader.snapshot;+ final marks = reader.readMarks;+ if (reader.accessRevoked || snapshot == null || marks == null) return 0;+ var count = 0;+ for (final m in asks?.mentions ?? const <SuperTabMention>[]) {+ final root = m.threadId;+ if (root == null || snapshot.conversation(m.conversationId) == null) {+ continue;+ }+ if (snapshot.chatSettings[m.conversationId] == 'muted') continue;+ final through = marks.threadThrough(m.conversationId, root);+ if (through == null) return 0;+ if ((m.messageSequence ?? _unknown) > through) count++;+ }+ return count;+ }++ /// A tag from a server that does not say where it is: it counts until+ /// answered, past any read mark.+ static const _unknown = 1 << 52;++ /// How many new replies [thread] shows: as many as it had when this visit+ /// first listed it new.+ int newCount(SwarmFollowedThread thread) =>+ _counts[thread.key] ?? thread.unreadReplies;++ /// Whether [thread] shows as new in this visit.+ bool isNew(SwarmFollowedThread thread) =>+ _newThisVisit.contains(thread.key) ||+ unread.any((t) => t.key == thread.key);++ /// The threads the page lists: new ones first, then the rest, each newest+ /// reply first; one read during this visit stays with the new ones.+ List<SwarmFollowedThread> get shown {+ final fresh = <SwarmFollowedThread>[+ ...unread,+ ...read.where((t) => _newThisVisit.contains(t.key)),+ ];+ final keys = fresh.map((t) => t.key).toSet();+ int newest(SwarmFollowedThread a, SwarmFollowedThread b) =>+ (b.lastReplyAt ?? DateTime(0)).compareTo(a.lastReplyAt ?? DateTime(0));+ return [+ ...fresh..sort(newest),+ ...read.where((t) => !keys.contains(t.key)),+ ];+ }++ /// The page opened: reads now, and what is new stays new until [closed].+ void opened() {+ if (_disposed) return;+ _open = true;+ _visit++;+ // A server that answered 404 once may have been updated since.+ followSupported = true;+ _newThisVisit+ ..clear()+ ..addAll(unread.map((t) => t.key));+ _counts+ ..clear()+ ..addAll({for (final t in unread) t.key: t.unreadReplies});+ _repliesFailed.clear();+ _lastRead = null;+ // A read already under way (the row's) answers for the page too.+ if (_loading == null) unawaited(load());+ }++ void closed() {+ if (_disposed) return;+ _open = false;+ _visit++;+ _newThisVisit.clear();+ _counts.clear();+ newReplies.clear();+ _readingReplies.clear();+ _repliesFailed.clear();+ notifyListeners();+ }++ /// Something [threadMentions] reads moved.+ void _told() {+ if (!_disposed) notifyListeners();+ }++ void _clear() {+ unread = read = const [];+ loaded = false;+ error = null;+ more = false;+ _newThisVisit.clear();+ _counts.clear();+ newReplies.clear();+ _readingReplies.clear();+ _repliesFailed.clear();+ following.clear();+ _trailing?.cancel();+ _trailing = null;+ // An answer on its way belongs to what the reader could read before.+ _shown = ++_asked;+ }++ void _changed() {+ if (_disposed) return;+ if (reader.accessRevoked) {+ if (loaded || error != null || unread.isNotEmpty || read.isNotEmpty) {+ _clear();+ notifyListeners();+ } else {+ _shown = ++_asked;+ }+ return;+ }+ // The Home kept from before is no read ([SwarmReader.heldLoad]): nothing+ // is asked on its word.+ if (reader.snapshot == null || reader.heldLoad == 0) return;+ final generation = reader.generation;+ if (generation != _generation) {+ final moved = _generation != null;+ _generation = generation;+ if (moved) {+ // Who may read what changed: nothing read before shows until read+ // again.+ _clear();+ notifyListeners();+ if (!hasListeners) return;+ _lastChangedAt = reader.lastChangedAt;+ unawaited(load());+ return;+ }+ }+ // Read only while something shows it (the Threads row, the page).+ if (!hasListeners) return;+ if (reader.lastChangedAt == _lastChangedAt && loaded) return;+ final now = _now();+ // Inside the gap, or waiting out a refusal: one read when it is over, so+ // the change is not lost.+ final until = [+ if (_waitUntil case final wait? when now.isBefore(wait)) wait,+ if (_lastRead case final last?) last.add(_open ? openGap : quietGap),+ ].fold<DateTime?>(null, (a, b) => a == null || b.isAfter(a) ? b : a);+ if (until != null && now.isBefore(until)) {+ _trailing ??= Timer(until.difference(now), () {+ _trailing = null;+ _changed();+ });+ return;+ }+ _trailing?.cancel();+ _trailing = null;+ _lastChangedAt = reader.lastChangedAt;+ unawaited(load());+ }++ /// Joins a read under way, and has it read once more when asked again.+ Future<void> load() {+ if (_disposed) return Future.value();+ if (_loading case final running?) {+ _dirty = true;+ return running;+ }+ return _loading = () async {+ do {+ _dirty = false;+ await _read();+ } while (_dirty && !_disposed);+ }().whenComplete(() => _loading = null);+ }++ Future<void> _read() async {+ if (reader.accessRevoked ||+ reader.snapshot == null ||+ reader.heldLoad == 0) {+ return;+ }+ final asked = ++_asked;+ final generation = reader.generation;+ _lastRead = _now();+ bool current() =>+ !_disposed &&+ !reader.accessRevoked &&+ asked > _shown &&+ reader.generation == generation;+ try {+ Map<String, dynamic>? answer;+ // A server before followed threads (it answers 404): its inbox lists+ // the unread ones, and nothing keeps Follow.+ var full = followSupported;+ if (full) {+ try {+ answer = superTabMap(await reader.request('GET', '$_path/threads'));+ } on SuperTabFailure catch (failure) {+ if (failure.statusCode != 404) rethrow;+ full = false;+ }+ }+ if (!current()) return;+ answer ??= superTabMap(await reader.request('GET', '$_path/inbox'));+ if (!current()) return;+ _shown = asked;+ final readable = {+ for (final g in reader.snapshot?.conversations ?? const []) g.id,+ };+ List<SwarmFollowedThread> rows(Object? list) => [+ for (final row in list is List ? list : const [])+ if (row is Map)+ if (_parse(superTabMap(row)) case final t?+ // Only chats this reader still has; the server checked, and a+ // chat they lost since is not shown on its word alone.+ when readable.contains(t.conversationId))+ t,+ ];+ unread = rows(full ? answer['unread'] : answer['threads']);+ read = full ? rows(answer['read']) : const [];+ followSupported = full;+ more = answer['more'] == true;+ error = null;+ loaded = true;+ if (_open) {+ _newThisVisit.addAll(unread.map((t) => t.key));+ for (final t in unread) {+ _counts.putIfAbsent(t.key, () => t.unreadReplies);+ }+ }+ _waitUntil = null;+ notifyListeners();+ } catch (failure) {+ if (!current()) return;+ _shown = asked;+ if (failure is SuperTabFailure && failure.statusCode == 429) {+ // Asked too often: the next change after a pause reads again.+ _waitUntil = _now().add(busyWait);+ }+ error = 'Could not load threads.';+ notifyListeners();+ }+ }++ static SwarmFollowedThread? _parse(Map<String, dynamic> row) {+ try {+ return SwarmFollowedThread.fromJson(row);+ } catch (_) {+ // A row of another shape is no thread.+ return null;+ }+ }++ /// Reads the replies of [thread] the reader has not read, to show under its+ /// root, then marks the thread read: opening the page reads what it shows+ /// (the desktop's `showReplies`). A read that answers after the visit, or+ /// the reader's access, is over marks nothing.+ Future<void> showReplies(SwarmFollowedThread thread) async {+ if (_disposed ||+ !_open ||+ reader.accessRevoked ||+ newReplies.containsKey(thread.key) ||+ _repliesFailed.contains(thread.key) ||+ !_readingReplies.add(thread.key)) {+ return;+ }+ final generation = reader.generation;+ final visit = _visit;+ final seen =+ reader.readMarks?.threadThrough(thread.conversationId, thread.rootId) ??+ reader.snapshot?.threadMarks[thread.conversationId]?[thread.rootId] ??+ 0;+ bool current() =>+ !_disposed &&+ !reader.accessRevoked &&+ reader.generation == generation &&+ _visit == visit &&+ _readingReplies.contains(thread.key);+ try {+ final answer = superTabMap(+ await reader.request(+ 'GET',+ '$_path/conversations/${Uri.encodeComponent(thread.conversationId)}'+ '/messages?thread=${Uri.encodeQueryComponent(thread.rootId)}',+ ),+ );+ if (!current()) return;+ final replies = [+ for (final row in answer['messages'] as List? ?? const [])+ if (row is Map)+ if (SuperTabMessage.fromJson(superTabMap(row)) case final m+ when m.conversationId == thread.conversationId &&+ m.thread == thread.rootId &&+ m.threadReply &&+ m.sequence > seen)+ m,+ ]..sort((a, b) => a.sequence.compareTo(b.sequence));+ newReplies[thread.key] = replies.length > shownReplies+ ? replies.sublist(replies.length - shownReplies)+ : replies;+ final through = max(+ thread.lastReplySequence,+ replies.lastOrNull?.sequence ?? 0,+ );+ reader.readMarks?.markThreadRead(+ thread.conversationId,+ thread.rootId,+ through,+ );+ notifyListeners();+ } catch (_) {+ // The thread stays unread and its root shows; the next visit tries+ // again.+ if (current()) _repliesFailed.add(thread.key);+ } finally {+ if (_visit == visit) _readingReplies.remove(thread.key);+ }+ }++ /// Follows (true) or unfollows (false) [thread] on every device of the+ /// reader; false when the server did not keep it.+ Future<bool> setFollow(SwarmFollowedThread thread, bool follow) async {+ if (_disposed ||+ reader.accessRevoked ||+ !followSupported ||+ !following.add(thread.key)) {+ return false;+ }+ final generation = reader.generation;+ notifyListeners();+ try {+ await reader.request(+ 'POST',+ '$_path/conversations/${Uri.encodeComponent(thread.conversationId)}'+ '/threads/${Uri.encodeComponent(thread.rootId)}/follow',+ body: {'follow': follow},+ );+ if (_disposed || reader.accessRevoked) return false;+ if (reader.generation == generation) {+ _lastRead = null;+ unawaited(load());+ }+ return true;+ } catch (_) {+ return false;+ } finally {+ if (following.remove(thread.key) && !_disposed) notifyListeners();+ }+ }++ /// The last one showing it went: no read is waited for.+ @override+ void removeListener(VoidCallback listener) {+ super.removeListener(listener);+ if (_disposed || hasListeners) return;+ _trailing?.cancel();+ _trailing = null;+ }++ /// The first one showing it came: what moved while none did is read.+ @override+ void addListener(VoidCallback listener) {+ final first = !hasListeners;+ super.addListener(listener);+ if (first && !_disposed) _changed();+ }++ @override+ void dispose() {+ if (_disposed) return;+ _disposed = true;+ _trailing?.cancel();+ _trailing = null;+ reader.removeListener(_changed);+ reader.reads.removeListener(_changed);+ asks?.removeListener(_told);+ reader.readMarks?.removeListener(_told);+ super.dispose();+ }+}++/// One followed thread on the phone's Threads page, in the Swarm it is in.+typedef SwarmThreadEntry = ({+ String swarmId,+ String swarmName,+ SwarmFollowedThread thread,+});++/// The Threads row and page over the Swarms Home shows ([swarms]): each+/// Swarm's [SwarmThreads] ([source]) in one list, new first, then the rest,+/// each newest reply first; bold while any has new replies, its number the+/// sum of theirs. [changed] tells when the Swarms shown, or their sources,+/// may have changed (the inbox). A Swarm that leaves the list leaves the page+/// at once, with everything read of it.+class SwarmThreadsMerge extends ChangeNotifier {+ SwarmThreadsMerge({+ required this.source,+ required this.swarms,+ required this.changed,+ }) {+ changed.addListener(_sync);+ _sync();+ }++ /// [swarmId]'s threads, while it is listed.+ final SwarmThreads? Function(String swarmId) source;++ /// The Swarms shown, in Home's order.+ final List<SwarmListing> Function() swarms;+ final Listenable changed;++ /// Each Swarm shown with its threads, in Home's order.+ final _sources = <String, (SwarmListing, SwarmThreads)>{};+ bool _open = false, _disposed = false;++ /// How many new threads show their replies when the page opens, as many+ /// as the desktop's `kThreadsShowingReplies`.+ static const showingReplies = 10;++ /// More than one Swarm shown: each row names its Swarm.+ bool get manySwarms => _sources.length > 1;++ /// Every Swarm shown has answered since it was opened, or since who may+ /// read what in it changed; one that failed says so instead ([error]).+ bool get loaded =>+ _sources.values.every((s) => s.$2.loaded || s.$2.error != null);++ /// What the first Swarm that could not be read says; Retry reads those+ /// again ([retry]).+ String? get error =>+ [for (final (_, threads) in _sources.values) ?threads.error].firstOrNull;++ /// A followed thread has replies the person has not read: the row is bold.+ bool get unread => _sources.values.any((s) => s.$2.threadsUnread);++ /// The row's number: tags of the person in threads they have not read past.+ int get mentions =>+ _sources.values.fold(0, (n, s) => n + s.$2.threadMentions);++ /// A Swarm's server stopped short of everything.+ bool get more => _sources.values.any((s) => s.$2.more);++ SwarmThreads? _of(SwarmThreadEntry entry) => _sources[entry.swarmId]?.$2;++ List<SwarmThreadEntry> _entries(bool fresh) {+ final entries = [+ for (final (swarm, threads) in _sources.values)+ for (final thread in threads.shown)+ if (threads.isNew(thread) == fresh)+ (swarmId: swarm.id, swarmName: swarm.name, thread: thread),+ ];+ // One Swarm keeps its own order; several are put together by time.+ if (manySwarms) {+ entries.sort(+ (a, b) => (b.thread.lastReplyAt ?? DateTime(0)).compareTo(+ a.thread.lastReplyAt ?? DateTime(0),+ ),+ );+ }+ return entries;+ }++ /// Threads with new replies this visit, newest reply first.+ List<SwarmThreadEntry> get fresh => _entries(true);++ /// The rest, newest reply first.+ List<SwarmThreadEntry> get rest => _entries(false);++ int newCount(SwarmThreadEntry entry) =>+ _of(entry)?.newCount(entry.thread) ?? 0;++ /// [entry]'s new replies, once read; null until then.+ List<SuperTabMessage>? newReplies(SwarmThreadEntry entry) =>+ _of(entry)?.newReplies[entry.thread.key];++ /// Follow or Unfollow is offered: the server keeps it.+ bool followOffered(SwarmThreadEntry entry) =>+ _of(entry)?.followSupported ?? false;++ /// Follow or Unfollow of [entry] is on its way.+ bool following(SwarmThreadEntry entry) =>+ _of(entry)?.following.contains(entry.thread.key) ?? false;++ /// [entry]'s chat, while its Swarm lists it for the person.+ SuperTabConversation? chat(SwarmThreadEntry entry) =>+ _of(entry)?.reader.snapshot?.conversation(entry.thread.conversationId);++ Future<bool> setFollow(SwarmThreadEntry entry, bool follow) =>+ _of(entry)?.setFollow(entry.thread, follow) ?? Future.value(false);++ /// Reads again each Swarm that could not be read.+ void retry() {+ for (final (_, threads) in _sources.values) {+ if (threads.error != null) unawaited(threads.load());+ }+ }++ /// The page opened: each Swarm shown reads now, and what is new stays new+ /// until [closed].+ void opened() {+ if (_disposed || _open) return;+ _open = true;+ for (final (_, threads) in _sources.values) {+ threads.opened();+ }+ }++ void closed() {+ if (_disposed || !_open) return;+ _open = false;+ for (final (_, threads) in _sources.values) {+ threads.closed();+ }+ }++ /// The page shows its first new threads: their replies are read, and each+ /// is marked read once they are (the desktop's read on open).+ void showReplies() {+ if (_disposed) return;+ for (final entry in fresh.take(showingReplies)) {+ unawaited(_of(entry)?.showReplies(entry.thread));+ }+ }++ void _sync() {+ if (_disposed) return;+ final wanted = <String, (SwarmListing, SwarmThreads)>{+ for (final swarm in swarms())+ if (source(swarm.id) case final threads?) swarm.id: (swarm, threads),+ };+ var moved = wanted.length != _sources.length;+ for (final MapEntry(key: id, value: (_, threads)) in _sources.entries) {+ if (identical(wanted[id]?.$2, threads)) continue;+ moved = true;+ _detach(threads);+ }+ for (final MapEntry(key: id, value: (_, threads)) in wanted.entries) {+ if (identical(_sources[id]?.$2, threads)) continue;+ moved = true;+ threads.addListener(notifyListeners);+ if (_open) threads.opened();+ }+ _sources+ ..clear()+ ..addAll(wanted);+ if (moved) notifyListeners();+ }++ /// A Swarm dropped from the inbox has its threads disposed already: both+ /// are no-ops then.+ void _detach(SwarmThreads threads) {+ threads.removeListener(notifyListeners);+ if (_open) threads.closed();+ }++ @override+ void dispose() {+ if (_disposed) return;+ _disposed = true;+ changed.removeListener(_sync);+ for (final (_, threads) in _sources.values) {+ _detach(threads);+ }+ _sources.clear();+ super.dispose();+ }+}diff --git a/mobile/lib/swarm/swarm_threads_page.dart b/mobile/lib/swarm/swarm_threads_page.dartnew file mode 100644index 000000000..5be5d1d36--- /dev/null+++ b/mobile/lib/swarm/swarm_threads_page.dart@@ -0,0 +1,640 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/fzf.dart' show fzfAge;+import 'package:harness_mobile/phone/out_of_sight.dart';+import 'package:harness_mobile/phone/phone_navigation.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';++import 'swarm_inbox.dart' show SwarmListing;+import 'swarm_project_page.dart' show swarmChatRoute;+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';+import 'swarm_threads.dart';++/// The followed threads of the Swarms [shown] ([SwarmThreadsMerge]): every+/// Swarm's, or [swarmId]'s alone when Home shows that one. [changed] tells+/// when they may have changed, beside the inbox.+SwarmThreadsMerge swarmThreadsOf(+ SwarmSession session, {+ String? swarmId,+ List<SwarmListing> Function()? shown,+ Listenable? changed,+}) => SwarmThreadsMerge(+ source: session.inbox.threads,+ swarms:+ shown ??+ () => [+ for (final swarm in session.inbox.swarms)+ if (swarmId == null || swarm.id == swarmId) swarm,+ ],+ changed: changed == null+ ? session.inbox+ : Listenable.merge([session.inbox, changed]),+);++/// Opens Threads over [context]'s page, [swarmId]'s alone when Home shows+/// that Swarm.+void openSwarmThreads(BuildContext context, {String? swarmId}) => unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => SwarmThreadsPage(swarmId: swarmId),+ listensForItself: true,+ ),+ ),+);++/// Home's Threads row, over the projects: bold while a followed thread has+/// new replies, the person's tags in threads at its end (desktop's Threads+/// row, #2434). A tap opens Threads.+class SwarmThreadsRow extends StatelessWidget {+ const SwarmThreadsRow({+ super.key,+ required this.threads,+ required this.onTap,+ });++ final SwarmThreadsMerge threads;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: threads,+ builder: (context, _) {+ AppTheme.watch(context);+ final unread = threads.unread, tags = threads.mentions;+ final bright = unread || tags > 0;+ return Material(+ type: MaterialType.transparency,+ child: InkWell(+ key: const ValueKey('swarm-threads-row'),+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: SwarmRow.height),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ vertical: AppSpace.m,+ ),+ child: Row(+ children: [+ SizedBox(+ width: 16,+ child: Icon(+ LucideIcons.messagesSquare300,+ size: 16,+ color: bright+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ ),+ ),+ const SizedBox(width: AppSpace.s),+ Expanded(+ child: Semantics(+ label: unread && tags == 0 ? 'New replies' : null,+ child: Text(+ 'Threads',+ style: AppType.label(+ color: bright+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ height: 1.3,+ fontWeight: bright ? AppFont.semibold : null,+ ),+ ),+ ),+ ),+ if (tags > 0)+ SwarmTags(+ tags,+ key: const ValueKey('swarm-threads-tags'),+ filled: true,+ ),+ ],+ ),+ ),+ ),+ ),+ );+ },+ );+}++/// Threads, as Slack's and the desktop's (#2434): the threads the person+/// follows, those with new replies first under New replies, each with its+/// newest replies, then Earlier. Opening it reads what it shows: each new+/// thread is marked read on every device once its replies are in. A tap+/// opens the thread in its chat; ⋯, or a long press, Follow or Unfollow.+class SwarmThreadsPage extends StatefulWidget {+ const SwarmThreadsPage({super.key, this.swarmId, this.now = DateTime.now});++ /// Home shows this Swarm alone; null for every Swarm.+ final String? swarmId;+ final DateTime Function() now;++ @override+ State<SwarmThreadsPage> createState() => _SwarmThreadsPageState();+}++class _SwarmThreadsPageState extends State<SwarmThreadsPage> {+ SwarmSession? _session;+ SwarmThreadsMerge? _threads;+ bool _seen = false;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final session = SwarmScope.of(context);+ final seen = session != null && !OutOfSight.of(context);+ if (!identical(session, _session)) {+ _see(false);+ _threads?.dispose();+ _session = session;+ _threads = session == null+ ? null+ : swarmThreadsOf(session, swarmId: widget.swarmId);+ }+ _see(seen);+ }++ /// In sight: the Swarms are read, and the page reads its threads (and+ /// marks what it shows); out of sight, neither.+ void _see(bool seen) {+ final session = _session, threads = _threads;+ if (session == null || threads == null || seen == _seen) return;+ _seen = seen;+ if (seen) {+ session.enter();+ threads.opened();+ unawaited(session.inbox.refresh());+ } else {+ threads.closed();+ session.leave();+ }+ }++ @override+ void dispose() {+ _see(false);+ _threads?.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final threads = _threads;+ return Scaffold(+ backgroundColor: AppPalette.windowBg,+ body: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SwarmTopBar(+ leading: SwarmBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ title: 'Threads',+ ),+ if (threads != null)+ Expanded(+ child: ListenableBuilder(+ listenable: threads,+ builder: (context, _) => _list(context, threads),+ ),+ ),+ ],+ ),+ ),+ );+ }++ Widget _list(BuildContext context, SwarmThreadsMerge threads) {+ final fresh = threads.fresh, rest = threads.rest;+ // What it shows is read: the first threads with new replies.+ if (_seen) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && _seen) threads.showReplies();+ });+ }+ final note = AppType.caption(color: AppPalette.textSecondary, height: 1.35);+ Widget card(SwarmThreadEntry entry) => SwarmThreadCard(+ key: ValueKey('swarm-thread-${entry.swarmId}/${entry.thread.key}'),+ threads: threads,+ entry: entry,+ now: widget.now(),+ onOpen: () => _open(context, threads, entry),+ onMore: () => _more(context, threads, entry),+ );+ return ListView(+ key: const ValueKey('swarm-threads-list'),+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ AppSpace.xs,+ AppSpace.m,+ MediaQuery.paddingOf(context).bottom + AppSpace.xl,+ ),+ children: [+ if (threads.error case final error?)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: Row(+ children: [+ Expanded(child: Text(error, style: note)),+ SwarmButton(+ key: const ValueKey('swarm-threads-retry'),+ label: 'Try again',+ style: SwarmButtonStyle.link,+ onPressed: threads.retry,+ ),+ ],+ ),+ ),+ if (!threads.loaded)+ SwarmSkeletonRows(id: 'swarm-threads-loading', round: true)+ else if (fresh.isEmpty && rest.isEmpty && threads.error == null)+ Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.xs,+ vertical: AppSpace.s,+ ),+ child: Text(+ 'No threads yet.',+ key: const ValueKey('swarm-threads-none'),+ style: note,+ ),+ ),+ if (fresh.isNotEmpty) ...[+ const SwarmCaption('New replies', first: true),+ SwarmGroup(children: [for (final entry in fresh) card(entry)]),+ ],+ if (rest.isNotEmpty) ...[+ SwarmCaption('Earlier', first: fresh.isEmpty),+ SwarmGroup(children: [for (final entry in rest) card(entry)]),+ ],+ if (threads.more)+ Padding(+ padding: const EdgeInsets.all(AppSpace.s),+ child: Text('Older threads are not listed.', style: note),+ ),+ ],+ );+ }++ /// Opens [entry]'s chat at its newest new reply, which opens its thread,+ /// else at its root.+ void _open(+ BuildContext context,+ SwarmThreadsMerge threads,+ SwarmThreadEntry entry,+ ) {+ final reply = threads.newReplies(entry)?.lastOrNull;+ unawaited(+ Navigator.of(context).push(+ swarmChatRoute(+ swarmId: entry.swarmId,+ conversationId: entry.thread.conversationId,+ messageId: reply?.id ?? entry.thread.rootId,+ ),+ ),+ );+ }++ Future<void> _more(+ BuildContext context,+ SwarmThreadsMerge threads,+ SwarmThreadEntry entry,+ ) async {+ if (!threads.followOffered(entry)) return;+ final followed = entry.thread.follow != false;+ final key = entry.thread.key;+ bool listed() => [+ ...threads.fresh,+ ...threads.rest,+ ].any((e) => e.swarmId == entry.swarmId && e.thread.key == key);+ final picked = await showSwarmThreadFollowSheet(+ context,+ followed: followed,+ watch: threads,+ listed: listed,+ );+ if (picked != true || !mounted || !listed()) return;+ final kept = await threads.setFollow(entry, !followed);+ if (!kept && context.mounted) {+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ SnackBar(+ content: Text(followed ? 'Could not unfollow.' : 'Could not follow.'),+ ),+ );+ }+ }+}++/// One followed thread: where it is, its root, then its new replies while+/// new, else its reply count; a quiet ⋯ for Follow or Unfollow.+class SwarmThreadCard extends StatelessWidget {+ const SwarmThreadCard({+ super.key,+ required this.threads,+ required this.entry,+ required this.now,+ required this.onOpen,+ required this.onMore,+ });++ final SwarmThreadsMerge threads;+ final SwarmThreadEntry entry;+ final DateTime now;+ final VoidCallback onOpen, onMore;++ /// The words under the avatar start here: past it and the gap beside it.+ static const _indent = 32.0 + 12;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final thread = entry.thread;+ final fresh = threads.fresh.any(+ (e) => e.swarmId == entry.swarmId && e.thread.key == thread.key,+ );+ final replies = threads.newReplies(entry);+ final count = threads.newCount(entry);+ final chat = threads.chat(entry);+ final place = [+ '#${chat?.title ?? ''}',+ if (threads.manySwarms) entry.swarmName,+ ].where((part) => part.length > 1).join(' · ');+ final caption = AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.35,+ );+ return Material(+ type: MaterialType.transparency,+ child: InkWell(+ onTap: onOpen,+ onLongPress: threads.followOffered(entry) ? onMore : null,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.s,+ AppSpace.xs,+ AppSpace.m,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ place,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: caption,+ ),+ ),+ if (threads.followOffered(entry))+ SwarmIconButton(+ key: ValueKey('swarm-thread-more-${thread.key}'),+ icon: LucideIcons.ellipsis300,+ size: 18,+ label: thread.follow == false+ ? 'Follow thread'+ : 'Unfollow thread',+ onPressed: onMore,+ )+ else+ const SizedBox(height: 44),+ ],+ ),+ Padding(+ padding: const EdgeInsets.only(right: AppSpace.m),+ child: _Said(+ author: thread.rootAuthor,+ text: thread.rootText,+ at: thread.rootAt,+ now: now,+ strong: fresh,+ ),+ ),+ Padding(+ padding: const EdgeInsets.only(left: _indent, top: AppSpace.xs),+ child: fresh+ ? Text(+ count == 1 ? '1 new reply' : '$count new replies',+ key: ValueKey('swarm-thread-new-${thread.key}'),+ style: AppType.caption(+ color: AppPalette.accent,+ fontWeight: AppFont.semibold,+ height: 1.35,+ ),+ )+ : Text(+ [+ if (thread.replies case final n?)+ n == 1 ? '1 reply' : '$n replies',+ if (thread.lastReplyAt case final at?)+ 'last ${fzfAge(at.toLocal(), now.toLocal())}',+ ].join(' · '),+ style: caption,+ ),+ ),+ if (fresh && replies != null)+ for (final reply in replies)+ Padding(+ padding: const EdgeInsets.only(+ left: _indent,+ top: AppSpace.s,+ right: AppSpace.m,+ ),+ child: _Said(+ author: reply.author,+ text: reply.text,+ at: reply.createdAt,+ now: now,+ strong: true,+ small: true,+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}++/// One message in a thread card: who, when, and what they said.+class _Said extends StatelessWidget {+ const _Said({+ required this.author,+ required this.text,+ required this.at,+ required this.now,+ required this.strong,+ this.small = false,+ });++ final Map<String, dynamic> author;+ final String text;+ final DateTime? at;+ final DateTime now;+ final bool strong, small;++ @override+ Widget build(BuildContext context) {+ final id = author['id'] as String? ?? '';+ final name =+ author['displayName'] as String? ?? author['name'] as String? ?? '';+ final age = at == null ? '' : fzfAge(at!.toLocal(), now.toLocal());+ return Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SwarmAvatar(id: id, name: name, size: small ? 24 : 32),+ SizedBox(width: small ? 8 : 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ [name, age].where((part) => part.isNotEmpty).join(' · '),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.35,+ ),+ ),+ const SizedBox(height: 2),+ Text(+ text,+ maxLines: small ? 4 : 3,+ overflow: TextOverflow.ellipsis,+ style: AppType.label(+ color: strong+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ fontWeight: strong && !small ? AppFont.semibold : null,+ height: 1.3,+ ),+ ),+ ],+ ),+ ),+ ],+ );+ }+}++/// Follow or Unfollow of a thread ([followed]), on a sheet. Answers true when+/// tapped, null when closed. Once the thread is no longer [listed] — its+/// Swarm or access gone — it shows nothing of it and closes.+Future<bool?> showSwarmThreadFollowSheet(+ BuildContext context, {+ required bool followed,+ required Listenable watch,+ required bool Function() listed,+}) => showModalBottomSheet<bool>(+ context: context,+ backgroundColor: AppGlass.rowFill,+ shape: AppControl.sheetShape,+ builder: (context) =>+ _FollowSheet(followed: followed, watch: watch, listed: listed),+);++class _FollowSheet extends StatefulWidget {+ const _FollowSheet({+ required this.followed,+ required this.watch,+ required this.listed,+ });++ final bool followed;+ final Listenable watch;+ final bool Function() listed;++ @override+ State<_FollowSheet> createState() => _FollowSheetState();+}++class _FollowSheetState extends State<_FollowSheet> {+ bool _closing = false;++ /// Closes the sheet once, after the frame it went blank in.+ void _close() {+ if (_closing) return;+ _closing = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ final route = ModalRoute.of(context);+ if (route == null || !route.isActive) return;+ if (route.isCurrent) {+ Navigator.of(context).pop();+ } else {+ Navigator.of(context).removeRoute(route);+ }+ });+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: widget.watch,+ builder: (context, _) {+ if (_closing || !widget.listed()) {+ _close();+ return const SizedBox.shrink();+ }+ final followed = widget.followed;+ return SafeArea(+ top: false,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.m,+ AppSpace.l,+ AppSpace.l,+ ),+ child: SwarmGroup(+ children: [+ Material(+ type: MaterialType.transparency,+ child: InkWell(+ key: const ValueKey('swarm-thread-follow'),+ onTap: () => Navigator.of(context).pop(true),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ vertical: AppSpace.m,+ ),+ child: Row(+ children: [+ Icon(+ followed+ ? LucideIcons.bellOff300+ : LucideIcons.bell300,+ size: 18,+ color: AppPalette.textPrimary,+ ),+ const SizedBox(width: AppSpace.m),+ Text(+ followed ? 'Unfollow thread' : 'Follow thread',+ style: AppType.label(color: AppPalette.textPrimary),+ ),+ ],+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ },+ );+}diff --git a/mobile/test/swarm/swarm_conversation_test.dart b/mobile/test/swarm/swarm_conversation_test.dartindex 2ee5b2ff3..08a7c8085 100644--- a/mobile/test/swarm/swarm_conversation_test.dart+++ b/mobile/test/swarm/swarm_conversation_test.dart@@ -43,6 +43,7 @@ void main() {String role = 'owner',bool archived = false,Map<String, int> readMarks = const {},+ int? mainSequence,}) {final swarm = FakeSwarm();Map<String, dynamic> g1(int seq) => {@@ -53,6 +54,7 @@ void main() {lastMessageSequence: seq,),'archived': archived,+ 'lastMainSequence': ?mainSequence,};swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {...firstLoad(groups: [g1(sequence)], derived: {'readMarks': readMarks}),@@ -1221,21 +1223,21 @@ void main() {return (marks: marks, sent: sent);}- /// A change read in which g1 moved on to [sequence].- void moveOn(FakeSwarm swarm, int sequence) =>+ /// A change read in which g1 moved on to [sequence], its main stream to+ /// [main] where the server says it.+ void moveOn(FakeSwarm swarm, int sequence, {int? main}) =>swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c3',groups: [- part(- 'g1',- 9 + sequence,- groupData(+ part('g1', 9 + sequence, {+ ...groupData('g1',title: 'Fix login',agentIds: const ['agent-lead', 'agent-builder'],lastMessageSequence: sequence,),- ),+ 'lastMainSequence': ?main,+ }),],);@@ -1383,7 +1385,7 @@ void main() {test('an open chat whose newest message is a reply only in a thread is ''read through its newest message in the main stream, and a reply ''only in a thread arriving later marks nothing', () async {- final r = rig(sequence: 3, readMarks: const {'g1': 1});+ final r = rig(sequence: 3, readMarks: const {'g1': 1}, mainSequence: 2);final m = marked(r);r.swarm.routes[messages] = (_) => {'messages': [@@ -1406,7 +1408,7 @@ void main() {],'next': null,};- moveOn(r.swarm, 4);+ moveOn(r.swarm, 4, main: 2);await r.reader.refresh();await settle();@@ -1417,7 +1419,7 @@ void main() {test('a chat read before, opened again with no network, is read through ''the newest main-stream message it kept', () async {- final r = rig(sequence: 3, readMarks: const {'g1': 1});+ final r = rig(sequence: 3, readMarks: const {'g1': 1}, mainSequence: 2);final m = marked(r);r.swarm.routes[messages] = (_) => {'messages': [@@ -1447,7 +1449,7 @@ void main() {test('a chat opened at a reply only in a thread is read through the ''main-stream message before it', () async {- final r = rig(sequence: 4);+ final r = rig(sequence: 4, mainSequence: 4);final m = marked(r);r.swarm.routes[messages] = (_) => {'messages': [@@ -1467,6 +1469,49 @@ void main() {expect(m.sent, [2]);});+ test('a reply also sent to the chat is in the main stream, and moves '+ 'the mark when it is the newest', () async {+ final r = rig(sequence: 3, readMarks: const {'g1': 1}, mainSequence: 3);+ final m = marked(r);+ r.swarm.routes[messages] = (_) => {+ 'messages': [+ {+ ...message('m3', 3, text: 'also in the chat'),+ 'thread': 'm1',+ 'alsoInChat': true,+ },+ message('m2', 2),+ {...message('m1', 1), 'thread': 'm1'},+ ],+ 'next': null,+ };++ await open(r.reader);+ await settle();++ expect(m.sent, [3]);+ });++ test('a server too old to say a chat\'s newest main-stream message is '+ 'read through its newest message, as on the desktop', () async {+ final r = rig(sequence: 3, readMarks: const {'g1': 1});+ final m = marked(r);+ r.swarm.routes[messages] = (_) => {+ 'messages': [+ {...message('m3', 3, text: 'in the thread'), 'thread': 'm1'},+ message('m2', 2),+ {...message('m1', 1), 'thread': 'm1'},+ ],+ 'next': null,+ };++ await open(r.reader);+ await settle();++ expect(r.reader.snapshot!.conversation('g1')!.lastMainSequence, isNull);+ expect(m.sent, [3]);+ });+test('a mark the server holds ahead of what the chat shows is neither ''sent back nor replaced', () async {final r = rig(sequence: 3, readMarks: const {'g1': 5});diff --git a/mobile/test/swarm/swarm_home_test.dart b/mobile/test/swarm/swarm_home_test.dartindex 2e86faa18..b7ff83731 100644--- a/mobile/test/swarm/swarm_home_test.dart+++ b/mobile/test/swarm/swarm_home_test.dart@@ -524,7 +524,11 @@ void main() {await pump(tester, fake);expect(key('swarm-projects-loading'), findsNothing);- expect(key('swarm-title-loading'), findsNothing, reason: 'none will come');+ expect(+ key('swarm-title-loading'),+ findsNothing,+ reason: 'none will come',+ );final line = tester.widget<Text>(key('swarm-too-old'));expect(line.data, swarmServerTooOld);expect(line.style?.color, isNot(AppColors.danger));@@ -538,12 +542,13 @@ void main() {).first;- testWidgets('with nothing over it, Projects has the first room', (+ testWidgets('under the Threads row, Projects has the usual room', (tester,) async {await pump(tester, backend());- expect(first(tester, 'Projects'), isTrue);+ expect(find.byKey(const ValueKey('swarm-threads-row')), findsOneWidget);+ expect(first(tester, 'Projects'), isFalse);});testWidgets('over Pinned, Projects has the usual room', (tester) async {@@ -551,7 +556,7 @@ void main() {host.session!.home.pin(tab, project, true);await tester.pumpAndSettle();- expect(first(tester, 'Pinned'), isTrue);+ expect(first(tester, 'Pinned'), isFalse, reason: 'under Threads');expect(first(tester, 'Projects'), isFalse);});});@@ -790,11 +795,8 @@ void main() {'for ever', (tester) async {var now = _halfHourIn();final fake = backend()- ..routes['/api/super-tabs/$tab/parts'] = (_) => throw SuperTabFailure(- 'UPDATE_REQUIRED',- 'Update',- statusCode: 426,- );+ ..routes['/api/super-tabs/$tab/parts'] = (_) =>+ throw SuperTabFailure('UPDATE_REQUIRED', 'Update', statusCode: 426);await pump(tester, fake, now: () => now, settle: false);await away(tester,@@ -853,10 +855,7 @@ void main() {fake.routes['/api/super-tabs/$tab/parts'] = (_) => {...firstLoad(head: headData(- projects: [- inProject(project, 'public'),- inProject(web, 'private'),- ],+ projects: [inProject(project, 'public'), inProject(web, 'private')],),agents: [agent('agent-builder'), agent('agent-idle')],groups: [@@ -2567,10 +2566,7 @@ void main() {expect(key('swarm-title-loading'), findsOneWidget);expect(key('swarm-title'), findsNothing);- expect(- inside('swarm-title-button', find.byType(Skeleton)),- findsWidgets,- );+ expect(inside('swarm-title-button', find.byType(Skeleton)), findsWidgets);expect(find.text('Swarm'), findsNothing, reason: 'no word for a name');listed.complete();@@ -2584,24 +2580,26 @@ void main() {);});- testWidgets('a start screen has no Swarm coming: the title is no skeleton',- (tester) async {- final fake = backend();- final listed = hold(fake, '/api/super-tabs/list');- await pump(- tester,- fake,- computers: _Computers(const []),- settle: false,- );+ testWidgets(+ 'a start screen has no Swarm coming: the title is no skeleton',+ (tester) async {+ final fake = backend();+ final listed = hold(fake, '/api/super-tabs/list');+ await pump(+ tester,+ fake,+ computers: _Computers(const []),+ settle: false,+ );- expect(find.byType(SwarmStartView), findsOneWidget);- expect(key('swarm-title-loading'), findsNothing);- expect(tester.widget<Text>(key('swarm-title')).data, 'Swarm');+ expect(find.byType(SwarmStartView), findsOneWidget);+ expect(key('swarm-title-loading'), findsNothing);+ expect(tester.widget<Text>(key('swarm-title')).data, 'Swarm');- listed.complete();- await tester.pumpAndSettle();- });+ listed.complete();+ await tester.pumpAndSettle();+ },+ );testWidgets('the switcher opened before the list answers has a row on its ''way, and the Swarm in its place after', (tester) async {@@ -2678,9 +2676,7 @@ void main() {final listed = hold(fake, '/api/super-tabs/list');await pump(tester, fake, settle: false);final row = height(tester, 'swarm-projects-loading-0');- final loading = find.byKey(- const ValueKey('swarm-projects-loading-0'),- );+ final loading = find.byKey(const ValueKey('swarm-projects-loading-0'));final dot = tester.getCenter(find.descendant(of: loading, matching: find.byType(Skeleton)).first,);diff --git a/mobile/test/swarm/swarm_threads_merge_test.dart b/mobile/test/swarm/swarm_threads_merge_test.dartnew file mode 100644index 000000000..da4577abc--- /dev/null+++ b/mobile/test/swarm/swarm_threads_merge_test.dart@@ -0,0 +1,338 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_read_marks.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_threads.dart';++import 'swarm_fixture.dart';++/// The phone's one Threads row and page over the Swarms Home shows: each+/// Swarm's followed threads put together.+void main() {+ Map<String, dynamic> row(+ String chat,+ String root, {+ int unread = 0,+ String at = '2026-11-01T01:00:00.000Z',+ }) => {+ 'conversationId': chat,+ 'rootId': root,+ 'root': {+ 'id': root,+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'text': 'root $root',+ 'createdAt': '2026-11-01T00:00:00.000Z',+ },+ 'lastReplyAt': at,+ 'lastReplySequence': 3,+ 'unreadReplies': unread,+ 'replies': 2,+ 'follow': null,+ };++ /// One Swarm [id] listing chat [chat], whose threads route answers+ /// [answer].+ ({FakeSwarm swarm, SwarmReader reader, SwarmThreads threads}) swarmOf(+ String id,+ String chat,+ FutureOr<Object?> Function() answer,+ ) {+ final swarm = FakeSwarm();+ final path = '/api/super-tabs/$id';+ swarm.routes['$path/parts'] = (_) => firstLoad(+ tabId: id,+ groups: [groupData(chat, title: 'Chat $chat', lastMessageSequence: 3)],+ derived: {+ 'readMarks': {chat: 1},+ },+ );+ swarm.routes['$path/changes'] = (_) => changes(cursor: 'c2');+ swarm.routes['$path/threads'] = (_) => answer();+ swarm.routes['$path/conversations/'] = (_) => {'ok': true};+ final reader = SwarmReader(+ tabId: id,+ accountId: me,+ request: swarm.request,+ );+ final marks = SwarmReadMarks(reader, store: null);+ reader.readMarks = marks;+ final threads = SwarmThreads(reader);+ addTearDown(() {+ threads.dispose();+ marks.dispose();+ reader.dispose();+ });+ return (swarm: swarm, reader: reader, threads: threads);+ }++ /// The page over [sources], every one of them shown unless [shown] says.+ ({SwarmThreadsMerge merge, ValueNotifier<int> changed}) mergeOf(+ Map<String, SwarmThreads> sources, {+ List<String>? shown,+ }) {+ final changed = ValueNotifier(0);+ final merge = SwarmThreadsMerge(+ source: (id) => sources[id],+ swarms: () => [+ for (final id in shown ?? sources.keys.toList())+ (id: id, name: 'Swarm $id'),+ ],+ changed: changed,+ );+ merge.addListener(() {});+ addTearDown(merge.dispose);+ return (merge: merge, changed: changed);+ }++ test('puts the Swarms\' threads together, new first, newest reply first, '+ 'each naming its Swarm', () async {+ final a = swarmOf(+ 's1',+ 'g1',+ () => {+ 'unread': [row('g1', 'a1', unread: 1, at: '2026-11-01T01:00:00.000Z')],+ 'read': [row('g1', 'a2', at: '2026-11-01T05:00:00.000Z')],+ },+ );+ final b = swarmOf(+ 's2',+ 'h1',+ () => {+ 'unread': [row('h1', 'b1', unread: 2, at: '2026-11-01T03:00:00.000Z')],+ 'read': [row('h1', 'b2', at: '2026-11-01T04:00:00.000Z')],+ },+ );+ await a.reader.refresh();+ await b.reader.refresh();++ final m = mergeOf({'s1': a.threads, 's2': b.threads}).merge;+ await settle();++ expect(m.manySwarms, isTrue);+ expect(m.loaded, isTrue);+ expect(m.unread, isTrue);+ expect([for (final e in m.fresh) e.thread.key], ['h1/b1', 'g1/a1']);+ expect([for (final e in m.rest) e.thread.key], ['g1/a2', 'h1/b2']);+ expect(m.fresh.first.swarmName, 'Swarm s2');+ expect(m.chat(m.fresh.first)?.title, 'Chat h1');+ });++ test('a Swarm that leaves Home leaves the page at once', () async {+ final a = swarmOf(+ 's1',+ 'g1',+ () => {+ 'unread': [row('g1', 'a1', unread: 1)],+ 'read': [],+ },+ );+ final b = swarmOf(+ 's2',+ 'h1',+ () => {+ 'unread': [row('h1', 'b1', unread: 1)],+ 'read': [],+ },+ );+ await a.reader.refresh();+ await b.reader.refresh();+ final sources = {'s1': a.threads, 's2': b.threads};+ final r = mergeOf(sources);+ r.merge.opened();+ await settle();+ expect(r.merge.fresh, hasLength(2));++ var told = 0;+ r.merge.addListener(() => told++);+ sources.remove('s2');+ r.changed.value++;++ expect([for (final e in r.merge.fresh) e.swarmId], ['s1']);+ expect(r.merge.manySwarms, isFalse);+ told = 0;+ b.reader.revoke();+ expect(told, 0, reason: 'let go: its changes no longer reach the page');++ // Dropped from the inbox: its threads are disposed before the page hears.+ final c = swarmOf('s3', 'k1', () => {'unread': [], 'read': []});+ await c.reader.refresh();+ sources['s3'] = c.threads;+ r.changed.value++;+ await settle();+ c.threads.dispose();+ sources.remove('s3');+ r.changed.value++;+ expect([for (final e in r.merge.fresh) e.swarmId], ['s1']);+ r.merge.closed();+ });++ test('a Swarm that cannot be read says so, never Loading, and Retry reads '+ 'it again', () async {+ var fail = true;+ final a = swarmOf(+ 's1',+ 'g1',+ () => {+ 'unread': [row('g1', 'a1', unread: 1)],+ 'read': [],+ },+ );+ final b = swarmOf(+ 's2',+ 'h1',+ () => fail+ ? throw const SuperTabFailure('BUSY', 'Busy', statusCode: 500)+ : {+ 'unread': [row('h1', 'b1', unread: 1)],+ 'read': [],+ },+ );+ await a.reader.refresh();+ await b.reader.refresh();+ final m = mergeOf({'s1': a.threads, 's2': b.threads}).merge;+ await settle();++ expect(m.loaded, isTrue);+ expect(m.error, isNotNull);+ expect([for (final e in m.fresh) e.thread.key], ['g1/a1']);++ fail = false;+ m.retry();+ await settle();++ expect(m.error, isNull);+ expect(m.fresh, hasLength(2));+ });++ test('opening reads the first new threads\' replies, each in its own '+ 'Swarm, and only while open', () async {+ final a = swarmOf(+ 's1',+ 'g1',+ () => {+ 'unread': [+ for (var i = 0; i < 12; i++)+ row('g1', 'a$i', unread: 1, at: '2026-11-01T0${i % 10}:00:00.000Z'),+ ],+ 'read': [],+ },+ );+ final b = swarmOf(+ 's2',+ 'h1',+ () => {+ 'unread': [row('h1', 'b1', unread: 1, at: '2026-11-01T09:30:00.000Z')],+ 'read': [],+ },+ );+ for (final s in [a, b]) {+ s.swarm.routes['/api/super-tabs/${s.reader.tabId}/conversations/'] = (+ _,+ ) => {'messages': <Object>[]};+ }+ await a.reader.refresh();+ await b.reader.refresh();+ final m = mergeOf({'s1': a.threads, 's2': b.threads}).merge;+ await settle();++ m.showReplies();+ await settle();+ expect(+ [...a.swarm.paths, ...b.swarm.paths].where((p) => p.contains('?thread=')),+ isEmpty,+ reason: 'not open',+ );++ m.opened();+ await settle();+ m.showReplies();+ await settle();++ List<String> asked(FakeSwarm s) =>+ s.paths.where((p) => p.contains('?thread=')).toList();+ expect(asked(b.swarm), [+ '/api/super-tabs/s2/conversations/h1/messages?thread=b1',+ ]);+ expect(asked(a.swarm), hasLength(SwarmThreadsMerge.showingReplies - 1));+ expect(+ b.swarm.paths,+ contains('/api/super-tabs/s2/conversations/h1/threads/b1/read'),+ );+ expect(+ a.swarm.paths.where((p) => p.contains('/s2/') || p.contains('h1')),+ isEmpty,+ reason: 'never asked of the other Swarm',+ );+ m.closed();+ });++ test(+ 'access lost in one Swarm while the page is open takes only its rows',+ () async {+ final a = swarmOf(+ 's1',+ 'g1',+ () => {+ 'unread': [row('g1', 'a1', unread: 1)],+ 'read': [],+ },+ );+ final b = swarmOf(+ 's2',+ 'h1',+ () => {+ 'unread': [row('h1', 'b1', unread: 1)],+ 'read': [],+ },+ );+ await a.reader.refresh();+ await b.reader.refresh();+ final m = mergeOf({'s1': a.threads, 's2': b.threads}).merge;+ m.opened();+ await settle();++ b.reader.revoke();++ expect([for (final e in m.fresh) e.swarmId], ['s1']);+ expect(m.unread, isTrue);+ m.closed();+ },+ );++ test('Follow and Unfollow go to the thread\'s own Swarm', () async {+ final a = swarmOf(+ 's1',+ 'g1',+ () => {+ 'unread': [],+ 'read': [row('g1', 'a1')],+ },+ );+ final b = swarmOf(+ 's2',+ 'h1',+ () => {+ 'unread': [],+ 'read': [row('h1', 'b1')],+ },+ );+ await a.reader.refresh();+ await b.reader.refresh();+ final m = mergeOf({'s1': a.threads, 's2': b.threads}).merge;+ await settle();++ final entry = m.rest.firstWhere((e) => e.swarmId == 's2');+ expect(m.followOffered(entry), isTrue);+ expect(await m.setFollow(entry, false), isTrue);++ expect(+ b.swarm.calls.where((c) => c.path.endsWith('/follow')).single.path,+ '/api/super-tabs/s2/conversations/h1/threads/b1/follow',+ );+ expect(a.swarm.paths.where((p) => p.endsWith('/follow')), isEmpty);+ });+}diff --git a/mobile/test/swarm/swarm_threads_page_test.dart b/mobile/test/swarm/swarm_threads_page_test.dartnew file mode 100644index 000000000..5e5b60350--- /dev/null+++ b/mobile/test/swarm/swarm_threads_page_test.dart@@ -0,0 +1,276 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_threads_page.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// The phone's Threads page (desktop #2434): the threads the person follows,+/// new replies first, read on open; Follow and Unfollow on a sheet.+void main() {+ const path = '/api/super-tabs/$tab';++ Map<String, dynamic> row(+ String root, {+ int unread = 0,+ int last = 5,+ bool? follow,+ String text = 'Can we retry the refresh?',+ }) => {+ 'conversationId': 'g1',+ 'rootId': root,+ 'root': {+ 'id': root,+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'text': text,+ 'createdAt': '2026-11-01T00:00:00.000Z',+ },+ 'lastReplyAt': '2026-11-01T01:00:00.000Z',+ 'lastReplySequence': last,+ 'unreadReplies': unread,+ 'replies': 4,+ 'follow': follow,+ };++ Map<String, dynamic> reply(String id, int sequence, String root) => {+ 'id': id,+ 'conversationId': 'g1',+ 'text': 'reply $id',+ 'sequence': sequence,+ 'thread': root,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'createdAt': '2026-11-01T01:00:00.000Z',+ };++ /// One Swarm with chat g1; [threads] answers its followed threads.+ FakeSwarm backend({required Object? Function() threads, bool listed = true}) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ if (listed) {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['$path/parts'] = (_) => firstLoad(+ groups: [groupData('g1', title: 'Fix login', lastMessageSequence: 5)],+ derived: {+ 'readMarks': {'g1': 1},+ },+ );+ fake.routes['$path/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['$path/decisions'] = (_) => {'decisions': <Object>[]};+ fake.routes['$path/mentions'] = (_) => {'mentions': <Object>[]};+ fake.routes['$path/threads'] = (_) => threads();+ fake.routes['$path/conversations/'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };+ fake.routes['$path/conversations/g1/messages?thread=m1'] = (_) => {+ 'messages': [reply('r5', 5, 'm1'), reply('r4', 4, 'm1')],+ };+ return fake;+ }++ Future<SwarmHost> pump(WidgetTester tester, FakeSwarm fake) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: SwarmThreadsPage(now: () => DateTime.utc(2026, 11, 1, 2)),+ ),+ );+ await tester.pumpAndSettle();+ return host;+ }++ /// Leaves the page, so nothing it started outlives the test.+ Future<void> leave(WidgetTester tester) async {+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 30));+ }++ testWidgets('opening lists new replies, then Earlier, and marks the new '+ 'thread read once its replies show', (tester) async {+ final fake = backend(+ threads: () => {+ 'unread': [row('m1', unread: 2)],+ 'read': [row('m7', follow: true, text: 'Rate limits')],+ },+ );+ await pump(tester, fake);++ expect(find.text('New replies'), findsOneWidget);+ expect(find.text('Earlier'), findsOneWidget);+ expect(find.text('2 new replies'), findsOneWidget);+ expect(find.text('reply r4'), findsOneWidget);+ expect(find.text('reply r5'), findsOneWidget);+ expect(find.text('4 replies · last 1h'), findsOneWidget, reason: 'Earlier');+ expect(+ fake.calls.where(+ (c) => c.path == '$path/conversations/g1/threads/m1/read',+ ),+ [+ isA<({String method, String path, Map<String, dynamic>? body})>()+ .having((c) => c.body, 'body', {'sequence': 5}),+ ],+ );+ expect(+ fake.paths.where((p) => p.endsWith('/threads/m7/read')),+ isEmpty,+ reason: 'a read thread marks nothing',+ );+ await leave(tester);+ });++ testWidgets('a tap opens the chat at the newest new reply, which opens its '+ 'thread', (tester) async {+ await pump(+ tester,+ backend(+ threads: () => {+ 'unread': [row('m1', unread: 2)],+ 'read': [],+ },+ ),+ );++ await tester.tap(find.text('Can we retry the refresh?'));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 500));++ expect(+ find.byWidgetPredicate(+ (w) =>+ w is SwarmOpenedChat &&+ w.conversationId == 'g1' &&+ w.messageId == 'r5',+ ),+ findsOneWidget,+ );+ await leave(tester);+ });++ testWidgets('Unfollow from ⋯ is kept on the server, and the thread leaves', (+ tester,+ ) async {+ var followed = true;+ final fake = backend(+ threads: () => {+ 'unread': <Object>[],+ 'read': [if (followed) row('m7', follow: true, text: 'Rate limits')],+ },+ );+ fake.routes['$path/conversations/g1/threads/m7/follow'] = (body) {+ followed = body!['follow'] as bool;+ return {'ok': true};+ };+ await pump(tester, fake);++ await tester.tap(find.byKey(const ValueKey('swarm-thread-more-g1/m7')));+ await tester.pumpAndSettle();+ expect(find.text('Unfollow thread'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('swarm-thread-follow')));+ await tester.pumpAndSettle();++ expect(followed, isFalse);+ expect(find.text('Rate limits'), findsNothing);+ expect(find.text('No threads yet.'), findsOneWidget);+ await leave(tester);+ });++ testWidgets('access lost with the sheet open: the sheet closes and the rows '+ 'go', (tester) async {+ var listed = true;+ final fake = backend(+ threads: () => {+ 'unread': <Object>[],+ 'read': [row('m7', follow: true, text: 'Rate limits')],+ },+ );+ final host = await pump(tester, fake);+ await tester.tap(find.byKey(const ValueKey('swarm-thread-more-g1/m7')));+ await tester.pumpAndSettle();+ expect(find.text('Unfollow thread'), findsOneWidget);++ // Removed from the Swarm: the list no longer has it.+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ if (listed) {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ listed = false;+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();++ expect(find.text('Unfollow thread'), findsNothing);+ expect(find.text('Rate limits'), findsNothing);+ expect(fake.paths.where((p) => p.endsWith('/follow')), isEmpty);+ await leave(tester);+ });++ testWidgets('a server before followed threads lists the unread ones and '+ 'offers no ⋯', (tester) async {+ final fake = backend(+ threads: () =>+ throw const SuperTabFailure('NOT_FOUND', 'Nope', statusCode: 404),+ );+ fake.routes['$path/inbox'] = (_) => {+ 'threads': [+ {...row('m1', unread: 2), 'replies': null},+ ],+ };+ await pump(tester, fake);++ expect(find.text('2 new replies'), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-thread-more-g1/m1')), findsNothing);+ await leave(tester);+ });++ testWidgets('a failed read says so, never a skeleton for ever, and Try '+ 'again recovers', (tester) async {+ var fail = true;+ await pump(+ tester,+ backend(+ threads: () => fail+ ? throw const SuperTabFailure('BUSY', 'Busy', statusCode: 500)+ : {+ 'unread': <Object>[],+ 'read': [row('m7', follow: true, text: 'Rate limits')],+ },+ ),+ );++ expect(find.text('Could not load threads.'), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-threads-loading')), findsNothing);++ fail = false;+ await tester.tap(find.byKey(const ValueKey('swarm-threads-retry')));+ await tester.pumpAndSettle();++ expect(find.text('Could not load threads.'), findsNothing);+ expect(find.text('Rate limits'), findsOneWidget);+ await leave(tester);+ });+}diff --git a/mobile/test/swarm/swarm_threads_shots_test.dart b/mobile/test/swarm/swarm_threads_shots_test.dartnew file mode 100644index 000000000..5f69fa53f--- /dev/null+++ b/mobile/test/swarm/swarm_threads_shots_test.dart@@ -0,0 +1,292 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/cupertino.dart' show CupertinoPageRoute;+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_threads_page.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Review screenshots of Threads on the phone: Home's Threads row and the+/// Threads page, at 390 wide in both phone themes, with the app's own fonts,+/// from made-up data only, to the folder `SWARM_THREADS_SHOTS` names.+final shots = Platform.environment['SWARM_THREADS_SHOTS'];+void main() {+ setUpAll(() async {+ if (shots == null || !Platform.isMacOS) return;+ final sf = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {+ await (FontLoader(family)..addFont(Future.value(sf))).load();+ }+ final mono = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {+ await (FontLoader(family)..addFont(Future.value(mono))).load();+ }+ final manifest =+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;+ for (final entry in manifest.cast<Map<String, dynamic>>()) {+ final loader = FontLoader(entry['family'] as String);+ for (final font in (entry['fonts'] as List).cast<Map>()) {+ loader.addFont(rootBundle.load(font['asset'] as String));+ }+ await loader.load();+ }+ });++ const path = '/api/super-tabs/$tab';+ final now = DateTime.utc(2026, 11, 1, 9, 41);++ Map<String, dynamic> who(String id, String name) => {+ 'kind': 'agent',+ 'id': id,+ 'name': name,+ };++ Map<String, dynamic> row(+ String chat,+ String root, {+ required Map<String, dynamic> author,+ required String text,+ required DateTime last,+ int unread = 0,+ int replies = 2,+ }) => {+ 'conversationId': chat,+ 'rootId': root,+ 'root': {+ 'id': root,+ 'sequence': 1,+ 'author': author,+ 'text': text,+ 'createdAt': last.subtract(const Duration(minutes: 40)).toIso8601String(),+ },+ 'lastReplyAt': last.toIso8601String(),+ 'lastReplySequence': 20,+ 'unreadReplies': unread,+ 'replies': replies,+ 'follow': true,+ };++ Map<String, dynamic> reply(+ String id,+ int sequence,+ Map<String, dynamic> author,+ String text,+ ) => {+ 'id': id,+ 'conversationId': 'fix-login',+ 'text': text,+ 'sequence': sequence,+ 'thread': 'm1',+ 'author': author,+ 'createdAt': now+ .subtract(Duration(minutes: 20 - sequence))+ .toIso8601String(),+ };++ /// [load] with each chat last changed a few minutes before [now].+ Map<String, dynamic> withTimes(Map<String, dynamic> load) => {+ ...load,+ 'groups': [+ for (final g in load['groups'] as List)+ {+ ...g as Map<String, dynamic>,+ 'changedAt': now+ .subtract(const Duration(minutes: 2))+ .millisecondsSinceEpoch,+ },+ ],+ };++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'autonomous.ai', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['$path/parts'] = (_) => {+ ...withTimes(+ firstLoad(+ head: headData(name: 'autonomous.ai'),+ groups: [+ groupData(leadChat, title: 'Mobile', lastMessageSequence: 9),+ groupData('fix-login', title: 'fix-login', lastMessageSequence: 20),+ groupData('api', title: 'api', lastMessageSequence: 20),+ ],+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ ],+ derived: {+ 'readMarks': {leadChat: 9, 'fix-login': 20, 'api': 20},+ 'mentionsWaiting': 1,+ },+ ),+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['$path/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['$path/decisions'] = (_) => {'decisions': <Object>[]};+ fake.routes['$path/mentions'] = (_) => {+ 'mentions': [+ {+ 'id': 'tag-1',+ 'projectId': project,+ 'projectName': 'Mobile',+ 'conversationId': 'fix-login',+ 'conversationTitle': 'fix-login',+ 'messageId': 'r19',+ 'leadName': 'River',+ 'text': '@me can you check this on the phone?',+ 'createdAt': now.toIso8601String(),+ 'threadId': 'm1',+ 'messageSequence': 19,+ },+ ],+ };+ fake.routes['$path/threads'] = (_) => {+ 'unread': [+ row(+ 'fix-login',+ 'm1',+ author: who('agent-builder', 'Nova'),+ text: 'Can we retry the token refresh once before signing out?',+ last: now.subtract(const Duration(minutes: 2)),+ unread: 2,+ replies: 5,+ ),+ ],+ 'read': [+ row(+ 'api',+ 'm2',+ author: who('agent-lead', 'River'),+ text: 'Rate limits on the threads route: 30 reads a minute is fine.',+ last: now.subtract(const Duration(hours: 2)),+ replies: 4,+ ),+ row(+ 'fix-login',+ 'm3',+ author: who('agent-builder', 'Nova'),+ text: 'Screenshots for the sign-in error are in the PR.',+ last: now.subtract(const Duration(days: 1)),+ replies: 1,+ ),+ ],+ 'more': false,+ };+ fake.routes['$path/conversations/'] = (_) => {'ok': true};+ fake.routes['$path/conversations/fix-login/messages?thread=m1'] = (_) => {+ 'messages': [+ reply(+ 'r20',+ 20,+ who('agent-builder', 'Nova'),+ 'Agreed. I will add a test for the second failure.',+ ),+ reply(+ 'r19',+ 19,+ who('agent-lead', 'River'),+ 'Retry once, then sign out. @me can you check this on the phone?',+ ),+ ],+ };+ fake.routes['$path/conversations/$leadChat/messages'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };+ return fake;+ }++ testWidgets('Home\'s Threads row and the Threads page', (tester) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final boundary = GlobalKey();+ Future<void> capture(String name) => tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$shots/threads-$name-390-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (_, child) => SwarmScope(notifier: host, child: child!),+ onGenerateRoute: (_) => CupertinoPageRoute<void>(+ builder: (_) => SwarmPage(now: () => now),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('swarm-threads-row')), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-threads-tags')), findsOneWidget);+ await capture('home');++ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ key: const ValueKey('threads-page'),+ builder: (_, child) => SwarmScope(notifier: host, child: child!),+ home: SwarmThreadsPage(now: () => now),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('2 new replies'), findsOneWidget);+ await capture('page');++ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 30));+ host.dispose();+ }+ await tester.binding.setSurfaceSize(null);+ tester.view.resetPadding();+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_threads_test.dart b/mobile/test/swarm/swarm_threads_test.dartnew file mode 100644index 000000000..b7adc622f--- /dev/null+++ b/mobile/test/swarm/swarm_threads_test.dart@@ -0,0 +1,493 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_asks.dart';+import 'package:harness_mobile/swarm/swarm_read_marks.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_threads.dart';++import 'swarm_fixture.dart';++/// The threads the reader follows in one Swarm (backend+/// read/followedThreads.ts, #2434): the Threads row and page, read as the+/// desktop's `SuperTabAttention` reads them.+void main() {+ const path = '/api/super-tabs/$tab';+ const threadsRoute = '$path/threads';++ Map<String, dynamic> row(+ String chat,+ String root, {+ int last = 3,+ int unread = 0,+ int? replies = 2,+ bool? follow,+ String text = 'Can we retry the refresh?',+ String at = '2026-11-01T01:00:00.000Z',+ }) => {+ 'conversationId': chat,+ 'rootId': root,+ 'root': {+ 'id': root,+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'text': text,+ 'createdAt': '2026-11-01T00:00:00.000Z',+ },+ 'lastReplyAt': at,+ 'lastReplySequence': last,+ 'unreadReplies': unread,+ 'replies': ?replies,+ 'follow': follow,+ };++ Map<String, dynamic> reply(+ String chat,+ String id,+ int sequence,+ String root,+ ) => {+ 'id': id,+ 'conversationId': chat,+ 'text': 'reply $id',+ 'sequence': sequence,+ 'thread': root,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'createdAt': '2026-11-01T01:00:00.000Z',+ };++ Map<String, dynamic> mention(+ String id, {+ String chat = 'g1',+ String? thread,+ int? sequence,+ }) => {+ 'id': id,+ 'projectId': project,+ 'projectName': 'Mobile',+ 'conversationId': chat,+ 'conversationTitle': 'Fix login',+ 'messageId': 'msg-$id',+ 'leadName': 'River',+ 'text': 'Look',+ 'createdAt': '2026-11-01T01:00:00.000Z',+ 'threadId': ?thread,+ 'messageSequence': ?sequence,+ };++ /// A Swarm listing chats g1 and g2 (g2 muted), its read marks and asks, and+ /// its followed threads; [clock] is what the threads' gaps are measured by.+ ({+ FakeSwarm swarm,+ SwarmReader reader,+ SwarmThreads threads,+ SwarmReadMarks marks,+ List<({String path, Object? sequence})> sent,+ void Function(Duration) tick,+ void Function(int lastChangedAt) move,+ })+ rig({+ Map<String, dynamic> threadMarks = const {},+ List<Map<String, dynamic>> mentions = const [],+ }) {+ final swarm = FakeSwarm();+ var now = DateTime(2026, 11, 1, 9);+ final derived = {+ 'readMarks': {'g1': 1, 'g2': 1},+ 'threadMarks': threadMarks,+ 'chatSettings': {'g2': 'muted'},+ 'mentionsWaiting': mentions.length,+ };+ swarm.routes['$path/parts'] = (_) => firstLoad(+ groups: [+ groupData('g1', title: 'Fix login', lastMessageSequence: 9),+ groupData('g2', title: 'API', lastMessageSequence: 9),+ ],+ derived: derived,+ );+ swarm.routes['$path/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ swarm.routes['$path/mentions'] = (_) => {'mentions': mentions};+ swarm.routes['$path/decisions'] = (_) => {'decisions': <Object>[]};+ final sent = <({String path, Object? sequence})>[];+ swarm.routes['$path/conversations/'] = (body) {+ sent.add((path: swarm.calls.last.path, sequence: body?['sequence']));+ return {'ok': true};+ };+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ final marks = SwarmReadMarks(reader, store: null);+ reader.readMarks = marks;+ final asks = SwarmAsks(reader);+ final threads = SwarmThreads(reader, asks: asks, now: () => now);+ addTearDown(() {+ threads.dispose();+ asks.dispose();+ marks.dispose();+ reader.dispose();+ });+ return (+ swarm: swarm,+ reader: reader,+ threads: threads,+ marks: marks,+ sent: sent,+ tick: (d) => now = now.add(d),+ move: (at) =>+ swarm.routes['$path/changes'] = (_) =>+ changes(cursor: 'c$at', derived: derived, lastChangedAt: at),+ );+ }++ int threadReads(FakeSwarm swarm) =>+ swarm.paths.where((p) => p == threadsRoute).length;++ /// [r]'s threads shown, as the Threads row or page would: read once.+ Future<void> show(SwarmThreads threads) async {+ threads.addListener(() {});+ await settle();+ }++ test('lists followed threads, new first, and never a chat the Swarm does '+ 'not list for the reader', () async {+ final r = rig();+ r.swarm.routes[threadsRoute] = (_) => {+ 'unread': [+ row('g1', 'm1', unread: 2, at: '2026-11-01T02:00:00.000Z'),+ // Another project's chat, or someone's private Buddy chat.+ row('buddy-other', 'b1', unread: 1, text: 'private plan'),+ ],+ 'read': [+ row('g2', 'm5', follow: true, at: '2026-11-01T03:00:00.000Z'),+ row('elsewhere', 'e1', text: 'secret title'),+ ],+ 'more': false,+ };+ await r.reader.refresh();++ await show(r.threads);++ expect([for (final t in r.threads.shown) t.key], ['g1/m1', 'g2/m5']);+ expect(r.threads.threadsUnread, isTrue);+ expect(+ r.threads.shown.map((t) => t.rootText),+ isNot(contains(anyOf('private plan', 'secret title'))),+ );+ expect(r.threads.loaded, isTrue);+ expect(r.threads.followSupported, isTrue);+ });++ test('reads only while something shows it', () async {+ final r = rig();+ r.swarm.routes[threadsRoute] = (_) => {'unread': [], 'read': []};+ await r.reader.refresh();+ r.move(200);+ await r.reader.refresh();+ await settle();++ expect(threadReads(r.swarm), 0);++ await show(r.threads);+ expect(threadReads(r.swarm), 1);+ });++ test('a server before followed threads (404) lists the inbox\'s unread '+ 'threads and offers no Follow; the next visit asks again', () async {+ final r = rig();+ r.swarm.routes['$path/inbox'] = (_) => {+ 'threads': [row('g1', 'm1', unread: 1, replies: null)],+ };+ await r.reader.refresh();++ await show(r.threads);++ expect(r.swarm.paths, contains('$path/inbox'));+ expect([for (final t in r.threads.shown) t.key], ['g1/m1']);+ expect(r.threads.followSupported, isFalse);+ expect(await r.threads.setFollow(r.threads.shown.single, false), isFalse);+ expect(r.swarm.paths.where((p) => p.endsWith('/follow')), isEmpty);++ // Updated since: the page opened again finds Follow.+ r.swarm.routes[threadsRoute] = (_) => {+ 'unread': [row('g1', 'm1', unread: 1)],+ 'read': [],+ };+ r.threads.opened();+ await settle();+ expect(r.threads.followSupported, isTrue);+ r.threads.closed();+ });++ test('a failed first read says so, never Loading, and a later read '+ 'recovers with Follow', () async {+ final r = rig();+ var fail = true;+ r.swarm.routes[threadsRoute] = (_) => fail+ ? throw const SuperTabFailure('BUSY', 'Busy', statusCode: 500)+ : {+ 'unread': [row('g1', 'm1', unread: 1)],+ 'read': [],+ };+ // A busy server is not one before followed threads.+ r.swarm.routes['$path/inbox'] = (_) => {'threads': <Object>[]};+ await r.reader.refresh();++ await show(r.threads);+ expect(r.threads.loaded, isFalse);+ expect(r.threads.error, isNotNull);++ fail = false;+ await r.threads.load();++ expect(r.threads.error, isNull);+ expect(r.threads.loaded, isTrue);+ expect(r.threads.followSupported, isTrue);+ expect(r.threads.threadsUnread, isTrue);+ });++ test('asked too often (429), it waits before reading again', () async {+ final r = rig();+ var busy = true;+ r.swarm.routes[threadsRoute] = (_) => busy+ ? throw const SuperTabFailure('BUSY', 'Slow down', statusCode: 429)+ : {'unread': [], 'read': []};+ await r.reader.refresh();+ r.threads+ ..addListener(() {})+ ..opened();+ await settle();+ expect(threadReads(r.swarm), 1);+ expect(r.threads.error, isNotNull);++ busy = false;+ // Past the open page's gap, inside the wait.+ r.tick(SwarmThreads.openGap + const Duration(seconds: 1));+ r.move(200);+ await r.reader.refresh();+ await settle();+ expect(threadReads(r.swarm), 1, reason: 'inside the wait');++ r.tick(SwarmThreads.busyWait);+ r.move(300);+ await r.reader.refresh();+ await settle();+ expect(threadReads(r.swarm), 2, reason: 'the wait is over');+ expect(r.threads.error, isNull);+ r.threads.closed();+ });++ group('the page', () {+ test('opening shows a new thread\'s newest replies and marks it read '+ 'through its last reply, once', () async {+ final r = rig(+ threadMarks: {+ 'g1': {'m1': 2},+ },+ );+ r.swarm.routes[threadsRoute] = (_) => {+ 'unread': [row('g1', 'm1', last: 9, unread: 7)],+ 'read': [],+ };+ r.swarm.routes['$path/conversations/g1/messages?thread=m1'] = (_) => {+ 'messages': [for (var s = 9; s >= 2; s--) reply('g1', 'r$s', s, 'm1')],+ };+ await r.reader.refresh();+ await settle();+ r.threads.opened();+ await settle();+ final thread = r.threads.shown.single;++ await r.threads.showReplies(thread);+ await r.threads.showReplies(thread);+ await settle();++ expect(+ [for (final m in r.threads.newReplies[thread.key]!) m.id],+ ['r5', 'r6', 'r7', 'r8', 'r9'],+ );+ expect(r.sent, [+ (path: '$path/conversations/g1/threads/m1/read', sequence: 9),+ ]);+ expect(r.marks.threadThrough('g1', 'm1'), 9);+ expect(r.threads.newCount(thread), 7, reason: 'what it had this visit');+ r.threads.closed();+ });++ test('unfollow is kept on the server, and a new reply then lists and '+ 'marks nothing', () async {+ final r = rig();+ var followed = true;+ r.swarm.routes[threadsRoute] = (_) => {+ 'unread': <Object>[],+ 'read': [if (followed) row('g1', 'm1', follow: true)],+ };+ r.swarm.routes['$path/conversations/g1/threads/m1/follow'] = (body) {+ followed = body!['follow'] as bool;+ return {'ok': true};+ };+ await r.reader.refresh();+ r.threads.opened();+ await settle();++ expect(await r.threads.setFollow(r.threads.shown.single, false), isTrue);+ await settle();+ expect(r.swarm.calls.last.path, threadsRoute, reason: 'read again');+ expect(r.swarm.calls.firstWhere((c) => c.path.endsWith('/follow')).body, {+ 'follow': false,+ });+ expect(r.threads.shown, isEmpty);++ // A new reply in it: the server lists it nowhere for this reader.+ r.tick(SwarmThreads.quietGap);+ r.move(200);+ await r.reader.refresh();+ await settle();++ expect(r.threads.shown, isEmpty);+ expect(r.threads.threadsUnread, isFalse);+ expect(r.sent, isEmpty);+ r.threads.closed();+ });++ test('replies read for a visit that is over mark nothing, the page '+ 'opened again or not', () async {+ final r = rig();+ r.swarm.routes[threadsRoute] = (_) => {+ 'unread': [row('g1', 'm1', last: 4, unread: 1)],+ 'read': [],+ };+ final answers = <Completer<Object?>>[];+ r.swarm.routes['$path/conversations/g1/messages?thread=m1'] = (_) =>+ (answers..add(Completer())).last.future;+ await r.reader.refresh();+ r.threads.opened();+ await settle();+ final thread = r.threads.shown.single;++ final first = r.threads.showReplies(thread);+ r.threads.closed();+ r.threads.opened();+ await settle();+ final second = r.threads.showReplies(thread);+ await settle();+ answers.first.complete({+ 'messages': [reply('g1', 'r4', 4, 'm1')],+ });+ await first;+ await settle();++ expect(r.sent, isEmpty, reason: 'the first visit is over');+ expect(r.threads.newReplies, isEmpty);++ r.threads.closed();+ answers.last.complete({+ 'messages': [reply('g1', 'r4', 4, 'm1')],+ });+ await second;+ await settle();+ expect(r.sent, isEmpty, reason: 'closed');+ });+ });++ group('access', () {+ test('lost while the page is open: rows, replies and pending answers go, '+ 'and nothing is marked', () async {+ final r = rig();+ r.swarm.routes[threadsRoute] = (_) => {+ 'unread': [+ row('g1', 'm1', last: 4, unread: 1),+ row('g1', 'm2', last: 5, unread: 1),+ ],+ 'read': [],+ };+ r.swarm.routes['$path/conversations/g1/messages?thread=m1'] = (_) => {+ 'messages': [reply('g1', 'r4', 4, 'm1')],+ };+ final replies = Completer<Object?>();+ r.swarm.routes['$path/conversations/g1/messages?thread=m2'] = (_) =>+ replies.future;+ await r.reader.refresh();+ r.threads.opened();+ await settle();+ await r.threads.showReplies(r.threads.shown.first);+ await settle();+ final second = r.threads.shown.firstWhere((t) => t.rootId == 'm2');+ final reading = r.threads.showReplies(second);+ final list = Completer<Object?>();+ r.swarm.routes[threadsRoute] = (_) => list.future;+ final relist = r.threads.load();+ final sentBefore = r.sent.length;++ r.reader.revoke();+ replies.complete({+ 'messages': [reply('g1', 'r5', 5, 'm2')],+ });+ list.complete({+ 'unread': [row('g1', 'm1', unread: 1)],+ 'read': [],+ });+ await reading;+ await relist;+ await settle();++ expect(r.threads.shown, isEmpty);+ expect(r.threads.newReplies, isEmpty);+ expect(r.threads.loaded, isFalse);+ expect(r.threads.threadMentions, 0);+ expect(r.sent.length, sentBefore, reason: 'no mark after access went');+ expect(await r.threads.setFollow(second, false), isFalse);+ });++ test(+ 'an answer asked before who may read what changed is not shown',+ () async {+ final r = rig();+ final list = Completer<Object?>();+ r.swarm.routes[threadsRoute] = (_) => list.future;+ await r.reader.refresh();+ r.threads.addListener(() {});+ await settle();++ r.reader.generation++;+ list.complete({+ 'unread': [row('g1', 'm1', unread: 1)],+ 'read': [],+ });+ await settle();++ expect(r.threads.shown, isEmpty);+ expect(r.threads.loaded, isFalse);+ },+ );+ });++ group('the Threads row\'s number', () {+ test('counts tags in threads not read past, never in a muted chat, the '+ 'main stream or a chat the Swarm does not list', () async {+ final r = rig(+ threadMarks: {+ 'g1': {'m9': 6},+ },+ mentions: [+ mention('t1', thread: 'm1', sequence: 4),+ mention('t2', thread: 'm9', sequence: 5), // read past+ mention('t3', chat: 'g2', thread: 'm3', sequence: 7), // muted+ mention('t4', sequence: 8), // main stream+ mention('t5', chat: 'private', thread: 'p1', sequence: 9),+ ],+ );+ r.swarm.routes[threadsRoute] = (_) => {'unread': [], 'read': []};+ await r.reader.refresh();+ await settle();++ expect(r.threads.threadMentions, 1);++ r.marks.markThreadRead('g1', 'm1', 4);+ expect(r.threads.threadMentions, 0);+ });+ });+}