The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Phone project screen (Swarm Home C): Chat and Team, Tasks on top, New messages, Jump to latest, Approve asks first (#2259)
harness-for-autonomous[bot]d75cf3e69613
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex 9bce38d79..b7f92a0e3 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -85,6 +85,11 @@ class SuperTabAgent {),avatar = SuperTabAvatarPicture.fromJson(row['avatar']),downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),+ workDecision = switch (row['workDecision']) {+ final String decision when _workDecisions.contains(decision) =>+ decision,+ _ => null,+ },confidential = row['confidential'] == true,configuration = Map.unmodifiable(superTabMap(row['configuration']));final String id, projectId, name, machineId, harnessId, contributorId;@@ -104,6 +109,13 @@ class SuperTabAgent {/// while it runs.final DateTime? downSince;+ /// What its project's Lead decided once its work was over (backend+ /// model.ts `workDecision`): `awaiting` a decision, kept (`keep`) for more+ /// work, or `stop`ped. Null while it has not finished any.+ final String? workDecision;++ static const _workDecisions = {'awaiting', 'keep', 'stop'};+/// The account whose computer runs it; a contributor may run agents on a computer another account shared with them.final String machineOwnerId;diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex e972050b0..59a5c5488 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -36,11 +36,13 @@ import 'swarm_need_rows.dart';import 'swarm_profile_sheet.dart';import 'swarm_project_page.dart';import 'swarm_reactions.dart';+import 'swarm_read_marks.dart';import 'swarm_session.dart';import 'swarm_style.dart';import 'swarm_thread.dart';import 'swarm_thread_line.dart';import 'swarm_thread_page.dart';+import 'swarm_unread_line.dart';import 'swarm_voice.dart';import 'team_glance.dart';@@ -110,6 +112,7 @@ class SwarmConversationPage extends StatefulWidget {this.messageId,this.decisionId,this.mention,+ this.homeC = false,});final String swarmId, conversationId;@@ -129,6 +132,13 @@ 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; and Jump to latest while they read more than a+ /// screen back.+ final bool homeC;+@overrideState<SwarmConversationPage> createState() => _SwarmConversationPageState();}@@ -194,9 +204,27 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// says how many. Null at the foot.final _held = ValueNotifier<String?>(null);+ /// Swarm Home C: the person reads more than a screen back, where Jump to+ /// latest is offered.+ final _farBack = ValueNotifier<bool>(false);+/// 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.+ String? _lineAt;+ bool _lineDecided = false;++ /// The read marks the line waits on: the phone's, not read back yet when+ /// the chat's first read came ([_placeLine]).+ SwarmReadMarks? _marksAwaited;+ final _lineKey = GlobalKey(debugLabel: 'New messages line');++ /// No message has this id: held at it, a chat reads nothing until its New+ /// messages line is placed ([SwarmConversation.heldAt]).+ static const _undecided = '';+/// What [_shown] was made from; the messages by id, and each entry's/// place in [_shown] by its key.Object? _madeFrom;@@ -262,12 +290,16 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>session.inbox.removeListener(_attach);// Set before what the chat kept is shown, so it is read only as far as// it is seen: opened at a message, through it until the person goes- // down to the foot.+ // down to the foot; with a New messages line to place, nothing until it+ // is placed.final c = _conversation = SwarmConversation(reader,widget.conversationId,shown: _seen,- heldAt: widget.messageId ?? _held.value,+ heldAt:+ widget.messageId ??+ _held.value ??+ (widget.homeC && !_lineDecided ? _undecided : null),);c.composer.addListener(_drafted);if (widget.mention case final agentId?) c.mention(agentId);@@ -277,6 +309,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_watch();unawaited(c.load().then((_) {+ _placeLine(c);if (!mounted || _conversation != c || _noticeHandled) return;if (widget.messageId case final messageId?) {_noticeHandled = true;@@ -287,6 +320,102 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>if (rebuild && mounted) setState(() {});}+ /// Places Swarm Home C'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+ /// the screen opens the chat at it ([_openAtLine]), unless a notice opened+ /// it at a message.+ void _placeLine(SwarmConversation c) {+ if (!mounted || _conversation != c || _lineDecided || !widget.homeC) {+ return;+ }+ final marks = c.reader.readMarks;+ if (marks != null && !marks.loaded) {+ if (_marksAwaited != marks) {+ _stopAwaitingMarks();+ _marksAwaited = marks..addListener(_marksMoved);+ }+ return;+ }+ _stopAwaitingMarks();+ _lineDecided = true;+ final at = swarmFirstUnread(+ c.messages,+ c.reader.readMarks?.readThrough(c.id),+ accountId: c.reader.accountId,+ hasOlder: c.hasOlder,+ );+ if (at == null) {+ if (c.heldAt == _undecided) c.heldAt = null;+ return;+ }+ setState(() => _lineAt = at);+ if (widget.messageId == null) _openAtLine(c, at, 0);+ }++ /// The marks the line waits on moved: back, it is placed. Only the chat's+ /// first read waits on them, so that read is in.+ void _marksMoved() {+ if (_conversation case final c?) _placeLine(c);+ }++ void _stopAwaitingMarks() {+ _marksAwaited?.removeListener(_marksMoved);+ _marksAwaited = null;+ }++ /// Once the line is drawn: on screen, all that is shown is read; above+ /// it, the chat goes to the line, and what came before the line is read+ /// while the rest waits until the person goes down to it. The list builds+ /// only the rows near what is shown, so it jumps near the line by its place+ /// until its row is built, as [_reveal] does.+ void _openAtLine(SwarmConversation c, String at, int attempt) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || _conversation != c || _lineAt != at) return;+ final row = _lineKey.currentContext;+ if (attempt == 0) {+ if (row != null && _onScreen(row)) {+ if (c.heldAt == _undecided) c.heldAt = null;+ return;+ }+ final place = c.messages.indexWhere((m) => m.id == at);+ if (place > 0 && c.heldAt == _undecided) {+ c.heldAt = c.messages[place - 1].id;+ }+ }+ if (row != null) {+ unawaited(Scrollable.ensureVisible(row, alignment: 1));+ return;+ }+ final index = _shown.indexWhere((entry) => entry is _LineEntry);+ if (!_scroll.hasClients || index < 0 || attempt > 20) return;+ final position = _scroll.position;+ position.jumpTo(+ (position.maxScrollExtent * (index + 1) / _shown.length).clamp(+ 0,+ position.maxScrollExtent,+ ),+ );+ _openAtLine(c, at, attempt + 1);+ });+ WidgetsBinding.instance.scheduleFrame();+ }++ /// Whether [row]'s top is inside its list: the list runs from the foot, so+ /// a row drawn there is on screen unless it starts above the list's top.+ static bool _onScreen(BuildContext row) {+ final box = row.findRenderObject(), list = Scrollable.maybeOf(row);+ final view = list?.context.findRenderObject();+ if (box is! RenderBox || view is! RenderBox) return false;+ if (!box.hasSize || !view.hasSize) return false;+ return box.localToGlobal(Offset.zero).dy >=+ view.localToGlobal(Offset.zero).dy;+ }+/// Its Swarm is watched while the chat is open and visible, so it is read/// every few seconds only then ([SwarmSession.watch]).void _watch() {@@ -350,6 +479,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_buddy = null;_rows.clear();_madeFrom = null;+ _lineAt = null;+ _lineDecided = false;+ _stopAwaitingMarks();if (_watching) session?.unwatch(widget.swarmId);_watching = false;_conversation = null;@@ -364,6 +496,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_voice?.dispose();_view.dispose();_held.dispose();+ _farBack.dispose();_litTimer?.cancel();_text.dispose();_focus.dispose();@@ -421,6 +554,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_nearTop();if (!_scroll.hasClients) return;final back = _scroll.offset > _readingBack;+ if (widget.homeC) {+ _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?) {@@ -888,9 +1024,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>right: 0,bottom: 8,child: ListenableBuilder(- listenable: Listenable.merge([c, _held]),+ listenable: Listenable.merge([c, _held, _farBack]),builder: (context, _) => switch (_waiting(c)) {- 0 => const SizedBox.shrink(),+ 0 when !_farBack.value => const SizedBox.shrink(),final count => Center(child: _NewPill(count: count, onTap: _toFoot),),@@ -1093,6 +1229,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>c.hasOlder,_held.value,answered.join(','),+ _lineAt,);if (from != _madeFrom) {// Read back: the messages after the newest shown then wait below, and@@ -1109,7 +1246,12 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>for (final need in view.decisions)if (!(need.decision.createdAt?.isAfter(last) ?? false)) need,];- _shown = _timeline(shown, asks, hasOlder: c.hasOlder).reversed.toList();+ _shown = _timeline(+ shown,+ asks,+ hasOlder: c.hasOlder,+ lineAt: _lineAt,+ ).reversed.toList();// Every message read, for the quotes._byId = {for (final m in c.messages) m.id: m};_placeOf = {for (final (i, entry) in _shown.indexed) _keyOf(entry): i};@@ -1130,6 +1272,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>Widget entry(_Entry entry) {final key = _keyOf(entry);switch (entry) {+ case _LineEntry():+ return _row(key, const (), () => SwarmNewMessagesLine(key: _lineKey));case _DayEntry(:final day):final today = DateUtils.dateOnly(DateTime.now());return _row(key, (day, today), () => _Day(day: day, today: today));@@ -1252,6 +1396,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>onReact: view.canPost? (emoji) => unawaited(c.react(m, emoji)): null,+ onAdd: widget.homeC && view.canPost+ ? () => unawaited(_pickReaction(c, m.id))+ : null,),onLongPress: view.canPost? () => unawaited(_pickReaction(c, m.id))@@ -1369,6 +1516,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// The key a row of [entry] keeps wherever it moves in the list.static String _keyOf(_Entry entry) => switch (entry) {+ _LineEntry() => 'swarm-new-messages-line',_DayEntry(:final day) => 'swarm-row-day-${day.toIso8601String()}',_MessageEntry(:final message) => 'swarm-row-m-${message.id}',_AskEntry(:final need) => 'swarm-row-${need.key}',@@ -1767,6 +1915,9 @@ class _ChatView {/// One row of the chat.sealed class _Entry {}+/// Swarm Home C's New messages line, above the first unread message.+final class _LineEntry extends _Entry {}+/// Where a day starts.final class _DayEntry extends _Entry {_DayEntry(this.day);@@ -1793,11 +1944,14 @@ final class _AskEntry extends _Entry {/// [messages] (oldest first) with the [asks] put where they were asked and a/// divider where each day starts. An ask from before the messages read so far/// — while there are [hasOlder] ones — goes at the foot instead, so a question-/// still open is never out of sight behind "Earlier messages".+/// still open is never out of sight behind "Earlier messages". The New+/// messages line goes right above [lineAt], which is then drawn in full, not+/// as a follow-up of the one before.List<_Entry> _timeline(List<SuperTabMessage> messages,List<SwarmDecisionNeed> asks, {required bool hasOlder,+ String? lineAt,}) {final grouped = swarmGroupedMessages(messages);final oldest = messages.map((m) => m.createdAt).nonNulls.firstOrNull;@@ -1840,7 +1994,8 @@ List<_Entry> _timeline(ask(waiting[next]);next++;}- // Grouped only right under a message: not under a question.+ if (m.id == lineAt) rows.add((_LineEntry(), m.createdAt));+ // Grouped only right under a message: not under a question or the line.final under = rows.isNotEmpty && rows.last.$1 is _MessageEntry;rows.add((_MessageEntry(m, grouped: under && grouped.contains(m.id)),@@ -2081,8 +2236,9 @@ class _Day extends StatelessWidget {}}-/// How many messages arrived below while the person read back; a tap goes-/// down to them.+/// 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);+/// a tap goes down to the foot.class _NewPill extends StatelessWidget {const _NewPill({required this.count, required this.onTap});@@ -2094,10 +2250,14 @@ class _NewPill extends StatelessWidget {@overrideWidget build(BuildContext context) => Semantics(button: true,- label: count == 1 ? '1 new message' : '$count new messages',+ label: count == 0+ ? 'Jump to latest'+ : count == 1+ ? '1 new message'+ : '$count new messages',excludeSemantics: true,child: GestureDetector(- key: const ValueKey('swarm-new-pill'),+ key: ValueKey(count == 0 ? 'swarm-jump-latest' : 'swarm-new-pill'),behavior: HitTestBehavior.opaque,onTap: onTap,// 44 to tap, 36 to see.@@ -2118,7 +2278,7 @@ class _NewPill extends StatelessWidget {const Icon(LucideIcons.arrowDown, size: 16, color: AppInk.onFill),const SizedBox(width: 6),Text(- '$count new',+ count == 0 ? 'Jump to latest' : '$count new',style: swarmChatText(14,color: AppInk.onFill,diff --git a/mobile/lib/swarm/swarm_leaderboard.dart b/mobile/lib/swarm/swarm_leaderboard.dartindex 6f77b4478..178bb3b31 100644--- a/mobile/lib/swarm/swarm_leaderboard.dart+++ b/mobile/lib/swarm/swarm_leaderboard.dart@@ -246,11 +246,11 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {own: score.personId == viewer,columns: columns!,onTap: () => unawaited(- _showPerson(+ showSwarmPersonWeek(context,- score,- personOf(score.personId),- nameOf(score),+ score: score,+ person: personOf(score.personId),+ name: nameOf(score),),),),@@ -287,21 +287,28 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {if (week == null || !mounted) return;await reader.showWeek(week == current ? null : week);}+}- /// [score]'s week in a sheet, as the desktop shows it when a name is- /// clicked.- Future<void> _showPerson(- BuildContext context,- SwarmScore score,- SuperTabPerson? person,- String name,- ) => showModalBottomSheet<void>(- context: context,- isScrollControlled: true,- backgroundColor: AppGlass.rowFill,- showDragHandle: true,- shape: AppControl.sheetShape,- builder: (context) => _Sheet(+/// [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, for a screen that must close it itself.+Future<void> showSwarmPersonWeek(+ BuildContext context, {+ required SwarmScore score,+ required SuperTabPerson? person,+ required String name,+ ValueChanged<ModalRoute<void>>? opened,+}) => showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: AppGlass.rowFill,+ showDragHandle: true,+ shape: AppControl.sheetShape,+ builder: (context) {+ if (ModalRoute.of(context) case final ModalRoute<void> route?) {+ opened?.call(route);+ }+ return _Sheet(key: const ValueKey('swarm-leaderboard-sheet'),title: name,leading: SwarmAvatar(@@ -314,9 +321,9 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {for (final (label, value) in swarmPersonWeek(score))_WeekLine(label: label, value: value),],- ),- );-}+ );+ },+);/// Figures of one width, so a column of numbers holds row under row.const _figures = [FontFeature.tabularFigures()];@@ -328,7 +335,7 @@ TextStyle _rankStyle() => AppType.label(color: AppPalette.textSecondary,fontFeatures: _figures,);-TextStyle _pointsStyle() => AppType.label(+TextStyle swarmPointsStyle() => AppType.label(fontWeight: FontWeight.w600,color: AppPalette.textPrimary,fontFeatures: _figures,@@ -413,7 +420,7 @@ class _Columns {rank: width(widest(scores.map((score) => score.rank)), _rankStyle()),points: width(widest(scores.map((score) => score.points)),- _pointsStyle(),+ swarmPointsStyle(),),trend: changes.isEmpty? null@@ -537,7 +544,11 @@ class _PersonRow extends StatelessWidget {column('points',columns.points,- Text('${score.points}', maxLines: 1, style: _pointsStyle()),+ Text(+ '${score.points}',+ maxLines: 1,+ style: swarmPointsStyle(),+ ),),],),diff --git a/mobile/lib/swarm/swarm_project_page.dart b/mobile/lib/swarm/swarm_project_page.dartindex fdd046b6f..9eac0e09a 100644--- a/mobile/lib/swarm/swarm_project_page.dart+++ b/mobile/lib/swarm/swarm_project_page.dart@@ -23,6 +23,7 @@ import 'swarm_message_row.dart';import 'swarm_pm_chat.dart';import 'swarm_project_tabs.dart';import 'swarm_project_tasks.dart';+import 'swarm_project_team.dart';import 'swarm_reader.dart';import 'swarm_row.dart';import 'swarm_session.dart';@@ -78,15 +79,20 @@ Set<String> swarmWaitingOnYou(SwarmInbox inbox, String swarmId) => {/// One project, as Tony's prototype B2 draws it (2026-10-29): a header with/// back, the project's name over its team in coloured dots, and its team at/// the end ([showSwarmProjectSheet]); under it four tabs-/// ([SwarmProjectTab]) — its chat with everyone, the person's Buddy chat,-/// its tasks ([SwarmProjectTasks]) and its leaderboard. Only the tab shown-/// is built: a chat out of sight reads nothing and marks nothing read.+/// ([SwarmProjectTab.homeB]) — its chat with everyone, the person's Buddy+/// chat, its tasks ([SwarmProjectTasks]) and its leaderboard. Swarm Home C+/// (Tony, 2026-10-30) has two ([SwarmProjectTab.homeC]): its chat and its+/// team, under its #name over how many humans and agents it has and what+/// they are doing; the team is a tab there, so the header has no team+/// button. Only the tab shown is built: a chat out of sight reads nothing+/// and marks nothing read.class SwarmProjectPage extends StatefulWidget {const SwarmProjectPage({super.key,required this.swarmId,required this.projectId,this.tab = SwarmProjectTab.chat,+ this.tabs = SwarmProjectTab.homeB,this.mention,});@@ -95,6 +101,9 @@ class SwarmProjectPage extends StatefulWidget {/// The tab it opens on.final SwarmProjectTab tab;+ /// The tabs it has.+ final List<SwarmProjectTab> tabs;+/// An agent to @mention in the chat's draft as it opens/// ([SwarmConversationPage.mention]).final String? mention;@@ -105,7 +114,12 @@ class SwarmProjectPage extends StatefulWidget {class _SwarmProjectPageState extends State<SwarmProjectPage> {SwarmSession? _session;- late SwarmProjectTab _tab = widget.tab;+ late SwarmProjectTab _tab = widget.tabs.contains(widget.tab)+ ? widget.tab+ : widget.tabs.first;++ /// Swarm Home C's page: Chat and Team.+ bool get _homeC => widget.tabs.contains(SwarmProjectTab.team);/// What the page shows of the inbox ([_inboxChanged]): its Swarm's/// reader, whether there are several Swarms, why the list was not read.@@ -211,7 +225,9 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {/// The header: back, [project]'s name over its team — "Updating…" while/// counted from the Home kept, and with several Swarms which one — and the- /// team at its end, after Remove Buddy on the Buddy tab.+ /// team at its end, after Remove Buddy on the Buddy tab. Swarm Home C+ /// writes the name as a channel's, #name, puts how many humans and agents+ /// before the team's dots, and has no team button: Team is a tab.Widget _header(SwarmSession session,SwarmReader reader,@@ -220,9 +236,16 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {Widget back,) {final kept = swarmHomeKept(reader);+ final glance = swarmTeamGlance(snapshot, projectId: project.id);+ final heads = _homeC+ ? swarmProjectHeads(+ humans: swarmProjectPeople(snapshot, project).length,+ agents: glance.agents.length,+ )+ : null;return SwarmTopBar(leading: back,- title: project.name,+ title: _homeC ? '#${project.name}' : project.name,line: KeyedSubtree(key: const ValueKey('swarm-project-team-line'),child: kept@@ -235,8 +258,11 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {),): SwarmTeamDots(- swarmTeamGlance(snapshot, projectId: project.id),- lead: _several ? snapshot.name : null,+ glance,+ lead: switch ([if (_several) snapshot.name, ?heads]) {+ final words when words.isNotEmpty => words.join(' · '),+ _ => null,+ },),),trailing: Row(@@ -244,12 +270,13 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {children: [if (_tab == SwarmProjectTab.buddy && _buddy != null)SwarmBuddyMenuButton(actions: _buddy!),- SwarmIconButton(- key: const ValueKey('swarm-project-team'),- icon: LucideIcons.users300,- label: 'Team',- onPressed: _openTeam,- ),+ if (!_homeC)+ SwarmIconButton(+ key: const ValueKey('swarm-project-team'),+ icon: LucideIcons.users300,+ label: 'Team',+ onPressed: _openTeam,+ ),],),);@@ -290,6 +317,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {conversationId: project.leadConversationId,header: false,mention: widget.mention,+ homeC: _homeC,),SwarmProjectTab.buddy => SwarmProjectBuddy(reader: reader,@@ -308,6 +336,12 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {projectId: project.id,header: false,),+ SwarmProjectTab.team => SwarmProjectTeam(+ session: session,+ reader: reader,+ projectId: project.id,+ onOpen: _open,+ ),};@override@@ -344,6 +378,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {ListenableBuilder(listenable: asks ?? Listenable.merge(const []),builder: (context, _) => SwarmProjectTabBar(+ tabs: widget.tabs,selected: _tab,chatNews: chat == null || _tab == SwarmProjectTab.chat? swarmNoNewsdiff --git a/mobile/lib/swarm/swarm_project_tabs.dart b/mobile/lib/swarm/swarm_project_tabs.dartindex 2b099b0df..e5ed4f15d 100644--- a/mobile/lib/swarm/swarm_project_tabs.dart+++ b/mobile/lib/swarm/swarm_project_tabs.dart@@ -17,20 +17,26 @@ import 'swarm_row.dart';import 'swarm_style.dart';import 'swarm_unread.dart';-/// A project's tabs, as B2 draws them (Tony, 2026-10-29): its chat with-/// everyone, the person's Buddy chat, its tasks and its leaderboard.+/// A project's tabs: as B2 draws them (Tony, 2026-10-29), its chat with+/// everyone, the person's Buddy chat, its tasks and its leaderboard+/// ([homeB]); as Swarm Home C draws them (Tony, 2026-10-30), its chat and its+/// team ([homeC]).enum SwarmProjectTab {chat('Chat'),buddy('Buddy'),tasks('Tasks'),- leaderboard('Leaderboard');+ leaderboard('Leaderboard'),+ team('Team');const SwarmProjectTab(this.label);final String label;++ static const homeB = [chat, buddy, tasks, leaderboard];+ static const homeC = [chat, team];}-/// The row of a project's tabs under its header: each a quarter of the+/// The row of a project's [tabs] under its header: each an equal share of the/// width, the one shown bright over a line, the others quiet. The chat's/// says what is new in it as a project's Home row does: the Lead's tags/// waiting there in a filled "@N", else a dot while it is unread@@ -40,9 +46,11 @@ class SwarmProjectTabBar extends StatelessWidget {super.key,required this.selected,required this.onSelect,+ this.tabs = SwarmProjectTab.homeB,this.chatNews = swarmNoNews,});+ final List<SwarmProjectTab> tabs;final SwarmProjectTab selected;final ValueChanged<SwarmProjectTab> onSelect;final SwarmRowNews chatNews;@@ -58,7 +66,7 @@ class SwarmProjectTabBar extends StatelessWidget {padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),child: Row(children: [- for (final tab in SwarmProjectTab.values)+ for (final tab in tabs)Expanded(child: _Tab(tab: tab,diff --git a/mobile/lib/swarm/swarm_project_tasks.dart b/mobile/lib/swarm/swarm_project_tasks.dartindex 143b5abe0..279f478d2 100644--- a/mobile/lib/swarm/swarm_project_tasks.dart+++ b/mobile/lib/swarm/swarm_project_tasks.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:clock/clock.dart';import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';@@ -8,6 +10,7 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/theme/app_theme.dart' show AppColors;import 'model.dart';+import 'swarm_activity_page.dart' show confirmSwarmApprove;import 'swarm_home_rows.dart';import 'swarm_inbox.dart';import 'swarm_need_rows.dart';@@ -451,16 +454,31 @@ class SwarmWaitingRow extends StatelessWidget {decision.recommended >= decision.options.length) {return (null, reply);}+ final option = swarmOption(decision.options, decision.recommended);return (session.dropped(need) ? 'Not sent, choose again.' : null,SwarmButton(key: ValueKey('swarm-approve-${decision.id}'),- label: swarmOption(decision.options, decision.recommended),+ label: option,style: SwarmButtonStyle.fill,- onPressed: () => session.hold(need, decision.recommended),+ onPressed: () => unawaited(_approve(context, need, option)),),);}++ /// Approve asks first ([confirmSwarmApprove]); confirmed, the recommended+ /// answer is held for Undo and then sent — unless meanwhile its row went:+ /// the decision left the person's list (answered elsewhere, or access+ /// taken away).+ Future<void> _approve(+ BuildContext context,+ SwarmDecisionNeed need,+ String option,+ ) async {+ if (!await confirmSwarmApprove(context, need, option)) return;+ if (!context.mounted) return;+ session.hold(need, need.decision.recommended);+ }}/// What waits on the person: a small dot in the warning colour.diff --git a/mobile/lib/swarm/swarm_project_team.dart b/mobile/lib/swarm/swarm_project_team.dartnew file mode 100644index 000000000..03e69412d--- /dev/null+++ b/mobile/lib/swarm/swarm_project_team.dart@@ -0,0 +1,647 @@+import 'dart:async';++import 'package:clock/clock.dart';+import 'package:flutter/material.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/shared/widgets/touch_target.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'identity.dart';+import 'model.dart';+import 'swarm_leaderboard.dart';+import 'swarm_leaderboard_reader.dart';+import 'swarm_project_tasks.dart';+import 'swarm_reader.dart';+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';+import 'swarm_task_status.dart';+import 'team_glance.dart';++/// The people of [project] in [snapshot]: everyone in the Swarm, or, for a+/// private project, only its owner and members — the people who read it.+List<SuperTabPerson> swarmProjectPeople(+ SuperTabSnapshot snapshot,+ SuperTabProject project,+) => [+ for (final person in snapshot.people)+ if (!project.isPrivate ||+ person.id == project.ownerId ||+ project.memberIds.contains(person.id))+ person,+];++/// "3 humans · 5 agents", the people and agents of a project in words; the+/// agents left out when there are none, as the team's line then says so.+String swarmProjectHeads({required int humans, required int agents}) => [+ humans == 1 ? '1 human' : '$humans humans',+ if (agents > 0) agents == 1 ? '1 agent' : '$agents agents',+].join(' · ');++/// An agent's state on a project's Team (Dee, 2026-10-29: every state),+/// in the order the list puts them, the most urgent first: its work needs a+/// person; it waits on a review or a usage limit; it is offline; it is+/// working; it finished and waits on the Product Manager's decision; it is+/// idle; it was stopped. The phone's team glance order ([swarmTeamGlance]),+/// with the states only the Team tells apart.+enum SwarmMemberState {+ needsInput('needs input'),+ waiting('waiting'),+ offline('offline'),+ working('working'),+ done('done'),+ idle('idle'),+ stopped('stopped');++ const SwarmMemberState(this.counted);++ /// How the Team's count names it: "2 working".+ final String counted;+}++/// One agent on a project's Team: its state in a word or two ([label]) and+/// the open work it holds ([task]).+class SwarmTeamAgent {+ SwarmTeamAgent(this.agent, this.name, this.state, this.label, this.task);+ final SuperTabAgent agent;+ final String name;+ final SwarmMemberState state;+ final String label;+ final SuperTabConversation? task;++ /// Its row's quiet line: "Working · #2156 Buddy chat header".+ String get line => [label, ?task?.label].join(' · ');+}++/// [projectId]'s agents as its Team lists them: each in its state+/// ([SwarmMemberState]), the most urgent first, then by name, letter case+/// aside. Read from the Swarm alone, as the team glance is: an agent is of+/// the project it records or whose work it is in, matched by id, never by+/// name; a Buddy is no one's team. Work it still holds in another project is+/// not named here, nor opened: its state stays, as the glance counts it.+List<SwarmTeamAgent> swarmProjectAgents(+ SuperTabSnapshot snapshot,+ String projectId, {+ DateTime? now,+}) {+ final glance = swarmTeamGlance(snapshot, projectId: projectId, now: now);+ final team = [+ // The read names its Buddies; one it has not named yet says so itself.+ for (final a in glance.agents)+ if (!a.agent.isBuddy) _member(a, projectId),+ ];+ String sortName(SwarmTeamAgent a) => a.name.toLowerCase();+ return team..sort((a, b) {+ final byState = a.state.index.compareTo(b.state.index);+ if (byState != 0) return byState;+ final byName = sortName(a).compareTo(sortName(b));+ return byName != 0 ? byName : a.agent.id.compareTo(b.agent.id);+ });+}++SwarmTeamAgent _member(SwarmAgentGlance glance, String projectId) {+ final agent = glance.agent;+ final work = glance.task?.assignment?['status'];+ // Offline outranks a stop, which outranks the work it still holds.+ final (state, label) = switch (glance.state) {+ SwarmAgentState.down => (SwarmMemberState.offline, 'Offline'),+ _ when agent.workDecision == 'stop' => (+ SwarmMemberState.stopped,+ 'Stopped',+ ),+ SwarmAgentState.waiting => (SwarmMemberState.needsInput, 'Needs input'),+ SwarmAgentState.stuck => (SwarmMemberState.needsInput, 'Stuck'),+ SwarmAgentState.limited => (SwarmMemberState.waiting, glance.label),+ SwarmAgentState.working when work == 'review' => (+ SwarmMemberState.waiting,+ 'Waiting for review',+ ),+ SwarmAgentState.working => (SwarmMemberState.working, glance.label),+ SwarmAgentState.idle when agent.workDecision == 'awaiting' => (+ SwarmMemberState.done,+ 'Done',+ ),+ SwarmAgentState.idle => (SwarmMemberState.idle, 'Idle'),+ };+ final task = glance.task;+ return SwarmTeamAgent(+ agent,+ glance.name,+ state,+ label,+ task?.projectId == projectId ? task : null,+ );+}++/// What on [team] needs a look, counted in the order it is listed: "1 needs+/// input · 1 waiting · 2 working". Done, idle and stopped agents are not+/// counted; empty when nothing is.+String swarmTeamAgentsLine(List<SwarmTeamAgent> team) => [+ for (final state in const [+ SwarmMemberState.needsInput,+ SwarmMemberState.waiting,+ SwarmMemberState.offline,+ SwarmMemberState.working,+ ])+ if (team.where((a) => a.state == state).length case final n when n > 0)+ '$n ${state.counted}',+].join(' · ');++/// The open [tasks] of a project counted as its Team's Tasks caption says+/// them, in the order they are listed: "1 waiting on you · 2 working"; empty+/// when none is open.+String swarmTeamTasksLine(SwarmProjectTaskLists tasks) => [+ if (tasks.waiting.isNotEmpty) '${tasks.waiting.length} waiting on you',+ if (tasks.working.isNotEmpty) '${tasks.working.length} working',+].join(' · ');++/// One person on a project's Team: what they are on now (the status they+/// set, while it lasts), their week's [score] from its board, if the board+/// has answered, and whether they are the viewer.+typedef SwarmTeamHuman = ({+ SuperTabPerson person,+ String name,+ String? now,+ SwarmScore? score,+ bool own,+});++/// [project]'s people ([swarmProjectPeople]) as its Team lists them: by this+/// week's points on [board], most first, then by name, letter case aside —+/// all by name while there is no board. No ranks (Dee, 2026-10-29); each row+/// shows its points beside a line of what earned them, as Desktop's member+/// list does (#2230). Matched by id, never by name.+List<SwarmTeamHuman> swarmProjectHumans(+ SuperTabSnapshot snapshot,+ SuperTabProject project,+ SwarmLeaderboard? board, {+ required String viewer,+ DateTime? now,+}) {+ final at = now ?? clock.now();+ final scores = {+ for (final score in board?.people ?? const <SwarmScore>[])+ score.personId: score,+ };+ final humans = [+ for (final person in swarmProjectPeople(snapshot, project))+ (+ person: person,+ name:+ scores[person.id]?.displayName ?? superTabPersonName(person.email),+ now: switch (person.status) {+ final status? when status.shownAt(at) => status.label,+ _ => null,+ },+ score: scores[person.id],+ own: person.id == viewer,+ ),+ ];+ String sortName(SwarmTeamHuman h) => h.name.toLowerCase();+ int points(SwarmTeamHuman h) => h.score?.points ?? 0;+ return humans..sort((a, b) {+ final byPoints = points(b).compareTo(points(a));+ if (byPoints != 0) return byPoints;+ final byName = sortName(a).compareTo(sortName(b));+ return byName != 0 ? byName : a.person.id.compareTo(b.person.id);+ });+}++/// The colour of [state]'s dot on an agent's face. Never the only signal: the+/// row says the state in words.+Color swarmMemberColor(SwarmMemberState state) => switch (state) {+ SwarmMemberState.needsInput || SwarmMemberState.waiting => AppColors.warning,+ SwarmMemberState.offline => AppColors.danger,+ SwarmMemberState.working => AppColors.success,+ SwarmMemberState.done => AppPalette.swarmAccent,+ SwarmMemberState.idle || SwarmMemberState.stopped => AppPalette.textFaint,+};++/// A project's Team, as Swarm Home C draws it (Tony, 2026-10-30) to Dee's+/// rules (2026-10-29), one row shape for all ([SwarmMemberRow]) and no+/// ranks. On top its open tasks (Tony, 2026-10-30: Home C has no Tasks tab),+/// in the Tasks tab's rows: what waits on the person there, then the work+/// going on ([swarmProjectTasks]), counted beside their caption, each+/// opening its chat ([onOpen]). Then its humans by this week's points, most first, then by name, each+/// opening their week; then its agents, each in its state with the task it+/// holds, the most urgent first ([swarmProjectAgents]), with what needs a look+/// counted beside their caption, each opening the task it holds ([onOpen]).+///+/// The points are the project's leaderboard ([SwarmLeaderboardReader]),+/// read as the tab opens and every few minutes while the app is in front:+/// until it answers the people show without points; a read that failed says+/// why, with Try again. A pull reads the Swarm and the board again. Nothing+/// read for one Swarm or project is shown for another.+class SwarmProjectTeam extends StatefulWidget {+ const SwarmProjectTeam({+ super.key,+ required this.session,+ required this.reader,+ required this.projectId,+ required this.onOpen,+ });++ final SwarmSession session;+ final SwarmReader reader;+ final String projectId;++ /// Opens one of the project's chats, by id.+ final ValueChanged<String> onOpen;++ @override+ State<SwarmProjectTeam> createState() => _SwarmProjectTeamState();+}++class _SwarmProjectTeamState extends State<SwarmProjectTeam> {+ late SwarmLeaderboardReader _board = _read();++ /// The person's week this Team opened, while it is up. What it shows is+ /// the project's: it closes with the Team, and when the read, the Swarm or+ /// the project it was opened from is gone ([_closeWeek]).+ ModalRoute<void>? _week;++ SwarmLeaderboardReader _read() => SwarmLeaderboardReader(+ tabId: widget.reader.tabId,+ projectId: widget.projectId,+ request: widget.reader.request,+ inFront: () => widget.session.inbox.shown,+ )..start();++ @override+ void didUpdateWidget(SwarmProjectTeam old) {+ super.didUpdateWidget(old);+ // Another Swarm's read or another project: none of the last board stays.+ if (old.reader != widget.reader || old.projectId != widget.projectId) {+ _board.dispose();+ _board = _read();+ }+ if (old.session != widget.session ||+ old.reader != widget.reader ||+ old.projectId != widget.projectId) {+ _closeWeek();+ }+ }++ @override+ void dispose() {+ _closeWeek();+ _board.dispose();+ super.dispose();+ }++ void _openWeek(SwarmTeamHuman h, SwarmScore score) {+ ModalRoute<void>? shown;+ unawaited(+ showSwarmPersonWeek(+ context,+ score: score,+ person: h.person,+ name: h.name,+ opened: (route) => _week = shown = route,+ ).whenComplete(() {+ if (_week == shown) _week = null;+ }),+ );+ }++ /// Closes the week open, if any: once this frame is done, as a Team going+ /// away may not change the navigator while it does.+ void _closeWeek() {+ final week = _week;+ _week = null;+ if (week == null) return;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (week.isActive) week.navigator?.removeRoute(week);+ });+ }++ Future<void> _pull() =>+ Future.wait([widget.reader.refresh(), _board.refresh()]);++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final session = widget.session;+ final reader = widget.reader;+ return ListenableBuilder(+ // Needs and held answers move with the session and its inbox; the+ // work and the team with the read; the points with the board.+ listenable: Listenable.merge([session, session.inbox, reader, _board]),+ builder: (context, _) {+ final snapshot = reader.snapshot;+ final project = snapshot?.projects+ .where((p) => p.id == widget.projectId)+ .firstOrNull;+ if (snapshot == null || project == null) {+ _closeWeek();+ return const SizedBox.shrink();+ }+ final now = clock.now();+ final tasks = swarmProjectTasks(session.inbox, reader, project.id, now);+ final personName = swarmTaskPersonName(snapshot);+ final agents = swarmProjectAgents(snapshot, project.id);+ final board = _board.board;+ final humans = swarmProjectHumans(+ snapshot,+ project,+ board,+ viewer: reader.accountId,+ );+ return RefreshIndicator(+ onRefresh: _pull,+ child: ListView(+ key: const ValueKey('swarm-project-team-list'),+ physics: const AlwaysScrollableScrollPhysics(),+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ AppSpace.xs,+ AppSpace.m,+ MediaQuery.paddingOf(context).bottom + AppSpace.xl,+ ),+ children: [+ SwarmCaption(+ 'Tasks',+ key: const ValueKey('swarm-team-tasks-caption'),+ note: swarmTeamTasksLine(tasks),+ first: true,+ ),+ if (tasks.waiting.isEmpty && tasks.working.isEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: SwarmRow.line(+ 'No open tasks.',+ key: const ValueKey('swarm-team-no-tasks'),+ ),+ )+ else+ SwarmGroup(+ children: [+ for (final need in tasks.waiting)+ SwarmWaitingRow(+ key: ValueKey('swarm-waiting-${need.key}'),+ session: session,+ snapshot: snapshot,+ need: need,+ personName: personName,+ now: now,+ onOpen: () => widget.onOpen(need.conversationId),+ ),+ for (final g in tasks.working)+ SwarmWorkRow(+ key: ValueKey('swarm-task-${g.id}'),+ snapshot: snapshot,+ group: g,+ personName: personName,+ onTap: () => widget.onOpen(g.id),+ ),+ ],+ ),+ SwarmCaption(+ 'Humans',+ key: const ValueKey('swarm-team-humans-caption'),+ ),+ if (_board.error case final error? when board == null)+ _BoardError(error: error, onRetry: _board.refresh),+ SwarmGroup(+ children: [+ for (final h in humans)+ SwarmMemberRow(+ key: ValueKey('swarm-member-person-${h.person.id}'),+ face: SwarmAvatar(+ id: h.person.id,+ name: h.name,+ picture: h.person.avatar,+ ),+ name: h.name,+ // As Desktop's member list (#2230): what they are on+ // after the name, what they did this week beneath it,+ // and the week's points at the right.+ tag: switch ([if (h.own) 'you', ?h.now]) {+ final words when words.isNotEmpty => words.join(' · '),+ _ => null,+ },+ detail: switch (h.score) {+ final score? => swarmNumbers(score).join(' · '),+ null => null,+ },+ points: h.score?.points,+ onTap: switch (h.score) {+ final score? => () => _openWeek(h, score),+ null => null,+ },+ ),+ ],+ ),+ SwarmCaption(+ 'Agents',+ key: const ValueKey('swarm-team-agents-caption'),+ note: swarmTeamAgentsLine(agents),+ ),+ if (agents.isEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: SwarmRow.line(+ 'No agents yet.',+ key: const ValueKey('swarm-team-no-agents'),+ ),+ )+ else+ SwarmGroup(+ children: [+ for (final a in agents)+ SwarmMemberRow(+ key: ValueKey('swarm-member-${a.agent.id}'),+ face: SwarmAvatar(+ id: a.agent.id,+ name: a.name,+ picture: a.agent.avatar,+ ),+ dot: swarmMemberColor(a.state),+ name: a.name,+ detail: a.line,+ onTap: switch (a.task) {+ final task? => () => widget.onOpen(task.id),+ null => null,+ },+ ),+ ],+ ),+ ],+ ),+ );+ },+ );+ }+}++/// Why the board was not read, and Try again: one read per tap.+class _BoardError extends StatelessWidget {+ const _BoardError({required this.error, required this.onRetry});++ final String error;+ final Future<void> Function() onRetry;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.fromLTRB(AppSpace.xs, 0, AppSpace.xs, AppSpace.s),+ child: Row(+ children: [+ Expanded(+ child: SwarmRow.line(+ error,+ key: const ValueKey('swarm-team-board-error'),+ lines: 2,+ ),+ ),+ SwarmButton(+ key: const ValueKey('swarm-team-board-retry'),+ label: 'Try again',+ onPressed: () => unawaited(onRetry()),+ ),+ ],+ ),+ );+}++/// One person or agent on a project's Team, in the one shape both share+/// (Dee, 2026-10-29): the face in one column — an agent's with its state's+/// [dot] — the name, a quiet [detail] line beneath, and a person's week's+/// [points] at the right. The same height with or without the line; a tap+/// does [onTap], when there is one.+class SwarmMemberRow extends StatelessWidget {+ const SwarmMemberRow({+ super.key,+ required this.face,+ required this.name,+ this.dot,+ this.tag,+ this.detail,+ this.points,+ this.onTap,+ });++ final Widget face;+ final String name;++ /// A person's points this week, once the board has answered.+ final int? points;++ /// The state's colour on the face's corner: an agent's.+ final Color? dot;++ /// Quiet words after the name: "you" on the viewer's own row.+ final String? tag;+ final String? detail;+ final VoidCallback? onTap;++ static const double _face = 36, _dot = 11;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final dot = this.dot, tag = this.tag, detail = this.detail;+ final points = this.points;+ return Semantics(+ // Its own node, a tap or not: one row, said as one.+ container: true,+ button: onTap != null,+ label: [+ name,+ ?tag,+ if (detail != null && detail.isNotEmpty) detail,+ if (points != null) '$points points',+ ].join(', '),+ excludeSemantics: true,+ child: InkWell(+ onTap: onTap,+ child: ConstrainedBox(+ // A name over its line, with or without the line: every row of the+ // Team one height.+ constraints: const BoxConstraints(minHeight: minTouchTarget + 16),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ vertical: AppSpace.s,+ ),+ child: Row(+ children: [+ SizedBox.square(+ dimension: _face,+ child: Stack(+ clipBehavior: Clip.none,+ children: [+ Positioned.fill(child: FittedBox(child: face)),+ if (dot != null)+ Positioned(+ right: -2,+ bottom: -2,+ child: Container(+ width: _dot,+ height: _dot,+ decoration: BoxDecoration(+ color: dot,+ shape: BoxShape.circle,+ border: Border.all(+ color: AppGlass.rowFill,+ width: 2,+ strokeAlign: BorderSide.strokeAlignOutside,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text.rich(+ TextSpan(+ children: [+ TextSpan(text: name),+ if (tag != null)+ TextSpan(+ text: ' $tag',+ style: AppType.caption(+ color: AppPalette.textSecondary,+ ),+ ),+ ],+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.label(color: AppPalette.textPrimary),+ ),+ if (detail != null && detail.isNotEmpty) ...[+ const SizedBox(height: 2),+ Text(+ detail,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.35,+ ),+ ),+ ],+ ],+ ),+ ),+ if (points != null) ...[+ const SizedBox(width: AppSpace.s),+ Text('$points', maxLines: 1, style: swarmPointsStyle()),+ ],+ ],+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_reactions.dart b/mobile/lib/swarm/swarm_reactions.dartindex 0a1950180..2b0913f62 100644--- a/mobile/lib/swarm/swarm_reactions.dart+++ b/mobile/lib/swarm/swarm_reactions.dart@@ -1,5 +1,6 @@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';import 'package:harness_mobile/shared/theme/app_icon_size.dart';@@ -16,7 +17,8 @@ typedef SwarmReactorName = String Function(String kind, String id);/// The counts under a message, as Desktop draws them (`reactions.dart`): each/// emoji and how many gave it, the reader's own marked. A tap takes theirs/// back or adds it; holding one names who gave it. Without [onReact] (a-/// reader who cannot post) the counts only show.+/// reader who cannot post) the counts only show. With [onAdd], an+/// add-reaction chip after the counts opens the picker (Swarm Home C).class SwarmReactionBar extends StatelessWidget {const SwarmReactionBar({super.key,@@ -25,6 +27,7 @@ class SwarmReactionBar extends StatelessWidget {required this.readerId,required this.nameOf,this.onReact,+ this.onAdd,});final String messageId;@@ -32,6 +35,7 @@ class SwarmReactionBar extends StatelessWidget {final String readerId;final SwarmReactorName nameOf;final ValueChanged<SuperTabReactionEmoji>? onReact;+ final VoidCallback? onAdd;@overrideWidget build(BuildContext context) {@@ -52,6 +56,11 @@ class SwarmReactionBar extends StatelessWidget {null => null,},),+ if (onAdd case final add?)+ _AddChip(+ key: ValueKey('swarm-add-reaction-$messageId'),+ onTap: add,+ ),],),);@@ -135,6 +144,50 @@ class _Count extends StatelessWidget {}}+/// After a message's counts: a finger's size to tap, drawn as a count is,+/// with a face and a plus; a tap opens the picker.+class _AddChip extends StatelessWidget {+ const _AddChip({super.key, required this.onTap});++ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Semantics(+ button: true,+ label: 'Add reaction',+ excludeSemantics: true,+ onTap: onTap,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minWidth: 44, minHeight: 44),+ child: Center(+ widthFactor: 1,+ child: Container(+ height: 30,+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),+ decoration: ShapeDecoration(+ color: swarmChatCard(tty),+ shape: StadiumBorder(+ side: BorderSide(color: swarmChatHair(tty)),+ ),+ ),+ child: Icon(+ LucideIcons.smilePlus,+ size: 16,+ color: AppPalette.textSecondary,+ ),+ ),+ ),+ ),+ ),+ );+ }+}+/// Opens the reactions a message can carry in a sheet, with a light tap of/// the phone as a long-press gives: Desktop's seven, the reader's own marked./// Answers the one picked, or null when the sheet closed without one.diff --git a/mobile/lib/swarm/swarm_read_marks.dart b/mobile/lib/swarm/swarm_read_marks.dartindex d56ef087d..16b7e9454 100644--- a/mobile/lib/swarm/swarm_read_marks.dart+++ b/mobile/lib/swarm/swarm_read_marks.dart@@ -117,6 +117,11 @@ class SwarmReadMarks extends ChangeNotifier {String get _key => 'swarm_read_marks.${reader.accountId}.${reader.tabId}';+ /// The phone's marks were read back. Until then [readThrough] has none to+ /// give, which is not a chat with no mark: what waits on a mark waits on+ /// this, and is told when it moves.+ bool get loaded => _loaded;+/// Whether [group] has messages in its main stream past what the person/// has read.bool unread(SuperTabConversation group) {@@ -126,8 +131,9 @@ class SwarmReadMarks extends ChangeNotifier {}/// How far the person has read [conversationId]: the higher of the- /// server's mark and this phone's; null until the phone's are read back.- int? readThrough(String conversationId) => _loaded+ /// server's mark and this phone's; null until the phone's are read back,+ /// and once access is lost.+ int? readThrough(String conversationId) => _loaded && !reader.accessRevoked? max(reader.snapshot?.readMarks[conversationId] ?? 0,_marks[conversationId] ?? 0,diff --git a/mobile/lib/swarm/swarm_style.dart b/mobile/lib/swarm/swarm_style.dartindex 06c91c926..77f732b66 100644--- a/mobile/lib/swarm/swarm_style.dart+++ b/mobile/lib/swarm/swarm_style.dart@@ -239,7 +239,8 @@ class SwarmTabHeader extends StatelessWidget {);}-/// A caption over a card, in sentence case, with maybe a count at its right.+/// A caption over a card, in sentence case, with maybe a count, or a+/// [note], at its right.class SwarmCaption extends StatelessWidget {const SwarmCaption(this.text, {@@ -247,11 +248,16 @@ class SwarmCaption extends StatelessWidget {this.count,this.countColor,this.countKey = const ValueKey('swarm-needs-count'),+ this.note,this.first = false,});final String text;+ /// Quiet words at its right: what the card's column means, or a count in+ /// words ("Points this week", "2 working · 1 waiting").+ final String? note;+/// How many there are: what waits on the person, in the warning colour/// unless [countColor] says otherwise; null shows none.final int? count;@@ -265,6 +271,9 @@ class SwarmCaption extends StatelessWidget {Widget build(BuildContext context) {AppTheme.watch(context);final tty = Tty.of(context);+ final quiet = AppType.caption(+ color: Color.lerp(AppPalette.textFaint, AppPalette.textSecondary, .5),+ );return Padding(padding: EdgeInsets.fromLTRB(AppSpace.xs,@@ -276,18 +285,18 @@ class SwarmCaption extends StatelessWidget {crossAxisAlignment: CrossAxisAlignment.baseline,textBaseline: TextBaseline.alphabetic,children: [- Expanded(- child: Text(- text,- style: AppType.caption(- color: Color.lerp(- AppPalette.textFaint,- AppPalette.textSecondary,- .5,- ),+ Expanded(child: Text(text, style: quiet)),+ if (note case final note? when note.isNotEmpty)+ Flexible(+ flex: 2,+ child: Text(+ note,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.end,+ style: quiet,),),- ),if (count case final count? when count > 0)Text('$count',diff --git a/mobile/lib/swarm/swarm_unread_line.dart b/mobile/lib/swarm/swarm_unread_line.dartnew file mode 100644index 000000000..75bf3e64b--- /dev/null+++ b/mobile/lib/swarm/swarm_unread_line.dart@@ -0,0 +1,67 @@+import 'package:flutter/material.dart';++import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'model.dart';+import 'swarm_message_row.dart' show swarmChatText;++/// The first of [messages] (oldest first, every one read) the person has+/// not read, for the New messages line (Desktop's `superTabFirstUnread`): in+/// the main stream — a reply only in its thread is read there — from someone+/// else, and past both [mark] and the person's own newest message in the+/// chat, since writing in a chat reads what came before it. Null when all is+/// 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.+String? swarmFirstUnread(+ List<SuperTabMessage> messages,+ int? mark, {+ required String accountId,+ required bool hasOlder,+}) {+ if (mark == null || mark <= 0 || messages.isEmpty) return null;+ if (hasOlder && messages.first.sequence > mark + 1) return null;+ bool own(SuperTabMessage m) => !m.fromAgent && m.authorId == accountId;+ var read = mark;+ for (final m in messages) {+ 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;+ }+ return null;+}++/// The line above the first unread message: an accent rule and the words,+/// so colour is never the only signal.+class SwarmNewMessagesLine extends StatelessWidget {+ const SwarmNewMessagesLine({super.key});++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final accent = AppPalette.accentOnSurface;+ return Semantics(+ container: true,+ label: 'New messages',+ excludeSemantics: true,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.screenInset,+ vertical: AppSpace.s,+ ),+ child: Row(+ children: [+ Expanded(child: Divider(height: 1, color: accent)),+ const SizedBox(width: AppSpace.s),+ Text(+ 'New messages',+ style: swarmChatText(13, color: accent, weight: FontWeight.w600),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/test/swarm/swarm_home_test.dart b/mobile/test/swarm/swarm_home_test.dartindex fc014948e..56e6ed4c8 100644--- a/mobile/test/swarm/swarm_home_test.dart+++ b/mobile/test/swarm/swarm_home_test.dart@@ -2107,14 +2107,51 @@ void main() {);});- testWidgets('Approve holds the recommended answer with Undo, then sends '- 'it once', (tester) async {+ testWidgets('Approve asks first, naming the answer, who asked, where and '+ 'the question; Cancel sends nothing', (tester) async {final fake = backend();await pump(tester, fake);await openTasks(tester);await tester.tap(key('swarm-approve-d1'));- await tester.pump();+ await tester.pumpAndSettle();+ expect(find.text('Approve?'), findsOneWidget);+ expect(+ find.text(+ 'Sends “Yes” to River in #Mobile: Ship it behind a flag?\n\n'+ 'You can undo it for a few seconds.',+ ),+ findsOneWidget,+ );+ expect(+ inside('swarm-waiting-decision:d1', find.text('Sending “Yes”')),+ findsNothing,+ reason: 'nothing is held until the person confirms',+ );++ await tester.tap(key('swarm-activity-approve-cancel'));+ await tester.pumpAndSettle();+ expect(find.text('Approve?'), findsNothing);+ expect(key('swarm-approve-d1'), findsOneWidget);+ await tester.pump(const Duration(seconds: 5));+ await tester.pumpAndSettle();+ expect(fake.commands, isEmpty);+ });++ testWidgets('Approve, confirmed, holds the recommended answer with Undo, '+ 'then sends it once', (tester) async {+ final fake = backend();+ await pump(tester, fake);+ await openTasks(tester);++ Future<void> approve() async {+ await tester.tap(key('swarm-approve-d1'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-activity-approve-confirm'));+ await tester.pumpAndSettle();+ }++ await approve();expect(inside('swarm-waiting-decision:d1', find.text('Sending “Yes”')),findsOneWidget,@@ -2125,7 +2162,7 @@ void main() {await tester.pump(const Duration(seconds: 4));expect(fake.commands, isEmpty);- await tester.tap(key('swarm-approve-d1'));+ await approve();await tester.pump(const Duration(seconds: 2));expect(fake.commands, isEmpty, reason: 'Undo still can');await tester.pump(const Duration(seconds: 2));diff --git a/mobile/test/swarm/swarm_project_c_shots_test.dart b/mobile/test/swarm/swarm_project_c_shots_test.dartnew file mode 100644index 000000000..e8bc8eb73--- /dev/null+++ b/mobile/test/swarm/swarm_project_c_shots_test.dart@@ -0,0 +1,334 @@+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_project_page.dart';+import 'package:harness_mobile/swarm/swarm_project_tabs.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Review screenshots of a project's screen in Swarm Home C, as Tony's+/// prototype draws it (2026-10-30): its Chat with the New messages line,+/// a task card and a PR card, a code block, reactions with the add-reaction+/// chip and a replies row; its Team with open tasks on top, the humans with+/// their week and points, and the agents in their states; and Approve's+/// question. On a 390-point phone in both phone themes, from made-up data+/// only, to the folder `SWARM_PROJECT_C_SHOTS` names.+final shots = Platform.environment['SWARM_PROJECT_C_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('the project screen, its Chat and Team, in both phone themes', (+ tester,+ ) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ // An iPhone's status bar and home indicator.+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);+ addTearDown(tester.view.resetPadding);+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final now = DateTime.now().toUtc();+ String ago(int minutes) =>+ now.subtract(Duration(minutes: minutes)).toIso8601String();+ const pr = 'https://github.com/example/app/pull/2161';+ Map<String, dynamic> said(+ String id,+ int sequence,+ String text, {+ String author = 'agent-lead',+ String kind = 'agent',+ String name = 'River',+ Map<String, List<(String, String)>> reactions = const {},+ }) => {+ 'id': id,+ 'conversationId': leadChat,+ 'text': text,+ 'sequence': sequence,+ 'thread': id,+ 'author': {'kind': kind, 'id': author, 'name': name},+ 'reactions': [+ for (final MapEntry(key: emoji, value: by) in reactions.entries)+ {+ 'emoji': emoji,+ 'count': by.length,+ 'by': [+ for (final (kind, who) in by) {'kind': kind, 'id': who},+ ],+ },+ ],+ 'createdAt': ago(40 - sequence * 4),+ };+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Autonomous', 'ownerId': me},+ ],+ 'next': null,+ };+ const derived = {+ 'decisionsWaiting': 1,+ 'readMarks': {leadChat: 5},+ };+ final load = firstLoad(+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ agent('agent-juno', displayName: 'Juno'),+ agent('agent-ash', displayName: 'Ash'),+ {...agent('agent-wren', displayName: 'Wren'), 'workDecision': 'stop'},+ ],+ groups: [+ groupData(+ 'g1',+ title: 'Buddy chat header',+ number: 2156,+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ workerId: 'agent-builder',+ lastMessageSequence: 3,+ ),+ groupData(+ 'g2',+ title: 'Saved views cache',+ number: 2160,+ agentIds: ['agent-lead', 'agent-juno'],+ status: 'needs_human',+ workerId: 'agent-juno',+ lastMessageSequence: 4,+ ),+ ],+ derived: derived,+ );+ final groups = load['groups'] as List;+ // When each chat last moved: Juno's ask a few minutes ago.+ for (final row in groups.cast<Map>()) {+ row['changedAt'] = now+ .subtract(Duration(minutes: row['key'] == 'g2' ? 7 : 2))+ .millisecondsSinceEpoch;+ }+ final lead = (groups.first as Map)['data'] as Map;+ lead+ ..['lastMessageSequence'] = 7+ ..['number'] = 12+ ..['pullRequestUrls'] = [pr]+ ..['cards'] = {+ 'task': 'm1',+ 'pullRequests': [+ {'url': pr, 'messageId': 'm2'},+ ],+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...load,+ 'members': [+ part(me, 1, person(me)),+ part('diego', 1, {+ ...person('diego', role: 'collaborator'),+ // No emoji: the test engine draws none.+ 'status': {'text': 'Reviewing PRs'},+ }),+ part('ken', 1, person('ken', role: 'collaborator')),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'projectId': project,+ 'projectName': 'Mobile',+ 'conversationId': 'g2',+ 'conversationTitle': 'Saved views cache',+ 'askerName': 'River',+ 'question': 'Merge #2160?',+ 'options': ['Merge', 'Wait'],+ 'recommended': 0,+ 'createdAt': ago(3),+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =+ (_) => {+ 'messages': [+ said('m1', 1, 'Brief: the project screen, Chat and Team.'),+ said(+ 'm2',+ 2,+ 'Opened $pr',+ author: 'agent-builder',+ name: 'Nova',+ ),+ said(+ 'm3',+ 3,+ 'Run this:\n```bash\nflutter test test/swarm\n```',+ author: 'agent-builder',+ name: 'Nova',+ ),+ said(+ 'm4',+ 4,+ 'Shipped to TestFlight.',+ reactions: {+ 'eyes': [('person', me), ('person', 'diego')],+ 'check': [('person', 'diego')],+ 'rocket': [('agent', 'agent-builder')],+ },+ ),+ said(+ 'm5',+ 5,+ 'Which header goes on Team?',+ author: 'diego',+ kind: 'person',+ name: 'Diego',+ ),+ said(+ 'm6',+ 6,+ 'The #name one, with the humans and agents line.',+ author: 'agent-builder',+ name: 'Nova',+ ),+ said('m7', 7, 'Juno needs a call on the saved views cache.'),+ ],+ 'threads': [+ {+ 'id': 'm5',+ 'replies': 3,+ 'lastSequence': 9,+ 'lastAt': ago(2),+ 'authors': [+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ ],+ 'people': <String>[],+ },+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/leaderboard?projectId=$project'] =+ (_) => leaderboardData(+ people: [+ {+ ...scoreData(+ me,+ points: 1320,+ rank: 1,+ shipped: 6,+ unblocked: 3,+ ),+ 'displayName': 'Ada',+ },+ {+ ...scoreData('diego', points: 1050, rank: 2, lentMs: 36000000),+ 'displayName': 'Diego',+ },+ {+ ...scoreData('ken', points: 640, rank: 3, unblocked: 2),+ 'displayName': 'Ken',+ },+ ],+ );+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => me,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ 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!),+ home: const SwarmProjectPage(+ swarmId: tab,+ projectId: project,+ tabs: SwarmProjectTab.homeC,+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ Future<void> capture(String name) => tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$shots/project-c-$name-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ Finder key(String value) => find.byKey(ValueKey(value));+ await capture('chat');+ await tester.drag(key('swarm-messages'), const Offset(0, 600));+ await tester.pumpAndSettle();+ await capture('chat-earlier');+ await tester.tap(key('swarm-project-tab-team'));+ await tester.pumpAndSettle();+ await capture('team');+ await tester.drag(key('swarm-project-team-list'), const Offset(0, -400));+ await tester.pumpAndSettle();+ await capture('team-agents');+ await tester.drag(key('swarm-project-team-list'), const Offset(0, 400));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-approve-d1'));+ await tester.pumpAndSettle();+ await capture('approve');+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 30));+ host.dispose();+ account.dispose();+ }+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_project_c_test.dart b/mobile/test/swarm/swarm_project_c_test.dartnew file mode 100644index 000000000..d0fdcd1a1--- /dev/null+++ b/mobile/test/swarm/swarm_project_c_test.dart@@ -0,0 +1,1733 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/widgets/touch_target.dart';+import 'package:harness_mobile/swarm/swarm_code_block.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_inbox.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_project_tabs.dart';+import 'package:harness_mobile/swarm/swarm_project_tasks.dart';+import 'package:harness_mobile/swarm/swarm_project_team.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';++/// The project screen of Tony's Swarm Home, direction C (2026-10-30): the+/// project's #name over its team line, and two tabs, Chat and Team.+void main() {+ const board = '/api/super-tabs/$tab/leaderboard?projectId=$project';++ /// One Swarm whose project Mobile has three people (the viewer, diego and+ /// ken) and four agents: River, the Product Manager; Nova at work on g1;+ /// Juno, whose work waits on a person; and Ash with none.+ 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(+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ agent('agent-juno', displayName: 'Juno'),+ agent('agent-ash', displayName: 'Ash'),+ ],+ groups: [+ groupData(+ 'g1',+ title: 'Buddy chat header',+ number: 2156,+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ workerId: 'agent-builder',+ lastMessageSequence: 3,+ ),+ groupData(+ 'g2',+ title: 'Saved views cache',+ number: 2160,+ agentIds: ['agent-lead', 'agent-juno'],+ status: 'needs_human',+ workerId: 'agent-juno',+ lastMessageSequence: 4,+ ),+ ],+ ),+ 'members': [+ part(me, 1, person(me)),+ part('diego', 1, {+ ...person('diego', role: 'collaborator'),+ 'status': {'text': 'Reviewing PRs', 'emoji': '🎯'},+ }),+ part('ken', 1, {+ ...person('ken', role: 'collaborator'),+ 'status': {+ 'text': 'At lunch',+ 'emoji': '🍽️',+ 'until': '2026-10-01T05:00:00.000Z',+ },+ }),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =+ (_) => {+ 'messages': [+ {+ 'id': 'msg-lead-1',+ 'conversationId': leadChat,+ 'text': 'CI on #2154 is green.',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'createdAt': '2026-10-29T02:40:00.000Z',+ },+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/conversations/g1/messages'] = (_) => {+ 'messages': [+ {+ 'id': 'msg-g1-1',+ 'conversationId': 'g1',+ 'text': 'Header is in.',+ 'sequence': 3,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'createdAt': '2026-10-29T02:50:00.000Z',+ },+ ],+ 'next': null,+ };+ fake.routes[board] = (_) => leaderboardData(+ people: [+ scoreData(me, points: 1320, rank: 1, shipped: 6, unblocked: 3),+ scoreData('diego', points: 1050, rank: 2, lentMs: 10 * 3600000),+ scoreData('ken', points: 640, rank: 3),+ ],+ );+ return fake;+ }++ /// [home] under a signed-in shell's Swarm, with Swarm turned on; the+ /// phone keeps its read marks in [marks].+ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake,+ Widget home, {+ bool settle = true,+ LocalKeyValueStore? marks,+ }) 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,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: marks ?? MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: home,+ ),+ );+ if (settle) {+ await tester.pumpAndSettle();+ } else {+ // A read held on its way: skeletons pulse until it answers.+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ }+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ const page = SwarmProjectPage(+ swarmId: tab,+ projectId: project,+ tabs: SwarmProjectTab.homeC,+ );++ /// The page on its Team tab.+ Future<SwarmHost> team(WidgetTester tester, FakeSwarm fake) async {+ final host = await pump(tester, fake, page);+ await tester.tap(key('swarm-project-tab-team'));+ await tester.pumpAndSettle();+ return host;+ }++ /// The words of the row keyed [k], its rich text included.+ String said(WidgetTester tester, String k) => [+ for (final text in tester.widgetList<RichText>(+ find.descendant(of: key(k), matching: find.byType(RichText)),+ ))+ text.text.toPlainText(),+ ].join(' | ');++ /// How a screen reader says the row keyed [k].+ String heard(WidgetTester tester, String k) =>+ tester.getSemantics(key(k)).label;++ /// The [SwarmHost] a test's app is under.+ SwarmHost host(WidgetTester tester) =>+ tester.widget<SwarmScope>(find.byType(SwarmScope)).notifier!;++ /// [path] answers only once the returned gate is opened.+ Completer<void> hold(FakeSwarm fake, String path) {+ final gate = Completer<void>();+ final answer = fake.routes[path]!;+ fake.routes[path] = (body) async {+ await gate.future;+ return answer(body);+ };+ return gate;+ }++ /// The member rows under the caption keyed [caption]'s card.+ List<String> rowsAfter(WidgetTester tester, String caption, String? next) {+ final top = tester.getBottomLeft(key(caption)).dy;+ final bottom = next == null+ ? double.infinity+ : tester.getTopLeft(key(next)).dy;+ final rows =+ tester.widgetList<SwarmMemberRow>(find.byType(SwarmMemberRow)).where((+ row,+ ) {+ final y = tester.getTopLeft(find.byWidget(row)).dy;+ return y >= top && y < bottom;+ }).toList()..sort(+ (a, b) => tester+ .getTopLeft(find.byWidget(a))+ .dy+ .compareTo(tester.getTopLeft(find.byWidget(b)).dy),+ );+ return [for (final row in rows) (row.key! as ValueKey<String>).value];+ }++ /// The texts of the row keyed [k] with a digit in them, its face aside.+ Finder figures(String k) => find.descendant(+ of: key(k),+ matching: find.textContaining(RegExp(r'\d'), findRichText: true),+ );++ group('Team, its tasks', () {+ /// The key of Juno's work in g2, waiting on the person.+ String workKey(WidgetTester tester) =>+ host(tester).session!.inbox.needs.whereType<SwarmWorkNeed>().single.key;++ testWidgets('on top: what waits on the person, then what is worked on, '+ "in the Tasks tab's rows, counted beside their caption", (+ tester,+ ) async {+ await team(tester, backend());++ expect(+ said(tester, 'swarm-team-tasks-caption'),+ 'Tasks | 1 waiting on you · 1 working',+ );+ final waiting = 'swarm-waiting-${workKey(tester)}';+ expect(key(waiting), findsOneWidget);+ expect(tester.widget(key(waiting)), isA<SwarmWaitingRow>());+ expect(tester.widget(key('swarm-task-g1')), isA<SwarmWorkRow>());+ expect(key('swarm-task-g2'), findsNothing, reason: 'it waits on you');+ expect(key('swarm-reply-${workKey(tester)}'), findsOneWidget);+ double y(String k) => tester.getTopLeft(key(k)).dy;+ final order = [+ y('swarm-team-tasks-caption'),+ y(waiting),+ y('swarm-task-g1'),+ y('swarm-team-humans-caption'),+ y('swarm-team-agents-caption'),+ ];+ expect(order, [...order]..sort(), reason: 'Tasks first, waiting first');+ expect(find.text('Done today'), findsNothing, reason: 'open tasks only');+ });++ /// [backend] with River asking the person, in g2, whether to merge.+ FakeSwarm asked() {+ final fake = backend();+ const derived = {'decisionsWaiting': 1};+ final load = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async => {+ ...(await load(body))! as Map<String, dynamic>,+ 'derived': derived,+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'projectName': 'Mobile',+ 'conversationId': 'g2',+ 'conversationTitle': 'Saved views cache',+ 'askerName': 'River',+ 'question': 'Merge #2160?',+ 'options': ['Merge', 'Wait'],+ },+ ],+ };+ return fake;+ }++ testWidgets('Approve asks first, naming the answer, who asked, where and '+ 'the question; confirmed, it is held for Undo and sent once', (+ tester,+ ) async {+ final fake = asked();+ await team(tester, fake);++ await tester.tap(key('swarm-approve-d1'));+ await tester.pumpAndSettle();+ expect(+ find.text(+ 'Sends “Merge” to River in #Mobile: Merge #2160?\n\n'+ 'You can undo it for a few seconds.',+ ),+ findsOneWidget,+ );+ await tester.tap(key('swarm-activity-approve-cancel'));+ await tester.pumpAndSettle();+ await tester.pump(const Duration(seconds: 5));+ await tester.pumpAndSettle();+ expect(fake.commands, isEmpty, reason: 'Cancel sends nothing');++ await tester.tap(key('swarm-approve-d1'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-activity-approve-confirm'));+ await tester.pumpAndSettle();+ expect(+ find.descendant(+ of: key('swarm-waiting-decision:d1'),+ matching: find.text('Sending “Merge”'),+ ),+ findsOneWidget,+ );+ expect(fake.commands, isEmpty, reason: 'Undo still can');+ await tester.pump(const Duration(seconds: 3));+ await tester.pumpAndSettle();+ expect(fake.commands.single, {+ 'type': 'decision.answer',+ 'decisionId': 'd1',+ 'choice': 0,+ });+ });++ testWidgets('access taken away while Approve asks: confirming it then '+ 'holds and sends nothing', (tester) async {+ final fake = asked();+ await team(tester, fake);++ await tester.tap(key('swarm-approve-d1'));+ await tester.pumpAndSettle();+ host(tester).session!.inbox.reader(tab)!.revoke();+ await tester.pump();+ await tester.tap(key('swarm-activity-approve-confirm'));+ await tester.pumpAndSettle();+ await tester.pump(const Duration(seconds: 5));+ await tester.pumpAndSettle();++ expect(fake.commands, isEmpty);+ expect(find.byType(SwarmWaitingRow), findsNothing);+ });++ testWidgets('a task opens its chat', (tester) async {+ await team(tester, backend());++ await tester.tap(key('swarm-task-g1'));+ await tester.pumpAndSettle();++ expect(find.text('Header is in.'), findsOneWidget);+ });++ testWidgets('none open says so in a line, and finished work is not '+ 'listed', (tester) async {+ final fake = backend();+ final load = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {+ final read = (await load(body))! as Map<String, dynamic>;+ return {+ ...read,+ 'groups': [+ part(+ 'g1',+ 1,+ groupData(+ 'g1',+ title: 'Buddy chat header',+ number: 2156,+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'done',+ workerId: 'agent-builder',+ ),+ ),+ ],+ };+ };+ await team(tester, fake);++ expect(said(tester, 'swarm-team-tasks-caption'), 'Tasks');+ expect(key('swarm-team-no-tasks'), findsOneWidget);+ expect(find.text('No open tasks.'), findsOneWidget);+ expect(key('swarm-task-g1'), findsNothing);+ });+ });++ group('Team, its humans', () {+ testWidgets("ordered by this week's points, most first, as Desktop's "+ 'member list draws them (#2230): the name and what they are on now, '+ 'a line of what they did this week, and the points at the right', (+ tester,+ ) async {+ await team(tester, backend());++ expect(said(tester, 'swarm-team-humans-caption'), 'Humans');+ expect(+ rowsAfter(+ tester,+ 'swarm-team-humans-caption',+ 'swarm-team-agents-caption',+ ),+ [+ 'swarm-member-person-person-me',+ 'swarm-member-person-diego',+ 'swarm-member-person-ken',+ ],+ );+ expect(+ heard(tester, 'swarm-member-person-person-me'),+ 'person-me, you, 6 shipped · 3 unblocked, 1320 points',+ );+ expect(+ heard(tester, 'swarm-member-person-diego'),+ 'diego, 🎯 Reviewing PRs, 10 hours lent, 1050 points',+ );+ expect(+ heard(tester, 'swarm-member-person-ken'),+ 'ken, 640 points',+ reason: 'a status whose time has passed is not shown, nor zeros',+ );+ expect(+ said(tester, 'swarm-member-person-diego'),+ 'D | diego 🎯 Reviewing PRs | 10 hours lent | 1050',+ reason: 'the status after the name, as on Desktop',+ );+ final name = tester.getTopRight(+ find.descendant(+ of: key('swarm-member-person-diego'),+ matching: find.textContaining('diego', findRichText: true),+ ),+ );+ Finder points(String id, String value) => find.descendant(+ of: key('swarm-member-person-$id'),+ matching: find.text(value),+ );+ expect(+ tester.getTopLeft(points('diego', '1050')).dx,+ greaterThan(name.dx),+ reason: 'at the right',+ );+ expect(+ tester.getTopRight(points('diego', '1050')).dx,+ tester.getTopRight(points('ken', '640')).dx,+ reason: 'the points line up',+ );+ });++ testWidgets('in the one row shape the agents share', (tester) async {+ await team(tester, backend());++ expect(+ rowsAfter(tester, 'swarm-team-agents-caption', null),+ hasLength(4),+ );+ final human = tester.getSize(key('swarm-member-person-diego'));+ final agent = tester.getSize(key('swarm-member-agent-ash'));+ expect(human.height, agent.height);+ expect(human.width, agent.width);+ });++ testWidgets('equal points, and none, go by name', (tester) async {+ final fake = backend();+ fake.routes[board] = (_) => leaderboardData(+ people: [+ scoreData('ken', points: 40, rank: 1),+ scoreData('diego', points: 40, rank: 1),+ ],+ );+ await team(tester, fake);++ expect(+ rowsAfter(+ tester,+ 'swarm-team-humans-caption',+ 'swarm-team-agents-caption',+ ),+ [+ 'swarm-member-person-diego',+ 'swarm-member-person-ken',+ 'swarm-member-person-person-me',+ ],+ );+ });++ testWidgets('a row opens their week', (tester) async {+ await team(tester, backend());++ await tester.tap(key('swarm-member-person-diego'));+ await tester.pumpAndSettle();++ expect(+ find.byKey(const ValueKey('swarm-leaderboard-sheet')),+ findsOneWidget,+ );+ });++ testWidgets('a private project lists only the people who read it', (+ tester,+ ) async {+ final fake = backend();+ final load = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {+ final read = (await load(body))! as Map<String, dynamic>;+ final head = (read['head'] as Map)['data'] as Map<String, dynamic>;+ final mobile = (head['projects'] as List).single as Map;+ mobile['visibility'] = 'private';+ mobile['members'] = [+ {'id': 'diego', 'generation': 'gen-diego'},+ ];+ return read;+ };+ await team(tester, fake);++ expect(key('swarm-member-person-ken'), findsNothing);+ expect(key('swarm-member-person-diego'), findsOneWidget);+ });++ testWidgets('while the board is read, the people show at once by name, '+ 'never a Loading that stays, and take its order when it answers', (+ tester,+ ) async {+ final fake = backend();+ final gate = hold(fake, board);+ await team(tester, fake);++ List<String> humans() => rowsAfter(+ tester,+ 'swarm-team-humans-caption',+ 'swarm-team-agents-caption',+ );+ expect(humans(), [+ 'swarm-member-person-diego',+ 'swarm-member-person-ken',+ 'swarm-member-person-person-me',+ ]);+ expect(find.textContaining('Loading'), findsNothing);+ for (final id in ['person-me', 'diego', 'ken']) {+ expect(+ figures('swarm-member-person-$id'),+ findsNothing,+ reason: 'no points nor numbers before the board answers: $id',+ );+ }++ gate.complete();+ await tester.pumpAndSettle();+ expect(humans(), [+ 'swarm-member-person-person-me',+ 'swarm-member-person-diego',+ 'swarm-member-person-ken',+ ]);+ });++ testWidgets('a board that cannot be read says so, and Try again reads it '+ 'once', (tester) async {+ final fake = backend();+ final answer = fake.routes[board]!;+ fake.routes[board] = (_) =>+ throw const SuperTabFailure('INTERNAL', 'Board is down.');+ await team(tester, fake);++ expect(find.text('Board is down.'), findsOneWidget);+ expect(key('swarm-member-person-diego'), findsOneWidget);+ final reads = fake.paths.where((p) => p == board).length;++ fake.routes[board] = answer;+ await tester.tap(key('swarm-team-board-retry'));+ await tester.pumpAndSettle();++ expect(fake.paths.where((p) => p == board).length, reads + 1);+ expect(find.text('Board is down.'), findsNothing);+ expect(+ rowsAfter(+ tester,+ 'swarm-team-humans-caption',+ 'swarm-team-agents-caption',+ ).first,+ 'swarm-member-person-person-me',+ );+ });++ testWidgets('access taken away while it is open leaves nothing of the '+ 'team, and the board answer on its way is dropped', (tester) async {+ final fake = backend();+ final gate = hold(fake, board);+ await team(tester, fake);++ host(tester).session!.inbox.reader(tab)!.revoke();+ await tester.pump();+ gate.complete();+ await tester.pumpAndSettle();++ expect(find.byType(SwarmMemberRow), findsNothing);+ expect(find.byType(SwarmProjectTeam), findsNothing);+ expect(+ find.text('This project is no longer in the Swarm.'),+ findsOneWidget,+ );+ });+ });++ group('Team, its agents', () {+ testWidgets('each in its state with the task it holds, the most urgent '+ 'first, with what needs a look counted', (tester) async {+ await team(tester, backend());++ expect(+ said(tester, 'swarm-team-agents-caption'),+ 'Agents | 1 needs input · 1 working',+ );+ double y(String id) => tester.getTopLeft(key('swarm-member-$id')).dy;+ expect(+ [+ for (final id in ['agent-juno', 'agent-builder', 'agent-ash'])+ y(id) < y('agent-lead'),+ ],+ [true, true, true],+ );+ expect(y('agent-juno'), lessThan(y('agent-builder')));+ expect(y('agent-builder'), lessThan(y('agent-ash')));+ expect(+ heard(tester, 'swarm-member-agent-juno'),+ 'Juno, Needs input · #2160 Saved views cache',+ );+ expect(+ heard(tester, 'swarm-member-agent-builder'),+ 'Nova, Working · #2156 Buddy chat header',+ );+ expect(heard(tester, 'swarm-member-agent-ash'), 'Ash, Idle');+ for (final id in ['agent-juno', 'agent-builder', 'agent-ash']) {+ expect(+ tester.getSize(key('swarm-member-$id')).height,+ greaterThanOrEqualTo(minTouchTarget),+ reason: id,+ );+ }+ });++ testWidgets('a row opens the task its agent holds', (tester) async {+ await team(tester, backend());++ // Under the Tasks and the humans.+ await tester.ensureVisible(key('swarm-member-agent-builder'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-member-agent-builder'));+ await tester.pumpAndSettle();++ expect(find.text('Header is in.'), findsOneWidget);+ });+ });++ group('the project screen', () {+ testWidgets('its #name over the humans, the agents and who is working', (+ tester,+ ) async {+ await pump(tester, backend(), page);++ expect(+ tester.widget<Text>(key('swarm-title')).data,+ '#Mobile',+ reason: 'a channel name, as Slack writes one',+ );+ expect(+ find.descendant(+ of: key('swarm-project-team-line'),+ matching: find.textContaining(+ '3 humans · 4 agents · ● 1 working',+ findRichText: true,+ ),+ ),+ findsOneWidget,+ );+ });++ testWidgets('one human and one agent are said so', (tester) async {+ final fake = backend();+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ agents: [agent('agent-lead', name: 'Lead', displayName: 'River')],+ ),+ 'members': [part(me, 1, person(me))],+ };+ await pump(tester, fake, page);++ expect(+ find.descendant(+ of: key('swarm-project-team-line'),+ matching: find.textContaining(+ '1 human · 1 agent · All idle',+ findRichText: true,+ ),+ ),+ findsOneWidget,+ );+ });++ testWidgets('a private project counts only the people who read it', (+ tester,+ ) async {+ final fake = backend();+ final load = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {+ final read = (await load(body))! as Map<String, dynamic>;+ final head = (read['head'] as Map)['data'] as Map<String, dynamic>;+ final mobile = (head['projects'] as List).single as Map;+ mobile['visibility'] = 'private';+ mobile['members'] = [+ {'id': 'diego', 'generation': 'gen-diego'},+ ];+ return read;+ };+ await pump(tester, fake, page);++ expect(+ find.descendant(+ of: key('swarm-project-team-line'),+ matching: find.textContaining(+ '2 humans · 4 agents',+ findRichText: true,+ ),+ ),+ findsOneWidget,+ reason: 'its owner (the viewer) and diego; ken does not read it',+ );+ });++ testWidgets('has two tabs, Chat and Team, each half the width and a '+ "finger's height", (tester) async {+ await pump(tester, backend(), page);++ for (final name in ['buddy', 'tasks', 'leaderboard']) {+ expect(key('swarm-project-tab-$name'), findsNothing, reason: name);+ }+ final width = tester.getSize(find.byType(SwarmProjectPage)).width;+ for (final name in ['chat', 'team']) {+ final size = tester.getSize(key('swarm-project-tab-$name'));+ expect(size.height, greaterThanOrEqualTo(minTouchTarget), reason: name);+ expect(size.width, greaterThan(width / 2 - 16), reason: name);+ }+ expect(find.text('Chat'), findsOneWidget);+ expect(find.text('Team'), findsOneWidget);+ expect(+ key('swarm-project-team'),+ findsNothing,+ reason: 'the team is a tab, not a sheet from the header',+ );+ });++ testWidgets('opens on its chat, and Team shows the team in its place', (+ tester,+ ) async {+ await pump(tester, backend(), page);+ expect(find.text('CI on #2154 is green.'), findsOneWidget);+ expect(key('swarm-project-body-chat'), findsOneWidget);++ await tester.tap(key('swarm-project-tab-team'));+ await tester.pumpAndSettle();++ expect(key('swarm-project-body-team'), findsOneWidget);+ expect(find.text('CI on #2154 is green.'), findsNothing);+ expect(+ tester+ .widget<Semantics>(key('swarm-project-tab-team'))+ .properties+ .selected,+ isTrue,+ );+ });++ testWidgets('the four tabs of direction B stay as they were', (+ tester,+ ) async {+ await pump(+ tester,+ backend(),+ const SwarmProjectPage(swarmId: tab, projectId: project),+ );++ for (final name in ['chat', 'buddy', 'tasks', 'leaderboard']) {+ expect(key('swarm-project-tab-$name'), findsOneWidget, reason: name);+ }+ expect(key('swarm-project-tab-team'), findsNothing);+ expect(tester.widget<Text>(key('swarm-title')).data, 'Mobile');+ expect(key('swarm-project-team'), findsOneWidget);+ });+ });++ group('Chat, its New messages line and Jump to latest', () {+ /// River's message [sequence] in the project's chat, [author] another's.+ Map<String, dynamic> said(+ int sequence, {+ String author = 'agent-lead',+ String kind = 'agent',+ String? text,+ }) => {+ 'id': 'msg-$sequence',+ 'conversationId': leadChat,+ 'text': text ?? 'Update $sequence.',+ 'sequence': sequence,+ 'author': {'kind': kind, 'id': author, 'name': author},+ 'createdAt': DateTime.utc(2026, 10, 29, 2, sequence).toIso8601String(),+ };++ /// [backend] whose project chat holds [messages], read through [mark]+ /// on some device (the server's mark, #2131), [older] ones before them.+ FakeSwarm chat(+ List<Map<String, dynamic>> messages, {+ required int mark,+ bool older = false,+ }) {+ final fake = backend();+ final load = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {+ final read = (await load(body))! as Map<String, dynamic>;+ ((read['groups'] as List).first as Map)['data']['lastMessageSequence'] =+ messages.last['sequence'];+ return {+ ...read,+ 'derived': {+ 'readMarks': {leadChat: mark},+ },+ };+ };+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =+ (_) => {+ 'messages': messages,+ 'next': older+ ? {'sequence': messages.first['sequence'], 'id': 'msg-older'}+ : null,+ };+ return fake;+ }++ final line = key('swarm-new-messages-line');++ /// The read marks sent for the project's chat, in order.+ List<Object?> marksSent(FakeSwarm fake) => [+ for (final call in fake.calls)+ if (call.method == 'POST' &&+ call.path == '/api/super-tabs/$tab/conversations/$leadChat/read')+ call.body?['sequence'],+ ];++ /// Whether [f] is drawn inside the chat's list, not scrolled out of it.+ bool onScreen(WidgetTester tester, Finder f) {+ if (f.evaluate().isEmpty) return false;+ final list = tester.getRect(key('swarm-messages'));+ final row = tester.getRect(f);+ return row.top >= list.top && row.bottom <= list.bottom;+ }++ testWidgets('sits above the first message the person has not read, from '+ 'someone else, and says so in words', (tester) async {+ await pump(+ tester,+ chat([for (var i = 1; i <= 4; i++) said(i)], mark: 2),+ page,+ );++ expect(line, findsOneWidget);+ expect(find.text('New messages'), findsOneWidget);+ expect(tester.getSemantics(line).label, 'New messages');+ 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("passes over the person's own messages; their own newest "+ 'reads what came before it', (tester) async {+ await pump(+ tester,+ chat([+ said(1),+ said(2),+ said(3, author: me, kind: 'person', text: 'On it.'),+ ], mark: 1),+ page,+ );++ expect(line, findsNothing);+ });++ testWidgets('is placed once: a message that comes later and the mark '+ 'moving on leave it where it was', (tester) async {+ final fake = chat([for (var i = 1; i <= 3; i++) said(i)], mark: 1);+ await pump(tester, fake, page);+ expect(+ tester.getTopLeft(find.text('Update 2.')).dy,+ greaterThan(tester.getTopLeft(line).dy),+ );++ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =+ (_) => {+ 'messages': [for (var i = 1; i <= 4; i++) said(i)],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part(+ leadChat,+ 9,+ groupData(+ leadChat,+ title: 'Mobile',+ agentIds: ['agent-lead'],+ leadId: 'agent-lead',+ lastMessageSequence: 4,+ ),+ ),+ ],+ );+ await host(tester).session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(find.text('Update 4.'), findsOneWidget);+ expect(line, findsOneWidget);+ final y = tester.getTopLeft(line).dy;+ expect(tester.getTopLeft(find.text('Update 1.')).dy, lessThan(y));+ expect(tester.getTopLeft(find.text('Update 2.')).dy, greaterThan(y));+ });++ testWidgets("the phone's marks read back after the chat's first read: "+ 'nothing is read meanwhile, and the line is still placed', (+ tester,+ ) async {+ final marks = _SlowMarks();+ final fake = chat([for (var i = 1; i <= 3; i++) said(i)], mark: 1);+ await pump(tester, fake, page, marks: marks);+ expect(find.text('Update 3.'), findsOneWidget);+ expect(line, findsNothing);+ expect(marksSent(fake), isEmpty, reason: 'held until the line is placed');++ marks.back.complete();+ await tester.pumpAndSettle();++ expect(line, findsOneWidget);+ final y = tester.getTopLeft(line).dy;+ expect(tester.getTopLeft(find.text('Update 1.')).dy, lessThan(y));+ expect(tester.getTopLeft(find.text('Update 2.')).dy, greaterThan(y));+ // The mark is written once this frame's work is done.+ await tester.pump(Duration.zero);+ expect(marksSent(fake), [3], reason: 'the line on screen: all is read');+ });++ testWidgets('a chat never read anywhere, or one read through its end, '+ 'has none', (tester) async {+ await pump(tester, chat([said(1), said(2)], mark: 2), page);+ expect(line, findsNothing);+ });++ testWidgets('more unread than one read reaches has none, and opens at '+ 'the foot as before', (tester) async {+ await pump(+ tester,+ chat([for (var i = 10; i <= 12; i++) said(i)], mark: 2, older: true),+ page,+ );++ expect(line, findsNothing);+ expect(onScreen(tester, find.text('Update 12.')), isTrue);+ });++ testWidgets('above the screen, the chat opens at it, and what is below '+ 'is read only once the person goes down to it', (tester) async {+ final fake = chat([for (var i = 1; i <= 40; i++) said(i)], mark: 5);+ await pump(tester, fake, page);++ 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(key('swarm-messages'), const Offset(0, -6000), 4000);+ await tester.pumpAndSettle();++ expect(onScreen(tester, find.text('Update 40.')), isTrue);+ expect(marksSent(fake).last, 40);+ });++ testWidgets('reading more than a screen back, Jump to latest takes the '+ 'person to the foot; a little way back, none', (tester) async {+ await pump(+ tester,+ chat([for (var i = 1; i <= 40; i++) said(i)], mark: 40),+ page,+ );+ final jump = key('swarm-jump-latest');+ expect(line, findsNothing);+ expect(jump, findsNothing, reason: 'at the foot');++ await tester.drag(key('swarm-messages'), const Offset(0, 120));+ await tester.pumpAndSettle();+ expect(jump, findsNothing, reason: 'not a screen back');++ await tester.drag(key('swarm-messages'), const Offset(0, 1500));+ await tester.pumpAndSettle();+ expect(onScreen(tester, find.text('Update 40.')), isFalse);+ expect(jump, findsOneWidget);+ expect(find.text('Jump to latest'), findsOneWidget);+ expect(tester.getSemantics(jump).label, 'Jump to latest');+ expect(tester.getSize(jump).height, greaterThanOrEqualTo(minTouchTarget));++ await tester.tap(jump);+ await tester.pumpAndSettle();+ expect(onScreen(tester, find.text('Update 40.')), isTrue);+ expect(jump, findsNothing);+ });++ testWidgets('far back, what came meanwhile is counted in its place', (+ tester,+ ) async {+ final fake = chat([for (var i = 1; i <= 40; i++) said(i)], mark: 40);+ await pump(tester, fake, page);+ await tester.drag(key('swarm-messages'), const Offset(0, 1500));+ await tester.pumpAndSettle();+ expect(key('swarm-jump-latest'), findsOneWidget);++ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =+ (_) => {+ 'messages': [for (var i = 1; i <= 41; i++) said(i)],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part(+ leadChat,+ 9,+ groupData(+ leadChat,+ title: 'Mobile',+ agentIds: ['agent-lead'],+ leadId: 'agent-lead',+ lastMessageSequence: 41,+ ),+ ),+ ],+ );+ await host(tester).session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(key('swarm-new-pill'), findsOneWidget);+ expect(find.text('1 new'), findsOneWidget);+ expect(key('swarm-jump-latest'), findsNothing);+ });++ testWidgets("direction B's chat has none", (tester) async {+ await pump(+ tester,+ chat([for (var i = 1; i <= 4; i++) said(i)], mark: 2),+ const SwarmProjectPage(swarmId: tab, projectId: project),+ );++ expect(find.text('Update 4.'), findsOneWidget);+ expect(line, findsNothing);+ });++ testWidgets("direction B's chat offers no Jump to latest", (tester) async {+ await pump(+ tester,+ chat([for (var i = 1; i <= 40; i++) said(i)], mark: 40),+ const SwarmProjectPage(swarmId: tab, projectId: project),+ );+ await tester.drag(key('swarm-messages'), const Offset(0, 1500));+ await tester.pumpAndSettle();++ expect(onScreen(tester, find.text('Update 40.')), isFalse);+ expect(key('swarm-jump-latest'), findsNothing);+ });+ });++ group('Chat, its messages', () {+ const pr = 'https://github.com/example/app/pull/7';++ /// A message of the project's chat; [thread] its own id by default.+ Map<String, dynamic> said(+ String id,+ int sequence,+ String text, {+ String author = 'agent-lead',+ Map<String, List<(String, String)>> reactions = const {},+ }) => {+ 'id': id,+ 'conversationId': leadChat,+ 'text': text,+ 'sequence': sequence,+ 'thread': id,+ 'author': {+ 'kind': 'agent',+ 'id': author,+ 'name': author == 'agent-lead' ? 'River' : 'Nova',+ },+ 'reactions': [+ for (final MapEntry(key: emoji, value: by) in reactions.entries)+ {+ 'emoji': emoji,+ 'count': by.length,+ 'by': [+ for (final (kind, who) in by) {'kind': kind, 'id': who},+ ],+ },+ ],+ 'createdAt': DateTime.utc(2026, 10, 29, 2, sequence).toIso8601String(),+ };++ /// The project's chat: River's brief, a task card; Nova's Opened, a PR+ /// card; a code block; reactions 👀 ✅ 🚀; and a root with 3 replies.+ FakeSwarm talk() {+ final fake = backend();+ final load = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {+ final read = (await load(body))! as Map<String, dynamic>;+ final lead = ((read['groups'] as List).first as Map)['data'] as Map;+ lead+ ..['lastMessageSequence'] = 5+ ..['number'] = 12+ ..['pullRequestUrls'] = [pr]+ ..['cards'] = {+ 'task': 'm1',+ 'pullRequests': [+ {'url': pr, 'messageId': 'm2'},+ ],+ };+ return read;+ };+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =+ (_) => {+ 'messages': [+ said('m1', 1, 'Brief: the project screen.'),+ said('m2', 2, 'Opened $pr', author: 'agent-builder'),+ said(+ 'm3',+ 3,+ 'Run this:\n```bash\nflutter test test/swarm\n```',+ author: 'agent-builder',+ ),+ said(+ 'm4',+ 4,+ 'Shipped.',+ reactions: {+ 'eyes': [('person', me), ('person', 'diego')],+ 'check': [('person', 'diego')],+ 'rocket': [('agent', 'agent-builder')],+ },+ ),+ said('m5', 5, 'Which header?'),+ ],+ 'threads': [+ {+ 'id': 'm5',+ 'replies': 3,+ 'lastSequence': 8,+ 'lastAt': DateTime.utc(2026, 10, 29, 2, 8).toIso8601String(),+ 'authors': [+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ ],+ 'people': <String>[],+ },+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => {+ 'result': <String, dynamic>{},+ };+ return fake;+ }++ Finder inside(String k, Finder f) =>+ find.descendant(of: key(k), matching: f);++ testWidgets('a task card and a PR card, in place of their messages', (+ tester,+ ) async {+ await pump(tester, talk(), page);++ // The oldest, above the screen.+ for (final card in ['swarm-card-m2', 'swarm-card-m1']) {+ await tester.dragUntilVisible(+ key(card),+ key('swarm-messages'),+ const Offset(0, 200),+ );+ await tester.pumpAndSettle();+ }+ expect(key('swarm-card-m1'), findsOneWidget, reason: 'the task card');+ expect(key('swarm-card-m2'), findsOneWidget, reason: 'the PR card');+ expect(+ inside('swarm-card-m2', find.textContaining('#7', findRichText: true)),+ findsWidgets,+ );+ });++ testWidgets('a code block, with Copy', (tester) async {+ await pump(tester, talk(), page);++ expect(find.byType(SwarmCodeBlock), findsOneWidget);+ expect(+ find.descendant(+ of: find.byType(SwarmCodeBlock),+ matching: find.textContaining('flutter test test/swarm'),+ ),+ findsOneWidget,+ );+ expect(find.bySemanticsLabel(RegExp('Copy')), findsWidgets);+ });++ testWidgets('reactions 👀 ✅ 🚀, each a finger to tap, the add-reaction '+ 'chip after them, and a pick from it is sent', (tester) async {+ final fake = talk();+ await pump(tester, fake, page);++ for (final (emoji, count) in [('eyes', 2), ('check', 1), ('rocket', 1)]) {+ final chip = key('swarm-reaction-m4-$emoji');+ expect(chip, findsOneWidget, reason: emoji);+ final size = tester.getSize(chip);+ expect(+ size.height,+ greaterThanOrEqualTo(minTouchTarget),+ reason: emoji,+ );+ expect(size.width, greaterThanOrEqualTo(minTouchTarget), reason: emoji);+ expect(+ inside('swarm-reaction-m4-$emoji', find.text('$count')),+ findsOneWidget,+ );+ }+ expect(find.text('👍'), findsNothing);+ final add = key('swarm-add-reaction-m4');+ expect(add, findsOneWidget);+ expect(tester.getSize(add).height, greaterThanOrEqualTo(minTouchTarget));+ expect(tester.getSize(add).width, greaterThanOrEqualTo(minTouchTarget));+ expect(tester.getSemantics(add).label, 'Add reaction');+ expect(+ tester.getTopLeft(add).dx,+ greaterThan(tester.getTopLeft(key('swarm-reaction-m4-rocket')).dx),+ reason: 'after the counts',+ );+ expect(+ key('swarm-add-reaction-m1'),+ findsNothing,+ reason: 'only where there are reactions',+ );++ await tester.tap(add);+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-react-tada'));+ await tester.pumpAndSettle();++ expect(fake.commands.where((c) => c['type'] == 'message.react').single, {+ 'type': 'message.react',+ 'conversationId': leadChat,+ 'messageId': 'm4',+ 'emoji': 'tada',+ 'on': true,+ });+ });++ testWidgets("a root's replies in one row, which opens its thread", (+ tester,+ ) async {+ final fake = talk();+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'+ '?thread=m5'] = (_) => {+ 'messages': [+ {+ ...said('m8', 8, 'The one on Home C.', author: 'agent-builder'),+ 'thread': 'm5',+ 'replyTo': 'm5',+ },+ said('m5', 5, 'Which header?'),+ ],+ 'next': null,+ };+ await pump(tester, fake, page);++ final line = key('swarm-thread-line-m5');+ expect(+ inside('swarm-thread-line-m5', find.text('3 replies')),+ findsOneWidget,+ );+ expect(tester.getSize(line).height, greaterThanOrEqualTo(minTouchTarget));+ expect(key('swarm-thread-line-m4'), findsNothing, reason: 'no replies');++ await tester.tap(line);+ await tester.pumpAndSettle();++ expect(+ inside('swarm-thread-messages', find.text('Which header?')),+ findsOneWidget,+ );+ expect(+ inside('swarm-thread-messages', find.text('The one on Home C.')),+ findsOneWidget,+ );+ });+ });++ group('its privacy edges', () {+ const desktop = 'project-2';+ const messages = '/api/super-tabs/$tab/conversations/$leadChat/messages';++ /// [backend] whose Swarm has a second project, Desktop, the person reads+ /// too: Ash, Mobile's agent, still holds work there; another agent named+ /// Nova waits on the person there; and Mobile has the person's Buddy chat+ /// with Pip.+ FakeSwarm twoProjects() {+ final fake = backend();+ final load = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {+ final read = (await load(body))! as Map<String, dynamic>;+ final head = (read['head'] as Map)['data'] as Map;+ head['projects'] = [+ ...head['projects'] as List,+ {+ 'id': desktop,+ 'name': 'Desktop',+ 'ownerId': me,+ 'leadConversationId': 'group-lead-2',+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ];+ Map<String, dynamic> there(Map<String, dynamic> g) => {+ ...g,+ 'projectId': desktop,+ };+ read['agents'] = [+ ...read['agents'] as List,+ part('agent-nova-2', 1, {+ ...agent('agent-nova-2', displayName: 'Nova'),+ 'projectId': desktop,+ }),+ part('buddy-pip', 1, buddyData('buddy-pip', displayName: 'Pip')),+ ];+ final groups = read['groups'] as List;+ read['groups'] = [+ groups.first,+ part(+ 'group-lead-2',+ 7,+ there(groupData('group-lead-2', title: 'Desktop')),+ ),+ part(+ 'g3',+ 8,+ there(+ groupData(+ 'g3',+ title: 'Desktop sign-in',+ number: 3001,+ agentIds: ['agent-ash'],+ status: 'working',+ workerId: 'agent-ash',+ lastMessageSequence: 2,+ ),+ ),+ ),+ part(+ 'g4',+ 9,+ there(+ groupData(+ 'g4',+ title: 'Desktop keychain',+ number: 3002,+ agentIds: ['agent-nova-2'],+ status: 'needs_human',+ workerId: 'agent-nova-2',+ lastMessageSequence: 2,+ ),+ ),+ ),+ part(+ 'buddy-chat',+ 10,+ buddyChatData(+ 'buddy-chat',+ agentIds: ['buddy-pip'],+ lastMessageSequence: 1,+ ),+ ),+ ...groups.skip(1),+ ];+ return read;+ };+ return fake;+ }++ /// Whether [words] are drawn anywhere on the screen.+ Finder shown(String words) =>+ find.textContaining(words, findRichText: true);++ testWidgets("Team lists this project's alone: not another project's "+ 'task, nor its agent of the same name, nor a Buddy', (tester) async {+ await team(tester, twoProjects());++ expect(find.byType(SwarmWaitingRow), findsOneWidget, reason: 'Juno');+ expect(find.byType(SwarmWorkRow), findsOneWidget, reason: 'Nova');+ expect(shown('Desktop keychain'), findsNothing);+ expect(shown('#3002'), findsNothing);+ expect(key('swarm-member-agent-nova-2'), findsNothing);+ expect(key('swarm-member-buddy-pip'), findsNothing);+ expect(+ tester+ .widgetList<SwarmMemberRow>(find.byType(SwarmMemberRow))+ .where((row) => row.name == 'Nova')+ .length,+ 1,+ );+ expect(+ said(tester, 'swarm-team-tasks-caption'),+ 'Tasks | 1 waiting on you · 1 working',+ );+ });++ testWidgets('an agent of this project still holding work in another '+ 'names none of it on the Team, and opens none of it', (tester) async {+ final fake = twoProjects();+ await team(tester, fake);++ await tester.ensureVisible(key('swarm-member-agent-ash'));+ await tester.pumpAndSettle();+ expect(heard(tester, 'swarm-member-agent-ash'), 'Ash, Working');+ expect(shown('Desktop sign-in'), findsNothing);+ expect(shown('#3001'), findsNothing);++ await tester.tap(key('swarm-member-agent-ash'));+ await tester.pumpAndSettle();++ expect(key('swarm-project-team-list'), findsOneWidget);+ expect(fake.paths.where((p) => p.contains('/conversations/g3/')), []);+ });++ testWidgets("another Swarm's project, a work chat, a Buddy chat and the "+ "project's own chat are refused alike, with nothing of them shown "+ 'or read', (tester) async {+ for (final id in ['project-elsewhere', 'g1', 'buddy-chat', leadChat]) {+ final fake = twoProjects();+ await pump(+ tester,+ fake,+ SwarmProjectPage(+ swarmId: tab,+ projectId: id,+ tabs: SwarmProjectTab.homeC,+ ),+ );++ expect(+ find.text('This project is no longer in the Swarm.'),+ findsOneWidget,+ reason: id,+ );+ expect(key('swarm-project-tab-team'), findsNothing, reason: id);+ for (final words in [+ 'Mobile',+ 'Desktop',+ 'Buddy chat header',+ "$me's Buddy",+ 'Pip',+ ]) {+ expect(shown(words), findsNothing, reason: '$id: $words');+ }+ expect(+ fake.paths.where(+ (p) => p.contains('/messages') || p.contains('/leaderboard'),+ ),+ [],+ reason: id,+ );+ }+ });++ testWidgets('a board that lists someone who does not read the project '+ 'shows nothing of them', (tester) async {+ final fake = backend();+ final answer = fake.routes[board]!;+ fake.routes[board] = (body) {+ final read = answer(body)! as Map<String, dynamic>;+ return {+ ...read,+ 'people': [+ {+ ...scoreData('stranger', points: 9999, rank: 1, shipped: 40),+ 'displayName': 'Mallory',+ },+ ...read['people'] as List,+ ],+ };+ };+ await team(tester, fake);++ expect(shown('Mallory'), findsNothing);+ expect(shown('9999'), findsNothing);+ expect(shown('40 shipped'), findsNothing);+ expect(+ rowsAfter(+ tester,+ 'swarm-team-humans-caption',+ 'swarm-team-agents-caption',+ ),+ [+ 'swarm-member-person-person-me',+ 'swarm-member-person-diego',+ 'swarm-member-person-ken',+ ],+ );+ });++ testWidgets('access taken away with the Team open: its tasks and agents '+ 'go, and the Swarm read on its way brings none back', (tester) async {+ final fake = backend();+ await team(tester, fake);+ expect(find.byType(SwarmWaitingRow), findsOneWidget);++ final gate = hold(fake, '/api/super-tabs/$tab/changes');+ final reader = host(tester).session!.inbox.reader(tab)!;+ unawaited(reader.refresh());+ await tester.pump();+ reader.revoke();+ await tester.pump();+ gate.complete();+ await tester.pumpAndSettle();++ expect(find.byType(SwarmWaitingRow), findsNothing);+ expect(find.byType(SwarmWorkRow), findsNothing);+ expect(find.byType(SwarmMemberRow), findsNothing);+ for (final words in [+ 'Juno',+ 'Nova',+ 'Saved views cache',+ 'Buddy chat header',+ '#Mobile',+ ]) {+ expect(shown(words), findsNothing, reason: words);+ }+ expect(+ find.text('This project is no longer in the Swarm.'),+ findsOneWidget,+ );+ expect(fake.commands, isEmpty);+ });++ /// [backend] whose Mobile is private to the person and Diego, on its+ /// Team with Diego's week open.+ Future<FakeSwarm> diegoWeek(WidgetTester tester) async {+ final fake = backend();+ final load = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {+ final read = (await load(body))! as Map<String, dynamic>;+ final head = (read['head'] as Map)['data'] as Map<String, dynamic>;+ final mobile = (head['projects'] as List).single as Map;+ mobile['visibility'] = 'private';+ mobile['members'] = [+ {'id': 'diego', 'generation': 'gen-diego'},+ ];+ return read;+ };+ await team(tester, fake);+ await tester.tap(key('swarm-member-person-diego'));+ await tester.pumpAndSettle();+ expect(key('swarm-leaderboard-sheet'), findsOneWidget);+ expect(find.text('diego'), findsWidgets);+ return fake;+ }++ testWidgets("access taken away with a person's week open: the week "+ 'closes, and nothing of them stays', (tester) async {+ await diegoWeek(tester);++ host(tester).session!.inbox.reader(tab)!.revoke();+ await tester.pumpAndSettle();++ expect(key('swarm-leaderboard-sheet'), findsNothing);+ expect(find.text('diego'), findsNothing);+ });++ testWidgets("the project taken off the Swarm with a person's week open, "+ 'the Swarm still read: the week closes', (tester) async {+ final fake = await diegoWeek(tester);+ final reader = host(tester).session!.inbox.reader(tab)!;++ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c3'),+ 'head': part('head', 2, headData(projects: const [])),+ };+ await reader.refresh();+ await tester.pumpAndSettle();++ expect(reader.accessRevoked, isFalse, reason: 'the Swarm is still read');+ expect(key('swarm-leaderboard-sheet'), findsNothing);+ expect(find.text('diego'), findsNothing);+ });++ testWidgets("the account signing out with a person's week open: the "+ 'week closes', (tester) async {+ await diegoWeek(tester);++ (host(tester).account as ValueNotifier<String?>).value = null;+ await tester.pumpAndSettle();++ expect(key('swarm-leaderboard-sheet'), findsNothing);+ expect(find.text('diego'), findsNothing);+ });++ testWidgets('access taken away with the chat open: its messages go, and '+ 'nothing is marked read after', (tester) async {+ final fake = backend();+ await pump(tester, fake, page);+ expect(find.text('CI on #2154 is green.'), findsOneWidget);+ final posts = fake.calls.where((c) => c.method == 'POST').length;++ host(tester).session!.inbox.reader(tab)!.revoke();+ await tester.pumpAndSettle();++ expect(find.text('CI on #2154 is green.'), findsNothing);+ expect(key('swarm-new-messages-line'), findsNothing);+ expect(find.byType(TextField), findsNothing, reason: 'no composer');+ expect(+ find.text('This project is no longer in the Swarm.'),+ findsOneWidget,+ );+ expect(fake.calls.where((c) => c.method == 'POST').length, posts);+ });++ testWidgets("access taken away while the chat's first read is on its way: "+ 'the answer is dropped, and no Loading stays', (tester) async {+ final fake = backend();+ final gate = hold(fake, messages);+ await pump(tester, fake, page, settle: false);+ expect(find.byType(SwarmChatSkeleton), findsOneWidget);++ host(tester).session!.inbox.reader(tab)!.revoke();+ await tester.pump();+ gate.complete();+ await tester.pumpAndSettle();++ expect(find.text('CI on #2154 is green.'), findsNothing);+ expect(find.byType(SwarmChatSkeleton), findsNothing);+ expect(+ find.text('This project is no longer in the Swarm.'),+ findsOneWidget,+ );+ expect(+ fake.calls.where((c) => c.method == 'POST' && c.path.endsWith('/read')),+ isEmpty,+ );+ });++ testWidgets("a chat's first read that fails says so with no Loading left, "+ "and is read again once, at the Swarm's next read", (tester) async {+ final fake = backend();+ final answer = fake.routes[messages]!;+ fake.routes[messages] = (_) =>+ throw const SuperTabFailure('INTERNAL', 'Messages are down.');+ await pump(tester, fake, page);+ int reads() => fake.paths.where((p) => p.startsWith(messages)).length;++ expect(find.text('Messages are down.'), findsOneWidget);+ expect(find.byType(SwarmChatSkeleton), findsNothing);+ final opened = reads();+ expect(+ opened,+ lessThanOrEqualTo(2),+ reason: 'its open, and the Swarm read that came with it',+ );+ await tester.pump(const Duration(minutes: 1));+ expect(reads(), opened, reason: 'not again on its own, in a loop');++ fake.routes[messages] = answer;+ await host(tester).session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(reads(), opened + 1);+ expect(find.text('CI on #2154 is green.'), findsOneWidget);+ expect(find.text('Messages are down.'), findsNothing);+ });++ testWidgets("a page carrying another chat's message shows none of it, "+ 'says the read failed, and leaves no Loading', (tester) async {+ final fake = backend();+ fake.routes[messages] = (_) => {+ 'messages': [+ {+ 'id': 'msg-lead-1',+ 'conversationId': leadChat,+ 'text': 'CI on #2154 is green.',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ },+ {+ 'id': 'msg-buddy-1',+ 'conversationId': 'buddy-chat',+ 'text': 'A word to my Buddy.',+ 'sequence': 2,+ 'author': {'kind': 'person', 'id': me, 'name': me},+ },+ ],+ 'next': null,+ };+ await pump(tester, fake, page);++ expect(find.text('A word to my Buddy.'), findsNothing);+ expect(find.text('CI on #2154 is green.'), findsNothing);+ expect(find.text('Could not load messages. Try again.'), findsOneWidget);+ expect(find.byType(SwarmChatSkeleton), findsNothing);+ });+ });+}++/// A phone whose read marks come back only once [back] completes: its+/// other keys at once.+class _SlowMarks extends MemoryKeyValueStore {+ final back = Completer<void>();++ @override+ Future<String?> read(String key) async {+ if (key.startsWith('swarm_read_marks.')) await back.future;+ return super.read(key);+ }+}diff --git a/mobile/test/swarm/swarm_project_team_test.dart b/mobile/test/swarm/swarm_project_team_test.dartnew file mode 100644index 000000000..3f6048dba--- /dev/null+++ b/mobile/test/swarm/swarm_project_team_test.dart@@ -0,0 +1,271 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_project_team.dart';++import 'swarm_fixture.dart';++/// A project's Team, as Swarm Home C lists it (Dee's rules, 2026-10-29):+/// every agent in one of seven states, the most urgent first, and no ranks.+void main() {+ final now = DateTime(2026, 10, 30, 9);++ SuperTabSnapshot swarm({+ required List<Map<String, dynamic>> agents,+ List<Map<String, dynamic>> groups = const [],+ Map<String, dynamic> derived = const {},+ }) => SuperTabSnapshot.fromJson(+ SuperTabParts.firstLoad(+ firstLoad(agents: agents, groups: groups, derived: derived),+ ).state,+ );++ Map<String, dynamic> work(String agentId, String status, {int? number}) =>+ groupData(+ 'work-$agentId',+ title: 'Task of $agentId',+ number: number,+ agentIds: [agentId],+ status: status,+ workerId: agentId,+ );++ SwarmTeamAgent of(List<SwarmTeamAgent> team, String agentId) =>+ team.singleWhere((a) => a.agent.id == agentId);++ group('each agent', () {+ test('is in one of seven states, in words', () {+ final team = swarmProjectAgents(+ swarm(+ agents: [+ agent('a-input', displayName: 'Ana'),+ agent('a-stuck', displayName: 'Bo'),+ agent('a-review', displayName: 'Cy'),+ {+ ...agent('a-limit', displayName: 'Di'),+ 'limitedUntil': DateTime(+ 2026,+ 10,+ 30,+ 9,+ 5,+ ).toUtc().toIso8601String(),+ },+ {+ ...agent('a-down', displayName: 'Ed'),+ 'downSince': '2026-10-30T01:00:00Z',+ },+ agent('a-lost', displayName: 'Fy'),+ agent('a-work', displayName: 'Gu'),+ agent('a-check', displayName: 'Hu'),+ {...agent('a-done', displayName: 'Io'), 'workDecision': 'awaiting'},+ {...agent('a-kept', displayName: 'Jo'), 'workDecision': 'keep'},+ agent('a-idle', displayName: 'Ky'),+ {...agent('a-stop', displayName: 'Lu'), 'workDecision': 'stop'},+ ],+ groups: [+ work('a-input', 'needs_human'),+ work('a-stuck', 'blocked'),+ work('a-review', 'review'),+ work('a-lost', 'lost'),+ work('a-work', 'working'),+ work('a-check', 'reconciling'),+ ],+ ),+ project,+ now: now,+ );++ String said(String id) =>+ '${of(team, id).state.name}: '+ '${of(team, id).label}';+ expect(said('a-input'), 'needsInput: Needs input');+ expect(said('a-stuck'), 'needsInput: Stuck');+ expect(said('a-review'), 'waiting: Waiting for review');+ expect(said('a-limit'), 'waiting: Limited until 09:05');+ expect(said('a-down'), 'offline: Offline');+ expect(said('a-lost'), 'offline: Offline');+ expect(said('a-work'), 'working: Working');+ expect(said('a-check'), 'working: Checking');+ expect(said('a-done'), 'done: Done');+ expect(said('a-kept'), 'idle: Idle');+ expect(said('a-idle'), 'idle: Idle');+ expect(said('a-stop'), 'stopped: Stopped');+ });++ test('the Swarm saying it finished, after it was read idle, is Done', () {+ final team = swarmProjectAgents(+ swarm(+ agents: [agent('a1', displayName: 'Ana')],+ derived: {+ 'agents': {+ 'a1': {+ 'downSince': null,+ 'limitedUntil': null,+ 'workDecision': 'awaiting',+ 'roleId': null,+ },+ },+ },+ ),+ project,+ now: now,+ );++ expect(of(team, 'a1').state, SwarmMemberState.done);+ });++ test('being stopped outranks the work it still holds; offline outranks '+ 'being stopped', () {+ final team = swarmProjectAgents(+ swarm(+ agents: [+ {...agent('a1', displayName: 'Ana'), 'workDecision': 'stop'},+ {+ ...agent('a2', displayName: 'Bo'),+ 'workDecision': 'stop',+ 'downSince': '2026-10-30T01:00:00Z',+ },+ ],+ groups: [work('a1', 'working')],+ ),+ project,+ now: now,+ );++ expect(of(team, 'a1').state, SwarmMemberState.stopped);+ expect(of(team, 'a2').state, SwarmMemberState.offline);+ });++ test('holds its open task, said after its state', () {+ final team = swarmProjectAgents(+ swarm(+ agents: [+ agent('a1', displayName: 'Ana'),+ agent('a2'),+ ],+ groups: [work('a1', 'working', number: 2156)],+ ),+ project,+ now: now,+ );++ expect(of(team, 'a1').line, 'Working · #2156 Task of a1');+ expect(of(team, 'a2').line, 'Idle');+ });+ });++ group('the list', () {+ test('is the most urgent first, then by name, with no ranks', () {+ final team = swarmProjectAgents(+ swarm(+ agents: [+ {...agent('a-stop', displayName: 'Ash'), 'workDecision': 'stop'},+ agent('a-idle', displayName: 'bea'),+ {+ ...agent('a-done', displayName: 'Cal'),+ 'workDecision': 'awaiting',+ },+ agent('a-work2', displayName: 'Wren'),+ agent('a-work1', displayName: 'moss'),+ {+ ...agent('a-off', displayName: 'Dot'),+ 'downSince': '2026-10-30T01:00:00Z',+ },+ agent('a-wait', displayName: 'Juno'),+ agent('a-input', displayName: 'Zed'),+ ],+ groups: [+ work('a-work1', 'working'),+ work('a-work2', 'working'),+ work('a-wait', 'review'),+ work('a-input', 'needs_human'),+ ],+ ),+ project,+ now: now,+ );++ expect(+ [for (final a in team) a.name],+ ['Zed', 'Juno', 'Dot', 'moss', 'Wren', 'Cal', 'bea', 'Ash'],+ reason: 'letter case aside within a state',+ );+ });++ test("lists only this project's agents, never a Buddy, and matches by "+ 'id though another project has an agent of the same name', () {+ final team = swarmProjectAgents(+ swarm(+ agents: [+ agent('a-nova', displayName: 'Nova'),+ {...agent('b-nova', displayName: 'Nova'), 'projectId': 'project-2'},+ buddyData('buddy-me'),+ ],+ groups: [+ {...work('b-nova', 'needs_human'), 'projectId': 'project-2'},+ ],+ ),+ project,+ now: now,+ );++ expect([for (final a in team) a.agent.id], ['a-nova']);+ expect(+ of(team, 'a-nova').state,+ SwarmMemberState.idle,+ reason: "the other Nova's work is not this one's",+ );+ });++ test('names none of the work an agent still holds in another project, '+ 'and keeps its state', () {+ final team = swarmProjectAgents(+ swarm(+ agents: [agent('a-ash', displayName: 'Ash')],+ groups: [+ {+ ...work('a-ash', 'working', number: 3001),+ 'projectId': 'project-2',+ },+ ],+ ),+ project,+ now: now,+ );++ expect(of(team, 'a-ash').state, SwarmMemberState.working);+ expect(of(team, 'a-ash').task, isNull);+ expect(of(team, 'a-ash').line, 'Working');+ });++ test('counts what needs attention, in the order it is listed', () {+ final team = swarmProjectAgents(+ swarm(+ agents: [+ agent('a1'),+ agent('a2'),+ agent('a3'),+ agent('a4'),+ {...agent('a5'), 'workDecision': 'stop'},+ agent('a6'),+ ],+ groups: [+ work('a1', 'working'),+ work('a2', 'working'),+ work('a3', 'review'),+ work('a4', 'needs_human'),+ ],+ ),+ project,+ now: now,+ );++ expect(+ swarmTeamAgentsLine(team),+ '1 needs input · 1 waiting · 2 working',+ );+ expect(swarmTeamAgentsLine(const []), '');+ });+ });+}diff --git a/mobile/test/swarm/swarm_read_marks_test.dart b/mobile/test/swarm/swarm_read_marks_test.dartindex 8bf149ca0..ba57dfba6 100644--- a/mobile/test/swarm/swarm_read_marks_test.dart+++ b/mobile/test/swarm/swarm_read_marks_test.dart@@ -182,6 +182,69 @@ void main() {expect(r.marks.unread(chat(r.reader, work)), isFalse);});+ test("how far a chat is read is the higher of the server's mark and the "+ "phone's, none before the phone's are read back, nor once access is "+ 'lost', () async {+ final r = rig();+ expect(r.marks.readThrough(work), isNull, reason: 'nothing read back yet');+ await r.reader.refresh();+ await settle();+ expect(+ r.marks.readThrough(work),+ 4,+ reason: 'the first read on this phone',+ );++ moveOn(r.swarm, work, 9);+ await r.reader.refresh();+ await settle();+ expect(r.marks.readThrough(work), 4, reason: 'a new message is not read');+ r.marks.markRead(work, 6);+ expect(r.marks.readThrough(work), 6);++ r.reader.snapshot = SuperTabSnapshot.fromJson({+ ...headData(),+ 'people': [person(me)],+ 'agents': <Object>[],+ 'conversations': [+ groupData(leadChat, lastMessageSequence: 2),+ groupData(work, lastMessageSequence: 9),+ ],+ 'readMarks': {work: 8},+ });+ expect(+ r.marks.readThrough(work),+ 8,+ reason: "the server's, read elsewhere",+ );++ r.reader.revoke();+ expect(+ r.marks.readThrough(work),+ isNull,+ reason: 'access lost forgets them',+ );+ });++ test("the phone's marks still on their way are told apart from none: "+ 'loaded only once they are read back, with or without a mark', () async {+ final back = Completer<void>();+ final r = rig(store: _HeldStore(back.future));+ await r.reader.refresh();+ await settle();+ expect(r.marks.loaded, isFalse, reason: 'still on their way');+ expect(r.marks.readThrough(work), isNull);++ back.complete();+ await settle();+ expect(r.marks.loaded, isTrue, reason: 'back, though the phone had none');+ expect(+ r.marks.readThrough(work),+ 4,+ reason: 'the first read on this phone',+ );+ });+test("the server's marks come with the Swarm's reads, as on Desktop "'(#2131): a read that moves only a mark still counts', () async {final r = rig();@@ -370,3 +433,15 @@ class _SlowStore extends MemoryKeyValueStore {_pending.clear();}}++/// A phone store whose reads answer only once [back] completes.+class _HeldStore extends MemoryKeyValueStore {+ _HeldStore(this.back);+ final Future<void> back;++ @override+ Future<String?> read(String key) async {+ await back;+ return super.read(key);+ }+}diff --git a/mobile/test/swarm/swarm_unread_line_test.dart b/mobile/test/swarm/swarm_unread_line_test.dartnew file mode 100644index 000000000..dc54e536b--- /dev/null+++ b/mobile/test/swarm/swarm_unread_line_test.dart@@ -0,0 +1,84 @@+import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_unread_line.dart';++/// Where a chat's New messages line goes: above the first message the person+/// has not read, from someone else (Desktop's `superTabFirstUnread`).+void main() {+ const me = 'person-me';++ SuperTabMessage message(+ int sequence, {+ String author = 'agent-nova',+ String kind = 'agent',+ String? thread,+ bool alsoInChat = false,+ }) => SuperTabMessage.fromJson({+ 'id': 'm$sequence',+ 'conversationId': 'g1',+ 'text': 'Message $sequence',+ 'sequence': sequence,+ 'thread': ?thread,+ 'alsoInChat': alsoInChat,+ 'author': {'kind': kind, 'id': author, 'name': author},+ });++ 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);++ test('is the first message past the mark', () {+ expect(first([message(1), message(2), message(3)], 1), 'm2');+ });++ test('is none when everything is read, or no mark is known', () {+ expect(first([message(1), message(2)], 2), isNull);+ expect(first([message(1), message(2)], null), isNull);+ expect(first([message(1), message(2)], 0), isNull);+ expect(first(const [], 3), isNull);+ });++ test("passes over the person's own messages, and their own newest one "+ 'reads what came before it', () {+ expect(first([message(1), mine(2), message(3)], 1), 'm3');+ expect(+ first([message(1), message(2), mine(3)], 1),+ isNull,+ reason: 'writing in a chat reads it',+ );+ expect(+ first([mine(1, thread: 'm0'), message(2), mine(3, thread: 'm0')], 1),+ 'm2',+ reason: 'a reply only in its thread reads the thread, not the chat',+ );+ });++ test("passes over a reply only in its thread, and an agent's message "+ "with the person's id is someone else's", () {+ expect(first([message(1), message(2, thread: 'm1'), message(3)], 1), 'm3');+ expect(+ first([message(1), message(2, thread: 'm1', alsoInChat: true)], 1),+ 'm2',+ reason: 'also sent to the chat',+ );+ expect(first([message(1), message(2, author: me)], 1), 'm2');+ });++ test('is none when the mark is older than what was read and earlier '+ 'messages are still unread', () {+ expect(first([message(5), message(6)], 2, older: true), isNull);+ expect(+ first([message(3), message(4)], 2, older: true),+ 'm3',+ reason: 'the read reaches the mark',+ );+ expect(+ first([message(5), message(6)], 2),+ 'm5',+ reason: 'nothing is older than what was read',+ );+ });+}