Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Phone: threads like Slack Mobile (Tony, option B) (#2180)

harness-for-autonomous[bot]7f8e5722c0e5
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index 3fd115f95..41cfedd93 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -215,7 +215,7 @@ class SuperTabConversation {
/// The newest message that makes it unread, as the desktop's
/// `SuperTabController.unread` counts it: a reply only in its thread does
- /// not, though the phone, with no thread view yet, shows it in the chat.
+ /// not, as it is not in the chat.
int get mainSequence => lastMainSequence ?? lastMessageSequence;
/// Moves whenever a reaction here is added or taken back (backend
@@ -803,7 +803,8 @@ class SuperTabDelivery {
/// What a page says about one thread (backend threads.ts): the line under its
/// root, and who it marks unread for. Read as the desktop's model reads it
-/// (desktop_parity_test); the phone shows none of it yet.
+/// (desktop_parity_test); the phone draws the line, not yet who it is unread
+/// for.
class SuperTabThread {
SuperTabThread.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
@@ -863,7 +864,6 @@ class SuperTabMessage {
bool get threadReply => thread != null && thread != id;
/// Whether the main stream lists it: a thread reply only when also sent.
- /// The phone, with no thread view yet, shows every reply in the chat.
bool get inMainStream => !threadReply || alsoInChat;
final int sequence;
final Map<String, dynamic> author;
diff --git a/mobile/lib/swarm/swarm_chat_cache.dart b/mobile/lib/swarm/swarm_chat_cache.dart
index 3a6ed4d01..88d13b879 100644
--- a/mobile/lib/swarm/swarm_chat_cache.dart
+++ b/mobile/lib/swarm/swarm_chat_cache.dart
@@ -4,11 +4,13 @@ import 'model.dart';
import 'swarm_reader.dart';
/// What a closed chat held: its messages, oldest first, where the earlier
-/// ones start, and the reaction counter they were read with.
+/// ones start, the reaction counter they were read with, and the thread lines
+/// of their roots.
typedef SwarmChatKept = ({
List<SuperTabMessage> messages,
SuperTabPage? before,
int? reactionSeq,
+ Map<String, SuperTabThread> threads,
});
/// The chats last read on this phone, so one opened again shows at once what
@@ -42,18 +44,21 @@ abstract final class SwarmChatCache {
messages: kept.messages,
before: kept.before,
reactionSeq: kept.reactionSeq,
+ threads: kept.threads,
);
}
/// Keeps chat [id] as [reader] read it — its newest [page] of [messages],
- /// oldest first, and where the earlier ones start — as the newest kept;
- /// unless its Swarm's read no longer has it, or nothing of it was read.
+ /// oldest first, where the earlier ones start, and the [threads] of the
+ /// roots among them — as the newest kept; unless its Swarm's read no longer
+ /// has it, or nothing of it was read.
static void keep(
SwarmReader reader,
String id, {
required List<SuperTabMessage> messages,
required SuperTabPage? before,
int? reactionSeq,
+ Map<String, SuperTabThread> threads = const {},
}) {
_kept.remove((reader, id));
if (messages.length > page) {
@@ -61,11 +66,16 @@ abstract final class SwarmChatCache {
before = SuperTabPage.of(messages.first);
}
if (messages.isNotEmpty && _holds(reader, id, reader.generation)) {
+ final roots = {for (final m in messages) m.id};
_kept[(reader, id)] = _Kept(
messages,
before,
reader.generation,
reactionSeq,
+ Map.unmodifiable({
+ for (final MapEntry(key: root, value: thread) in threads.entries)
+ if (roots.contains(root)) root: thread,
+ }),
);
while (_kept.length > size) {
_kept.remove(_kept.keys.first);
@@ -120,10 +130,17 @@ abstract final class SwarmChatCache {
}
class _Kept {
- _Kept(this.messages, this.before, this.generation, this.reactionSeq);
+ _Kept(
+ this.messages,
+ this.before,
+ this.generation,
+ this.reactionSeq,
+ this.threads,
+ );
final List<SuperTabMessage> messages;
final SuperTabPage? before;
final int? reactionSeq;
+ final Map<String, SuperTabThread> threads;
/// The reader's [SwarmReader.generation] it was read under.
final int generation;
diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dart
index 5f344c5cb..58347f1c6 100644
--- a/mobile/lib/swarm/swarm_conversation.dart
+++ b/mobile/lib/swarm/swarm_conversation.dart
@@ -39,6 +39,7 @@ class SwarmConversation extends ChangeNotifier {
messages = kept.messages;
_before = kept.before;
_reactionSeq = kept.reactionSeq;
+ _threads.addAll(kept.threads);
_read = _kept = true;
_markRead();
}
@@ -61,9 +62,43 @@ class SwarmConversation extends ChangeNotifier {
/// The files of a post are on their way to the backend, before the post.
bool uploading = false;
- /// Oldest first.
+ /// Oldest first: every message read, a reply only in its thread too.
List<SuperTabMessage> messages = const [];
+ /// The [messages] the chat lists: a reply only in its thread shows there
+ /// alone ([SuperTabMessage.inMainStream], the desktop's main stream).
+ List<SuperTabMessage> get stream {
+ if (!identical(_streamOf, messages)) {
+ _streamOf = messages;
+ _stream = List.unmodifiable(messages.where((m) => m.inMainStream));
+ }
+ return _stream;
+ }
+
+ List<SuperTabMessage>? _streamOf;
+ List<SuperTabMessage> _stream = const [];
+
+ /// Each thread's line, by its root, as the newest page that named it said
+ /// it (the desktop's `_keepThreads`): its replies, who wrote them and when
+ /// the last came.
+ final _threads = <String, SuperTabThread>{};
+
+ /// [root]'s thread, once a page named it with a reply.
+ SuperTabThread? thread(String root) => _threads[root];
+
+ /// Each thread's draft while the chat is open (the desktop's
+ /// `threadDraft`): a thread closed and opened again finds it.
+ final _threadDrafts = <String, String>{};
+
+ String threadDraft(String root) => _threadDrafts[root] ?? '';
+ void setThreadDraft(String root, String text) {
+ if (text.isEmpty) {
+ _threadDrafts.remove(root);
+ } else {
+ _threadDrafts[root] = text;
+ }
+ }
+
/// On screen, no other screen covers it and Harness is in front: what it
/// shows is read ([SwarmReader.readMarks]), now and as new messages come.
bool get shown => _shown;
@@ -176,7 +211,8 @@ class SwarmConversation extends ChangeNotifier {
SuperTabMessage? _replyingTo;
- String get _path =>
+ /// Where its messages are read, a thread's with `?thread=`.
+ String get messagesPath =>
'/api/super-tabs/${Uri.encodeComponent(reader.tabId)}'
'/conversations/${Uri.encodeComponent(id)}/messages';
@@ -346,6 +382,7 @@ class SwarmConversation extends ChangeNotifier {
/// Drops the messages read, and the answer of any read under way.
void _forget() {
messages = const [];
+ _threads.clear();
_before = null;
_read = false;
_epoch++;
@@ -370,6 +407,7 @@ class SwarmConversation extends ChangeNotifier {
_refused = true;
_forget();
_draft = '';
+ _threadDrafts.clear();
_mentions.clear();
_pending = null;
_sent = null;
@@ -468,7 +506,9 @@ class SwarmConversation extends ChangeNotifier {
: again
? '?before=${tail + 1}'
: '?after=$tail';
- final answer = superTabMap(await reader.request('GET', '$_path$query'));
+ final answer = superTabMap(
+ await reader.request('GET', '$messagesPath$query'),
+ );
if (_disposed || epoch != _epoch) return;
final incoming = [
for (final row in answer['messages'] as List)
@@ -492,6 +532,7 @@ class SwarmConversation extends ChangeNotifier {
? <String, SuperTabMessage>{}
: {for (final m in messages) m.id: m};
var changed = !_read || error != null || _refused || latest;
+ changed |= _keepThreads(answer['threads']);
for (final m in incoming) {
if (byId[m.id] case final shown? when _same(shown, m)) continue;
byId[m.id] = m;
@@ -810,6 +851,40 @@ class SwarmConversation extends ChangeNotifier {
return refused == null;
}
+ /// Keeps the thread lines a page named ([thread]): one a later page said
+ /// is kept over an older one. True when a line drawn changed.
+ bool _keepThreads(Object? rows) {
+ if (rows is! List) return false;
+ var changed = false;
+ for (final row in rows) {
+ final next = SuperTabThread.fromJson(superTabMap(row));
+ final held = _threads[next.id];
+ if (held != null &&
+ (held.lastSequence > next.lastSequence || _sameThread(held, next))) {
+ continue;
+ }
+ _threads[next.id] = next;
+ changed = true;
+ }
+ return changed;
+ }
+
+ /// Thread lines a thread's own read brought ([SwarmThread]): the root's
+ /// line in the chat moves with them.
+ void keepThreads(Object? rows) {
+ if (!_disposed && _keepThreads(rows)) notifyListeners();
+ }
+
+ /// What a thread's line draws, the same in [a] as in [b].
+ static bool _sameThread(SuperTabThread a, SuperTabThread b) =>
+ a.replies == b.replies &&
+ a.lastSequence == b.lastSequence &&
+ a.lastAt == b.lastAt &&
+ listEquals(
+ [for (final who in a.authors) '${who['kind']}:${who['id']}'],
+ [for (final who in b.authors) '${who['kind']}:${who['id']}'],
+ );
+
/// A post moved between the composer and the messages: both are told.
void _tell() {
notifyListeners();
@@ -894,6 +969,7 @@ class SwarmConversation extends ChangeNotifier {
messages: messages,
before: _before,
reactionSeq: _reactionSeq,
+ threads: _threads,
);
}
reader.removeListener(_swarmChanged);
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index c4d2a0a7e..09844ea89 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -34,6 +34,9 @@ import 'swarm_project_page.dart';
import 'swarm_reactions.dart';
import 'swarm_session.dart';
import 'swarm_style.dart';
+import 'swarm_thread.dart';
+import 'swarm_thread_line.dart';
+import 'swarm_thread_page.dart';
import 'swarm_voice.dart';
import 'team_glance.dart';
@@ -406,11 +409,11 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
if (!back) {
c.heldAt = null;
} else {
- c.heldAt ??= c.messages.lastOrNull?.id;
+ c.heldAt ??= c.stream.lastOrNull?.id;
}
}
if (back == (_held.value != null)) return;
- _held.value = back ? _conversation?.messages.lastOrNull?.id : null;
+ _held.value = back ? _conversation?.stream.lastOrNull?.id : null;
}
/// How close to the oldest message shown the earlier ones start to be
@@ -484,6 +487,106 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
_focus.requestFocus();
}
+ /// Opens [root]'s thread of [c] over the chat, full screen.
+ void _openThread(SwarmConversation c, String root) {
+ if (_acting != null) setState(() => _acting = null);
+ _focus.unfocus();
+ unawaited(
+ Navigator.of(context).push(
+ phoneRoute(
+ (_) => SwarmThreadPage(
+ swarmId: widget.swarmId,
+ chat: c,
+ root: root,
+ title: _view.value?.title,
+ row: (t, m, {required grouped, required acting, required onTap}) =>
+ _threadRow(
+ c,
+ t,
+ m,
+ grouped: grouped,
+ acting: acting,
+ onTap: onTap,
+ ),
+ pending: (t, text) => _threadPending(c, t, text),
+ ),
+ listensForItself: true,
+ ),
+ ),
+ );
+ }
+
+ /// One of thread [t]'s messages as the chat draws its own, less what only
+ /// the chat has: no quote, no thread line, no Reply (the box is the reply).
+ Widget _threadRow(
+ SwarmConversation c,
+ SwarmThread t,
+ SuperTabMessage m, {
+ required bool grouped,
+ required bool acting,
+ required VoidCallback onTap,
+ }) {
+ final view = _view.value;
+ if (view == null) return const SizedBox.shrink();
+ final pm = swarmIsPmLine(c.reader, m);
+ return SwarmMessageRow(
+ key: ValueKey('swarm-thread-message-${m.id}'),
+ message: m,
+ name: _nameOf(c, m),
+ look: _lookOf(c, m),
+ role: m.fromAgent && !pm ? view.roles[m.authorId] : null,
+ mentions: view.mentions,
+ grouped: grouped,
+ lit: false,
+ quote: null,
+ actions: acting,
+ onTap: onTap,
+ onReply: null,
+ onAuthor: m.fromAgent
+ ? null
+ : () => unawaited(
+ showSwarmPerson(
+ context,
+ swarmId: widget.swarmId,
+ personId: m.authorId,
+ ),
+ ),
+ reactions: SwarmReactionBar(
+ messageId: m.id,
+ reactions: c.reactionsOf(m),
+ readerId: c.reader.accountId,
+ nameOf: (kind, id) => _reactorName(c, kind, id),
+ onReact: view.canPost ? (emoji) => unawaited(t.react(m, emoji)) : null,
+ ),
+ onLongPress: view.canPost
+ ? () => unawaited(_pickThreadReaction(c, t, m.id))
+ : null,
+ );
+ }
+
+ /// The person's reply on its way in thread [t].
+ Widget _threadPending(SwarmConversation c, SwarmThread t, String text) {
+ final mine = t.messages.reversed
+ .where((m) => !m.fromAgent && m.authorId == c.reader.accountId)
+ .firstOrNull;
+ return KeyedSubtree(
+ key: const ValueKey('swarm-thread-pending'),
+ child: _Pending(
+ name: mine == null ? 'You' : _nameOf(c, mine),
+ look:
+ c.reader.snapshot?.personLook(c.reader.accountId) ??
+ (picture: null, status: null),
+ text: text,
+ files: const [],
+ mentions: _view.value?.mentions ?? SwarmMentions(const []),
+ // Taken by the backend and not read back yet: still on its way.
+ sending: t.sending || t.confirmed,
+ quote: null,
+ onSendAgain: () => unawaited(t.send()),
+ ),
+ );
+ }
+
/// How many earlier pages a quote's original is looked for in: as many as
/// a tag opens through on the desktop.
static const _findPages = 50;
@@ -501,6 +604,21 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
// once, with the original among the messages.
final found = await c.readBackTo(messageId, pages: _findPages);
if (!mounted || _conversation != c) return;
+ // A thread reply opens its thread; one shown only there has no row in
+ // the chat to bring into view (the desktop's tag and notice rule).
+ final target = found
+ ? c.messages.where((m) => m.id == messageId).firstOrNull
+ : null;
+ if (target != null && target.threadReply) {
+ _openThread(c, target.thread!);
+ if (!target.inMainStream) {
+ setState(() => _finding = false);
+ if (!_scroll.hasClients || _scroll.offset <= _readingBack) {
+ c.heldAt = null;
+ }
+ return;
+ }
+ }
setState(() {
_finding = false;
_note = found
@@ -616,7 +734,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
? _said(_notOpen)
: error != null
? _said(error)
- : const _ChatSkeleton(),
+ : const SwarmChatSkeleton(),
),
],
);
@@ -876,6 +994,25 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
return email == null ? 'Someone' : superTabPersonName(email);
}
+ /// The reaction picker over thread [t]'s message [id], as [_pickReaction]
+ /// does in the chat.
+ Future<void> _pickThreadReaction(
+ SwarmConversation c,
+ SwarmThread t,
+ String id,
+ ) async {
+ SuperTabMessage? shown() => t.messages.where((m) => m.id == id).firstOrNull;
+ final message = shown();
+ if (message == null) return;
+ final emoji = await showSwarmReactionPicker(
+ context,
+ reactions: c.reactionsOf(message),
+ readerId: c.reader.accountId,
+ );
+ if (emoji == null || !mounted) return;
+ if (shown() case final now?) await t.react(now, emoji);
+ }
+
/// The reaction picker over message [id]: the pick reacts to the message
/// as it is by then.
Future<void> _pickReaction(SwarmConversation c, String id) async {
@@ -907,14 +1044,14 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
) {
final state = c.state;
if (state == SwarmChatState.lost) return _said(c.error ?? _notOpen);
- if (c.messages.isEmpty && c.pending == null) {
+ if (c.stream.isEmpty && c.pending == null) {
if (state != SwarmChatState.loaded) {
// A first read that failed: said under the chat once it is known,
// here until then.
if (c.error case final error?) {
return view.known ? const SizedBox.shrink() : _said(error);
}
- return const _ChatSkeleton();
+ return const SwarmChatSkeleton();
}
if (view.decisions.isEmpty) {
return _said(
@@ -924,7 +1061,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
}
}
final snapshot = c.reader.snapshot;
- final messages = c.messages;
+ // A reply only in its thread shows there alone.
+ final messages = c.stream;
final from = (messages, view.decisions, c.hasOlder, _held.value);
if (from != _madeFrom) {
// Read back: the messages after the newest shown then wait below, and
@@ -942,7 +1080,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
if (!(need.decision.createdAt?.isAfter(last) ?? false)) need,
];
_shown = _timeline(shown, asks, hasOlder: c.hasOlder).reversed.toList();
- _byId = {for (final m in messages) m.id: m};
+ // Every message read, for the quotes.
+ _byId = {for (final m in c.messages) m.id: m};
_placeOf = {for (final (i, entry) in _shown.indexed) _keyOf(entry): i};
_rows.removeWhere((key, _) => !_placeOf.containsKey(key));
_madeFrom = from;
@@ -965,7 +1104,16 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
final today = DateUtils.dateOnly(DateTime.now());
return _row(key, (day, today), () => _Day(day: day, today: today));
case _MessageEntry(message: final m, :final grouped):
- final reply = m.replyTo == null ? null : byId[m.replyTo];
+ // A thread reply quotes nothing: it sits under its root, and one
+ // also sent here says so and opens the thread.
+ final reply = m.replyTo == null || m.threadReply
+ ? null
+ : byId[m.replyTo];
+ final root = m.thread;
+ final line = root == m.id ? c.thread(m.id) : null;
+ final faces = line == null
+ ? const <SwarmThreadFace>[]
+ : swarmThreadFaces(snapshot, line);
final name = _nameOf(c, m);
final look = _lookOf(c, m);
final pm = swarmIsPmLine(c.reader, m);
@@ -996,6 +1144,11 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
reactions,
answerIn,
view.project,
+ line,
+ [
+ for (final who in faces)
+ '${who.id}:${who.name}:${swarmLookKey(who.look)}',
+ ].join(','),
),
() => SwarmMessageRow(
key: followed ? _targetKey : null,
@@ -1007,7 +1160,12 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
grouped: grouped,
lit: lit,
followed: followed,
- quote: m.replyTo == null
+ quote: m.threadReply
+ ? SwarmRepliedInThread(
+ key: ValueKey('swarm-replied-in-thread-${m.id}'),
+ onOpen: () => _openThread(c, root!),
+ )
+ : m.replyTo == null
? null
: SwarmQuote(
key: ValueKey('swarm-quote-${m.id}'),
@@ -1018,7 +1176,22 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
actions: acting,
onTap: () =>
setState(() => _acting = _acting == m.id ? null : m.id),
- onReply: view.canPost ? () => _reply(c, m) : null,
+ // A message with a thread is answered there; one from before
+ // threads keeps the inline reply.
+ onReply: !view.canPost
+ ? null
+ : root != null
+ ? () => _openThread(c, root)
+ : () => _reply(c, m),
+ inThread: root != null,
+ thread: line == null || line.replies == 0
+ ? null
+ : SwarmThreadLine(
+ key: ValueKey('swarm-thread-line-${m.id}'),
+ thread: line,
+ faces: faces,
+ onOpen: () => _openThread(c, m.id),
+ ),
onAuthor: m.fromAgent
? null
: () => unawaited(
@@ -1169,12 +1342,14 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
return row;
}
- /// How many messages wait below while the person reads back.
+ /// How many messages wait below while the person reads back: those the
+ /// list will show, not replies only in their thread.
int _waiting(SwarmConversation c) {
final held = _held.value;
if (held == null) return 0;
- final at = c.messages.lastIndexWhere((m) => m.id == held);
- return at < 0 ? 0 : c.messages.length - at - 1;
+ final stream = c.stream;
+ final at = stream.lastIndexWhere((m) => m.id == held);
+ return at < 0 ? 0 : stream.length - at - 1;
}
/// Back to the foot, where the messages that waited show.
@@ -1270,7 +1445,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
),
),
),
- _Round(
+ SwarmRoundButton(
key: const ValueKey('swarm-reply-cancel'),
label: 'Cancel reply',
onTap: () => c.replyingTo = null,
@@ -1335,7 +1510,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (swarmSendsFiles)
- _Round(
+ SwarmRoundButton(
key: const ValueKey('swarm-attach'),
label: 'Attach files',
onTap: c.uploading || c.files.room <= 0
@@ -1351,7 +1526,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
),
const SizedBox(width: 6),
Expanded(
- child: _MessageField(
+ child: SwarmMessageField(
controller: _text,
focus: _focus,
hint: hint,
@@ -1361,7 +1536,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
SwarmVoiceMic(voice: voice)
else
const SizedBox(width: 6),
- _Round(
+ SwarmRoundButton(
key: const ValueKey('swarm-send'),
label: 'Send',
fill: canSend ? AppPalette.accent : ttyRaised(tty),
@@ -1755,9 +1930,9 @@ const _listPadding = EdgeInsets.fromLTRB(
/// The chat's first page on its way: bubbles in the shape of messages, at
/// the foot where they will show. Each has a fixed number of lines, so none
-/// changes height as it breathes.
-class _ChatSkeleton extends StatelessWidget {
- const _ChatSkeleton();
+/// changes height as it breathes. A thread's first read shows it too.
+class SwarmChatSkeleton extends StatelessWidget {
+ const SwarmChatSkeleton({super.key});
/// Each bubble's lines and its last line's width, newest last.
static const _bubbles = [
@@ -2264,18 +2439,23 @@ class _AnswerIn extends StatelessWidget {
}
/// The composer's field: one rounded line that grows with what is typed, up
-/// to five, in the app's own face.
-class _MessageField extends StatelessWidget {
- const _MessageField({
+/// to five, in the app's own face. A thread's reply box has it too.
+class SwarmMessageField extends StatelessWidget {
+ const SwarmMessageField({
+ super.key,
required this.controller,
required this.focus,
required this.hint,
+ this.fieldKey = const ValueKey('swarm-field'),
});
final TextEditingController controller;
final FocusNode focus;
final String hint;
+ /// The pill's key: the chat's and a thread's box are told apart by it.
+ final Key fieldKey;
+
@override
Widget build(BuildContext context) {
final tty = Tty.of(context);
@@ -2284,7 +2464,7 @@ class _MessageField extends StatelessWidget {
behavior: HitTestBehavior.opaque,
onTap: focus.requestFocus,
child: Container(
- key: const ValueKey('swarm-field'),
+ key: fieldKey,
constraints: const BoxConstraints(minHeight: 44),
alignment: Alignment.centerLeft,
// One line rests at the 44 of the buttons beside it.
@@ -2345,9 +2525,10 @@ class _MessageField extends StatelessWidget {
}
}
-/// A round 44pt button: @, Send, the reply bar's ✕. [fill] draws it solid.
-class _Round extends StatelessWidget {
- const _Round({
+/// A round 44pt button: @, Send, the reply bar's ✕, a thread's Send. [fill]
+/// draws it solid.
+class SwarmRoundButton extends StatelessWidget {
+ const SwarmRoundButton({
super.key,
required this.label,
required this.onTap,
diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dart
index 6b18f5138..5283196c5 100644
--- a/mobile/lib/swarm/swarm_message_row.dart
+++ b/mobile/lib/swarm/swarm_message_row.dart
@@ -181,9 +181,9 @@ class SwarmMessageFrame extends StatelessWidget {
}
/// One message: avatar, who wrote it, their role and when — none of it for a
-/// follow-up — then what it answers, its text, its files and its
-/// [reactions]. A tap opens its actions, a long-press [onLongPress]; lit for
-/// a moment when a quote leads to it.
+/// follow-up — then what it answers, its text, its files, its [reactions] and
+/// its [thread]'s line. A tap opens its actions, a long-press [onLongPress];
+/// lit for a moment when a quote leads to it.
class SwarmMessageRow extends StatelessWidget {
const SwarmMessageRow({
super.key,
@@ -199,8 +199,10 @@ class SwarmMessageRow extends StatelessWidget {
required this.actions,
required this.onTap,
required this.onReply,
+ this.inThread = false,
this.onAuthor,
this.reactions,
+ this.thread,
this.below,
this.onLongPress,
});
@@ -221,15 +223,22 @@ class SwarmMessageRow extends StatelessWidget {
final Widget? quote;
final VoidCallback onTap;
- /// Null where the person cannot post.
+ /// Null where the person cannot post, or in the thread itself.
final VoidCallback? onReply;
+ /// [onReply] opens the message's thread: "Reply in thread", where a
+ /// message from before threads keeps "Reply" and its inline quote.
+ final bool inThread;
+
/// Who wrote it, in a sheet; null where nothing opens.
final VoidCallback? onAuthor;
/// Drawn under its text and files: its reaction counts.
final Widget? reactions;
+ /// Under its reactions: the line of the thread it is the root of.
+ final Widget? thread;
+
/// Under its reactions: what the person may do with it besides Reply — the
/// PM's private line answered in the project chat.
final Widget? below;
@@ -312,6 +321,7 @@ class SwarmMessageRow extends StatelessWidget {
),
),
?reactions,
+ ?thread,
?below,
if (actions)
Padding(
@@ -323,8 +333,10 @@ class SwarmMessageRow extends StatelessWidget {
if (onReply case final reply?)
SwarmSmallButton(
key: ValueKey('swarm-reply-${message.id}'),
- icon: LucideIcons.reply,
- label: 'Reply',
+ icon: inThread
+ ? LucideIcons.messageSquareReply
+ : LucideIcons.reply,
+ label: inThread ? 'Reply in thread' : 'Reply',
onTap: reply,
),
SwarmSmallButton(
@@ -443,10 +455,15 @@ class SwarmChatAvatar extends StatelessWidget {
this.pm = false,
this.picture,
this.status,
+ this.diameter = size,
});
static const double size = 32;
+ /// How wide it is drawn: [size] beside a message, smaller in a thread's
+ /// line.
+ final double diameter;
+
/// The member palette's hues in the order the chat has always given them,
/// so no one's colour moves: the [pm]'s blue first, then the six an agent
/// takes by its id (blue, teal, violet, amber, rose, green, slate).
@@ -480,21 +497,21 @@ class SwarmChatAvatar extends StatelessWidget {
: name.trim().characters.first.toUpperCase();
return SwarmStatusFace(
name: name,
- size: size,
+ size: diameter,
status: status,
face: SwarmFace(
picture: picture,
- size: size,
+ size: diameter,
tint: fill,
fallback: Container(
- width: size,
- height: size,
+ width: diameter,
+ height: diameter,
alignment: Alignment.center,
decoration: BoxDecoration(color: fill, shape: BoxShape.circle),
child: Text(
initial,
style: swarmChatText(
- 13.5,
+ 13.5 * diameter / size,
color: AppInk.onFill,
weight: FontWeight.w600,
),
diff --git a/mobile/lib/swarm/swarm_thread.dart b/mobile/lib/swarm/swarm_thread.dart
new file mode 100644
index 000000000..91c5bc57f
--- /dev/null
+++ b/mobile/lib/swarm/swarm_thread.dart
@@ -0,0 +1,498 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import 'model.dart';
+import 'swarm_conversation.dart';
+import 'swarm_reader.dart';
+import 'swarm_request.dart';
+
+/// One thread of a chat on the phone: its root, its replies and the reply
+/// box — the desktop's thread panel (`SuperTabThreadPanel`) and what its
+/// controller does for it (`loadThread`, `sendThreadReply`).
+///
+/// Read through its [chat]'s own messages path, so it reads only what the
+/// chat may: the newest [pagesOnOpen] pages of replies when it opens, earlier
+/// ones on demand ([loadEarlier]), and the root by itself when no page
+/// brought it. Replies that arrive later come with the chat's own reads,
+/// which keep running under it. Nothing of it stays once the person cannot
+/// read the chat: its rows, its draft and a reply not confirmed.
+class SwarmThread extends ChangeNotifier {
+ SwarmThread(this.chat, this.root) : _draft = chat.threadDraft(root) {
+ _listed = chat.conversation != null;
+ chat.addListener(_chatChanged);
+ reader.addListener(_chatChanged);
+ }
+
+ final SwarmConversation chat;
+
+ /// The id of the message the thread hangs from.
+ final String root;
+
+ SwarmReader get reader => chat.reader;
+
+ /// How many pages a thread reads when it opens; past them "Show earlier
+ /// replies" reads on, a page at a time (the desktop's `threadPagesOnOpen`).
+ static const pagesOnOpen = 5;
+
+ /// What its own reads brought, oldest first.
+ List<SuperTabMessage> _rows = const [];
+
+ /// Where its earlier replies continue, while there are more.
+ SuperTabPage? _before;
+
+ bool _read = false, _refused = false, _disposed = false;
+
+ /// The chat was in its Swarm's read: one that then leaves it hides the
+ /// thread at once, as the chat hides its messages.
+ late bool _listed;
+
+ Future<void>? _reading;
+
+ /// "Show earlier replies" is being read.
+ bool readingEarlier = false;
+
+ /// Moves when what was read is dropped: a read asked for before then
+ /// answers nothing.
+ int _epoch = 0;
+
+ /// What the last read or reply could not do, as a sentence.
+ String? error;
+
+ /// Why the thread could not be read when it opened, until a read succeeds:
+ /// what the chat has of it shows, with Try again.
+ String? get readError => _readError;
+ String? _readError;
+
+ /// The root and its replies, oldest first: what its own reads brought and
+ /// what the chat has read of it since (the desktop's `threadMessages`).
+ /// None once the person cannot read it.
+ List<SuperTabMessage> get messages {
+ if (state == SwarmChatState.lost) return const [];
+ final chatRows = chat.messages;
+ if (!identical(_madeFrom?.$1, _rows) ||
+ !identical(_madeFrom?.$2, chatRows)) {
+ final byId = {
+ for (final m in _rows) m.id: m,
+ for (final m in chatRows)
+ if (m.thread == root) m.id: m,
+ };
+ _messages = List.unmodifiable(
+ byId.values.toList()..sort(superTabMessageOrder),
+ );
+ _madeFrom = (_rows, chatRows);
+ }
+ return _messages;
+ }
+
+ List<SuperTabMessage> _messages = const [];
+ (List<SuperTabMessage>, List<SuperTabMessage>)? _madeFrom;
+
+ /// The message the thread hangs from, once read.
+ SuperTabMessage? get rootMessage =>
+ messages.where((m) => m.id == root).firstOrNull;
+
+ /// Its replies, oldest first.
+ List<SuperTabMessage> get replies => [
+ for (final m in messages)
+ if (m.id != root) m,
+ ];
+
+ /// How many replies it has: as its line says, else as many as were read.
+ int get count => chat.thread(root)?.replies ?? replies.length;
+
+ /// Replies before those read wait to be read.
+ bool get hasEarlier => _before != null;
+
+ /// Where the thread stands: a skeleton, its messages, or not open.
+ SwarmChatState get state => _refused || chat.state == SwarmChatState.lost
+ ? SwarmChatState.lost
+ : _read
+ ? SwarmChatState.loaded
+ : SwarmChatState.loading;
+
+ /// The person may reply: as they may post in the chat.
+ bool get canPost => chat.canPost;
+
+ /// Tells the reply box what changed in it — the draft, Also send, a reply
+ /// leaving it — while this notifier itself tells the messages.
+ Listenable get composer => _composer;
+ final _composer = _Changes();
+
+ String _draft;
+ String get draft => _draft;
+ set draft(String value) {
+ _draft = value;
+ chat.setThreadDraft(root, value);
+ _composer.changed();
+ }
+
+ /// The reply also goes to the chat's main stream.
+ bool get alsoSend => _alsoSend;
+ bool _alsoSend = false;
+ set alsoSend(bool value) {
+ if (_alsoSend == value) return;
+ _alsoSend = value;
+ _composer.changed();
+ }
+
+ /// Where Also send puts a reply, as the desktop names the chat.
+ String get alsoSendLabel {
+ final group = chat.conversation;
+ if (group != null && reader.snapshot?.isProjectLead(group.id) == true) {
+ return 'Also send to the project chat';
+ }
+ return group?.number != null
+ ? 'Also send to the workgroup'
+ : 'Also send to the chat';
+ }
+
+ /// A reply is on its way.
+ bool sending = false;
+
+ /// The reply on its way, then — while its answer never came — retried
+ /// under the same operation id, so the backend runs it once.
+ Map<String, dynamic>? _pending;
+
+ /// What the box held when [_pending] left it: a refusal puts it back.
+ ({String draft, bool alsoSend})? _sent;
+
+ /// The reply on its way or not confirmed: drawn under the replies,
+ /// "Sending…" and then [unconfirmed], until it is read back.
+ String? get pending => (_pending?['command'] as Map?)?['text'] as String?;
+
+ /// The backend took the reply on its way, which no read has brought back
+ /// yet: it stays on its way, and is not sent again.
+ bool get confirmed => _confirmed;
+ bool _confirmed = false;
+
+ /// A reply was sent and not confirmed: [send] retries it.
+ bool get unconfirmed => _pending != null && !sending && !_confirmed;
+
+ /// The box may send now: there is text, and no reply is under way.
+ bool get canSend =>
+ canPost && _pending == null && !sending && _draft.trim().isNotEmpty;
+
+ /// The chat or its Swarm changed: replies read since show, and a thread the
+ /// person can no longer read keeps nothing.
+ void _chatChanged() {
+ if (_disposed) return;
+ if (reader.accessRevoked || chat.state == SwarmChatState.lost) {
+ _lose();
+ return;
+ }
+ if (reader.snapshot != null) {
+ final listed = chat.conversation != null;
+ if (_listed && !listed) {
+ // Taken out of the chat: what was read of it goes at once.
+ _forget();
+ } else if (!_listed && listed && !_read && error == null) {
+ unawaited(load());
+ }
+ _listed = listed;
+ }
+ _settle();
+ notifyListeners();
+ }
+
+ /// Drops what was read, and the answer of any read under way.
+ void _forget() {
+ _rows = const [];
+ _before = null;
+ _read = false;
+ _readError = null;
+ readingEarlier = false;
+ _reading = null;
+ _epoch++;
+ }
+
+ /// The person cannot read the chat: nothing of the thread stays.
+ void _lose() {
+ final held =
+ !_refused ||
+ _rows.isNotEmpty ||
+ _draft.isNotEmpty ||
+ _pending != null ||
+ error != null;
+ _refused = true;
+ _forget();
+ _draft = '';
+ _alsoSend = false;
+ _pending = null;
+ _sent = null;
+ _confirmed = false;
+ error = null;
+ if (held) _tell();
+ }
+
+ /// The backend refused [failure] as a chat that is not the person's: the
+ /// thread keeps nothing, as when access is revoked, and the chat learns it
+ /// from a read of its own. False for any other refusal.
+ bool _refusedChat(SuperTabFailure failure) {
+ if (!const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) return false;
+ _lose();
+ unawaited(chat.load());
+ return true;
+ }
+
+ /// A confirmed reply read back shows as its row, no longer on its way.
+ void _settle() {
+ if (!_confirmed) return;
+ final id = _pending?['operationId'];
+ if (!messages.any((m) => m.id == id)) return;
+ _pending = null;
+ _sent = null;
+ _confirmed = false;
+ _composer.changed();
+ }
+
+ /// Reads the thread: from its newest reply back through [pagesOnOpen]
+ /// pages, and its root when no page brought it. Joins a read under way.
+ Future<void> load() =>
+ _reading ??= _load(earlier: false).whenComplete(() => _reading = null);
+
+ /// Reads the page of replies before those read.
+ Future<void> loadEarlier() async {
+ if (!hasEarlier || readingEarlier || _reading != null) return;
+ readingEarlier = true;
+ notifyListeners();
+ await (_reading = _load(earlier: true).whenComplete(() => _reading = null));
+ }
+
+ Future<void> _load({required bool earlier}) async {
+ if (_disposed ||
+ reader.accessRevoked ||
+ chat.state == SwarmChatState.lost) {
+ return;
+ }
+ final epoch = _epoch;
+ final path = chat.messagesPath;
+ final thread = Uri.encodeQueryComponent(root);
+ // Still open, still readable: an answer that comes back after access went
+ // or the chat was left is not kept.
+ bool current() =>
+ !_disposed &&
+ epoch == _epoch &&
+ !reader.accessRevoked &&
+ chat.conversation != null;
+ List<SuperTabMessage> rowsOf(Object? answer) => [
+ for (final row in superTabMap(answer)['messages'] as List)
+ if (SuperTabMessage.fromJson(superTabMap(row)) case final m
+ when m.conversationId == chat.id && m.thread == root)
+ m,
+ ];
+ try {
+ final rows = {
+ if (earlier)
+ for (final m in _rows) m.id: m,
+ };
+ var from = earlier ? _before : null;
+ Object? threads;
+ for (var page = 0; page < (earlier ? 1 : pagesOnOpen); page++) {
+ final answer = superTabMap(
+ await reader.request(
+ 'GET',
+ from == null
+ ? '$path?thread=$thread'
+ : '$path?thread=$thread&before=${from.sequence}'
+ '&beforeId=${Uri.encodeQueryComponent(from.id)}',
+ ),
+ );
+ if (!current()) return;
+ threads ??= answer['threads'];
+ for (final m in rowsOf(answer)) {
+ rows[m.id] = m;
+ }
+ from = SuperTabPage.read(answer['next']);
+ if (from == null) break;
+ }
+ // A long thread's pages read so far start after its root.
+ if (!rows.containsKey(root) && !chat.messages.any((m) => m.id == root)) {
+ final answer = await reader.request(
+ 'GET',
+ '$path?messageId=${Uri.encodeQueryComponent(root)}',
+ );
+ if (!current()) return;
+ for (final m in rowsOf(answer)) {
+ if (m.id == root) rows[m.id] = m;
+ }
+ }
+ _rows = List.unmodifiable(
+ rows.values.toList()..sort(superTabMessageOrder),
+ );
+ _before = from;
+ _read = true;
+ error = _readError = null;
+ chat.keepThreads(threads);
+ _settle();
+ } on SuperTabFailure catch (failure) {
+ if (!current()) return;
+ if (_refusedChat(failure)) return;
+ error = failure.message;
+ if (!earlier) _readError = error;
+ } catch (_) {
+ if (!current()) return;
+ error = earlier
+ ? 'Could not load earlier replies. Try again.'
+ : _readError = 'Could not load the thread. Try again.';
+ } finally {
+ if (earlier && epoch == _epoch) readingEarlier = false;
+ }
+ if (!_disposed) notifyListeners();
+ }
+
+ /// Adds the person's [emoji] to [message], or takes it back (the chat's
+ /// [SwarmConversation.react]), then reads the thread's newest page again:
+ /// a reply the chat has not read shows the backend's counts too. A refused
+ /// reaction has the chat read again, which tells whether it is still open.
+ Future<bool> react(
+ SuperTabMessage message,
+ SuperTabReactionEmoji emoji,
+ ) async {
+ final done = await chat.react(message, emoji);
+ if (_disposed) return done;
+ if (done && _read) {
+ await _reread();
+ } else if (!done && chat.error != null) {
+ unawaited(chat.load());
+ }
+ return done;
+ }
+
+ /// The thread's newest page again, over the rows read of it.
+ Future<void> _reread() async {
+ final epoch = _epoch;
+ try {
+ final answer = superTabMap(
+ await reader.request(
+ 'GET',
+ '${chat.messagesPath}?thread=${Uri.encodeQueryComponent(root)}',
+ ),
+ );
+ if (_disposed ||
+ epoch != _epoch ||
+ reader.accessRevoked ||
+ chat.conversation == null) {
+ return;
+ }
+ final rows = {for (final m in _rows) m.id: m};
+ for (final row in answer['messages'] as List) {
+ final m = SuperTabMessage.fromJson(superTabMap(row));
+ if (m.conversationId == chat.id && m.thread == root) rows[m.id] = m;
+ }
+ _rows = List.unmodifiable(
+ rows.values.toList()..sort(superTabMessageOrder),
+ );
+ chat.keepThreads(answer['threads']);
+ _settle();
+ notifyListeners();
+ } on SuperTabFailure catch (failure) {
+ if (_disposed || epoch != _epoch) return;
+ // Any other refusal keeps the counts read before.
+ _refusedChat(failure);
+ } catch (_) {
+ // The counts read before stay; the next open reads them again.
+ }
+ }
+
+ /// Sends the draft to the thread's root, also to the chat with [alsoSend]
+ /// — or, while a reply is [unconfirmed], sends that one again. The reply
+ /// leaves the box at once and shows as [pending] until it is read back.
+ /// True once the backend took it.
+ Future<bool> send() async {
+ if (sending || _confirmed || _disposed || !canPost) return false;
+ var pending = _pending;
+ if (pending == null) {
+ final text = _draft.trim();
+ if (text.isEmpty || chat.conversation == null) return false;
+ pending = {
+ 'operationId': superTabOperationId(),
+ 'command': {
+ 'type': 'message.send',
+ 'conversationId': chat.id,
+ 'text': text,
+ 'replyTo': root,
+ 'recipientIds': const <String>[],
+ if (_alsoSend) 'alsoSend': true,
+ },
+ };
+ _sent = (draft: _draft, alsoSend: _alsoSend);
+ _draft = '';
+ chat.setThreadDraft(root, '');
+ _alsoSend = false;
+ }
+ _pending = pending;
+ sending = true;
+ error = null;
+ _tell();
+ // An answer that comes back after the thread closed, or after what it
+ // held was dropped, changes nothing: no text back in a box, no read.
+ final epoch = _epoch;
+ bool current() => !_disposed && epoch == _epoch;
+ try {
+ await reader.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
+ body: pending,
+ );
+ if (current()) _confirmed = true;
+ } on SuperTabFailure catch (failure) {
+ if (!current() || _refusedChat(failure)) return false;
+ // A definitive refusal made no change: the text goes back to the box
+ // to correct. A lost answer keeps its receipt, so a retry is the same
+ // reply.
+ final status = failure.statusCode;
+ if (status >= 400 && status < 500 && status != 408 && status != 429) {
+ _pending = null;
+ _restore();
+ }
+ error = failure.message;
+ return false;
+ } catch (_) {
+ if (!current()) return false;
+ error = 'Your reply is not confirmed. Send again to check it.';
+ return false;
+ } finally {
+ sending = false;
+ if (!_disposed) _tell();
+ }
+ if (!current()) return true;
+ unawaited(reader.refresh());
+ // On its way until a read brings it back: this one, or the chat's next.
+ await chat.load();
+ if (!current() || !identical(_pending, pending)) return true;
+ _settle();
+ _tell();
+ return true;
+ }
+
+ /// A refused reply's text back in the box, before anything typed since.
+ void _restore() {
+ final sent = _sent;
+ _sent = null;
+ if (sent == null) return;
+ draft = _draft.trim().isEmpty ? sent.draft : '${sent.draft}\n$_draft';
+ _alsoSend = _alsoSend || sent.alsoSend;
+ }
+
+ /// A reply moved between the box and the messages: both are told.
+ void _tell() {
+ notifyListeners();
+ _composer.changed();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _epoch++;
+ chat.removeListener(_chatChanged);
+ reader.removeListener(_chatChanged);
+ _composer.dispose();
+ super.dispose();
+ }
+}
+
+/// A notifier told from outside it: the thread's [SwarmThread.composer].
+class _Changes extends ChangeNotifier {
+ void changed() => notifyListeners();
+}
diff --git a/mobile/lib/swarm/swarm_thread_line.dart b/mobile/lib/swarm/swarm_thread_line.dart
new file mode 100644
index 000000000..47e154379
--- /dev/null
+++ b/mobile/lib/swarm/swarm_thread_line.dart
@@ -0,0 +1,168 @@
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/phone/tty.dart';
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import 'identity.dart';
+import 'model.dart';
+import 'swarm_face.dart';
+import 'swarm_message_row.dart';
+
+/// How long ago: "just now", "4s ago", "3 min ago", "2 h ago", "5 d ago" —
+/// the desktop's `superTabAgo`, word for word.
+String swarmAgo(Duration age) {
+ final seconds = age.inSeconds;
+ if (seconds < 1) return 'just now';
+ if (seconds < 60) return '${seconds}s ago';
+ if (age.inMinutes < 60) return '${age.inMinutes} min ago';
+ if (age.inHours < 24) return '${age.inHours} h ago';
+ return '${age.inDays} d ago';
+}
+
+/// One who replied in a thread, as the chat draws its authors.
+typedef SwarmThreadFace = ({
+ String name,
+ String id,
+ bool agent,
+ SwarmLook look,
+});
+
+/// The newest reply authors of [thread] as [snapshot] names and dresses them:
+/// an agent by the Swarm's name for it, a person by their address's first
+/// part, as the chat names a message's author.
+List<SwarmThreadFace> swarmThreadFaces(
+ SuperTabSnapshot? snapshot,
+ SuperTabThread thread,
+) => [
+ for (final author in thread.authors)
+ if (author['id'] case final String id)
+ author['kind'] == 'agent'
+ ? (
+ name:
+ snapshot?.agentName(
+ id,
+ fallback:
+ (author['displayName'] ?? author['name'] ?? 'Agent')
+ as String,
+ ) ??
+ (author['displayName'] ?? author['name'] ?? 'Agent')
+ as String,
+ id: id,
+ agent: true,
+ look: snapshot?.agentLook(id) ?? (picture: null, status: null),
+ )
+ : (
+ name: superTabPersonName(author['name'] as String? ?? ''),
+ id: id,
+ agent: false,
+ look: snapshot?.personLook(id) ?? (picture: null, status: null),
+ ),
+];
+
+/// The line under a thread's root: who replied, how many replies, and when
+/// the last came (the desktop's `SuperTabThreadLine`). A tap opens the
+/// thread.
+class SwarmThreadLine extends StatelessWidget {
+ const SwarmThreadLine({
+ super.key,
+ required this.thread,
+ required this.faces,
+ required this.onOpen,
+ });
+
+ final SuperTabThread thread;
+ final List<SwarmThreadFace> faces;
+ final VoidCallback onOpen;
+
+ /// The faces' width, a third of the chat's avatar.
+ static const double face = 20;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final count = thread.replies == 1 ? '1 reply' : '${thread.replies} replies';
+ final last = thread.lastAt;
+ final ago = last == null
+ ? null
+ : 'Last reply ${swarmAgo(DateTime.now().difference(last))}';
+ return Semantics(
+ button: true,
+ label: ago == null ? count : '$count, $ago',
+ hint: 'Open thread',
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onOpen,
+ child: ConstrainedBox(
+ // A thumb's height, though the line is shorter.
+ constraints: const BoxConstraints(minHeight: 44),
+ child: Row(
+ children: [
+ for (final who in faces) ...[
+ SwarmChatAvatar(
+ name: who.name,
+ id: who.id,
+ agent: who.agent,
+ picture: who.look.picture,
+ diameter: face,
+ ),
+ const SizedBox(width: AppSpace.xs),
+ ],
+ Text(
+ count,
+ key: ValueKey('swarm-thread-count-${thread.id}'),
+ style: swarmChatText(
+ 14,
+ color: AppPalette.accentOnSurface,
+ weight: FontWeight.w600,
+ ),
+ ),
+ if (ago != null) ...[
+ const SizedBox(width: AppSpace.s),
+ Flexible(
+ child: Text(
+ ago,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: swarmChatText(13, color: AppPalette.textFaint),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// Over a reply also sent to the chat: where it was written, a tap away
+/// (the desktop's "Replied in thread").
+class SwarmRepliedInThread extends StatelessWidget {
+ const SwarmRepliedInThread({super.key, required this.onOpen});
+
+ final VoidCallback onOpen;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ return Semantics(
+ button: true,
+ label: 'Replied in thread, open thread',
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onOpen,
+ child: Padding(
+ padding: const EdgeInsets.only(top: SwarmMessageFrame.bodyGap),
+ child: Text(
+ 'Replied in thread',
+ style: tty.style(color: AppPalette.textFaint, size: 12.5),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_thread_page.dart b/mobile/lib/swarm/swarm_thread_page.dart
new file mode 100644
index 000000000..6787a195a
--- /dev/null
+++ b/mobile/lib/swarm/swarm_thread_page.dart
@@ -0,0 +1,517 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/phone/tty.dart';
+import 'package:harness_mobile/phone/tty_controls.dart';
+import 'package:harness_mobile/shared/theme/app_ink.dart';
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import 'model.dart';
+import 'swarm_conversation.dart';
+import 'swarm_conversation_page.dart';
+import 'swarm_message_row.dart';
+import 'swarm_session.dart';
+import 'swarm_thread.dart';
+
+/// Draws one of a thread's messages as its chat draws them; a tap on it
+/// opens or closes its actions ([acting]).
+typedef SwarmThreadRow = Widget Function(
+ SwarmThread thread,
+ SuperTabMessage message, {
+ required bool grouped,
+ required bool acting,
+ required VoidCallback onTap,
+});
+
+/// Draws the person's reply on its way: "Sending…", then "Not confirmed"
+/// with Send again.
+typedef SwarmThreadPending = Widget Function(SwarmThread thread, String text);
+
+/// One thread of a chat, full screen as Slack Mobile opens one: its root at
+/// the top, "N replies", its replies, and a reply box at the foot with Also
+/// send (the desktop's thread panel, Tony's mockup of 10-29).
+///
+/// Its rows are drawn by the chat that opened it ([row], [pending]), so a
+/// message looks the same in both. While it is up its Swarm is watched, so
+/// replies arrive as they do in the chat.
+class SwarmThreadPage extends StatefulWidget {
+ const SwarmThreadPage({
+ super.key,
+ required this.swarmId,
+ required this.chat,
+ required this.root,
+ required this.title,
+ required this.row,
+ required this.pending,
+ });
+
+ final String swarmId;
+ final SwarmConversation chat;
+
+ /// The id of the message the thread hangs from.
+ final String root;
+
+ /// The chat's name, under "Thread".
+ final String? title;
+ final SwarmThreadRow row;
+ final SwarmThreadPending pending;
+
+ @override
+ State<SwarmThreadPage> createState() => _SwarmThreadPageState();
+}
+
+class _SwarmThreadPageState extends State<SwarmThreadPage> {
+ late final SwarmThread _thread = SwarmThread(widget.chat, widget.root);
+ late final _text = TextEditingController(text: _thread.draft);
+ final _focus = FocusNode(debugLabel: 'Swarm thread reply');
+ final _scroll = ScrollController();
+
+ /// The message whose actions are open (Copy), by a tap on it.
+ String? _acting;
+
+ SwarmSession? _session;
+ bool _watching = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _text.addListener(_typed);
+ _thread.composer.addListener(_drafted);
+ unawaited(_thread.load());
+ }
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final session = SwarmScope.of(context);
+ // Off while a screen pushed over this one covers it.
+ final watch = session != null && TickerMode.valuesOf(context).enabled;
+ if (session != _session || watch != _watching) {
+ if (_watching) _session?.unwatch(widget.swarmId);
+ _session = session;
+ _watching = watch;
+ if (watch) session.watch(widget.swarmId);
+ }
+ }
+
+ @override
+ void dispose() {
+ if (_watching) _session?.unwatch(widget.swarmId);
+ _thread.composer.removeListener(_drafted);
+ _thread.dispose();
+ _text.dispose();
+ _focus.dispose();
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ /// What the person typed, into the draft.
+ void _typed() {
+ if (_thread.draft != _text.text) _thread.draft = _text.text;
+ }
+
+ /// The draft changed under the field — a reply sent, or refused and put
+ /// back.
+ void _drafted() {
+ final draft = _thread.draft;
+ if (draft == _text.text) return;
+ _text.value = TextEditingValue(
+ text: draft,
+ selection: TextSelection.collapsed(offset: draft.length),
+ );
+ }
+
+ /// Sends the reply, at the foot of the thread where it shows. Once the
+ /// backend took it the keyboard goes down, unless the next is being typed.
+ Future<void> _send() async {
+ if (_scroll.hasClients) {
+ unawaited(
+ _scroll.animateTo(
+ _scroll.position.maxScrollExtent,
+ duration: const Duration(milliseconds: 250),
+ curve: Curves.easeOut,
+ ),
+ );
+ }
+ final sent = await _thread.send();
+ if (sent && mounted && _thread.draft.isEmpty) _focus.unfocus();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _header(context, tty),
+ Expanded(
+ child: ListenableBuilder(
+ listenable: _thread,
+ builder: (context, _) => _body(tty),
+ ),
+ ),
+ ListenableBuilder(
+ listenable: Listenable.merge([_thread, _thread.composer]),
+ builder: (context, _) => _foot(tty),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _header(BuildContext context, Tty tty) => Padding(
+ key: const ValueKey('swarm-thread-header'),
+ padding: const EdgeInsets.fromLTRB(0, AppSpace.xs, AppSpace.s, AppSpace.xs),
+ child: Row(
+ children: [
+ TtyBackButton(onPressed: () => Navigator.of(context).maybePop()),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Semantics(
+ header: true,
+ child: Text(
+ 'Thread',
+ key: const ValueKey('swarm-title'),
+ style: tty.style(
+ size: TtySize.title,
+ weight: FontWeight.w600,
+ ),
+ ),
+ ),
+ // Not named once the chat is no longer open to the person.
+ ListenableBuilder(
+ listenable: _thread,
+ builder: (context, _) => switch (widget.title) {
+ final title? when _thread.state != SwarmChatState.lost =>
+ Text(
+ title,
+ key: const ValueKey('swarm-thread-chat-title'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: swarmChatText(13, color: AppPalette.textSecondary),
+ ),
+ _ => const SizedBox.shrink(),
+ },
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+
+ /// Until the thread is read, skeleton bubbles; what it could not read, with
+ /// Try again; "not open" once the backend refused the chat; then the root,
+ /// "N replies", the replies and a reply on its way.
+ Widget _body(Tty tty) {
+ final t = _thread;
+ if (t.state == SwarmChatState.lost) {
+ return _said('This chat is not open to you.');
+ }
+ final messages = t.messages;
+ final root = t.rootMessage;
+ if (t.state != SwarmChatState.loaded && root == null) {
+ if (t.readError case final error?) {
+ return Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ _said(error, key: const ValueKey('swarm-thread-error')),
+ _Link(
+ key: const ValueKey('swarm-thread-retry'),
+ label: 'Try again',
+ onTap: () => unawaited(t.load()),
+ ),
+ ],
+ );
+ }
+ return const SwarmChatSkeleton();
+ }
+ if (messages.isEmpty) {
+ return _said('The original message is no longer in this chat.');
+ }
+ final replies = t.replies;
+ final count = t.count;
+ final pending = t.pending;
+ Widget row(SuperTabMessage m, {required bool grouped}) => widget.row(
+ t,
+ m,
+ grouped: grouped,
+ acting: _acting == m.id,
+ onTap: () => setState(() => _acting = _acting == m.id ? null : m.id),
+ );
+ return ListView(
+ key: const ValueKey('swarm-thread-messages'),
+ controller: _scroll,
+ // The chat's own inset, so a message sits where it does there.
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.m,
+ vertical: AppSpace.s,
+ ),
+ children: [
+ if (root != null) row(root, grouped: false),
+ if (count > 0)
+ Padding(
+ key: const ValueKey('swarm-thread-divider'),
+ // In line with the avatars.
+ padding: const EdgeInsets.all(AppSpace.s),
+ child: Row(
+ children: [
+ Text(
+ count == 1 ? '1 reply' : '$count replies',
+ style: swarmChatText(13, color: AppPalette.textSecondary),
+ ),
+ const SizedBox(width: AppSpace.s),
+ Expanded(child: Divider(height: 1, color: swarmChatHair(tty))),
+ ],
+ ),
+ ),
+ // What the chat has of it shows, and the rest is read again on a tap.
+ if (t.readError case final error?) ...[
+ _said(error, key: const ValueKey('swarm-thread-error')),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: _Link(
+ key: const ValueKey('swarm-thread-retry'),
+ label: 'Try again',
+ onTap: () => unawaited(t.load()),
+ ),
+ ),
+ ],
+ if (t.hasEarlier)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: t.readingEarlier
+ ? Padding(
+ key: const ValueKey('swarm-thread-earlier-loading'),
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.s,
+ vertical: AppSpace.m,
+ ),
+ child: Text(
+ 'Loading earlier replies…',
+ style: swarmChatText(15, color: AppPalette.textSecondary),
+ ),
+ )
+ : _Link(
+ key: const ValueKey('swarm-thread-earlier'),
+ label: 'Show earlier replies',
+ onTap: () => unawaited(t.loadEarlier()),
+ ),
+ ),
+ for (final (index, reply) in replies.indexed)
+ row(
+ reply,
+ grouped:
+ index > 0 &&
+ replies[index - 1].authorId == reply.authorId &&
+ replies[index - 1].fromAgent == reply.fromAgent,
+ ),
+ if (pending != null) widget.pending(t, pending),
+ ],
+ );
+ }
+
+ /// What could not be done, then the reply box — or why there is none.
+ Widget _foot(Tty tty) {
+ final t = _thread;
+ if (t.state == SwarmChatState.lost) return const SizedBox.shrink();
+ final group = t.chat.conversation;
+ final error = t.error;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ // The first read's failure is said in the body, with Try again.
+ if (error != null &&
+ error != t.readError &&
+ (t.rootMessage != null || t.pending != null))
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.screenInset,
+ AppSpace.s,
+ AppSpace.screenInset,
+ 0,
+ ),
+ child: Text(
+ error,
+ key: const ValueKey('swarm-thread-post-error'),
+ style: swarmChatText(13.5, color: tty.red),
+ ),
+ ),
+ if (t.canPost)
+ _box(t, tty)
+ else if (group != null)
+ Padding(
+ padding: const EdgeInsets.all(AppSpace.l),
+ child: Text(
+ group.archived
+ ? 'This chat is archived.'
+ : 'You can read this chat, not post in it.',
+ key: const ValueKey('swarm-thread-read-only'),
+ style: swarmChatText(13.5, color: AppPalette.textSecondary),
+ ),
+ ),
+ ],
+ );
+ }
+
+ /// The reply box: a field that grows with what is typed, then Also send
+ /// and a round Send (the desktop's thread composer).
+ Widget _box(SwarmThread t, Tty tty) {
+ final canSend = t.canSend;
+ // A reply not confirmed is sent again from where it shows.
+ final writable = !t.sending && t.pending == null;
+ return Container(
+ key: const ValueKey('swarm-thread-box'),
+ decoration: BoxDecoration(
+ color: Color.alphaBlend(tty.text.withValues(alpha: 0.02), tty.ground),
+ border: Border(top: BorderSide(color: swarmChatHair(tty))),
+ ),
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.m,
+ AppSpace.s,
+ AppSpace.m,
+ AppSpace.xs,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SwarmMessageField(
+ controller: _text,
+ focus: _focus,
+ hint: 'Reply',
+ fieldKey: const ValueKey('swarm-thread-field'),
+ ),
+ Row(
+ children: [
+ Expanded(
+ child: _AlsoSend(
+ label: t.alsoSendLabel,
+ value: t.alsoSend,
+ onChanged: writable ? (on) => t.alsoSend = on : null,
+ ),
+ ),
+ SwarmRoundButton(
+ key: const ValueKey('swarm-thread-send'),
+ label: 'Send reply',
+ fill: canSend ? AppPalette.accent : ttyRaised(tty),
+ onTap: canSend ? () => unawaited(_send()) : null,
+ child: Icon(
+ LucideIcons.arrowUp,
+ size: 20,
+ color: canSend ? AppInk.onFill : AppPalette.textFaint,
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _said(String text, {Key? key}) => Padding(
+ key: key,
+ padding: const EdgeInsets.all(AppSpace.xl),
+ child: Center(
+ child: Text(
+ text,
+ textAlign: TextAlign.center,
+ style: swarmChatText(15, color: AppPalette.textSecondary),
+ ),
+ ),
+ );
+}
+
+/// Also send, ticked or not: the reply goes to the chat's main stream too.
+/// The whole line is a thumb's target.
+class _AlsoSend extends StatelessWidget {
+ const _AlsoSend({
+ required this.label,
+ required this.value,
+ required this.onChanged,
+ });
+
+ final String label;
+ final bool value;
+
+ /// Null while a reply is on its way.
+ final ValueChanged<bool>? onChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final enabled = onChanged != null;
+ return Semantics(
+ key: const ValueKey('swarm-thread-also-send'),
+ checked: value,
+ enabled: enabled,
+ label: label,
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: enabled ? () => onChanged!(!value) : null,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: 44),
+ child: Row(
+ children: [
+ // The theme's checkbox, as the desktop's thread composer has.
+ Checkbox(
+ value: value,
+ visualDensity: VisualDensity.compact,
+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ onChanged: enabled ? (on) => onChanged!(on ?? false) : null,
+ ),
+ const SizedBox(width: AppSpace.s),
+ Flexible(
+ child: Text(
+ label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: swarmChatText(
+ 14,
+ color: enabled
+ ? AppPalette.textPrimary
+ : AppPalette.textFaint,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// A link in the accent: Show earlier replies, Try again.
+class _Link extends StatelessWidget {
+ const _Link({super.key, required this.label, required this.onTap});
+
+ final String label;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) => TtyTap(
+ semanticsLabel: label,
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.s,
+ vertical: AppSpace.m,
+ ),
+ child: Text(
+ label,
+ style: swarmChatText(15, color: AppPalette.accentOnSurface),
+ ),
+ ),
+ );
+}
diff --git a/mobile/test/render/swarm_thread_render_test.dart b/mobile/test/render/swarm_thread_render_test.dart
new file mode 100644
index 000000000..d8ef01e10
--- /dev/null
+++ b/mobile/test/render/swarm_thread_render_test.dart
@@ -0,0 +1,289 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+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' as grid;
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../swarm/swarm_fixture.dart';
+import '../voice_fakes.dart';
+
+/// Renders a phone Swarm chat's threads as Tony's mockup of 10-29 draws them —
+/// the chat with a root's "N replies" line, a reply also sent and Reply in
+/// thread, then the thread itself — in light and dark, at iPhone 14 size in
+/// the system fonts, to PNGs a reviewer can look at without a phone.
+/// Scripted data only.
+///
+/// Skipped unless PHONE_RENDER_DIR names a directory to write into:
+///
+/// PHONE_RENDER_DIR=/tmp/renders flutter test test/render/swarm_thread_render_test.dart
+///
+/// macOS only: it loads SF Pro and SF Mono from /System/Library/Fonts.
+final _outDir = Platform.environment['PHONE_RENDER_DIR'];
+
+Future<void> _loadFonts() async {
+ Future<void> load(String family, String file) async {
+ final bytes = await File('/System/Library/Fonts/$file').readAsBytes();
+ await (FontLoader(
+ family,
+ )..addFont(Future.value(ByteData.view(bytes.buffer)))).load();
+ }
+
+ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {
+ await load(family, 'SFNS.ttf');
+ }
+ for (final family in ['.AppleSystemUIFontMonospaced', 'SF Mono']) {
+ await load(family, 'SFNSMono.ttf');
+ }
+ // The icons, from the package in the pub cache.
+ final lucide =
+ '${Platform.environment['HOME']}/.pub-cache/hosted/pub.dev/lucide_icons_flutter-3.1.19/assets';
+ Future<void> icons(String family, String file) async {
+ final bytes = await File('$lucide/$file').readAsBytes();
+ await (FontLoader(
+ family,
+ )..addFont(Future.value(ByteData.view(bytes.buffer)))).load();
+ }
+
+ await icons('packages/lucide_icons_flutter/Lucide', 'lucide.ttf');
+ for (final weight in [100, 200, 300, 400, 500, 600]) {
+ await icons(
+ 'packages/lucide_icons_flutter/Lucide$weight',
+ 'build_font/LucideVariable-w$weight.ttf',
+ );
+ }
+}
+
+void main() {
+ final skip = _outDir == null;
+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';
+
+ FakeSwarm backend() {
+ final now = DateTime.now().toUtc();
+ Map<String, dynamic> message(
+ String id,
+ int sequence,
+ String text, {
+ required String author,
+ required int minutesAgo,
+ String? thread,
+ bool alsoInChat = false,
+ }) => {
+ 'id': id,
+ 'conversationId': 'g1',
+ 'text': text,
+ 'sequence': sequence,
+ 'thread': thread ?? id,
+ 'replyTo': ?thread,
+ if (alsoInChat) 'alsoInChat': true,
+ 'author': author == me
+ ? {'kind': 'person', 'id': me, 'name': 'tony'}
+ : {
+ 'kind': 'agent',
+ 'id': author,
+ 'name': author == 'agent-lead' ? 'River' : 'Nova',
+ },
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': now
+ .subtract(Duration(minutes: minutesAgo))
+ .toIso8601String(),
+ };
+
+ final page = [
+ message(
+ 'm1',
+ 1,
+ 'Can you check the drawer mockup?',
+ author: 'agent-lead',
+ minutesAgo: 20,
+ ),
+ message(
+ 'm2',
+ 2,
+ 'Looks good. One question on the bold names.',
+ author: 'agent-builder',
+ minutesAgo: 18,
+ thread: 'm1',
+ ),
+ message(
+ 'm3',
+ 3,
+ 'Ship it as drawn.',
+ author: me,
+ minutesAgo: 17,
+ thread: 'm1',
+ ),
+ message(
+ 'm4',
+ 4,
+ 'Pushed the fix.',
+ author: 'agent-builder',
+ minutesAgo: 5,
+ thread: 'm1',
+ alsoInChat: true,
+ ),
+ message(
+ 'm5',
+ 5,
+ 'Next: the leaderboard.',
+ author: 'agent-builder',
+ minutesAgo: 4,
+ ),
+ ];
+ final line = {
+ 'id': 'm1',
+ 'replies': 3,
+ 'lastSequence': 4,
+ 'lastAt': now.subtract(const Duration(minutes: 5)).toIso8601String(),
+ 'authors': [
+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},
+ {'kind': 'person', 'id': me, 'name': '[email protected]'},
+ ],
+ 'people': [me],
+ };
+
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ groupData(
+ 'g1',
+ title: 'Mobile: bold names and @N',
+ agentIds: ['agent-lead', 'agent-builder'],
+ status: 'working',
+ lastMessageSequence: 5,
+ ),
+ ],
+ ),
+ 'members': [part(me, 1, person(me))],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes[messages] = (_) => {
+ 'messages': page.reversed.toList(),
+ 'next': null,
+ 'threads': [line],
+ };
+ fake.routes['$messages?thread=m1'] = (_) => {
+ 'messages': [
+ for (final m in page.reversed)
+ if (m['thread'] == 'm1') m,
+ ],
+ 'next': null,
+ 'threads': [line],
+ };
+ return fake;
+ }
+
+ Future<void> shoot(WidgetTester tester, GlobalKey key, String name) async {
+ await tester.runAsync(() async {
+ final boundary =
+ key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ final file = File('$_outDir/$name.png');
+ await file.parent.create(recursive: true);
+ await file.writeAsBytes(png!.buffer.asUint8List());
+ });
+ }
+
+ for (final brightness in Brightness.values) {
+ final look = brightness.name;
+
+ Future<GlobalKey> chat(WidgetTester tester) async {
+ await tester.runAsync(_loadFonts);
+ // A palette carries its brightness: a light one is how the app goes light.
+ final palette = HarnessPalette.values.firstWhere(
+ (p) => p.brightness == brightness,
+ );
+ final previous = (
+ grid.AppTheme.brightness.value,
+ grid.AppTheme.palette.value,
+ );
+ grid.AppTheme.palette.value = palette;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() {
+ grid.AppTheme.brightness.value = previous.$1;
+ grid.AppTheme.palette.value = previous.$2;
+ });
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ tester.view.viewPadding = const FakeViewPadding(
+ top: 47 * 3,
+ bottom: 34 * 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: backend().request,
+ notices: SilentSystemNotices(),
+ features: features,
+ )..foreground = false;
+ addTearDown(host.dispose);
+ final key = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: key,
+ child: grid.BrightnessScope(
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(
+ swarmId: tab,
+ conversationId: 'g1',
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return key;
+ }
+
+ testWidgets(
+ 'the chat: a replies line, a reply also sent, Reply in '
+ 'thread ($look)',
+ skip: skip,
+ (tester) async {
+ final key = await chat(tester);
+ await tester.tap(find.text('Next: the leaderboard.'));
+ await tester.pumpAndSettle();
+ await shoot(tester, key, 'swarm-thread-chat-$look');
+ },
+ );
+
+ testWidgets('the thread ($look)', skip: skip, (tester) async {
+ final key = await chat(tester);
+ await tester.tap(find.byKey(const ValueKey('swarm-thread-line-m1')));
+ await tester.pumpAndSettle();
+ await shoot(tester, key, 'swarm-thread-open-$look');
+ });
+ }
+}
diff --git a/mobile/test/swarm/desktop_parity_test.dart b/mobile/test/swarm/desktop_parity_test.dart
index 12ea38799..d5e72a044 100644
--- a/mobile/test/swarm/desktop_parity_test.dart
+++ b/mobile/test/swarm/desktop_parity_test.dart
@@ -25,12 +25,12 @@ const _copies = {
/// a computer and dropped on the phone. Back in [_copies] once the desktop's
/// model carries them.
///
-/// Chat threads (#2132), PM ruling 10-29: the phone has no thread view yet,
-/// so a reply only in its thread stays in the chat, inline, and nothing is
-/// lost; but unread and bold follow the desktop's main-stream rule
-/// (`lastMainSequence`, [SuperTabConversation.mainSequence]), so a reply only
-/// in its thread makes a chat unread on neither. The phone reads a message's
-/// thread and the thread summaries as the desktop does, and shows none yet.
+/// Chat threads (#2132): the phone reads a message's thread and the thread
+/// summaries as the desktop does, and draws them as it does (Tony, option B,
+/// 10-29): the line under a root, a reply only in its thread out of the chat,
+/// and the thread on a screen of its own. Unread and bold follow the
+/// desktop's main-stream rule (`lastMainSequence`,
+/// [SuperTabConversation.mainSequence]) on both.
const _model = ('lib/swarm/model.dart', 'lib/super_tabs/model.dart');
void main() {
diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dart
index 3ea7e01dc..9956de49e 100644
--- a/mobile/test/swarm/swarm_chat_test.dart
+++ b/mobile/test/swarm/swarm_chat_test.dart
@@ -34,6 +34,8 @@ void main() {
String text = 'hello',
String author = 'agent-builder',
String? replyTo,
+ String? thread,
+ bool alsoInChat = false,
int minute = 0,
DateTime? at,
List<Map<String, dynamic>> attachments = const [],
@@ -44,6 +46,8 @@ void main() {
'text': text,
'sequence': sequence,
'replyTo': ?replyTo,
+ 'thread': ?thread,
+ if (alsoInChat) 'alsoInChat': true,
'author': author == me
? {'kind': 'person', 'id': me, 'name': 'tony'}
: {
@@ -82,11 +86,13 @@ void main() {
};
/// One Swarm whose chat g1 has River (its project's Product Manager) and
- /// Nova (an engineer), reading [page] as its latest messages, with
- /// [decisions] open in it. With [audience], g1 is that person's own chat.
+ /// Nova (an engineer), reading [page] as its latest messages with the lines
+ /// of [threads], with [decisions] open in it. With [audience], g1 is that
+ /// person's own chat.
FakeSwarm backend(
List<Map<String, dynamic>> page, {
Object? next,
+ List<Map<String, dynamic>> threads = const [],
List<Map<String, dynamic>> decisions = const [],
List<String>? audience,
List<Map<String, dynamic>>? members,
@@ -134,6 +140,7 @@ void main() {
fake.routes[messages] = (_) => {
'messages': page.reversed.toList(),
'next': next,
+ 'threads': threads,
};
fake.routes[commands] = (_) => {'result': <String, dynamic>{}};
return fake;
@@ -1307,6 +1314,381 @@ void main() {
});
});
+ group('threads', () {
+ const parts = '/api/super-tabs/$tab/parts';
+ const root = 'Can you check the drawer mockup?';
+ const onlyThere = 'Looks good. One question.';
+ const alsoHere = 'Pushed the fix.';
+ const next = 'Next: the leaderboard.';
+
+ /// The line under [id]: [replies] replies, the last [ago], Nova's.
+ Map<String, dynamic> line(
+ String id,
+ int replies,
+ int last, {
+ Duration ago = const Duration(minutes: 5),
+ }) => {
+ 'id': id,
+ 'replies': replies,
+ 'lastSequence': last,
+ 'lastAt': DateTime.now().subtract(ago).toUtc().toIso8601String(),
+ 'authors': [
+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},
+ ],
+ 'people': <String>[],
+ };
+
+ /// River's question with two replies in its thread, Nova's only there
+ /// and Nova's also sent to the chat; then a message of Nova's own. A
+ /// reply sent comes back in the page under its operation id, as the
+ /// backend writes it, and on the line; in both when also sent.
+ FakeSwarm threaded({List<Map<String, dynamic>>? members}) {
+ final page = [
+ message('m1', 1, author: 'agent-lead', text: root, thread: 'm1'),
+ message(
+ 'm2',
+ 2,
+ text: onlyThere,
+ thread: 'm1',
+ replyTo: 'm1',
+ minute: 2,
+ ),
+ message(
+ 'm3',
+ 3,
+ text: alsoHere,
+ thread: 'm1',
+ replyTo: 'm1',
+ alsoInChat: true,
+ minute: 8,
+ ),
+ message('m4', 4, text: next, thread: 'm4', minute: 9),
+ ];
+ final lines = [line('m1', 2, 3)];
+ final fake = backend(page, threads: lines, members: members);
+ for (final id in ['m1', 'm4']) {
+ fake.routes['$messages?thread=$id'] = (_) => {
+ 'messages': [
+ for (final m in page.reversed)
+ if (m['thread'] == id) m,
+ ],
+ 'next': null,
+ 'threads': [
+ for (final l in lines)
+ if (l['id'] == id) l,
+ ],
+ };
+ }
+ fake.routes[commands] = (body) {
+ final command = body!['command'] as Map<String, dynamic>;
+ page.add(
+ message(
+ body['operationId'] as String,
+ 5,
+ author: me,
+ text: command['text'] as String,
+ thread: 'm1',
+ replyTo: 'm1',
+ alsoInChat: command['alsoSend'] == true,
+ minute: 10,
+ ),
+ );
+ lines[0] = line('m1', 3, 5, ago: Duration.zero);
+ return {'result': <String, dynamic>{}};
+ };
+ return fake;
+ }
+
+ Finder inThread(String text) => find.descendant(
+ of: key('swarm-thread-messages'),
+ matching: find.text(text),
+ );
+
+ Future<void> back(WidgetTester tester) async {
+ await tester.tap(find.bySemanticsLabel('Back'));
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('a root says how many replies and when the last came; a reply '
+ 'only in its thread is not in the chat, and one also sent says where '
+ 'it was written', (tester) async {
+ await pump(tester, threaded());
+
+ final under = key('swarm-thread-line-m1');
+ expect(
+ find.descendant(of: under, matching: find.text('2 replies')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: under, matching: find.text('Last reply 5 min ago')),
+ findsOneWidget,
+ );
+ expect(find.text(onlyThere), findsNothing);
+ expect(find.text(alsoHere), findsOneWidget);
+ expect(key('swarm-replied-in-thread-m3'), findsOneWidget);
+ expect(key('swarm-quote-m3'), findsNothing, reason: 'no quote of m1');
+ expect(key('swarm-thread-line-m4'), findsNothing, reason: 'no replies');
+ });
+
+ testWidgets('a tap on the line opens the thread: the root, how many '
+ 'replies, each reply in order, and a box to reply in', (tester) async {
+ final fake = threaded();
+ await pump(tester, fake);
+
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+
+ expect(fake.paths, contains('$messages?thread=m1'));
+ expect(find.text('Thread'), findsOneWidget);
+ expect(
+ tester.widget<Text>(key('swarm-thread-chat-title')).data,
+ 'Fix login',
+ );
+ expect(
+ find.descendant(
+ of: key('swarm-thread-divider'),
+ matching: find.text('2 replies'),
+ ),
+ findsOneWidget,
+ );
+ final tops = [
+ for (final text in [root]) tester.getTopLeft(inThread(text)).dy,
+ tester.getTopLeft(key('swarm-thread-divider')).dy,
+ for (final text in [onlyThere, alsoHere])
+ tester.getTopLeft(inThread(text)).dy,
+ ];
+ expect(tops, orderedEquals([...tops]..sort()));
+ expect(key('swarm-replied-in-thread-m3'), findsNothing);
+ expect(key('swarm-thread-box'), findsOneWidget);
+ expect(find.text('Reply'), findsOneWidget, reason: 'the field hint');
+ expect(find.text('Also send to the chat'), findsOneWidget);
+ });
+
+ testWidgets('Reply in thread: a message\'s Reply opens its thread, with no '
+ 'reply bar in the chat', (tester) async {
+ final fake = threaded();
+ await pump(tester, fake);
+
+ await tester.tap(find.text(next));
+ await tester.pumpAndSettle();
+ expect(
+ find.descendant(
+ of: key('swarm-reply-m4'),
+ matching: find.text('Reply in thread'),
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(key('swarm-reply-m4'));
+ await tester.pumpAndSettle();
+
+ expect(fake.paths, contains('$messages?thread=m4'));
+ expect(inThread(next), findsOneWidget);
+ expect(key('swarm-thread-divider'), findsNothing, reason: 'no replies');
+
+ await back(tester);
+ expect(key('swarm-reply-bar'), findsNothing);
+ });
+
+ testWidgets('Replied in thread opens the thread it was written in', (
+ tester,
+ ) async {
+ await pump(tester, threaded());
+
+ await tester.tap(key('swarm-replied-in-thread-m3'));
+ await tester.pumpAndSettle();
+
+ expect(inThread(root), findsOneWidget);
+ expect(inThread(onlyThere), findsOneWidget);
+ expect(inThread(alsoHere), findsOneWidget);
+ });
+
+ testWidgets('a reply goes to the thread alone: it shows there, and the '
+ 'chat\'s line counts it', (tester) async {
+ final fake = threaded();
+ await pump(tester, fake);
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+
+ await tester.enterText(key('swarm-thread-field'), 'Ship it as drawn.');
+ await tester.pump();
+ await tester.tap(key('swarm-thread-send'));
+ await tester.pumpAndSettle();
+
+ expect(fake.commands.single, {
+ 'type': 'message.send',
+ 'conversationId': 'g1',
+ 'text': 'Ship it as drawn.',
+ 'replyTo': 'm1',
+ 'recipientIds': <String>[],
+ });
+ expect(inThread('Ship it as drawn.'), findsOneWidget);
+ expect(key('swarm-thread-pending'), findsNothing);
+
+ await back(tester);
+ expect(find.text('Ship it as drawn.'), findsNothing);
+ expect(
+ find.descendant(
+ of: key('swarm-thread-line-m1'),
+ matching: find.text('3 replies'),
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('Also send to the chat posts the reply in both', (
+ tester,
+ ) async {
+ final fake = threaded();
+ await pump(tester, fake);
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+
+ await tester.enterText(key('swarm-thread-field'), 'Ship it as drawn.');
+ await tester.tap(key('swarm-thread-also-send'));
+ await tester.pump();
+ await tester.tap(key('swarm-thread-send'));
+ await tester.pumpAndSettle();
+
+ expect(fake.commands.single['alsoSend'], isTrue);
+ expect(fake.commands.single['replyTo'], 'm1');
+ expect(inThread('Ship it as drawn.'), findsOneWidget);
+ // Ticked for this reply alone.
+ expect(
+ tester
+ .widget<Semantics>(key('swarm-thread-also-send'))
+ .properties
+ .checked,
+ isFalse,
+ );
+
+ await back(tester);
+ final sent = fake.calls
+ .lastWhere((call) => call.path == commands)
+ .body!['operationId'];
+ expect(find.text('Ship it as drawn.'), findsOneWidget);
+ expect(key('swarm-replied-in-thread-$sent'), findsOneWidget);
+ });
+
+ testWidgets('a notification of a reply only in its thread opens the '
+ 'thread', (tester) async {
+ await pump(tester, threaded(), messageId: 'm2');
+
+ expect(find.text('Thread'), findsOneWidget);
+ expect(inThread(onlyThere), findsOneWidget);
+ expect(
+ find.text('The original message is no longer in this chat.'),
+ findsNothing,
+ );
+ });
+
+ testWidgets('a person who can only read opens the thread with no box to '
+ 'reply in, and no Reply', (tester) async {
+ await pump(tester, threaded(members: [person(me, role: 'viewer')]));
+
+ await tester.tap(find.text(next));
+ await tester.pumpAndSettle();
+ expect(key('swarm-reply-m4'), findsNothing);
+
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+
+ expect(inThread(onlyThere), findsOneWidget);
+ expect(key('swarm-thread-box'), findsNothing);
+ expect(
+ find.text('You can read this chat, not post in it.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('taken out of the chat while its thread is open: nothing of '
+ 'it stays, not even the chat\'s name', (tester) async {
+ final fake = threaded();
+ final host = await pump(tester, fake);
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+ await tester.enterText(key('swarm-thread-field'), 'Half a reply');
+ await tester.pump();
+ expect(inThread(onlyThere), findsOneWidget);
+
+ final full = fake.routes[parts]!(null)! as Map;
+ fake.routes[parts] = (_) => {
+ ...full,
+ 'groups': [
+ for (final g in full['groups'] as List)
+ if ((g as Map)['key'] != 'g1') g,
+ ],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+
+ expect(find.text('This chat is not open to you.'), findsOneWidget);
+ for (final text in [root, onlyThere, alsoHere, 'Half a reply']) {
+ expect(find.text(text), findsNothing, reason: text);
+ }
+ expect(key('swarm-thread-chat-title'), findsNothing);
+ expect(key('swarm-thread-box'), findsNothing);
+ });
+
+ testWidgets('a reply refused as the chat is no longer the person\'s '
+ 'leaves nothing of the thread on screen', (tester) async {
+ final fake = threaded();
+ await pump(tester, fake);
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+ fake.routes[commands] = (_) => throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'Not yours.',
+ statusCode: 403,
+ );
+
+ await tester.enterText(key('swarm-thread-field'), 'Secret plan');
+ await tester.pump();
+ await tester.tap(key('swarm-thread-send'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('This chat is not open to you.'), findsOneWidget);
+ for (final text in [root, onlyThere, alsoHere, 'Secret plan']) {
+ expect(find.text(text), findsNothing, reason: text);
+ }
+ expect(key('swarm-thread-chat-title'), findsNothing);
+ expect(key('swarm-thread-box'), findsNothing);
+ });
+
+ testWidgets('a thread that fails to read shows what the chat has of it '
+ 'and Try again, which reads it', (tester) async {
+ final fake = threaded();
+ final working = fake.routes['$messages?thread=m1']!;
+ var fails = true;
+ fake.routes['$messages?thread=m1'] = (body) => fails
+ ? throw SuperTabFailure('INTERNAL', 'Server error', statusCode: 500)
+ : working(body);
+ await pump(tester, fake);
+
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+
+ expect(inThread(root), findsOneWidget);
+ expect(find.text('Server error'), findsOneWidget);
+ expect(key('swarm-chat-skeleton'), findsNothing);
+ final reads = fake.paths.where((p) => p.contains('thread=m1')).length;
+ await tester.pump(const Duration(seconds: 30));
+ expect(
+ fake.paths.where((p) => p.contains('thread=m1')).length,
+ reads,
+ reason: 'no read again on its own',
+ );
+
+ fails = false;
+ await tester.tap(key('swarm-thread-retry'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Server error'), findsNothing);
+ expect(key('swarm-thread-retry'), findsNothing);
+ expect(inThread(onlyThere), findsOneWidget);
+ });
+ });
+
group('drawn again', () {
List<Map<String, dynamic>> page() => [
message('m1', 1, author: 'agent-lead', text: 'The plan'),
diff --git a/mobile/test/swarm/swarm_conversation_test.dart b/mobile/test/swarm/swarm_conversation_test.dart
index 87e998432..d2c5f1566 100644
--- a/mobile/test/swarm/swarm_conversation_test.dart
+++ b/mobile/test/swarm/swarm_conversation_test.dart
@@ -1047,6 +1047,160 @@ void main() {
});
});
+ // Chat threads (backend threads.ts, the desktop's main stream): a reply
+ // only in its thread is read with the chat and listed in its thread alone;
+ // each page names the threads its rows are in.
+ group('threads', () {
+ Map<String, dynamic> line(String root, int replies, int last) => {
+ 'id': root,
+ 'replies': replies,
+ 'lastSequence': last,
+ 'lastAt': '2026-10-27T01:05:00.000Z',
+ 'authors': [
+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Builder'},
+ ],
+ 'people': [me],
+ };
+ Map<String, dynamic> reply(
+ String id,
+ int sequence, {
+ String root = 'm1',
+ bool also = false,
+ }) => {
+ ...message(id, sequence),
+ 'thread': root,
+ if (also) 'alsoInChat': true,
+ };
+
+ test('a reply only in its thread leaves the chat\'s list, one also sent '
+ 'stays, and the root keeps its thread line', () async {
+ final r = rig(sequence: 4);
+ r.swarm.routes[messages] = (_) => {
+ 'messages': [
+ {...message('m1', 1), 'thread': 'm1'},
+ reply('m2', 2),
+ reply('m3', 3, also: true),
+ {...message('m4', 4), 'thread': 'm4'},
+ ],
+ 'next': null,
+ 'threads': [line('m1', 2, 3)],
+ };
+
+ final c = await open(r.reader);
+
+ expect([for (final m in c.messages) m.id], ['m1', 'm2', 'm3', 'm4']);
+ expect([for (final m in c.stream) m.id], ['m1', 'm3', 'm4']);
+ expect(c.stream, same(c.stream), reason: 'made once per read');
+ expect(c.thread('m1')?.replies, 2);
+ expect(c.thread('m4'), isNull);
+ });
+
+ test('a read that brings only a thread reply moves its root\'s line and '
+ 'tells the chat, with its list as it was', () async {
+ final r = rig();
+ r.swarm.routes[messages] = (_) => {
+ 'messages': [
+ {...message('m1', 1), 'thread': 'm1'},
+ reply('m2', 2),
+ ],
+ 'next': null,
+ 'threads': [line('m1', 1, 2)],
+ };
+ final c = await open(r.reader);
+ var told = 0;
+ c.addListener(() => told++);
+ r.swarm.routes['$messages?after=2'] = (_) => {
+ 'messages': [reply('m3', 3)],
+ 'next': null,
+ 'threads': [line('m1', 2, 3)],
+ };
+
+ await c.load();
+
+ expect(told, greaterThan(0));
+ expect([for (final m in c.stream) m.id], ['m1']);
+ expect(c.thread('m1')?.replies, 2);
+ });
+
+ test('an older thread line never replaces a newer one, and the same line '
+ 'again tells no one', () async {
+ final r = rig();
+ r.swarm.routes[messages] = (_) => {
+ 'messages': [
+ {...message('m1', 1), 'thread': 'm1'},
+ ],
+ 'next': null,
+ 'threads': [line('m1', 3, 5)],
+ };
+ final c = await open(r.reader);
+ var told = 0;
+ c.addListener(() => told++);
+
+ c.keepThreads([line('m1', 2, 3)]);
+ c.keepThreads([line('m1', 3, 5)]);
+
+ expect(c.thread('m1')?.replies, 3);
+ expect(told, 0);
+ c.keepThreads([line('m1', 4, 6)]);
+ expect(c.thread('m1')?.replies, 4);
+ expect(told, 1);
+ });
+
+ test('a chat the person can no longer read forgets its thread lines and '
+ 'thread drafts', () async {
+ final r = rig();
+ var allowed = true;
+ r.swarm.routes[messages] = (_) => allowed
+ ? {
+ 'messages': [
+ {...message('m1', 1), 'thread': 'm1'},
+ reply('m2', 2),
+ ],
+ 'next': null,
+ 'threads': [line('m1', 1, 2)],
+ }
+ : throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'Not yours.',
+ statusCode: 403,
+ );
+ final c = await open(r.reader);
+ c.setThreadDraft('m1', 'Half a reply');
+ expect(c.threadDraft('m1'), 'Half a reply');
+
+ allowed = false;
+ await c.load();
+
+ expect(c.thread('m1'), isNull);
+ expect(c.threadDraft('m1'), isEmpty);
+ expect(c.stream, isEmpty);
+ });
+
+ test('opened again, a kept chat shows its roots\' lines at once, and only '
+ 'theirs', () async {
+ final r = rig();
+ r.swarm.routes[messages] = (_) => {
+ 'messages': [
+ {...message('m1', 1), 'thread': 'm1'},
+ reply('m2', 2),
+ ],
+ 'next': null,
+ 'threads': [line('m1', 1, 2), line('gone', 4, 1)],
+ };
+ await r.reader.refresh();
+ final first = SwarmConversation(r.reader, 'g1');
+ await first.load();
+ first.dispose();
+
+ final c = SwarmConversation(r.reader, 'g1');
+ addTearDown(c.dispose);
+
+ expect(c.thread('m1')?.replies, 1);
+ expect(c.thread('gone'), isNull);
+ expect([for (final m in c.stream) m.id], ['m1']);
+ });
+ });
+
group('read marks', () {
const read = '/api/super-tabs/$tab/conversations/g1/read';
diff --git a/mobile/test/swarm/swarm_thread_test.dart b/mobile/test/swarm/swarm_thread_test.dart
new file mode 100644
index 000000000..4aa3a4f7c
--- /dev/null
+++ b/mobile/test/swarm/swarm_thread_test.dart
@@ -0,0 +1,738 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_conversation.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_thread.dart';
+
+import 'swarm_fixture.dart';
+
+/// One thread of a chat on the phone (the desktop's thread panel): read
+/// through the chat's own path, replies that arrive later with the chat's
+/// reads, and a reply that goes to its root, to the chat too with Also send.
+void main() {
+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';
+ const thread = '$messages?thread=m1';
+ const commands = '/api/super-tabs/$tab/commands';
+
+ Map<String, dynamic> message(
+ String id,
+ int sequence, {
+ String? root,
+ bool also = false,
+ String conversationId = 'g1',
+ }) => {
+ 'id': id,
+ 'conversationId': conversationId,
+ 'text': 'text of $id',
+ 'sequence': sequence,
+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Builder'},
+ 'createdAt': '2026-10-27T01:00:00.000Z',
+ 'thread': root ?? id,
+ if (also) 'alsoInChat': true,
+ };
+
+ Map<String, dynamic> line(String root, int replies, int last) => {
+ 'id': root,
+ 'replies': replies,
+ 'lastSequence': last,
+ 'lastAt': '2026-10-27T01:05:00.000Z',
+ 'authors': [
+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Builder'},
+ ],
+ 'people': [me],
+ };
+
+ /// A Swarm with conversation g1 at [sequence] while [listed] says so, its
+ /// chat read with [chatRows]: root m1 and its first reply unless told.
+ Future<({FakeSwarm swarm, SwarmReader reader, SwarmConversation chat})> rig({
+ int sequence = 2,
+ String role = 'owner',
+ int? number,
+ List<Map<String, dynamic>>? chatRows,
+ bool Function()? listed,
+ }) async {
+ final swarm = FakeSwarm();
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ if (listed?.call() ?? true)
+ groupData(
+ 'g1',
+ title: 'Fix login',
+ number: number,
+ agentIds: ['agent-lead', 'agent-builder'],
+ lastMessageSequence: sequence,
+ ),
+ ],
+ ),
+ 'members': [part(me, 1, person(me, role: role))],
+ };
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ swarm.routes[messages] = (_) => {
+ 'messages': chatRows ?? [message('m1', 1), message('m2', 2, root: 'm1')],
+ 'next': null,
+ 'threads': [line('m1', 1, 2)],
+ };
+ final reader = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: swarm.request,
+ );
+ addTearDown(reader.dispose);
+ await reader.refresh();
+ final chat = SwarmConversation(reader, 'g1');
+ addTearDown(chat.dispose);
+ await chat.load();
+ return (swarm: swarm, reader: reader, chat: chat);
+ }
+
+ /// Takes each reply as the backend does — written under its operation id —
+ /// and has the chat's next read bring it back with m1 and m2.
+ void readsBack(FakeSwarm swarm, {bool Function()? lost}) {
+ final rows = [message('m1', 1), message('m2', 2, root: 'm1')];
+ swarm.routes[commands] = (body) {
+ if (lost?.call() ?? false) throw StateError('connection reset');
+ final id = body!['operationId'] as String;
+ rows.add(message(id, rows.length + 1, root: 'm1'));
+ return {'ok': true};
+ };
+ swarm.routes[messages] = (_) => {
+ 'messages': rows.reversed.toList(),
+ 'next': null,
+ };
+ }
+
+ SwarmThread open(SwarmConversation chat, [String root = 'm1']) {
+ final t = SwarmThread(chat, root);
+ addTearDown(t.dispose);
+ return t;
+ }
+
+ test('opening reads the thread through the chat\'s own path: its root, '
+ 'then its replies', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [
+ message('m1', 1),
+ message('m2', 2, root: 'm1'),
+ message('m3', 3, root: 'm1', also: true),
+ ],
+ 'next': null,
+ 'threads': [line('m1', 2, 3)],
+ };
+ final t = open(r.chat);
+ expect(t.state, SwarmChatState.loading);
+
+ await t.load();
+
+ expect(r.swarm.paths.last, thread);
+ expect(t.state, SwarmChatState.loaded);
+ expect(t.rootMessage?.id, 'm1');
+ expect([for (final m in t.replies) m.id], ['m2', 'm3']);
+ expect(t.count, 2, reason: 'as its line says');
+ expect(r.chat.thread('m1')?.replies, 2, reason: 'the chat\'s line moved');
+ expect(t.hasEarlier, isFalse);
+ });
+
+ test('a long thread reads five pages on opening, its root by itself, then '
+ 'earlier replies a page at a time', () async {
+ // The chat holds only its newest message: the root is far back.
+ final r = await rig(sequence: 200, chatRows: [message('m200', 200)]);
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m100', 100, root: 'm1')],
+ 'next': {'sequence': 100, 'id': 'm100'},
+ 'threads': [line('m1', 99, 100)],
+ };
+ for (var top = 100; top > 90; top--) {
+ r.swarm.routes['$thread&before=$top&beforeId=m$top'] = (_) => {
+ 'messages': [message('m${top - 1}', top - 1, root: 'm1')],
+ 'next': {'sequence': top - 1, 'id': 'm${top - 1}'},
+ };
+ }
+ r.swarm.routes['$messages?messageId=m1'] = (_) => {
+ 'messages': [message('m1', 1)],
+ 'next': null,
+ };
+ final t = open(r.chat);
+
+ await t.load();
+
+ expect(
+ r.swarm.paths.where((p) => p.startsWith(thread)),
+ hasLength(SwarmThread.pagesOnOpen),
+ );
+ expect(
+ [for (final m in t.replies) m.id],
+ ['m96', 'm97', 'm98', 'm99', 'm100'],
+ );
+ expect(t.rootMessage?.id, 'm1');
+ expect(t.hasEarlier, isTrue);
+ expect(t.count, 99);
+
+ await t.loadEarlier();
+
+ expect(
+ r.swarm.paths.where((p) => p.startsWith(thread)),
+ hasLength(SwarmThread.pagesOnOpen + 1),
+ );
+ expect(t.replies.map((m) => m.id), contains('m95'));
+ expect(t.readingEarlier, isFalse);
+ });
+
+ test('its root is not read by itself when the chat has it', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m2', 2, root: 'm1')],
+ 'next': null,
+ };
+ final t = open(r.chat);
+
+ await t.load();
+
+ expect(r.swarm.paths.where((p) => p.contains('messageId=')), isEmpty);
+ expect(t.rootMessage?.id, 'm1');
+ });
+
+ test('replies that arrive later come with the chat\'s own reads', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1), message('m2', 2, root: 'm1')],
+ 'next': null,
+ };
+ final t = open(r.chat);
+ await t.load();
+ var told = 0;
+ t.addListener(() => told++);
+ r.swarm.routes['$messages?after=2'] = (_) => {
+ 'messages': [message('m3', 3, root: 'm1')],
+ 'next': null,
+ 'threads': [line('m1', 2, 3)],
+ };
+
+ await r.chat.load();
+
+ expect([for (final m in t.replies) m.id], ['m2', 'm3']);
+ expect(t.count, 2);
+ expect(told, greaterThan(0));
+ });
+
+ test('rows of another conversation or another thread in an answer are '
+ 'left out', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [
+ message('m1', 1),
+ message('x1', 5, root: 'm1', conversationId: 'g-private'),
+ message('x2', 6, root: 'm9'),
+ ],
+ 'next': null,
+ };
+ final t = open(r.chat);
+
+ await t.load();
+
+ expect([for (final m in t.messages) m.id], ['m1', 'm2']);
+ });
+
+ test('a root from another chat finds nothing here, as one that is gone '
+ 'does', () async {
+ final r = await rig();
+ r.swarm.routes['$messages?thread=elsewhere'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ r.swarm.routes['$messages?messageId=elsewhere'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ final t = open(r.chat, 'elsewhere');
+
+ await t.load();
+
+ expect(t.state, SwarmChatState.loaded);
+ expect(t.rootMessage, isNull);
+ expect(t.messages, isEmpty);
+ });
+
+ group('a reply', () {
+ test('goes to the root with no one named, and to the chat too only with '
+ 'Also send', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1)],
+ 'next': null,
+ };
+ readsBack(r.swarm);
+ final t = open(r.chat);
+ await t.load();
+
+ t.draft = ' Looks good ';
+ expect(t.canSend, isTrue);
+ expect(await t.send(), isTrue);
+ t.draft = 'Shipping it';
+ t.alsoSend = true;
+ expect(await t.send(), isTrue);
+
+ expect(r.swarm.commands, [
+ {
+ 'type': 'message.send',
+ 'conversationId': 'g1',
+ 'text': 'Looks good',
+ 'replyTo': 'm1',
+ 'recipientIds': <String>[],
+ },
+ {
+ 'type': 'message.send',
+ 'conversationId': 'g1',
+ 'text': 'Shipping it',
+ 'replyTo': 'm1',
+ 'recipientIds': <String>[],
+ 'alsoSend': true,
+ },
+ ]);
+ expect(t.draft, isEmpty);
+ expect(t.alsoSend, isFalse, reason: 'each reply asks again');
+ expect(t.pending, isNull);
+ expect(r.chat.threadDraft('m1'), isEmpty);
+ });
+
+ test('shows as on its way until the chat\'s read brings it back', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1)],
+ 'next': null,
+ };
+ final answer = Completer<Object?>();
+ String? sent;
+ r.swarm.routes[commands] = (body) {
+ sent = body!['operationId'] as String;
+ return answer.future;
+ };
+ r.swarm.routes['$messages?after=2'] = (_) => {
+ 'messages': [message(sent!, 3, root: 'm1')],
+ 'next': null,
+ };
+ final t = open(r.chat);
+ await t.load();
+ t.draft = 'On it';
+
+ final sending = t.send();
+ await settle();
+ expect(t.pending, 'On it');
+ expect(t.sending, isTrue);
+ expect(t.draft, isEmpty);
+
+ answer.complete({'ok': true});
+ await sending;
+
+ expect(t.pending, isNull);
+ expect([for (final m in t.replies) m.id], ['m2', sent]);
+ });
+
+ test('taken by the backend and not read back yet, it stays on its way '
+ 'until a read brings it', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1)],
+ 'next': null,
+ };
+ String? sent;
+ r.swarm.routes[commands] = (body) {
+ sent = body!['operationId'] as String;
+ return {'ok': true};
+ };
+ var reads = 0;
+ r.swarm.routes['$messages?after=2'] = (_) => switch (reads++) {
+ // The read after the post fails; the next one has not got it yet.
+ 0 => throw StateError('offline'),
+ 1 => {'messages': <Object>[], 'next': null},
+ _ => {
+ 'messages': [message(sent!, 3, root: 'm1')],
+ 'next': null,
+ },
+ };
+ final t = open(r.chat);
+ await t.load();
+ t.draft = 'On it';
+
+ expect(await t.send(), isTrue, reason: 'the backend took it');
+
+ expect(t.pending, 'On it');
+ expect(t.confirmed, isTrue);
+ expect(t.unconfirmed, isFalse, reason: 'not to be sent again');
+ t.draft = 'And another';
+ expect(t.canSend, isFalse);
+ expect(await t.send(), isFalse);
+ expect(r.swarm.commands, hasLength(1));
+
+ await r.chat.load();
+ expect(t.pending, 'On it');
+
+ await r.chat.load();
+ expect(t.pending, isNull);
+ expect(t.confirmed, isFalse);
+ expect([for (final m in t.replies) m.id], ['m2', sent]);
+ expect(t.canSend, isTrue);
+ });
+
+ test('refused goes back to the box, with Also send as it was', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1)],
+ 'next': null,
+ };
+ r.swarm.routes[commands] = (_) => throw const SuperTabFailure(
+ 'ARCHIVED',
+ 'This chat is archived.',
+ statusCode: 409,
+ );
+ final t = open(r.chat);
+ await t.load();
+ t.draft = 'Too late';
+ t.alsoSend = true;
+
+ expect(await t.send(), isFalse);
+
+ expect(t.draft, 'Too late');
+ expect(t.alsoSend, isTrue);
+ expect(t.pending, isNull);
+ expect(t.error, 'This chat is archived.');
+ expect(r.chat.threadDraft('m1'), 'Too late');
+ });
+
+ test('whose answer was lost is sent again as the same reply', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1)],
+ 'next': null,
+ };
+ var lost = true;
+ readsBack(r.swarm, lost: () => lost);
+ final t = open(r.chat);
+ await t.load();
+ t.draft = 'Once only';
+
+ expect(await t.send(), isFalse);
+ expect(t.unconfirmed, isTrue);
+ expect(t.pending, 'Once only');
+ expect(t.error, contains('not confirmed'));
+
+ lost = false;
+ expect(await t.send(), isTrue);
+
+ final posts = [
+ for (final call in r.swarm.calls)
+ if (call.path == commands) call.body!['operationId'],
+ ];
+ expect(posts, hasLength(2));
+ expect(posts.toSet(), hasLength(1));
+ expect(t.pending, isNull);
+ });
+
+ test('a viewer cannot reply', () async {
+ final r = await rig(role: 'viewer');
+ final t = open(r.chat);
+ t.draft = 'Hello';
+ expect(t.canPost, isFalse);
+ expect(t.canSend, isFalse);
+ expect(await t.send(), isFalse);
+ expect(r.swarm.commands, isEmpty);
+ });
+ });
+
+ test('the draft stays with its thread while the chat is open', () async {
+ final r = await rig();
+ final first = SwarmThread(r.chat, 'm1')..draft = 'Half a reply';
+ first.dispose();
+
+ expect(open(r.chat).draft, 'Half a reply');
+ expect(open(r.chat, 'm9').draft, isEmpty);
+ });
+
+ test('Also send names the chat as the desktop does', () async {
+ final work = await rig(number: 12);
+ expect(open(work.chat).alsoSendLabel, 'Also send to the workgroup');
+ final chat = await rig();
+ expect(open(chat.chat).alsoSendLabel, 'Also send to the chat');
+ });
+
+ group('privacy', () {
+ test('access taken away while the thread is open drops its rows, its '
+ 'draft and an answer on its way', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1), message('m2', 2, root: 'm1')],
+ 'next': null,
+ };
+ final t = open(r.chat);
+ await t.load();
+ t.draft = 'Secret plan';
+ final late = Completer<Object?>();
+ r.swarm.routes[thread] = (_) => late.future;
+ final reading = t.load();
+ await settle();
+
+ r.reader.revoke();
+ late.complete({
+ 'messages': [message('m1', 1), message('m4', 4, root: 'm1')],
+ 'next': null,
+ });
+ await reading;
+ await settle();
+
+ expect(t.state, SwarmChatState.lost);
+ expect(t.messages, isEmpty);
+ expect(t.draft, isEmpty);
+ expect(r.chat.threadDraft('m1'), isEmpty);
+ expect(t.canSend, isFalse);
+ });
+
+ test('a chat refused to the person refuses its thread alike, showing '
+ 'nothing', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'Not yours.',
+ statusCode: 403,
+ );
+ final t = open(r.chat);
+ t.draft = 'Hello';
+
+ await t.load();
+
+ expect(t.state, SwarmChatState.lost);
+ expect(t.messages, isEmpty);
+ expect(t.draft, isEmpty);
+ expect(t.error, isNull, reason: 'the page says it is not open');
+ });
+
+ for (final code in ['FORBIDDEN', 'NOT_FOUND']) {
+ test('a reply refused with $code drops the thread as a refused read '
+ 'does, and the chat reads again', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1), message('m2', 2, root: 'm1')],
+ 'next': null,
+ };
+ final t = open(r.chat);
+ await t.load();
+ r.swarm.routes[commands] = (_) =>
+ throw SuperTabFailure(code, 'Not yours.', statusCode: 403);
+ final before = r.swarm.paths.length;
+ t.draft = 'Secret plan';
+ t.alsoSend = true;
+
+ expect(await t.send(), isFalse);
+ await settle();
+
+ expect(t.state, SwarmChatState.lost);
+ expect(t.messages, isEmpty);
+ expect(t.draft, isEmpty, reason: 'not put back in the box');
+ expect(t.alsoSend, isFalse);
+ expect(t.pending, isNull);
+ expect(t.error, isNull, reason: 'the page says it is not open');
+ expect(r.chat.threadDraft('m1'), isEmpty);
+ expect(
+ r.swarm.paths.skip(before).where((p) => p.startsWith(messages)),
+ isNotEmpty,
+ reason: 'the chat reads again',
+ );
+ });
+ }
+
+ test(
+ 'a reaction whose read of the thread is refused drops the thread',
+ () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1), message('m2', 2, root: 'm1')],
+ 'next': null,
+ };
+ final t = open(r.chat);
+ await t.load();
+ r.swarm.routes[commands] = (_) => {'ok': true};
+ r.swarm.routes[thread] = (_) => throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'Not yours.',
+ statusCode: 403,
+ );
+
+ expect(
+ await t.react(t.replies.single, SuperTabReactionEmoji.rocket),
+ isTrue,
+ );
+ await settle();
+
+ expect(t.state, SwarmChatState.lost);
+ expect(t.messages, isEmpty);
+ },
+ );
+
+ test('a refused reaction has the chat read again, and a chat refused '
+ 'there drops the thread', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1), message('m2', 2, root: 'm1')],
+ 'next': null,
+ };
+ final t = open(r.chat);
+ await t.load();
+ const refused = SuperTabFailure(
+ 'FORBIDDEN',
+ 'Not yours.',
+ statusCode: 403,
+ );
+ r.swarm.routes[commands] = (_) => throw refused;
+ r.swarm.routes[messages] = (_) => throw refused;
+
+ expect(
+ await t.react(t.replies.single, SuperTabReactionEmoji.rocket),
+ isFalse,
+ );
+ await settle();
+
+ expect(r.chat.state, SwarmChatState.lost);
+ expect(t.state, SwarmChatState.lost);
+ expect(t.messages, isEmpty);
+ });
+
+ test('a reply refused after its thread closed puts nothing back', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1)],
+ 'next': null,
+ };
+ final answer = Completer<Object?>();
+ r.swarm.routes[commands] = (_) => answer.future;
+ final t = SwarmThread(r.chat, 'm1');
+ await t.load();
+ t.draft = 'Too late';
+ final sending = t.send();
+ await settle();
+
+ t.dispose();
+ answer.completeError(
+ const SuperTabFailure(
+ 'ARCHIVED',
+ 'This chat is archived.',
+ statusCode: 409,
+ ),
+ );
+
+ expect(await sending, isFalse);
+ expect(r.chat.threadDraft('m1'), isEmpty);
+ });
+
+ test('a reply refused after access went puts nothing back', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1)],
+ 'next': null,
+ };
+ final answer = Completer<Object?>();
+ r.swarm.routes[commands] = (_) => answer.future;
+ final t = open(r.chat);
+ await t.load();
+ t.draft = 'Secret plan';
+ t.alsoSend = true;
+ final sending = t.send();
+ await settle();
+
+ r.reader.revoke();
+ answer.completeError(
+ const SuperTabFailure(
+ 'ARCHIVED',
+ 'This chat is archived.',
+ statusCode: 409,
+ ),
+ );
+
+ expect(await sending, isFalse);
+ expect(t.state, SwarmChatState.lost);
+ expect(t.draft, isEmpty);
+ expect(t.alsoSend, isFalse);
+ expect(t.error, isNull);
+ expect(r.chat.threadDraft('m1'), isEmpty);
+ });
+
+ test('taken out of the chat, the thread hides what it read', () async {
+ var listed = true;
+ final r = await rig(listed: () => listed);
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1), message('m2', 2, root: 'm1')],
+ 'next': null,
+ };
+ final t = open(r.chat);
+ await t.load();
+ expect(t.messages, isNotEmpty);
+ listed = false;
+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};
+
+ await r.reader.refresh();
+ await settle();
+
+ expect(t.messages, isEmpty);
+ expect(t.state, isNot(SwarmChatState.loaded));
+ });
+
+ test('a failed read says so, is not left loading, and reads again when '
+ 'asked', () async {
+ final r = await rig();
+ var fails = true;
+ r.swarm.routes[thread] = (_) => fails
+ ? throw StateError('offline')
+ : {
+ 'messages': [message('m1', 1), message('m2', 2, root: 'm1')],
+ 'next': null,
+ };
+ final t = open(r.chat);
+
+ await t.load();
+
+ expect(t.error, 'Could not load the thread. Try again.');
+ expect(r.swarm.paths.where((p) => p.startsWith(thread)), hasLength(1));
+ await settle();
+ expect(
+ r.swarm.paths.where((p) => p.startsWith(thread)),
+ hasLength(1),
+ reason: 'no read of its own again',
+ );
+
+ fails = false;
+ await t.load();
+
+ expect(t.error, isNull);
+ expect(t.state, SwarmChatState.loaded);
+ expect([for (final m in t.replies) m.id], ['m2']);
+ });
+
+ test('earlier replies that fail say so and can be asked again', () async {
+ final r = await rig();
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1), message('m2', 2, root: 'm1')],
+ 'next': {'sequence': 2, 'id': 'm2'},
+ };
+ for (var top = 2; top < 10; top++) {
+ // Five pages on opening, each ending where it began.
+ r.swarm.routes['$thread&before=$top&beforeId=m$top'] = (_) => {
+ 'messages': <Object>[],
+ 'next': {'sequence': 2, 'id': 'm2'},
+ };
+ }
+ final t = open(r.chat);
+ await t.load();
+ expect(t.hasEarlier, isTrue);
+ r.swarm.routes['$thread&before=2&beforeId=m2'] = (_) =>
+ throw StateError('offline');
+
+ await t.loadEarlier();
+
+ expect(t.error, 'Could not load earlier replies. Try again.');
+ expect(t.readingEarlier, isFalse);
+ expect(t.hasEarlier, isTrue);
+ });
+ });
+}