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.

Merge batch 11-04 b0215: #2861 #2852 #2849 #2851 #2848 (#2862)

0xken15e0d1e6fe4170
diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dart
index 57783e3c3..e19ce74f8 100644
--- a/mobile/lib/swarm/swarm_conversation.dart
+++ b/mobile/lib/swarm/swarm_conversation.dart
@@ -29,7 +29,9 @@ import 'swarm_uploads.dart';
/// and is asked for by id, as a closed one is in no full read; one it never
/// had is asked for while its messages are read. One the person cannot read
/// keeps nothing here: messages, draft and a post not confirmed.
-class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
+class SwarmConversation extends ChangeNotifier
+ with SwarmMentioning
+ implements SwarmFilesBox {
/// [shown] and [heldAt] as they are from the start, so what it kept is
/// read only as far as it is seen.
SwarmConversation(
@@ -124,6 +126,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
}
}
+ @override
final SwarmReader reader;
final String id;
@@ -193,21 +196,40 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
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.
+ /// `threadDraft`), and those it mentions (`threadMentions`): a thread
+ /// closed and opened again finds them.
final _threadDrafts = <String, String>{};
+ final _threadMentions = <String, Map<String, String>>{};
String threadDraft(String root) =>
_threadDrafts[root] ??
reader.kept?.draft(reader.tabId, id, root)?.text ??
'';
- void setThreadDraft(String root, String text) {
+
+ /// Those [root]'s thread's draft mentions, by id with the token that names
+ /// them.
+ Map<String, String> threadMentions(String root) =>
+ _threadMentions[root] ??
+ reader.kept?.draft(reader.tabId, id, root)?.mentions ??
+ const {};
+
+ void setThreadDraft(
+ String root,
+ String text, [
+ Map<String, String> mentions = const {},
+ ]) {
if (_refused) return;
- reader.kept?.setDraft(reader.tabId, id, root, text);
+ reader.kept?.setDraft(reader.tabId, id, root, text, mentions);
if (text.isEmpty) {
_threadDrafts.remove(root);
} else {
_threadDrafts[root] = text;
}
+ if (text.isEmpty || mentions.isEmpty) {
+ _threadMentions.remove(root);
+ } else {
+ _threadMentions[root] = Map.of(mentions);
+ }
}
/// On screen, no other screen covers it and Harness is in front: what it
@@ -301,10 +323,6 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
int _epoch = 0;
String _draft = '';
- /// Agents and people mentioned in the draft, by id, with the token that
- /// names them: an agent's is a recipient, a person's a tag.
- final _mentions = <String, String>{};
-
/// The person's posts on their way, each sent on its own and — while its
/// answer never came — retried under its own operation id, so the backend
/// runs it once.
@@ -516,10 +534,12 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
false;
}
+ @override
String get draft => _draft;
+ @override
set draft(String value) {
_draft = value;
- _mentions.removeWhere((_, token) => !containsMention(value, token));
+ keepMentionsOf(value);
_composer.changed();
}
@@ -528,48 +548,6 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
RegExp('(?:^|\\s)${RegExp.escape(token)}(?=\$|\\s|[.,!?;:])')
.hasMatch(text);
- /// The name typed after an @ that ends the draft — what the mention picker
- /// narrows to; null while the draft does not end in one.
- String? get mentionQuery =>
- RegExp(r'(?:^|\s)@(\S*)$').firstMatch(_draft)?.group(1);
-
- /// [id]'s name — an agent's or a person's — in place of the @ being typed
- /// ([mentionQuery]), as [mention] adds it.
- void completeMention(String id) {
- if (mentionQuery case final query?) {
- _draft = _draft.substring(0, _draft.length - query.length - 1);
- }
- mention(id);
- }
-
- /// The Tag chip: ends the draft in an @, which opens the picker, or takes
- /// back an @ with no name typed after it. A name being typed is left alone.
- void toggleMention() {
- switch (mentionQuery) {
- case null:
- final spaced = _draft.isEmpty || RegExp(r'\s$').hasMatch(_draft);
- draft = '$_draft${spaced ? '' : ' '}@';
- case '':
- draft = _draft.substring(0, _draft.length - 1);
- case _:
- break;
- }
- }
-
- /// Adds [id]'s name to the draft: an agent's (the post goes to it) or a
- /// person's username (the post tags them), while the name stays in the
- /// text.
- void mention(String id) {
- final snapshot = reader.snapshot;
- if (snapshot == null) return;
- final person = snapshot.people.where((p) => p.id == id).firstOrNull;
- final token = '@${person?.username ?? snapshot.agentName(id)}';
- final spaced = _draft.isEmpty || RegExp(r'\s$').hasMatch(_draft);
- _draft = '$_draft${spaced ? '' : ' '}$token ';
- _mentions[id] = token;
- _composer.changed();
- }
-
/// The agents a post can mention: those in this conversation.
List<SuperTabAgent> get mentionable {
final snapshot = reader.snapshot;
@@ -697,6 +675,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
_forget();
_draft = _keptDraft = '';
_threadDrafts.clear();
+ _threadMentions.clear();
reader.kept?.dropChat(reader.tabId, id);
// A thread's files go too; its own screen hears it and gives up theirs.
for (final box in _threadFiles.values) {
@@ -915,7 +894,14 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
final again = _outbox.unconfirmed;
return again != null && await retry(again);
}
- if (conversation == null) return false;
+ final group = conversation;
+ if (group == null) return false;
+ // As the desktop's, before any file goes up.
+ if (namesAgentGone(_draft, group.agentIds)) {
+ error = swarmMentionedAgentLeft;
+ _tell();
+ return false;
+ }
final ids = await _uploadAll(outgoing);
if (ids == null || _disposed) return false;
final body = _compose(ids);
@@ -1448,14 +1434,8 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
Map<String, dynamic>? _compose([List<String> attachmentIds = const []]) {
final text = _draft.trim();
final group = conversation;
- final people = {...?reader.snapshot?.people.map((p) => p.id)};
if ((text.isEmpty && attachmentIds.isEmpty) || group == null) return null;
- // A person still in the Swarm whose username the text still says is
- // tagged, as Desktop sends it; the backend refuses one who cannot read.
- final tagged = [
- for (final MapEntry(key: id, value: token) in _mentions.entries)
- if (containsMention(text, token) && people.contains(id)) id,
- ];
+ final (:tagged, :addressed) = mentionsSaid(text, group.agentIds);
return {
'operationId': superTabOperationId(),
'command': {
@@ -1463,12 +1443,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
'conversationId': id,
'text': text,
'replyTo': _replyingTo?.id,
- 'recipientIds': [
- for (final MapEntry(key: agentId, value: token) in _mentions.entries)
- if (containsMention(text, token) &&
- group.agentIds.contains(agentId))
- agentId,
- ],
+ 'recipientIds': addressed,
if (tagged.isNotEmpty) 'mentions': tagged,
if (attachmentIds.isNotEmpty) 'attachmentIds': attachmentIds,
// As the desktop's: the server refuses it in an older Buddy chat.
@@ -1523,3 +1498,152 @@ enum SwarmChatState { loading, locating, loaded, lost }
class _Changes extends ChangeNotifier {
void changed() => notifyListeners();
}
+
+/// The desktop's words (`controller.dart` `send`, `sendThreadReply`) for a
+/// draft that still names an agent picked for it who has left the chat since.
+const swarmMentionedAgentLeft =
+ 'A mentioned agent is no longer in this conversation. '
+ 'Remove its mention or choose another agent.';
+
+/// The @ of a box — the chat's composer, a thread's reply box
+/// ([SwarmThread]): the name typed after an @, and the agents and people
+/// picked for the draft while its text still names them.
+mixin SwarmMentioning {
+ SwarmReader get reader;
+ String get draft;
+
+ /// Calls [keepMentionsOf] and tells the box.
+ set draft(String value);
+
+ /// Agents and people mentioned in the draft, by id, with the token that
+ /// names them: an agent's is a recipient, a person's a tag.
+ final _mentions = <String, String>{};
+
+ /// Those the draft mentions, by id with the token that names them.
+ Map<String, String> get mentions => Map.unmodifiable(_mentions);
+
+ /// [picked] mentioned again: a draft kept, or a post refused, put back.
+ @protected
+ void restoreMentions(Map<String, String> picked) => _mentions.addAll(picked);
+
+ /// Nobody is mentioned any more: the draft went, or the box with it.
+ @protected
+ void forgetMentions() => _mentions.clear();
+
+ /// Drops those [text] no longer names.
+ @protected
+ void keepMentionsOf(String text) => _mentions.removeWhere(
+ (_, token) => !SwarmConversation.containsMention(text, token),
+ );
+
+ /// The name typed after an @ that ends the draft — what the mention picker
+ /// narrows to; null while the draft does not end in one.
+ String? get mentionQuery =>
+ RegExp(r'(?:^|\s)@(\S*)$').firstMatch(draft)?.group(1);
+
+ /// [id]'s name — an agent's or a person's — in place of the @ being typed
+ /// ([mentionQuery]), as [mention] adds it.
+ void completeMention(String id) {
+ final text = draft;
+ final query = mentionQuery;
+ _name(
+ id,
+ query == null ? text : text.substring(0, text.length - query.length - 1),
+ );
+ }
+
+ /// The Tag chip: ends the draft in an @, which opens the picker, or takes
+ /// back an @ with no name typed after it. A name being typed is left alone.
+ void toggleMention() {
+ final text = draft;
+ switch (mentionQuery) {
+ case null:
+ final spaced = text.isEmpty || RegExp(r'\s$').hasMatch(text);
+ draft = '$text${spaced ? '' : ' '}@';
+ case '':
+ draft = text.substring(0, text.length - 1);
+ case _:
+ break;
+ }
+ }
+
+ /// Adds [id]'s name to the draft: an agent's (the post goes to it) or a
+ /// person's username (the post tags them), while the name stays in the
+ /// text.
+ void mention(String id) => _name(id, draft);
+
+ /// The token that names [id] in a draft: a person's username or an
+ /// agent's name, after an @. Null before the Swarm is read.
+ String? _tokenOf(String id) {
+ final snapshot = reader.snapshot;
+ if (snapshot == null) return null;
+ final person = snapshot.people.where((p) => p.id == id).firstOrNull;
+ return '@${person?.username ?? snapshot.agentName(id)}';
+ }
+
+ /// Those a sent [command] named, by id with their tokens as [text] still
+ /// says them: what a kept post puts back in the box when it is refused.
+ Map<String, String> mentionsSent(Map<String, dynamic> command, String text) {
+ final ids = {
+ ...?(command['recipientIds'] as List?)?.whereType<String>(),
+ ...?(command['mentions'] as List?)?.whereType<String>(),
+ };
+ return {
+ for (final id in ids)
+ if (_tokenOf(id) case final token?
+ when SwarmConversation.containsMention(text, token))
+ id: token,
+ };
+ }
+
+ /// [id]'s name after [before], as the draft.
+ void _name(String id, String before) {
+ final token = _tokenOf(id);
+ if (token == null) return;
+ final spaced = before.isEmpty || RegExp(r'\s$').hasMatch(before);
+ // Picked first: the draft keeps only those its text names.
+ _mentions[id] = token;
+ draft = '$before${spaced ? '' : ' '}$token ';
+ }
+
+ /// What the mentions [text] still names send, as Desktop sends them
+ /// (`_tagsSaid`): the people still in the Swarm, tagged, and the agents of
+ /// [agentIds], its recipients. The backend checks each again, and refuses
+ /// a person who cannot read the chat.
+ /// Whether [text] still names an agent picked for it that is not one of
+ /// [agentIds] any more: an agent of the Swarm that has left the chat
+ /// since, which the desktop refuses (`send`, `sendThreadReply`). A person
+ /// who left the Swarm is only no longer tagged, as before.
+ bool namesAgentGone(String text, List<String> agentIds) {
+ final snapshot = reader.snapshot;
+ if (snapshot == null) return false;
+ return _mentions.entries.any(
+ (entry) =>
+ SwarmConversation.containsMention(text, entry.value) &&
+ !agentIds.contains(entry.key) &&
+ snapshot.agent(entry.key) != null &&
+ !snapshot.people.any((p) => p.id == entry.key),
+ );
+ }
+
+ ({List<String> tagged, List<String> addressed}) mentionsSaid(
+ String text,
+ List<String> agentIds,
+ ) {
+ final people = {...?reader.snapshot?.people.map((p) => p.id)};
+ final said = [
+ for (final MapEntry(key: id, value: token) in _mentions.entries)
+ if (SwarmConversation.containsMention(text, token)) id,
+ ];
+ return (
+ tagged: [
+ for (final id in said)
+ if (people.contains(id)) id,
+ ],
+ addressed: [
+ for (final id in said)
+ if (agentIds.contains(id)) id,
+ ],
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index 8d4d7d405..9a508763d 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -179,13 +179,8 @@ class SwarmConversationPage extends StatefulWidget {
/// it is their Buddy chat.
final SwarmBuddyActions? buddy;
- /// Swarm Home C's project chat (Tony, 2026-10-30): a New messages line
- /// above the first message the person had not read as it opened
- /// ([swarmFirstUnread]), placed once, the chat opening at it when it is
- /// above the screen; Jump to first unread while the line is above the view
- /// and has not been seen; and Jump to latest while they read more than a
- /// screen back. The person's own Buddy chat has them too, in the project's
- /// Buddy tab and on its own page.
+ /// Swarm Home C's project chat (Tony, 2026-10-30): it gates only the
+ /// add-reaction chip after a message's reactions.
final bool homeC;
/// At the root of a tab, as the Buddy tab holds the person's Buddy chat: no
@@ -263,15 +258,11 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
/// says how many. Null at the foot.
final _held = ValueNotifier<String?>(null);
- /// Whether this chat has the New messages line and Jump to latest: Swarm
- /// Home C's project chat and the person's own Buddy chat, known as the chat
- /// opens. Not a work chat.
- bool _unreadLine = false;
-
- /// Whether this chat's Swarm has not been read yet, so whose Buddy chat it
- /// is is not known: [_unreadLine] waits for the first read that works, and
+ /// Whether this chat's Swarm has not been read yet, so the server's read
+ /// mark for it is not known (a notice tapped at launch, a Swarm read that
+ /// failed): the New messages line waits for the first read that works, and
/// nothing is read until then, as until the line is placed.
- bool _ownerUnknown = false;
+ bool _swarmUnread = false;
/// The chat's first read is done, so its line can be placed.
bool _firstRead = false;
@@ -283,8 +274,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
/// Each entry's row as last built, with what it was built from ([_row]).
final _rows = <String, ({Object inputs, Widget row})>{};
- /// Swarm Home C's New messages line: the message it sits above once
- /// placed, and whether it was placed this visit.
+ /// The New messages line: the message it sits above once placed, and
+ /// whether it was placed this visit.
String? _lineAt;
bool _lineDecided = false;
@@ -381,12 +372,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
return;
}
session.inbox.removeListener(_attach);
- _ownerUnknown =
- !widget.homeC && widget.buddy == null && reader.snapshot == null;
- _unreadLine =
- widget.homeC ||
- widget.buddy != null ||
- swarmIsOwnBuddyChat(reader, widget.conversationId);
+ _swarmUnread = reader.snapshot == null;
// Set before what the chat kept is shown, so it is read only as far as
// it is seen: with a New messages line to place, nothing until it is
// placed, a notice's message included, or the line would sit under it;
@@ -395,9 +381,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
reader,
widget.conversationId,
shown: _seen,
- heldAt: (_unreadLine || _ownerUnknown) && !_lineDecided
- ? _undecided
- : widget.messageId ?? _held.value,
+ heldAt: _lineDecided ? widget.messageId ?? _held.value : _undecided,
);
c.composer.addListener(_drafted);
// The draft it kept, in the box.
@@ -422,22 +406,21 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
if (rebuild && mounted) setState(() {});
}
- /// Places Swarm Home C's New messages line once, from what the chat's
+ /// Places the chat's New messages line once, from what the chat's
/// first read brought and how far the person had read it
/// ([SwarmReadMarks.readThrough]; nothing here is read until then, so that is
- /// how far as it opened) ([swarmFirstUnread]). The phone's marks may come
- /// back after the first read: the chat stays held, and the line is placed
- /// once they are back ([_marksMoved]). It stays there however the chat and
- /// its marks move on. Without one, everything shown is read. A line above
+ /// how far as it opened) ([swarmFirstUnread]), above a row the chat draws:
+ /// never a prompt's warning already answered, which a task's chat often
+ /// has (Desktop's `_ownShown`).
+ /// The phone's marks may come back after the first read: the chat stays
+ /// held, and the line is placed once they are back ([_marksMoved]). It
+ /// stays there however the chat and its marks move on. Without one,
+ /// everything shown is read. A line above
/// the screen opens the chat at it ([_openAtLine]), unless a notice opened
/// it at a message. A read that failed says nothing of what is unread: the
/// chat stays held, and the first read that works places it ([_chatMoved]).
void _placeLine(SwarmConversation c) {
- if (!mounted || _conversation != c || _lineDecided || _ownerUnknown) {
- return;
- }
- if (!_unreadLine) {
- _releaseHold(c);
+ if (!mounted || _conversation != c || _lineDecided || _swarmUnread) {
return;
}
if (c.state != SwarmChatState.loaded || c.error != null) return;
@@ -451,11 +434,13 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
}
_stopAwaitingMarks();
_lineDecided = true;
+ final drawn = {for (final m in _drawnOf(c).rows) m.id};
final at = swarmFirstUnread(
c.messages,
c.reader.readMarks?.readThrough(c.id),
accountId: c.reader.accountId,
hasOlder: c.hasOlder,
+ drawn: (m) => drawn.contains(m.id),
);
if (at == null) {
_releaseHold(c);
@@ -662,9 +647,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
final session = _session, c = _conversation;
if (session == null || c == null) return;
_syncSteps(c);
- if (_ownerUnknown && c.reader.snapshot != null) {
- _ownerUnknown = false;
- _unreadLine = swarmIsOwnBuddyChat(c.reader, widget.conversationId);
+ if (_swarmUnread && c.reader.snapshot != null) {
+ _swarmUnread = false;
if (_firstRead) _placeLine(c);
}
final view = _view.value = _ChatView.of(session, c, _view.value);
@@ -719,7 +703,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
_lineSeen = false;
_landing = null;
_offersUnread.value = false;
- _ownerUnknown = false;
+ _swarmUnread = false;
_firstRead = false;
_farBack.value = false;
_stopAwaitingMarks();
@@ -799,9 +783,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
if (!_scroll.hasClients) return;
_measureLineSoon();
final back = _scroll.offset > _readingBack;
- if (_unreadLine) {
- _farBack.value = _scroll.offset > _scroll.position.viewportDimension;
- }
+ _farBack.value = _scroll.offset > _scroll.position.viewportDimension;
// At the foot all is seen; reading back, only what was seen at the foot
// before, or the message a notice opened the chat at.
if (_conversation case final c?) {
@@ -1783,6 +1765,36 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
messageId: id,
);
+ /// What [c]'s list draws, oldest first ([rows]): its main stream, a reply
+ /// only in its thread showing there alone, with a task's steps' rows merged
+ /// in by time (task steps design) ([stream]); less the prompt warnings
+ /// already [answered].
+ ({
+ List<SuperTabMessage> stream,
+ Set<String> answered,
+ List<SuperTabMessage> rows,
+ })
+ _drawnOf(SwarmConversation c) {
+ final snapshot = c.reader.snapshot;
+ final stream = _steps.isEmpty
+ ? c.stream
+ : _merge.of(c.stream, {
+ for (final MapEntry(:key, :value) in _steps.entries)
+ key: value.stream,
+ });
+ final answered = answeredPromptAlerts(
+ stream,
+ (agentId) => snapshot?.agent(agentId),
+ );
+ final rows = answered.isEmpty
+ ? stream
+ : [
+ for (final m in stream)
+ if (!answered.contains(m.id)) m,
+ ];
+ return (stream: stream, answered: answered, rows: rows);
+ }
+
/// The messages, newest at the foot, with the decisions asked among them.
/// The entries are made again only when what they are made from changed,
/// and each row is the one built before while it draws the same ([_row]):
@@ -1816,24 +1828,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
}
}
final snapshot = c.reader.snapshot;
- // A reply only in its thread shows there alone. A task's steps' rows are
- // merged in by time (task steps design).
- final stream = _steps.isEmpty
- ? c.stream
- : _merge.of(c.stream, {
- for (final MapEntry(:key, :value) in _steps.entries)
- key: value.stream,
- });
- final answered = answeredPromptAlerts(
- stream,
- (agentId) => snapshot?.agent(agentId),
- );
- final messages = answered.isEmpty
- ? stream
- : [
- for (final m in stream)
- if (!answered.contains(m.id)) m,
- ];
+ final (:stream, :answered, rows: messages) = _drawnOf(c);
// The notes hidden are part of what the rows were made from: a warning
// goes once its agent's prompt is answered, with no new message.
final from = (
@@ -2256,7 +2251,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (query != null && snapshot != null && !talking)
- _MentionPicker(
+ SwarmMentionPicker(
people: c.mentionablePeople,
agents: c.mentionable,
snapshot: snapshot,
@@ -2430,7 +2425,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
: () => unawaited(_pickFiles(c)),
),
if (taggable)
- _TagButton(
+ SwarmTagButton(
open: query != null,
onTap: () {
c.toggleMention();
@@ -2725,7 +2720,7 @@ class _ChatView {
/// One row of the chat.
sealed class _Entry {}
-/// Swarm Home C's New messages line, above the first unread message.
+/// The New messages line, above the first unread message.
final class _LineEntry extends _Entry {}
/// Where a day starts.
@@ -3046,7 +3041,7 @@ class _Day extends StatelessWidget {
}
/// How many messages arrived below while the person read back — or, with
-/// none ([count] 0), Jump to latest while they read far back (Swarm Home C);
+/// none ([count] 0), Jump to latest while they read far back;
/// a tap goes down to the foot. The chat's and a thread's.
class SwarmNewPill extends StatelessWidget {
const SwarmNewPill({super.key, required this.count, required this.onTap});
@@ -3353,9 +3348,11 @@ class _Ask extends StatelessWidget {
/// them: the chat's people whose username or shown name holds what follows
/// it (each by the name they show by, `@username` beside one who set a name;
/// a pick still puts in `@username`), then its agents whose name starts with
-/// it, each with its role and what it is doing.
-class _MentionPicker extends StatelessWidget {
- const _MentionPicker({
+/// it, each with its role and what it is doing. The chat's and a thread's
+/// reply box alike.
+class SwarmMentionPicker extends StatelessWidget {
+ const SwarmMentionPicker({
+ super.key,
required this.people,
required this.agents,
required this.snapshot,
@@ -3864,12 +3861,13 @@ class SwarmAttachButton extends StatelessWidget {
);
}
-/// The chat composer's @ ([SwarmConversation.toggleMention]): ends the draft
-/// in an @, which opens the picker, or closes it again while no name is
-/// typed. The sign alone on a round face, as + is (Tony, 11-03: the word Tag
-/// said nothing more); in the accent while the picker is open.
-class _TagButton extends StatelessWidget {
- const _TagButton({required this.open, required this.onTap});
+/// The composer's @ ([SwarmMentioning.toggleMention]), the chat's and a
+/// thread's: ends the draft in an @, which opens the picker, or closes it
+/// again while no name is typed. The sign alone on a round face, as + is
+/// (Tony, 11-03: the word Tag said nothing more); in the accent while the
+/// picker is open.
+class SwarmTagButton extends StatelessWidget {
+ const SwarmTagButton({super.key, required this.open, required this.onTap});
final bool open;
final VoidCallback onTap;
diff --git a/mobile/lib/swarm/swarm_home_top.dart b/mobile/lib/swarm/swarm_home_top.dart
index a84b52dc1..7fa6ec690 100644
--- a/mobile/lib/swarm/swarm_home_top.dart
+++ b/mobile/lib/swarm/swarm_home_top.dart
@@ -1,16 +1,20 @@
import 'dart:async';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:harness_mobile/shared/theme/app_icon_size.dart';
import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/widgets/skeleton.dart';
+import 'package:harness_mobile/shared/widgets/touch_target.dart';
import 'model.dart';
import 'swarm_inbox.dart';
import 'swarm_needs_page.dart';
import 'swarm_project_tasks.dart' show swarmProgressAt;
+import 'swarm_rename.dart';
import 'swarm_row.dart';
import 'swarm_session.dart';
import 'swarm_start.dart';
@@ -50,6 +54,9 @@ String swarmHomeTitle(SwarmInbox inbox, List<SwarmListing> shown) =>
/// Swarm, the one shown ticked and what waits in each other one counted,
/// and Join or create a Swarm. A Swarm the account loses, or whose read is
/// taken away, while it is open leaves it, and a tap on it shows nothing.
+/// A Swarm with a menu for the person ([swarmHasMenu]) shows a ⋮ on its
+/// row; the ⋮, or holding the row, closes it for that menu over Home
+/// ([showSwarmMenu]).
Future<void> showSwarmSwitcher(BuildContext context, SwarmSession session) =>
showModalBottomSheet<void>(
context: context,
@@ -62,15 +69,38 @@ Future<void> showSwarmSwitcher(BuildContext context, SwarmSession session) =>
Navigator.of(sheet).pop();
unawaited(showSwarmJoinOrCreate(context));
},
+ onHold: (swarmId) {
+ Navigator.of(sheet).pop();
+ unawaited(showSwarmMenu(context, session.inbox, swarmId));
+ },
),
);
class _Switcher extends StatelessWidget {
- const _Switcher({required this.session, required this.onJoin});
+ const _Switcher({
+ required this.session,
+ required this.onJoin,
+ required this.onHold,
+ });
final SwarmSession session;
final VoidCallback onJoin;
+ /// A Swarm's menu asked for, from its row's ⋮ or by holding the row,
+ /// with its id.
+ final ValueChanged<String> onHold;
+
+ /// A row's end: what it shows ([status]), then its ⋮ ([menu]).
+ static Widget? _trailing(Widget? status, {Widget? menu}) => menu == null
+ ? status
+ : Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (status != null) ...[status, const SizedBox(width: AppSpace.s)],
+ menu,
+ ],
+ );
+
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([session.inbox, session.home]),
@@ -139,17 +169,31 @@ class _Switcher extends StatelessWidget {
key: ValueKey('swarm-switch-${swarm.id}'),
leading: SwarmProjectTile(swarm.name),
title: swarm.name,
- trailing: swarm == shown
- ? tick('Shown on Swarm Home')
- // What waits in a Swarm Home does not show.
- : switch (shown == null
- ? 0
- : swarmNeedsOf(inbox, swarm.id).length) {
- 0 => null,
- final count => SwarmBadge(count, warn: true),
- },
+ trailing: _trailing(
+ swarm == shown
+ ? tick('Shown on Swarm Home')
+ // What waits in a Swarm Home does not show.
+ : switch (shown == null
+ ? 0
+ : swarmNeedsOf(inbox, swarm.id).length) {
+ 0 => null,
+ final count => SwarmBadge(count, warn: true),
+ },
+ // Its menu, for someone with something in it to do,
+ // from a ⋮ as a chat's is.
+ menu: swarmHasMenu(inbox, swarm.id)
+ ? _SwarmMenuButton(
+ key: ValueKey('swarm-switch-menu-${swarm.id}'),
+ onTap: () => onHold(swarm.id),
+ )
+ : null,
+ ),
chevron: null,
onTap: () => show(swarm.id),
+ // Held, the same menu: a shortcut to the ⋮.
+ onLongPress: swarmHasMenu(inbox, swarm.id)
+ ? () => onHold(swarm.id)
+ : null,
),
SwarmRow(
key: const ValueKey('swarm-switch-join'),
@@ -166,6 +210,41 @@ class _Switcher extends StatelessWidget {
);
}
+/// A switcher row's ⋮: that Swarm's menu ([showSwarmMenu]), as a chat's ⋮
+/// opens its own. A thumb's size, inside the row.
+class _SwarmMenuButton extends StatelessWidget {
+ const _SwarmMenuButton({super.key, required this.onTap});
+
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) => Semantics(
+ // Its own button for a screen reader, not merged into the row's.
+ container: true,
+ button: true,
+ label: 'Swarm options',
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ HapticFeedback.selectionClick();
+ onTap();
+ },
+ child: SizedBox.square(
+ dimension: minTouchTarget,
+ child: Align(
+ alignment: AlignmentDirectional.centerEnd,
+ child: Icon(
+ LucideIcons.ellipsisVertical300,
+ size: AppIconSize.standalone,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ ),
+ );
+}
+
/// A sheet's grabber: a capsule as wide as the two largest steps.
class _Grabber extends StatelessWidget {
const _Grabber();
diff --git a/mobile/lib/swarm/swarm_inbox.dart b/mobile/lib/swarm/swarm_inbox.dart
index 3c7b9e83c..09d94e9d3 100644
--- a/mobile/lib/swarm/swarm_inbox.dart
+++ b/mobile/lib/swarm/swarm_inbox.dart
@@ -226,6 +226,74 @@ class SwarmInbox extends ChangeNotifier {
return true;
}
+ /// Names sent for a Swarm and not yet read back, with the number of the
+ /// rename that sent each ([rename]): what the list shows for it meanwhile,
+ /// so a read under way does not put the old name back.
+ final _renaming = <String, (String, int)>{};
+ int _renames = 0;
+
+ /// Renames Swarm [id] to [name], trimmed (backend `tab.rename`, the
+ /// desktop's Rename Tab): Home and the switcher show it at once, and the
+ /// name before it again when the server did not keep it. A newer rename of
+ /// the same Swarm settles it. Null once kept, when nothing changes, or once
+ /// the Swarm is no longer the person's to read; else the sentence to show.
+ Future<String?> rename(String id, String name) async {
+ final trimmed = name.trim();
+ final before = swarms.where((swarm) => swarm.id == id).firstOrNull?.name;
+ final reader = _readers[id];
+ if (_disposed || before == null || reader == null) return null;
+ if (reader.accessRevoked || !swarmCanWrite(reader)) {
+ return 'You can’t rename this Swarm.';
+ }
+ if (trimmed.isEmpty) return 'Name cannot be empty';
+ if (trimmed == before) return null;
+ final asked = ++_renames;
+ _renaming[id] = (trimmed, asked);
+ _named(id, trimmed);
+ String? error;
+ try {
+ await request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(id)}/commands',
+ body: {
+ 'operationId': superTabOperationId(),
+ 'command': {'type': 'tab.rename', 'name': trimmed},
+ },
+ );
+ } on SuperTabFailure catch (failure) {
+ error = failure.message;
+ } catch (_) {
+ // A call lost on the way (a timeout, a socket dropped) is no answer.
+ error = 'Could not rename the Swarm.';
+ }
+ if (_disposed) return null;
+ final newest = _renaming[id]?.$2 == asked;
+ if (error != null) {
+ if (newest) {
+ _renaming.remove(id);
+ _named(id, before);
+ }
+ // Lost meanwhile: the refusal is for a Swarm no longer shown.
+ return reader.accessRevoked || !identical(_readers[id], reader)
+ ? null
+ : error;
+ }
+ // Read back past a read under way, which may have been sent before it.
+ if (_refreshing case final reading?) await reading;
+ await Future.wait([refresh(), reader.refresh()]);
+ if (_renaming[id]?.$2 == asked) _renaming.remove(id);
+ return null;
+ }
+
+ /// Swarm [id] is called [name] in [swarms], at once.
+ void _named(String id, String name) {
+ if (!swarms.any((swarm) => swarm.id == id)) return;
+ swarms = List.unmodifiable([
+ for (final swarm in swarms) swarm.id == id ? (id: id, name: name) : swarm,
+ ]);
+ _rebuild(told: true);
+ }
+
/// Leaves [invitation] for now: it stays on the server, and the start
/// screen goes on to what else there is.
void notNow(SwarmInvitation invitation) {
@@ -545,7 +613,8 @@ class SwarmInbox extends ChangeNotifier {
// (backend superTabs/deletion.ts): one marked so is left out.
if (row['deletedAt'] != null) continue;
final id = row['id'] as String;
- listed[id] = (id: id, name: row['name'] as String);
+ // A rename on its way is shown until a read after it carries it.
+ listed[id] = (id: id, name: _renaming[id]?.$1 ?? row['name'] as String);
changedAt[id] = (row['lastChangedAt'] as num?)?.toInt() ?? 0;
}
after = page['next'] as String?;
diff --git a/mobile/lib/swarm/swarm_leaderboard.dart b/mobile/lib/swarm/swarm_leaderboard.dart
index d997d9bb1..6ac0478c5 100644
--- a/mobile/lib/swarm/swarm_leaderboard.dart
+++ b/mobile/lib/swarm/swarm_leaderboard.dart
@@ -5,6 +5,7 @@ import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:url_launcher/url_launcher.dart';
import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -732,10 +733,12 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {
}
/// [score]'s week in a sheet, as the desktop shows it when a name is clicked:
-/// from the leaderboard and from a project's Team. [opened] is told the
-/// sheet's route before it is pushed, not when it first draws, so a screen
-/// that loses what the sheet shows between the tap and the next frame can
-/// still close it.
+/// from the leaderboard and from a project's Team. Its points, then what they
+/// shipped, unblocked and lent item by item ([_PersonDetails]); from a server
+/// without details, their numbers line by line. [opened] is told the sheet's
+/// route before it is pushed, not when it first draws, so a screen that loses
+/// what the sheet shows between the tap and the next frame can still close
+/// it.
Future<void> showSwarmPersonWeek(
BuildContext context, {
required SwarmScore score,
@@ -745,19 +748,30 @@ Future<void> showSwarmPersonWeek(
}) {
final route = swarmSheetRoute<void>(
context,
- builder: (context) => _Sheet(
- key: const ValueKey('swarm-leaderboard-sheet'),
- title: name,
- leading: SwarmAvatar(
- id: score.personId,
- name: name,
- picture: person?.avatar,
+ // Never over the status bar: a long week scrolls inside it.
+ builder: (context) => ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(context).height * .82,
+ ),
+ child: _Sheet(
+ key: const ValueKey('swarm-leaderboard-sheet'),
+ title: name,
+ leading: SwarmAvatar(
+ id: score.personId,
+ name: name,
+ picture: person?.avatar,
+ ),
+ closeKey: 'swarm-leaderboard-sheet-close',
+ children: [
+ if (score.details case final details?)
+ Flexible(
+ child: _PersonDetails(score: score, details: details),
+ )
+ else
+ for (final (label, value) in swarmPersonWeek(score))
+ _WeekLine(label: label, value: value),
+ ],
),
- closeKey: 'swarm-leaderboard-sheet-close',
- children: [
- for (final (label, value) in swarmPersonWeek(score))
- _WeekLine(label: label, value: value),
- ],
),
);
opened?.call(route);
@@ -1369,3 +1383,232 @@ class _WeekLine extends StatelessWidget {
return width;
}
}
+
+/// What a person's numbers are made of, as the desktop's person card shows
+/// them: their points with the time before, then Shipped, Unblocked and Lent,
+/// each with its count, its newest five and the rest behind Show all, and
+/// saying so when empty. It scrolls inside its sheet.
+class _PersonDetails extends StatefulWidget {
+ const _PersonDetails({required this.score, required this.details});
+
+ final SwarmScore score;
+ final SwarmPersonDetails details;
+
+ @override
+ State<_PersonDetails> createState() => _PersonDetailsState();
+}
+
+class _PersonDetailsState extends State<_PersonDetails> {
+ /// The newest a list shows before Show all.
+ static const _shown = 5;
+
+ /// The lists whose Show all was tapped.
+ final _expanded = <String>{};
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final details = widget.details;
+ return SingleChildScrollView(
+ key: const ValueKey('swarm-leaderboard-details'),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ swarmPersonPoints(widget.score),
+ key: const ValueKey('swarm-leaderboard-details-points'),
+ style: AppType.caption(color: AppPalette.textSecondary),
+ ),
+ _section('shipped', 'Shipped', 'No pull requests merged yet', [
+ for (final shipped in details.shipped)
+ _DetailItem(title: shipped.title, link: shipped.link),
+ ]),
+ _section('unblocked', 'Unblocked', 'No questions answered yet', [
+ for (final unblocked in details.unblocked)
+ _DetailItem(
+ title: unblocked.title,
+ trailing: swarmWaited(unblocked.waitedMinutes),
+ ),
+ ]),
+ // What each machine the person brought did (contributor view,
+ // #2444), as the desktop's card; a server before it says Lent.
+ if (widget.score.brought case final brought?)
+ _section('brought', 'Brought', 'No machines brought yet', [
+ for (final machine in brought)
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _DetailItem(
+ title: machine.machineName,
+ trailing: swarmBroughtSummary(machine),
+ ),
+ for (final (engine, week) in swarmBroughtSubscriptions(
+ machine,
+ clock.now(),
+ ))
+ _DetailItem(title: engine, trailing: week, under: true),
+ ],
+ ),
+ ])
+ else
+ _section('lent', 'Lent', 'No machines lent yet', [
+ for (final lent in details.lent)
+ _DetailItem(
+ title: lent.machineName,
+ trailing: swarmBusy(lent.busyHours),
+ ),
+ ]),
+ ],
+ ),
+ );
+ }
+
+ Widget _section(String id, String title, String empty, List<Widget> items) {
+ final all = _expanded.contains(id) || items.length <= _shown;
+ final quiet = AppType.body(color: AppPalette.textSecondary);
+ return Padding(
+ key: ValueKey('swarm-leaderboard-details-$id'),
+ padding: const EdgeInsets.only(top: AppSpace.l),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ MergeSemantics(
+ child: Semantics(
+ header: true,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ Text(
+ title,
+ style: AppType.label(color: AppPalette.textPrimary),
+ ),
+ if (items.isNotEmpty) ...[
+ const SizedBox(width: AppSpace.s),
+ Text(
+ '${items.length}',
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ fontFeatures: _figures,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ if (items.isEmpty)
+ Padding(
+ padding: const EdgeInsets.only(top: AppSpace.s),
+ child: Text(empty, style: quiet),
+ )
+ else ...[
+ ...all ? items : items.take(_shown),
+ if (!all)
+ _DetailItem(
+ key: ValueKey('swarm-leaderboard-details-$id-all'),
+ title: 'Show all ${items.length}',
+ onTap: () => setState(() => _expanded.add(id)),
+ ),
+ ],
+ ],
+ ),
+ );
+ }
+}
+
+/// One item behind a person's numbers, a thumb tall: its title on up to two
+/// lines and what it measured at its right. A pull request with a web
+/// [link] opens it, and reads as a link; [onTap] makes it a button. [under]
+/// sets it in under the item before, quieter and only as tall as its words:
+/// a brought machine's subscriptions.
+class _DetailItem extends StatelessWidget {
+ const _DetailItem({
+ super.key,
+ required this.title,
+ this.trailing,
+ this.link,
+ this.onTap,
+ this.under = false,
+ });
+
+ final String title;
+ final String? trailing;
+ final Uri? link;
+ final VoidCallback? onTap;
+ final bool under;
+
+ @override
+ Widget build(BuildContext context) {
+ final link = this.link, trailing = this.trailing;
+ final onTap = link == null
+ ? this.onTap
+ : () => unawaited(launchUrl(link, mode: LaunchMode.inAppBrowserView));
+ final row = ConstrainedBox(
+ constraints: BoxConstraints(minHeight: under ? 0 : minTouchTarget),
+ // A title on two lines keeps the room one on one line has.
+ child: Padding(
+ padding: EdgeInsets.only(
+ left: under ? AppSpace.l : 0,
+ top: AppSpace.xs,
+ bottom: AppSpace.xs,
+ ),
+ child: LayoutBuilder(
+ builder: (context, line) => Row(
+ children: [
+ Expanded(
+ child: Text(
+ title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.body(
+ color: under
+ ? AppPalette.textSecondary
+ : onTap == null
+ ? AppPalette.textPrimary
+ : AppPalette.swarmAccent,
+ ),
+ ),
+ ),
+ if (trailing != null) ...[
+ const SizedBox(width: AppSpace.m),
+ // A long measure ("5 shipped · 31 h for others" in large
+ // text on a small phone) wraps rather than push the title
+ // off the line.
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: line.maxWidth * .6),
+ child: Text(
+ trailing,
+ textAlign: TextAlign.end,
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ fontFeatures: _figures,
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ );
+ if (onTap == null) return MergeSemantics(child: row);
+ void tap() {
+ HapticFeedback.selectionClick();
+ onTap();
+ }
+
+ return Semantics(
+ link: link != null,
+ button: link == null,
+ label: title,
+ onTap: tap,
+ excludeSemantics: true,
+ child: InkWell(
+ borderRadius: BorderRadius.circular(AppControl.radius),
+ onTap: tap,
+ child: row,
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_leaderboard_reader.dart b/mobile/lib/swarm/swarm_leaderboard_reader.dart
index 909a0c705..62f10b6e9 100644
--- a/mobile/lib/swarm/swarm_leaderboard_reader.dart
+++ b/mobile/lib/swarm/swarm_leaderboard_reader.dart
@@ -108,12 +108,15 @@ class SwarmScore {
_ => null,
},
prevWeekPoints = _optional(json['prevWeekPoints']),
+ details = json['details'] is Map
+ ? SwarmPersonDetails.fromJson(_map(json['details']))
+ : null,
brought = switch (_map(json['details'])['brought']) {
final List<Object?> machines => [
for (final machine in machines.whereType<Map<String, dynamic>>())
- if (machine['machineName'] case final String name)
+ if (_text(machine['machineName']) case final name?)
(
- machineName: name,
+ machineName: _withoutLocal(name),
shipped: _int(machine['shipped']),
busyHours: machine['busyHours'] is num
? (machine['busyHours'] as num).toDouble()
@@ -156,19 +159,85 @@ class SwarmScore {
/// for Last 30d, which has no comparison.
final int? prevWeekPoints;
+ /// What the numbers are made of; null from a server before details.
+ final SwarmPersonDetails? details;
+
/// Every machine the person brought (contributor view, #2444): the verified
/// requests that shipped on it, its hours for others, and each
- /// subscription's weekly use and reset. Null from a server before it, which
- /// shows Lent instead.
- final List<
- ({
- String machineName,
- int shipped,
- double busyHours,
- List<({String engine, int? usedPercent, int? resetsAt})> subscriptions,
- })
- >?
- brought;
+ /// subscription's weekly use and reset; named without `.local`. Null from a
+ /// server before it, which shows Lent instead.
+ final List<SwarmBroughtMachine>? brought;
+}
+
+/// One machine a person brought (backend `BroughtMachine`).
+typedef SwarmBroughtMachine = ({
+ String machineName,
+ int shipped,
+ double busyHours,
+ List<({String engine, int? usedPercent, int? resetsAt})> subscriptions,
+});
+
+/// A person's period item by item, each list newest first and only what the
+/// reader can read (the desktop's `SuperTabPersonDetails`). An item without a
+/// title, or a machine without a name, is left out.
+class SwarmPersonDetails {
+ SwarmPersonDetails.fromJson(Map<String, dynamic> json)
+ : shipped = List.unmodifiable([
+ for (final item in _maps(json['shipped']))
+ if (_text(item['title']) case final title?)
+ (title: title, link: _webLink(item['prUrl'])),
+ ]),
+ unblocked = List.unmodifiable([
+ for (final item in _maps(json['unblocked']))
+ if (_text(item['title']) case final title?)
+ (title: title, waitedMinutes: _int(item['waitedMinutes'])),
+ ]),
+ lent = List.unmodifiable([
+ for (final item in _maps(json['lent']))
+ if (_text(item['machineName']) case final name?)
+ (
+ machineName: _withoutLocal(name),
+ busyHours: item['busyHours'] is num
+ ? (item['busyHours'] as num).toDouble()
+ : 0.0,
+ ),
+ ]);
+
+ /// Pull requests that merged; [link] only a web page's, as a link from the
+ /// server is data and any other scheme could open a file or an app.
+ final List<({String title, Uri? link})> shipped;
+
+ /// Questions answered, and how long the agent waited.
+ final List<({String title, int waitedMinutes})> unblocked;
+
+ /// Machines whose agents ran, and for how long; named without `.local`.
+ final List<({String machineName, double busyHours})> lent;
+}
+
+List<Map<String, dynamic>> _maps(Object? value) => [
+ if (value is List)
+ for (final item in value)
+ if (item is Map) _map(item),
+];
+
+String? _text(Object? value) =>
+ value is String && value.isNotEmpty ? value : null;
+
+Uri? _webLink(Object? value) {
+ final uri = value is String ? Uri.tryParse(value) : null;
+ return uri != null &&
+ (uri.scheme == 'https' || uri.scheme == 'http') &&
+ uri.host.isNotEmpty
+ ? uri
+ : null;
+}
+
+/// A machine's name without its `.local`, as the desktop shows it.
+String _withoutLocal(String name) {
+ const suffix = '.local';
+ return name.length > suffix.length && name.toLowerCase().endsWith(suffix)
+ ? name.substring(0, name.length - suffix.length)
+ : name;
}
/// How Brought names a subscription's engine, as the Swarm's other lines do.
@@ -196,27 +265,28 @@ String _resetsIn(int at, DateTime now) {
: '${minutes ~/ 1440}d';
}
-/// A machine's Brought lines: what shipped and its hours for others, then each
-/// subscription's week.
-List<(String, String)> _broughtLines(SwarmScore score, DateTime now) {
- final brought = score.brought!;
- if (brought.isEmpty) return [('Brought', 'No machines brought yet')];
- return [
- for (final machine in brought)
- (
- machine.machineName,
- [
- '${machine.shipped} shipped · ${_broughtHours(machine.busyHours)} for others',
- for (final sub in machine.subscriptions)
- '${_engineNames[sub.engine] ?? sub.engine} ${switch (sub) {
- (usedPercent: final used?, resetsAt: final at?, engine: _) => '$used% used, resets in ${_resetsIn(at, now)}',
- (usedPercent: final used?, resetsAt: null, engine: _) => '$used% used',
- _ => 'not read yet',
- }}',
- ].join('\n'),
- ),
- ];
-}
+/// "5 shipped · 31 h for others": what a machine the person brought did.
+String swarmBroughtSummary(SwarmBroughtMachine machine) =>
+ '${machine.shipped} shipped · ${_broughtHours(machine.busyHours)} for others';
+
+/// Each of a brought machine's subscriptions with its week, as
+/// ("Claude", "38% used · resets in 3d"), in the desktop's words
+/// (`person_row.dart`).
+List<(String, String)> swarmBroughtSubscriptions(
+ SwarmBroughtMachine machine,
+ DateTime now,
+) => [
+ for (final sub in machine.subscriptions)
+ (
+ _engineNames[sub.engine] ?? sub.engine,
+ switch (sub) {
+ (usedPercent: final used?, resetsAt: final at?, engine: _) =>
+ '$used% used · resets in ${_resetsIn(at, now)}',
+ (usedPercent: final used?, resetsAt: null, engine: _) => '$used% used',
+ _ => 'not read yet',
+ },
+ ),
+];
/// "6 min" under an hour, then hours with one decimal unless whole: "3 h",
/// "3.1 h" (the desktop's `leaderboardDuration`).
@@ -405,7 +475,7 @@ class SwarmLeaderboardReader extends ChangeNotifier {
/// A person's week as the desktop's `LeaderboardPersonWeek` words it: the
/// points and place, what landed, what they answered, what they lent, and
/// their streak.
-List<(String, String)> swarmPersonWeek(SwarmScore score, {DateTime? now}) {
+List<(String, String)> swarmPersonWeek(SwarmScore score) {
String median(int? ms, String what) =>
ms == null ? '' : ' · median ${swarmDuration(ms)}$what';
return [
@@ -429,16 +499,13 @@ List<(String, String)> swarmPersonWeek(SwarmScore score, {DateTime? now}) {
: '${score.unblocked} answered${median(score.medianAnswerMs, '')}'
' · ${swarmDuration(score.unblockedMs)} of agent time freed',
),
- if (score.brought != null)
- ..._broughtLines(score, now ?? DateTime.now())
- else
- (
- 'Lent',
- score.lentMachines == 0
- ? 'Nothing lent yet'
- : '${_plural(score.lentMachines, 'machine')}'
- ' · ${swarmHours(score.lentMs)} agent-hours',
- ),
+ (
+ 'Lent',
+ score.lentMachines == 0
+ ? 'Nothing lent yet'
+ : '${_plural(score.lentMachines, 'machine')}'
+ ' · ${swarmHours(score.lentMs)} agent-hours',
+ ),
(
'Streak',
score.streakDays == 0
@@ -447,3 +514,18 @@ List<(String, String)> swarmPersonWeek(SwarmScore score, {DateTime? now}) {
),
];
}
+
+/// The points first in a person's details, as the desktop's
+/// `LeaderboardPersonWeek` says them, the time before beside them rather than
+/// a difference: "21 points in the last 7 days · 15 the 7 days before".
+String swarmPersonPoints(SwarmScore score) => [
+ '${_plural(score.points, 'point')} ${score.spanName}',
+ if (score.prevWeekPoints case final before?) '$before ${score.earlierName}',
+].join(' · ');
+
+/// "waited 1.6 h": how long an answered question's agent waited.
+String swarmWaited(int minutes) => 'waited ${swarmDuration(minutes * 60000)}';
+
+/// "12.5 h busy": how long a lent machine's agents ran.
+String swarmBusy(double hours) =>
+ '${swarmDuration((hours * 3600000).round())} busy';
diff --git a/mobile/lib/swarm/swarm_rename.dart b/mobile/lib/swarm/swarm_rename.dart
new file mode 100644
index 000000000..8f73347e4
--- /dev/null
+++ b/mobile/lib/swarm/swarm_rename.dart
@@ -0,0 +1,261 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/phone/phone_sheet.dart';
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/app_type.dart';
+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
+
+import 'swarm_buddy.dart' show swarmCanWrite;
+import 'swarm_inbox.dart';
+import 'swarm_style.dart';
+
+/// The longest name a Swarm takes here: the desktop's Rename Tab's
+/// (`swarm_dialogs.dart` `showSwarmRenameDialog`). The server takes 160.
+const swarmNameMaxLength = 80;
+
+/// What is wrong with [name] as a Swarm's name, in the desktop's words
+/// (`TerminalNamePrompt`); null when nothing is.
+String? swarmNameProblem(String name) {
+ final trimmed = name.trim();
+ if (trimmed.isEmpty) return 'Name cannot be empty';
+ if (trimmed.characters.length > swarmNameMaxLength) {
+ return 'Use at most $swarmNameMaxLength characters.';
+ }
+ return null;
+}
+
+/// Whether the person may rename Swarm [swarmId]: it is listed, read, and
+/// theirs to write in, as the server allows (backend `tab.rename`: every
+/// writable person; never a viewer).
+bool swarmMayRename(SwarmInbox inbox, String swarmId) {
+ final reader = inbox.reader(swarmId);
+ return reader != null &&
+ !reader.accessRevoked &&
+ inbox.swarms.any((swarm) => swarm.id == swarmId) &&
+ swarmCanWrite(reader);
+}
+
+/// Whether Swarm [swarmId] has a menu for the person ([showSwarmMenu]):
+/// something in it they may do. Each item of the menu adds its own check
+/// here and its row in [_swarmMenuActions].
+bool swarmHasMenu(SwarmInbox inbox, String swarmId) =>
+ swarmMayRename(inbox, swarmId);
+
+/// The rows of Swarm [swarmId]'s menu, each where the person may.
+List<PhoneSheetAction> _swarmMenuActions(
+ BuildContext context,
+ SwarmInbox inbox,
+ String swarmId,
+) => [
+ if (swarmMayRename(inbox, swarmId))
+ PhoneSheetAction(
+ icon: LucideIcons.pencil300,
+ label: 'Rename Swarm',
+ onTap: () => unawaited(showSwarmRename(context, inbox, swarmId)),
+ ),
+];
+
+/// Swarm [swarmId]'s menu, from its row's ⋮ in the switcher, or by holding
+/// the row: the desktop's menu on a Swarm's tab, as a chat's ⋮ opens its.
+/// Rename Swarm, for someone who may write there. It goes once nothing in
+/// it is the person's to do ([swarmHasMenu]): access lost, the Swarm gone.
+Future<void> showSwarmMenu(
+ BuildContext context,
+ SwarmInbox inbox,
+ String swarmId,
+) async {
+ final name = inbox.swarms
+ .where((swarm) => swarm.id == swarmId)
+ .firstOrNull
+ ?.name;
+ if (name == null || !swarmHasMenu(inbox, swarmId)) return;
+ Route<void>? sheet;
+ void moved() {
+ final route = sheet;
+ if (route == null || swarmHasMenu(inbox, swarmId)) return;
+ sheet = null;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (route.isActive) route.navigator?.removeRoute(route);
+ });
+ }
+
+ inbox.addListener(moved);
+ try {
+ await showPhoneSheet(
+ context,
+ title: name,
+ onShown: (route) => sheet = route,
+ actions: _swarmMenuActions(context, inbox, swarmId),
+ );
+ } finally {
+ inbox.removeListener(moved);
+ }
+}
+
+/// Renames Swarm [swarmId] in a dialog: its name to edit, then Save. The new
+/// name shows at once and the dialog closes; the server's refusal brings
+/// the old name back and says why at the foot of the screen. It goes once
+/// the Swarm can no longer be renamed — access lost, or gone.
+Future<void> showSwarmRename(
+ BuildContext context,
+ SwarmInbox inbox,
+ String swarmId,
+) async {
+ if (!context.mounted || !swarmMayRename(inbox, swarmId)) return;
+ await showDialog<void>(
+ context: context,
+ builder: (_) => SwarmRenameDialog(inbox: inbox, swarmId: swarmId),
+ );
+}
+
+/// What [showSwarmRename] shows.
+class SwarmRenameDialog extends StatefulWidget {
+ const SwarmRenameDialog({
+ super.key,
+ required this.inbox,
+ required this.swarmId,
+ });
+
+ final SwarmInbox inbox;
+ final String swarmId;
+
+ @override
+ State<SwarmRenameDialog> createState() => _SwarmRenameDialogState();
+}
+
+class _SwarmRenameDialogState extends State<SwarmRenameDialog> {
+ /// Opens with the whole name selected, as the desktop's does: the first
+ /// key replaces it.
+ late final _name = () {
+ final name =
+ widget.inbox.swarms
+ .where((swarm) => swarm.id == widget.swarmId)
+ .firstOrNull
+ ?.name ??
+ '';
+ return TextEditingController(text: name)
+ ..selection = TextSelection(baseOffset: 0, extentOffset: name.length);
+ }();
+ bool _closed = false;
+ String? _error;
+
+ @override
+ void initState() {
+ super.initState();
+ widget.inbox.addListener(_moved);
+ }
+
+ @override
+ void dispose() {
+ widget.inbox.removeListener(_moved);
+ _name.dispose();
+ super.dispose();
+ }
+
+ void _moved() {
+ if (_closed || !mounted || swarmMayRename(widget.inbox, widget.swarmId)) {
+ return;
+ }
+ _closed = true;
+ // Not while the inbox tells its listeners: once this frame is done.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) Navigator.of(context).pop();
+ });
+ }
+
+ void _close() {
+ if (_closed) return;
+ _closed = true;
+ Navigator.of(context).pop();
+ }
+
+ void _save() {
+ if (_closed) return;
+ if (swarmNameProblem(_name.text) case final problem?) {
+ setState(() => _error = problem);
+ return;
+ }
+ final inbox = widget.inbox, swarmId = widget.swarmId;
+ // The screen under the dialog says a refusal, once it has closed.
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ final name = _name.text;
+ _close();
+ unawaited(() async {
+ final error = await inbox.rename(swarmId, name);
+ if (error == null || messenger == null || !messenger.mounted) return;
+ messenger.showSnackBar(
+ SnackBar(
+ key: const ValueKey('swarm-rename-failed'),
+ content: Text(error),
+ ),
+ );
+ }());
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final empty = _name.text.trim().isEmpty;
+ return AlertDialog(
+ title: Text(
+ 'Rename Swarm',
+ style: AppType.heading(color: AppPalette.textPrimary),
+ ),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ TextField(
+ key: const ValueKey('swarm-rename-name'),
+ controller: _name,
+ autofocus: true,
+ maxLength: swarmNameMaxLength,
+ textInputAction: TextInputAction.done,
+ style: AppType.body(color: AppPalette.textPrimary),
+ decoration: InputDecoration(
+ // Named for a screen reader as well as seen, as the
+ // desktop's Tab name is.
+ labelText: 'Swarm name',
+ counterText: '',
+ filled: true,
+ fillColor: AppPalette.swarmField,
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(AppControl.radius),
+ borderSide: BorderSide.none,
+ ),
+ ),
+ onChanged: (_) => setState(() => _error = null),
+ onSubmitted: (_) => _save(),
+ ),
+ if (_error case final error?)
+ Padding(
+ padding: const EdgeInsets.only(top: AppSpace.s),
+ child: Text(
+ error,
+ key: const ValueKey('swarm-rename-error'),
+ style: AppType.caption(color: AppColors.danger),
+ ),
+ ),
+ ],
+ ),
+ actions: [
+ SwarmButton(
+ key: const ValueKey('swarm-rename-cancel'),
+ label: 'Cancel',
+ style: SwarmButtonStyle.link,
+ onPressed: _close,
+ ),
+ SwarmButton(
+ key: const ValueKey('swarm-rename-save'),
+ label: 'Save',
+ style: SwarmButtonStyle.fill,
+ onPressed: empty ? null : _save,
+ ),
+ ],
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_row.dart b/mobile/lib/swarm/swarm_row.dart
index eb2ddd523..e59cc72af 100644
--- a/mobile/lib/swarm/swarm_row.dart
+++ b/mobile/lib/swarm/swarm_row.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/phone/tty.dart';
@@ -27,6 +28,7 @@ class SwarmRow extends StatelessWidget {
this.chevron = LucideIcons.chevronRight300,
this.news = swarmNoNews,
required this.onTap,
+ this.onLongPress,
});
final Widget? leading;
@@ -48,6 +50,10 @@ class SwarmRow extends StatelessWidget {
final SwarmRowNews news;
final VoidCallback? onTap;
+ /// The row held, with a thump a thumb can feel: its menu. Null leaves a
+ /// held row a slow tap.
+ final VoidCallback? onLongPress;
+
/// Every row clears this, for a thumb.
static const double height = 56;
@@ -137,9 +143,19 @@ class SwarmRow extends StatelessWidget {
),
);
if (onTap == null) return row;
+ final held = onLongPress;
return Material(
color: Colors.transparent,
- child: InkWell(onTap: onTap, child: row),
+ child: InkWell(
+ onTap: onTap,
+ onLongPress: held == null
+ ? null
+ : () {
+ HapticFeedback.mediumImpact();
+ held();
+ },
+ child: row,
+ ),
);
}
}
diff --git a/mobile/lib/swarm/swarm_thread.dart b/mobile/lib/swarm/swarm_thread.dart
index dc33c5bcd..1c4892f98 100644
--- a/mobile/lib/swarm/swarm_thread.dart
+++ b/mobile/lib/swarm/swarm_thread.dart
@@ -48,10 +48,18 @@ class SwarmThreadFocus {
/// picker, limits and upload ([SwarmUploads]) to the chat's conversation,
/// before the reply. They wait in the chat's box for this thread
/// ([SwarmConversation.threadFiles]) while the chat is open.
-class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
+///
+/// An @ names people and agents as in the chat's composer ([SwarmMentioning],
+/// the desktop thread panel's `@`): a reply goes to the agents it names and
+/// tags the people.
+class SwarmThread extends ChangeNotifier
+ with SwarmMentioning
+ implements SwarmFilesBox {
SwarmThread(this.chat, this.root)
: _draft = chat.threadDraft(root),
files = chat.threadFiles(root) {
+ restoreMentions(chat.threadMentions(root));
+ keepMentionsOf(_draft);
_listed = chat.conversation != null;
chat.addListener(_chatChanged);
reader.addListener(_chatChanged);
@@ -59,14 +67,25 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
final posts = [
for (final row
in reader.kept?.posts(reader.tabId, chat.id, root) ?? const [])
- ?SwarmPost.fromKept(row, _heldOf),
+ ?SwarmPost.fromKept(row, (text) => _heldOf(text, row)),
];
if (posts.isNotEmpty) _outbox.restore(posts);
}
- /// What a kept reply puts back in the box if it is refused: only its words.
- static Object? _heldOf(String text) =>
- (draft: text, alsoSend: false, newSession: false);
+ /// What a kept reply puts back in the box if it is refused: its words and
+ /// those they named ([mentionsSent]), so they go with it again.
+ Object? _heldOf(String text, Map<String, dynamic> row) => (
+ draft: text,
+ mentions: switch (row['body']) {
+ {'command': final Map<String, dynamic> command} => mentionsSent(
+ command,
+ text,
+ ),
+ _ => const <String, String>{},
+ },
+ alsoSend: false,
+ newSession: false,
+ );
void _keepPosts() {
if (_disposed) return;
@@ -118,6 +137,7 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
@override
double? uploadProgress(SwarmOutgoingFile file) => _uploads.progress(file);
+ @override
SwarmReader get reader => chat.reader;
/// How many pages a thread reads when it opens; past them "Show earlier
@@ -219,13 +239,24 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
final _composer = _Changes();
String _draft;
+ @override
String get draft => _draft;
+ @override
set draft(String value) {
_draft = value;
- chat.setThreadDraft(root, value);
+ keepMentionsOf(value);
+ chat.setThreadDraft(root, value, mentions);
_composer.changed();
}
+ /// The agents a reply can name: the chat's, but none where the thread's
+ /// own session alone hears the reply (Desktop's thread `_tagChoices`).
+ List<SuperTabAgent> get mentionable =>
+ newSession || session != null ? const [] : chat.mentionable;
+
+ /// The people a reply can tag: the chat's.
+ List<SuperTabPerson> get mentionablePeople => chat.mentionablePeople;
+
/// The reply also goes to the chat's main stream.
bool get alsoSend => _alsoSend;
bool _alsoSend = false;
@@ -445,6 +476,7 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
_uploads.cancel();
files.clear();
_draft = '';
+ forgetMentions();
_alsoSend = false;
_outbox.clear();
error = null;
@@ -619,7 +651,8 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
}
}
- /// Sends the draft to the thread's root, also to the chat with [alsoSend]
+ /// Sends the draft to the thread's root, to the agents it names and tagging
+ /// the people it names, also to the chat with [alsoSend]
/// — or, with nothing typed while a reply is [unconfirmed], sends that one
/// again. The reply leaves the box at once and shows in [outgoing] until it
/// is read back; one on its way never holds this one back. True once the
@@ -635,7 +668,23 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
final again = _outbox.unconfirmed;
return again != null && await retry(again);
}
- if (chat.conversation == null) return false;
+ final listed = chat.conversation;
+ if (listed == null) return false;
+ // As the desktop's, before any file goes up: an agent picked for the
+ // reply who has left the chat since is never dropped without a word.
+ if (namesAgentGone(_draft, listed.agentIds)) {
+ error = swarmMentionedAgentLeft;
+ _tell();
+ return false;
+ }
+ if (_namesAgentInSession) {
+ // As the desktop's, before any file goes up.
+ error =
+ "Only this thread's session hears a reply here. "
+ "Remove the agent's mention.";
+ _tell();
+ return false;
+ }
// The files go up first, the draft and the files staying in the box
// meanwhile, as the chat's do.
var ids = const <String>[];
@@ -655,9 +704,11 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
if (up.ids == null) return false;
}
final text = _draft.trim();
- if ((text.isEmpty && ids.isEmpty) || chat.conversation == null) {
+ final group = chat.conversation;
+ if ((text.isEmpty && ids.isEmpty) || group == null) {
return false;
}
+ final (:tagged, :addressed) = mentionsSaid(text, group.agentIds);
final operationId = superTabOperationId();
final startsSession = newSession;
final post = SwarmPost(
@@ -668,7 +719,8 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
'conversationId': chat.id,
'text': text,
'replyTo': root,
- 'recipientIds': const <String>[],
+ 'recipientIds': addressed,
+ if (tagged.isNotEmpty) 'mentions': tagged,
// A session's thread stays in the thread: never also sent.
if (_alsoSend && offersAlsoSend) 'alsoSend': true,
if (startsSession) 'newSession': true,
@@ -683,9 +735,15 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
operationId: operationId,
),
files: outgoing,
- held: (draft: _draft, alsoSend: _alsoSend, newSession: _newSession),
+ held: (
+ draft: _draft,
+ mentions: mentions,
+ alsoSend: _alsoSend,
+ newSession: _newSession,
+ ),
);
_draft = '';
+ forgetMentions();
chat.setThreadDraft(root, '');
_alsoSend = false;
_newSession = false;
@@ -697,6 +755,15 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
return _answered(post, await _outbox.add(post), current);
}
+ /// The draft names an agent where the thread's own session alone hears a
+ /// reply (backend routeBuddySession), which would refuse it.
+ bool get _namesAgentInSession {
+ final group = chat.conversation;
+ return group != null &&
+ (newSession || session != null) &&
+ mentionsSaid(_draft, group.agentIds).addressed.isNotEmpty;
+ }
+
/// Sends [post], not confirmed, again under its own operation id: the
/// backend posts it once however often it goes.
Future<bool> retry(SwarmPost post) async {
@@ -741,7 +808,17 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
/// typed or added since.
void _restore(SwarmPost post) {
final sent = post.held;
- if (sent is! ({String draft, bool alsoSend, bool newSession})) return;
+ if (sent
+ is! ({
+ String draft,
+ Map<String, String> mentions,
+ bool alsoSend,
+ bool newSession,
+ })) {
+ return;
+ }
+ // Picked again first: the draft keeps those its text names.
+ restoreMentions(sent.mentions);
draft = _draft.trim().isEmpty ? sent.draft : '${sent.draft}\n$_draft';
_alsoSend = _alsoSend || sent.alsoSend;
// Refused for New session itself, it comes back as a plain reply.
diff --git a/mobile/lib/swarm/swarm_thread_page.dart b/mobile/lib/swarm/swarm_thread_page.dart
index 9684aec2c..65253c3bc 100644
--- a/mobile/lib/swarm/swarm_thread_page.dart
+++ b/mobile/lib/swarm/swarm_thread_page.dart
@@ -134,6 +134,9 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
final _targetKey = GlobalKey();
bool _landing = false;
+ /// Reply options under the card is open: folded each time the page opens.
+ bool _optionsOpen = false;
+
/// Once the thread is read: finds the focus (reading earlier replies back
/// to it, a bounded number of pages), scrolls to it and lights it for
/// 2 seconds, as the chat does for a quoted message.
@@ -407,46 +410,71 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
listenable: _thread,
builder: (context, _) => SwarmThreadSessionLine(thread: _thread),
),
+ // The box takes what it needs, up to all of the room under the
+ // header, as the chat's composer does: on a short phone with the
+ // keyboard up and the @ list open, the list and then the field
+ // give up room before anything overflows.
Expanded(
- child: Stack(
- children: [
- Positioned.fill(
- child: NotificationListener<Notification>(
- onNotification: _measured,
+ child: LayoutBuilder(
+ builder: (context, below) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: NotificationListener<Notification>(
+ onNotification: _measured,
+ child: ListenableBuilder(
+ // Message links resolve against the inbox's
+ // current reader, which can change
+ // independently of this thread's older
+ // conversation reader.
+ listenable: Listenable.merge([
+ _thread,
+ if (_session case final session?)
+ session.inbox,
+ ]),
+ builder: (context, _) => _body(tty),
+ ),
+ ),
+ ),
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 8,
+ child: ListenableBuilder(
+ listenable: Listenable.merge([_thread, _farBack]),
+ builder: (context, _) =>
+ _farBack.value &&
+ _thread.state == SwarmChatState.loaded
+ ? Center(
+ child: SwarmNewPill(
+ count: 0,
+ onTap: _toFoot,
+ ),
+ )
+ : const SizedBox.shrink(),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ConstrainedBox(
+ constraints: BoxConstraints(maxHeight: below.maxHeight),
child: ListenableBuilder(
- // Message links resolve against the inbox's current
- // reader, which can change independently of this
- // thread's older conversation reader.
listenable: Listenable.merge([
_thread,
- if (_session case final session?) session.inbox,
+ _thread.composer,
+ _voice,
]),
- builder: (context, _) => _body(tty),
+ builder: (context, _) => _foot(tty),
),
),
- ),
- Positioned(
- left: 0,
- right: 0,
- bottom: 8,
- child: ListenableBuilder(
- listenable: Listenable.merge([_thread, _farBack]),
- builder: (context, _) =>
- _farBack.value &&
- _thread.state == SwarmChatState.loaded
- ? Center(
- child: SwarmNewPill(count: 0, onTap: _toFoot),
- )
- : const SizedBox.shrink(),
- ),
- ),
- ],
+ ],
+ ),
),
),
- ListenableBuilder(
- listenable: Listenable.merge([_thread, _thread.composer, _voice]),
- builder: (context, _) => _foot(tty),
- ),
],
),
),
@@ -547,6 +575,9 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
return ListView(
key: const ValueKey('swarm-thread-messages'),
controller: _scroll,
+ // As the chat: a finger's scroll puts the keyboard away, the draft
+ // stays; a reply arriving or a jump moving the list leaves it up.
+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
// The chat's own inset, so a message sits where it does there.
padding: const EdgeInsets.symmetric(
horizontal: AppSpace.m,
@@ -623,6 +654,7 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
final group = t.chat.conversation;
final error = t.error;
return Column(
+ mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// The first read's failure is said in the body, with Try again.
@@ -643,7 +675,7 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
),
),
if (t.canPost)
- _box(t, tty)
+ Flexible(child: _box(t, tty))
else if (group != null)
Padding(
padding: const EdgeInsets.all(AppSpace.l),
@@ -659,25 +691,48 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
);
}
- /// The reply box: notes, then the card ([SwarmComposerCard]) — the files
- /// going with the reply, a field that grows with what is typed and its X,
- /// then +, Also send, the mic and a round Send (the desktop's thread
- /// composer, with the main chat's mic). While a take is under way the
- /// toolbar is the voice row ([SwarmVoiceRow]): Also send is hidden, and
- /// keeps its tick for the row's Send or the one after the take. No Tag: a
- /// thread has no @ picker.
+ /// The reply box: the @ picker while a name is typed, notes, then the card
+ /// ([SwarmComposerCard]) — the files going with the reply, a field that
+ /// grows with what is typed and its X, then +, @, the mic and a round
+ /// Send (the desktop's thread composer, with the main chat's mic and @)
+ /// — and under the card Reply options, folded until tapped: New session
+ /// and Also send, the desktop's two choices, both off to begin with
+ /// ([_options]). While a take is under way the toolbar is the voice row
+ /// ([SwarmVoiceRow]): the picker is hidden, and Reply options stays as it
+ /// is but takes no taps, its ticks kept for the row's Send or the one
+ /// after the take.
Widget _box(SwarmThread t, Tty tty) {
// A reply on its way never holds the box: the next is typed meanwhile.
final canSend = t.canSend;
final canAttach = !t.uploading && t.files.room > 0;
final voice = _voice;
final talking = voice?.face != null;
+ final snapshot = t.reader.snapshot;
+ final query = t.mentionQuery;
+ final taggable =
+ snapshot != null &&
+ (t.mentionablePeople.isNotEmpty || t.mentionable.isNotEmpty);
return Padding(
key: const ValueKey('swarm-thread-box'),
padding: SwarmComposer.padding,
child: Column(
+ mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
+ // The chat's picker: short of room, it scrolls in what is left.
+ if (query != null && snapshot != null && !talking)
+ Flexible(
+ child: SwarmMentionPicker(
+ people: t.mentionablePeople,
+ agents: t.mentionable,
+ snapshot: snapshot,
+ query: query,
+ onPick: (id) {
+ t.completeMention(id);
+ _focus.requestFocus();
+ },
+ ),
+ ),
ValueListenableBuilder(
valueListenable: _attachNote,
builder: (context, note, _) => note == null
@@ -725,7 +780,6 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
style: AppType.caption(color: AppPalette.textSecondary),
),
),
- if (t.offersSessions && !talking) SwarmNewSessionCheck(thread: t),
SwarmComposerCard(
focus: _focus,
chips: t.files.files.isEmpty ? null : SwarmOutgoingChips(box: t),
@@ -754,16 +808,15 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
? () => unawaited(_pickFiles())
: null,
),
- if (t.offersAlsoSend)
- Expanded(
- child: _AlsoSend(
- label: t.alsoSendLabel,
- value: t.alsoSend,
- onChanged: (on) => t.alsoSend = on,
- ),
- )
- else
- const Spacer(),
+ if (taggable)
+ SwarmTagButton(
+ open: query != null,
+ onTap: () {
+ t.toggleMention();
+ _focus.requestFocus();
+ },
+ ),
+ const Spacer(),
// The main chat's mic, beside Send as there.
if (voice != null) SwarmVoiceMic(voice: voice),
SwarmRoundButton(
@@ -781,11 +834,68 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
],
),
),
+ // None in a session's thread: its replies stay in the thread.
+ if (t.session == null)
+ ..._options(t, talking: talking, picking: query != null),
],
),
);
}
+ /// Reply options under the card: a line that says what is on while it is
+ /// folded, and opens to New session (in the person's own Buddy chat) and
+ /// Also send. A reply that starts a session never also goes to the chat:
+ /// Also send then keeps its place, so the box does not jump. Short of
+ /// room, the open choices scroll in what is left rather than overflow.
+ /// While the @ picker is up they step aside for it, the line saying what
+ /// is on and taking no taps, and come back after the pick.
+ List<Widget> _options(
+ SwarmThread t, {
+ required bool talking,
+ required bool picking,
+ }) {
+ final on = [
+ if (t.offersSessions && t.newSession) 'New session',
+ if (t.offersAlsoSend && t.alsoSend) t.alsoSendLabel,
+ ];
+ final open = _optionsOpen && !picking;
+ return [
+ IgnorePointer(
+ ignoring: talking || picking,
+ child: _ReplyOptionsToggle(
+ open: open,
+ on: on,
+ onTap: () => setState(() => _optionsOpen = !open),
+ ),
+ ),
+ if (open)
+ Flexible(
+ child: IgnorePointer(
+ ignoring: talking,
+ child: SingleChildScrollView(
+ key: const ValueKey('swarm-thread-options-choices'),
+ // Never the page's: a tap on the status bar scrolls the thread.
+ primary: false,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (t.offersSessions) SwarmNewSessionCheck(thread: t),
+ t.offersAlsoSend
+ ? _AlsoSend(
+ label: t.alsoSendLabel,
+ value: t.alsoSend,
+ onChanged: (on) => t.alsoSend = on,
+ )
+ : const SizedBox(height: _AlsoSend.height),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ];
+ }
+
Widget _said(String text, {Key? key}) => Padding(
key: key,
padding: const EdgeInsets.all(AppSpace.xl),
@@ -799,8 +909,72 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
);
}
+/// Reply options' line: its name and a chevron, and while folded what is
+/// on, so a ticked choice is never out of sight. The whole line is a
+/// thumb's target.
+class _ReplyOptionsToggle extends StatelessWidget {
+ const _ReplyOptionsToggle({
+ required this.open,
+ required this.on,
+ required this.onTap,
+ });
+
+ final bool open;
+
+ /// The labels of the choices that are on.
+ final List<String> on;
+ final VoidCallback onTap;
+
+ static const _name = 'Reply options';
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final said = open || on.isEmpty ? _name : '$_name · ${on.join(' · ')}';
+ return Semantics(
+ key: const ValueKey('swarm-thread-options'),
+ button: true,
+ expanded: open,
+ label: _name,
+ value: on.isEmpty ? null : on.join(', '),
+ excludeSemantics: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: _AlsoSend.height),
+ child: Padding(
+ // Its words start where the checkboxes' squares do.
+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),
+ child: Row(
+ children: [
+ Flexible(
+ child: Text(
+ said,
+ key: const ValueKey('swarm-thread-options-label'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: swarmChatText(14, color: AppPalette.textSecondary),
+ ),
+ ),
+ const SizedBox(width: AppSpace.xs),
+ Icon(
+ open ? LucideIcons.chevronUp : LucideIcons.chevronDown,
+ size: 16,
+ 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.
+/// The whole line is a thumb's target, and its label is never cut short:
+/// large text wraps it instead.
class _AlsoSend extends StatelessWidget {
const _AlsoSend({
required this.label,
@@ -808,6 +982,9 @@ class _AlsoSend extends StatelessWidget {
required this.onChanged,
});
+ /// The line's height at normal text size, kept while it is hidden.
+ static const double height = 44;
+
final String label;
final bool value;
@@ -828,7 +1005,7 @@ class _AlsoSend extends StatelessWidget {
behavior: HitTestBehavior.opaque,
onTap: enabled ? () => onChanged!(!value) : null,
child: ConstrainedBox(
- constraints: const BoxConstraints(minHeight: 44),
+ constraints: const BoxConstraints(minHeight: height),
child: Row(
children: [
// The theme's checkbox, as the desktop's thread composer has.
@@ -842,7 +1019,8 @@ class _AlsoSend extends StatelessWidget {
Flexible(
child: Text(
label,
- maxLines: 1,
+ key: const ValueKey('swarm-thread-also-send-label'),
+ maxLines: 2,
overflow: TextOverflow.ellipsis,
style: swarmChatText(
14,
diff --git a/mobile/lib/swarm/swarm_unread_line.dart b/mobile/lib/swarm/swarm_unread_line.dart
index 66ad873ba..b445c9ea0 100644
--- a/mobile/lib/swarm/swarm_unread_line.dart
+++ b/mobile/lib/swarm/swarm_unread_line.dart
@@ -14,11 +14,15 @@ import 'swarm_message_row.dart' show swarmChatText;
/// read, for a chat never read on any device (no mark), and when the read
/// does not reach back to the mark while there are [hasOlder] messages: the
/// first unread may be among those, and the chat then opens at its foot.
+/// A message [drawn] says the chat does not draw (a prompt's warning already
+/// answered) is passed over, as Desktop decides from what it shows
+/// (`_ownShown`): the line never sits above a row that is not there.
String? swarmFirstUnread(
List<SuperTabMessage> messages,
int? mark, {
required String accountId,
required bool hasOlder,
+ bool Function(SuperTabMessage message)? drawn,
}) {
if (mark == null || mark <= 0 || messages.isEmpty) return null;
if (hasOlder && messages.first.sequence > mark + 1) return null;
@@ -29,7 +33,12 @@ String? swarmFirstUnread(
if (own(m) && m.inMainStream && m.sequence > read) read = m.sequence;
}
for (final m in messages) {
- if (m.sequence > read && m.inMainStream && !own(m)) return m.id;
+ if (m.sequence > read &&
+ m.inMainStream &&
+ !own(m) &&
+ (drawn?.call(m) ?? true)) {
+ return m.id;
+ }
}
return null;
}
diff --git a/mobile/test/render/swarm_thread_render_test.dart b/mobile/test/render/swarm_thread_render_test.dart
index 90cd72735..cb06e38d4 100644
--- a/mobile/test/render/swarm_thread_render_test.dart
+++ b/mobile/test/render/swarm_thread_render_test.dart
@@ -11,6 +11,8 @@ import 'package:harness_mobile/phone/voice_input_controller.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.dart'
+ show swarmMentionedAgentLeft;
import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
import 'package:harness_mobile/swarm/swarm_file_picker.dart';
import 'package:harness_mobile/swarm/swarm_session.dart';
@@ -249,6 +251,10 @@ void main() {
});
}
+ /// The Swarm and the app of the last [chat] pumped, to change under it.
+ late FakeSwarm swarm;
+ late SwarmHost app;
+
for (final brightness in Brightness.values) {
final look = brightness.name;
@@ -300,7 +306,7 @@ void main() {
final host = SwarmHost(
accountId: () => account.value,
account: account,
- request: backend().request,
+ request: (swarm = backend()).request,
upload: stuck,
notices: SilentSystemNotices(),
features: features,
@@ -311,6 +317,7 @@ void main() {
language: ValueNotifier('en'),
),
)..foreground = false;
+ app = host;
addTearDown(host.dispose);
final key = GlobalKey();
await tester.pumpWidget(
@@ -353,6 +360,83 @@ void main() {
await shoot(tester, key, 'swarm-thread-open-$look');
});
+ testWidgets(
+ 'the thread, Reply options open, Also send ticked ($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 tester.tap(find.byKey(const ValueKey('swarm-thread-options')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('swarm-thread-also-send')));
+ await tester.pumpAndSettle();
+ await shoot(tester, key, 'swarm-thread-options-open-$look');
+ // Folded again: the line says what is on.
+ await tester.tap(find.byKey(const ValueKey('swarm-thread-options')));
+ await tester.pumpAndSettle();
+ await shoot(tester, key, 'swarm-thread-options-folded-on-$look');
+ },
+ );
+
+ testWidgets('the thread, its @ picker open ($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 tester.tap(find.byKey(const ValueKey('swarm-tag')));
+ await tester.pumpAndSettle();
+ await shoot(tester, key, 'swarm-thread-tag-$look');
+ // The draft's save, a moment after it changed.
+ await tester.pump(const Duration(seconds: 1));
+ });
+
+ testWidgets(
+ 'the thread, a picked agent who left the chat refused '
+ '($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 tester.tap(find.byKey(const ValueKey('swarm-tag')));
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('swarm-pick-agent-builder')),
+ );
+ await tester.pumpAndSettle();
+ // Nova leaves the chat, and the Swarm is read again.
+ final parts = swarm.routes['/api/super-tabs/$tab/parts']!;
+ swarm.routes['/api/super-tabs/$tab/parts'] = (body) {
+ final read = parts(body) as Map<String, dynamic>;
+ return {
+ ...read,
+ 'groups': [
+ for (final g in (read['groups'] as List).cast<Map>())
+ g['key'] == 'g1'
+ ? part('g1', (g['version'] as int) + 1, {
+ ...(g['data'] as Map<String, dynamic>),
+ 'agentIds': ['agent-lead'],
+ })
+ : g,
+ ],
+ };
+ };
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};
+ await tester.runAsync(() => app.session!.inbox.reader(tab)!.refresh());
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('swarm-thread-send')));
+ await tester.pumpAndSettle();
+ expect(find.text(swarmMentionedAgentLeft), findsOneWidget);
+ FocusManager.instance.primaryFocus?.unfocus();
+ await tester.pumpAndSettle();
+ await shoot(tester, key, 'swarm-thread-agent-left-$look');
+ // The draft's save, a moment after it changed.
+ await tester.pump(const Duration(seconds: 1));
+ },
+ );
+
testWidgets('the thread, its mic listening ($look)', skip: skip, (
tester,
) async {
diff --git a/mobile/test/swarm/swarm_buddy_unread_line_test.dart b/mobile/test/swarm/swarm_buddy_unread_line_test.dart
index 37b7f88e2..b661b7551 100644
--- a/mobile/test/swarm/swarm_buddy_unread_line_test.dart
+++ b/mobile/test/swarm/swarm_buddy_unread_line_test.dart
@@ -18,7 +18,8 @@ import 'swarm_fixture.dart';
/// (#2259) in the person's own Buddy chat too (Tony, 2026-10-30): above the
/// first message from someone else the person had not read as the chat
/// opened, placed once, the chat opening at it; and Jump to latest while
-/// they read more than a screen back. Work chats have neither.
+/// they read more than a screen back. A task's chat has both too
+/// (swarm_task_unread_line_test.dart).
void main() {
const chat = 'buddy-me';
const messages = '/api/super-tabs/$tab/conversations/$chat/messages';
@@ -277,20 +278,26 @@ void main() {
expect(find.text('Update 4.'), findsOneWidget);
});
- testWidgets('a work chat has none, nor Jump to latest', (tester) async {
+ testWidgets('a work chat has it too, from its own mark, and Jump to '
+ 'latest', (tester) async {
await pump(
tester,
backend([said(1)], mark: 1),
home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
);
- expect(line, findsNothing);
- await tester.drag(
- find.byKey(const ValueKey('swarm-messages')),
- const Offset(0, 1500),
+ // g1 is read through 3 of its 40.
+ expect(onScreen(tester, line), isTrue, reason: 'opened at the line');
+ expect(onScreen(tester, find.text('Update 4.')), isTrue);
+ expect(
+ tester.getTopLeft(find.text('Update 4.')).dy,
+ greaterThan(tester.getTopLeft(line).dy),
);
- await tester.pumpAndSettle();
-
expect(onScreen(tester, find.text('Update 40.')), isFalse);
+ expect(jump, findsOneWidget);
+
+ await tester.tap(jump);
+ await tester.pumpAndSettle();
+ expect(onScreen(tester, find.text('Update 40.')), isTrue);
expect(jump, findsNothing);
});
});
@@ -433,7 +440,9 @@ void main() {
expect(tester.getTopLeft(find.text('Update 3.')).dy, greaterThan(y));
});
- testWidgets('a work chat still has neither', (tester) async {
+ testWidgets('a work chat gets both too, with nothing read before', (
+ tester,
+ ) async {
final fake = backend([said(1)], mark: 1);
late SwarmHost host;
final recover = swarmDownAt(tester, fake, () => host);
@@ -443,18 +452,17 @@ void main() {
settle: false,
home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
);
+ expect(marksSent(fake, 'g1'), isEmpty);
await recover();
- await tester.drag(
- find.byKey(const ValueKey('swarm-messages')),
- const Offset(0, 1500),
- );
- await tester.pumpAndSettle();
- expect(line, findsNothing);
- expect(onScreen(tester, find.text('Update 40.')), isFalse);
- expect(jump, findsNothing);
- expect(marksSent(fake, 'g1'), isNotEmpty, reason: 'read, once known');
+ expect(onScreen(tester, line), isTrue, reason: 'opened at the line');
+ expect(jump, findsOneWidget);
+ expect(
+ marksSent(fake, 'g1').where((s) => (s! as int) > 3),
+ isEmpty,
+ reason: 'nothing past the line is read yet',
+ );
});
testWidgets('a chat left behind, still reading, does not mark the new '
diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dart
index e068ed8d1..54c8c2a3e 100644
--- a/mobile/test/swarm/swarm_chat_test.dart
+++ b/mobile/test/swarm/swarm_chat_test.dart
@@ -2529,6 +2529,11 @@ void main() {
expect(key('swarm-replied-in-thread-m3'), findsNothing);
expect(key('swarm-thread-box'), findsOneWidget);
expect(find.text('Reply'), findsOneWidget, reason: 'the field hint');
+ // Also send is in Reply options, folded until it is opened.
+ expect(find.text('Reply options'), findsOneWidget);
+ expect(find.text('Also send to the chat'), findsNothing);
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
expect(find.text('Also send to the chat'), findsOneWidget);
});
@@ -2768,8 +2773,19 @@ void main() {
await tester.pumpAndSettle();
await tester.enterText(key('swarm-thread-field'), 'Ship it as drawn.');
+ String said() =>
+ tester.widget<Text>(key('swarm-thread-options-label')).data!;
+ // Folded under Reply options until it is opened, nothing ticked.
+ expect(key('swarm-thread-also-send'), findsNothing);
+ expect(said(), 'Reply options');
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
await tester.tap(key('swarm-thread-also-send'));
await tester.pump();
+ // Folded again, its line says the reply goes to the chat too.
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
+ expect(said(), 'Reply options · Also send to the chat');
await tester.tap(key('swarm-thread-send'));
await tester.pumpAndSettle();
@@ -2777,6 +2793,9 @@ void main() {
expect(fake.commands.single['replyTo'], 'm1');
expect(inThread('Ship it as drawn.'), findsOneWidget);
// Ticked for this reply alone.
+ expect(said(), 'Reply options');
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
expect(
tester
.widget<Semantics>(key('swarm-thread-also-send'))
@@ -2791,6 +2810,12 @@ void main() {
.body!['operationId'];
expect(find.text('Ship it as drawn.'), findsOneWidget);
expect(key('swarm-replied-in-thread-${sentId(sent)}'), findsOneWidget);
+
+ // Opened again, the thread starts with Reply options folded.
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-thread-options'), findsOneWidget);
+ expect(key('swarm-thread-also-send'), findsNothing);
});
bool sendable(WidgetTester tester, String button) =>
diff --git a/mobile/test/swarm/swarm_composer_test.dart b/mobile/test/swarm/swarm_composer_test.dart
index 6235f494a..0256ddbbc 100644
--- a/mobile/test/swarm/swarm_composer_test.dart
+++ b/mobile/test/swarm/swarm_composer_test.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart' show RenderParagraph;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/notify/system_notices.dart';
@@ -171,8 +172,9 @@ void main() {
addTearDown(tester.view.reset);
}
- /// Chat g1 on screen; with [shell], under an outer Scaffold as the phone's
- /// shell puts every page (it takes the keyboard's inset out for its body).
+ /// Chat g1 on screen; with [shell], in a navigator under an outer Scaffold
+ /// as the phone's shell puts every page, a thread pushed over it too (it
+ /// takes the keyboard's inset out for its body).
late ValueNotifier<String?> account;
/// The microphone and the transcriber of the last [pump] with a voice.
@@ -213,7 +215,14 @@ void main() {
MaterialApp(
theme: grid.buildAppTheme(brightness: Brightness.dark),
builder: (context, child) => SwarmScope(notifier: host, child: child!),
- home: shell ? const Scaffold(body: page) : page,
+ home: shell
+ ? Scaffold(
+ body: Navigator(
+ onGenerateRoute: (_) =>
+ MaterialPageRoute<void>(builder: (_) => page),
+ ),
+ )
+ : page,
),
);
await tester.pumpAndSettle();
@@ -641,8 +650,9 @@ void main() {
message('m2', 2, text: 'Looks good.', thread: 'm1', replyTo: 'm1'),
], threads: true);
- testWidgets('the same card: + at the left, then Also send, the mic and '
- 'Send; no Tag', (tester) async {
+ testWidgets('the same card: + at the left, then Tag, the mic and Send; '
+ 'Reply options folded under the card, Also send in it, its label '
+ 'whole', (tester) async {
phone(tester);
await openThread(tester, threaded());
@@ -653,12 +663,92 @@ void main() {
),
findsOneWidget,
);
- expect(key('swarm-tag'), findsNothing);
+ expect(
+ find.descendant(
+ of: key('swarm-thread-box'),
+ matching: key('swarm-tag'),
+ ),
+ findsOneWidget,
+ );
final attach = tester.getRect(key('swarm-thread-attach'));
- final also = tester.getRect(key('swarm-thread-also-send'));
+ final tag = tester.getRect(key('swarm-tag'));
final send = tester.getRect(key('swarm-thread-send'));
- expect(attach.right, lessThanOrEqualTo(also.left));
- expect(also.right, lessThanOrEqualTo(send.left));
+ final card = tester.getRect(key('swarm-composer-card'));
+ expect(tag.left, attach.right);
+ expect(tester.getSize(key('swarm-tag')).height, 44);
+ expect(tag.right, lessThanOrEqualTo(send.left));
+ // Folded: one line under the card, a thumb's target.
+ expect(key('swarm-thread-also-send'), findsNothing);
+ final options = tester.getRect(key('swarm-thread-options'));
+ expect(options.top, card.bottom);
+ expect(options.height, greaterThanOrEqualTo(44));
+ expect(
+ tester.widget<Text>(key('swarm-thread-options-label')).data,
+ 'Reply options',
+ );
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
+ final also = tester.getRect(key('swarm-thread-also-send'));
+ // Its own line: under Reply options, not squeezed between Tag and Send.
+ expect(also.top, tester.getRect(key('swarm-thread-options')).bottom);
+ expect(also.height, greaterThanOrEqualTo(44), reason: 'a thumb target');
+ final label = tester.renderObject<RenderParagraph>(
+ key('swarm-thread-also-send-label'),
+ );
+ expect(label.didExceedMaxLines, isFalse);
+ expect(
+ tester.getSize(key('swarm-thread-also-send-label')).height,
+ lessThan(30),
+ reason: 'one line on a 393pt phone',
+ );
+ expect(
+ (label.text as TextSpan).toPlainText(),
+ startsWith('Also send to the'),
+ );
+ });
+
+ /// A thread long enough to scroll with the keyboard up.
+ FakeSwarm long() => backend([
+ message('m1', 1, author: 'agent-lead', thread: 'm1'),
+ for (var i = 2; i <= 24; i++)
+ message('m$i', i, text: 'Reply $i.', thread: 'm1', replyTo: 'm1'),
+ ], threads: true);
+
+ testWidgets('a finger scrolling the thread puts the keyboard away; the '
+ 'draft stays', (tester) async {
+ phone(tester, keyboard: 336);
+ await openThread(tester, long());
+ await type(tester, 'half a thought', 'swarm-thread-field');
+ expect(focused(tester, 'swarm-thread-field'), isTrue);
+
+ // Whichever end it opened at, one of the two moves it.
+ await tester.drag(key('swarm-thread-messages'), const Offset(0, 200));
+ await tester.drag(key('swarm-thread-messages'), const Offset(0, -200));
+ await tester.pump();
+
+ expect(focused(tester, 'swarm-thread-field'), isFalse);
+ expect(field(tester, 'swarm-thread-field').text, 'half a thought');
+ });
+
+ testWidgets('the list moving by itself leaves the keyboard up', (
+ tester,
+ ) async {
+ phone(tester, keyboard: 336);
+ await openThread(tester, long());
+ await type(tester, 'half a thought', 'swarm-thread-field');
+
+ final list = tester.state<ScrollableState>(
+ find.descendant(
+ of: key('swarm-thread-messages'),
+ matching: find.byType(Scrollable),
+ ),
+ );
+ list.position.jumpTo(0);
+ await tester.pump();
+ list.position.jumpTo(list.position.maxScrollExtent);
+ await tester.pump();
+
+ expect(focused(tester, 'swarm-thread-field'), isTrue);
});
testWidgets('its X clears the text only: the files stay, Send stays on '
@@ -682,14 +772,213 @@ void main() {
expect(sendable(tester, 'swarm-thread-send'), isTrue);
});
- testWidgets('a 320pt phone: the toolbar fits a long Also send label', (
+ testWidgets('Tag opens the chat\'s picker over the box, focus in the '
+ 'field; a pick fills the name in and the reply goes to them', (
+ tester,
+ ) async {
+ final fake = threaded();
+ await openThread(tester, fake);
+
+ await tester.tap(key('swarm-tag'));
+ await tester.pump();
+ expect(field(tester, 'swarm-thread-field').text, '@');
+ expect(focused(tester, 'swarm-thread-field'), isTrue);
+ expect(
+ find.descendant(
+ of: key('swarm-thread-box'),
+ matching: key('swarm-mention-picker'),
+ ),
+ findsOneWidget,
+ );
+ // The chat's agents, with the chat's look.
+ expect(key('swarm-pick-agent-lead'), findsOneWidget);
+ expect(key('swarm-pick-agent-builder'), findsOneWidget);
+
+ await tester.tap(key('swarm-pick-agent-builder'));
+ await tester.pump();
+ expect(field(tester, 'swarm-thread-field').text, '@Nova ');
+ expect(key('swarm-mention-picker'), findsNothing);
+
+ await type(tester, '@Nova can you look', 'swarm-thread-field');
+ await tester.tap(key('swarm-thread-send'));
+ await tester.pumpAndSettle();
+ final sent = fake.commands.single;
+ expect(sent['replyTo'], 'm1');
+ expect(sent['text'], '@Nova can you look');
+ expect(sent['recipientIds'], ['agent-builder']);
+ expect(sent.containsKey('mentions'), isFalse);
+ });
+
+ testWidgets('typing an @ narrows the same picker; a person picked is '
+ 'tagged', (tester) async {
+ final fake = backend(
+ [
+ message('m1', 1, author: 'agent-lead', thread: 'm1'),
+ message('m2', 2, text: 'Looks good.', thread: 'm1', replyTo: 'm1'),
+ ],
+ threads: true,
+ members: [
+ person(me),
+ person('dee', role: 'collaborator'),
+ ],
+ );
+ await openThread(tester, fake);
+
+ await type(tester, 'thanks @de', 'swarm-thread-field');
+ expect(key('swarm-pick-person-dee'), findsOneWidget);
+ expect(key('swarm-pick-agent-lead'), findsNothing);
+ await tester.tap(key('swarm-pick-person-dee'));
+ await tester.pump();
+ expect(field(tester, 'swarm-thread-field').text, 'thanks @dee ');
+
+ await tester.tap(key('swarm-thread-send'));
+ await tester.pumpAndSettle();
+ expect(fake.commands.single['mentions'], ['dee']);
+ expect(fake.commands.single['recipientIds'], isEmpty);
+ });
+
+ for (final shell in [false, true]) {
+ testWidgets('with the keyboard up and the picker open, the card and '
+ 'Reply options under it sit on the keyboard and the picker over '
+ 'the card, the inset taken '
+ 'once${shell ? ' under the phone shell\'s Scaffold' : ''}', (
+ tester,
+ ) async {
+ phone(tester, keyboard: 336);
+ await pump(tester, threaded(), shell: shell, upload: uploaded);
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+ await type(tester, '@', 'swarm-thread-field');
+
+ expect(tester.takeException(), isNull);
+ final card = tester.getRect(
+ find.descendant(
+ of: key('swarm-thread-box'),
+ matching: key('swarm-composer-card'),
+ ),
+ );
+ final picker = tester.getRect(key('swarm-mention-picker'));
+ final options = tester.getRect(key('swarm-thread-options'));
+ expect(options.bottom, 852 - 336 - 6);
+ expect(card.bottom, options.top);
+ expect(card.height, 86);
+ expect(picker.bottom, lessThanOrEqualTo(card.top));
+ expect(
+ picker.top,
+ greaterThanOrEqualTo(
+ tester.getRect(key('swarm-thread-header')).bottom,
+ ),
+ );
+ });
+ }
+
+ testWidgets('a 320pt phone with the keyboard up: the picker gives up room '
+ 'and scrolls, the card and Reply options stay whole on the keyboard', (
tester,
) async {
phone(tester, width: 320, height: 568, keyboard: 253);
+ await openThread(tester, threaded());
+ await type(tester, '@', 'swarm-thread-field');
+ await tester.pumpAndSettle();
+
+ expect(tester.takeException(), isNull);
+ final card = tester.getRect(
+ find.descendant(
+ of: key('swarm-thread-box'),
+ matching: key('swarm-composer-card'),
+ ),
+ );
+ final picker = tester.getRect(key('swarm-mention-picker'));
+ final options = tester.getRect(key('swarm-thread-options'));
+ expect(options.bottom, 568 - 253 - 6);
+ expect(card.bottom, options.top);
+ expect(card.height, 86);
+ expect(picker.bottom, lessThanOrEqualTo(card.top));
+ expect(
+ picker.top,
+ greaterThanOrEqualTo(tester.getRect(key('swarm-thread-header')).bottom),
+ );
+ // Short of room for both agents' 52pt rows, its border and margin: it
+ // still shows one whole row, and scrolls to the second.
+ expect(picker.height, lessThan(2 * 52 + 2 + 8));
+ expect(picker.height, greaterThanOrEqualTo(52 + 2));
+ await tester.dragUntilVisible(
+ key('swarm-pick-agent-builder'),
+ key('swarm-mention-picker'),
+ const Offset(0, -40),
+ );
+ await tester.ensureVisible(key('swarm-pick-agent-builder'));
+ await tester.pumpAndSettle();
+ final row = tester.getRect(key('swarm-pick-agent-builder'));
+ expect(row.top, greaterThanOrEqualTo(picker.top));
+ expect(row.bottom, lessThanOrEqualTo(picker.bottom));
+ await tester.tap(key('swarm-pick-agent-builder'));
+ await tester.pump();
+ expect(field(tester, 'swarm-thread-field').text, '@Nova ');
+ });
+
+ for (final shell in [false, true]) {
+ testWidgets('with the keyboard up, Reply options opened: the card, its '
+ 'line and Also send stack on the keyboard, the field keeps the '
+ 'keyboard, the inset taken '
+ 'once${shell ? ' under the phone shell\'s Scaffold' : ''}', (
+ tester,
+ ) async {
+ phone(tester, keyboard: 336);
+ await pump(tester, threaded(), shell: shell, upload: uploaded);
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+ await type(tester, 'half a thought', 'swarm-thread-field');
+ final folded = tester.getRect(
+ find.descendant(
+ of: key('swarm-thread-box'),
+ matching: key('swarm-composer-card'),
+ ),
+ );
+
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pumpAndSettle();
+
+ expect(tester.takeException(), isNull);
+ expect(focused(tester, 'swarm-thread-field'), isTrue);
+ final card = tester.getRect(
+ find.descendant(
+ of: key('swarm-thread-box'),
+ matching: key('swarm-composer-card'),
+ ),
+ );
+ final options = tester.getRect(key('swarm-thread-options'));
+ final also = tester.getRect(key('swarm-thread-also-send'));
+ expect(also.bottom, 852 - 336 - 6);
+ expect(options.bottom, also.top);
+ expect(card.bottom, options.top);
+ // Opening it lifts the card by Also send's line, no more.
+ expect(card.top, folded.top - also.height);
+ expect(card.height, folded.height);
+
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pumpAndSettle();
+ expect(
+ tester.getRect(
+ find.descendant(
+ of: key('swarm-thread-box'),
+ matching: key('swarm-composer-card'),
+ ),
+ ),
+ folded,
+ );
+ });
+ }
+
+ testWidgets('a 320pt phone with large text: the toolbar fits a long '
+ 'Also send label, and Reply options opened scrolls in what is left '
+ 'rather than overflow', (tester) async {
+ phone(tester, width: 320, height: 568, keyboard: 253);
tester.platformDispatcher.textScaleFactorTestValue = 1.3;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
await openThread(tester, threaded());
await type(tester, 'one more', 'swarm-thread-field');
+ await tester.tap(key('swarm-thread-options'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
@@ -698,6 +987,73 @@ void main() {
tester.getRect(key('swarm-thread-send')).right,
lessThan(card.right),
);
+ // Large text wraps the label rather than cutting it short.
+ expect(
+ tester
+ .renderObject<RenderParagraph>(key('swarm-thread-also-send-label'))
+ .didExceedMaxLines,
+ isFalse,
+ );
+ expect(
+ tester.getRect(key('swarm-thread-also-send')).right,
+ lessThanOrEqualTo(card.right),
+ );
+ // The box takes all of the room under the header, no more.
+ expect(
+ tester.getRect(key('swarm-thread-box')).bottom,
+ lessThanOrEqualTo(568 - 253),
+ );
+ await tester.tap(key('swarm-thread-also-send'));
+ await tester.pump();
+ expect(
+ tester
+ .widget<Semantics>(key('swarm-thread-also-send'))
+ .properties
+ .checked,
+ isTrue,
+ );
+ });
+
+ testWidgets('Reply options opened steps aside while the @ picker is up, '
+ 'its line saying what is on, and is back after the pick', (
+ tester,
+ ) async {
+ phone(tester, keyboard: 336);
+ final fake = threaded();
+ await openThread(tester, fake);
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
+ await tester.tap(key('swarm-thread-also-send'));
+ await tester.pump();
+
+ await type(tester, '@', 'swarm-thread-field');
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ expect(key('swarm-mention-picker'), findsOneWidget);
+ expect(key('swarm-thread-also-send'), findsNothing);
+ expect(
+ tester.widget<Text>(key('swarm-thread-options-label')).data,
+ 'Reply options · Also send to the chat',
+ );
+ // Its line waits for the pick.
+ await tester.tap(key('swarm-thread-options'), warnIfMissed: false);
+ await tester.pump();
+ expect(key('swarm-thread-also-send'), findsNothing);
+
+ await tester.tap(key('swarm-pick-agent-builder'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-mention-picker'), findsNothing);
+ expect(
+ tester
+ .widget<Semantics>(key('swarm-thread-also-send'))
+ .properties
+ .checked,
+ isTrue,
+ );
+ await tester.tap(key('swarm-thread-send'));
+ await tester.pumpAndSettle();
+ expect(fake.commands.single['alsoSend'], isTrue);
+ expect(fake.commands.single['recipientIds'], ['agent-builder']);
});
});
diff --git a/mobile/test/swarm/swarm_drafts_unsent_test.dart b/mobile/test/swarm/swarm_drafts_unsent_test.dart
index c1616b5cb..83102be16 100644
--- a/mobile/test/swarm/swarm_drafts_unsent_test.dart
+++ b/mobile/test/swarm/swarm_drafts_unsent_test.dart
@@ -131,6 +131,30 @@ void main() {
expect(after.threadDraft('root-1'), 'in the thread');
});
+ test('a thread reply keeps its mentions too, across a restart', () async {
+ final before = await app();
+ final c = await chat(before);
+ final t = SwarmThread(c, 'root-1');
+ addTearDown(t.dispose);
+ t.draft = 'ask';
+ t.mention('agent-lead');
+ final draft = t.draft;
+ await before.kept.flush();
+ final again = await app();
+ final after = SwarmThread(await chat(again), 'root-1');
+ addTearDown(after.dispose);
+ expect(after.draft, draft);
+ expect(after.mentions, {'agent-lead': '@River'});
+ expect(again.kept.draft(tab, 'g1', 'root-1')?.mentions.keys, [
+ 'agent-lead',
+ ]);
+ expect(
+ again.kept.draft(tab, 'g1', null),
+ isNull,
+ reason: 'the chat\'s own draft is apart',
+ );
+ });
+
test(
'goes once sent, and a kill right after brings nothing back',
() async {
@@ -309,6 +333,32 @@ void main() {
expect((await app()).kept.posts(tab, 'g1', 'root-1'), isEmpty);
});
+ test('a thread reply refused after a restart comes back with its '
+ 'mentions, which go with it again', () async {
+ final c = await chat(await app());
+ swarm.routes[commands] = lost;
+ final t = SwarmThread(c, 'root-1');
+ addTearDown(t.dispose);
+ t.draft = 'ask';
+ t.mention('agent-lead');
+ await t.send();
+ expect(t.outgoing.single.state, SwarmPostState.unconfirmed);
+
+ final after = await chat(await app());
+ final again = SwarmThread(after, 'root-1');
+ addTearDown(again.dispose);
+ swarm.routes[commands] = (_) =>
+ throw const SuperTabFailure('INVALID', 'Refused.', statusCode: 400);
+ await again.retry(again.outgoing.single);
+
+ expect(again.outgoing, isEmpty);
+ expect(again.draft, 'ask @River');
+ expect(again.mentions, {'agent-lead': '@River'});
+ swarm.routes[commands] = (_) => {'ok': true};
+ expect(await again.send(), isTrue);
+ expect(swarm.commands.last['recipientIds'], ['agent-lead']);
+ });
+
testWidgets('its row has Retry and Delete; Sending… has neither', (
tester,
) async {
diff --git a/mobile/test/swarm/swarm_jump_unread_test.dart b/mobile/test/swarm/swarm_jump_unread_test.dart
index 492b602fb..152e39766 100644
--- a/mobile/test/swarm/swarm_jump_unread_test.dart
+++ b/mobile/test/swarm/swarm_jump_unread_test.dart
@@ -48,6 +48,7 @@ void main() {
List<Map<String, dynamic>> page, {
required int mark,
bool older = false,
+ int taskMark = 40,
}) {
final fake = FakeSwarm();
fake.routes['/api/super-tabs/list'] = (_) => {
@@ -76,7 +77,7 @@ void main() {
buddyData('agent-wren', displayName: 'Wren'),
],
derived: {
- 'readMarks': {chat: mark, 'g1': 40},
+ 'readMarks': {chat: mark, 'g1': taskMark},
},
),
'members': [part(me, 1, person(me))],
@@ -283,7 +284,7 @@ void main() {
expect(pill, findsOneWidget);
});
- testWidgets('a work chat has none', (tester) async {
+ testWidgets('a work chat read through its end has none', (tester) async {
await pump(
tester,
backend(forty(), mark: 40),
@@ -291,6 +292,24 @@ void main() {
messageId: 'msg-20',
);
expect(onScreen(tester, find.text('Update 20.')), isTrue);
+ expect(line, findsNothing);
+ expect(pill, findsNothing);
+ });
+
+ testWidgets('a work chat with its line above has it too, and a tap lands '
+ 'on the line', (tester) async {
+ await pump(
+ tester,
+ backend(forty(), mark: 40, taskMark: 5),
+ conversation: 'g1',
+ messageId: 'msg-20',
+ );
+ expect(onScreen(tester, find.text('Update 20.')), isTrue);
+ expect(pill, findsOneWidget);
+
+ await tester.tap(pill);
+ await tester.pumpAndSettle();
+ expect(onScreen(tester, line), isTrue);
expect(pill, findsNothing);
});
});
diff --git a/mobile/test/swarm/swarm_leaderboard_page_test.dart b/mobile/test/swarm/swarm_leaderboard_page_test.dart
index 54ffab233..4d28eed65 100644
--- a/mobile/test/swarm/swarm_leaderboard_page_test.dart
+++ b/mobile/test/swarm/swarm_leaderboard_page_test.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter/material.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';
@@ -541,6 +542,395 @@ void main() {
}
});
+ group("a person's details, as the desktop's person card shows them", () {
+ const sheet = 'swarm-leaderboard-sheet';
+
+ /// This week's board, diego's and ken's numbers with what they are made
+ /// of: [shipped] stands for diego's pull requests when given.
+ /// [brought] is ken's machines, from a server that reads Brought.
+ FakeSwarm detailed({
+ List<Map<String, dynamic>>? shipped,
+ List<Object>? brought,
+ }) {
+ final fake = backend();
+ fake.routes[path] = (_) {
+ final data = board();
+ final people = (data['people'] as List).cast<Map<String, dynamic>>();
+ people[0]['details'] = {
+ 'shipped':
+ shipped ??
+ [
+ {
+ 'title': 'Desktop: a machine shows its agents as one count',
+ 'prUrl':
+ 'https://github.com/autonomous-ai/openharness/pull/1824',
+ 'mergedAt': 2,
+ },
+ {
+ 'title': 'Swarm digest pauses with the Swarm',
+ 'prUrl': 'file:///etc/hosts',
+ 'mergedAt': 1,
+ },
+ ],
+ 'unblocked': [
+ {
+ 'title': 'Which sign-in page ships first?',
+ 'conversationId': 'c1',
+ 'kind': 'decision',
+ 'waitedMinutes': 96,
+ },
+ ],
+ 'lent': <Object>[],
+ };
+ people[1]['details'] = {
+ 'shipped': <Object>[],
+ 'unblocked': <Object>[],
+ 'lent': [
+ {'machineName': 'MACs-Mac-Studio.local', 'busyHours': 12.5},
+ {'machineName': 'build-box', 'busyHours': 7},
+ ],
+ 'brought': ?brought,
+ };
+ return data;
+ };
+ return fake;
+ }
+
+ /// Records what the phone asks the system to open.
+ List<Object?> launches(WidgetTester tester) {
+ final opened = <Object?>[];
+ const launcher = MethodChannel('plugins.flutter.io/url_launcher');
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(launcher, (call) async {
+ if (call.method == 'launch') {
+ opened.add((call.arguments as Map)['url']);
+ }
+ return true;
+ });
+ addTearDown(() => messenger.setMockMethodCallHandler(launcher, null));
+ return opened;
+ }
+
+ testWidgets('the points, then what shipped, was unblocked and was lent, '
+ 'and saying so where nothing was', (tester) async {
+ await pump(tester, detailed());
+ await tester.pumpAndSettle();
+
+ await tester.tap(key('swarm-leaderboard-person-diego'));
+ await tester.pumpAndSettle();
+
+ expect(inside(sheet, find.text('diego')), findsOneWidget);
+ final points = inside(
+ sheet,
+ find.text('28 points this week · 20 last week'),
+ );
+ expect(points, findsOneWidget);
+ expect(tester.widget<Text>(points).style!.fontSize, AppType.captionSize);
+ double top(String section) =>
+ tester.getTopLeft(key('swarm-leaderboard-details-$section')).dy;
+ expect(tester.getTopLeft(points).dy, lessThan(top('shipped')));
+ expect(top('shipped'), lessThan(top('unblocked')));
+ expect(top('unblocked'), lessThan(top('lent')));
+ Finder within(String section, String text) =>
+ inside('swarm-leaderboard-details-$section', find.text(text));
+ // Each list's count beside its heading.
+ expect(within('shipped', 'Shipped'), findsOneWidget);
+ expect(within('shipped', '2'), findsOneWidget);
+ expect(
+ within('shipped', 'Desktop: a machine shows its agents as one count'),
+ findsOneWidget,
+ );
+ expect(within('unblocked', 'Unblocked'), findsOneWidget);
+ expect(within('unblocked', '1'), findsOneWidget);
+ expect(
+ within('unblocked', 'Which sign-in page ships first?'),
+ findsOneWidget,
+ );
+ expect(within('unblocked', 'waited 1.6 h'), findsOneWidget);
+ expect(within('lent', 'No machines lent yet'), findsOneWidget);
+ // The numbers line by line are a server's without details.
+ expect(inside(sheet, find.text('Streak')), findsNothing);
+ expect(inside(sheet, find.text('3 days shipping')), findsNothing);
+ expect(
+ tester.getSemantics(
+ find.ancestor(
+ of: within('unblocked', 'waited 1.6 h'),
+ matching: find.byType(MergeSemantics),
+ ),
+ ),
+ isSemantics(label: 'Which sign-in page ships first?\nwaited 1.6 h'),
+ );
+ expect(tester.takeException(), isNull);
+
+ await tester.tap(key('swarm-leaderboard-sheet-close'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-ken'));
+ await tester.pumpAndSettle();
+ expect(
+ inside(sheet, find.text('21 points this week · 25 last week')),
+ findsOneWidget,
+ );
+ expect(within('shipped', 'No pull requests merged yet'), findsOneWidget);
+ expect(within('unblocked', 'No questions answered yet'), findsOneWidget);
+ // The machine as it calls itself, without .local, busiest first.
+ expect(within('lent', 'MACs-Mac-Studio'), findsOneWidget);
+ expect(within('lent', '12.5 h busy'), findsOneWidget);
+ expect(within('lent', '7 h busy'), findsOneWidget);
+ expect(
+ tester.getTopLeft(within('lent', 'MACs-Mac-Studio')).dy,
+ lessThan(tester.getTopLeft(within('lent', 'build-box')).dy),
+ );
+ });
+
+ /// Ken's two machines: one with a subscription read, one not read yet.
+ List<Object> machines() => [
+ {
+ 'machineId': 'studio',
+ 'machineName': 'MACs-Mac-Studio.local',
+ 'shipped': 5,
+ 'busyHours': 31,
+ 'subscriptions': [
+ {
+ 'engine': 'claude',
+ 'usedPercent': 38,
+ 'resetsAt': DateTime.now()
+ .add(const Duration(days: 3, hours: 2))
+ .millisecondsSinceEpoch,
+ },
+ {'engine': 'codex', 'usedPercent': null, 'resetsAt': null},
+ ],
+ },
+ {
+ 'machineId': 'box',
+ 'machineName': 'build-box',
+ 'shipped': 0,
+ 'busyHours': 0,
+ 'subscriptions': <Object>[],
+ },
+ ];
+
+ testWidgets('from a server with Brought, the machines the person brought '
+ 'stand in place of Lent, each subscription\'s week under its '
+ 'machine', (tester) async {
+ await pump(tester, detailed(brought: machines()));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-ken'));
+ await tester.pumpAndSettle();
+
+ Finder within(String text) =>
+ inside('swarm-leaderboard-details-brought', find.text(text));
+ expect(key('swarm-leaderboard-details-lent'), findsNothing);
+ expect(within('Brought'), findsOneWidget);
+ expect(within('2'), findsOneWidget, reason: 'its count');
+ // Named without .local, as the desktop does.
+ expect(within('MACs-Mac-Studio'), findsOneWidget);
+ expect(within('5 shipped · 31 h for others'), findsOneWidget);
+ expect(within('Claude'), findsOneWidget);
+ expect(within('38% used · resets in 3d'), findsOneWidget);
+ expect(within('Codex'), findsOneWidget);
+ expect(within('not read yet'), findsOneWidget);
+ expect(within('build-box'), findsOneWidget);
+ expect(within('0 shipped · 0 h for others'), findsOneWidget);
+ // Each subscription under its machine, set in and quieter.
+ final studio = tester.getTopLeft(within('MACs-Mac-Studio'));
+ final claude = tester.getTopLeft(within('Claude'));
+ final codex = tester.getTopLeft(within('Codex'));
+ final box = tester.getTopLeft(within('build-box'));
+ expect(studio.dy, lessThan(claude.dy));
+ expect(claude.dy, lessThan(codex.dy));
+ expect(codex.dy, lessThan(box.dy));
+ expect(claude.dx, greaterThan(studio.dx));
+ expect(
+ tester.widget<Text>(within('Claude')).style!.color,
+ AppPalette.textSecondary,
+ );
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('from a server with Brought and nothing brought, it says so', (
+ tester,
+ ) async {
+ await pump(tester, detailed(brought: <Object>[]));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-ken'));
+ await tester.pumpAndSettle();
+
+ expect(
+ inside(
+ 'swarm-leaderboard-details-brought',
+ find.text('No machines brought yet'),
+ ),
+ findsOneWidget,
+ );
+ expect(key('swarm-leaderboard-details-lent'), findsNothing);
+ });
+
+ testWidgets('a 320pt phone with large text fits a brought machine\'s '
+ 'lines', (tester) async {
+ tester.view.devicePixelRatio = 2;
+ tester.view.physicalSize = const Size(320 * 2, 568 * 2);
+ addTearDown(tester.view.reset);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.3;
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await pump(tester, detailed(brought: machines()));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-ken'));
+ await tester.pumpAndSettle();
+
+ expect(tester.takeException(), isNull);
+ final sheet = tester.getRect(key('swarm-leaderboard-details'));
+ for (final text in [
+ '5 shipped · 31 h for others',
+ '38% used · resets in 3d',
+ ]) {
+ final line = tester.getRect(
+ inside('swarm-leaderboard-details-brought', find.text(text)),
+ );
+ expect(line.right, lessThanOrEqualTo(sheet.right), reason: text);
+ }
+ // The machine's name keeps its room beside its measure.
+ final name = tester.getRect(
+ inside(
+ 'swarm-leaderboard-details-brought',
+ find.text('MACs-Mac-Studio'),
+ ),
+ );
+ expect(name.width, greaterThan(0));
+ expect(
+ name.right,
+ lessThan(
+ tester
+ .getRect(
+ inside(
+ 'swarm-leaderboard-details-brought',
+ find.text('5 shipped · 31 h for others'),
+ ),
+ )
+ .left,
+ ),
+ );
+ });
+
+ testWidgets('a pull request opens in the in-app browser; one without a '
+ 'web link is text', (tester) async {
+ final opened = launches(tester);
+ await pump(tester, detailed());
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-diego'));
+ await tester.pumpAndSettle();
+
+ const web = 'Desktop: a machine shows its agents as one count';
+ const file = 'Swarm digest pauses with the Swarm';
+ expect(
+ tester.widget<Text>(find.text(web)).style!.color,
+ AppPalette.swarmAccent,
+ );
+ expect(
+ tester.widget<Text>(find.text(file)).style!.color,
+ AppPalette.textPrimary,
+ );
+ expect(
+ tester
+ .getSize(
+ find.ancestor(of: find.text(web), matching: find.byType(InkWell)),
+ )
+ .height,
+ greaterThanOrEqualTo(minTouchTarget),
+ reason: 'a thumb',
+ );
+ expect(
+ tester.getSemantics(
+ find.ancestor(of: find.text(web), matching: find.byType(InkWell)),
+ ),
+ isSemantics(label: web, isLink: true, hasTapAction: true),
+ );
+
+ await tester.tap(find.text(web));
+ await tester.pumpAndSettle();
+ expect(opened, [
+ 'https://github.com/autonomous-ai/openharness/pull/1824',
+ ]);
+ await tester.tap(find.text(file));
+ await tester.pumpAndSettle();
+ expect(opened, hasLength(1), reason: 'only a web page opens');
+ expect(
+ find.ancestor(of: find.text(file), matching: find.byType(InkWell)),
+ findsNothing,
+ );
+ // The sheet stays: nothing behind it was tapped.
+ expect(key(sheet), findsOneWidget);
+ });
+
+ testWidgets('a long list shows its newest five, Show all the rest, and '
+ 'scrolls inside the sheet on a small phone', (tester) async {
+ await tester.binding.setSurfaceSize(const Size(375, 667));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await pump(
+ tester,
+ detailed(
+ shipped: [
+ for (var i = 0; i < 20; i++)
+ {'title': 'Pull request $i', 'prUrl': 'https://x.dev/pull/$i'},
+ ],
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-diego'));
+ await tester.pumpAndSettle();
+
+ expect(tester.takeException(), isNull);
+ expect(
+ inside('swarm-leaderboard-details-shipped', find.text('20')),
+ findsOneWidget,
+ );
+ expect(find.text('Pull request 4'), findsOneWidget);
+ expect(find.text('Pull request 5'), findsNothing);
+ // Never over the status bar.
+ expect(tester.getSize(key(sheet)).height, lessThanOrEqualTo(667 * .82));
+
+ await tester.tap(find.text('Show all 20'));
+ await tester.pumpAndSettle();
+ expect(find.text('Show all 20'), findsNothing);
+ final scroll = find.descendant(
+ of: key('swarm-leaderboard-details'),
+ matching: find.byType(Scrollable),
+ );
+ await tester.scrollUntilVisible(
+ find.text('No machines lent yet'),
+ 100,
+ scrollable: scroll.first,
+ );
+ expect(find.text('Pull request 19'), findsOneWidget);
+ expect(find.text('No machines lent yet'), findsOneWidget);
+ // The sheet's title stays above what scrolls.
+ expect(inside(sheet, find.text('diego')), findsOneWidget);
+ expect(
+ tester.getBottomLeft(inside(sheet, find.text('diego'))).dy,
+ lessThanOrEqualTo(
+ tester.getTopLeft(key('swarm-leaderboard-details')).dy,
+ ),
+ );
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('five or fewer have no Show all', (tester) async {
+ await pump(
+ tester,
+ detailed(
+ shipped: [
+ for (var i = 0; i < 5; i++)
+ {'title': 'Pull request $i', 'prUrl': 'https://x.dev/pull/$i'},
+ ],
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-leaderboard-person-diego'));
+ await tester.pumpAndSettle();
+ expect(find.text('Pull request 4'), findsOneWidget);
+ expect(find.textContaining('Show all'), findsNothing);
+ });
+ });
+
group("a person's week closes when what opened it is lost", () {
const sheet = 'swarm-leaderboard-sheet';
diff --git a/mobile/test/swarm/swarm_leaderboard_shots_test.dart b/mobile/test/swarm/swarm_leaderboard_shots_test.dart
index 2350c5b8c..4788808fc 100644
--- a/mobile/test/swarm/swarm_leaderboard_shots_test.dart
+++ b/mobile/test/swarm/swarm_leaderboard_shots_test.dart
@@ -33,6 +33,13 @@ void main() {
for (final family in ['.AppleSystemUIFont', 'Roboto']) {
await (FontLoader(family)..addFont(Future.value(sf))).load();
}
+ // The title's monospace, as the other shots tests load it.
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
final manifest =
jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
for (final entry in manifest.cast<Map<String, dynamic>>()) {
@@ -77,6 +84,62 @@ void main() {
),
'displayName': 'Diego',
'prevWeekPoints': 20,
+ 'details': {
+ 'shipped': [
+ for (final (i, title) in [
+ 'Phone: the leaderboard shows what each number is made of',
+ 'Desktop: a machine shows its agents as one count',
+ 'Swarm digest pauses with the Swarm',
+ 'CLI: resume keeps the last model',
+ 'Backend: the board reads only what changed',
+ 'Phone: Undo after answering a decision',
+ 'Desktop: Models list leaves out unnamed records',
+ 'Daemon: idle timers stop while nothing changed',
+ ].indexed)
+ {
+ 'title': title,
+ 'prUrl': 'https://github.com/o/r/pull/${2800 - i}',
+ },
+ ],
+ 'unblocked': [
+ {
+ 'title': 'Which sign-in page ships first?',
+ 'conversationId': 'c1',
+ 'kind': 'decision',
+ 'waitedMinutes': 96,
+ },
+ ],
+ 'lent': [
+ {'machineName': 'MACs-Mac-Studio.local', 'busyHours': 31.5},
+ {'machineName': 'build-box', 'busyHours': 8.5},
+ ],
+ // A server that reads Brought shows it in place of Lent.
+ 'brought': [
+ {
+ 'machineId': 'studio',
+ 'machineName': 'MACs-Mac-Studio.local',
+ 'shipped': 5,
+ 'busyHours': 31.5,
+ 'subscriptions': [
+ {
+ 'engine': 'claude',
+ 'usedPercent': 38,
+ 'resetsAt': DateTime.now()
+ .add(const Duration(days: 3, hours: 2))
+ .millisecondsSinceEpoch,
+ },
+ {'engine': 'codex', 'usedPercent': null, 'resetsAt': null},
+ ],
+ },
+ {
+ 'machineId': 'box',
+ 'machineName': 'build-box',
+ 'shipped': 0,
+ 'busyHours': 8.5,
+ 'subscriptions': <Object>[],
+ },
+ ],
+ },
},
{
...scoreData('ken', points: 21, rank: 2, shipped: 3, unblocked: 4),
@@ -142,6 +205,36 @@ void main() {
await File('$shots/phone-leaderboard-${brightness.name}.png')
.writeAsBytes(png!.buffer.asUint8List());
});
+ // A person's week: their points and what the numbers are made of.
+ await tester.tap(
+ find.byKey(const ValueKey('swarm-leaderboard-person-diego')),
+ );
+ await tester.pumpAndSettle();
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/phone-leaderboard-person-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ });
+ // Scrolled to its end: what the machines they brought did.
+ await tester.drag(
+ find.byKey(const ValueKey('swarm-leaderboard-details')),
+ const Offset(0, -600),
+ );
+ await tester.pumpAndSettle();
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File(
+ '$shots/phone-leaderboard-person-brought-${brightness.name}.png',
+ ).writeAsBytes(png!.buffer.asUint8List());
+ });
await tester.pumpWidget(const SizedBox());
host.dispose();
}
diff --git a/mobile/test/swarm/swarm_leaderboard_test.dart b/mobile/test/swarm/swarm_leaderboard_test.dart
index debd95747..e87ce2df3 100644
--- a/mobile/test/swarm/swarm_leaderboard_test.dart
+++ b/mobile/test/swarm/swarm_leaderboard_test.dart
@@ -55,6 +55,110 @@ void main() {
expect(kim.medianAskToShipMs, isNull);
expect(kim.medianAnswerMs, isNull);
expect(kim.streakDays, 0);
+ expect(kim.details, isNull, reason: 'a server before details');
+ });
+
+ test("keeps a person's details in the order the backend sends", () {
+ final details = SwarmScore.fromJson({
+ ...scoreData('a', points: 9, rank: 1),
+ 'details': {
+ 'shipped': [
+ {
+ 'title': 'Phone: the board shows details',
+ 'prUrl': 'https://github.com/o/r/pull/2',
+ 'mergedAt': 2,
+ },
+ {'title': 'Desktop: one count', 'prUrl': 'http://x.dev/pull/1'},
+ ],
+ 'unblocked': [
+ {
+ 'title': 'Which sign-in page ships first?',
+ 'conversationId': 'c1',
+ 'kind': 'decision',
+ 'waitedMinutes': 96,
+ },
+ ],
+ 'lent': [
+ {'machineName': 'MACs-Mac-Studio.local', 'busyHours': 12.5},
+ {'machineName': 'build-box', 'busyHours': 7},
+ ],
+ },
+ }).details!;
+
+ expect(details.shipped.map((s) => s.title), [
+ 'Phone: the board shows details',
+ 'Desktop: one count',
+ ]);
+ expect(
+ details.shipped.first.link,
+ Uri.parse('https://github.com/o/r/pull/2'),
+ );
+ expect(details.shipped.last.link, Uri.parse('http://x.dev/pull/1'));
+ expect(details.unblocked.single.title, 'Which sign-in page ships first?');
+ expect(details.unblocked.single.waitedMinutes, 96);
+ // The machine as it calls itself, without .local; a whole number of
+ // hours reads as one.
+ expect(details.lent.map((l) => (l.machineName, l.busyHours)), [
+ ('MACs-Mac-Studio', 12.5),
+ ('build-box', 7.0),
+ ]);
+ });
+
+ test('a detail without a title or a web link, or of another type, is '
+ 'left out or kept as text', () {
+ final details = SwarmScore.fromJson({
+ ...scoreData('a', points: 1, rank: 1),
+ 'details': {
+ 'shipped': [
+ {'title': '', 'prUrl': 'https://x.dev/pull/1'},
+ {'prUrl': 'https://x.dev/pull/2'},
+ {'title': 'A file', 'prUrl': 'file:///etc/hosts'},
+ {'title': 'A script', 'prUrl': 'javascript:alert(1)'},
+ {'title': 'An app', 'prUrl': 'x-harness://open'},
+ {'title': 'No host', 'prUrl': 'https:pull/3'},
+ {'title': 'No link'},
+ 'not a map',
+ ],
+ 'unblocked': [
+ {'title': 'Asked', 'waitedMinutes': 'long'},
+ {'waitedMinutes': 4},
+ ],
+ 'lent': [
+ {'machineName': '', 'busyHours': 2},
+ {'machineName': '.local', 'busyHours': 'many'},
+ ],
+ },
+ }).details!;
+
+ expect(details.shipped.map((s) => (s.title, s.link)), [
+ ('A file', null),
+ ('A script', null),
+ ('An app', null),
+ ('No host', null),
+ ('No link', null),
+ ]);
+ expect(details.unblocked.map((u) => (u.title, u.waitedMinutes)), [
+ ('Asked', 0),
+ ]);
+ // A name that is only the suffix stays whole.
+ expect(details.lent.map((l) => (l.machineName, l.busyHours)), [
+ ('.local', 0.0),
+ ]);
+
+ final empty = SwarmScore.fromJson({
+ ...scoreData('b', points: 0, rank: 2),
+ 'details': {'shipped': 'none', 'lent': null},
+ }).details!;
+ expect(empty.shipped, isEmpty);
+ expect(empty.unblocked, isEmpty);
+ expect(empty.lent, isEmpty);
+ expect(
+ SwarmScore.fromJson({
+ ...scoreData('c', points: 0, rank: 3),
+ 'details': ['not', 'a', 'map'],
+ }).details,
+ isNull,
+ );
});
});
@@ -127,6 +231,33 @@ void main() {
expect(swarmDuration(3 * 3600000 + 6 * 60000), '3.1 h');
});
+ test("a person's points with the time before beside them", () {
+ SwarmScore score(int points, int? before, {String? period}) =>
+ SwarmScore.fromJson({
+ ...scoreData('a', points: points, rank: 1),
+ 'prevWeekPoints': ?before,
+ }, period: period);
+ expect(
+ swarmPersonPoints(score(21, 15, period: '7d')),
+ '21 points in the last 7 days · 15 the 7 days before',
+ );
+ expect(swarmPersonPoints(score(1, 0)), '1 point this week · 0 last week');
+ // Last 30d has no comparison.
+ expect(
+ swarmPersonPoints(score(30, null, period: '30d')),
+ '30 points in the last 30 days',
+ );
+ });
+
+ test('how long an answer waited and a machine was busy', () {
+ expect(swarmWaited(6), 'waited 6 min');
+ expect(swarmWaited(96), 'waited 1.6 h');
+ expect(swarmWaited(0), 'waited 0 min');
+ expect(swarmBusy(12.5), '12.5 h busy');
+ expect(swarmBusy(7), '7 h busy');
+ expect(swarmBusy(0.1), '6 min busy');
+ });
+
test('lent time in whole agent-hours', () {
expect(swarmHours(0), 0);
expect(swarmHours(40 * 3600000), 40);
@@ -405,10 +536,8 @@ void main() {
'details': {'brought': ?brought},
});
- test('puts a line per machine in place of Lent: what shipped, hours for others and each subscription\'s week', () {
- final resets = now
- .add(const Duration(days: 3, hours: 2))
- .millisecondsSinceEpoch;
+ test('the week lines keep Lent and never Brought: Brought comes only '
+ 'with the details, and the details sheet shows it', () {
final lines = swarmPersonWeek(
score([
{
@@ -416,40 +545,72 @@ void main() {
'machineName': 'Mac Studio',
'shipped': 5,
'busyHours': 31,
- 'subscriptions': [
- {'engine': 'claude', 'usedPercent': 38, 'resetsAt': resets},
- {'engine': 'codex', 'usedPercent': null, 'resetsAt': null},
- ],
- },
- {
- 'machineId': 'mbp',
- 'machineName': 'MacBook Pro',
- 'shipped': 0,
- 'busyHours': 0,
'subscriptions': <Object>[],
},
]),
- now: now,
- );
- expect(
- lines,
- contains((
- 'Mac Studio',
- '5 shipped · 31 h for others\nClaude 38% used, resets in 3d\nCodex not read yet',
- )),
);
- expect(lines, contains(('MacBook Pro', '0 shipped · 0 h for others')));
- expect(lines.map((l) => l.$1), isNot(contains('Lent')));
+ expect(lines.map((l) => l.$1), contains('Lent'));
+ expect(lines.map((l) => l.$1), isNot(contains('Mac Studio')));
+ expect(lines.map((l) => l.$1), isNot(contains('Brought')));
+ });
+
+ test("a subscription's week in the desktop's words: used · resets in", () {
+ final resets = now
+ .add(const Duration(days: 3, hours: 2))
+ .millisecondsSinceEpoch;
+ final read = score([
+ {
+ 'machineId': 'studio',
+ 'machineName': 'Mac Studio',
+ 'shipped': 5,
+ 'busyHours': 31,
+ 'subscriptions': [
+ {'engine': 'claude', 'usedPercent': 38, 'resetsAt': resets},
+ {'engine': 'codex', 'usedPercent': 12, 'resetsAt': null},
+ {'engine': 'codex', 'usedPercent': null, 'resetsAt': null},
+ ],
+ },
+ ]);
+ expect(swarmBroughtSubscriptions(read.brought!.single, now), [
+ ('Claude', '38% used · resets in 3d'),
+ ('Codex', '12% used'),
+ ('Codex', 'not read yet'),
+ ]);
});
- test('says so when the person brought nothing', () {
- final lines = swarmPersonWeek(score(<Object>[]), now: now);
- expect(lines, contains(('Brought', 'No machines brought yet')));
- expect(lines.map((l) => l.$1), isNot(contains('Lent')));
+ test('names a machine without .local and leaves out one with no name, '
+ 'with the details\' lists read beside it', () {
+ final read = SwarmScore.fromJson({
+ 'personId': 'ken',
+ 'points': 13,
+ 'rank': 1,
+ 'shipped': {'count': 1},
+ 'unblocked': {'count': 0, 'agentMs': 0},
+ 'lent': {'machines': 1, 'agentMs': 0},
+ 'streakDays': 0,
+ 'details': {
+ 'shipped': [
+ {'title': 'Ship it', 'prUrl': 'https://example.com/pr/1'},
+ ],
+ 'unblocked': <Object>[],
+ 'lent': <Object>[],
+ 'brought': [
+ {'machineName': 'MACs-Mac-Studio.local', 'shipped': 2},
+ {'machineName': '', 'shipped': 1},
+ ],
+ },
+ });
+ expect(read.brought!.map((m) => m.machineName), ['MACs-Mac-Studio']);
+ expect(read.details!.shipped.single.title, 'Ship it');
+ expect(
+ swarmBroughtSummary(read.brought!.single),
+ '2 shipped · 0 h for others',
+ );
+ expect(swarmBroughtSubscriptions(read.brought!.single, now), isEmpty);
});
test('keeps Lent from a server before Brought', () {
- final lines = swarmPersonWeek(score(null), now: now);
+ final lines = swarmPersonWeek(score(null));
expect(lines.map((l) => l.$1), contains('Lent'));
});
});
diff --git a/mobile/test/swarm/swarm_project_c_test.dart b/mobile/test/swarm/swarm_project_c_test.dart
index 05bed4dd4..d5a031f33 100644
--- a/mobile/test/swarm/swarm_project_c_test.dart
+++ b/mobile/test/swarm/swarm_project_c_test.dart
@@ -1891,7 +1891,8 @@ void main() {
expect(key('swarm-jump-latest'), findsNothing);
});
- testWidgets("direction B's chat has none", (tester) async {
+ // Every chat has both, as on Desktop: direction B's, opened by none, too.
+ testWidgets("direction B's chat has it too", (tester) async {
await pump(
tester,
chat([for (var i = 1; i <= 4; i++) said(i)], mark: 2),
@@ -1903,10 +1904,13 @@ void main() {
);
expect(find.text('Update 4.'), findsOneWidget);
- expect(line, findsNothing);
+ expect(line, findsOneWidget);
+ final y = tester.getTopLeft(line).dy;
+ expect(tester.getTopLeft(find.text('Update 2.')).dy, lessThan(y));
+ expect(tester.getTopLeft(find.text('Update 3.')).dy, greaterThan(y));
});
- testWidgets("direction B's chat offers no Jump to latest", (tester) async {
+ testWidgets("direction B's chat offers Jump to latest too", (tester) async {
await pump(
tester,
chat([for (var i = 1; i <= 40; i++) said(i)], mark: 40),
@@ -1920,7 +1924,7 @@ void main() {
await tester.pumpAndSettle();
expect(onScreen(tester, find.text('Update 40.')), isFalse);
- expect(key('swarm-jump-latest'), findsNothing);
+ expect(key('swarm-jump-latest'), findsOneWidget);
});
});
diff --git a/mobile/test/swarm/swarm_rename_shots_test.dart b/mobile/test/swarm/swarm_rename_shots_test.dart
new file mode 100644
index 000000000..883d8c39c
--- /dev/null
+++ b/mobile/test/swarm/swarm_rename_shots_test.dart
@@ -0,0 +1,139 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_page.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of Rename a Swarm on Swarm Home, 390 points wide in
+/// both phone themes, from made-up data, to the folder `SWARM_RENAME_SHOTS`
+/// names: the switcher with each Swarm's ⋮, the Swarm's menu, and the
+/// Rename dialog.
+final shots = Platform.environment['SWARM_RENAME_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('Rename a Swarm, in both phone themes', (tester) async {
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ await tester.binding.setSurfaceSize(const Size(390, 640));
+ for (final state in ['switcher', 'menu', 'dialog']) {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'OpenHarness', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(head: headData(name: 'OpenHarness')),
+ 'members': [part(me, 1, person(me, role: 'owner'))],
+ };
+ 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>[],
+ };
+ final host = SwarmHost(
+ accountId: () => me,
+ account: ValueNotifier<String?>(me),
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ onGenerateRoute: (_) =>
+ CupertinoPageRoute<void>(builder: (_) => const SwarmPage()),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('swarm-title-button')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('swarm-switch-menu-$tab')), findsOne);
+ if (state != 'switcher') {
+ await tester.tap(
+ find.byKey(const ValueKey('swarm-switch-menu-$tab')),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Rename Swarm'), findsOneWidget);
+ if (state == 'dialog') {
+ await tester.tap(find.text('Rename Swarm'));
+ await tester.pumpAndSettle();
+ expect(find.text('Swarm name'), findsOneWidget);
+ // The caret's blink is not in the picture.
+ FocusManager.instance.primaryFocus?.unfocus();
+ await tester.pumpAndSettle();
+ }
+ }
+ expect(tester.takeException(), isNull);
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File(
+ '$shots/phone-swarm-rename-$state-${brightness.name}-390.png',
+ ).writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ await tester.pump(const Duration(minutes: 1));
+ }
+ }
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_rename_test.dart b/mobile/test/swarm/swarm_rename_test.dart
new file mode 100644
index 000000000..f058431a3
--- /dev/null
+++ b/mobile/test/swarm/swarm_rename_test.dart
@@ -0,0 +1,578 @@
+import 'dart:async';
+
+import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/swarm/swarm_inbox.dart';
+import 'package:harness_mobile/swarm/swarm_page.dart';
+import 'package:harness_mobile/swarm/swarm_rename.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_style.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Rename a Swarm on the phone (Tony's task 17), as the desktop's Rename Tab
+/// does it with `tab.rename`: from its row's ⋮ in Home's switcher (or held), for
+/// someone who may write there; the new name shows at once, and the old one
+/// comes back when the server does not keep it.
+void main() {
+ /// The Swarm's name as the server has it.
+ late String name;
+
+ /// The reader's role in the Swarm.
+ late String role;
+
+ /// The next command waits for this, while set.
+ Completer<void>? wait;
+
+ /// The next command throws this instead of answering, while set.
+ Object? refuse;
+
+ var version = 1;
+
+ FakeSwarm backend() {
+ name = 'Phone Swarm';
+ version = 1;
+ wait = null;
+ refuse = null;
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': name, 'ownerId': me, 'lastChangedAt': version},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ head: headData(name: name),
+ lastChangedAt: version,
+ ),
+ 'members': [part(me, 1, person(me, role: role))],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(cursor: 'c$version', lastChangedAt: version),
+ 'head': part('head', version, headData(name: name)),
+ };
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/commands'] = (body) async {
+ final command = body!['command'] as Map<String, dynamic>;
+ if (wait case final waiting?) await waiting.future;
+ if (refuse case final failure?) throw failure;
+ if (command['type'] == 'tab.rename') {
+ name = command['name'] as String;
+ version++;
+ }
+ return {'ok': true};
+ };
+ return fake;
+ }
+
+ List<Map<String, dynamic>> renames(FakeSwarm fake) => [
+ for (final command in fake.commands)
+ if (command['type'] == 'tab.rename') command,
+ ];
+
+ group('SwarmInbox.rename', () {
+ setUp(() => role = 'owner');
+
+ Future<SwarmInbox> read(FakeSwarm fake) async {
+ final inbox = SwarmInbox(accountId: me, request: fake.request);
+ addTearDown(inbox.dispose);
+ await inbox.refresh();
+ expect(inbox.reader(tab)?.snapshot, isNotNull);
+ return inbox;
+ }
+
+ String listed(SwarmInbox inbox) => inbox.swarms.single.name;
+
+ test('shows the name at once, sends it trimmed as tab.rename, and keeps '
+ 'it once the server has', () async {
+ final fake = backend();
+ final inbox = await read(fake);
+ wait = Completer<void>();
+
+ final renaming = inbox.rename(tab, ' Lamp ');
+ expect(listed(inbox), 'Lamp', reason: 'before the server answers');
+
+ wait!.complete();
+ expect(await renaming, isNull);
+ expect(listed(inbox), 'Lamp');
+ expect(inbox.reader(tab)!.snapshot!.name, 'Lamp', reason: 'read again');
+ expect(renames(fake), [
+ {'type': 'tab.rename', 'name': 'Lamp'},
+ ]);
+ });
+
+ test('a list read while it is on its way does not bring the old name '
+ 'back', () async {
+ final fake = backend();
+ final inbox = await read(fake);
+ wait = Completer<void>();
+
+ final renaming = inbox.rename(tab, 'Lamp');
+ await inbox.refresh();
+ expect(listed(inbox), 'Lamp', reason: 'the list still says the old');
+
+ wait!.complete();
+ expect(await renaming, isNull);
+ expect(listed(inbox), 'Lamp');
+ });
+
+ test("a refusal brings the old name back, in the server's words", () async {
+ final fake = backend();
+ final inbox = await read(fake);
+ refuse = const SuperTabFailure(
+ 'READ_ONLY',
+ 'This Super Tab is read-only for you.',
+ statusCode: 403,
+ );
+
+ expect(
+ await inbox.rename(tab, 'Lamp'),
+ 'This Super Tab is read-only for you.',
+ );
+ expect(listed(inbox), 'Phone Swarm');
+ });
+
+ test("a call lost on the way says the desktop's words", () async {
+ final fake = backend();
+ final inbox = await read(fake);
+ refuse = StateError('socket closed');
+
+ expect(await inbox.rename(tab, 'Lamp'), 'Could not rename the Swarm.');
+ expect(listed(inbox), 'Phone Swarm');
+ });
+
+ test(
+ 'a newer rename settles it: an older refusal leaves the newer name',
+ () async {
+ final fake = backend();
+ final inbox = await read(fake);
+ final first = Completer<void>();
+ wait = first;
+ refuse = const SuperTabFailure('BUSY', 'Try again.');
+ final older = inbox.rename(tab, 'Lamp');
+ // The newer one is answered at once, and kept.
+ wait = null;
+ refuse = null;
+ expect(await inbox.rename(tab, 'Spaceship'), isNull);
+
+ refuse = const SuperTabFailure('BUSY', 'Try again.');
+ first.complete();
+ expect(await older, 'Try again.');
+ expect(listed(inbox), 'Spaceship');
+ },
+ );
+
+ test('the name it has, or none, sends nothing', () async {
+ final fake = backend();
+ final inbox = await read(fake);
+
+ expect(await inbox.rename(tab, ' Phone Swarm '), isNull);
+ expect(await inbox.rename(tab, ' '), 'Name cannot be empty');
+ expect(renames(fake), isEmpty);
+ expect(listed(inbox), 'Phone Swarm');
+ });
+
+ test('a viewer is told, and nothing is sent or shown', () async {
+ role = 'viewer';
+ final fake = backend();
+ final inbox = await read(fake);
+
+ expect(swarmMayRename(inbox, tab), isFalse);
+ expect(swarmHasMenu(inbox, tab), isFalse, reason: 'nothing in it');
+ expect(await inbox.rename(tab, 'Lamp'), 'You can’t rename this Swarm.');
+ expect(renames(fake), isEmpty);
+ expect(listed(inbox), 'Phone Swarm');
+ });
+
+ test('a collaborator may, as on the desktop', () async {
+ role = 'collaborator';
+ final inbox = await read(backend());
+ expect(swarmMayRename(inbox, tab), isTrue);
+ expect(swarmHasMenu(inbox, tab), isTrue);
+ });
+
+ test('a refusal once the Swarm was lost says nothing', () async {
+ final fake = backend();
+ final inbox = await read(fake);
+ wait = Completer<void>();
+ refuse = const SuperTabFailure('NOT_FOUND', 'Gone.', statusCode: 404);
+
+ final renaming = inbox.rename(tab, 'Lamp');
+ inbox.reader(tab)!.revoke();
+ wait!.complete();
+ expect(await renaming, isNull);
+ });
+
+ test('a Swarm it does not list is not renamed', () async {
+ final fake = backend();
+ final inbox = await read(fake);
+
+ expect(await inbox.rename('tab-other', 'Lamp'), isNull);
+ expect(swarmMayRename(inbox, 'tab-other'), isFalse);
+ expect(swarmHasMenu(inbox, 'tab-other'), isFalse);
+ expect(renames(fake), isEmpty);
+ });
+ });
+
+ test("the desktop's checks: not empty, at most 80 characters", () {
+ expect(swarmNameProblem('Lamp'), isNull);
+ expect(swarmNameProblem(' '), 'Name cannot be empty');
+ expect(swarmNameProblem('x' * 80), isNull);
+ expect(swarmNameProblem(' ${'x' * 80} '), isNull, reason: 'trimmed');
+ expect(swarmNameProblem('x' * 81), 'Use at most 80 characters.');
+ // Characters, not code units: an emoji with its skin tone is one.
+ expect(swarmNameProblem('👍🏽' * 80), isNull);
+ expect(swarmNameProblem('👍🏽' * 81), 'Use at most 80 characters.');
+ });
+
+ group('on the phone', () {
+ late FakeSwarm fake;
+ late SwarmHost host;
+
+ /// Swarm Home on an iPhone's screen (390 × 844), as `swarm_home_test`
+ /// pumps it.
+ Future<void> pump(WidgetTester tester, {String as = 'owner'}) async {
+ role = as;
+ fake = backend();
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ final account = ValueNotifier<String?>(me);
+ host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) =>
+ SwarmScope(notifier: host, child: child!),
+ onGenerateRoute: (_) =>
+ CupertinoPageRoute<void>(builder: (_) => const SwarmPage()),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+ Finder title(String text) => find.descendant(
+ of: key('swarm-title-button'),
+ matching: find.text(text),
+ );
+
+ /// Holds the Swarm's row in the switcher, from Home's title.
+ Future<void> hold(WidgetTester tester) async {
+ await tester.tap(key('swarm-title-button'));
+ await tester.pumpAndSettle();
+ await tester.longPress(key('swarm-switch-$tab'));
+ await tester.pumpAndSettle();
+ }
+
+ /// Rename Swarm, from the Swarm's menu.
+ Future<void> open(WidgetTester tester) async {
+ await hold(tester);
+ await tester.tap(find.text('Rename Swarm'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-rename-name'), findsOneWidget);
+ }
+
+ /// Half a second of frames, for a screen that cannot settle.
+ Future<void> frames(WidgetTester tester) async {
+ for (var i = 0; i < 5; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ String field(WidgetTester tester) =>
+ tester.widget<TextField>(key('swarm-rename-name')).controller!.text;
+
+ VoidCallback? save(WidgetTester tester) =>
+ tester.widget<SwarmButton>(key('swarm-rename-save')).onPressed;
+
+ testWidgets("holding the Swarm's row closes the switcher for its menu, "
+ 'Rename Swarm under its name', (tester) async {
+ await pump(tester);
+ await hold(tester);
+
+ expect(key('swarm-switch-join'), findsNothing, reason: 'it closed');
+ expect(find.text('Phone Swarm'), findsWidgets);
+ expect(find.text('Rename Swarm'), findsOneWidget);
+ });
+
+ testWidgets("the Swarm's row shows a ⋮ that opens its menu, as a "
+ "chat's ⋮ does", (tester) async {
+ await pump(tester);
+ await tester.tap(key('swarm-title-button'));
+ await tester.pumpAndSettle();
+
+ final dots = key('swarm-switch-menu-$tab');
+ expect(dots, findsOneWidget);
+ expect(
+ find.descendant(of: key('swarm-switch-$tab'), matching: dots),
+ findsOneWidget,
+ reason: "on the Swarm's own row",
+ );
+ expect(find.bySemanticsLabel('Swarm options'), findsOneWidget);
+ final size = tester.getSize(dots);
+ expect(size.width, greaterThanOrEqualTo(44));
+ expect(size.height, greaterThanOrEqualTo(44));
+
+ await tester.tap(dots);
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-switch-join'), findsNothing, reason: 'it closed');
+ expect(title('Phone Swarm'), findsOneWidget, reason: 'not picked anew');
+ expect(find.text('Rename Swarm'), findsOneWidget);
+ await tester.tap(find.text('Rename Swarm'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-rename-name'), findsOneWidget);
+ });
+
+ testWidgets('a viewer sees no ⋮ on the row', (tester) async {
+ await pump(tester, as: 'viewer');
+ await tester.tap(key('swarm-title-button'));
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-switch-$tab'), findsOneWidget);
+ expect(key('swarm-switch-menu-$tab'), findsNothing);
+ });
+
+ testWidgets("the name field is labelled 'Swarm name', for a screen "
+ 'reader too', (tester) async {
+ await pump(tester);
+ await open(tester);
+
+ final field = tester.widget<TextField>(key('swarm-rename-name'));
+ expect(field.decoration?.labelText, 'Swarm name');
+ expect(find.bySemanticsLabel(RegExp('Swarm name')), findsOneWidget);
+ });
+
+ testWidgets('a viewer holds a slow tap: no menu', (tester) async {
+ await pump(tester, as: 'viewer');
+ await hold(tester);
+
+ expect(find.text('Rename Swarm'), findsNothing);
+ expect(key('swarm-rename-name'), findsNothing);
+ expect(title('Phone Swarm'), findsOneWidget);
+ });
+
+ testWidgets('opens on the name, all of it selected, as the desktop does', (
+ tester,
+ ) async {
+ await pump(tester);
+ await open(tester);
+
+ expect(find.text('Rename Swarm'), findsOneWidget);
+ final controller = tester
+ .widget<TextField>(key('swarm-rename-name'))
+ .controller!;
+ expect(controller.text, 'Phone Swarm');
+ expect(
+ controller.selection,
+ const TextSelection(baseOffset: 0, extentOffset: 11),
+ );
+ });
+
+ testWidgets('Save closes at once and Home says the new name before the '
+ 'server answers; it stays once it has', (tester) async {
+ await pump(tester);
+ await open(tester);
+ wait = Completer<void>();
+
+ await tester.enterText(key('swarm-rename-name'), ' Lamp ');
+ await tester.pump();
+ await tester.tap(key('swarm-rename-save'));
+ await tester.pumpAndSettle();
+
+ expect(key('swarm-rename-name'), findsNothing, reason: 'it closed');
+ expect(title('Lamp'), findsOneWidget);
+ expect(renames(fake), [
+ {'type': 'tab.rename', 'name': 'Lamp'},
+ ]);
+
+ wait!.complete();
+ await tester.pumpAndSettle();
+ expect(title('Lamp'), findsOneWidget);
+ expect(key('swarm-rename-failed'), findsNothing);
+
+ // The switcher says it too.
+ await tester.tap(key('swarm-title-button'));
+ await tester.pumpAndSettle();
+ expect(
+ find.descendant(
+ of: key('swarm-switch-$tab'),
+ matching: find.text('Lamp'),
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets("a refusal brings the old name back and says why at the "
+ 'foot of Home', (tester) async {
+ await pump(tester);
+ await open(tester);
+ wait = Completer<void>();
+ refuse = const SuperTabFailure(
+ 'READ_ONLY',
+ 'This Super Tab is read-only for you.',
+ statusCode: 403,
+ );
+
+ await tester.enterText(key('swarm-rename-name'), 'Lamp');
+ await tester.pump();
+ await tester.tap(key('swarm-rename-save'));
+ await tester.pumpAndSettle();
+ expect(title('Lamp'), findsOneWidget, reason: 'at once');
+
+ wait!.complete();
+ await tester.pumpAndSettle();
+ expect(title('Phone Swarm'), findsOneWidget);
+ expect(
+ find.descendant(
+ of: key('swarm-rename-failed'),
+ matching: find.text('This Super Tab is read-only for you.'),
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a call lost on the way: the old name, and the desktop\'s '
+ 'words', (tester) async {
+ await pump(tester);
+ await open(tester);
+ refuse = StateError('socket closed');
+
+ await tester.enterText(key('swarm-rename-name'), 'Lamp');
+ await tester.pump();
+ await tester.tap(key('swarm-rename-save'));
+ await tester.pumpAndSettle();
+
+ expect(title('Phone Swarm'), findsOneWidget);
+ expect(find.text('Could not rename the Swarm.'), findsOneWidget);
+ });
+
+ testWidgets('an empty name: Save is off, and Done says why', (
+ tester,
+ ) async {
+ await pump(tester);
+ await open(tester);
+
+ await tester.enterText(key('swarm-rename-name'), ' ');
+ await tester.pump();
+ expect(save(tester), isNull);
+
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(
+ find.descendant(
+ of: key('swarm-rename-error'),
+ matching: find.text('Name cannot be empty'),
+ matchRoot: true,
+ ),
+ findsOneWidget,
+ );
+ expect(key('swarm-rename-name'), findsOneWidget, reason: 'still open');
+ expect(renames(fake), isEmpty);
+
+ await tester.enterText(key('swarm-rename-name'), 'L');
+ await tester.pump();
+ expect(key('swarm-rename-error'), findsNothing, reason: 'typing clears');
+ expect(save(tester), isNotNull);
+ });
+
+ testWidgets('the field takes at most 80 characters', (tester) async {
+ await pump(tester);
+ await open(tester);
+
+ await tester.enterText(key('swarm-rename-name'), 'x' * 100);
+ await tester.pump();
+ expect(field(tester), 'x' * 80);
+ });
+
+ testWidgets('Cancel, or the name it had, sends nothing', (tester) async {
+ await pump(tester);
+ await open(tester);
+ await tester.tap(key('swarm-rename-cancel'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-rename-name'), findsNothing);
+
+ await open(tester);
+ await tester.tap(key('swarm-rename-save'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-rename-name'), findsNothing);
+ expect(renames(fake), isEmpty);
+ expect(title('Phone Swarm'), findsOneWidget);
+ });
+
+ testWidgets('it goes once the Swarm can no longer be read', (tester) async {
+ await pump(tester);
+ await open(tester);
+
+ host.session!.inbox.reader(tab)!.revoke();
+ // Home's placeholders breathe once the read is taken away.
+ await frames(tester);
+
+ expect(key('swarm-rename-name'), findsNothing);
+ expect(renames(fake), isEmpty);
+ });
+
+ testWidgets("the Swarm's menu goes once the Swarm can no longer be read", (
+ tester,
+ ) async {
+ await pump(tester);
+ await hold(tester);
+ expect(find.text('Rename Swarm'), findsOneWidget);
+
+ host.session!.inbox.reader(tab)!.revoke();
+ await frames(tester);
+
+ expect(find.text('Rename Swarm'), findsNothing);
+ });
+
+ testWidgets('with the keyboard up, the field, its error and Save stay '
+ 'above the keys', (tester) async {
+ await pump(tester);
+ await open(tester);
+
+ const keyboard = 300.0;
+ tester.view.viewInsets = const FakeViewPadding(bottom: keyboard * 3);
+ await tester.pumpAndSettle();
+ await tester.enterText(key('swarm-rename-name'), ' ');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+
+ expect(tester.takeException(), isNull, reason: 'nothing overflows');
+ const above = 844 - keyboard;
+ for (final k in [
+ 'swarm-rename-name',
+ 'swarm-rename-error',
+ 'swarm-rename-save',
+ ]) {
+ final rect = tester.getRect(key(k));
+ expect(rect.bottom, lessThanOrEqualTo(above), reason: k);
+ expect(rect.top, greaterThanOrEqualTo(0), reason: k);
+ }
+ expect(
+ tester.getSize(key('swarm-rename-save')).height,
+ greaterThanOrEqualTo(44),
+ );
+ });
+ });
+}
diff --git a/mobile/test/swarm/swarm_row_test.dart b/mobile/test/swarm/swarm_row_test.dart
index 43b086b36..5736aaa39 100644
--- a/mobile/test/swarm/swarm_row_test.dart
+++ b/mobile/test/swarm/swarm_row_test.dart
@@ -74,4 +74,24 @@ void main() {
greaterThanOrEqualTo(SwarmRow.height),
);
});
+
+ testWidgets('a row held opens its menu, and a tap still opens it; with no '
+ 'menu a hold is a slow tap', (tester) async {
+ var taps = 0, holds = 0;
+ await show(
+ tester,
+ SwarmRow(
+ title: 'Fix login',
+ onTap: () => taps++,
+ onLongPress: () => holds++,
+ ),
+ );
+ await tester.longPress(find.byType(SwarmRow));
+ await tester.tap(find.byType(SwarmRow));
+ expect((taps, holds), (1, 1));
+
+ await show(tester, SwarmRow(title: 'Fix login', onTap: () => taps++));
+ await tester.longPress(find.byType(SwarmRow));
+ expect((taps, holds), (2, 1));
+ });
}
diff --git a/mobile/test/swarm/swarm_session_widgets_test.dart b/mobile/test/swarm/swarm_session_widgets_test.dart
index a2fa056e2..ba1a2fb1d 100644
--- a/mobile/test/swarm/swarm_session_widgets_test.dart
+++ b/mobile/test/swarm/swarm_session_widgets_test.dart
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show RenderParagraph;
+import 'package:flutter/semantics.dart' show SemanticsProperties;
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
@@ -215,12 +216,17 @@ void main() {
final fake = threadBackend(replies: plain);
await pump(tester, fake, thread: 'm1');
expect(key('swarm-thread-session-line'), findsNothing);
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
await tester.tap(key('swarm-thread-also-send'));
await tester.pump();
+ final box = tester.getRect(key('swarm-thread-box'));
await tester.tap(key('swarm-thread-new-session'));
await tester.pump();
// A reply that starts a session is not offered to the chat too.
expect(key('swarm-thread-also-send'), findsNothing);
+ // Also send's line keeps its place under the card: no jump.
+ expect(tester.getRect(key('swarm-thread-box')), box);
await tester.enterText(key('swarm-thread-field'), 'Look into it');
await tester.pump();
await tester.tap(key('swarm-thread-send'));
@@ -230,6 +236,59 @@ void main() {
expect(sent(fake).containsKey('alsoSend'), isFalse);
});
+ testWidgets('Reply options starts folded with nothing ticked; a tap '
+ 'opens it, another folds it and says what is on', (tester) async {
+ final fake = threadBackend(replies: plain);
+ await pump(tester, fake, thread: 'm1');
+ SemanticsProperties options() =>
+ tester.widget<Semantics>(key('swarm-thread-options')).properties;
+ String said() =>
+ tester.widget<Text>(key('swarm-thread-options-label')).data!;
+ bool? ticked(String name) =>
+ tester.widget<Semantics>(key(name)).properties.checked;
+
+ // Folded: its line only, under the card.
+ expect(said(), 'Reply options');
+ expect(options().expanded, isFalse);
+ expect(options().value, isNull);
+ expect(key('swarm-thread-new-session'), findsNothing);
+ expect(key('swarm-thread-also-send'), findsNothing);
+ expect(
+ tester.getRect(key('swarm-thread-options')).top,
+ tester.getRect(key('swarm-composer-card')).bottom,
+ );
+
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
+ expect(options().expanded, isTrue);
+ expect(ticked('swarm-thread-new-session'), isFalse);
+ expect(ticked('swarm-thread-also-send'), isFalse);
+ // New session above Also send, both under Reply options' line.
+ final line = tester.getRect(key('swarm-thread-options'));
+ final session = tester.getRect(key('swarm-thread-new-session'));
+ final also = tester.getRect(key('swarm-thread-also-send'));
+ expect(session.top, line.bottom);
+ expect(also.top, session.bottom);
+
+ await tester.tap(key('swarm-thread-new-session'));
+ await tester.pump();
+ // Open, the line says only its name: the ticks are in sight.
+ expect(said(), 'Reply options');
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
+ expect(options().expanded, isFalse);
+ expect(key('swarm-thread-new-session'), findsNothing);
+ expect(said(), 'Reply options · New session');
+ expect(options().value, 'New session');
+
+ // Folding keeps the tick: the reply still starts a session.
+ await tester.enterText(key('swarm-thread-field'), 'Look into it');
+ await tester.pump();
+ await tester.tap(key('swarm-thread-send'));
+ await tester.pumpAndSettle();
+ expect(sent(fake)['newSession'], isTrue);
+ });
+
testWidgets('a live session shows its status line; End session ends it '
'once', (tester) async {
final fake = threadBackend(
@@ -275,6 +334,8 @@ void main() {
],
);
await pump(tester, fake, thread: 'm1');
+ // Not even folded: Reply options is not there to open.
+ expect(key('swarm-thread-options'), findsNothing);
expect(key('swarm-thread-new-session'), findsNothing);
expect(key('swarm-thread-also-send'), findsNothing);
});
@@ -337,6 +398,14 @@ void main() {
'Session ended: idle for 30 minutes',
);
expect(key('swarm-thread-session-end'), findsNothing);
+ // Folded, Reply options still says the reply starts a session.
+ expect(
+ tester.widget<Text>(key('swarm-thread-options-label')).data,
+ 'Reply options · New session',
+ );
+ expect(key('swarm-thread-new-session'), findsNothing);
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
expect(
tester.widget<Text>(key('swarm-thread-new-session-note')).data,
'This thread\'s session ended. Your reply starts a new one.',
@@ -361,6 +430,13 @@ void main() {
) async {
final fake = threadBackend(replies: plain, engine: 'codex');
await pump(tester, fake, thread: 'm1');
+ // Nothing on: the folded line says only its name.
+ expect(
+ tester.widget<Text>(key('swarm-thread-options-label')).data,
+ 'Reply options',
+ );
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
expect(
tester.widget<Text>(key('swarm-thread-new-session-note')).data,
'Sessions need a Claude Code Buddy',
diff --git a/mobile/test/swarm/swarm_task_unread_line_test.dart b/mobile/test/swarm/swarm_task_unread_line_test.dart
new file mode 100644
index 000000000..316416b40
--- /dev/null
+++ b/mobile/test/swarm/swarm_task_unread_line_test.dart
@@ -0,0 +1,402 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// A task's chat has the New messages line, Jump to first unread and Jump to
+/// latest, as the project chat and the person's own Buddy chat do and as
+/// Desktop has them in every chat: placed from the server's read mark, above
+/// a row the chat draws, the task's own and not its steps'.
+void main() {
+ const task = 'task-1';
+ const step = 'review-1';
+ const messages = '/api/super-tabs/$tab/conversations/$task/messages';
+ final line = find.byKey(const ValueKey('swarm-new-messages-line'));
+ final latest = find.byKey(const ValueKey('swarm-jump-latest'));
+ final unread = find.byKey(const ValueKey('swarm-jump-unread'));
+ final list = find.byKey(const ValueKey('swarm-messages'));
+
+ Map<String, dynamic> said(
+ int sequence, {
+ String author = 'agent-dev',
+ String kind = 'agent',
+ String? text,
+ String conversation = task,
+ int? minute,
+ Map<String, dynamic>? source,
+ }) => {
+ 'id': '$conversation-$sequence',
+ 'conversationId': conversation,
+ 'text': text ?? 'Update $sequence.',
+ 'sequence': sequence,
+ 'author': {'kind': kind, 'id': author, 'name': author},
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'source': ?source,
+ 'createdAt': DateTime.utc(
+ 2026,
+ 11,
+ 2,
+ 9,
+ minute ?? sequence,
+ ).toIso8601String(),
+ };
+
+ List<Map<String, dynamic>> forty() => [for (var i = 1; i <= 40; i++) said(i)];
+
+ /// A task in the person's project holding [page], read through [mark] on
+ /// some device (the server's mark, #2131). With [steps], it has a Review
+ /// step holding them. Its Engineer is [dev], as the Swarm's read has it.
+ FakeSwarm backend(
+ List<Map<String, dynamic>> page, {
+ required int mark,
+ List<Map<String, dynamic>>? steps,
+ Map<String, dynamic>? dev,
+ }) {
+ 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(
+ task,
+ title: 'Fix login',
+ number: 12,
+ agentIds: ['agent-dev'],
+ status: 'working',
+ workerId: 'agent-dev',
+ lastMessageSequence: page.isEmpty
+ ? 0
+ : page.last['sequence'] as int,
+ ),
+ if (steps != null)
+ {
+ ...groupData(
+ step,
+ title: 'Review',
+ number: 13,
+ status: 'working',
+ workerId: 'agent-rev',
+ lastMessageSequence: steps.length,
+ ),
+ 'reviewOf': task,
+ 'step': 'Review',
+ },
+ ],
+ agents: [
+ dev ?? agent('agent-dev', displayName: 'Dev'),
+ agent('agent-rev', displayName: 'Nova'),
+ ],
+ derived: {
+ 'readMarks': {task: mark},
+ },
+ ),
+ '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,
+ };
+ if (steps != null) {
+ fake.routes['/api/super-tabs/$tab/conversations/$step/messages'] = (_) =>
+ {'messages': steps.reversed.toList(), 'next': null};
+ }
+ return fake;
+ }
+
+ Future<SwarmHost> pump(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ bool settle = true,
+ String? messageId,
+ }) async {
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ upload: refuseSwarmUpload,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: SwarmConversationPage(
+ swarmId: tab,
+ conversationId: task,
+ messageId: messageId,
+ ),
+ ),
+ );
+ if (settle) {
+ await tester.pumpAndSettle();
+ } else {
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ }
+ return host;
+ }
+
+ /// The read marks sent for [conversation], in order.
+ List<Object?> marksSent(FakeSwarm fake, [String conversation = task]) => [
+ for (final call in fake.calls)
+ if (call.method == 'POST' &&
+ call.path == '/api/super-tabs/$tab/conversations/$conversation/read')
+ call.body?['sequence'],
+ ];
+
+ bool onScreen(WidgetTester tester, Finder f) {
+ if (f.evaluate().isEmpty) return false;
+ final view = tester.getRect(list);
+ final row = tester.getRect(f);
+ return row.top >= view.top && row.bottom <= view.bottom;
+ }
+
+ double y(WidgetTester tester, String text) =>
+ tester.getTopLeft(find.textContaining(text)).dy;
+
+ group("a task's chat", () {
+ testWidgets('has the New messages line above the first message from '
+ 'someone else the person had not read', (tester) async {
+ final fake = backend([for (var i = 1; i <= 4; i++) said(i)], mark: 2);
+ await pump(tester, fake);
+
+ expect(line, findsOneWidget);
+ expect(find.text('New messages'), findsOneWidget);
+ final at = tester.getTopLeft(line).dy;
+ expect(y(tester, 'Update 2.'), lessThan(at));
+ expect(y(tester, 'Update 3.'), greaterThan(at));
+ expect(marksSent(fake).last, 4, reason: 'the line on screen: all read');
+ });
+
+ testWidgets('read through its end has none, and opens at its foot', (
+ tester,
+ ) async {
+ await pump(tester, backend(forty(), mark: 40));
+
+ expect(line, findsNothing);
+ expect(onScreen(tester, find.text('Update 40.')), isTrue);
+ expect(latest, findsNothing, reason: 'at the foot');
+ });
+
+ testWidgets('passes over what the person wrote', (tester) async {
+ await pump(
+ tester,
+ backend([
+ said(1),
+ said(2),
+ said(3, author: me, kind: 'person', text: 'On it.'),
+ ], mark: 1),
+ );
+
+ expect(line, findsNothing);
+ });
+
+ testWidgets('opens at a line above the screen and reads nothing below it '
+ 'until the person goes down to it', (tester) async {
+ final fake = backend(forty(), mark: 5);
+ await pump(tester, fake);
+
+ expect(onScreen(tester, line), isTrue, reason: 'opened at the line');
+ expect(onScreen(tester, find.text('Update 6.')), isTrue);
+ expect(onScreen(tester, find.text('Update 40.')), isFalse);
+ expect(
+ marksSent(fake).where((s) => (s! as int) > 5),
+ isEmpty,
+ reason: 'nothing past the line is read yet',
+ );
+
+ await tester.fling(list, const Offset(0, -6000), 4000);
+ await tester.pumpAndSettle();
+
+ expect(onScreen(tester, find.text('Update 40.')), isTrue);
+ expect(marksSent(fake).last, 40);
+ });
+
+ testWidgets('offers Jump to latest more than a screen back, and a tap '
+ 'takes the person to the foot', (tester) async {
+ await pump(tester, backend(forty(), mark: 40));
+
+ await tester.drag(list, const Offset(0, 120));
+ await tester.pumpAndSettle();
+ expect(latest, findsNothing, reason: 'not a screen back');
+
+ await tester.drag(list, const Offset(0, 1500));
+ await tester.pumpAndSettle();
+ expect(onScreen(tester, find.text('Update 40.')), isFalse);
+ expect(latest, findsOneWidget);
+ expect(find.text('Jump to latest'), findsOneWidget);
+
+ await tester.tap(latest);
+ await tester.pumpAndSettle();
+ expect(onScreen(tester, find.text('Update 40.')), isTrue);
+ expect(latest, findsNothing);
+ });
+
+ testWidgets('opened from a notice below the line, offers Jump to first '
+ 'unread, which lands on the line', (tester) async {
+ await pump(tester, backend(forty(), mark: 5), messageId: '$task-25');
+
+ expect(onScreen(tester, find.text('Update 25.')), isTrue);
+ expect(onScreen(tester, line), isFalse);
+ expect(unread, findsOneWidget);
+
+ await tester.tap(unread);
+ await tester.pumpAndSettle();
+ expect(onScreen(tester, line), isTrue);
+ expect(unread, findsNothing);
+ });
+ });
+
+ group('the line sits above a row the task draws', () {
+ testWidgets("its own first unread, not a step's row merged in before it", (
+ tester,
+ ) async {
+ final fake = backend(
+ [said(1, minute: 1), said(2, minute: 10), said(3, minute: 20)],
+ mark: 2,
+ // Never read, and written after the task's mark.
+ steps: [
+ said(
+ 1,
+ conversation: step,
+ author: 'agent-rev',
+ text: 'Review note.',
+ minute: 15,
+ ),
+ ],
+ );
+ await pump(tester, fake);
+
+ expect(find.textContaining('Nova · Review'), findsOneWidget);
+ expect(line, findsOneWidget);
+ final at = tester.getTopLeft(line).dy;
+ expect(y(tester, 'Update 2.'), lessThan(at));
+ // Merged in by time before the task's first unread: above the line.
+ expect(y(tester, 'Review note.'), lessThan(at));
+ expect(y(tester, 'Update 3.'), greaterThan(at));
+ expect(marksSent(fake).last, 3);
+ expect(marksSent(fake, step), isEmpty, reason: 'a step reads on its own');
+ });
+
+ testWidgets('an answered prompt warning is passed over: the line goes '
+ 'above the next message, and the chat is read', (tester) async {
+ final fake = backend(
+ [
+ said(1, text: 'Starting.'),
+ said(
+ 2,
+ text: 'Dev is waiting at a prompt in its terminal.',
+ source: {
+ 'kind': 'terminal-alert',
+ 'agentId': 'agent-dev',
+ 'alert': 'prompt',
+ },
+ ),
+ said(3, text: 'Prompt answered, carrying on.'),
+ ],
+ mark: 1,
+ // Its prompt answered: the warning is no longer drawn.
+ dev: {
+ ...agent('agent-dev', displayName: 'Dev'),
+ 'alerting': <String>[],
+ },
+ );
+ await pump(tester, fake);
+
+ expect(find.textContaining('waiting at a prompt'), findsNothing);
+ expect(line, findsOneWidget);
+ final at = tester.getTopLeft(line).dy;
+ expect(y(tester, 'Starting.'), lessThan(at));
+ expect(y(tester, 'Prompt answered'), greaterThan(at));
+ expect(marksSent(fake).last, 3, reason: 'the line on screen: all read');
+ });
+ });
+
+ group("the Swarm's read fails first", () {
+ /// [fake]'s Swarm read failing until the returned function is called,
+ /// which reads it again.
+ Future<void> Function() swarmDownAt(
+ WidgetTester tester,
+ FakeSwarm fake,
+ SwarmHost Function() host,
+ ) {
+ final parts = '/api/super-tabs/$tab/parts';
+ final answer = fake.routes[parts]!;
+ var down = true;
+ fake.routes[parts] = (body) {
+ if (down) {
+ throw const SuperTabFailure(
+ 'INTERNAL',
+ 'Swarm temporarily unavailable.',
+ );
+ }
+ return answer(body);
+ };
+ return () async {
+ down = false;
+ await host().session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ };
+ }
+
+ testWidgets('nothing is read until it works, then the line is placed '
+ "from the server's mark", (tester) async {
+ final fake = backend([for (var i = 1; i <= 4; i++) said(i)], mark: 2);
+ late SwarmHost host;
+ final recover = swarmDownAt(tester, fake, () => host);
+ host = await pump(tester, fake, settle: false);
+ expect(host.session!.inbox.reader(tab)!.snapshot, isNull);
+ expect(marksSent(fake), isEmpty);
+
+ await recover();
+
+ expect(line, findsOneWidget);
+ final at = tester.getTopLeft(line).dy;
+ expect(y(tester, 'Update 2.'), lessThan(at));
+ expect(y(tester, 'Update 3.'), greaterThan(at));
+ expect(marksSent(fake).last, 4);
+ });
+
+ testWidgets('and Jump to latest once it works', (tester) async {
+ final fake = backend(forty(), mark: 40);
+ late SwarmHost host;
+ final recover = swarmDownAt(tester, fake, () => host);
+ host = await pump(tester, fake, settle: false);
+
+ await recover();
+ await tester.drag(list, const Offset(0, 1500));
+ await tester.pumpAndSettle();
+
+ expect(line, findsNothing);
+ expect(onScreen(tester, find.text('Update 40.')), isFalse);
+ expect(latest, findsOneWidget);
+ });
+ });
+}
diff --git a/mobile/test/swarm/swarm_task_unread_shots_test.dart b/mobile/test/swarm/swarm_task_unread_shots_test.dart
new file mode 100644
index 000000000..69d9ebcd1
--- /dev/null
+++ b/mobile/test/swarm/swarm_task_unread_shots_test.dart
@@ -0,0 +1,191 @@
+import 'dart:convert';
+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';
+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 '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of a task's chat with the New messages line, and with
+/// Jump to first unread when a notice opened it further down. 390 points
+/// wide in both phone themes, from made-up data only, to the folder
+/// `SWARM_TASK_UNREAD_SHOTS` names.
+final shots = Platform.environment['SWARM_TASK_UNREAD_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ const task = 'task-1';
+ const lines = [
+ 'Pushed the plan for the login retry fix to the draft PR.',
+ 'The failing test is in: the timer restarts on every rebuild.',
+ 'Fix is in. The timer now starts once per code request.',
+ 'CI is green on the head. Asking for review next.',
+ ];
+
+ Map<String, dynamic> said(int sequence) => {
+ 'id': '$task-$sequence',
+ 'conversationId': task,
+ 'text': lines[sequence % lines.length],
+ 'sequence': sequence,
+ 'author': {'kind': 'agent', 'id': 'agent-dev', 'name': 'Dev'},
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': DateTime.utc(2026, 11, 2, 9, sequence).toIso8601String(),
+ };
+
+ FakeSwarm backend() {
+ 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(
+ task,
+ title: 'Fix the login retry timer',
+ number: 12,
+ agentIds: ['agent-dev'],
+ status: 'working',
+ workerId: 'agent-dev',
+ lastMessageSequence: 40,
+ ),
+ ],
+ agents: [agent('agent-dev', displayName: 'Plover')],
+ derived: {
+ 'readMarks': {task: 30},
+ },
+ ),
+ '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['/api/super-tabs/$tab/conversations/$task/messages'] = (_) => {
+ 'messages': [for (var i = 40; i >= 1; i--) said(i)],
+ 'next': null,
+ };
+ return fake;
+ }
+
+ testWidgets("a task's chat: the New messages line, and Jump to first "
+ 'unread', (tester) async {
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final boundary = GlobalKey();
+ Future<void> capture(String name) => tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/task-unread-$name-390-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+
+ /// The task's chat opened, from a notice at [messageId] when given.
+ Future<SwarmHost> open([String? messageId]) async {
+ final host = SwarmHost(
+ accountId: () => me,
+ account: ValueNotifier<String?>(me),
+ request: backend().request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: SwarmConversationPage(
+ swarmId: tab,
+ conversationId: task,
+ messageId: messageId,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return host;
+ }
+
+ Future<void> close(SwarmHost host) async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ host.dispose();
+ }
+
+ final line = find.byKey(const ValueKey('swarm-new-messages-line'));
+ final pill = find.byKey(const ValueKey('swarm-jump-unread'));
+
+ // Opened as it is: at the line, above the first message not read.
+ var host = await open();
+ expect(line, findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await capture('line');
+ await close(host);
+
+ // Opened by a notice near the foot: the line is above, not seen yet.
+ host = await open('$task-39');
+ expect(pill, findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await capture('jump');
+ await close(host);
+ }
+ await tester.binding.setSurfaceSize(null);
+ tester.view.resetPadding();
+ AppTheme.palette.value = HarnessPalette.graphite;
+ AppTheme.brightness.value = Brightness.dark;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_thread_session_test.dart b/mobile/test/swarm/swarm_thread_session_test.dart
index efeec46d8..a838190be 100644
--- a/mobile/test/swarm/swarm_thread_session_test.dart
+++ b/mobile/test/swarm/swarm_thread_session_test.dart
@@ -233,4 +233,56 @@ void main() {
});
},
);
+
+ group('@ where a session hears the thread (Desktop thread `_tagChoices`, '
+ '`sendThreadReply`)', () {
+ test('a plain thread offers the chat\'s Buddy; a reply that starts a '
+ 'session offers no agent', () async {
+ final (_, chat, thread) = await rig();
+ expect([for (final a in thread.mentionable) a.id], ['agent-wren']);
+
+ thread.newSession = true;
+
+ expect(thread.newSession, isTrue);
+ expect(thread.mentionable, isEmpty);
+ expect(chat.mentionable, isNotEmpty, reason: 'the chat still offers it');
+ });
+
+ test('a thread a session answers offers no agent', () async {
+ final rows = [
+ sessionMessage('m1', 1, author: me),
+ sessionMessage('m2', 2, root: 'm1', session: true),
+ ];
+ final (_, _, thread) = await rig(
+ backend: sessionBackend(sessions: live, page: rows),
+ page: rows,
+ );
+ expect(thread.session, isNotNull);
+ expect(thread.mentionable, isEmpty);
+ });
+
+ test('an agent named before New session was chosen holds the reply back '
+ 'and says why, as the desktop does; unnamed, it goes', () async {
+ final (fake, _, thread) = await rig();
+ thread.mention('agent-wren');
+ thread
+ ..draft = '${thread.draft}look'
+ ..newSession = true;
+
+ expect(await thread.send(), isFalse);
+
+ expect(
+ thread.error,
+ "Only this thread's session hears a reply here. Remove the agent's "
+ 'mention.',
+ );
+ expect(fake.commands.where((c) => c['type'] == 'message.send'), isEmpty);
+ expect(thread.draft, '@Wren look', reason: 'nothing left the box');
+
+ thread.draft = 'look';
+ expect(await thread.send(), isTrue);
+ expect(sent(fake)['recipientIds'], isEmpty);
+ expect(sent(fake)['newSession'], isTrue);
+ });
+ });
}
diff --git a/mobile/test/swarm/swarm_thread_test.dart b/mobile/test/swarm/swarm_thread_test.dart
index b88aa4783..9ff8f0a70 100644
--- a/mobile/test/swarm/swarm_thread_test.dart
+++ b/mobile/test/swarm/swarm_thread_test.dart
@@ -51,7 +51,7 @@ void main() {
/// A Swarm with conversation g1 at [sequence] while [listed] says so, its
/// chat read with [chatRows]: root m1 and its first reply unless told.
- /// Files go up to [uploads].
+ /// Files go up to [uploads]; [others] are members besides the person.
Future<({FakeSwarm swarm, SwarmReader reader, SwarmConversation chat})> rig({
int sequence = 2,
String role = 'owner',
@@ -59,6 +59,7 @@ void main() {
List<Map<String, dynamic>>? chatRows,
bool Function()? listed,
FakeUploads? uploads,
+ List<Map<String, dynamic>> others = const [],
}) async {
final swarm = FakeSwarm();
swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {
@@ -74,7 +75,10 @@ void main() {
),
],
),
- 'members': [part(me, 1, person(me, role: role))],
+ 'members': [
+ part(me, 1, person(me, role: role)),
+ for (final other in others) part(other['id'] as String, 1, other),
+ ],
};
swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
swarm.routes[messages] = (_) => {
@@ -499,6 +503,221 @@ void main() {
});
});
+ group('@ in a reply (Desktop thread panel `@`)', () {
+ /// Thread m1 of g1 read, with Dee in the Swarm besides the person.
+ Future<({FakeSwarm swarm, SwarmConversation chat, SwarmThread thread})>
+ tagging() async {
+ final r = await rig(others: [person('dee', role: 'collaborator')]);
+ r.swarm.routes[thread] = (_) => {
+ 'messages': [message('m1', 1)],
+ 'next': null,
+ };
+ readsBack(r.swarm);
+ final t = open(r.chat);
+ await t.load();
+ return (swarm: r.swarm, chat: r.chat, thread: t);
+ }
+
+ test('offers whom the chat\'s composer offers: its agents and the people '
+ 'who read it, never the reader', () async {
+ final r = await tagging();
+ expect(
+ [for (final a in r.thread.mentionable) a.id],
+ ['agent-lead', 'agent-builder'],
+ );
+ expect([for (final p in r.thread.mentionablePeople) p.id], ['dee']);
+ });
+
+ test('a picked agent is a recipient and a picked person is tagged, while '
+ 'the text names them', () async {
+ final r = await tagging();
+ final t = r.thread;
+
+ t.draft = 'Can you check';
+ t.mention('agent-builder');
+ t.mention('dee');
+ expect(t.draft, 'Can you check @Nova @dee ');
+ t.draft = '${t.draft}this';
+ expect(await t.send(), isTrue);
+
+ expect(r.swarm.commands.single, {
+ 'type': 'message.send',
+ 'conversationId': 'g1',
+ 'text': 'Can you check @Nova @dee this',
+ 'replyTo': 'm1',
+ 'recipientIds': ['agent-builder'],
+ 'mentions': ['dee'],
+ });
+ expect(t.mentions, isEmpty, reason: 'the next reply names no one yet');
+ expect(r.chat.threadMentions('m1'), isEmpty);
+ });
+
+ test('Tag ends the draft in an @ or takes it back, and a pick takes the '
+ 'place of the name being typed', () async {
+ final r = await tagging();
+ final t = r.thread;
+
+ t.draft = 'ask';
+ t.toggleMention();
+ expect(t.draft, 'ask @');
+ expect(t.mentionQuery, '');
+ t.toggleMention();
+ expect(t.draft, 'ask ');
+ expect(t.mentionQuery, isNull);
+
+ t.draft = 'ask @No';
+ expect(t.mentionQuery, 'No');
+ t.completeMention('agent-builder');
+ expect(t.draft, 'ask @Nova ');
+ expect(t.mentionQuery, isNull);
+ expect(t.mentions, {'agent-builder': '@Nova'});
+ });
+
+ test('a name taken out of the text names nobody', () async {
+ final r = await tagging();
+ final t = r.thread;
+
+ t.mention('agent-builder');
+ t.mention('dee');
+ t.draft = 'never mind';
+ expect(t.mentions, isEmpty);
+ expect(await t.send(), isTrue);
+
+ expect(r.swarm.commands.single['recipientIds'], isEmpty);
+ expect(r.swarm.commands.single.containsKey('mentions'), isFalse);
+ });
+
+ test('refused, the reply goes back to the box with its names, which go '
+ 'with it again', () async {
+ final r = await tagging();
+ var refuse = true;
+ r.swarm.routes[commands] = (body) => refuse
+ ? throw const SuperTabFailure(
+ 'TOO_LONG',
+ 'This message is too long.',
+ statusCode: 400,
+ )
+ : {'ok': true};
+ final t = r.thread;
+ t.mention('agent-builder');
+ t.mention('dee');
+ t.draft = '${t.draft}please';
+
+ expect(await t.send(), isFalse);
+ expect(t.draft, '@Nova @dee please');
+ expect(t.mentions, {'agent-builder': '@Nova', 'dee': '@dee'});
+ expect(t.error, 'This message is too long.');
+
+ refuse = false;
+ expect(await t.send(), isTrue);
+ expect(r.swarm.commands.last['recipientIds'], ['agent-builder']);
+ expect(r.swarm.commands.last['mentions'], ['dee']);
+ });
+
+ test('the names stay with the thread\'s draft while the chat is open, '
+ 'and not with another thread\'s', () async {
+ final r = await rig();
+ readsBack(r.swarm);
+ final first = SwarmThread(r.chat, 'm1')..mention('agent-builder');
+ first.dispose();
+
+ final again = open(r.chat);
+ expect(again.draft, '@Nova ');
+ expect(again.mentions, {'agent-builder': '@Nova'});
+ expect(open(r.chat, 'm9').mentions, isEmpty);
+ again.draft = '${again.draft}look';
+ expect(await again.send(), isTrue);
+ expect(r.swarm.commands.single['recipientIds'], ['agent-builder']);
+ });
+
+ /// Nova (agent-builder) taken out of g1, and the Swarm read again.
+ Future<void> novaLeaves(FakeSwarm swarm, SwarmReader reader) async {
+ final parts = swarm.routes['/api/super-tabs/$tab/parts']!;
+ swarm.routes['/api/super-tabs/$tab/parts'] = (body) {
+ final read = parts(body) as Map<String, dynamic>;
+ return {
+ ...read,
+ 'groups': [
+ for (final g in (read['groups'] as List).cast<Map>())
+ g['key'] == 'g1'
+ ? part('g1', (g['version'] as int) + 1, {
+ ...(g['data'] as Map<String, dynamic>),
+ 'agentIds': ['agent-lead'],
+ })
+ : g,
+ ],
+ };
+ };
+ // The changes say read it all again.
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};
+ await reader.refresh();
+ await settle();
+ }
+
+ const left =
+ 'A mentioned agent is no longer in this conversation. '
+ 'Remove its mention or choose another agent.';
+
+ test('a picked agent who has left the chat since is refused in the '
+ "desktop's words, the reply kept in the box (controller.dart "
+ 'sendThreadReply)', () async {
+ final r = await tagging();
+ final t = r.thread;
+ t.draft = 'Can you check';
+ t.mention('agent-builder');
+ t.mention('dee');
+ expect(t.draft, 'Can you check @Nova @dee ');
+
+ await novaLeaves(r.swarm, r.chat.reader);
+ expect(r.chat.conversation!.agentIds, ['agent-lead']);
+ expect(await t.send(), isFalse);
+
+ expect(t.error, left);
+ expect(r.swarm.commands, isEmpty, reason: 'nothing sent without Nova');
+ expect(t.draft, 'Can you check @Nova @dee ');
+ expect(t.mentions, {'agent-builder': '@Nova', 'dee': '@dee'});
+ });
+
+ test('the same in the chat\'s own box (controller.dart send)', () async {
+ final r = await tagging();
+ final c = r.chat;
+ c.draft = 'Can you check';
+ c.mention('agent-builder');
+
+ await novaLeaves(r.swarm, c.reader);
+ expect(await c.send(), isFalse);
+
+ expect(c.error, left);
+ expect(r.swarm.commands, isEmpty);
+ expect(c.draft, 'Can you check @Nova ');
+ expect(c.mentions, {'agent-builder': '@Nova'});
+ });
+
+ test('once the mention is taken out, the reply goes', () async {
+ final r = await tagging();
+ final t = r.thread;
+ t.mention('agent-builder');
+ await novaLeaves(r.swarm, r.chat.reader);
+ t.draft = 'never mind';
+
+ expect(await t.send(), isTrue);
+ expect(r.swarm.commands.single['recipientIds'], isEmpty);
+ });
+
+ test('access lost while the thread is open takes its names too', () async {
+ final r = await tagging();
+ r.thread.mention('agent-builder');
+
+ r.chat.reader.revoke();
+ await settle();
+
+ expect(r.thread.state, SwarmChatState.lost);
+ expect(r.thread.draft, isEmpty);
+ expect(r.thread.mentions, isEmpty);
+ expect(r.chat.threadMentions('m1'), 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';
diff --git a/mobile/test/swarm/swarm_thread_voice_test.dart b/mobile/test/swarm/swarm_thread_voice_test.dart
index 2e5752235..ecead6d05 100644
--- a/mobile/test/swarm/swarm_thread_voice_test.dart
+++ b/mobile/test/swarm/swarm_thread_voice_test.dart
@@ -206,20 +206,22 @@ void main() {
await frames(tester);
}
- testWidgets('the thread\'s reply box: +, Also send, then the main chat\'s '
- 'mic just left of Send, in one row', (tester) async {
+ testWidgets('the thread\'s reply box: +, then the main chat\'s mic just '
+ 'left of Send, in one row; Reply options on its own line under it', (
+ tester,
+ ) async {
await pump(tester);
expect(inBox(key('swarm-mic')), findsOneWidget);
final mic = tester.getCenter(inBox(key('swarm-mic')));
final send = tester.getCenter(key('swarm-thread-send'));
final attach = tester.getCenter(key('swarm-thread-attach'));
- final also = tester.getCenter(key('swarm-thread-also-send'));
- for (final other in [send, attach, also]) {
+ final options = tester.getCenter(key('swarm-thread-options'));
+ for (final other in [send, attach]) {
expect(mic.dy, other.dy, reason: 'in one row');
}
- expect(attach.dx, lessThan(also.dx), reason: '+ moved to the left');
- expect(also.dx, lessThan(mic.dx));
+ expect(options.dy, greaterThan(send.dy), reason: 'its own line, under');
+ expect(attach.dx, lessThan(mic.dx), reason: '+ moved to the left');
expect(mic.dx, lessThan(send.dx));
});
@@ -282,14 +284,33 @@ void main() {
});
testWidgets('Also send ticked, a take, stop, then Send posts to the chat '
- 'too: the tick survives the take', (tester) async {
+ 'too: the tick survives the take, and takes no taps during it', (
+ tester,
+ ) async {
await pump(tester);
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
await tester.tap(key('swarm-thread-also-send'));
await tester.pump();
stt.replies.add('also for everyone');
+ final box = tester.getRect(key('swarm-thread-box'));
+ bool? ticked() => tester
+ .widget<Semantics>(key('swarm-thread-also-send'))
+ .properties
+ .checked;
await tapMic(tester);
- expect(key('swarm-thread-also-send'), findsNothing, reason: 'hidden');
+ expect(
+ tester.getRect(key('swarm-thread-box')),
+ box,
+ reason: 'Reply options stays as it was: the box does not jump',
+ );
+ // In sight, as it will be sent: a tap during the take changes nothing.
+ await tester.tap(key('swarm-thread-also-send'), warnIfMissed: false);
+ await tester.tap(key('swarm-thread-options'), warnIfMissed: false);
+ await tester.pump();
+ expect(ticked(), isTrue);
+ expect(key('swarm-thread-also-send'), findsOneWidget, reason: 'still open');
await stop(tester);
await tester.pumpAndSettle();
expect(fake.commands, isEmpty);
@@ -314,6 +335,8 @@ void main() {
testWidgets("the row's Send ends the take and posts it as one reply, to the "
'chat too with Also send ticked', (tester) async {
await pump(tester);
+ await tester.tap(key('swarm-thread-options'));
+ await tester.pump();
await tester.tap(key('swarm-thread-also-send'));
await tester.pump();
await tester.enterText(key('swarm-thread-field'), 'Nova:');
@@ -418,8 +441,8 @@ void main() {
});
testWidgets("during a take the toolbar is cancel, the wave, stop and the "
- "row's Send: no box Send, Also send, + or X, which come back after "
- 'stop', (tester) async {
+ "row's Send: no box Send, + or X, which come back after stop; Reply "
+ 'options stays, folded', (tester) async {
await pump(tester);
await tester.enterText(key('swarm-thread-field'), 'Nova:');
await tester.pump();
@@ -430,7 +453,6 @@ void main() {
for (final gone in [
'swarm-thread-send',
- 'swarm-thread-also-send',
'swarm-thread-attach',
'swarm-thread-clear',
'swarm-mic',
@@ -442,16 +464,21 @@ void main() {
'swarm-voice-wave',
'swarm-voice-stop',
'swarm-voice-send',
+ 'swarm-thread-options',
]) {
expect(inBox(key(shown)), findsOneWidget, reason: shown);
}
+ // Folded it stays: a tap during the take does not open it.
+ await tester.tap(key('swarm-thread-options'), warnIfMissed: false);
+ await tester.pump();
+ expect(inBox(key('swarm-thread-also-send')), findsNothing);
await stop(tester);
await tester.pumpAndSettle();
for (final back in [
'swarm-thread-send',
- 'swarm-thread-also-send',
+ 'swarm-thread-options',
'swarm-thread-attach',
'swarm-thread-clear',
'swarm-mic',
diff --git a/mobile/test/swarm/swarm_unread_line_test.dart b/mobile/test/swarm/swarm_unread_line_test.dart
index d5897b72a..4325ebb3d 100644
--- a/mobile/test/swarm/swarm_unread_line_test.dart
+++ b/mobile/test/swarm/swarm_unread_line_test.dart
@@ -27,8 +27,18 @@ void main() {
SuperTabMessage mine(int sequence, {String? thread}) =>
message(sequence, author: me, kind: 'person', thread: thread);
- String? first(List<SuperTabMessage> read, int? mark, {bool older = false}) =>
- swarmFirstUnread(read, mark, accountId: me, hasOlder: older);
+ String? first(
+ List<SuperTabMessage> read,
+ int? mark, {
+ bool older = false,
+ Set<String>? hidden,
+ }) => swarmFirstUnread(
+ read,
+ mark,
+ accountId: me,
+ hasOlder: older,
+ drawn: hidden == null ? null : (m) => !hidden.contains(m.id),
+ );
test('is the first message past the mark', () {
expect(first([message(1), message(2), message(3)], 1), 'm2');
@@ -82,6 +92,29 @@ void main() {
);
});
+ test('passes over a message the chat does not draw, such as an answered '
+ "prompt's warning in a task's chat", () {
+ expect(
+ first([message(1), message(2), message(3)], 1, hidden: {'m2'}),
+ 'm3',
+ );
+ expect(
+ first([message(1), message(2), message(3)], 1, hidden: {'m2', 'm3'}),
+ isNull,
+ reason: 'nothing unread is drawn',
+ );
+ expect(
+ first([message(1), message(2), message(3)], 1, hidden: {'m1'}),
+ 'm2',
+ reason: 'a hidden message already read changes nothing',
+ );
+ expect(
+ first([message(3), message(4)], 2, older: true, hidden: {'m3'}),
+ 'm4',
+ reason: 'a hidden message still counts toward reaching the mark',
+ );
+ });
+
test("a message the server posted in the person's name reads nothing "
'before it (plain chat, #2294)', () {
SuperTabMessage posted(int sequence, String kind) =>
diff --git a/scripts/ci-source-inputs.py b/scripts/ci-source-inputs.py
index 51abd023a..bd626b329 100644
--- a/scripts/ci-source-inputs.py
+++ b/scripts/ci-source-inputs.py
@@ -12,8 +12,21 @@ ci = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ci)
+# CI checks out with --filter=blob:none. git status reads the nested .gitignore
+# files outside the sparse patterns from the index, and would fetch each missing
+# blob from GitHub (#2848, #2860 timed out). Nothing here needs a blob's content,
+# so fetching stays off: a missing ignore file can only report more untracked
+# files, never fewer. The timeout still fails a hung git, inside the job's limit.
+GIT_TIMEOUT = 60
+
+
+def git_env():
+ return {**os.environ, "GIT_NO_LAZY_FETCH": "1"}
+
+
def git(root, *args):
- return subprocess.check_output(["git", *args], cwd=root, stderr=subprocess.PIPE, timeout=15).decode().strip()
+ return subprocess.check_output(["git", *args], cwd=root, stderr=subprocess.PIPE, timeout=GIT_TIMEOUT,
+ env=git_env()).decode().strip()
def verify_checkout(root, scope, subset=False):
@@ -31,7 +44,8 @@ def verify_checkout(root, scope, subset=False):
raise ValueError("checkout includes source outside the declared CI inputs")
if not subset and patterns != {"/" + path for path in declared}:
raise ValueError("checkout does not match the complete declared CI inputs")
- entries = subprocess.check_output(["git", "ls-files", "-t", "-z"], cwd=root, timeout=15).decode().split("\0")
+ entries = subprocess.check_output(["git", "ls-files", "-t", "-z"], cwd=root, timeout=GIT_TIMEOUT,
+ env=git_env()).decode().split("\0")
for entry in filter(None, entries):
flag, path = entry[:1], entry[2:]
# Catch a populated file outside the sparse patterns, including when Git
diff --git a/scripts/tests/test_ci_source_inputs.py b/scripts/tests/test_ci_source_inputs.py
index a5e16ebe5..6150ec433 100644
--- a/scripts/tests/test_ci_source_inputs.py
+++ b/scripts/tests/test_ci_source_inputs.py
@@ -17,11 +17,13 @@ class SourceInputTests(unittest.TestCase):
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
for name in (".github/workflows/ci.yml", "scripts/check.py", "desktop/scripts/upload.sh",
- "desktop/lib/main.dart", "desktop/test/app_test.dart", "cli/main.ts", "docs/guide.md",
+ "desktop/lib/main.dart", "desktop/test/app_test.dart", "cli/main.ts", "backend/.gitignore",
+ "backend/scripts/release-be.sh", "docs/guide.md",
"tests/fixtures/layout.json", "daemons/frames.json", "store/catalog.json", "docs/images/poster.png"):
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("fixture\n")
+ (self.root / "backend/.gitignore").write_text("*.log\n") # its own blob, never in the sparse checkout
self.git("init", "-q")
self.git("add", ".")
self.git("-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-qm", "source")
@@ -82,6 +84,58 @@ class SourceInputTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "clean"):
inputs.verify_checkout(self.root, "process")
+ def blobless_sparse_clone(self):
+ # CI's process checkout: sparse, depth 1 and --filter=blob:none, so blobs
+ # outside the sparse patterns (backend/.gitignore here) are never fetched.
+ self.git("config", "uploadpack.allowFilter", "true")
+ outside = tempfile.TemporaryDirectory()
+ self.addCleanup(outside.cleanup)
+ clone = Path(outside.name) / "clone"
+ subprocess.run(["git", "clone", "-q", "--filter=blob:none", "--no-checkout", "--depth=1",
+ self.root.as_uri(), str(clone)], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ subprocess.run(["git", "config", "core.sparseCheckout", "true"], cwd=clone, check=True)
+ (clone / ".git/info/sparse-checkout").write_text(
+ "".join("/" + path + "\n" for path in inputs.ci.SOURCE_INPUTS["process"]))
+ subprocess.run(["git", "checkout", "-q", "--force", self.sha], cwd=clone, check=True,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ # Any lazy fetch from here on fails, as a slow GitHub fetch would time out.
+ subprocess.run(["git", "remote", "set-url", "origin", (Path(outside.name) / "gone").as_uri()],
+ cwd=clone, check=True)
+ return clone
+
+ def test_blobless_sparse_checkout_is_verified_without_fetching_blobs(self):
+ clone = self.blobless_sparse_clone()
+ self.assertTrue((clone / "backend/scripts/release-be.sh").exists())
+ self.assertFalse((clone / "backend/.gitignore").exists())
+ inputs.verify_checkout(clone, "process")
+ (clone / "scripts/check.py").write_text("dirty\n")
+ with self.assertRaisesRegex(ValueError, "clean"):
+ inputs.verify_checkout(clone, "process")
+
+ def test_every_git_call_has_a_timeout(self):
+ self.sparse(inputs.ci.SOURCE_INPUTS["process"])
+ real, timeouts = subprocess.check_output, []
+ def recording(cmd, *args, **kwargs):
+ if cmd[0] == "git":
+ timeouts.append((cmd[1], kwargs.get("timeout")))
+ return real(cmd, *args, **kwargs)
+ with mock.patch.object(inputs.subprocess, "check_output", side_effect=recording):
+ inputs.verify_checkout(self.root, "process")
+ self.assertIn("status", [name for name, _ in timeouts])
+ for name, timeout in timeouts:
+ self.assertIsNotNone(timeout, name)
+
+ def test_a_hung_git_still_fails_the_check(self):
+ self.sparse(inputs.ci.SOURCE_INPUTS["process"])
+ real = subprocess.check_output
+ def hung_status(cmd, *args, **kwargs):
+ if cmd[:2] == ["git", "status"]:
+ raise subprocess.TimeoutExpired(cmd, kwargs["timeout"])
+ return real(cmd, *args, **kwargs)
+ with mock.patch.object(inputs.subprocess, "check_output", side_effect=hung_status):
+ with self.assertRaises(subprocess.TimeoutExpired):
+ inputs.verify_checkout(self.root, "process")
+
def test_capture_binds_git_objects_to_the_real_source_run_and_attempt(self):
self.sparse(inputs.ci.SOURCE_INPUTS["process"])
with mock.patch.dict(os.environ, GITHUB_SHA=self.sha, CI_SOURCE_SHA=self.sha,