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: Swarm Activity and Buddies screens (direction C, part b) (#2254)
harness-for-autonomous[bot]c7ca0f531157
diff --git a/mobile/lib/swarm/swarm_activity.dart b/mobile/lib/swarm/swarm_activity.dartnew file mode 100644index 000000000..49bec95dc--- /dev/null+++ b/mobile/lib/swarm/swarm_activity.dart@@ -0,0 +1,678 @@+import 'dart:async';+import 'dart:convert';++import 'package:flutter/foundation.dart';++import '../core/local_key_value_store.dart';+import 'model.dart';+import 'swarm_chat_peeks.dart';+import 'swarm_inbox.dart';+import 'swarm_reader.dart';+import 'swarm_session.dart';++/// Activity's filters, as Tony's prototype C3 names them.+enum SwarmActivityFilter {+ /// Decisions asked of the person and work waiting on them.+ needsYou('Needs you'),++ /// The Product Manager's tags of the person.+ mentions('@'),++ /// Threads the person wrote in or was tagged in.+ threads('Threads'),++ /// Others' reactions to what the person wrote.+ reactions('Reactions');++ const SwarmActivityFilter(this.label);+ final String label;+}++/// One row of Activity, in the Swarm it is in.+sealed class SwarmActivityItem {+ const SwarmActivityItem(this.swarmId);+ final String swarmId;++ /// Stable across reads: what the row and its handled mark are keyed by.+ String get key;+ SwarmActivityFilter get filter;++ /// The chat Reply opens.+ String get conversationId;++ /// The message Reply opens the chat at; null opens it at its end.+ String? get messageId;++ /// When it happened, where that is known.+ DateTime? get at;+}++/// Something a Swarm asks of the person ([SwarmNeed]): Needs you, or @ for a+/// tag.+class SwarmActivityNeed extends SwarmActivityItem {+ SwarmActivityNeed(this.need) : super(need.swarmId);+ final SwarmNeed need;++ @override+ String get key => need.key;++ @override+ SwarmActivityFilter get filter => need is SwarmMentionNeed+ ? SwarmActivityFilter.mentions+ : SwarmActivityFilter.needsYou;++ @override+ String get conversationId => need.conversationId;++ @override+ String? get messageId => switch (need) {+ SwarmMentionNeed(:final mention) => mention.messageId,+ _ => null,+ };++ @override+ DateTime? get at => switch (need) {+ SwarmDecisionNeed(:final decision) => decision.createdAt,+ SwarmMentionNeed(:final mention) => mention.createdAt,+ SwarmWorkNeed(:final work) => work.conversation.changedAt,+ };+}++/// A thread in a project chat that the person wrote in or was tagged in.+class SwarmActivityThread extends SwarmActivityItem {+ const SwarmActivityThread(+ super.swarmId, {+ required this.project,+ required this.chatId,+ required this.thread,+ this.root,+ });+ final SuperTabProject project;+ final String chatId;+ final SuperTabThread thread;++ /// Its first message, when the page read has it.+ final SuperTabMessage? root;++ @override+ String get key => 'thread:$swarmId:${thread.id}';++ @override+ SwarmActivityFilter get filter => SwarmActivityFilter.threads;++ @override+ String get conversationId => chatId;++ @override+ String? get messageId => thread.id;++ @override+ DateTime? get at => thread.lastAt;+}++/// Others' reactions to one of the person's messages in a project chat.+class SwarmActivityReaction extends SwarmActivityItem {+ const SwarmActivityReaction(+ super.swarmId, {+ required this.project,+ required this.chatId,+ required this.message,+ required this.reactions,+ });+ final SuperTabProject project;+ final String chatId;+ final SuperTabMessage message;++ /// Each emoji with who gave it, the person themself left out.+ final List<SuperTabReactionCount> reactions;++ @override+ String get key => 'reaction:$swarmId:${message.id}';++ @override+ SwarmActivityFilter get filter => SwarmActivityFilter.reactions;++ @override+ String get conversationId => chatId;++ @override+ String? get messageId => message.id;++ @override+ DateTime? get at => message.createdAt;++ /// Who gave which emoji, in one value: a reaction seen is handled until+ /// this moves.+ String get signature => ([+ for (final r in reactions)+ for (final who in r.by) '${r.emoji.key}:${who.kind}:${who.id}',+ ]..sort()).join(',');+}++/// Activity, in place of Needs you (Tony's prototype C3; Product Manager's+/// brief 10-30): what the Swarms ask of the person (Needs you, @), the threads+/// they are in and others' reactions to what they wrote, each filter counted,+/// and the rows they acted on kept as handled.+///+/// Needs you and @ are the inbox's, read already. Threads and Reactions come+/// from each project chat's newest page ([SwarmChatPeeks]), read only while+/// Activity is [shown] and only when the chat's counters moved; Buddy chats+/// and task chats are not read. A thread is handled once the person read the+/// chat past its last reply, or opened it here; a reaction once opened here.+/// Those marks are kept on the phone under the account and the Swarm (thread+/// and message ids, and numbers; no words), and leave it with the Swarm. A+/// need the person answered, marked done or opened here stays as a handled+/// row for the session.+class SwarmActivity extends ChangeNotifier {+ SwarmActivity(this.session, {LocalKeyValueStore? store})+ : store = store ?? session.inbox.readMarks {+ inbox.addListener(_changed);+ session.addListener(_changed);+ session.peeks.addListener(_changed);+ _changed();+ }++ final SwarmSession session;++ /// Where the handled marks of threads and reactions are kept; null keeps+ /// them in memory.+ final LocalKeyValueStore? store;++ SwarmInbox get inbox => session.inbox;+ String get accountId => session.accountId;++ /// How many handled needs are kept as rows once they leave the inbox.+ static const keptHandled = 20;++ /// How many marks each Swarm keeps on the phone: the oldest go first.+ static const keptMarks = 500;++ bool _disposed = false, _tracking = false;++ /// Needs acted on here, by key, with what was done: "Opened" at once,+ /// "Approved", "Answered" or "Done" once it was sent.+ final _acted = <String, ({String swarmId, String word})>{};++ /// Decisions approved from Activity: their answer, once sent, is "Approved".+ final _approving = <String>{};++ /// Needs acted on here that left the inbox, newest last.+ final _gone = <String, ({SwarmActivityNeed item, String word})>{};++ /// Each listed Swarm's handled marks.+ final _marks = <String, _SwarmMarks>{};++ Map<SwarmActivityFilter, List<SwarmActivityItem>>? _built;++ /// Screens showing Activity ([watch]): while there is one, the project+ /// chats are read when their counters move.+ int _views = 0;+ bool get shown => _views > 0;++ /// A screen shows Activity: its chats are read as their counters move.+ void watch() {+ if (_disposed || _views++ > 0) return;+ _want();+ }++ /// That screen went, or out of sight: once none shows it, the chats still+ /// waiting their turn for it are not read ([SwarmChatPeeks.withdraw]).+ void unwatch() {+ if (_views > 0 && --_views == 0) session.peeks.withdraw(this);+ }++ /// The rows of [filter]: those still to handle, newest first, then the+ /// handled ones.+ List<SwarmActivityItem> items(SwarmActivityFilter filter) =>+ (_built ??= _build())[filter] ?? const [];++ /// The rows of [filter] still to handle.+ int count(SwarmActivityFilter filter) =>+ items(filter).where((item) => handled(item) == null).length;++ /// The tab's badge, as the prototype draws it: what needs the person.+ int get badge => count(SwarmActivityFilter.needsYou);++ /// Some project chat could not be read at its last change.+ bool get unreadChats => _anyChat(session.peeks.failedAt);++ /// A project chat is being read for the first time since it moved, with+ /// nothing of it read yet: Threads and Reactions may still fill.+ bool get reading => _anyChat(+ (reader, chat) =>+ session.peeks.busyAt(reader, chat) &&+ session.peeks.of(reader, chat) == null,+ );++ /// The person's Try again: the project chats that failed are read again.+ void retry() => _anyChat((reader, chat) {+ session.peeks.retry(reader, chat, owner: this);+ return false;+ });++ /// Whether [test] holds for a project chat of a listed Swarm.+ bool _anyChat(bool Function(SwarmReader reader, String chatId) test) {+ for (final swarm in inbox.swarms) {+ final reader = inbox.reader(swarm.id);+ if (reader == null) continue;+ for (final (project: _, :chat) in _projectChats(reader)) {+ if (test(reader, chat.id)) return true;+ }+ }+ return false;+ }++ /// What the person did with [item], in a word, once it counts as handled;+ /// null while it is still to handle.+ String? handled(SwarmActivityItem item) {+ switch (item) {+ case SwarmActivityNeed():+ if (_gone[item.key] case final gone?) return gone.word;+ final acted = _acted[item.key]?.word;+ return acted == 'Opened' ? acted : null;+ case SwarmActivityThread(:final thread):+ final marks = _marks[item.swarmId];+ final reader = inbox.reader(item.swarmId);+ if (marks == null || reader == null) return null;+ final mine = switch (thread.authors.firstOrNull) {+ {'kind': 'person', 'id': final String id} => id == accountId,+ _ => false,+ };+ final read = reader.readMarks?.readThrough(item.chatId);+ final opened = marks.values['t:${thread.id}'];+ return mine ||+ read == null ||+ thread.lastSequence <= read ||+ opened is int && thread.lastSequence <= opened+ ? 'Read'+ : null;+ case SwarmActivityReaction():+ final seen = _marks[item.swarmId]?.values['r:${item.message.id}'];+ return seen == item.signature ? 'Seen' : null;+ }+ }++ /// The option Approve sends for [item]: a decision's recommended one;+ /// null for anything else, and while an answer is held or on its way.+ String? approveOption(SwarmActivityItem item) {+ if (item case SwarmActivityNeed(need: final SwarmDecisionNeed need)+ when _open(item)) {+ final decision = need.decision;+ final asks = inbox.asks(need.swarmId);+ final busy =+ session.held(need) != null ||+ (asks?.answering.contains(decision.id) ?? false) ||+ asks?.unconfirmed(decision) != null;+ final choice = decision.recommended;+ if (!busy && choice >= 0 && choice < decision.options.length) {+ return decision.options[choice];+ }+ }+ return null;+ }++ bool canApprove(SwarmActivityItem item) => approveOption(item) != null;++ /// Holds [item]'s recommended option for the session's Undo window, then+ /// sends it ([SwarmSession.hold]); the screen asks first. Sent, it is+ /// "Approved".+ void approve(SwarmActivityItem item) {+ if (_disposed || !canApprove(item)) return;+ final need = (item as SwarmActivityNeed).need as SwarmDecisionNeed;+ _approving.add(item.key);+ session.hold(need, need.decision.recommended);+ }++ /// The person opened [item] with Reply: handled at once. A need stays+ /// handled until it changes (its key moves); a thread until a newer reply,+ /// a reaction until someone else reacts.+ void replied(SwarmActivityItem item) {+ if (_disposed) return;+ switch (item) {+ case SwarmActivityNeed():+ if (!_open(item)) return;+ _acted[item.key] = (swarmId: item.swarmId, word: 'Opened');+ case SwarmActivityThread(:final thread):+ _marks[item.swarmId]?.put('t:${thread.id}', thread.lastSequence);+ case SwarmActivityReaction():+ _marks[item.swarmId]?.put('r:${item.message.id}', item.signature);+ }+ _built = null;+ notifyListeners();+ }++ bool _open(SwarmActivityNeed item) =>+ inbox.needs.any((need) => need.key == item.key);++ /// Each project chat [reader] holds, with its project: never a Buddy chat.+ Iterable<({SuperTabProject project, SuperTabConversation chat})>+ _projectChats(SwarmReader reader) sync* {+ final snapshot = reader.snapshot;+ if (snapshot == null || reader.accessRevoked) return;+ for (final project in snapshot.projects) {+ final chat = snapshot.conversation(project.leadConversationId);+ if (chat == null || chat.isBuddyChat) continue;+ yield (project: project, chat: chat);+ }+ }++ void _changed() {+ if (_disposed) return;+ _sweep();+ _seed();+ _built = null;+ if (shown) _want();+ // What a send does is told before the send starts (SwarmSession._send):+ // what was done is looked at once it has.+ if (!_tracking) {+ _tracking = true;+ scheduleMicrotask(() {+ _tracking = false;+ if (!_disposed) _track();+ });+ }+ notifyListeners();+ }++ /// A Swarm off the list, or no longer readable, takes its marks off the+ /// phone and its handled rows with it; one newly listed reads its marks.+ void _sweep() {+ final listed = {for (final swarm in inbox.swarms) swarm.id};+ bool gone(String swarmId) =>+ !listed.contains(swarmId) ||+ (inbox.reader(swarmId)?.accessRevoked ?? true);+ for (final MapEntry(key: id, value: marks) in _marks.entries.toList()) {+ if (gone(id) || !identical(inbox.reader(id), marks.reader)) {+ _marks.remove(id)!.forget();+ }+ }+ _acted.removeWhere((_, acted) => gone(acted.swarmId));+ _gone.removeWhere((_, row) => gone(row.item.swarmId));+ for (final id in listed) {+ final reader = inbox.reader(id);+ if (reader == null || reader.accessRevoked || _marks.containsKey(id)) {+ continue;+ }+ _marks[id] = _SwarmMarks(reader, store, accountId, onLoaded: _changed);+ }+ }++ bool _held(String key) => inbox.needs.any(+ (need) =>+ need.key == key &&+ need is SwarmDecisionNeed &&+ session.held(need) != null,+ );++ /// On this phone's first Activity of a Swarm, the reactions already there+ /// count as seen: a new phone does not start with all of them new.+ void _seed() {+ for (final MapEntry(key: id, value: marks) in _marks.entries) {+ if (!marks.loaded || marks.found) continue;+ for (final (:project, :chat) in _projectChats(marks.reader)) {+ if (marks.seeded.contains(chat.id)) continue;+ final peek = session.peeks.of(marks.reader, chat.id);+ if (peek == null) continue;+ marks.seeded.add(chat.id);+ for (final item in _reactions(id, project, chat.id, peek)) {+ marks.put('r:${item.message.id}', item.signature);+ }+ }+ }+ }++ /// Asks for each project chat as its counters stand: read only if they+ /// moved since it was last read.+ void _want() {+ for (final swarm in inbox.swarms) {+ final reader = inbox.reader(swarm.id);+ if (reader == null) continue;+ for (final (project: _, :chat) in _projectChats(reader)) {+ session.peeks.want(+ reader,+ chat.id,+ counter: (chat.lastMessageSequence, chat.reactionSeq),+ owner: this,+ );+ }+ }+ }++ /// What was done with each need, once it is done: an answer on its way+ /// is sent, a tag being marked is done. A need acted on that left the+ /// inbox stays as a handled row.+ void _track() {+ final open = {for (final need in inbox.needs) need.key: need};+ var changed = false;+ for (final need in open.values) {+ final asks = inbox.asks(need.swarmId);+ final String? word = switch (need) {+ SwarmDecisionNeed(:final decision)+ when (asks?.answering.contains(decision.id) ?? false) ||+ asks?.unconfirmed(decision) != null =>+ _approving.contains(need.key) ? 'Approved' : 'Answered',+ SwarmMentionNeed(:final mention)+ when asks?.finishing(mention) ?? false =>+ 'Done',+ _ => null,+ };+ if (word != null && _acted[need.key]?.word != word) {+ _acted[need.key] = (swarmId: need.swarmId, word: word);+ changed = true;+ }+ // A Done that failed is not done.+ if (need case SwarmMentionNeed(:final mention)+ when asks?.notDone(mention) != null &&+ _acted[need.key]?.word == 'Done') {+ _acted.remove(need.key);+ changed = true;+ }+ }+ // An Approve undone, or dropped before it was sent, is no Approve.+ _approving.removeWhere((key) => !_acted.containsKey(key) && !_held(key));+ for (final key in _acted.keys.toList()) {+ if (open.containsKey(key)) continue;+ final acted = _acted.remove(key)!;+ _approving.remove(key);+ final row = _last[key];+ if (row != null) {+ _gone[key] = (item: row, word: acted.word);+ while (_gone.length > keptHandled) {+ _gone.remove(_gone.keys.first);+ }+ }+ changed = true;+ }+ _last+ ..clear()+ ..addAll({+ for (final need in open.values) need.key: SwarmActivityNeed(need),+ });+ if (changed) {+ _built = null;+ notifyListeners();+ }+ }++ /// Each open need's row as last seen: what a handled row shows once it+ /// left the inbox.+ final _last = <String, SwarmActivityNeed>{};++ Map<SwarmActivityFilter, List<SwarmActivityItem>> _build() {+ final rows = {+ for (final f in SwarmActivityFilter.values) f: <SwarmActivityItem>[],+ };+ for (final need in inbox.needs) {+ final item = SwarmActivityNeed(need);+ rows[item.filter]!.add(item);+ }+ for (final swarm in inbox.swarms) {+ final reader = inbox.reader(swarm.id);+ if (reader == null) continue;+ for (final (:project, :chat) in _projectChats(reader)) {+ final peek = session.peeks.of(reader, chat.id);+ if (peek == null) continue;+ rows[SwarmActivityFilter.threads]!.addAll(+ _threads(swarm.id, project, chat.id, peek),+ );+ rows[SwarmActivityFilter.reactions]!.addAll(+ _reactions(swarm.id, project, chat.id, peek),+ );+ }+ }+ int newest(SwarmActivityItem a, SwarmActivityItem b) =>+ (b.at ?? DateTime(0)).compareTo(a.at ?? DateTime(0));+ for (final filter in [+ SwarmActivityFilter.threads,+ SwarmActivityFilter.reactions,+ ]) {+ rows[filter]!.sort(newest);+ }+ final built = <SwarmActivityFilter, List<SwarmActivityItem>>{};+ for (final MapEntry(key: filter, value: list) in rows.entries) {+ final handledNeeds = [+ for (final row in _gone.values.toList().reversed)+ if (row.item.filter == filter) row.item,+ ];+ built[filter] = List.unmodifiable([+ ...list.where((item) => handled(item) == null),+ ...list.where((item) => handled(item) != null),+ ...handledNeeds,+ ]);+ }+ return built;+ }++ Iterable<SwarmActivityThread> _threads(+ String swarmId,+ SuperTabProject project,+ String chatId,+ SwarmPeek peek,+ ) sync* {+ for (final thread in peek.threads.values) {+ if (!thread.people.contains(accountId) || thread.replies == 0) continue;+ yield SwarmActivityThread(+ swarmId,+ project: project,+ chatId: chatId,+ thread: thread,+ root: peek.messages.where((m) => m.id == thread.id).firstOrNull,+ );+ }+ }++ Iterable<SwarmActivityReaction> _reactions(+ String swarmId,+ SuperTabProject project,+ String chatId,+ SwarmPeek peek,+ ) sync* {+ for (final message in peek.messages) {+ if (message.fromAgent || message.authorId != accountId) continue;+ final others = [+ for (final r in message.reactions)+ if ([+ for (final who in r.by)+ if (!(who.kind == 'person' && who.id == accountId)) who,+ ]+ case final by when by.isNotEmpty)+ SuperTabReactionCount(r.emoji, by),+ ];+ if (others.isEmpty) continue;+ yield SwarmActivityReaction(+ swarmId,+ project: project,+ chatId: chatId,+ message: message,+ reactions: List.unmodifiable(others),+ );+ }+ }++ @override+ void dispose() {+ _disposed = true;+ inbox.removeListener(_changed);+ session.removeListener(_changed);+ session.peeks.removeListener(_changed);+ // Closing keeps the marks on the phone for the next session.+ _marks.clear();+ super.dispose();+ }+}++/// One Swarm's handled marks on the phone: a thread's last reply opened, a+/// message's reactions seen.+class _SwarmMarks {+ _SwarmMarks(+ this.reader,+ this.store,+ String accountId, {+ required this.onLoaded,+ }) : _key = 'swarm_activity.$accountId.${reader.tabId}' {+ unawaited(_load());+ }++ final SwarmReader reader;+ final LocalKeyValueStore? store;+ final VoidCallback onLoaded;+ final String _key;+ final values = <String, Object>{};++ /// The project chats seeded on this phone's first Activity.+ final seeded = <String>{};+ bool loaded = false, found = false, _forgotten = false;++ Future<void> _load() async {+ final held = <String, Object>{};+ var found = false;+ try {+ if (await store?.read(_key) case final raw?) {+ if (jsonDecode(raw) case {'marks': final Map marks}) {+ for (final MapEntry(:key, :value) in marks.entries) {+ if (key is String && (value is int || value is String)) {+ held[key] = value as Object;+ }+ }+ found = true;+ }+ }+ } catch (_) {+ // An unreadable value is no marks: this Activity starts afresh.+ }+ if (_forgotten) return;+ for (final MapEntry(:key, :value) in held.entries) {+ values.putIfAbsent(key, () => value);+ }+ this.found = found;+ loaded = true;+ if (values.isNotEmpty) _write();+ onLoaded();+ }++ void put(String key, Object value) {+ if (_forgotten || values[key] == value) return;+ values.remove(key);+ values[key] = value;+ while (values.length > SwarmActivity.keptMarks) {+ values.remove(values.keys.first);+ }+ _write();+ }++ void _write() {+ if (!loaded || _forgotten) return;+ unawaited(+ store+ ?.write(_key, jsonEncode({'marks': values}))+ .catchError((Object _) {}),+ );+ }++ /// The Swarm left: nothing of it stays on the phone.+ void forget() {+ _forgotten = true;+ values.clear();+ unawaited(store?.delete(_key).catchError((Object _) {}));+ }+}diff --git a/mobile/lib/swarm/swarm_activity_page.dart b/mobile/lib/swarm/swarm_activity_page.dartnew file mode 100644index 000000000..935e0b5d1--- /dev/null+++ b/mobile/lib/swarm/swarm_activity_page.dart@@ -0,0 +1,744 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/fzf.dart' show fzfAge;+import 'package:harness_mobile/phone/out_of_sight.dart';+import 'package:harness_mobile/phone/phone_navigation.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';++import 'identity.dart';+import 'swarm_activity.dart';+import 'swarm_conversation_page.dart';+import 'swarm_home_rows.dart' show swarmNeedAsk;+import 'swarm_inbox.dart';+import 'swarm_need_rows.dart';+import 'swarm_reader.dart';+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';++/// Opens Activity over [context]'s page: [focus] — a row's key — open in+/// full under its filter; only Swarm [swarmId]'s rows when Home shows that+/// Swarm alone.+void openSwarmActivity(+ BuildContext context, {+ String? focus,+ String? swarmId,+}) => unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => SwarmActivityPage(focus: focus, swarmId: swarmId),+ listensForItself: true,+ ),+ ),+);++/// Activity as a page of its own, with a way back: Home's "See all" and its+/// rows open it until the tab bar does.+class SwarmActivityPage extends StatelessWidget {+ const SwarmActivityPage({super.key, this.focus, this.swarmId});++ final String? focus, swarmId;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Scaffold(+ backgroundColor: AppPalette.windowBg,+ body: SwarmActivityView(+ focus: focus,+ swarmId: swarmId,+ leading: SwarmBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ ),+ );+ }+}++/// Activity, in place of Needs you (Tony's prototype C3): its title in the+/// terminal's face, the filters — Needs you · @ · Threads · Reactions — each+/// with its count, then the open filter's rows: where and who over what, and+/// Approve (which asks first) or Reply at the row's end. A row the person+/// handled stays, dimmed, under the others. The Activity tab's screen, and+/// [SwarmActivityPage]'s.+///+/// Only while it is in sight ([OutOfSight]) does it read the project chats+/// ([SwarmActivity.watch]) and keep the Swarm's notices quiet.+class SwarmActivityView extends StatefulWidget {+ const SwarmActivityView({super.key, this.focus, this.swarmId, this.leading});++ /// The row open first, by its key.+ final String? focus;++ /// Only this Swarm's rows; null for every Swarm's.+ final String? swarmId;++ /// Before the title: a page's back; none on the tab.+ final Widget? leading;++ @override+ State<SwarmActivityView> createState() => _SwarmActivityViewState();+}++class _SwarmActivityViewState extends State<SwarmActivityView> {+ SwarmSession? _session;+ bool _seen = false;+ late SwarmActivityFilter _filter = _filterOf(widget.focus);+ late String? _open = widget.focus;++ static SwarmActivityFilter _filterOf(String? key) => switch (key) {+ final key? when key.startsWith('mention:') => SwarmActivityFilter.mentions,+ final key? when key.startsWith('thread:') => SwarmActivityFilter.threads,+ final key? when key.startsWith('reaction:') =>+ SwarmActivityFilter.reactions,+ _ => SwarmActivityFilter.needsYou,+ };++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final session = SwarmScope.of(context);+ final seen = session != null && !OutOfSight.of(context);+ if (identical(session, _session) && seen == _seen) return;+ _see(false);+ _session = session;+ _see(seen);+ }++ /// In sight: Activity reads its chats, the inbox is read now, and the+ /// Swarm's notices keep quiet. Out of sight, none of it.+ void _see(bool seen) {+ final session = _session;+ if (session == null || seen == _seen) return;+ _seen = seen;+ if (seen) {+ session.enter();+ session.activity.watch();+ unawaited(session.inbox.refresh());+ } else {+ session.activity.unwatch();+ session.leave();+ }+ }++ @override+ void dispose() {+ _see(false);+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final session = _session;+ return Material(+ color: AppPalette.windowBg,+ child: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (widget.leading case final leading?)+ SwarmTopBar(leading: leading, title: 'Activity')+ else+ const SwarmTabHeader('Activity'),+ if (session != null)+ Expanded(+ child: ListenWhileInSight(+ listenable: session.activity,+ builder: (context) => _body(context, session),+ ),+ ),+ ],+ ),+ ),+ );+ }++ /// [filter]'s rows, of [widget.swarmId] alone when it names one.+ List<SwarmActivityItem> _items(+ SwarmActivity activity,+ SwarmActivityFilter filter,+ ) => [+ for (final item in activity.items(filter))+ if (widget.swarmId == null || item.swarmId == widget.swarmId) item,+ ];++ Widget _body(BuildContext context, SwarmSession session) {+ final activity = session.activity;+ final items = _items(activity, _filter);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SingleChildScrollView(+ scrollDirection: Axis.horizontal,+ padding: const EdgeInsets.fromLTRB(+ AppSpace.m,+ AppSpace.xs,+ AppSpace.m,+ AppSpace.s,+ ),+ child: Row(+ children: [+ for (final (i, filter) in SwarmActivityFilter.values.indexed) ...[+ if (i > 0) const SizedBox(width: AppSpace.s),+ SwarmActivityFilterPill(+ key: ValueKey('swarm-activity-filter-${filter.name}'),+ filter: filter,+ count: _items(+ activity,+ filter,+ ).where((item) => activity.handled(item) == null).length,+ selected: filter == _filter,+ onTap: () => setState(() => _filter = filter),+ ),+ ],+ ],+ ),+ ),+ Expanded(+ child: ListView(+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ AppSpace.xs,+ AppSpace.m,+ MediaQuery.paddingOf(context).bottom + AppSpace.xl,+ ),+ children: _rows(context, session, items),+ ),+ ),+ ],+ );+ }++ List<Widget> _rows(+ BuildContext context,+ SwarmSession session,+ List<SwarmActivityItem> items,+ ) {+ final activity = session.activity, inbox = session.inbox;+ final fromChats =+ _filter == SwarmActivityFilter.threads ||+ _filter == SwarmActivityFilter.reactions;+ final note = AppType.caption(color: AppPalette.textSecondary, height: 1.35);+ return [+ if (fromChats && activity.unreadChats)+ _Note(+ text: 'Some chats could not be read.',+ action: SwarmButton(+ key: const ValueKey('swarm-activity-retry'),+ label: 'Try again',+ style: SwarmButtonStyle.link,+ onPressed: activity.retry,+ ),+ ),+ if (!inbox.loaded && inbox.error != null)+ _Note(+ text: inbox.error!,+ action: SwarmButton(+ key: const ValueKey('swarm-activity-retry-list'),+ label: 'Try again',+ style: SwarmButtonStyle.link,+ onPressed: () => unawaited(inbox.refresh()),+ ),+ )+ else if (items.isEmpty &&+ (!inbox.loaded || fromChats && activity.reading))+ SwarmSkeletonRows(id: 'swarm-activity-loading', round: true)+ else if (items.isEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.xs,+ vertical: AppSpace.s,+ ),+ child: Text(+ _nothing(_filter),+ key: const ValueKey('swarm-activity-none'),+ style: note,+ ),+ )+ else+ SwarmGroup(+ children: [for (final item in items) _row(context, session, item)],+ ),+ ];+ }++ static String _nothing(SwarmActivityFilter filter) => switch (filter) {+ SwarmActivityFilter.needsYou => 'Nothing needs you.',+ SwarmActivityFilter.mentions => 'No one tagged you.',+ SwarmActivityFilter.threads => 'No threads with you yet.',+ SwarmActivityFilter.reactions => 'No reactions to you yet.',+ };++ Widget _row(+ BuildContext context,+ SwarmSession session,+ SwarmActivityItem item,+ ) {+ final activity = session.activity;+ final handled = activity.handled(item);+ // A need tapped opens in full: every option, Done, Open chat.+ if (item case SwarmActivityNeed(:final need)+ when handled == null && item.key == _open) {+ return SwarmNeedRow(+ key: ValueKey('swarm-activity-open-${item.key}'),+ session: session,+ need: need,+ onOpen: (_, _) => _reply(context, session, item),+ );+ }+ return SwarmActivityRow(+ key: ValueKey('swarm-activity-row-${item.key}'),+ session: session,+ item: item,+ handled: handled,+ now: DateTime.now(),+ onTap: () => item is SwarmActivityNeed && handled == null+ ? setState(() => _open = item.key)+ : _reply(context, session, item),+ onApprove: () => unawaited(_approve(context, session, item)),+ onReply: () => _reply(context, session, item),+ );+ }++ /// Opens where [item] was asked, at its message, and counts it handled.+ void _reply(+ BuildContext context,+ SwarmSession session,+ SwarmActivityItem item,+ ) {+ session.activity.replied(item);+ unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => SwarmConversationPage(+ swarmId: item.swarmId,+ conversationId: item.conversationId,+ messageId: item.messageId,+ decisionId: switch (item) {+ SwarmActivityNeed(need: SwarmDecisionNeed(:final decision)) =>+ decision.id,+ _ => null,+ },+ ),+ listensForItself: true,+ ),+ ),+ );+ }++ /// Approve asks first, naming the option it sends and to whom; then the+ /// answer is held for Undo before it goes ([SwarmActivity.approve]).+ Future<void> _approve(+ BuildContext context,+ SwarmSession session,+ SwarmActivityItem item,+ ) async {+ final option = session.activity.approveOption(item);+ if (option == null ||+ item is! SwarmActivityNeed ||+ item.need is! SwarmDecisionNeed) {+ return;+ }+ final need = item.need as SwarmDecisionNeed;+ final yes = await confirmSwarmApprove(context, need, option);+ if (yes && mounted) session.activity.approve(item);+ }+}++/// Asks before [option] is sent as the answer to [need]: who asked, where,+/// and the question, and that it can still be undone. True once the person+/// confirms; the caller then holds the answer for Undo and sends it+/// ([SwarmSession.hold]). Activity's Approve asks this.+Future<bool> confirmSwarmApprove(+ BuildContext context,+ SwarmDecisionNeed need,+ String option,+) async {+ final decision = need.decision;+ final where = decision.projectName.isEmpty+ ? ''+ : ' in #${decision.projectName}';+ final yes = await showDialog<bool>(+ context: context,+ builder: (context) => AlertDialog(+ title: Text(+ 'Approve?',+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ content: Text(+ 'Sends “$option” to ${decision.askerName}$where: '+ '${decision.question}\n\nYou can undo it for a few seconds.',+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ actions: [+ SwarmButton(+ key: const ValueKey('swarm-activity-approve-cancel'),+ label: 'Cancel',+ style: SwarmButtonStyle.link,+ onPressed: () => Navigator.of(context).pop(false),+ ),+ SwarmButton(+ key: const ValueKey('swarm-activity-approve-confirm'),+ label: 'Approve',+ style: SwarmButtonStyle.fill,+ onPressed: () => Navigator.of(context).pop(true),+ ),+ ],+ ),+ );+ return yes ?? false;+}++/// A line over the rows, with what can be done about it.+class _Note extends StatelessWidget {+ const _Note({required this.text, required this.action});++ final String text;+ final Widget action;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.only(left: AppSpace.xs, bottom: AppSpace.s),+ child: Row(+ children: [+ Expanded(+ child: Text(+ text,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.35,+ ),+ ),+ ),+ action,+ ],+ ),+ );+}++/// One of Activity's filters: its name and count in a pill a thumb can find,+/// filled while it is the one open.+class SwarmActivityFilterPill extends StatelessWidget {+ const SwarmActivityFilterPill({+ super.key,+ required this.filter,+ required this.count,+ required this.selected,+ required this.onTap,+ });++ final SwarmActivityFilter filter;+ final int count;+ final bool selected;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final ink = selected ? AppPalette.windowBg : AppPalette.textPrimary;+ final heard = filter == SwarmActivityFilter.mentions+ ? 'Mentions'+ : filter.label;+ return Semantics(+ button: true,+ selected: selected,+ label: '$heard, $count',+ excludeSemantics: true,+ child: Material(+ color: selected+ ? AppPalette.textPrimary+ : AppPalette.swarmSearchSurface,+ shape: const StadiumBorder(),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 44, minWidth: 44),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.l),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ filter.label,+ style: AppType.label(+ color: ink,+ fontWeight: AppFont.semibold,+ height: 1,+ ),+ ),+ const SizedBox(width: 6),+ Text(+ '$count',+ style: AppType.label(+ color: selected+ ? ink.withValues(alpha: .7)+ : AppPalette.textSecondary,+ height: 1,+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}++/// One row of Activity, as prototype C3 draws it: who it is from, "#project ·+/// who · when" over what it is in bold, maybe a line under that (a thread's+/// replies, the reactions), and at its end Approve or Reply. A decision+/// whose answer is held or on its way shows that, with Undo, in place of+/// the button; a handled row is dimmed, with what was done at its end.+class SwarmActivityRow extends StatelessWidget {+ const SwarmActivityRow({+ super.key,+ required this.session,+ required this.item,+ required this.handled,+ required this.now,+ required this.onTap,+ required this.onApprove,+ required this.onReply,+ });++ final SwarmSession session;+ final SwarmActivityItem item;++ /// What was done with it; null while it is still to handle.+ final String? handled;+ final DateTime now;+ final VoidCallback onTap, onApprove, onReply;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final reader = session.inbox.reader(item.swarmId);+ final who = swarmActivityWho(item, reader);+ final busy = _busy();+ final line = _line();+ final content = Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SwarmAvatar(id: who.id, name: who.name),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ [+ '#${_project()}',+ who.name,+ fzfAge(item.at?.toLocal(), now.toLocal()),+ ].where((part) => part.length > 1).join(' · '),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.35,+ ),+ ),+ const SizedBox(height: 2),+ Text(+ _title(),+ maxLines: 3,+ overflow: TextOverflow.ellipsis,+ style: AppType.label(+ color: AppPalette.textPrimary,+ fontWeight: handled == null+ ? AppFont.semibold+ : AppFont.regular,+ height: 1.3,+ ),+ ),+ if (line != null) ...[+ const SizedBox(height: 2),+ SwarmRow.line(line),+ ],+ ],+ ),+ ),+ ],+ );+ final Widget? end = switch (handled) {+ final word? => Row(+ key: ValueKey('swarm-activity-handled-${item.key}'),+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(LucideIcons.check300, size: 16, color: AppPalette.textFaint),+ const SizedBox(width: 4),+ Text(word, style: AppType.caption(color: AppPalette.textFaint)),+ ],+ ),+ null when busy != null => null,+ null when session.activity.canApprove(item) => SwarmButton(+ key: ValueKey('swarm-activity-approve-${item.key}'),+ label: 'Approve',+ style: SwarmButtonStyle.fill,+ onPressed: onApprove,+ ),+ null => SwarmButton(+ key: ValueKey('swarm-activity-reply-${item.key}'),+ label: 'Reply',+ onPressed: onReply,+ ),+ };+ return Material(+ type: MaterialType.transparency,+ child: InkWell(+ onTap: onTap,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ vertical: AppSpace.m,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.center,+ children: [+ Expanded(+ child: handled == null+ ? content+ : Opacity(opacity: .55, child: content),+ ),+ if (end != null) ...[const SizedBox(width: 12), end],+ ],+ ),+ if (busy != null) ...[+ const SizedBox(height: AppSpace.m),+ // Under the words, past the 32-point avatar and the gap beside it.+ Row(+ children: [+ const SizedBox(width: 32 + 12),+ Expanded(child: busy),+ ],+ ),+ ],+ ],+ ),+ ),+ ),+ );+ }++ /// A decision whose answer is held, on its way, not confirmed or dropped:+ /// what its full card says of it, with Undo while it is held.+ Widget? _busy() {+ if (item case SwarmActivityNeed(need: final SwarmDecisionNeed need)+ when handled == null) {+ final asks = session.inbox.asks(need.swarmId);+ if (session.held(need) != null ||+ (asks?.answering.contains(need.decision.id) ?? false) ||+ asks?.unconfirmed(need.decision) != null ||+ session.dropped(need)) {+ return SwarmDecisionAnswer(session: session, need: need);+ }+ }+ return null;+ }++ String _project() => switch (item) {+ SwarmActivityNeed(:final need) => switch (need) {+ SwarmDecisionNeed(:final decision) => decision.projectName,+ SwarmMentionNeed(:final mention) => mention.projectName,+ SwarmWorkNeed(:final work) => work.project.name,+ },+ SwarmActivityThread(:final project) => project.name,+ SwarmActivityReaction(:final project) => project.name,+ };++ String _title() => switch (item) {+ SwarmActivityNeed(:final need) => swarmNeedAsk(need),+ SwarmActivityThread(:final root, :final project) => switch (root?.text) {+ final text? when text.trim().isNotEmpty => text.trim(),+ _ => 'A thread in #${project.name}',+ },+ SwarmActivityReaction(:final message) => message.text.trim(),+ };++ String? _line() => switch (item) {+ SwarmActivityThread(:final thread) =>+ thread.replies == 1 ? '1 reply' : '${thread.replies} replies',+ SwarmActivityReaction(:final reactions) => [+ for (final r in reactions) '${r.emoji.glyph} ${r.count}',+ ].join(' '),+ _ => null,+ };+}++/// Who an Activity row is from, by an id its avatar is coloured by and a+/// name, read in the row's own Swarm ([reader]) and never another's: the+/// asker, the tagging Lead, the worker, a thread's last writer, or who+/// reacted. A person is named by their email's name, never the email.+({String id, String name}) swarmActivityWho(+ SwarmActivityItem item,+ SwarmReader? reader,+) {+ final snapshot = reader?.snapshot;+ String named(String kind, String id, String fallback) {+ if (kind == 'person' && id == reader?.accountId) return 'You';+ if (kind == 'agent') {+ return snapshot?.agentName(id, fallback: fallback) ?? fallback;+ }+ final email = snapshot?.people.where((p) => p.id == id).firstOrNull?.email;+ return email == null || email.isEmpty+ ? 'Someone'+ : superTabPersonName(email);+ }++ return switch (item) {+ SwarmActivityNeed(:final need) => switch (need) {+ SwarmDecisionNeed(:final decision) => (+ id: 'asker:${decision.askerName}',+ name: decision.askerName,+ ),+ SwarmMentionNeed(:final mention) => (+ id: 'lead:${mention.leadName}',+ name: mention.leadName,+ ),+ SwarmWorkNeed(:final work) => (+ id: work.conversation.assignment?['agentId'] as String? ?? 'work',+ name: work.agentName,+ ),+ },+ SwarmActivityThread(:final thread) => switch (thread.authors.firstOrNull) {+ {'kind': final String kind, 'id': final String id} && final author => (+ id: id,+ name: named(+ kind,+ id,+ author['displayName'] as String? ??+ author['name'] as String? ??+ 'Someone',+ ),+ ),+ _ => (id: thread.id, name: 'Someone'),+ },+ SwarmActivityReaction(:final reactions) => () {+ final by = [+ for (final r in reactions)+ for (final who in r.by) who,+ ];+ final names = {for (final who in by) named(who.kind, who.id, 'Someone')}+ .toList();+ return (+ id: by.isEmpty ? item.key : by.first.id,+ name: names.length <= 2+ ? names.join(', ')+ : '${names.take(2).join(', ')} +${names.length - 2}',+ );+ }(),+ };+}diff --git a/mobile/lib/swarm/swarm_buddies_page.dart b/mobile/lib/swarm/swarm_buddies_page.dartnew file mode 100644index 000000000..7fb7d0739--- /dev/null+++ b/mobile/lib/swarm/swarm_buddies_page.dart@@ -0,0 +1,361 @@+import 'dart:async';++import 'package:flutter/material.dart';++import 'package:harness_mobile/phone/fzf.dart' show fzfAge;+import 'package:harness_mobile/phone/out_of_sight.dart';+import 'package:harness_mobile/phone/phone_navigation.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'swarm_buddy_list.dart';+import 'swarm_project_page.dart';+import 'swarm_project_tabs.dart' show SwarmProjectTab;+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';++/// Buddies (Tony's prototype C2): its title in the terminal's face, then a+/// row for each project ([SwarmBuddyRow]), newest first — its tile, its+/// name, how the person's Buddy there stands, and the last message of their+/// Buddy chat — bold with a dot while that chat has something unread. A tap+/// opens the project on its Buddy tab, where the chat is, or where the Buddy+/// is started. The Buddies tab's screen.+///+/// Only while it is in sight ([OutOfSight]) does it read the Buddy chats+/// ([SwarmBuddyList.watch]) and keep the Swarm's notices quiet.+class SwarmBuddiesView extends StatefulWidget {+ const SwarmBuddiesView({super.key, this.leading});++ /// Before the title: a page's back; none on the tab.+ final Widget? leading;++ @override+ State<SwarmBuddiesView> createState() => _SwarmBuddiesViewState();+}++class _SwarmBuddiesViewState extends State<SwarmBuddiesView> {+ SwarmSession? _session;+ bool _seen = false;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final session = SwarmScope.of(context);+ final seen = session != null && !OutOfSight.of(context);+ if (identical(session, _session) && seen == _seen) return;+ _see(false);+ _session = session;+ _see(seen);+ }++ /// In sight: the Buddy chats are read as they move, the inbox is read now,+ /// and the Swarm's notices keep quiet. Out of sight, none of it.+ void _see(bool seen) {+ final session = _session;+ if (session == null || seen == _seen) return;+ _seen = seen;+ if (seen) {+ session.enter();+ session.buddyList.watch();+ unawaited(session.inbox.refresh());+ } else {+ session.buddyList.unwatch();+ session.leave();+ }+ }++ @override+ void dispose() {+ _see(false);+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final session = _session;+ return Material(+ color: AppPalette.windowBg,+ child: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (widget.leading case final leading?)+ SwarmTopBar(leading: leading, title: 'Buddies')+ else+ const SwarmTabHeader('Buddies'),+ if (session != null)+ Expanded(+ child: ListenWhileInSight(+ listenable: session.buddyList,+ builder: (context) => _body(context, session),+ ),+ ),+ ],+ ),+ ),+ );+ }++ Widget _body(BuildContext context, SwarmSession session) {+ final list = session.buddyList, inbox = session.inbox;+ final rows = list.rows;+ final now = DateTime.now();+ final note = AppType.caption(color: AppPalette.textSecondary, height: 1.35);+ return ListView(+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ AppSpace.xs,+ AppSpace.m,+ MediaQuery.paddingOf(context).bottom + AppSpace.xl,+ ),+ children: [+ if (list.unreadChats)+ _Note(+ text: 'Some Buddy chats could not be read.',+ action: SwarmButton(+ key: const ValueKey('swarm-buddies-retry'),+ label: 'Try again',+ style: SwarmButtonStyle.link,+ onPressed: list.retry,+ ),+ ),+ if (!inbox.loaded && inbox.error != null)+ _Note(+ text: inbox.error!,+ action: SwarmButton(+ key: const ValueKey('swarm-buddies-retry-list'),+ label: 'Try again',+ style: SwarmButtonStyle.link,+ onPressed: () => unawaited(inbox.refresh()),+ ),+ )+ else if (rows.isEmpty && !inbox.loaded)+ SwarmSkeletonRows(id: 'swarm-buddies-loading')+ else if (rows.isEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.xs,+ vertical: AppSpace.s,+ ),+ child: Text(+ 'No projects yet.',+ key: const ValueKey('swarm-buddies-none'),+ style: note,+ ),+ )+ else+ SwarmGroup(+ children: [+ for (final row in rows)+ SwarmBuddiesRow(+ key: ValueKey('swarm-buddies-row-${row.key}'),+ row: row,+ line: swarmBuddyLine(row, inbox.reader(row.swarmId)),+ now: now,+ onTap: () => _open(context, row),+ ),+ ],+ ),+ ],+ );+ }++ /// Opens [row]'s project on its Buddy tab: the chat, or the Buddy's start.+ void _open(BuildContext context, SwarmBuddyRow row) => unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => SwarmProjectPage(+ swarmId: row.swarmId,+ projectId: row.project.id,+ tab: SwarmProjectTab.buddy,+ ),+ listensForItself: true,+ ),+ ),+ );+}++/// A line over the rows, with what to do about it at its end.+class _Note extends StatelessWidget {+ const _Note({required this.text, required this.action});++ final String text;+ final Widget action;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.only(left: AppSpace.xs, bottom: AppSpace.s),+ child: Row(+ children: [+ Expanded(+ child: Text(+ text,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.35,+ ),+ ),+ ),+ action,+ ],+ ),+ );+}++/// One project on Buddies, as prototype C2 draws it: its tile; its name —+/// bold and bright while its Buddy chat has something unread, quiet+/// otherwise — with how its Buddy stands after it and when the chat last+/// moved at the end; under them the chat's last message ([line]), and a dot+/// at its end while unread.+class SwarmBuddiesRow extends StatelessWidget {+ const SwarmBuddiesRow({+ super.key,+ required this.row,+ required this.line,+ required this.now,+ required this.onTap,+ });++ final SwarmBuddyRow row;+ final String line;+ final DateTime now;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final unread = row.unread;+ final state = row.note ?? 'running';+ final age = switch (row.at) {+ final at? => fzfAge(at.toLocal(), now.toLocal()),+ null => '',+ };+ return Semantics(+ button: true,+ label: [+ row.project.name,+ '${row.name} $state',+ if (line.isNotEmpty) line,+ if (unread) 'Unread messages',+ ].join(', '),+ excludeSemantics: true,+ child: Material(+ color: Colors.transparent,+ child: InkWell(+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: SwarmRow.height),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ vertical: AppSpace.m,+ ),+ child: Row(+ children: [+ SwarmProjectTile(row.project.name),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.baseline,+ textBaseline: TextBaseline.alphabetic,+ children: [+ Expanded(+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.baseline,+ textBaseline: TextBaseline.alphabetic,+ children: [+ Flexible(+ child: Text(+ row.project.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.label(+ color: unread+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ height: 1.3,+ fontWeight: unread+ ? AppFont.semibold+ : null,+ ),+ ),+ ),+ const SizedBox(width: AppSpace.s),+ Text(+ state,+ style: AppType.caption(+ color: row.note == null+ ? AppColors.success+ : AppPalette.textFaint,+ height: 1.3,+ ),+ ),+ ],+ ),+ ),+ if (age.isNotEmpty) ...[+ const SizedBox(width: AppSpace.s),+ Text(+ age,+ key: ValueKey('swarm-buddies-age-${row.key}'),+ style: AppType.caption(+ color: AppPalette.textFaint,+ height: 1.3,+ ),+ ),+ ],+ ],+ ),+ const SizedBox(height: 2),+ Row(+ children: [+ Expanded(+ child: Text(+ line,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(+ color: unread+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ height: 1.35,+ ),+ ),+ ),+ if (unread) ...[+ const SizedBox(width: AppSpace.s),+ Container(+ key: ValueKey(+ 'swarm-buddies-unread-${row.key}',+ ),+ width: 7,+ height: 7,+ decoration: BoxDecoration(+ color: AppPalette.textPrimary,+ shape: BoxShape.circle,+ ),+ ),+ ],+ ],+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_buddy_list.dart b/mobile/lib/swarm/swarm_buddy_list.dartnew file mode 100644index 000000000..b56e5afa5--- /dev/null+++ b/mobile/lib/swarm/swarm_buddy_list.dart@@ -0,0 +1,233 @@+import 'package:flutter/foundation.dart';++import 'identity.dart';+import 'model.dart';+import 'swarm_buddy.dart';+import 'swarm_inbox.dart';+import 'swarm_reader.dart';+import 'swarm_session.dart';++/// One project on Buddies (Tony's prototype C2): the person's own Buddy in+/// [project] of Swarm [swarmId], by its [name] ("Buddy" while none runs) and+/// how it stands ([note]: "offline", "starting" or "not started"; null while+/// it runs), their Buddy chat there ([chat]; null while none is opened) and+/// the last message in it once read ([last]), [unread] while the chat has a+/// message past the person's read mark.+@immutable+class SwarmBuddyRow {+ const SwarmBuddyRow({+ required this.swarmId,+ required this.project,+ required this.name,+ this.note,+ this.chat,+ this.last,+ this.unread = false,+ });++ final String swarmId;+ final SuperTabProject project;+ final String name;+ final String? note;+ final SuperTabConversation? chat;+ final SuperTabMessage? last;+ final bool unread;++ /// When the chat last moved: its last message, or the chat's own change+ /// until that is read.+ DateTime? get at => last?.createdAt ?? chat?.changedAt;++ /// The row's key: a project id may be in another Swarm too.+ String get key => '$swarmId/${project.id}';+}++/// [row]'s second line: its last message on one line, "You: " before the+/// person's own and the writer's name before the PM's private lines+/// ([swarmIsPmLine]), named in [reader], the row's own Swarm; what stands in+/// for it while there is none. Empty while the last message is not read.+String swarmBuddyLine(SwarmBuddyRow row, SwarmReader? reader) {+ final chat = row.chat;+ final last = row.last;+ if (chat == null) return 'No Buddy yet';+ if (last == null) return chat.mainSequence == 0 ? 'No messages yet' : '';+ final text = last.text.replaceAll(RegExp(r'\s+'), ' ').trim();+ final said = text.isNotEmpty+ ? text+ : switch (last.attachments.length) {+ 0 => '',+ 1 => 'Sent a file',+ final n => 'Sent $n files',+ };+ final snapshot = reader?.snapshot;+ final String? who;+ if (!last.fromAgent && last.authorId == reader?.accountId) {+ who = 'You';+ } else if (reader != null && swarmIsPmLine(reader, last)) {+ who = snapshot?.agentName(last.authorId, fallback: last.authorName);+ } else if (!last.fromAgent) {+ final email = snapshot?.people+ .where((p) => p.id == last.authorId)+ .firstOrNull+ ?.email;+ who = email == null || email.isEmpty+ ? 'Someone'+ : superTabPersonName(email);+ } else {+ who = null;+ }+ return who == null ? said : '$who: $said';+}++/// Buddies (Tony's prototype C2; Product Manager's brief 10-30): a row for+/// each project of every listed Swarm ([SwarmBuddyRow]), newest first, with+/// the person's own Buddy there and their Buddy chat's last message.+///+/// Each of the person's own Buddy chats is read from its last message on+/// ([SwarmChatPeeks]), only while Buddies is [shown] and only when that+/// message moved; a reply only in a thread does not move it. Another+/// person's Buddy chat is never listed or read. Nothing is kept beyond what+/// the peeks keep, which leave with the Swarm's access.+class SwarmBuddyList extends ChangeNotifier {+ SwarmBuddyList(this.session) {+ inbox.addListener(_changed);+ session.peeks.addListener(_changed);+ }++ final SwarmSession session;++ SwarmInbox get inbox => session.inbox;++ bool _disposed = false;+ List<SwarmBuddyRow>? _rows;++ /// Screens showing Buddies ([watch]): while there is one, the Buddy chats+ /// are read when their last message moves.+ int _views = 0;+ bool get shown => _views > 0;++ /// A screen shows Buddies: its chats are read as they move.+ void watch() {+ if (_disposed || _views++ > 0) return;+ _want();+ }++ /// That screen went, or out of sight: once none shows it, the chats still+ /// waiting their turn for it are not read ([SwarmChatPeeks.withdraw]).+ void unwatch() {+ if (_views > 0 && --_views == 0) session.peeks.withdraw(this);+ }++ /// Every project's row, newest first; those with no time after, in the+ /// order read.+ List<SwarmBuddyRow> get rows => _rows ??= _build();++ /// The tab's badge: the Buddy chats with something unread.+ int get badge => rows.where((row) => row.unread).length;++ /// Some Buddy chat could not be read at its last message.+ bool get unreadChats => _anyChat(session.peeks.failedAt);++ /// A Buddy chat is being read for the first time since it moved, with+ /// nothing of it read yet.+ bool get reading => _anyChat(+ (reader, chat) =>+ session.peeks.busyAt(reader, chat) &&+ session.peeks.of(reader, chat) == null,+ );++ /// The person's Try again: the Buddy chats that failed are read again.+ void retry() => _anyChat((reader, chat) {+ session.peeks.retry(reader, chat, owner: this);+ return false;+ });++ bool _anyChat(bool Function(SwarmReader reader, String chatId) test) {+ for (final (reader, chat) in _chats()) {+ if (test(reader, chat.id)) return true;+ }+ return false;+ }++ /// The listed Swarms the person can still read, each with its reader.+ Iterable<(String, SwarmReader, SuperTabSnapshot)> _swarms() sync* {+ for (final swarm in inbox.swarms) {+ final reader = inbox.reader(swarm.id);+ final snapshot = reader?.snapshot;+ if (reader == null || snapshot == null || reader.accessRevoked) {+ continue;+ }+ yield (swarm.id, reader, snapshot);+ }+ }++ /// The person's own Buddy chats with a message in them.+ Iterable<(SwarmReader, SuperTabConversation)> _chats() sync* {+ for (final (_, reader, snapshot) in _swarms()) {+ for (final project in snapshot.projects) {+ final chat = swarmBuddyChat(reader, project.id);+ if (chat != null && chat.mainSequence > 0) yield (reader, chat);+ }+ }+ }++ /// Asks for each Buddy chat from its last message on: read only if that+ /// moved since it was last read.+ void _want() {+ for (final (reader, chat) in _chats()) {+ final last = chat.mainSequence;+ session.peeks.want(+ reader,+ chat.id,+ counter: last,+ after: last - 1,+ owner: this,+ );+ }+ }++ List<SwarmBuddyRow> _build() {+ final rows = <SwarmBuddyRow>[];+ for (final (id, reader, snapshot) in _swarms()) {+ for (final project in snapshot.projects) {+ final chat = swarmBuddyChat(reader, project.id);+ final peek = chat == null ? null : session.peeks.of(reader, chat.id);+ rows.add(+ SwarmBuddyRow(+ swarmId: id,+ project: project,+ name: swarmBuddyName(reader, project.id),+ note: swarmBuddyNote(reader, project.id),+ chat: chat,+ last: peek?.messages.where((m) => m.inMainStream).lastOrNull,+ unread: chat != null && (reader.readMarks?.unread(chat) ?? false),+ ),+ );+ }+ }+ // Stable: what has no time keeps the order read, after the rest.+ final order = {for (final (i, row) in rows.indexed) row: i};+ return List.unmodifiable(+ rows..sort((a, b) {+ final (x, y) = (a.at, b.at);+ if (x != null && y != null && x != y) return y.compareTo(x);+ if ((x == null) != (y == null)) return x == null ? 1 : -1;+ return order[a]!.compareTo(order[b]!);+ }),+ );+ }++ void _changed() {+ if (_disposed) return;+ _rows = null;+ if (shown) _want();+ notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ inbox.removeListener(_changed);+ session.peeks.removeListener(_changed);+ super.dispose();+ }+}diff --git a/mobile/lib/swarm/swarm_chat_peeks.dart b/mobile/lib/swarm/swarm_chat_peeks.dartnew file mode 100644index 000000000..6317f96ea--- /dev/null+++ b/mobile/lib/swarm/swarm_chat_peeks.dart@@ -0,0 +1,271 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import 'model.dart';+import 'swarm_reader.dart';+import 'swarm_request.dart';++/// What one read of a chat brought: its messages, oldest first, and the+/// thread lines of the roots among them.+typedef SwarmPeek = ({+ List<SuperTabMessage> messages,+ Map<String, SuperTabThread> threads,+});++/// A few chats' newest rows, for the screens that list many chats at once:+/// Activity (each project chat's newest page) and Buddies (each Buddy chat+/// from its last message on). There is no read across chats on the server+/// yet, so each chat is read on its own, with the limits the Product Manager+/// set (10-30): a chat is read again only when its [want] counter moved, so a+/// screen opened again costs nothing; never on a timer of its own; only for+/// a list on screen, which takes back what still waits once it leaves+/// ([withdraw]); at most [parallel] at a time, and one read of a chat at a+/// time; and only through the route that checks who may read it. A chat the+/// person may not read is skipped quietly, under nothing of its own. In+/// memory only, and what a reader read goes the moment its access ends or it+/// reads from nothing again ([SwarmReader.generation]).+///+/// Follow-ups if it is slow: a page-size option on the messages route (it+/// answers 100 rows), and a summary route for Activity and Buddies.+class SwarmChatPeeks extends ChangeNotifier {+ SwarmChatPeeks({this.parallel = 2, this.tries = 3});++ /// How many chats are read at once.+ final int parallel;++ /// How many times a read that failed is tried again for one counter.+ final int tries;++ final _entries = <(SwarmReader, String), _Entry>{};++ /// The chats waiting their turn, oldest first, each once, for its latest+ /// counter.+ final _waiting = <(SwarmReader, String)>{};++ /// The chats being read, each with the entry it is read for.+ final _reading = <(SwarmReader, String), _Entry>{};+ bool _disposed = false;++ /// [chatId] of [reader] could not be read at its last counter: not a+ /// refusal, which is no failure to report.+ bool failedAt(SwarmReader reader, String chatId) {+ final entry = _entries[(reader, chatId)];+ return entry != null && entry.failures > 0 && _current(reader, entry);+ }++ /// What was last read of [chatId] in [reader], while the reader still+ /// holds what it was read under; null before, or once it is not.+ SwarmPeek? of(SwarmReader reader, String chatId) {+ final entry = _entries[(reader, chatId)];+ return entry != null && _current(reader, entry) ? entry.peek : null;+ }++ /// [owner] wants [chatId] of [reader] read at [counter] (compared by+ /// value): its newest page, or with [after] the rows past that sequence.+ /// Nothing is asked if it was read or refused at that counter, is being+ /// read there, or failed [tries] times there. A chat waits its turn once,+ /// for its latest counter; one whose counter moves while it is read waits+ /// for that read to end.+ void want(+ SwarmReader reader,+ String chatId, {+ required Object counter,+ required Object owner,+ int? after,+ }) {+ if (_disposed || reader.accessRevoked) return;+ final key = (reader, chatId);+ var entry = _entries[key];+ if (entry == null || !_current(reader, entry)) {+ entry = _entries[key] = _Entry(counter, reader.generation);+ } else if (entry.counter != counter) {+ // What was read at an earlier counter shows until the new read answers.+ entry+ ..counter = counter+ ..failures = 0;+ }+ if (entry.readAt == counter ||+ entry.failures >= tries ||+ identical(_reading[key], entry) && entry.readingAt == counter) {+ return;+ }+ entry+ ..after = after+ ..owners.add(owner);+ _waiting.add(key);+ _pump();+ }++ /// [chatId] of [reader] is being read, or waits its turn.+ bool busyAt(SwarmReader reader, String chatId) {+ final key = (reader, chatId);+ final entry = _entries[key];+ return entry != null &&+ _current(reader, entry) &&+ (_waiting.contains(key) || identical(_reading[key], entry));+ }++ /// The person's Try again, for [owner]: [chatId] of [reader] is read once+ /// more if its last read failed, however many times it was tried.+ void retry(SwarmReader reader, String chatId, {required Object owner}) {+ final entry = _entries[(reader, chatId)];+ if (_disposed ||+ entry == null ||+ entry.failures == 0 ||+ !_current(reader, entry) ||+ busyAt(reader, chatId)) {+ return;+ }+ entry+ ..failures = 0+ ..owners.add(owner);+ _waiting.add((reader, chatId));+ _pump();+ }++ /// [owner] left the screen: what waits only for it is not read, and is+ /// asked again by its next [want]. What is being read finishes, and what+ /// another list waits for keeps its turn.+ void withdraw(Object owner) {+ _waiting.removeWhere((key) {+ final owners = _entries[key]?.owners;+ return owners == null || (owners..remove(owner)).isEmpty;+ });+ }++ /// Keeps what [readers] hold now and drops the rest: what was read of a+ /// Swarm off the list, of one whose access ended, or of one that reads+ /// from nothing again ([SwarmReader.generation]) leaves memory, and an+ /// answer still on its way for it is dropped.+ void keepOnly(Iterable<SwarmReader> readers) {+ final listed = readers.toSet();+ bool gone((SwarmReader, String) key, _Entry entry) =>+ !listed.contains(key.$1) || !_current(key.$1, entry);+ _entries.removeWhere(gone);+ _waiting.removeWhere((key) => !_entries.containsKey(key));+ }++ /// How many chats are held, read or being read.+ @visibleForTesting+ int get held => _entries.length;++ bool _current(SwarmReader reader, _Entry entry) =>+ !reader.accessRevoked && entry.generation == reader.generation;++ /// Starts the oldest waiting chats that are not being read already, up to+ /// [parallel] reads in all.+ void _pump() {+ while (!_disposed && _reading.length < parallel) {+ final key = _waiting+ .where((key) => !_reading.containsKey(key))+ .firstOrNull;+ if (key == null) return;+ _waiting.remove(key);+ final entry = _entries[key]?..owners.clear();+ if (entry == null ||+ !_current(key.$1, entry) ||+ entry.readAt == entry.counter ||+ entry.failures >= tries) {+ continue;+ }+ entry.readingAt = entry.counter;+ _reading[key] = entry;+ unawaited(+ _read(key, entry).whenComplete(() {+ if (identical(_reading[key], entry)) _reading.remove(key);+ _pump();+ }),+ );+ }+ }++ Future<void> _read((SwarmReader, String) key, _Entry entry) async {+ final (reader, chatId) = key;+ final counter = entry.counter, after = entry.after;+ bool live() =>+ !_disposed &&+ identical(_entries[key], entry) &&+ _current(reader, entry);+ // A failure counts against the counter it was read at, if still the+ // latest: one that moved meanwhile starts its own tries.+ void failed() {+ if (entry.counter == counter) entry.failures++;+ }++ try {+ final answer = superTabMap(+ await reader.request(+ 'GET',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}'+ '/conversations/${Uri.encodeComponent(chatId)}/messages'+ '${after == null ? '' : '?after=$after'}',+ ),+ );+ if (!live()) return;+ final messages = [+ for (final row in answer['messages'] as List)+ SuperTabMessage.fromJson(superTabMap(row)),+ ]..sort(superTabMessageOrder);+ if (messages.any((m) => m.conversationId != chatId)) {+ throw const FormatException('A different conversation was returned.');+ }+ final threads = [+ for (final row in answer['threads'] as List? ?? const [])+ SuperTabThread.fromJson(superTabMap(row)),+ ];+ entry+ ..peek = (+ messages: List.unmodifiable(messages),+ threads: Map.unmodifiable({for (final t in threads) t.id: t}),+ )+ ..readAt = counter;+ if (entry.counter == counter) entry.failures = 0;+ } on SuperTabFailure catch (failure) {+ if (!live()) return;+ if (const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code) ||+ const {403, 404}.contains(failure.statusCode)) {+ entry+ ..readAt = counter+ ..peek = null;+ } else {+ failed();+ }+ } catch (_) {+ if (!live()) return;+ // An answer that is not a page of this chat shows nothing of it.+ entry.peek = null;+ failed();+ } finally {+ entry.readingAt = null;+ }+ if (live()) notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ _entries.clear();+ _waiting.clear();+ _reading.clear();+ super.dispose();+ }+}++class _Entry {+ _Entry(this.counter, this.generation);+ final int generation;++ /// The counter last wanted; [readAt] the one it was last read (or+ /// refused) at, and [readingAt] the one it is being read at.+ Object counter;+ Object? readAt, readingAt;+ int? after;+ SwarmPeek? peek;++ /// Failed reads at [counter].+ int failures = 0;++ /// The lists that want it read, while it waits its turn.+ final owners = <Object>{};+}diff --git a/mobile/lib/swarm/swarm_needs_page.dart b/mobile/lib/swarm/swarm_needs_page.dartindex 9ca1774f3..99e088633 100644--- a/mobile/lib/swarm/swarm_needs_page.dart+++ b/mobile/lib/swarm/swarm_needs_page.dart@@ -1,170 +1,16 @@-import 'dart:async';+import 'package:flutter/widgets.dart';-import 'package:flutter/material.dart';--import 'package:harness_mobile/phone/out_of_sight.dart';-import 'package:harness_mobile/phone/phone_navigation.dart';-import 'package:harness_mobile/shared/theme/app_space.dart';-import 'package:harness_mobile/shared/theme/app_theme.dart';--import 'swarm_conversation_page.dart';+import 'swarm_activity_page.dart';import 'swarm_inbox.dart';-import 'swarm_need_rows.dart';-import 'swarm_row.dart';-import 'swarm_session.dart';-import 'swarm_style.dart';-/// Opens everything that needs the person over [context]'s page, [focus]-/// open — a need's key — else the first; only Swarm [swarmId]'s when Home-/// shows that Swarm alone.+/// Opens Activity, which replaced Needs you (Tony's prototype C3), over+/// [context]'s page: [focus] — a need's key — open in full under its filter;+/// only Swarm [swarmId]'s rows when Home shows that Swarm alone.void openSwarmNeeds(BuildContext context, {String? focus, String? swarmId}) =>- unawaited(- Navigator.of(context).push(- phoneRoute(- (_) => SwarmNeedsPage(focus: focus, swarmId: swarmId),- listensForItself: true,- ),- ),- );+ openSwarmActivity(context, focus: focus, swarmId: swarmId);/// The needs Home shows: every Swarm's, or [swarmId]'s alone.List<SwarmNeed> swarmNeedsOf(SwarmInbox inbox, String? swarmId) => [for (final need in inbox.needs)if (swarmId == null || need.swarmId == swarmId) need,];--/// Everything that needs the person, from Home's "See all" or one of its-/// rows: one thing open at a time with what can be done with it-/// ([SwarmNeedRow]) — the one tapped, while it waits, else the first;-/// answered or done, the next one opens — and the others a line each that-/// opens it in its place.-///-/// Also the Activity tab ([SwarmTabsPage]): there, at the root, it has no-/// back button, and it is kept out of sight while another tab is open.-class SwarmNeedsPage extends StatefulWidget {- const SwarmNeedsPage({super.key, this.focus, this.swarmId});-- /// The need open first, by its key.- final String? focus;-- /// Only this Swarm's needs; null for every Swarm's.- final String? swarmId;-- @override- State<SwarmNeedsPage> createState() => _SwarmNeedsPageState();-}--class _SwarmNeedsPageState extends State<SwarmNeedsPage> {- SwarmSession? _session;- late String? _focus = widget.focus;-- /// Kept out of sight — a tab under another, or under Harness: no Swarm- /// screen meanwhile, so a notice tells what arrives. Shown again, it reads- /// the Swarms.- bool _hidden = false;-- @override- void didChangeDependencies() {- super.didChangeDependencies();- final session = SwarmScope.of(context);- final hidden = OutOfSight.of(context);- if (session == _session && hidden == _hidden) return;- if (!_hidden) _session?.leave();- _session = session;- _hidden = hidden;- if (hidden || session == null) return;- session.enter();- // Joins Home's read when it opened from Home.- unawaited(session.inbox.refresh());- }-- @override- void dispose() {- if (!_hidden) _session?.leave();- super.dispose();- }-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- final session = _session;- // Pushed over Home, or a tab at the root.- final pushed = ModalRoute.isFirstOf(context) == false;- return Scaffold(- backgroundColor: AppPalette.windowBg,- body: SafeArea(- bottom: false,- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (pushed)- SwarmTopBar(- leading: SwarmBackButton(- onPressed: () => Navigator.of(context).maybePop(),- ),- title: 'Needs you',- )- else- const SwarmTabHeader('Needs you'),- Expanded(- child: session == null- ? const SizedBox.shrink()- : ListenWhileInSight(- listenable: Listenable.merge([session, session.inbox]),- builder: (context) => ListView(- padding: EdgeInsets.fromLTRB(- AppSpace.m,- AppSpace.s,- AppSpace.m,- MediaQuery.paddingOf(context).bottom + AppSpace.xl,- ),- children: _needs(context, session),- ),- ),- ),- ],- ),- ),- );- }-- List<Widget> _needs(BuildContext context, SwarmSession session) {- final needs = swarmNeedsOf(session.inbox, widget.swarmId);- if (needs.isEmpty) {- return [- Padding(- padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),- child: SwarmRow.line(- 'Nothing needs you.',- key: const ValueKey('swarm-needs-none'),- ),- ),- ];- }- final open = needs.firstWhere(- (need) => need.key == _focus,- orElse: () => needs.first,- );- return [- SwarmGroup(- children: [- for (final need in needs)- if (need == open)- SwarmNeedRow(- session: session,- need: need,- onOpen: (swarmId, conversationId) =>- openSwarmConversation(context, swarmId, conversationId),- )- else- SwarmNeedLine(- key: ValueKey('swarm-need-row-${need.key}'),- session: session,- need: need,- onTap: () => setState(() => _focus = need.key),- ),- ],- ),- ];- }-}diff --git a/mobile/lib/swarm/swarm_read_marks.dart b/mobile/lib/swarm/swarm_read_marks.dartindex 182cda538..d56ef087d 100644--- a/mobile/lib/swarm/swarm_read_marks.dart+++ b/mobile/lib/swarm/swarm_read_marks.dart@@ -125,6 +125,15 @@ class SwarmReadMarks extends ChangeNotifier {return group.mainSequence > max(server, _marks[group.id] ?? 0);}+ /// 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+ ? max(+ reader.snapshot?.readMarks[conversationId] ?? 0,+ _marks[conversationId] ?? 0,+ )+ : null;+/// The person saw [conversationId] through [sequence]: sent to the server,/// and kept on the phone when it moves the phone's mark on.void markRead(String conversationId, int sequence) {diff --git a/mobile/lib/swarm/swarm_session.dart b/mobile/lib/swarm/swarm_session.dartindex 0edcb6778..7453fd03a 100644--- a/mobile/lib/swarm/swarm_session.dart+++ b/mobile/lib/swarm/swarm_session.dart@@ -7,6 +7,9 @@ import '../core/local_key_value_store.dart';import '../notify/system_notices.dart';import '../phone/voice_input_controller.dart';import '../settings/experimental_features.dart';+import 'swarm_activity.dart';+import 'swarm_buddy_list.dart';+import 'swarm_chat_peeks.dart';import 'swarm_choices.dart';import 'swarm_dictation.dart';import 'swarm_face.dart';@@ -55,6 +58,20 @@ class SwarmSession extends ChangeNotifier {final String accountId;final SwarmInbox inbox;+ /// The project and Buddy chats read for Activity and Buddies, a few at a+ /// time ([SwarmChatPeeks]).+ final peeks = SwarmChatPeeks();++ /// Activity, in place of Needs you: its filters, counts and handled rows.+ /// Made when a screen first asks for it.+ SwarmActivity get activity => _activity ??= SwarmActivity(this);+ SwarmActivity? _activity;++ /// Buddies: the person's own Buddy in each project, with its chat's last+ /// message. Made when a screen first asks for it.+ SwarmBuddyList get buddyList => _buddyList ??= SwarmBuddyList(this);+ SwarmBuddyList? _buddyList;+/// What the person chose for Home on this phone: the projects pinned and/// the one Swarm shown. A Swarm the account no longer has takes its own.final SwarmHomePrefs home;@@ -156,6 +173,8 @@ class SwarmSession extends ChangeNotifier {if (inbox.loaded) {home.keepOnly({for (final swarm in inbox.swarms) swarm.id});}+ // What was read of a Swarm off the list, or out of reach, leaves memory.+ peeks.keepOnly([for (final swarm in inbox.swarms) ?inbox.reader(swarm.id)]);_announcer.settle(inbox.needs);// Answered somewhere else meanwhile, or out of the list while the Swarm// is read again: nothing is sent, and a card that comes back says so.@@ -178,6 +197,9 @@ class SwarmSession extends ChangeNotifier {held.timer.cancel();}_held.clear();+ _activity?.dispose();+ _buddyList?.dispose();+ peeks.dispose();inbox.removeListener(_needsChanged);_announcer.clear();inbox.dispose();diff --git a/mobile/lib/swarm/swarm_tabs.dart b/mobile/lib/swarm/swarm_tabs.dartindex 01c59bba0..4c4d51167 100644--- a/mobile/lib/swarm/swarm_tabs.dart+++ b/mobile/lib/swarm/swarm_tabs.dart@@ -8,7 +8,8 @@ import 'package:harness_mobile/shared/theme/app_space.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/shared/theme/app_type.dart';-import 'swarm_needs_page.dart';+import 'swarm_activity_page.dart';+import 'swarm_buddies_page.dart';import 'swarm_page.dart';import 'swarm_session.dart';import 'swarm_style.dart';@@ -58,12 +59,10 @@ class SwarmTabEntry {}/// Swarm's tabs, in the bar's order: each part of Swarm plugs its screen in-/// here, one entry each. Each opens a screen the phone already has: Home,-/// Needs you with what waits on the person counted, and [settings], the-/// phone's Settings, as You. [onSettings] opens Settings over Home.-///-/// Buddies is not on the bar until its screen comes (part b of direction-/// C): main has no list of Buddies, each is in its project.+/// here, one entry each: Home; Buddies ([SwarmBuddiesView]) with the Buddy+/// chats that have something unread counted; Activity ([SwarmActivityView])+/// with what waits on the person counted; and [settings], the phone's+/// Settings, as You. [onSettings] opens Settings over Home.List<SwarmTabEntry> swarmTabs({void Function(BuildContext context)? onSettings,required WidgetBuilder settings,@@ -74,12 +73,19 @@ List<SwarmTabEntry> swarmTabs({icon: LucideIcons.house300,screen: (_) => SwarmPage(onSettings: onSettings),),+ SwarmTabEntry(+ tab: SwarmTab.buddies,+ label: 'Buddies',+ icon: LucideIcons.messageCircle300,+ screen: (_) => const SwarmBuddiesView(),+ badge: (session) => (count: session.buddyList.badge, warn: false),+ ),SwarmTabEntry(tab: SwarmTab.activity,label: 'Activity',icon: LucideIcons.bell300,- screen: (_) => const SwarmNeedsPage(),- badge: (session) => (count: session.inbox.needs.length, warn: true),+ screen: (_) => const SwarmActivityView(),+ badge: (session) => (count: session.activity.badge, warn: true),),SwarmTabEntry(tab: SwarmTab.you,diff --git a/mobile/test/swarm/swarm_activity_fixture.dart b/mobile/test/swarm/swarm_activity_fixture.dartnew file mode 100644index 000000000..359bf6d95--- /dev/null+++ b/mobile/test/swarm/swarm_activity_fixture.dart@@ -0,0 +1,217 @@+import 'swarm_fixture.dart';++/// Activity's backend as a test scripts it (swarm_activity_test.dart,+/// swarm_activity_page_test.dart), built by hand so it reads like the wire.++const activityChatPath =+ '/api/super-tabs/$tab/conversations/$leadChat/messages';++Map<String, dynamic> activityMessage(+ String id,+ int sequence, {+ String text = '',+ bool mine = false,+ String? thread,+ List<Map<String, dynamic>> reactions = const [],+}) => {+ 'id': id,+ 'conversationId': leadChat,+ 'text': text.isEmpty ? 'Row $id' : text,+ 'sequence': sequence,+ 'thread': thread ?? id,+ 'author': mine+ ? {'kind': 'person', 'id': me, 'name': '[email protected]'}+ : {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'reactions': reactions,+ 'createdAt': DateTime.utc(2026, 10, 29, 8, sequence).toIso8601String(),+};++Map<String, dynamic> activityThread(+ String root, {+ required int last,+ List<String> people = const [me],+ bool lastByMe = false,+}) => {+ 'id': root,+ 'replies': 2,+ 'lastSequence': last,+ 'lastAt': DateTime.utc(2026, 10, 29, 9, last).toIso8601String(),+ 'authors': [+ lastByMe+ ? {'kind': 'person', 'id': me, 'name': '[email protected]'}+ : {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ ],+ 'people': people,+};++/// One Swarm, project Mobile: decision d1 (recommending "Merge"), River's+/// tag m1, work g1 waiting on the person, and a project chat whose newest+/// page [page] answers. The server's read mark of that chat is [readMark].+FakeSwarm activityBackend({+ Map<String, dynamic> Function()? page,+ int readMark = 10,+ int chatSequence = 12,+ bool decision = true,+ List<Map<String, dynamic>> groups = const [],+}) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me, 'lastChangedAt': 1},+ ],+ 'next': null,+ };+ final derived = {+ 'decisionsWaiting': decision ? 1 : 0,+ 'mentionsWaiting': 1,+ 'readMarks': {leadChat: readMark},+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) {+ final load = firstLoad(+ derived: derived,+ lastChangedAt: 1,+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ number: 4,+ status: 'needs_human',+ workerId: 'agent-builder',+ ),+ ...groups,+ ],+ );+ // The project chat holds [chatSequence] rows.+ final lead = (load['groups'] as List).first as Map<String, dynamic>;+ (lead['data'] as Map<String, dynamic>)['lastMessageSequence'] =+ chatSequence;+ return load;+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived, lastChangedAt: 1);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ if (decision)+ {+ 'id': 'd1',+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'askerName': 'River',+ 'question': 'Approve merge: PR #2154?',+ 'options': ['Wait', 'Merge'],+ 'recommended': 1,+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [+ {+ 'id': 'm1',+ 'projectName': 'Mobile',+ 'conversationId': leadChat,+ 'conversationTitle': 'Mobile',+ 'messageId': 'msg-tag',+ 'leadName': 'River',+ 'text': 'Can you check the copy?',+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => {+ 'result': <String, dynamic>{},+ };+ fake.routes[activityChatPath] = (_) =>+ page?.call() ?? {'messages': <Object>[], 'next': null};+ return fake;+}++/// The project chat's newest page: the person's root-1 (a thread with a reply+/// since they read the chat), their mine-2 with River's ✅ and their own, own-only+/// with only their own 👀, root-old (a thread read already) and root-others (a+/// thread they are not in).+Map<String, dynamic> activityPage() => {+ 'messages': [+ activityMessage('root-1', 3, text: 'Ship the build tonight?', mine: true),+ activityMessage(+ 'mine-2',+ 5,+ text: 'Copy is fixed.',+ mine: true,+ reactions: [+ {+ 'emoji': 'check',+ 'by': [+ {'kind': 'agent', 'id': 'agent-lead'},+ {'kind': 'person', 'id': me},+ ],+ },+ ],+ ),+ activityMessage(+ 'own-only',+ 6,+ mine: true,+ reactions: [+ {+ 'emoji': 'eyes',+ 'by': [+ {'kind': 'person', 'id': me},+ ],+ },+ ],+ ),+ activityMessage('root-old', 7),+ activityMessage('root-others', 8),+ ],+ 'threads': [+ activityThread('root-1', last: 12),+ activityThread('root-old', last: 9),+ activityThread('root-others', last: 12, people: ['person-other']),+ ],+ 'next': null,+};++/// Adds a second Swarm, [swarmId], to [fake]'s list, after the first: the+/// same project, chat and agent ids, its Lead Cleo and its builder Pip, and+/// a project chat whose newest page [page] answers.+void activitySecondSwarm(+ FakeSwarm fake, {+ String swarmId = 'tab-2',+ Map<String, dynamic> Function()? page,+}) {+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me, 'lastChangedAt': 2},+ {'id': swarmId, 'name': 'Other Swarm', 'ownerId': me, 'lastChangedAt': 1},+ ],+ 'next': null,+ };+ final derived = {+ 'readMarks': {leadChat: 10},+ };+ fake.routes['/api/super-tabs/$swarmId/parts'] = (_) {+ final load = firstLoad(+ tabId: swarmId,+ head: headData(id: swarmId, name: 'Other Swarm'),+ derived: derived,+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'Cleo'),+ agent('agent-builder', displayName: 'Pip'),+ ],+ );+ final lead = (load['groups'] as List).first as Map<String, dynamic>;+ (lead['data'] as Map<String, dynamic>)['lastMessageSequence'] = 12;+ return load;+ };+ fake.routes['/api/super-tabs/$swarmId/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$swarmId/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$swarmId/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$swarmId/conversations/$leadChat/messages'] = (+ _,+ ) => page?.call() ?? {'messages': <Object>[], 'next': null};+}diff --git a/mobile/test/swarm/swarm_activity_page_test.dart b/mobile/test/swarm/swarm_activity_page_test.dartnew file mode 100644index 000000000..b0a189272--- /dev/null+++ b/mobile/test/swarm/swarm_activity_page_test.dart@@ -0,0 +1,377 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/phone/out_of_sight.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_activity_page.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_activity_fixture.dart';+import 'swarm_fixture.dart';++/// The Activity screen (Tony's prototype C3): four filters, each with its+/// count; Approve, which asks first, and Reply on the row; rows the person+/// handled kept, dimmed, below the others; and nothing of a Swarm left on+/// screen once the person can no longer read it.+void main() {+ const work = 'work:$tab:g1:attempt-g1:needs_human';++ /// [home] under a signed-in shell's Swarm, Swarm on, on a 390-point phone.+ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ Widget home = const SwarmActivityPage(),+ MemoryKeyValueStore? store,+ }) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ 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: store ?? MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: home,+ ),+ );+ await tester.pumpAndSettle();+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ SwarmHost host(WidgetTester tester) =>+ tester.widget<SwarmScope>(find.byType(SwarmScope)).notifier!;++ int chatReads(FakeSwarm fake) =>+ fake.paths.where((p) => p.startsWith(activityChatPath)).length;++ /// Opens filter [name], scrolled into view first: the pills scroll+ /// sideways, as the prototype's do.+ Future<void> filter(WidgetTester tester, String name) async {+ await tester.ensureVisible(key('swarm-activity-filter-$name'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-activity-filter-$name'));+ await tester.pumpAndSettle();+ }++ testWidgets('four filters, each with its count, each a thumb tall', (+ tester,+ ) async {+ await pump(tester, activityBackend(page: activityPage));++ expect(find.text('Activity'), findsOneWidget);+ for (final (name, label, count) in [+ ('needsYou', 'Needs you', '2'),+ ('mentions', '@', '1'),+ ('threads', 'Threads', '1'),+ ('reactions', 'Reactions', '0'),+ ]) {+ final pill = key('swarm-activity-filter-$name');+ expect(+ find.descendant(of: pill, matching: find.text(label)),+ findsOneWidget,+ );+ expect(+ find.descendant(of: pill, matching: find.text(count)),+ findsOneWidget,+ reason: '$label carries its count',+ );+ expect(tester.getSize(pill).height, greaterThanOrEqualTo(44));+ }+ });++ testWidgets('Needs you: where and who over the ask, Approve on a decision, '+ 'Reply on work', (tester) async {+ await pump(tester, activityBackend());++ final decision = key('swarm-activity-row-decision:d1');+ expect(+ find.descendant(of: decision, matching: find.text('#Mobile · River')),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: decision,+ matching: find.text('Approve merge: PR #2154?'),+ ),+ findsOneWidget,+ );+ final approve = key('swarm-activity-approve-decision:d1');+ final reply = key('swarm-activity-reply-$work');+ expect(approve, findsOneWidget);+ expect(reply, findsOneWidget);+ expect(key('swarm-activity-reply-decision:d1'), findsNothing);+ for (final button in [approve, reply]) {+ expect(tester.getSize(button).height, greaterThanOrEqualTo(44));+ expect(tester.getSize(button).width, greaterThanOrEqualTo(44));+ }+ });++ testWidgets('Approve asks first, naming the option; Cancel sends nothing', (+ tester,+ ) async {+ final fake = activityBackend();+ await pump(tester, fake);++ await tester.tap(key('swarm-activity-approve-decision:d1'));+ await tester.pumpAndSettle();+ expect(find.text('Approve?'), findsOneWidget);+ expect(find.textContaining('“Merge”'), findsOneWidget);++ await tester.tap(key('swarm-activity-approve-cancel'));+ await tester.pump(const Duration(seconds: 5));+ await tester.pumpAndSettle();++ expect(fake.commands, isEmpty);+ expect(key('swarm-activity-approve-decision:d1'), findsOneWidget);+ });++ testWidgets('Approve confirmed is held for Undo, then sent, and the row '+ 'stays as handled', (tester) async {+ final fake = activityBackend();+ final host = await pump(tester, fake);++ await tester.tap(key('swarm-activity-approve-decision:d1'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-activity-approve-confirm'));+ await tester.pump();+ expect(find.text('Sending “Merge”'), findsOneWidget);+ expect(key('swarm-undo-d1'), findsOneWidget);++ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ await tester.pump(const Duration(seconds: 4));+ await tester.pumpAndSettle();+ expect(fake.commands.single, {+ 'type': 'decision.answer',+ 'decisionId': 'd1',+ 'choice': 1,+ });+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();++ expect(key('swarm-activity-handled-decision:d1'), findsOneWidget);+ expect(find.text('Approved'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-activity-filter-needsYou'),+ matching: find.text('1'),+ ),+ findsOneWidget,+ );+ });++ testWidgets('Reply opens where it was asked; back, the row is handled', (+ tester,+ ) async {+ await pump(tester, activityBackend());++ await tester.tap(key('swarm-activity-reply-$work'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmConversationPage), findsOneWidget);+ expect(+ tester+ .widget<SwarmConversationPage>(find.byType(SwarmConversationPage))+ .conversationId,+ 'g1',+ );++ await tester.tap(find.byKey(const ValueKey('tty-back')).first);+ await tester.pumpAndSettle();+ expect(key('swarm-activity-handled-$work'), findsOneWidget);+ expect(find.text('Opened'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-activity-filter-needsYou'),+ matching: find.text('1'),+ ),+ findsOneWidget,+ );+ });++ testWidgets('a row tapped opens in full, with every option', (tester) async {+ await pump(tester, activityBackend());++ await tester.tap(key('swarm-activity-row-decision:d1'));+ await tester.pumpAndSettle();++ expect(key('swarm-option-d1-0'), findsOneWidget);+ expect(key('swarm-option-d1-1'), findsOneWidget);+ });++ testWidgets('@: the tags, Reply opening the chat at the tag', (tester) async {+ await pump(tester, activityBackend());+ await filter(tester, 'mentions');++ expect(find.text('Can you check the copy?'), findsOneWidget);+ await tester.tap(key('swarm-activity-reply-mention:m1'));+ await tester.pumpAndSettle();++ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.conversationId, page.messageId), (leadChat, 'msg-tag'));+ });++ testWidgets('Threads: the person\'s threads, the one with news first', (+ tester,+ ) async {+ await pump(tester, activityBackend(page: activityPage));+ await filter(tester, 'threads');++ final open = key('swarm-activity-row-thread:$tab:root-1');+ expect(+ find.descendant(of: open, matching: find.text('Ship the build tonight?')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: open, matching: find.text('2 replies')),+ findsOneWidget,+ );+ expect(key('swarm-activity-handled-thread:$tab:root-old'), findsOneWidget);+ expect(+ tester.getTopLeft(open).dy,+ lessThan(+ tester.getTopLeft(key('swarm-activity-row-thread:$tab:root-old')).dy,+ ),+ );++ await tester.tap(key('swarm-activity-reply-thread:$tab:root-1'));+ await tester.pumpAndSettle();+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.conversationId, page.messageId), (leadChat, 'root-1'));+ });++ testWidgets("Reactions: who reacted how to the person's message", (+ tester,+ ) async {+ final store = MemoryKeyValueStore()+ ..values['swarm_activity.$me.$tab'] = '{"marks":{}}';+ await pump(tester, activityBackend(page: activityPage), store: store);+ await filter(tester, 'reactions');++ final row = key('swarm-activity-row-reaction:$tab:mine-2');+ expect(+ find.descendant(of: row, matching: find.text('Copy is fixed.')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: row, matching: find.textContaining('River')),+ findsWidgets,+ );+ expect(+ find.descendant(of: row, matching: find.textContaining('✅ 1')),+ findsOneWidget,+ );+ expect(key('swarm-activity-row-reaction:$tab:own-only'), findsNothing);+ });++ testWidgets('the same agent id in two Swarms: each row is named in its '+ 'own Swarm', (tester) async {+ final fake = activityBackend(page: activityPage);+ activitySecondSwarm(fake, page: activityPage);+ await pump(tester, fake);+ await filter(tester, 'threads');++ Finder caption(String row, String text) => find.descendant(+ of: key('swarm-activity-row-$row'),+ matching: find.textContaining(text),+ );+ await tester.ensureVisible(key('swarm-activity-row-thread:tab-2:root-1'));+ expect(caption('thread:$tab:root-1', 'Nova'), findsOneWidget);+ expect(caption('thread:$tab:root-1', 'Pip'), findsNothing);+ expect(caption('thread:tab-2:root-1', 'Pip'), findsOneWidget);+ expect(caption('thread:tab-2:root-1', 'Nova'), findsNothing);+ });++ testWidgets('a filter with nothing in it says so', (tester) async {+ await pump(tester, activityBackend());+ await filter(tester, 'reactions');++ expect(key('swarm-activity-none'), findsOneWidget);+ expect(find.text('No reactions to you yet.'), findsOneWidget);+ });++ testWidgets('a Swarm the person can no longer read leaves the screen at '+ 'once, with nothing of it left', (tester) async {+ final fake = activityBackend(page: activityPage);+ final host = await pump(tester, fake);+ expect(key('swarm-activity-row-decision:d1'), findsOneWidget);++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': <Object>[],+ 'next': null,+ };+ fake.routes['/api/super-tabs/invitations'] = (_) => <Object>[];+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();++ expect(find.textContaining('Mobile'), findsNothing);+ expect(find.textContaining('River'), findsNothing);+ expect(key('swarm-activity-none'), findsOneWidget);+ await filter(tester, 'threads');+ expect(find.text('Ship the build tonight?'), findsNothing);+ expect(key('swarm-activity-loading'), findsNothing);+ });++ testWidgets('a project chat that cannot be read says so, and Try again '+ 'reads it again', (tester) async {+ final fake = activityBackend();+ fake.routes[activityChatPath] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ await pump(tester, fake);+ await filter(tester, 'threads');++ expect(find.text('Some chats could not be read.'), findsOneWidget);+ expect(key('swarm-activity-loading'), findsNothing);++ fake.routes[activityChatPath] = (_) => activityPage();+ await tester.tap(key('swarm-activity-retry'));+ await tester.pumpAndSettle();++ expect(find.text('Some chats could not be read.'), findsNothing);+ expect(find.text('Ship the build tonight?'), findsOneWidget);+ });++ testWidgets('out of sight, it reads no chat; in sight again, it does', (+ tester,+ ) async {+ final fake = activityBackend(page: activityPage);+ final hidden = ValueNotifier(true);+ addTearDown(hidden.dispose);+ await pump(+ tester,+ fake,+ home: Scaffold(+ body: ValueListenableBuilder(+ valueListenable: hidden,+ builder: (_, out, _) =>+ OutOfSight(hidden: out, child: const SwarmActivityView()),+ ),+ ),+ );+ await host(tester).session!.inbox.refresh();+ await tester.pumpAndSettle();+ expect(chatReads(fake), 0);++ hidden.value = false;+ await tester.pumpAndSettle();+ expect(chatReads(fake), 1);+ });+}diff --git a/mobile/test/swarm/swarm_activity_shots_test.dart b/mobile/test/swarm/swarm_activity_shots_test.dartnew file mode 100644index 000000000..f187916a3--- /dev/null+++ b/mobile/test/swarm/swarm_activity_shots_test.dart@@ -0,0 +1,586 @@+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_session.dart';+import 'package:harness_mobile/swarm/swarm_tabs.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Review screenshots of Activity and Buddies, direction C, as Tony's+/// prototype C2 and C3 draw them (2026-10-30) — each filter of Activity,+/// Approve's confirm and its Undo, a need opened, the handled row, and+/// Buddies, over the Swarm tab bar — with their touch targets outlined and+/// measured, in both phone+/// themes, from made-up Swarm data only, to the folder+/// `SWARM_ACTIVITY_SHOTS` names.+final shots = Platform.environment['SWARM_ACTIVITY_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('Activity and Buddies, in both phone themes', (tester) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final now = DateTime.now();+ String ago(Duration age) => now.subtract(age).toUtc().toIso8601String();+ const minute = Duration(minutes: 1);++ Map<String, dynamic> projectOf(String id, String name) => {+ 'id': id,+ 'name': name,+ 'ownerId': me,+ 'leadConversationId': 'lead-$id',+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ };+ Map<String, dynamic> inProject(String id, Map<String, dynamic> row) => {+ ...row,+ 'projectId': id,+ };+ final projects = [+ projectOf('p-oh', 'openharness'),+ projectOf('p-desk', 'desktop-app'),+ projectOf('p-fw', 'firmware-dial'),+ projectOf('p-web', 'web-2'),+ ];+ final leads = {+ 'p-oh': 'agent-river',+ 'p-desk': 'agent-pike',+ 'p-fw': 'agent-kite',+ 'p-web': 'agent-cleo',+ };+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'OpenHarness', 'ownerId': me},+ ],+ 'next': null,+ };+ const derived = {+ 'decisionsWaiting': 2,+ 'mentionsWaiting': 2,+ 'readMarks': {+ 'lead-p-oh': 20,+ 'lead-p-desk': 10,+ 'buddy-oh': 12,+ 'buddy-desk': 6,+ 'buddy-web': 3,+ },+ };+ final load = firstLoad(+ derived: derived,+ head: headData(name: 'OpenHarness', projects: projects),+ agents: [+ inProject(+ 'p-oh',+ agent('agent-river', name: 'Lead', displayName: 'River'),+ ),+ inProject('p-oh', agent('agent-ash', displayName: 'Ash')),+ inProject('p-oh', agent('agent-moss', displayName: 'Moss')),+ inProject(+ 'p-desk',+ agent('agent-pike', name: 'Lead', displayName: 'Pike'),+ ),+ inProject(+ 'p-fw',+ agent('agent-kite', name: 'Lead', displayName: 'Kite'),+ ),+ inProject(+ 'p-web',+ agent('agent-cleo', name: 'Lead', displayName: 'Cleo'),+ ),+ inProject('p-oh', buddyData('agent-wren', displayName: 'Wren')),+ inProject('p-desk', {+ ...buddyData('agent-juno', displayName: 'Juno'),+ 'downSince': ago(const Duration(hours: 2)),+ }),+ inProject('p-web', buddyData('agent-sage', displayName: 'Sage')),+ ],+ groups: [+ for (final p in projects)+ inProject(+ p['id'] as String,+ groupData(+ 'lead-${p['id']}',+ title: p['name'] as String,+ agentIds: [leads[p['id']]!],+ leadId: leads[p['id']],+ lastMessageSequence: 24,+ ),+ ),+ inProject(+ 'p-oh',+ groupData(+ 'g-ask',+ title: 'phone leaderboard',+ number: 2151,+ status: 'needs_human',+ workerId: 'agent-ash',+ agentIds: ['agent-ash'],+ ),+ ),+ inProject(+ 'p-oh',+ buddyChatData(+ 'buddy-oh',+ agentIds: ['agent-wren'],+ lastMessageSequence: 14,+ ),+ ),+ inProject(+ 'p-desk',+ buddyChatData(+ 'buddy-desk',+ agentIds: ['agent-juno'],+ lastMessageSequence: 6,+ ),+ ),+ inProject(+ 'p-web',+ buddyChatData(+ 'buddy-web',+ agentIds: ['agent-sage'],+ lastMessageSequence: 3,+ ),+ ),+ ],+ );+ int at(Duration age) => now.subtract(age).millisecondsSinceEpoch;+ // When each chat last moved.+ final moved = {+ 'g-ask': at(minute * 12),+ 'buddy-oh': at(minute),+ 'buddy-desk': at(const Duration(hours: 2)),+ 'buddy-web': at(const Duration(days: 1)),+ for (final p in projects) 'lead-${p['id']}': at(minute * 4),+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...load,+ // The fixture's lead chat is another project's.+ 'groups': [+ for (final row in load['groups'] as List)+ if ((row as Map)['key'] != leadChat)+ {...row, 'changedAt': ?moved[row['key']]},+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ var answered = false;+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ if (!answered)+ {+ 'id': 'd1',+ 'projectId': 'p-oh',+ 'projectName': 'openharness',+ 'conversationId': 'g-ask',+ 'conversationTitle': 'phone leaderboard',+ 'askerName': 'River',+ 'question': 'Approve merge: PR #2154 Batch AB',+ 'options': ['Merge', 'Wait'],+ 'recommended': 0,+ 'createdAt': ago(minute * 2),+ },+ {+ 'id': 'd2',+ 'projectId': 'p-desk',+ 'projectName': 'desktop-app',+ 'conversationId': 'lead-p-desk',+ 'conversationTitle': 'desktop-app',+ 'askerName': 'Pike',+ 'question': 'Review proposal: Windows pipe fix',+ 'options': ['Approve', 'Hold'],+ 'recommended': 0,+ 'createdAt': ago(minute * 31),+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [+ {+ 'id': 'm1',+ 'projectId': 'p-oh',+ 'projectName': 'openharness',+ 'conversationId': 'lead-p-oh',+ 'conversationTitle': 'openharness',+ 'messageId': 'oh-9',+ 'leadName': 'River',+ 'text': 'Wait for #2151 before TestFlight?',+ 'createdAt': ago(minute * 9),+ },+ {+ 'id': 'm2',+ 'projectId': 'p-fw',+ 'projectName': 'firmware-dial',+ 'conversationId': 'lead-p-fw',+ 'conversationTitle': 'firmware-dial',+ 'messageId': 'fw-3',+ 'leadName': 'Kite',+ 'text': 'Plug in the Dial to flash the build',+ 'createdAt': ago(minute * 41),+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (body) {+ if (body?['command']?['type'] == 'decision.answer') answered = true;+ return {'result': <String, dynamic>{}};+ };+ Map<String, dynamic> message(+ String chat,+ String id,+ int sequence,+ String text, {+ String? by,+ Duration age = const Duration(minutes: 30),+ List<Map<String, dynamic>> reactions = const [],+ }) => {+ 'id': id,+ 'conversationId': chat,+ 'text': text,+ 'sequence': sequence,+ 'thread': id,+ 'author': by == null+ ? {'kind': 'person', 'id': me, 'name': '[email protected]'}+ : {'kind': 'agent', 'id': by, 'name': 'Agent'},+ 'reactions': reactions,+ 'createdAt': ago(age),+ };+ Map<String, dynamic> thread(+ String root,+ int last,+ String by, {+ int replies = 2,+ Duration age = const Duration(minutes: 5),+ }) => {+ 'id': root,+ 'replies': replies,+ 'lastSequence': last,+ 'lastAt': ago(age),+ 'authors': [+ {'kind': 'agent', 'id': by, 'name': 'Agent'},+ ],+ 'people': [me],+ };+ Map<String, dynamic> pageOf(+ List<Map<String, dynamic>> messages, [+ List<Map<String, dynamic>> threads = const [],+ ]) => {'messages': messages, 'threads': threads, 'next': null};+ fake.routes['/api/super-tabs/$tab/conversations/'] = (_) =>+ pageOf(const []);+ fake.routes['/api/super-tabs/$tab/conversations/lead-p-oh/messages'] =+ (_) => pageOf(+ [+ message(+ 'lead-p-oh',+ 'oh-4',+ 4,+ 'Ship the TestFlight tonight?',+ age: const Duration(hours: 1),+ ),+ message(+ 'lead-p-oh',+ 'oh-6',+ 6,+ 'Settings copy is fixed.',+ age: minute * 50,+ reactions: [+ {+ 'emoji': 'check',+ 'by': [+ {'kind': 'agent', 'id': 'agent-river'},+ ],+ },+ {+ 'emoji': 'rocket',+ 'by': [+ {'kind': 'agent', 'id': 'agent-moss'},+ ],+ },+ ],+ ),+ message(+ 'lead-p-oh',+ 'oh-8',+ 8,+ 'Starting the Dial build now.',+ age: minute * 20,+ reactions: [+ {+ 'emoji': 'eyes',+ 'by': [+ {'kind': 'agent', 'id': 'agent-ash'},+ ],+ },+ ],+ ),+ ],+ [thread('oh-4', 24, 'agent-ash', replies: 3, age: minute * 4)],+ );+ fake.routes['/api/super-tabs/$tab/conversations/lead-p-desk/messages'] =+ (_) => pageOf(+ [+ message(+ 'lead-p-desk',+ 'desk-3',+ 3,+ 'Is the 0.9 installer signed yet?',+ age: const Duration(hours: 3),+ ),+ ],+ [thread('desk-3', 8, 'agent-pike', age: const Duration(hours: 2))],+ );+ fake.routes['/api/super-tabs/$tab/conversations/buddy-oh/messages'] =+ (_) => pageOf([+ message(+ 'buddy-oh',+ 'b-oh-14',+ 14,+ 'Sent the Batch PR report: 3 of 4 checks green.',+ by: 'agent-wren',+ age: minute,+ ),+ ]);+ fake.routes['/api/super-tabs/$tab/conversations/buddy-desk/messages'] =+ (_) => pageOf([+ message(+ 'buddy-desk',+ 'b-desk-6',+ 6,+ 'Is 0.9 out yet?',+ age: const Duration(hours: 2),+ ),+ ]);+ fake.routes['/api/super-tabs/$tab/conversations/buddy-web/messages'] =+ (_) => pageOf([+ message(+ 'buddy-web',+ 'b-web-3',+ 3,+ 'The 502s were the worker pool running out.',+ by: 'agent-sage',+ age: const Duration(days: 1),+ ),+ ]);++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ // Not this phone's first Activity: the reactions are new.+ final store = MemoryKeyValueStore()+ ..values['swarm_activity.$me.$tab'] = '{"marks":{}}';+ final host = SwarmHost(+ accountId: () => me,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: store,+ )..foreground = false;+ final boundary = GlobalKey();+ final targets = ValueNotifier<List<Rect>>(const []);+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: Directionality(+ textDirection: TextDirection.ltr,+ child: Stack(+ children: [+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (_, child) =>+ SwarmScope(notifier: host, child: child!),+ // The Swarm tabs, as the phone's root has them.+ home: SwarmTabsPage(settings: (_) => const SizedBox()),+ ),+ Positioned.fill(+ child: IgnorePointer(+ child: ValueListenableBuilder<List<Rect>>(+ valueListenable: targets,+ builder: (_, rects, _) =>+ CustomPaint(painter: _Targets(rects)),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );+ 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/activity-c-$name-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ Finder keyed(String prefix) => find.byWidgetPredicate(+ (widget) =>+ widget.key is ValueKey<String> &&+ (widget.key! as ValueKey<String>).value.startsWith(prefix),+ );+ // Outlines what a thumb can tap, each with its size.+ Future<void> captureTargets(String name, List<String> prefixes) async {+ targets.value = [+ for (final prefix in prefixes)+ for (final element in keyed(prefix).evaluate())+ tester.getRect(find.byWidget(element.widget)),+ ];+ await tester.pump();+ await capture(name);+ targets.value = const [];+ await tester.pump();+ }++ Future<void> filter(String name) async {+ await tester.ensureVisible(+ find.byKey(ValueKey('swarm-activity-filter-$name')),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(ValueKey('swarm-activity-filter-$name')));+ await tester.pumpAndSettle();+ }++ Future<void> openTab(String name) async {+ await tester.tap(find.byKey(ValueKey('swarm-tab-$name')));+ await tester.pumpAndSettle();+ }++ const tabs = [+ 'swarm-tab-home',+ 'swarm-tab-buddies',+ 'swarm-tab-activity',+ 'swarm-tab-you',+ ];+ await openTab('activity');+ await capture('needs');+ await captureTargets('needs-targets', [+ ...tabs,+ 'swarm-activity-filter-',+ 'swarm-activity-approve-',+ 'swarm-activity-reply-',+ ]);+ await tester.tap(+ find.byKey(const ValueKey('swarm-activity-row-decision:d2')),+ );+ await tester.pumpAndSettle();+ await capture('needs-open');+ await tester.tap(+ find.byKey(const ValueKey('swarm-activity-approve-decision:d1')),+ );+ await tester.pumpAndSettle();+ await capture('approve-confirm');+ await tester.tap(+ find.byKey(const ValueKey('swarm-activity-approve-confirm')),+ );+ // The confirm closes, then its answer is held for Undo.+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 400));+ await capture('approve-held');+ await tester.pump(const Duration(seconds: 6));+ await tester.pumpAndSettle();+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();+ await capture('approved');+ await filter('mentions');+ await capture('mentions');+ await filter('threads');+ await capture('threads');+ await filter('reactions');+ await capture('reactions');+ await captureTargets('reactions-targets', [+ 'swarm-activity-filter-',+ 'swarm-activity-reply-',+ ]);++ await openTab('buddies');+ await capture('buddies');+ await captureTargets('buddies-targets', [...tabs, 'swarm-buddies-row-']);++ await tester.pumpWidget(const SizedBox());+ host.dispose();+ account.dispose();+ targets.dispose();+ }+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ }, skip: shots == null);+}++/// Each touch target outlined, its size in points over it.+class _Targets extends CustomPainter {+ _Targets(this.rects);++ final List<Rect> rects;++ @override+ void paint(Canvas canvas, Size size) {+ const color = Color(0xFFFF2D96);+ final outline = Paint()+ ..color = color+ ..style = PaintingStyle.stroke+ ..strokeWidth = 1.5;+ for (final rect in rects) {+ canvas.drawRect(rect.deflate(.75), outline);+ final label = TextPainter(+ text: TextSpan(+ text: '${rect.width.round()}×${rect.height.round()}',+ style: const TextStyle(+ fontFamily: '.AppleSystemUIFont',+ color: Colors.white,+ fontSize: 9,+ fontWeight: FontWeight.w700,+ backgroundColor: color,+ ),+ ),+ textDirection: TextDirection.ltr,+ )..layout();+ label.paint(canvas, rect.topLeft + const Offset(2, 1));+ }+ }++ @override+ bool shouldRepaint(_Targets old) => old.rects != rects;+}diff --git a/mobile/test/swarm/swarm_activity_test.dart b/mobile/test/swarm/swarm_activity_test.dartnew file mode 100644index 000000000..4f687b036--- /dev/null+++ b/mobile/test/swarm/swarm_activity_test.dart@@ -0,0 +1,558 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/swarm/swarm_activity.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart' show MemoryKeyValueStore;+import 'swarm_activity_fixture.dart';+import 'swarm_fixture.dart';++/// Activity, in place of Needs you (Tony's prototype C3): what the Swarms ask+/// of the person under Needs you and @, the threads they are in and the+/// reactions to what they wrote, each filter counted, and a row the person+/// acted on kept as handled.+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ const chatPath = activityChatPath;+ const backend = activityBackend;+ const message = activityMessage;+ const thread = activityThread;++ Future<SwarmSession> start(+ FakeSwarm fake, {+ MemoryKeyValueStore? store,+ Duration undoWindow = const Duration(milliseconds: 40),+ }) async {+ final session = SwarmSession(+ accountId: me,+ request: fake.request,+ notices: SilentSystemNotices(),+ undoWindow: undoWindow,+ readMarks: store ?? MemoryKeyValueStore(),+ );+ addTearDown(session.dispose);+ await session.inbox.refresh();+ await settle();+ return session;+ }++ List<String> keys(SwarmActivity activity, SwarmActivityFilter filter) => [+ for (final item in activity.items(filter)) item.key,+ ];++ int chatReads(FakeSwarm fake) =>+ fake.paths.where((p) => p.startsWith(chatPath)).length;++ group('Needs you and @', () {+ test('decisions and work waiting on the person, then the tags, each '+ 'counted', () async {+ final session = await start(backend());+ final activity = session.activity;++ expect(keys(activity, SwarmActivityFilter.needsYou), [+ 'decision:d1',+ 'work:$tab:g1:attempt-g1:needs_human',+ ]);+ expect(keys(activity, SwarmActivityFilter.mentions), ['mention:m1']);+ expect(activity.count(SwarmActivityFilter.needsYou), 2);+ expect(activity.count(SwarmActivityFilter.mentions), 1);+ expect(activity.badge, 2, reason: "the tab's badge: what needs them");+ });++ test('Approve holds the recommended option for Undo, sends it, and keeps '+ 'the row as handled once it is answered', () async {+ final fake = backend();+ final session = await start(fake);+ final activity = session.activity;+ final row = activity.items(SwarmActivityFilter.needsYou).first;++ activity.approve(row);+ expect(session.held(session.inbox.needs.first as dynamic), 1);+ expect(fake.commands, isEmpty, reason: 'held for Undo first');++ await until(() => fake.commands.isNotEmpty);+ expect(fake.commands.single, {+ 'type': 'decision.answer',+ 'decisionId': 'd1',+ 'choice': 1,+ });++ // Answered: the next read no longer has it.+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ derived: {'decisionsWaiting': 0, 'mentionsWaiting': 1},+ lastChangedAt: 2,+ );+ await session.inbox.refresh();+ await settle();++ final handled = activity.items(SwarmActivityFilter.needsYou).last;+ expect(handled.key, 'decision:d1');+ expect(activity.handled(handled), 'Approved');+ expect(activity.count(SwarmActivityFilter.needsYou), 1);+ });++ test('an Approve undone leaves the row open and sends nothing', () async {+ final fake = backend();+ final session = await start(fake, undoWindow: const Duration(seconds: 5));+ final activity = session.activity;+ final row = activity.items(SwarmActivityFilter.needsYou).first;++ activity.approve(row);+ session.undo(session.inbox.needs.first as dynamic);+ await settle();++ expect(fake.commands, isEmpty);+ expect(activity.handled(row), isNull);+ expect(activity.count(SwarmActivityFilter.needsYou), 2);+ });++ test('only a decision can be approved', () async {+ final session = await start(backend());+ final activity = session.activity;+ final tag = activity.items(SwarmActivityFilter.mentions).single;++ expect(activity.canApprove(tag), isFalse);+ activity.approve(tag);+ await settle();+ expect(activity.handled(tag), isNull);+ });++ test('Reply marks a row handled at once, out of the count', () async {+ final session = await start(backend());+ final activity = session.activity;+ final work = activity.items(SwarmActivityFilter.needsYou).last;++ activity.replied(work);++ expect(activity.handled(work), 'Opened');+ expect(activity.count(SwarmActivityFilter.needsYou), 1);+ expect(+ activity.items(SwarmActivityFilter.needsYou).last.key,+ work.key,+ reason: 'handled rows go below the open ones',+ );+ });++ test(+ 'a Swarm that leaves the list takes its rows, handled ones too',+ () async {+ final fake = backend();+ final session = await start(fake);+ final activity = session.activity;+ activity.replied(activity.items(SwarmActivityFilter.needsYou).last);++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': <Object>[],+ 'next': null,+ };+ fake.routes['/api/super-tabs/invitations'] = (_) => <Object>[];+ await session.inbox.refresh();+ await settle();++ for (final filter in SwarmActivityFilter.values) {+ expect(activity.items(filter), isEmpty, reason: filter.label);+ expect(activity.count(filter), 0);+ }+ },+ );+ });++ group('Threads and Reactions', () {+ const page = activityPage;++ test('reads nothing until Activity is on screen, then each project chat '+ 'once per counter', () async {+ final fake = backend(page: page);+ final session = await start(fake);+ final activity = session.activity;+ expect(chatReads(fake), 0);++ activity.watch();+ await settle();+ activity.unwatch();+ activity.watch();+ await session.inbox.refresh();+ await settle();++ expect(chatReads(fake), 1, reason: 'its counter did not move');+ });++ test('out of sight before its chats are read: what waits is taken back '+ 'and read only once Activity shows again', () async {+ final fake = backend(page: page);+ final session = await start(fake);+ final reader = session.inbox.reader(tab)!;+ // Another list's two reads hold both slots.+ final other = Object();+ final gates = [Completer<void>(), Completer<void>()];+ for (final (i, gate) in gates.indexed) {+ fake.routes['/api/super-tabs/$tab/conversations/other-$i/messages'] =+ (_) async {+ await gate.future;+ return {'messages': <Object>[], 'next': null};+ };+ session.peeks.want(reader, 'other-$i', counter: 1, owner: other);+ }+ final activity = session.activity..watch();+ await settle();+ expect(chatReads(fake), 0);++ activity.unwatch();+ for (final gate in gates) {+ gate.complete();+ }+ await settle();+ expect(chatReads(fake), 0, reason: 'nothing starts out of sight');++ activity.watch();+ await settle();+ expect(chatReads(fake), 1);+ });++ test(+ 'a thread the person is in, with a reply since they read the chat',+ () async {+ final fake = backend(page: page);+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();++ // root-old's last reply is before the read mark; root-others is not theirs.+ expect(keys(activity, SwarmActivityFilter.threads), [+ 'thread:$tab:root-1',+ 'thread:$tab:root-old',+ ]);+ final open = activity.items(SwarmActivityFilter.threads).first;+ expect(activity.handled(open), isNull);+ expect(+ activity.handled(activity.items(SwarmActivityFilter.threads).last),+ 'Read',+ );+ expect(activity.count(SwarmActivityFilter.threads), 1);+ },+ );++ test("a thread whose last reply is the person's own is not news", () async {+ final fake = backend(+ page: () => {+ ...page(),+ 'threads': [thread('root-1', last: 12, lastByMe: true)],+ },+ );+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();++ expect(activity.count(SwarmActivityFilter.threads), 0);+ });++ test(+ "others' reactions to the person's own messages, never their own",+ () async {+ final store = MemoryKeyValueStore()+ // Not this phone's first Activity: nothing is taken as seen.+ ..values['swarm_activity.$me.$tab'] = '{"marks":{}}';+ final fake = backend(page: page);+ final session = await start(fake, store: store);+ final activity = session.activity..watch();+ await settle();++ final rows = activity.items(SwarmActivityFilter.reactions);+ expect([for (final r in rows) r.key], ['reaction:$tab:mine-2']);+ final reaction = rows.single as SwarmActivityReaction;+ expect(+ [for (final r in reaction.reactions) (r.emoji.glyph, r.by.length)],+ [('✅', 1)],+ );+ expect(activity.count(SwarmActivityFilter.reactions), 1);+ },+ );++ test('handled threads and reactions stay handled on this phone, until '+ 'something new comes', () async {+ final store = MemoryKeyValueStore()+ ..values['swarm_activity.$me.$tab'] = '{"marks":{}}';+ var next = page();+ final fake = backend(page: () => next);+ final session = await start(fake, store: store);+ final activity = session.activity..watch();+ await settle();++ activity.replied(activity.items(SwarmActivityFilter.threads).first);+ activity.replied(activity.items(SwarmActivityFilter.reactions).single);+ await settle();+ expect(activity.count(SwarmActivityFilter.threads), 0);+ expect(activity.count(SwarmActivityFilter.reactions), 0);++ // Another phone session, the same marks.+ final again = await start(fake, store: store);+ again.activity.watch();+ await settle();+ expect(again.activity.count(SwarmActivityFilter.threads), 0);+ expect(again.activity.count(SwarmActivityFilter.reactions), 0);++ // A new reply and a new reaction: news again.+ next = {+ ...page(),+ 'messages': [+ for (final m in page()['messages'] as List)+ if ((m as Map)['id'] == 'mine-2')+ message(+ 'mine-2',+ 5,+ mine: true,+ reactions: [+ {+ 'emoji': 'check',+ 'by': [+ {'kind': 'agent', 'id': 'agent-lead'},+ {'kind': 'agent', 'id': 'agent-builder'},+ ],+ },+ ],+ )+ else+ m,+ ],+ 'threads': [thread('root-1', last: 14)],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ derived: {'decisionsWaiting': 1, 'mentionsWaiting': 1},+ lastChangedAt: 2,+ groups: [+ part(+ leadChat,+ 9,+ groupData(+ leadChat,+ title: 'Mobile',+ agentIds: ['agent-lead'],+ leadId: 'agent-lead',+ lastMessageSequence: 14,+ ),+ ),+ ],+ );+ await again.inbox.refresh();+ await settle();+ expect(again.activity.count(SwarmActivityFilter.threads), 1);+ expect(again.activity.count(SwarmActivityFilter.reactions), 1);+ });++ test("this phone's first Activity takes the reactions already there as "+ 'seen', () async {+ final fake = backend(page: page);+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();++ expect(activity.items(SwarmActivityFilter.reactions), hasLength(1));+ expect(activity.count(SwarmActivityFilter.reactions), 0);+ });++ test('a Swarm that leaves the list takes its marks, and what was read of '+ 'its chats, off the phone', () async {+ final store = MemoryKeyValueStore()+ ..values['swarm_activity.$me.$tab'] = '{"marks":{}}';+ final fake = backend(page: page);+ final session = await start(fake, store: store);+ final activity = session.activity..watch();+ await settle();+ activity.replied(activity.items(SwarmActivityFilter.threads).first);+ await settle();+ expect(store.values['swarm_activity.$me.$tab'], contains('root-1'));+ expect(session.peeks.held, 1);++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': <Object>[],+ 'next': null,+ };+ fake.routes['/api/super-tabs/invitations'] = (_) => <Object>[];+ await session.inbox.refresh();+ await settle();++ expect(store.values.containsKey('swarm_activity.$me.$tab'), isFalse);+ expect(activity.items(SwarmActivityFilter.threads), isEmpty);+ expect(session.peeks.held, 0, reason: 'no row of it left in memory');+ });++ test('a chat that cannot be read says so, and leaves the rest', () async {+ final fake = backend();+ fake.routes[chatPath] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();++ expect(activity.unreadChats, isTrue);+ expect(activity.count(SwarmActivityFilter.needsYou), 2);+ expect(activity.items(SwarmActivityFilter.threads), isEmpty);+ });++ test(+ 'reads while any screen shows it: the tab, and the page over Home',+ () async {+ final fake = backend(page: page);+ final session = await start(fake);+ final activity = session.activity+ ..watch()+ ..watch()+ ..unwatch();+ await settle();+ expect(activity.shown, isTrue);+ expect(chatReads(fake), 1);++ activity.unwatch();+ expect(activity.shown, isFalse);+ },+ );++ test('says it is reading the project chats until they answer', () async {+ final fake = backend();+ final gate = Completer<void>();+ fake.routes[chatPath] = (_) async {+ await gate.future;+ return {'messages': <Object>[], 'next': null};+ };+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();+ expect(activity.reading, isTrue);++ gate.complete();+ await settle();+ expect(activity.reading, isFalse);+ });++ test('Try again reads a project chat that failed', () async {+ final fake = backend();+ fake.routes[chatPath] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();+ expect(activity.unreadChats, isTrue);++ fake.routes[chatPath] = (_) => page();+ activity.retry();+ await settle();++ expect(activity.unreadChats, isFalse);+ expect(activity.items(SwarmActivityFilter.threads), isNotEmpty);+ });++ test(+ 'a chat the person may not read is skipped with nothing said',+ () async {+ final fake = backend();+ fake.routes[chatPath] = (_) =>+ throw const SuperTabFailure('FORBIDDEN', 'Not yours.');+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();++ expect(activity.unreadChats, isFalse);+ expect(activity.items(SwarmActivityFilter.threads), isEmpty);+ },+ );++ test('reads only project chats: never a Buddy chat, a private chat or a '+ 'task chat, however they moved', () async {+ final fake = backend(+ page: page,+ groups: [+ buddyChatData('buddy-me', lastMessageSequence: 4),+ buddyChatData(+ 'buddy-theirs',+ owner: 'person-other',+ lastMessageSequence: 4,+ ),+ groupData('g-private', audience: [me], lastMessageSequence: 3),+ groupData('g-task', title: 'Task', lastMessageSequence: 9),+ ],+ );+ final session = await start(fake);+ session.activity.watch();+ await settle();++ expect(+ [+ for (final path in fake.paths)+ if (path.contains('/messages')) path,+ ],+ [chatPath],+ );+ });++ test('access lost while a project chat is being read: its answer is '+ 'dropped, and nothing of the Swarm is left', () async {+ final fake = backend();+ final gate = Completer<void>();+ fake.routes[chatPath] = (_) async {+ await gate.future;+ return page();+ };+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();+ expect(activity.reading, isTrue);++ session.inbox.reader(tab)!.revoke();+ gate.complete();+ await settle();++ for (final filter in SwarmActivityFilter.values) {+ expect(activity.items(filter), isEmpty, reason: filter.label);+ }+ expect(activity.reading, isFalse);+ expect(activity.unreadChats, isFalse);+ expect(session.peeks.held, 0);+ });++ test('the same chat and agent ids in two Swarms: each read on its own, '+ 'its rows under its own Swarm', () async {+ final fake = backend(page: page);+ activitySecondSwarm(fake, page: page);+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();++ expect(+ [+ for (final path in fake.paths)+ if (path.contains('/messages')) path,+ ]..sort(),+ [chatPath, '/api/super-tabs/tab-2/conversations/$leadChat/messages'],+ );+ expect(keys(activity, SwarmActivityFilter.threads)..sort(), [+ 'thread:$tab:root-1',+ 'thread:$tab:root-old',+ 'thread:tab-2:root-1',+ 'thread:tab-2:root-old',+ ]);+ activity.replied(+ activity+ .items(SwarmActivityFilter.threads)+ .firstWhere((item) => item.key == 'thread:tab-2:root-1'),+ );+ expect(+ activity.handled(+ activity+ .items(SwarmActivityFilter.threads)+ .firstWhere((item) => item.key == 'thread:$tab:root-1'),+ ),+ isNull,+ reason: "a thread opened in one Swarm is not the other's",+ );+ });+ });+}diff --git a/mobile/test/swarm/swarm_buddies_fixture.dart b/mobile/test/swarm/swarm_buddies_fixture.dartnew file mode 100644index 000000000..bca057a6e--- /dev/null+++ b/mobile/test/swarm/swarm_buddies_fixture.dart@@ -0,0 +1,172 @@+import 'swarm_fixture.dart';++/// Buddies' backend as a test scripts it (swarm_buddy_list_test.dart,+/// swarm_buddies_page_test.dart), built by hand so it reads like the wire.++const buddiesWeb = 'project-2';+const buddiesDocs = 'project-3';++/// The person's Buddy chats: Mobile's, where Wren runs, and Web's, where+/// Kite is offline. Docs has none.+const buddiesMobileChat = 'buddy-mobile';+const buddiesWebChat = 'buddy-web';++/// Someone else's Buddy chat in Mobile: never listed, never read.+const buddiesTheirChat = 'buddy-ann';++String buddiesChatPath(String chat, {String swarmId = tab}) =>+ '/api/super-tabs/$swarmId/conversations/$chat/messages';++Map<String, dynamic> buddiesMessage(+ String chat,+ int sequence, {+ String text = '',+ bool mine = false,+ String author = 'agent-wren',+ String? thread,+}) => {+ 'id': '$chat-$sequence',+ 'conversationId': chat,+ 'text': text.isEmpty ? 'Row $sequence' : text,+ 'sequence': sequence,+ 'thread': ?thread,+ 'author': mine+ ? {'kind': 'person', 'id': me, 'name': '[email protected]'}+ : {'kind': 'agent', 'id': author, 'name': 'Buddy'},+ 'createdAt': DateTime.utc(2026, 10, 29, 8, sequence).toIso8601String(),+};++Map<String, dynamic> buddiesProject(String id, String name, String lead) => {+ 'id': id,+ 'name': name,+ 'ownerId': me,+ 'leadConversationId': lead,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+};++/// Swarm [swarmId]'s first load: Mobile, Web and Docs, each with its project+/// chat; the person's Buddy chats in Mobile ([mobileSequence] rows, Wren's+/// Buddy [wren] by name, running) and Web (4 rows, Kite offline); someone+/// else's Buddy chat in Mobile. The server's read marks are [readMarks].+Map<String, dynamic> buddiesLoad({+ String swarmId = tab,+ String swarmName = 'Phone Swarm',+ int mobileSequence = 7,+ int? mobileMainSequence,+ String wren = 'Wren',+ Map<String, int> readMarks = const {buddiesMobileChat: 5, buddiesWebChat: 4},+}) {+ Map<String, dynamic> inWeb(Map<String, dynamic> row) => {+ ...row,+ 'projectId': buddiesWeb,+ };+ Map<String, dynamic> inDocs(Map<String, dynamic> row) => {+ ...row,+ 'projectId': buddiesDocs,+ };+ return firstLoad(+ tabId: swarmId,+ derived: {'readMarks': readMarks},+ head: headData(+ id: swarmId,+ name: swarmName,+ projects: [+ buddiesProject(project, 'Mobile', leadChat),+ buddiesProject(buddiesWeb, 'Web', 'group-lead-web'),+ buddiesProject(buddiesDocs, 'Docs', 'group-lead-docs'),+ ],+ ),+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ buddyData('agent-wren', displayName: wren),+ inWeb({+ ...buddyData('agent-kite', displayName: 'Kite'),+ 'downSince': '2026-10-29T07:00:00.000Z',+ }),+ buddyData('agent-ann', owner: 'person-ann', displayName: 'Ann'),+ ],+ groups: [+ {+ ...buddyChatData(+ buddiesMobileChat,+ agentIds: ['agent-wren'],+ lastMessageSequence: mobileSequence,+ ),+ 'lastMainSequence': ?mobileMainSequence,+ },+ inWeb(+ buddyChatData(+ buddiesWebChat,+ agentIds: ['agent-kite'],+ lastMessageSequence: 4,+ ),+ ),+ buddyChatData(+ buddiesTheirChat,+ owner: 'person-ann',+ agentIds: ['agent-ann'],+ lastMessageSequence: 3,+ ),+ inWeb(groupData('group-lead-web', title: 'Web', leadId: 'agent-lead')),+ inDocs(groupData('group-lead-docs', title: 'Docs', leadId: 'agent-lead')),+ ],+ );+}++/// One Swarm as [buddiesLoad] has it. Mobile's Buddy chat answers Wren's+/// last line, Web's the person's own; every other chat answers nothing.+FakeSwarm buddiesBackend({+ int mobileSequence = 7,+ int? mobileMainSequence,+ Map<String, int> readMarks = const {buddiesMobileChat: 5, buddiesWebChat: 4},+}) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me, 'lastChangedAt': 1},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => buddiesLoad(+ mobileSequence: mobileSequence,+ mobileMainSequence: mobileMainSequence,+ readMarks: readMarks,+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: {'readMarks': readMarks});+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (body) => {+ 'result': switch (body?['command']) {+ {'type': 'buddy.chat', 'projectId': buddiesDocs} => {+ 'conversationId': 'buddy-docs',+ },+ _ => <String, dynamic>{},+ },+ };+ fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };+ fake.routes[buddiesChatPath(buddiesMobileChat)] = (_) => {+ 'messages': [+ buddiesMessage(buddiesMobileChat, 7, text: 'Done: the build is up.'),+ ],+ 'threads': <Object>[],+ 'next': null,+ };+ fake.routes[buddiesChatPath(buddiesWebChat)] = (_) => {+ 'messages': [+ buddiesMessage(buddiesWebChat, 4, text: 'Is 0.9 out yet?', mine: true),+ ],+ 'threads': <Object>[],+ 'next': null,+ };+ return fake;+}diff --git a/mobile/test/swarm/swarm_buddies_page_test.dart b/mobile/test/swarm/swarm_buddies_page_test.dartnew file mode 100644index 000000000..fe8b7b69e--- /dev/null+++ b/mobile/test/swarm/swarm_buddies_page_test.dart@@ -0,0 +1,249 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/phone/out_of_sight.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' show AppFont;+import 'package:harness_mobile/swarm/swarm_buddies_page.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_style.dart';++import '../voice_fakes.dart';+import 'swarm_buddies_fixture.dart';+import 'swarm_fixture.dart';++/// The Buddies screen (Tony's prototype C2): a row per project, its tile and+/// name, how the person's Buddy there stands and the last message of their+/// Buddy chat; unread ones bold; a tap opens that chat. It reads only while+/// on screen, says what it could not read, and shows nothing of a Swarm the+/// person can no longer read.+void main() {+ const mobile = 'swarm-buddies-row-$tab/$project';+ const web = 'swarm-buddies-row-$tab/$buddiesWeb';+ const docs = 'swarm-buddies-row-$tab/$buddiesDocs';++ /// [home] under a signed-in shell's Swarm, Swarm on, on a 390-point phone.+ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ Widget home = const SwarmBuddiesView(),+ }) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: home,+ ),+ );+ await tester.pumpAndSettle();+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ Finder inside(String row, Finder finder) =>+ find.descendant(of: key(row), matching: finder);++ int chatReads(FakeSwarm fake) =>+ fake.paths.where((p) => p.contains('/messages')).length;++ FontWeight? weightOf(WidgetTester tester, String row, String text) =>+ tester.widget<Text>(inside(row, find.text(text))).style?.fontWeight;++ testWidgets("its title, then a row per project, newest first: its tile and "+ "name, its Buddy's state and the last message", (tester) async {+ await pump(tester, buddiesBackend());++ expect(find.text('Buddies'), findsOneWidget);+ expect(inside(mobile, find.byType(SwarmProjectTile)), findsOneWidget);+ expect(inside(mobile, find.text('Mobile')), findsOneWidget);+ expect(inside(mobile, find.text('running')), findsOneWidget);+ expect(inside(mobile, find.text('Done: the build is up.')), findsOneWidget);+ expect(inside(web, find.text('offline')), findsOneWidget);+ expect(inside(web, find.text('You: Is 0.9 out yet?')), findsOneWidget);+ expect(inside(docs, find.text('not started')), findsOneWidget);+ expect(inside(docs, find.text('No Buddy yet')), findsOneWidget);+ double y(String row) => tester.getTopLeft(key(row)).dy;+ expect(y(mobile), lessThan(y(web)));+ expect(y(web), lessThan(y(docs)));+ expect(+ find.text("person-ann's Buddy"),+ findsNothing,+ reason: "someone else's Buddy chat is not listed",+ );+ });++ testWidgets("each row's time sits at its end, whatever its name's length", (+ tester,+ ) async {+ await pump(tester, buddiesBackend());++ double end(String row) =>+ tester.getTopRight(key('swarm-buddies-age-$tab/$row')).dx;+ expect(end(buddiesWeb), end(project));+ expect(+ end(project),+ closeTo(tester.getTopRight(key(mobile)).dx - 16, .5),+ reason: "at the row's inset",+ );+ });++ testWidgets('a chat with something unread is bold, with a dot; a read one '+ 'is quiet', (tester) async {+ await pump(tester, buddiesBackend());++ expect(weightOf(tester, mobile, 'Mobile'), AppFont.semibold);+ expect(key('swarm-buddies-unread-$tab/$project'), findsOneWidget);+ expect(weightOf(tester, web, 'Web'), isNot(AppFont.semibold));+ expect(key('swarm-buddies-unread-$tab/$buddiesWeb'), findsNothing);+ expect(find.bySemanticsLabel(RegExp('Unread messages')), findsOneWidget);+ });++ testWidgets('every row is a thumb tall, and a tap opens its Buddy chat', (+ tester,+ ) async {+ await pump(tester, buddiesBackend());++ for (final row in [mobile, web, docs]) {+ expect(tester.getSize(key(row)).height, greaterThanOrEqualTo(44));+ }+ await tester.tap(key(mobile));+ await tester.pumpAndSettle();++ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), (tab, buddiesMobileChat));+ });++ testWidgets('a project with no Buddy chat opens one on a tap', (+ tester,+ ) async {+ final fake = buddiesBackend();+ await pump(tester, fake);++ await tester.tap(key(docs));+ await tester.pumpAndSettle();++ expect(fake.commands.single, {+ 'type': 'buddy.chat',+ 'projectId': buddiesDocs,+ });+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), (tab, 'buddy-docs'));+ });++ testWidgets('out of sight, it reads no chat; in sight again, it does', (+ tester,+ ) async {+ final fake = buddiesBackend();+ final hidden = ValueNotifier(true);+ addTearDown(hidden.dispose);+ await pump(+ tester,+ fake,+ home: ValueListenableBuilder<bool>(+ valueListenable: hidden,+ builder: (context, out, _) =>+ OutOfSight(hidden: out, child: const SwarmBuddiesView()),+ ),+ );+ expect(chatReads(fake), 0);++ hidden.value = false;+ await tester.pumpAndSettle();+ expect(chatReads(fake), 2);+ expect(find.text('Done: the build is up.'), findsOneWidget);+ });++ testWidgets('a chat that could not be read says so; Try again reads it; '+ 'none waits on a stuck Loading', (tester) async {+ final fake = buddiesBackend();+ var fail = true;+ final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;+ fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) => fail+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : answer(body);+ await pump(tester, fake);++ expect(find.text('Some Buddy chats could not be read.'), findsOneWidget);+ expect(inside(web, find.text('You: Is 0.9 out yet?')), findsOneWidget);+ expect(key('swarm-buddies-loading'), findsNothing);+ expect(+ tester.getSize(key('swarm-buddies-retry')).height,+ greaterThanOrEqualTo(44),+ );++ fail = false;+ await tester.tap(key('swarm-buddies-retry'));+ await tester.pumpAndSettle();++ expect(find.text('Some Buddy chats could not be read.'), findsNothing);+ expect(inside(mobile, find.text('Done: the build is up.')), findsOneWidget);+ });++ testWidgets('the rows show while their chats are read, their last line '+ 'filling as each answers', (tester) async {+ final fake = buddiesBackend();+ final gate = Completer<void>();+ final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;+ fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) async {+ await gate.future;+ return answer(body);+ };+ await pump(tester, fake);++ expect(key(mobile), findsOneWidget);+ expect(inside(mobile, find.text('Done: the build is up.')), findsNothing);+ expect(inside(web, find.text('You: Is 0.9 out yet?')), findsOneWidget);++ gate.complete();+ await tester.pumpAndSettle();+ expect(inside(mobile, find.text('Done: the build is up.')), findsOneWidget);+ });++ testWidgets('access lost while it is open: every row of that Swarm goes', (+ tester,+ ) async {+ final host = await pump(tester, buddiesBackend());+ expect(key(mobile), findsOneWidget);++ host.session!.inbox.reader(tab)!.revoke();+ await tester.pumpAndSettle();++ for (final row in [mobile, web, docs]) {+ expect(key(row), findsNothing);+ }+ expect(find.text('Done: the build is up.'), findsNothing);+ expect(find.text('Mobile'), findsNothing);+ });++ testWidgets('a Swarm with no project says so', (tester) async {+ final fake = buddiesBackend();+ fake.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(head: headData(projects: const []));+ await pump(tester, fake);++ expect(key('swarm-buddies-none'), findsOneWidget);+ expect(find.text('No projects yet.'), findsOneWidget);+ });+}diff --git a/mobile/test/swarm/swarm_buddy_list_test.dart b/mobile/test/swarm/swarm_buddy_list_test.dartnew file mode 100644index 000000000..9529c8d15--- /dev/null+++ b/mobile/test/swarm/swarm_buddy_list_test.dart@@ -0,0 +1,343 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/swarm/swarm_buddy_list.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart' show MemoryKeyValueStore;+import 'swarm_buddies_fixture.dart';+import 'swarm_fixture.dart';++/// Buddies (Tony's prototype C2): one row per project of every Swarm, with+/// the person's own Buddy there, how it stands and the last message of their+/// Buddy chat, read from that message on and only while Buddies is on screen.+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ Future<SwarmSession> start(FakeSwarm fake) async {+ final session = SwarmSession(+ accountId: me,+ request: fake.request,+ notices: SilentSystemNotices(),+ readMarks: MemoryKeyValueStore(),+ );+ addTearDown(session.dispose);+ await session.inbox.refresh();+ await settle();+ return session;+ }++ List<String> reads(FakeSwarm fake) => [+ for (final path in fake.paths)+ if (path.contains('/messages')) path,+ ];++ SwarmBuddyRow row(SwarmBuddyList list, String projectId, {String? swarm}) =>+ list.rows.singleWhere(+ (row) =>+ row.project.id == projectId &&+ (swarm == null || row.swarmId == swarm),+ );++ test(+ 'one row per project, newest first; one with no Buddy chat last',+ () async {+ final session = await start(buddiesBackend());+ final list = session.buddyList..watch();+ await settle();++ expect(+ [for (final row in list.rows) row.project.name],+ ['Mobile', 'Web', 'Docs'],+ );+ expect(row(list, project).chat?.id, buddiesMobileChat);+ expect(row(list, buddiesDocs).chat, isNull);+ },+ );++ test('reads nothing until Buddies is on screen, then each of the '+ "person's Buddy chats from its last message on, once", () async {+ final fake = buddiesBackend();+ final session = await start(fake);+ final list = session.buddyList;+ expect(reads(fake), isEmpty);++ list.watch();+ await settle();+ expect(reads(fake)..sort(), [+ '${buddiesChatPath(buddiesMobileChat)}?after=6',+ '${buddiesChatPath(buddiesWebChat)}?after=3',+ ], reason: "never someone else's Buddy chat, nor a project chat");++ list.unwatch();+ list.watch();+ await settle();+ expect(reads(fake), hasLength(2), reason: 'nothing moved: nothing read');+ });++ test('out of sight before its chats are read: what waits is taken back '+ 'and read only once Buddies shows again', () async {+ final fake = buddiesBackend();+ final session = await start(fake);+ final reader = session.inbox.reader(tab)!;+ // Another list's two reads hold both slots.+ final other = Object();+ final gates = [Completer<void>(), Completer<void>()];+ for (final (i, gate) in gates.indexed) {+ fake.routes[buddiesChatPath('other-$i')] = (_) async {+ await gate.future;+ return {'messages': <Object>[], 'next': null};+ };+ session.peeks.want(reader, 'other-$i', counter: 1, owner: other);+ }+ List<String> buddyReads() => [+ for (final path in reads(fake))+ if (!path.contains('/other-')) path,+ ];+ final list = session.buddyList..watch();+ await settle();+ expect(buddyReads(), isEmpty);++ list.unwatch();+ for (final gate in gates) {+ gate.complete();+ }+ await settle();+ expect(buddyReads(), isEmpty, reason: 'nothing starts out of sight');++ list.watch();+ await settle();+ expect(buddyReads(), hasLength(2));+ });++ test("each row's last message, its Buddy's name and how it stands", () async {+ final session = await start(buddiesBackend());+ final list = session.buddyList..watch();+ await settle();+ final reader = session.inbox.reader(tab)!;++ final mobile = row(list, project);+ expect(mobile.last?.text, 'Done: the build is up.');+ expect(swarmBuddyLine(mobile, reader), 'Done: the build is up.');+ expect((mobile.name, mobile.note), ('Wren', null), reason: 'it runs');++ final web = row(list, buddiesWeb);+ expect(swarmBuddyLine(web, reader), 'You: Is 0.9 out yet?');+ expect((web.name, web.note), ('Kite', 'offline'));++ final docs = row(list, buddiesDocs);+ expect(swarmBuddyLine(docs, reader), 'No Buddy yet');+ expect((docs.name, docs.note), ('Buddy', 'not started'));+ });++ test('a chat past its read mark is unread; the badge counts those', () async {+ final session = await start(buddiesBackend());+ final list = session.buddyList..watch();+ await settle();++ expect(row(list, project).unread, isTrue);+ expect(row(list, buddiesWeb).unread, isFalse);+ expect(row(list, buddiesDocs).unread, isFalse);+ expect(list.badge, 1);+ });++ test('a new message in the chat is read again; a reply only in a thread '+ 'is not', () async {+ final fake = buddiesBackend();+ final session = await start(fake);+ final list = session.buddyList..watch();+ await settle();+ expect(reads(fake), hasLength(2));++ var version = 30;+ Future<void> move(int sequence, int main) async {+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c${version++}',+ derived: const {+ 'readMarks': {buddiesMobileChat: 5, buddiesWebChat: 4},+ },+ groups: [+ part(buddiesMobileChat, version, {+ ...buddyChatData(+ buddiesMobileChat,+ agentIds: ['agent-wren'],+ lastMessageSequence: sequence,+ ),+ 'lastMainSequence': main,+ }),+ ],+ );+ await session.inbox.refresh();+ await settle();+ }++ await move(8, 7);+ expect(reads(fake), hasLength(2), reason: 'a thread reply moved it');++ fake.routes[buddiesChatPath(buddiesMobileChat)] = (_) => {+ 'messages': [buddiesMessage(buddiesMobileChat, 9, text: 'Next one')],+ 'threads': <Object>[],+ 'next': null,+ };+ await move(9, 9);+ expect(reads(fake).last, '${buddiesChatPath(buddiesMobileChat)}?after=8');+ expect(row(list, project).last?.text, 'Next one');+ });++ test('the last message is the newest in the chat itself, not a reply in '+ 'a thread', () async {+ final fake = buddiesBackend(mobileSequence: 9, mobileMainSequence: 8);+ fake.routes[buddiesChatPath(buddiesMobileChat)] = (_) => {+ 'messages': [+ buddiesMessage(buddiesMobileChat, 8, text: 'In the chat'),+ buddiesMessage(+ buddiesMobileChat,+ 9,+ text: 'In a thread',+ thread: '$buddiesMobileChat-8',+ ),+ ],+ 'threads': <Object>[],+ 'next': null,+ };+ final session = await start(fake);+ final list = session.buddyList..watch();+ await settle();++ expect(row(list, project).last?.text, 'In the chat');+ });++ test('access lost while Buddies is open: its rows go, and an answer still '+ 'on its way is dropped', () async {+ final fake = buddiesBackend();+ final gate = Completer<void>();+ final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;+ fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) async {+ await gate.future;+ return answer(body);+ };+ final session = await start(fake);+ final list = session.buddyList..watch();+ await settle();+ expect(row(list, buddiesWeb).last, isNotNull);++ session.inbox.reader(tab)!.revoke();+ gate.complete();+ await settle();++ expect(list.rows, isEmpty);+ expect(list.badge, 0);+ expect(session.peeks.held, 0, reason: 'nothing of it left in memory');+ });++ test('the same Buddy id and chat id in two Swarms: each row reads and '+ 'names its own', () async {+ final fake = buddiesBackend();+ const other = 'tab-2';+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me, 'lastChangedAt': 2},+ {'id': other, 'name': 'Other', 'ownerId': me, 'lastChangedAt': 1},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$other/parts'] = (_) =>+ buddiesLoad(swarmId: other, swarmName: 'Other', wren: 'Pip');+ fake.routes['/api/super-tabs/$other/changes'] = (_) =>+ changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$other/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$other/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[buddiesChatPath(buddiesMobileChat, swarmId: other)] = (_) => {+ 'messages': [+ buddiesMessage(buddiesMobileChat, 7, text: 'From the other Swarm'),+ ],+ 'threads': <Object>[],+ 'next': null,+ };+ final session = await start(fake);+ final list = session.buddyList..watch();+ await settle();++ final mine = row(list, project, swarm: tab);+ final theirs = row(list, project, swarm: other);+ expect((mine.name, mine.last?.text), ('Wren', 'Done: the build is up.'));+ expect((theirs.name, theirs.last?.text), ('Pip', 'From the other Swarm'));+ expect(mine.key, isNot(theirs.key));+ });++ test('a chat that fails to read says so, is tried a few times, and Try '+ 'again reads it once more; never stuck reading', () async {+ final fake = buddiesBackend();+ var fail = true;+ final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;+ fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) => fail+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : answer(body);+ final session = await start(fake);+ final list = session.buddyList..watch();+ await settle();+ // Shown again and again, at the same counter.+ for (var i = 0; i < 4; i++) {+ list+ ..unwatch()+ ..watch();+ await settle();+ }++ int mobileReads() =>+ reads(fake)+ .where((p) => p.startsWith(buddiesChatPath(buddiesMobileChat)))+ .length;+ expect(mobileReads(), 3);+ expect(list.unreadChats, isTrue);+ expect(list.reading, isFalse);+ expect(row(list, project).last, isNull);++ fail = false;+ list.retry();+ await settle();+ expect(mobileReads(), 4);+ expect(list.unreadChats, isFalse);+ expect(row(list, project).last?.text, 'Done: the build is up.');+ });++ test(+ 'a Buddy chat the person may no longer read is skipped quietly',+ () async {+ final fake = buddiesBackend();+ fake.routes[buddiesChatPath(buddiesMobileChat)] = (_) =>+ throw const SuperTabFailure('FORBIDDEN', 'Not yours.');+ final session = await start(fake);+ final list = session.buddyList..watch();+ await settle();++ expect(list.unreadChats, isFalse);+ expect(row(list, project).last, isNull);+ expect(row(list, buddiesWeb).last, isNotNull);+ },+ );++ test('says it is reading while a chat is read for the first time', () async {+ final fake = buddiesBackend();+ final gate = Completer<void>();+ final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;+ fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) async {+ await gate.future;+ return answer(body);+ };+ final session = await start(fake);+ final list = session.buddyList..watch();+ await settle();+ expect(list.reading, isTrue);++ gate.complete();+ await settle();+ expect(list.reading, isFalse);+ });+}diff --git a/mobile/test/swarm/swarm_chat_peeks_test.dart b/mobile/test/swarm/swarm_chat_peeks_test.dartnew file mode 100644index 000000000..70388b2ec--- /dev/null+++ b/mobile/test/swarm/swarm_chat_peeks_test.dart@@ -0,0 +1,474 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_chat_peeks.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import 'swarm_fixture.dart';++/// A few chats' newest rows for Activity and Buddies, read only when a chat's+/// counter moved, two at a time, and never kept past the reader's access.+void main() {+ /// The list that wants the chats read, as Activity or Buddies would.+ final screen = Object();++ String path(String chat) =>+ '/api/super-tabs/$tab/conversations/$chat/messages';++ Map<String, dynamic> message(String id, String chat, int sequence) => {+ 'id': id,+ 'conversationId': chat,+ 'text': 'Row $id',+ 'sequence': sequence,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'createdAt': '2026-10-29T08:00:00.000Z',+ };++ Map<String, dynamic> page(String chat, List<int> sequences) => {+ 'messages': [for (final s in sequences) message('$chat-$s', chat, s)],+ 'threads': [+ {+ 'id': '$chat-${sequences.first}',+ 'replies': 2,+ 'lastSequence': sequences.last,+ 'lastAt': '2026-10-29T08:05:00.000Z',+ 'authors': <Object>[],+ 'people': [me],+ },+ ],+ 'next': null,+ };++ SwarmReader reader(FakeSwarm fake) {+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: fake.request,+ );+ addTearDown(reader.dispose);+ return reader;+ }++ SwarmChatPeeks peeks() {+ final peeks = SwarmChatPeeks();+ addTearDown(peeks.dispose);+ return peeks;+ }++ int reads(FakeSwarm fake, String chat) =>+ fake.paths.where((p) => p.startsWith(path(chat))).length;++ test('reads a chat once per counter, and again when it moves', () async {+ final fake = FakeSwarm();+ fake.routes[path('a')] = (_) => page('a', [3, 5]);+ final r = reader(fake);+ final p = peeks();++ p.want(r, 'a', counter: 5, owner: screen);+ await settle();+ p.want(r, 'a', counter: 5, owner: screen);+ await settle();++ expect(reads(fake, 'a'), 1);+ final peek = p.of(r, 'a')!;+ expect([for (final m in peek.messages) m.id], ['a-3', 'a-5']);+ expect(peek.threads['a-3']!.people, [me]);++ p.want(r, 'a', counter: 6, owner: screen);+ await settle();+ expect(reads(fake, 'a'), 2);+ });++ test('reads forward from a sequence when asked to', () async {+ final fake = FakeSwarm();+ fake.routes[path('b')] = (_) => page('b', [9]);+ final r = reader(fake);+ final p = peeks();++ p.want(r, 'b', counter: 9, after: 8, owner: screen);+ await settle();++ expect(fake.paths.single, '${path('b')}?after=8');+ expect(p.of(r, 'b')!.messages.single.id, 'b-9');+ });++ test('reads two chats at a time', () async {+ final fake = FakeSwarm();+ final gates = {+ for (final c in ['a', 'b', 'c']) c: Completer<void>(),+ };+ for (final chat in gates.keys) {+ fake.routes[path(chat)] = (_) async {+ await gates[chat]!.future;+ return page(chat, [1]);+ };+ }+ final r = reader(fake);+ final p = peeks();++ for (final chat in gates.keys) {+ p.want(r, chat, counter: 1, owner: screen);+ }+ await settle();+ expect(fake.paths, [path('a'), path('b')]);++ gates['a']!.complete();+ await settle();+ expect(fake.paths, [path('a'), path('b'), path('c')]);+ gates['b']!.complete();+ gates['c']!.complete();+ await settle();+ expect(p.of(r, 'c'), isNotNull);+ });++ test('an answer that comes after access ended is dropped', () async {+ final fake = FakeSwarm();+ final gate = Completer<void>();+ fake.routes[path('a')] = (_) async {+ await gate.future;+ return page('a', [1]);+ };+ final r = reader(fake);+ final p = peeks();++ p.want(r, 'a', counter: 1, owner: screen);+ await settle();+ r.revoke();+ gate.complete();+ await settle();++ expect(p.of(r, 'a'), isNull);+ });++ test('what was read goes when the reader reads from nothing again', () async {+ final fake = FakeSwarm();+ fake.routes[path('a')] = (_) => page('a', [1]);+ final r = reader(fake);+ final p = peeks();+ p.want(r, 'a', counter: 1, owner: screen);+ await settle();+ expect(p.of(r, 'a'), isNotNull);++ r.revoke();++ expect(p.of(r, 'a'), isNull, reason: 'held under an earlier generation');+ });++ test(+ 'a chat the person may not read is skipped quietly, and not asked again',+ () async {+ final fake = FakeSwarm();+ fake.routes[path('a')] = (_) =>+ throw const SuperTabFailure('FORBIDDEN', 'Not yours.');+ final r = reader(fake);+ final p = peeks();++ p.want(r, 'a', counter: 1, owner: screen);+ await settle();+ p.want(r, 'a', counter: 1, owner: screen);+ await settle();++ expect(p.of(r, 'a'), isNull);+ expect(+ p.failedAt(r, 'a'),+ isFalse,+ reason: 'a refusal is no failure to report',+ );+ expect(reads(fake, 'a'), 1);+ },+ );++ test('a failed read is tried at most three times for one counter', () async {+ final fake = FakeSwarm();+ var fail = true;+ fake.routes[path('a')] = (_) => fail+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : page('a', [1]);+ final r = reader(fake);+ final p = peeks();++ for (var i = 0; i < 5; i++) {+ p.want(r, 'a', counter: 1, owner: screen);+ await settle();+ }+ expect(reads(fake, 'a'), 3);+ expect(p.failedAt(r, 'a'), isTrue);++ fail = false;+ p.want(r, 'a', counter: 2, owner: screen);+ await settle();+ expect(p.of(r, 'a'), isNotNull);+ expect(p.failedAt(r, 'a'), isFalse);+ });++ test('a page of another conversation is refused', () async {+ final fake = FakeSwarm();+ fake.routes[path('a')] = (_) => page('other', [1]);+ final r = reader(fake);+ final p = peeks();++ p.want(r, 'a', counter: 1, owner: screen);+ await settle();++ expect(p.of(r, 'a'), isNull);+ });++ test('keeps only what the listed readers hold: a reader off the list, '+ 'revoked or reading from nothing again takes its rows with it', () async {+ final fake = FakeSwarm();+ fake.routes[path('a')] = (_) => page('a', [1]);+ fake.routes[path('b')] = (_) => page('b', [1]);+ final kept = reader(fake), gone = reader(fake), revoked = reader(fake);+ final p = peeks();+ for (final r in [kept, gone, revoked]) {+ p.want(r, 'a', counter: 1, owner: screen);+ p.want(r, 'b', counter: 1, owner: screen);+ }+ await settle();+ expect(p.held, 6);++ revoked.revoke();+ p.keepOnly([kept, revoked]);++ expect(p.held, 2, reason: "only the listed, readable reader's rows");+ expect(p.of(kept, 'a'), isNotNull);+ expect(p.of(gone, 'a'), isNull);+ p.want(gone, 'a', counter: 1, owner: screen);+ await settle();+ expect(reads(fake, 'a'), 4, reason: 'read again from nothing');+ });++ test('an answer for a reader taken off the list is dropped', () async {+ final fake = FakeSwarm();+ final gate = Completer<void>();+ fake.routes[path('a')] = (_) async {+ await gate.future;+ return page('a', [1]);+ };+ final r = reader(fake);+ final p = peeks();+ var told = 0;+ p.addListener(() => told++);++ p.want(r, 'a', counter: 1, owner: screen);+ await settle();+ p.keepOnly(const []);+ gate.complete();+ await settle();++ expect(p.held, 0);+ expect(p.of(r, 'a'), isNull);+ expect(told, 0);+ });++ test('says while a chat is being read, and not once it answers', () async {+ final fake = FakeSwarm();+ final gate = Completer<void>();+ fake.routes[path('a')] = (_) async {+ await gate.future;+ return page('a', [1]);+ };+ final r = reader(fake);+ final p = peeks();++ p.want(r, 'a', counter: 1, owner: screen);+ await settle();+ expect(p.busyAt(r, 'a'), isTrue);++ gate.complete();+ await settle();+ expect(p.busyAt(r, 'a'), isFalse);+ });++ test('Try again reads a chat that failed, past its tries', () async {+ final fake = FakeSwarm();+ fake.routes[path('a')] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ final r = reader(fake);+ final p = peeks();+ for (var i = 0; i < 3; i++) {+ p.want(r, 'a', counter: 1, owner: screen);+ await settle();+ }+ expect(reads(fake, 'a'), 3);++ fake.routes[path('a')] = (_) => page('a', [1]);+ p.retry(r, 'a', owner: screen);+ await settle();++ expect(reads(fake, 'a'), 4);+ expect(p.of(r, 'a'), isNotNull);+ expect(p.failedAt(r, 'a'), isFalse);+ });++ test('Try again leaves a chat that did not fail alone', () async {+ final fake = FakeSwarm();+ fake.routes[path('a')] = (_) => page('a', [1]);+ final r = reader(fake);+ final p = peeks();+ p.want(r, 'a', counter: 1, owner: screen);+ await settle();++ p.retry(r, 'a', owner: screen);+ await settle();++ expect(reads(fake, 'a'), 1);+ });++ /// Routes [chats] to pages that answer one at a time, as each call's gate+ /// in the returned lists (per chat, in call order) completes.+ Map<String, List<Completer<void>>> gated(FakeSwarm fake, List<String> chats) {+ final gates = {for (final chat in chats) chat: <Completer<void>>[]};+ for (final chat in chats) {+ fake.routes[path(chat)] = (_) async {+ final gate = Completer<void>();+ gates[chat]!.add(gate);+ await gate.future;+ return page(chat, [gates[chat]!.length]);+ };+ }+ return gates;+ }++ group('a list that leaves', () {+ test('takes back what it still waits for: what is being read finishes, '+ 'nothing more starts, and on its return only what is still needed '+ 'is read', () async {+ final fake = FakeSwarm();+ final gates = gated(fake, ['a', 'b', 'c']);+ final r = reader(fake);+ final p = peeks();+ for (final chat in ['a', 'b', 'c']) {+ p.want(r, chat, counter: 1, owner: screen);+ }+ await settle();+ expect(fake.paths, [path('a'), path('b')]);++ p.withdraw(screen);+ gates['a']!.single.complete();+ gates['b']!.single.complete();+ await settle();++ expect(fake.paths, [path('a'), path('b')], reason: 'no third read');+ expect(p.of(r, 'a'), isNotNull, reason: 'a read in flight finishes');+ expect(p.busyAt(r, 'c'), isFalse);++ for (final chat in ['a', 'b', 'c']) {+ p.want(r, chat, counter: 1, owner: screen);+ }+ await settle();+ expect(fake.paths, [path('a'), path('b'), path('c')]);+ gates['c']!.single.complete();+ await settle();+ expect(p.of(r, 'c'), isNotNull);+ });++ test("leaves another list's reads alone, and a chat both want", () async {+ final fake = FakeSwarm();+ final gates = gated(fake, ['a', 'b', 'c', 'd']);+ final r = reader(fake);+ final p = peeks();+ final other = Object();+ p.want(r, 'a', counter: 1, owner: screen);+ p.want(r, 'b', counter: 1, owner: screen);+ p.want(r, 'c', counter: 1, owner: screen);+ p.want(r, 'c', counter: 1, owner: other);+ p.want(r, 'd', counter: 1, owner: screen);+ await settle();++ p.withdraw(screen);+ gates['a']!.single.complete();+ gates['b']!.single.complete();+ await settle();++ expect(fake.paths, [path('a'), path('b'), path('c')]);+ expect(p.busyAt(r, 'd'), isFalse);+ });++ test('a chat that left the queue unread keeps no claim of the list that '+ 'wanted it then, once that list leaves', () async {+ final fake = FakeSwarm();+ final gates = gated(fake, ['a', 'x', 'y']);+ final r = reader(fake);+ final p = peeks();+ final other = Object(), stays = Object();+ p.want(r, 'a', counter: 1, owner: screen);+ p.want(r, 'x', counter: 1, owner: stays);+ await settle();+ // a waits for counter 2, then is wanted at 1 again, which is being read.+ p.want(r, 'a', counter: 2, owner: screen);+ p.want(r, 'a', counter: 1, owner: screen);+ p.want(r, 'y', counter: 1, owner: stays);+ gates['a']!.single.complete();+ await settle();+ expect(fake.paths, [path('a'), path('x'), path('y')]);+ p.withdraw(screen);++ p.want(r, 'a', counter: 3, owner: other);+ p.withdraw(other);+ gates['x']!.single.complete();+ gates['y']!.single.complete();+ await settle();++ expect(reads(fake, 'a'), 1, reason: 'no list on screen wants it');+ });+ });++ group('one read per chat', () {+ test('a waiting chat whose counter moves again and again is read once, '+ 'at its latest counter, even when both slots free together', () async {+ final fake = FakeSwarm();+ final gates = gated(fake, ['a', 'b', 'c']);+ final r = reader(fake);+ final p = peeks();+ p.want(r, 'a', counter: 1, owner: screen);+ p.want(r, 'b', counter: 1, owner: screen);+ for (final counter in [1, 2, 3]) {+ p.want(r, 'c', counter: counter, after: counter - 1, owner: screen);+ }+ await settle();++ gates['a']!.single.complete();+ gates['b']!.single.complete();+ await settle();++ expect(+ [+ for (final call in fake.paths)+ if (call.startsWith(path('c'))) call,+ ],+ ['${path('c')}?after=2'],+ );+ });++ test('a counter that moves while its chat is being read: the next read '+ 'waits for that one, the older answer leaves it busy, and the newer '+ 'one is what shows', () async {+ final fake = FakeSwarm();+ final gates = gated(fake, ['a']);+ final r = reader(fake);+ final p = peeks();+ p.want(r, 'a', counter: 1, owner: screen);+ await settle();++ p.want(r, 'a', counter: 2, owner: screen);+ await settle();+ expect(reads(fake, 'a'), 1, reason: 'never two reads of one chat');++ gates['a']![0].complete();+ await settle();+ expect(reads(fake, 'a'), 2, reason: 'then one at the new counter');+ expect(p.busyAt(r, 'a'), isTrue, reason: 'the newer read is on its way');+ expect(p.of(r, 'a')!.messages.single.id, 'a-1');++ gates['a']![1].complete();+ await settle();+ expect(p.busyAt(r, 'a'), isFalse);+ expect(p.of(r, 'a')!.messages.single.id, 'a-2');+ p.want(r, 'a', counter: 2, owner: screen);+ await settle();+ expect(reads(fake, 'a'), 2, reason: 'read at its latest counter');+ });+ });+}diff --git a/mobile/test/swarm/swarm_home_test.dart b/mobile/test/swarm/swarm_home_test.dartindex 4599a1300..981c7e743 100644--- a/mobile/test/swarm/swarm_home_test.dart+++ b/mobile/test/swarm/swarm_home_test.dart@@ -13,7 +13,7 @@ import 'package:harness_mobile/swarm/swarm_drawer.dart';import 'package:harness_mobile/swarm/swarm_home_rows.dart';import 'package:harness_mobile/swarm/swarm_inbox.dart';import 'package:harness_mobile/swarm/swarm_leaderboard.dart';-import 'package:harness_mobile/swarm/swarm_needs_page.dart';+import 'package:harness_mobile/swarm/swarm_activity_page.dart';import 'package:harness_mobile/swarm/swarm_page.dart';import 'package:harness_mobile/swarm/swarm_project_page.dart';import 'package:harness_mobile/swarm/swarm_request.dart';@@ -272,6 +272,20 @@ void main() {await tester.pumpAndSettle();}+ /// Taps one of Activity's filters, scrolled into sight first.+ Future<void> filter(WidgetTester tester, String name) async {+ await tester.ensureVisible(key('swarm-activity-filter-$name'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-activity-filter-$name'));+ await tester.pumpAndSettle();+ }++ /// Opens Activity's row [item] in full.+ Future<void> openRow(WidgetTester tester, String item) async {+ await tester.tap(key('swarm-activity-row-$item'));+ await tester.pumpAndSettle();+ }+/// Mobile's chats in [backend].const mobileChats = [leadChat,@@ -469,24 +483,36 @@ void main() {await tester.tap(key('swarm-home-need-mention:m1'));await tester.pumpAndSettle();- expect(find.byType(SwarmNeedsPage), findsOneWidget);- expect(key('swarm-done-m1'), findsOneWidget, reason: 'open there');+ expect(find.byType(SwarmActivityPage), findsOneWidget);+ expect(+ key('swarm-done-m1'),+ findsOneWidget,+ reason: 'open there, under @',+ );expect(key('swarm-option-d1-0'), findsNothing);- expect(key('swarm-need-row-decision:d1'), findsOneWidget);+ expect(+ key('swarm-activity-row-decision:d1'),+ findsNothing,+ reason: 'a decision is under Needs you, not @',+ );});- testWidgets('See all lists every need, the first open', (tester) async {+ testWidgets('See all opens Activity on Needs you, a row for each need, '+ 'none open; a tag is under @', (tester) async {await pump(tester, backend());await openNeeds(tester);- expect(find.text('Needs you'), findsOneWidget);- expect(key('swarm-option-d1-0'), findsOneWidget);- expect(key('swarm-need-row-mention:m1'), findsOneWidget);+ expect(find.byType(SwarmActivityPage), findsOneWidget);+ expect(key('swarm-activity-row-decision:d1'), findsOneWidget);expect(- key('swarm-need-row-work:$tab:g1:attempt-g1:needs_human'),+ key('swarm-activity-row-work:$tab:g1:attempt-g1:needs_human'),findsOneWidget,);+ expect(key('swarm-option-d1-0'), findsNothing, reason: 'a tap opens it');+ expect(key('swarm-activity-row-mention:m1'), findsNothing);+ await filter(tester, 'mentions');+ expect(key('swarm-activity-row-mention:m1'), findsOneWidget);await tester.tap(key('tty-back'));await tester.pumpAndSettle();expect(key('swarm-menu'), findsOneWidget);@@ -682,6 +708,7 @@ void main() {(tester) async {await pump(tester, backend());await openNeeds(tester);+ await openRow(tester, 'decision:d1');const card = 'swarm-need-decision:d1';expect(@@ -723,6 +750,7 @@ void main() {'16 points in, its glyph level with the first line', (tester) async {await pump(tester, backend());await openNeeds(tester);+ await openRow(tester, 'decision:d1');const card = 'swarm-need-decision:d1';final title = find.descendant(@@ -758,8 +786,8 @@ void main() {'Open chat', (tester) async {await pump(tester, backend());await openNeeds(tester);- await tester.tap(key('swarm-need-row-mention:m1'));- await tester.pumpAndSettle();+ await filter(tester, 'mentions');+ await openRow(tester, 'mention:m1');expect(tester.widget<SwarmButton>(key('swarm-done-m1')).style,@@ -773,18 +801,10 @@ void main() {inside('swarm-need-mention:m1', find.byIcon(LucideIcons.atSign300)),findsOneWidget,);- expect(- inside(- 'swarm-need-row-decision:d1',- find.byIcon(LucideIcons.circleQuestionMark300),- ),- findsOneWidget,- reason: 'a closed need keeps its glyph',- );const work = 'work:$tab:g1:attempt-g1:needs_human';- await tester.tap(key('swarm-need-row-$work'));- await tester.pumpAndSettle();+ await filter(tester, 'needsYou');+ await openRow(tester, work);await tester.tap(key('swarm-need-chat-$work'));await tester.pumpAndSettle();final page = tester.widget<SwarmConversationPage>(@@ -793,33 +813,26 @@ void main() {expect((page.swarmId, page.conversationId), (tab, 'g1'));});- testWidgets('Needs you opens one thing at a time; a line opens the next', (- tester,- ) async {+ testWidgets('Activity opens one need at a time; a row tapped opens and '+ 'the open one closes to its row', (tester) async {await pump(tester, backend());await openNeeds(tester);+ const work = 'work:$tab:g1:attempt-g1:needs_human';+ await openRow(tester, 'decision:d1');expect(key('swarm-option-d1-0'), findsOneWidget);- expect(key('swarm-done-m1'), findsNothing);- expect(key('swarm-need-row-mention:m1'), findsOneWidget);- expect(- key('swarm-need-row-work:$tab:g1:attempt-g1:needs_human'),- findsOneWidget,- );- expect(find.text('River tagged you'), findsOneWidget);- expect(find.text('Nova needs you'), findsOneWidget);-- await tester.tap(key('swarm-need-row-mention:m1'));- await tester.pumpAndSettle();+ expect(key('swarm-activity-row-decision:d1'), findsNothing);+ expect(key('swarm-activity-row-$work'), findsOneWidget);- expect(key('swarm-done-m1'), findsOneWidget);+ await openRow(tester, work);+ expect(key('swarm-need-chat-$work'), findsOneWidget);expect(key('swarm-option-d1-0'), findsNothing);- expect(key('swarm-need-row-decision:d1'), findsOneWidget);- expect(find.text('River asks you'), findsOneWidget);+ expect(key('swarm-activity-row-decision:d1'), findsOneWidget);+ expect(key('swarm-activity-approve-decision:d1'), findsOneWidget);});- testWidgets('one tap answers, held for Undo, said on Home too; then the '- 'next need opens', (tester) async {+ testWidgets('one tap answers, held for Undo, said on Home too; then its '+ 'row stays, marked Answered', (tester) async {final fake = backend();var answered = false;fake.routes['/api/super-tabs/$tab/commands'] = (body) {@@ -831,6 +844,7 @@ void main() {answered ? {'decisions': <Object>[]} : open(body);await pump(tester, fake);await openNeeds(tester);+ await openRow(tester, 'decision:d1');await tester.tap(key('swarm-option-d1-0'));await tester.pump();@@ -862,7 +876,11 @@ void main() {'choice': 0,});expect(key('swarm-need-decision:d1'), findsNothing);- expect(key('swarm-done-m1'), findsOneWidget, reason: 'the tag is next');+ expect(+ inside('swarm-activity-handled-decision:d1', find.text('Answered')),+ findsOneWidget,+ reason: 'what was done, on its row',+ );});testWidgets('Done marks a tag done', (tester) async {diff --git a/mobile/test/swarm/swarm_screens_test.dart b/mobile/test/swarm/swarm_screens_test.dartindex 51680991f..3d0ea6d9a 100644--- a/mobile/test/swarm/swarm_screens_test.dart+++ b/mobile/test/swarm/swarm_screens_test.dart@@ -9,7 +9,7 @@ import 'package:harness_mobile/shared/widgets/skeleton.dart';import 'package:harness_mobile/swarm/swarm_conversation_page.dart';import 'package:harness_mobile/swarm/swarm_mark.dart';import 'package:harness_mobile/swarm/swarm_home_rows.dart';-import 'package:harness_mobile/swarm/swarm_needs_page.dart';+import 'package:harness_mobile/swarm/swarm_activity_page.dart';import 'package:harness_mobile/swarm/swarm_page.dart';import 'package:harness_mobile/swarm/swarm_project_page.dart';import 'package:harness_mobile/swarm/swarm_request.dart';@@ -260,7 +260,7 @@ void main() {tester,) async {final fake = backend();- await pump(tester, fake, const SwarmNeedsPage());+ await pump(tester, fake, const SwarmActivityPage(focus: 'decision:d1'));await tester.tap(key('swarm-option-d1-0'));await tester.pump();@@ -277,7 +277,11 @@ void main() {'again',(tester) async {final fake = backend();- final host = await pump(tester, fake, const SwarmNeedsPage());+ final host = await pump(+ tester,+ fake,+ const SwarmActivityPage(focus: 'decision:d1'),+ );await tester.tap(key('swarm-option-d1-0'));await tester.pump();expect(find.text('Sending “Yes”'), findsOneWidget);@@ -314,7 +318,7 @@ void main() {tester,) async {final fake = backend();- await pump(tester, fake, const SwarmNeedsPage());+ await pump(tester, fake, const SwarmActivityPage(focus: 'decision:d1'));await tester.tap(key('swarm-option-d1-1'));await tester.pump(const Duration(seconds: 2));@@ -337,7 +341,7 @@ void main() {fake.routes['/api/super-tabs/$tab/commands'] = (_) => lost? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.'): {'result': <String, dynamic>{}};- await pump(tester, fake, const SwarmNeedsPage());+ await pump(tester, fake, const SwarmActivityPage(focus: 'decision:d1'));await tester.tap(key('swarm-option-d1-1'));await tester.pump(const Duration(seconds: 4));@@ -362,9 +366,7 @@ void main() {testWidgets('a tag is marked done from its row', (tester) async {final fake = backend();- await pump(tester, fake, const SwarmNeedsPage());- await tester.tap(key('swarm-need-row-mention:m1'));- await tester.pumpAndSettle();+ await pump(tester, fake, const SwarmActivityPage(focus: 'mention:m1'));await tester.tap(key('swarm-done-m1'));await tester.pumpAndSettle();@@ -376,11 +378,9 @@ void main() {tester,) async {final fake = backend();- await pump(tester, fake, const SwarmNeedsPage());+ await pump(tester, fake, const SwarmActivityPage(focus: 'mention:m1'));final confirmed = Completer<Object?>();fake.routes['/api/super-tabs/$tab/commands'] = (_) => confirmed.future;- await tester.tap(key('swarm-need-row-mention:m1'));- await tester.pumpAndSettle();await tester.tap(key('swarm-done-m1'));await tester.pump();@@ -397,11 +397,9 @@ void main() {testWidgets('a Done that fails says so on its row', (tester) async {final fake = backend();- await pump(tester, fake, const SwarmNeedsPage());+ await pump(tester, fake, const SwarmActivityPage(focus: 'mention:m1'));fake.routes['/api/super-tabs/$tab/commands'] = (_) =>throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');- await tester.tap(key('swarm-need-row-mention:m1'));- await tester.pumpAndSettle();await tester.tap(key('swarm-done-m1'));await tester.pumpAndSettle();@@ -420,8 +418,10 @@ void main() {testWidgets('a need opens the conversation it was asked in', (tester,) async {- await pump(tester, backend(), const SwarmNeedsPage());- await tester.tap(find.text('Nova needs you'));+ await pump(tester, backend(), const SwarmActivityPage());+ await tester.tap(+ key('swarm-activity-row-work:$tab:g1:attempt-g1:needs_human'),+ );await tester.pumpAndSettle();expect(find.byType(SwarmConversationPage),@@ -442,9 +442,11 @@ void main() {testWidgets('a tag opens the conversation from its text too', (tester,) async {- await pump(tester, backend(), const SwarmNeedsPage());- await tester.tap(key('swarm-need-row-mention:m1'));- await tester.pumpAndSettle();+ await pump(+ tester,+ backend(),+ const SwarmActivityPage(focus: 'mention:m1'),+ );await tester.tap(find.textContaining('Can you check the copy?', findRichText: true),diff --git a/mobile/test/swarm/swarm_tabs_test.dart b/mobile/test/swarm/swarm_tabs_test.dartindex a94215ad5..b3d2098d0 100644--- a/mobile/test/swarm/swarm_tabs_test.dart+++ b/mobile/test/swarm/swarm_tabs_test.dart@@ -4,12 +4,14 @@ import 'package:harness_mobile/notify/system_notices.dart';import 'package:harness_mobile/phone/out_of_sight.dart';import 'package:harness_mobile/settings/experimental_features.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';-import 'package:harness_mobile/swarm/swarm_needs_page.dart';+import 'package:harness_mobile/swarm/swarm_activity_page.dart';+import 'package:harness_mobile/swarm/swarm_buddies_page.dart';import 'package:harness_mobile/swarm/swarm_page.dart';import 'package:harness_mobile/swarm/swarm_session.dart';import 'package:harness_mobile/swarm/swarm_tabs.dart';import '../voice_fakes.dart';+import 'swarm_buddies_fixture.dart';import 'swarm_fixture.dart';/// A tab's screen that says which it is, whether it is out of sight, and how@@ -156,6 +158,7 @@ void main() {request: fake.request,notices: notices,features: features,+ readMarks: MemoryKeyValueStore(),)..foreground = false;addTearDown(host.dispose);await tester.pumpWidget(@@ -176,11 +179,11 @@ void main() {Finder said(String text) => find.text(text, skipOffstage: false);- testWidgets('the bar reads Home, Activity and You, and opens on Swarm '- 'Home; Buddies waits for its screen', (tester) async {+ testWidgets('the bar reads Home, Buddies, Activity and You, and opens on '+ 'Swarm Home', (tester) async {await pump(tester, _tabs);- const shown = [SwarmTab.home, SwarmTab.activity, SwarmTab.you];+ const shown = SwarmTab.values;final xs = [for (final tab in shown) tester.getCenter(tabOf(tab)).dx];expect([...xs]..sort(), xs, reason: 'left to right in this order');for (final tab in shown) {@@ -189,7 +192,6 @@ void main() {findsOneWidget,);}- expect(tabOf(SwarmTab.buddies), findsNothing);expect(find.text('Coming soon.', skipOffstage: false), findsNothing);expect(find.byType(SwarmPage), findsOneWidget);// The open tab's name in the main ink, bold; the others quiet.@@ -400,7 +402,7 @@ void main() {);});- testWidgets('Activity opens Needs you, as a tab with no way back, and '+ testWidgets('Activity opens Activity, as a tab with no way back, and ''counts what waits on the person', (tester) async {await pump(tester, _tabs, fake: _asking());final badge = find.byKey(const ValueKey('swarm-tab-badge-activity'));@@ -411,15 +413,71 @@ void main() {await open(tester, SwarmTab.activity);- expect(find.byType(SwarmNeedsPage), findsOneWidget);+ expect(find.byType(SwarmActivityView), findsOneWidget);expect(tester.widget<Text>(find.byKey(const ValueKey('swarm-title'))).data,- 'Needs you',+ 'Activity',);expect(find.byKey(const ValueKey('tty-back')), findsNothing);expect(find.text('Ship it?'), findsOneWidget);});+ testWidgets('Buddies opens Buddies, as a tab with no way back, and counts '+ 'the Buddy chats with something unread', (tester) async {+ await pump(tester, _tabs, fake: buddiesBackend());+ final badge = find.byKey(const ValueKey('swarm-tab-badge-buddies'));+ expect(+ find.descendant(of: badge, matching: find.text('1')),+ findsOneWidget,+ );++ await open(tester, SwarmTab.buddies);++ expect(find.byType(SwarmBuddiesView), findsOneWidget);+ expect(+ tester.widget<Text>(find.byKey(const ValueKey('swarm-title'))).data,+ 'Buddies',+ );+ expect(find.byKey(const ValueKey('tty-back')), findsNothing);+ expect(find.text('Done: the build is up.'), findsOneWidget);+ });++ testWidgets('Buddies reads its chats only while its tab is open', (+ tester,+ ) async {+ final fake = buddiesBackend();+ int reads() => fake.paths.where((p) => p.contains('/messages')).length;+ await pump(tester, _tabs, fake: fake);+ expect(reads(), 0, reason: 'its count needs no chat read');++ await open(tester, SwarmTab.buddies);+ expect(reads(), 2);++ await open(tester, SwarmTab.home);+ expect(host.session!.buddyList.shown, isFalse);+ // A new message in the Buddy chat while Buddies is out of sight.+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part(+ buddiesMobileChat,+ 30,+ buddyChatData(+ buddiesMobileChat,+ agentIds: ['agent-wren'],+ lastMessageSequence: 9,+ ),+ ),+ ],+ );+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();+ expect(reads(), 2, reason: 'out of sight, nothing is read');++ await open(tester, SwarmTab.buddies);+ expect(reads(), 3);+ });+testWidgets('You opens the phone\'s Settings', (tester) async {await pump(tester, _tabs);@@ -428,7 +486,7 @@ void main() {expect(find.text('the settings'), findsOneWidget);});- testWidgets('Needs you open on Activity mutes the notices it shows, and '+ testWidgets('Activity open mutes the notices it shows, and ''out of sight under Harness mutes none', (tester) async {final hidden = ValueNotifier(false);await pump(