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: Activity read from the server, as Desktop (Tony, task 8a) (#2475)
harness-for-autonomous[bot]9560294f7ca8
diff --git a/mobile/lib/swarm/swarm_activity.dart b/mobile/lib/swarm/swarm_activity.dartindex ac539fab2..427954a26 100644--- a/mobile/lib/swarm/swarm_activity.dart+++ b/mobile/lib/swarm/swarm_activity.dart@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';import '../core/local_key_value_store.dart';import 'model.dart';+import 'swarm_activity_feed.dart';import 'swarm_chat_peeks.dart';import 'swarm_inbox.dart';import 'swarm_reader.dart';@@ -24,6 +25,10 @@ enum SwarmActivityFilter {/// Others' reactions to what the person wrote.reactions('Reactions');+ /// What [threads] is called once the server lists replies to the person+ /// ([SwarmActivityFeed]), as Desktop calls it.+ static const repliesLabel = 'Replies';+const SwarmActivityFilter(this.label);final String label;}@@ -95,6 +100,9 @@ bool swarmActivityItemIn(SwarmActivityNeed(need: SwarmWorkNeed(:final work)) => work.project.id,SwarmActivityThread(:final project) => project.id,SwarmActivityReaction(:final project) => project.id,+ // A server row names no project of its own: its chat's, as read here.+ SwarmActivityServerItem(:final conversationId) =>+ snapshot.conversation(conversationId)?.projectId,};return named == projectId &&snapshot.conversation(item.conversationId)?.projectId == projectId;@@ -132,6 +140,31 @@ class SwarmActivityThread extends SwarmActivityItem {DateTime? get at => thread.lastAt;}+/// A reply to the person's message or a reaction to it, as the server lists+/// it ([SwarmActivityFeed]): under Threads (called Replies) or Reactions.+class SwarmActivityServerItem extends SwarmActivityItem {+ const SwarmActivityServerItem(super.swarmId, this.entry);+ final SwarmActivityEntry entry;++ @override+ String get key => 'activity:$swarmId:${entry.id}';++ @override+ SwarmActivityFilter get filter => entry.kind == SwarmActivityKind.reply+ ? SwarmActivityFilter.threads+ : SwarmActivityFilter.reactions;++ @override+ String get conversationId => entry.conversationId;++ /// A reply that lives only in its thread opens at the thread.+ @override+ String? get messageId => entry.threadId ?? entry.messageId;++ @override+ DateTime? get at => entry.createdAt;+}+/// Others' reactions to one of the person's messages in a project chat.class SwarmActivityReaction extends SwarmActivityItem {const SwarmActivityReaction(@@ -172,11 +205,18 @@ class SwarmActivityReaction extends SwarmActivityItem {}/// 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.+/// brief 10-30): what the Swarms ask of the person (Needs you, @), the replies+/// and reactions to what they wrote, each filter counted, and the needs they+/// acted on kept as handled.+///+/// Needs you and @ are the inbox's, read already. Replies and Reactions are+/// the server's, as Desktop reads them ([SwarmActivityFeed], #2453): unread+/// in bold, and read on every device once Activity is left — only those+/// Activity had open. The badge counts what Desktop's does: decisions and+/// tags waiting, and replies unread.///-/// Needs you and @ are the inbox's, read already. Threads and Reactions come+/// From a server before Activity (no digest, or 404), that Swarm's rows are+/// built on the phone as before: 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@@ -221,9 +261,16 @@ class SwarmActivity extends ChangeNotifier {/// Needs acted on here that left the inbox, newest last.final _gone = <String, ({SwarmActivityNeed item, String word})>{};- /// Each listed Swarm's handled marks.+ /// Each listed Swarm's handled marks, while its server has no Activity.final _marks = <String, _SwarmMarks>{};+ /// Each listed Swarm's replies and reactions from the server.+ final _feeds = <String, SwarmActivityFeed>{};++ /// The server rows each Swarm's Activity had open in this visit, by id:+ /// what is marked read when it is left.+ final _shownRows = <String, Set<String>>{};+Map<SwarmActivityFilter, List<SwarmActivityItem>>? _built;/// Screens showing Activity ([watch]): while there is one, the project@@ -234,13 +281,36 @@ class SwarmActivity extends ChangeNotifier {/// A screen shows Activity: its chats are read as their counters move.void watch() {if (_disposed || _views++ > 0) return;+ _shownRows.clear();+ for (final feed in _feeds.values) {+ feed.opened();+ }_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]).+ /// waiting their turn for it are not read ([SwarmChatPeeks.withdraw]), and+ /// the server rows it had open are read on every device.void unwatch() {- if (_views > 0 && --_views == 0) session.peeks.withdraw(this);+ if (_views > 0 && --_views == 0) {+ session.peeks.withdraw(this);+ if (_disposed) return;+ for (final MapEntry(key: id, value: feed) in _feeds.entries) {+ feed.closed({...?_shownRows[id]});+ }+ _shownRows.clear();+ }+ }++ /// A screen showing Activity has [items] open: their server rows are read+ /// once it is left ([unwatch]). Nothing is kept while none is in sight.+ void showing(Iterable<SwarmActivityItem> items) {+ if (_disposed || !shown) return;+ for (final item in items) {+ if (item is SwarmActivityServerItem) {+ (_shownRows[item.swarmId] ??= {}).add(item.entry.id);+ }+ }}/// The rows of [filter]: those still to handle, newest first, then the@@ -248,29 +318,91 @@ class SwarmActivity extends ChangeNotifier {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 rows of [filter] still to handle, or unread.+ int count(SwarmActivityFilter filter) => items(filter).where(waiting).length;- /// The tab's badge, as the prototype draws it: what needs the person.- int get badge => count(SwarmActivityFilter.needsYou);+ /// Whether [item] counts in its filter's number: a server row while it is+ /// unread on every device, any other while it is still to handle.+ bool waiting(SwarmActivityItem item) => switch (item) {+ SwarmActivityServerItem(:final entry) => !entry.read,+ _ => handled(item) == null,+ };- /// Some project chat could not be read at its last change.- bool get unreadChats => _anyChat(session.peeks.failedAt);+ /// Whether [item] shows bold: a server row unread, or unread when this+ /// visit began; any other while it is still to handle.+ bool unread(SwarmActivityItem item) => switch (item) {+ SwarmActivityServerItem(:final entry) =>+ _feeds[item.swarmId]?.isUnread(entry) ?? false,+ _ => handled(item) == null,+ };++ /// What [filter] is called: Threads is Replies once a server lists them.+ String label(SwarmActivityFilter filter) =>+ filter == SwarmActivityFilter.threads && repliesFromServer+ ? SwarmActivityFilter.repliesLabel+ : filter.label;++ /// Some listed Swarm's replies and reactions come from its server.+ bool get repliesFromServer => _feeds.values.any((feed) => feed.fromServer);++ /// The tab's badge, as Desktop counts its Activity: each Swarm's decisions+ /// and tags waiting, and the replies to the person not read on any device.+ /// A Swarm whose server has no Activity counts what needs the person, as+ /// before.+ int get badge {+ var count = 0;+ final before = <String>{};+ for (final swarm in inbox.swarms) {+ final reader = inbox.reader(swarm.id);+ final snapshot = reader?.snapshot;+ if (reader == null || reader.accessRevoked || snapshot == null) continue;+ final feed = _feeds[swarm.id];+ if (feed != null && feed.fromServer) {+ count +=+ snapshot.decisionsWaiting ++ snapshot.mentionsWaiting ++ feed.unreadReplies;+ } else {+ before.add(swarm.id);+ }+ }+ if (before.isEmpty) return count;+ return count ++ items(SwarmActivityFilter.needsYou)+ .where((item) => before.contains(item.swarmId) && waiting(item))+ .length;+ }++ /// Some project chat could not be read at its last change, or some+ /// Swarm's Activity could not be read from its server.+ bool get unreadChats =>+ _anyChat(session.peeks.failedAt) ||+ _feeds.values.any((feed) => feed.fromServer && feed.error != null);/// 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,- );+ /// nothing of it read yet, or a Swarm's Activity is read from its server+ /// for the first time: Replies and Reactions may still fill.+ bool get reading =>+ _feeds.values.any(+ (feed) => feed.fromServer && !feed.loaded && feed.error == null,+ ) ||+ _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;- });+ /// The person's Try again: the project chats that failed are read again,+ /// and each Swarm's Activity that failed.+ void retry() {+ for (final feed in _feeds.values) {+ if (feed.fromServer && feed.error != null) feed.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) {@@ -317,6 +449,10 @@ class SwarmActivity extends ChangeNotifier {case SwarmActivityReaction():final seen = _marks[item.swarmId]?.values['r:${item.message.id}'];return seen == item.signature ? 'Seen' : null;+ // Read or not, a server row is never handled here: its server says+ // whether it is read ([unread]).+ case SwarmActivityServerItem():+ return null;}}@@ -369,6 +505,9 @@ class SwarmActivity extends ChangeNotifier {?.markThreadRead(item.chatId, thread.id, thread.lastSequence);case SwarmActivityReaction():_marks[item.swarmId]?.put('r:${item.message.id}', item.signature);+ // Read on every device once Activity is left, as on Desktop.+ case SwarmActivityServerItem():+ return;}_built = null;notifyListeners();@@ -378,10 +517,12 @@ class SwarmActivity extends ChangeNotifier {inbox.needs.any((need) => need.key == item.key);/// Each project chat [reader] holds, with its project: never a Buddy chat.+ /// None while its server lists Activity: nothing of them is read then.Iterable<({SuperTabProject project, SuperTabConversation chat})>_projectChats(SwarmReader reader) sync* {final snapshot = reader.snapshot;if (snapshot == null || reader.accessRevoked) return;+ if (_feeds[reader.tabId]?.fromServer ?? false) return;for (final project in snapshot.projects) {final chat = snapshot.conversation(project.leadConversationId);if (chat == null || chat.isBuddyChat) continue;@@ -408,14 +549,27 @@ class SwarmActivity extends ChangeNotifier {}/// 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.+ /// phone and its handled rows with it, and its server rows; one newly+ /// listed reads its marks and its server's Activity. Once its server has+ /// answered Activity, the marks kept on the phone for it go: the server+ /// keeps what is read.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: feed) in _feeds.entries.toList()) {+ if (gone(id) || !identical(inbox.reader(id), feed.reader)) {+ _feeds.remove(id)!+ ..removeListener(_changed)+ ..dispose();+ _shownRows.remove(id);+ }+ }for (final MapEntry(key: id, value: marks) in _marks.entries.toList()) {- if (gone(id) || !identical(inbox.reader(id), marks.reader)) {+ if (gone(id) ||+ !identical(inbox.reader(id), marks.reader) ||+ _answered(id)) {_marks.remove(id)!.forget();}}@@ -423,13 +577,24 @@ class SwarmActivity extends ChangeNotifier {_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;+ if (reader == null || reader.accessRevoked) continue;+ if (!_feeds.containsKey(id)) {+ final feed = _feeds[id] = SwarmActivityFeed(reader);+ if (shown) feed.opened();+ feed.addListener(_changed);}+ if (_marks.containsKey(id) || _answered(id)) continue;_marks[id] = _SwarmMarks(reader, store, accountId, onLoaded: _changed);}}+ /// Swarm [id]'s server has listed its Activity: what is read is kept+ /// there, not on the phone.+ bool _answered(String id) => switch (_feeds[id]) {+ final feed? => feed.fromServer && feed.loaded && feed.error == null,+ null => false,+ };+bool _held(String key) => inbox.needs.any((need) =>need.key == key &&@@ -542,6 +707,12 @@ class SwarmActivity extends ChangeNotifier {for (final swarm in inbox.swarms) {final reader = inbox.reader(swarm.id);if (reader == null) continue;+ if (_feeds[swarm.id] case final feed? when feed.fromServer) {+ for (final entry in feed.items) {+ final item = SwarmActivityServerItem(swarm.id, entry);+ rows[item.filter]!.add(item);+ }+ }for (final (:project, :chat) in _projectChats(reader)) {final peek = session.peeks.of(reader, chat.id);if (peek == null) continue;@@ -630,6 +801,14 @@ class SwarmActivity extends ChangeNotifier {session.peeks.removeListener(_changed);// Closing keeps the marks on the phone for the next session._marks.clear();+ // An answer on its way belongs to the session that is gone.+ for (final feed in _feeds.values) {+ feed+ ..removeListener(_changed)+ ..dispose();+ }+ _feeds.clear();+ _shownRows.clear();super.dispose();}}diff --git a/mobile/lib/swarm/swarm_activity_feed.dart b/mobile/lib/swarm/swarm_activity_feed.dartnew file mode 100644index 000000000..fa0858f2b--- /dev/null+++ b/mobile/lib/swarm/swarm_activity_feed.dart@@ -0,0 +1,372 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import 'model.dart';+import 'swarm_reader.dart';+import 'swarm_request.dart';++/// What a server Activity row is: a reply to the person's message, or a+/// reaction to it (backend superTabs/activity.ts).+enum SwarmActivityKind { reply, reaction }++/// One reply to the person's message, or one reaction to it, as the server+/// lists it: the desktop's `SuperTabActivityItem`.+class SwarmActivityEntry {+ SwarmActivityEntry.fromJson(Map<String, dynamic> row)+ : id = row['id'] as String,+ kind = row['kind'] == 'reaction'+ ? SwarmActivityKind.reaction+ : SwarmActivityKind.reply,+ conversationId = row['conversationId'] as String,+ messageId = row['messageId'] as String,+ threadId = row['threadId'] as String?,+ actorKind = switch (row['actor']) {+ {'kind': 'person'} => 'person',+ _ => 'agent',+ },+ actorId = switch (row['actor']) {+ {'id': final String id} => id,+ _ => '',+ },+ actorName = switch (row['actor']) {+ {'name': final String name} => name,+ _ => '',+ },+ emoji = row['emoji'] as String?,+ text = row['text'] as String? ?? '',+ createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),+ read = row['read'] == true;++ SwarmActivityEntry._read(SwarmActivityEntry e)+ : id = e.id,+ kind = e.kind,+ conversationId = e.conversationId,+ messageId = e.messageId,+ threadId = e.threadId,+ actorKind = e.actorKind,+ actorId = e.actorId,+ actorName = e.actorName,+ emoji = e.emoji,+ text = e.text,+ createdAt = e.createdAt,+ read = true;++ final String id, conversationId, messageId;+ final SwarmActivityKind kind;++ /// The thread a reply that lives only there is in; null in the main stream.+ final String? threadId;++ /// Who replied or reacted: `person` or `agent`, its id, and the server's+ /// name for it — used only for an agent the Swarm no longer lists.+ final String actorKind, actorId, actorName;++ /// The reaction (`thumbs_up`, `check`, …); null for a reply.+ final String? emoji;++ /// The reply's text, or the reacted message's.+ final String text;+ final DateTime? createdAt;++ /// Read on some device ([SwarmActivityFeed.markShownRead]).+ final bool read;+}++/// One Swarm's replies and reactions to the person, read from the server+/// (`/activity`, #2453) as Desktop's `SuperTabActivity` reads them: when the+/// Swarm's Activity digest moves or Activity opens, never on a timer; marked+/// read on every device (`/activity/read`) once Activity is left.+///+/// A server before Activity sends no digest, or answers 404: [fromServer] is+/// false, and Activity builds this Swarm's rows on the phone as before.+///+/// Rows show only for chats [reader] holds: a chat the person lost since is+/// not shown on the server's word alone. A read asked before access moved+/// ([SwarmReader.generation]), before the person left, or before a newer+/// read answered changes nothing.+class SwarmActivityFeed extends ChangeNotifier {+ SwarmActivityFeed(this.reader) {+ reader.addListener(_changed);+ _changed();+ }++ final SwarmReader reader;++ /// Replies and reactions, newest first, in chats [reader] holds.+ List<SwarmActivityEntry> items = const [];++ /// Read once since access last moved; [error] says whether it failed.+ bool loaded = false;++ /// The server had older rows than it listed.+ bool more = false;+ String? error;++ /// The server answered 404 to the list: it has no Activity.+ bool _refused = false;++ /// Rows unread when Activity opened, or that came in while it was open:+ /// bold until it is left, though another device read them meanwhile.+ final _newThisVisit = <String>{};+ bool _open = false;++ String? _digest, _failedDigest;+ int? _generation;+ Future<void>? _loading;+ bool _dirty = false, _disposed = false;+ int _asked = 0, _shown = 0;+ DateTime? _waitUntil;+ Timer? _retry;++ /// How long a refused-for-load read waits before its one try more.+ static const busyWait = Duration(seconds: 5);++ String get _path =>+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/activity';++ /// This Swarm's replies and reactions come from the server: it sends an+ /// Activity digest and has not answered 404.+ bool get fromServer =>+ !_refused &&+ !reader.accessRevoked &&+ reader.snapshot?.activityDigest != null;++ /// Whether [entry] shows bold.+ bool isUnread(SwarmActivityEntry entry) =>+ !entry.read || _newThisVisit.contains(entry.id);++ /// Replies not read on any device: what the Activity badge adds.+ int get unreadReplies =>+ items.where((e) => e.kind == SwarmActivityKind.reply && !e.read).length;++ /// Activity is in sight: reads now; what is unread stays bold until+ /// [closed].+ void opened() {+ if (_disposed) return;+ _open = true;+ _newThisVisit+ ..clear()+ ..addAll(items.where((e) => !e.read).map((e) => e.id));+ if (fromServer) unawaited(load());+ }++ /// Activity was left: the rows of [shown] (ids) are read on every device,+ /// as far as no unread row it did not show comes before them.+ void closed(Set<String> shown) {+ if (!_open || _disposed) return;+ _open = false;+ _newThisVisit.clear();+ // The screen is going away while this runs (its dispose): what listens+ // is told after the frame's teardown, never during it.+ scheduleMicrotask(() {+ if (_disposed) return;+ unawaited(markShownRead(shown));+ notifyListeners();+ });+ }++ /// Marks read, on every device, the unread rows up to the newest moment+ /// before which every unread row is in [shown]: the server marks by time+ /// (`through`), and a row the person never had in front of them must not+ /// go read with the others.+ @visibleForTesting+ Future<void> markShownRead(Set<String> shown) async {+ if (!fromServer || _disposed) return;+ final unread = [+ for (final e in items)+ if (!e.read && e.createdAt != null) e,+ ]..sort((a, b) => a.createdAt!.compareTo(b.createdAt!));+ DateTime? through;+ for (var i = 0; i < unread.length; i++) {+ if (!shown.contains(unread[i].id)) break;+ final at = unread[i].createdAt!;+ // A row at the same moment that was not shown holds this one back too.+ final tie = unread.skip(i + 1).takeWhile((e) => e.createdAt == at);+ if (tie.any((e) => !shown.contains(e.id))) break;+ through = at;+ }+ // An undated row the server holds would go read with no time to say so.+ if (through == null) return;+ final generation = reader.generation;+ items = [+ for (final e in items)+ if (!e.read && e.createdAt != null && !e.createdAt!.isAfter(through))+ SwarmActivityEntry._read(e)+ else+ e,+ ];+ notifyListeners();+ try {+ await reader.request(+ 'POST',+ '$_path/read',+ body: {'through': through.toUtc().toIso8601String()},+ );+ } catch (_) {+ // Unread again as the server still has it: read once more now.+ if (!_disposed && reader.generation == generation) {+ _digest = null;+ unawaited(load());+ }+ }+ }++ /// The person's Try again.+ void retry() {+ _failedDigest = null;+ _waitUntil = null;+ unawaited(load());+ }++ void _clear() {+ items = const [];+ loaded = false;+ more = false;+ error = null;+ _newThisVisit.clear();+ _retry?.cancel();+ _retry = null;+ // An answer on its way belongs to what was held before.+ _shown = ++_asked;+ _digest = _failedDigest = null;+ }++ void _changed() {+ if (_disposed) return;+ if (reader.accessRevoked) {+ if (loaded || items.isNotEmpty || error != null || _loading != null) {+ _clear();+ notifyListeners();+ }+ return;+ }+ final snapshot = reader.snapshot;+ if (snapshot == null) return;+ if (_generation != reader.generation) {+ final moved = _generation != null;+ _generation = reader.generation;+ // Read again from nothing: what was read before shows no more until+ // read again.+ if (moved && (loaded || items.isNotEmpty)) {+ _clear();+ notifyListeners();+ }+ }+ // Rows of a chat the reader no longer holds go at once.+ final held = items+ .where((e) => snapshot.conversation(e.conversationId) != null)+ .toList();+ if (held.length != items.length) {+ items = List.unmodifiable(held);+ notifyListeners();+ }+ final digest = snapshot.activityDigest;+ if (digest == null || _refused) return;+ if (digest == _digest && loaded) return;+ // A read that failed is tried again when the digest moves, or by the+ // person's Try again: not at every read of the Swarm.+ if (digest == _failedDigest) return;+ _digest = digest;+ unawaited(load());+ }++ /// Joins a read under way, and has it read once more when asked again.+ Future<void> load() {+ if (_disposed || _refused) return Future.value();+ if (_loading case final running?) {+ _dirty = true;+ return running;+ }+ return _loading = () async {+ do {+ _dirty = false;+ await _read();+ } while (_dirty && !_disposed);+ }().whenComplete(() => _loading = null);+ }++ Future<void> _read() async {+ if (reader.accessRevoked || reader.snapshot == null) return;+ if (_waitUntil case final wait? when DateTime.now().isBefore(wait)) {+ // Asked too often: one read when the wait is over, no more.+ _retry ??= Timer(wait.difference(DateTime.now()), () {+ _retry = null;+ unawaited(load());+ });+ return;+ }+ final asked = ++_asked;+ final generation = reader.generation;+ final digest = reader.snapshot?.activityDigest;+ bool current() =>+ !_disposed &&+ !reader.accessRevoked &&+ asked > _shown &&+ reader.generation == generation;+ try {+ final answer = superTabMap(await reader.request('GET', _path));+ if (!current()) return;+ _shown = asked;+ final snapshot = reader.snapshot;+ final read = <SwarmActivityEntry>[];+ for (final row in answer['items'] as List? ?? const []) {+ final SwarmActivityEntry entry;+ try {+ entry = SwarmActivityEntry.fromJson(superTabMap(row));+ } catch (_) {+ // A row this build cannot read is left out, not the list.+ continue;+ }+ // Only chats this reader holds; a chat lost since is not shown on+ // the server's word alone.+ if (snapshot?.conversation(entry.conversationId) == null) continue;+ read.add(entry);+ }+ items = List.unmodifiable(read);+ more = answer['more'] == true;+ loaded = true;+ error = null;+ _failedDigest = null;+ _waitUntil = null;+ if (_open) {+ _newThisVisit.addAll(items.where((e) => !e.read).map((e) => e.id));+ }+ notifyListeners();+ } catch (failure) {+ if (!current()) return;+ _shown = asked;+ if (failure is SuperTabFailure && failure.statusCode == 404) {+ // A server before Activity: the phone builds these rows itself.+ _refused = true;+ items = const [];+ loaded = true;+ error = null;+ notifyListeners();+ return;+ }+ if (failure is SuperTabFailure && failure.statusCode == 429) {+ _waitUntil = DateTime.now().add(busyWait);+ // One read when the wait is over.+ _retry ??= Timer(busyWait, () {+ _retry = null;+ unawaited(load());+ });+ }+ _digest = null;+ _failedDigest = digest;+ loaded = true;+ error = 'Could not load activity.';+ notifyListeners();+ }+ }++ @override+ void dispose() {+ if (_disposed) return;+ _disposed = true;+ _retry?.cancel();+ reader.removeListener(_changed);+ super.dispose();+ }+}diff --git a/mobile/lib/swarm/swarm_activity_page.dart b/mobile/lib/swarm/swarm_activity_page.dartindex 58dfd77ab..f5e1cd0f4 100644--- a/mobile/lib/swarm/swarm_activity_page.dart+++ b/mobile/lib/swarm/swarm_activity_page.dart@@ -13,6 +13,7 @@ import 'package:harness_mobile/shared/theme/app_type.dart';import 'identity.dart';import 'model.dart';import 'swarm_activity.dart';+import 'swarm_activity_feed.dart';import 'swarm_asks.dart' show SwarmAsks;import 'swarm_home_rows.dart' show swarmNeedAsk;import 'swarm_inbox.dart';@@ -81,11 +82,13 @@ class SwarmActivityPage extends StatelessWidget {}/// 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.+/// terminal's face, the filters — Needs you · @ · Replies · Reactions (Threads+/// from a server before Activity) — 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 need the person handled stays, dimmed, under the+/// others; a reply or reaction is bold while unread. The rows shown are read+/// on every device once Activity is left ([SwarmActivity.showing]). 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.@@ -249,6 +252,8 @@ class _SwarmActivityViewState extends State<SwarmActivityView> {Widget _body(BuildContext context, SwarmSession session) {final activity = session.activity;final items = _items(session, _filter);+ // What is open here is what goes read once Activity is left.+ activity.showing(items);return Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [@@ -267,10 +272,8 @@ class _SwarmActivityViewState extends State<SwarmActivityView> {SwarmActivityFilterPill(key: ValueKey('swarm-activity-filter-${filter.name}'),filter: filter,- count: _items(- session,- filter,- ).where((item) => activity.handled(item) == null).length,+ label: activity.label(filter),+ count: _items(session, filter).where(activity.waiting).length,selected: filter == _filter,onTap: () => setState(() => _filter = filter),),@@ -361,7 +364,7 @@ class _SwarmActivityViewState extends State<SwarmActivityView> {vertical: AppSpace.s,),child: Text(- _nothing(_filter),+ _nothing(_filter, replies: activity.repliesFromServer),key: const ValueKey('swarm-activity-none'),style: note,),@@ -415,12 +418,15 @@ class _SwarmActivityViewState extends State<SwarmActivityView> {});}- 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.',- };+ static String _nothing(SwarmActivityFilter filter, {required bool replies}) =>+ switch (filter) {+ SwarmActivityFilter.needsYou => 'Nothing needs you.',+ SwarmActivityFilter.mentions => 'No one tagged you.',+ SwarmActivityFilter.threads when replies =>+ 'No replies to your messages yet.',+ SwarmActivityFilter.threads => 'No threads with you yet.',+ SwarmActivityFilter.reactions => 'No reactions to you yet.',+ };Widget _row(BuildContext context,@@ -456,6 +462,7 @@ class _SwarmActivityViewState extends State<SwarmActivityView> {session: session,item: item,handled: handled,+ unread: session.activity.unread(item),now: DateTime.now(),onTap: () => item is SwarmActivityNeed && handled == null? setState(() => _open = item.key)@@ -659,9 +666,13 @@ class SwarmActivityFilterPill extends StatelessWidget {required this.count,required this.selected,required this.onTap,+ this.label,});final SwarmActivityFilter filter;++ /// What it is called, when not [SwarmActivityFilter.label].+ final String? label;final int count;final bool selected;final VoidCallback onTap;@@ -670,9 +681,8 @@ class SwarmActivityFilterPill extends StatelessWidget {Widget build(BuildContext context) {AppTheme.watch(context);final ink = selected ? AppPalette.windowBg : AppPalette.textPrimary;- final heard = filter == SwarmActivityFilter.mentions- ? 'Mentions'- : filter.label;+ final name = label ?? filter.label;+ final heard = filter == SwarmActivityFilter.mentions ? 'Mentions' : name;return Semantics(button: true,selected: selected,@@ -694,7 +704,7 @@ class SwarmActivityFilterPill extends StatelessWidget {mainAxisSize: MainAxisSize.min,children: [Text(- filter.label,+ name,style: AppType.label(color: ink,fontWeight: AppFont.semibold,@@ -736,13 +746,17 @@ class SwarmActivityRow extends StatelessWidget {required this.onTap,required this.onApprove,required this.onReply,- });+ bool? unread,+ }) : unread = unread ?? handled == null;final SwarmSession session;final SwarmActivityItem item;/// What was done with it; null while it is still to handle.final String? handled;++ /// Bold: still to handle, or a reply or reaction not read.+ final bool unread;final DateTime now;final VoidCallback onTap, onApprove, onReply;@@ -782,9 +796,7 @@ class SwarmActivityRow extends StatelessWidget {overflow: TextOverflow.ellipsis,style: AppType.label(color: AppPalette.textPrimary,- fontWeight: handled == null- ? AppFont.semibold- : AppFont.regular,+ fontWeight: unread ? AppFont.semibold : AppFont.regular,height: 1.3,),),@@ -884,6 +896,15 @@ class SwarmActivityRow extends StatelessWidget {},SwarmActivityThread(:final project) => project.name,SwarmActivityReaction(:final project) => project.name,+ // The project as this Swarm's own read has the chat: never the server's+ // word for it.+ SwarmActivityServerItem(:final conversationId) =>+ session.inbox+ .reader(item.swarmId)+ ?.snapshot+ ?.projectFor(conversationId)+ ?.name ??+ '',};String _title() => switch (item) {@@ -893,9 +914,17 @@ class SwarmActivityRow extends StatelessWidget {_ => 'A thread in #${project.name}',},SwarmActivityReaction(:final message) => message.text.trim(),+ SwarmActivityServerItem(:final entry) => swarmActivityDid(+ entry,+ swarmActivityWho(item, session.inbox.reader(item.swarmId)).name,+ ),};String? _line() => switch (item) {+ SwarmActivityServerItem(:final entry) => switch (entry.text.trim()) {+ '' => null,+ final text => text,+ },SwarmActivityThread(:final thread) =>thread.replies == 1 ? '1 reply' : '${thread.replies} replies',SwarmActivityReaction(:final reactions) => [@@ -967,5 +996,27 @@ class SwarmActivityRow extends StatelessWidget {: '${names.take(2).join(', ')} +${names.length - 2}',);}(),+ // An agent the Swarm no longer lists keeps the server's name for it; a+ // person is named only as this Swarm lists them.+ SwarmActivityServerItem(:final entry) => (+ id: entry.actorId.isEmpty ? item.key : entry.actorId,+ name: named(+ entry.actorKind,+ entry.actorId,+ entry.actorName.isEmpty ? 'An agent' : entry.actorName,+ ),+ ),};}++/// What [entry]'s [who] did, as Desktop's Activity says it.+String swarmActivityDid(SwarmActivityEntry entry, String who) =>+ switch (entry.kind) {+ SwarmActivityKind.reply => '$who replied to your message',+ SwarmActivityKind.reaction => switch (SuperTabReactionEmoji.of(+ entry.emoji,+ )?.glyph) {+ final glyph? => '$who reacted $glyph to your message',+ null => '$who reacted to your message',+ },+ };diff --git a/mobile/test/swarm/swarm_activity_feed_page_test.dart b/mobile/test/swarm/swarm_activity_feed_page_test.dartnew file mode 100644index 000000000..90fb42ae0--- /dev/null+++ b/mobile/test/swarm/swarm_activity_feed_page_test.dart@@ -0,0 +1,277 @@+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_activity_page.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 on a server with Activity (Tony, task 8a): Replies in+/// place of Threads, a row bold while unread and named as this Swarm lists+/// who it is from, and what was open read on every device once it is left.+void main() {+ /// [home] under a signed-in shell's Swarm, on a 390-point phone, against+ /// a server whose `/activity` answers [rows].+ Future<FakeSwarm> pump(+ WidgetTester tester,+ List<Map<String, dynamic>> rows, {+ Widget home = const SwarmActivityPage(),+ List<Map<String, dynamic>> groups = const [],+ }) async {+ final fake = activityBackend(+ page: activityPage,+ activityDigest: () => 'digest-1',+ groups: groups,+ );+ fake.routes[activityPath] = (_) => {'items': rows, 'more': false};+ // As the backend marks: the person's rows made at or before `through`.+ fake.routes['$activityPath/read'] = (body) {+ final through = DateTime.parse(body!['through'] as String);+ for (final row in rows) {+ if (!DateTime.parse(row['createdAt'] as String).isAfter(through)) {+ row['read'] = true;+ }+ }+ return {'marked': 1};+ };+ 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 fake;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ 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();+ }++ List<Map<String, dynamic>?> marks(FakeSwarm fake) => [+ for (final call in fake.calls)+ if (call.method == 'POST' && call.path == '$activityPath/read') call.body,+ ];++ FontWeight? weight(WidgetTester tester, String text) =>+ tester.widget<Text>(find.text(text)).style?.fontWeight;++ testWidgets('Replies in place of Threads, counting the unread; a row bold '+ 'while unread, with what was said under it', (tester) async {+ await pump(tester, [+ activityRow('r2', minute: 9, text: "Merged, it's in tonight's build"),+ activityRow(+ 'r1',+ minute: 3,+ read: true,+ actor: {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ text: 'Looks good',+ ),+ ]);++ final pill = key('swarm-activity-filter-threads');+ expect(+ find.descendant(of: pill, matching: find.text('Replies')),+ findsOneWidget,+ );+ expect(find.descendant(of: pill, matching: find.text('1')), findsOneWidget);++ await filter(tester, 'threads');+ expect(find.text('River replied to your message'), findsOneWidget);+ expect(find.text("Merged, it's in tonight's build"), findsOneWidget);+ expect(weight(tester, 'River replied to your message'), AppFont.semibold);+ expect(weight(tester, 'Nova replied to your message'), AppFont.regular);+ expect(find.textContaining('#Mobile'), findsNWidgets(2));+ expect(+ find.byKey(const ValueKey('swarm-activity-reply-activity:$tab:r2')),+ findsOneWidget,+ );+ });++ testWidgets("a project's Activity (its status card) lists only the server "+ "rows of that project's chats", (tester) async {+ await pump(+ tester,+ [+ activityRow('here', minute: 5, text: 'In Mobile'),+ activityRow(+ 'there',+ minute: 4,+ conversationId: 'chat-other',+ text: 'In another project',+ ),+ ],+ groups: [+ {...groupData('chat-other', title: 'Other'), 'projectId': 'project-2'},+ ],+ home: const SwarmActivityPage(swarmId: tab, projectId: project),+ );+ await filter(tester, 'threads');+ expect(find.text('In Mobile'), findsOneWidget);+ expect(find.text('In another project'), findsNothing);+ });++ testWidgets('a reaction names its emoji', (tester) async {+ await pump(tester, [+ activityRow('x1', kind: 'reaction', emoji: 'thumbs_up', minute: 2),+ ]);+ await filter(tester, 'reactions');+ expect(find.text('River reacted 👍 to your message'), findsOneWidget);+ });++ testWidgets('who it is from is named as this Swarm lists them: an agent by '+ "its name here, a person it does not list as Someone, never the server's "+ 'word for a person', (tester) async {+ await pump(tester, [+ activityRow(+ 'p1',+ minute: 5,+ actor: {'kind': 'person', 'id': 'person-gone', 'name': 'secret-name'},+ ),+ activityRow(+ 'a1',+ minute: 4,+ actor: {'kind': 'agent', 'id': 'agent-builder', 'name': 'Elsewhere'},+ ),+ activityRow(+ 'a2',+ minute: 3,+ actor: {'kind': 'agent', 'id': 'agent-left', 'name': 'Old Pip'},+ ),+ ]);+ await filter(tester, 'threads');+ expect(find.text('Someone replied to your message'), findsOneWidget);+ expect(find.text('Nova replied to your message'), findsOneWidget);+ expect(find.text('Old Pip replied to your message'), findsOneWidget);+ expect(find.textContaining('secret-name'), findsNothing);+ expect(find.textContaining('Elsewhere'), findsNothing);+ });++ testWidgets('Activity left (another tab) marks what it had open read on '+ 'every device; a list never opened stays unread', (tester) async {+ final hidden = ValueNotifier(false);+ addTearDown(hidden.dispose);+ final fake = await pump(+ tester,+ [+ activityRow('r2', minute: 9),+ activityRow('x1', kind: 'reaction', emoji: 'check', minute: 12),+ ],+ home: Scaffold(+ body: ValueListenableBuilder(+ valueListenable: hidden,+ builder: (_, out, _) =>+ OutOfSight(hidden: out, child: const SwarmActivityView()),+ ),+ ),+ );+ await filter(tester, 'threads');++ // A chat opened from a row is over Activity, not instead of it.+ await tester.tap(key('swarm-activity-reply-activity:$tab:r2'));+ await tester.pumpAndSettle();+ expect(marks(fake), isEmpty);+ Navigator.of(+ tester.element(find.byType(SwarmActivityView, skipOffstage: false)),+ ).pop();+ await tester.pumpAndSettle();+ expect(weight(tester, 'River replied to your message'), AppFont.semibold);++ hidden.value = true;+ await tester.pumpAndSettle();+ expect(marks(fake), [+ {'through': DateTime.utc(2026, 11, 1, 7, 9).toIso8601String()},+ ], reason: 'the reaction behind Reactions was never open: it stays unread');++ hidden.value = false;+ await tester.pumpAndSettle();+ expect(weight(tester, 'River replied to your message'), AppFont.regular);+ final pill = key('swarm-activity-filter-reactions');+ expect(find.descendant(of: pill, matching: find.text('1')), findsOneWidget);+ });++ testWidgets('a Swarm the person can no longer read leaves the list at once', (+ tester,+ ) async {+ await pump(tester, [activityRow('r1', text: 'Private words')]);+ await filter(tester, 'threads');+ expect(find.text('Private words'), findsOneWidget);++ final host = tester.widget<SwarmScope>(find.byType(SwarmScope)).notifier!;+ host.session!.inbox.reader(tab)!.revoke();+ await tester.pumpAndSettle();+ expect(find.text('Private words'), findsNothing);+ expect(find.textContaining('replied to your message'), findsNothing);+ });++ testWidgets('a list that cannot be read says so and Try again reads it', (+ tester,+ ) async {+ final fake = activityBackend(+ page: activityPage,+ activityDigest: () => 'digest-1',+ );+ var fail = true;+ fake.routes[activityPath] = (_) => fail+ ? throw Exception('down')+ : {+ 'items': [activityRow('r1', text: 'Back again')],+ 'more': false,+ };+ 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: const SwarmActivityPage(),+ ),+ );+ await tester.pumpAndSettle();+ await filter(tester, 'threads');++ expect(find.text('Some chats could not be read.'), findsOneWidget);+ expect(key('swarm-activity-loading'), findsNothing);++ fail = false;+ await tester.tap(key('swarm-activity-retry'));+ await tester.pumpAndSettle();+ expect(find.text('Back again'), findsOneWidget);+ expect(find.text('Some chats could not be read.'), findsNothing);+ });+}diff --git a/mobile/test/swarm/swarm_activity_feed_shots_test.dart b/mobile/test/swarm/swarm_activity_feed_shots_test.dartnew file mode 100644index 000000000..b7e623602--- /dev/null+++ b/mobile/test/swarm/swarm_activity_feed_shots_test.dart@@ -0,0 +1,162 @@+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_activity_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_activity_fixture.dart';+import 'swarm_fixture.dart';++/// Review screenshots of Activity read from the server (Tony, task 8a):+/// Replies and Reactions, unread rows bold over read ones, 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('Replies and Reactions from the server, 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().toUtc();+ Map<String, dynamic> at(Map<String, dynamic> row, Duration age) => {+ ...row,+ 'createdAt': now.subtract(age).toIso8601String(),+ };+ final fake = activityBackend(+ page: activityPage,+ activityDigest: () => 'digest-1',+ );+ fake.routes[activityPath] = (_) => {+ 'items': [+ at(+ activityRow('r2', text: "Merged, it's in tonight's build"),+ const Duration(minutes: 5),+ ),+ at(+ activityRow(+ 'x1',+ kind: 'reaction',+ emoji: 'thumbs_up',+ text: 'Can we ship the status card?',+ ),+ const Duration(minutes: 40),+ ),+ at(+ activityRow(+ 'r1',+ read: true,+ actor: {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ text: 'Looks good to me, one nit on the copy.',+ ),+ const Duration(hours: 2),+ ),+ at(+ activityRow(+ 'x2',+ kind: 'reaction',+ emoji: 'check',+ read: true,+ actor: {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ text: 'Fixed the login copy.',+ ),+ const Duration(hours: 3),+ ),+ ],+ 'more': false,+ };+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => me,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (_, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmActivityPage(),+ ),+ ),+ );+ await tester.pumpAndSettle();++ Future<void> capture(String name) async {+ if (shots == null) return;+ await tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$shots/activity-server-$name-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ }++ for (final filter in ['threads', 'reactions']) {+ final pill = find.byKey(ValueKey('swarm-activity-filter-$filter'));+ await tester.ensureVisible(pill);+ await tester.pumpAndSettle();+ await tester.tap(pill);+ await tester.pumpAndSettle();+ await capture(filter == 'threads' ? 'replies' : filter);+ }+ expect(find.text('River reacted 👍 to your message'), findsOneWidget);++ await tester.pumpWidget(const SizedBox());+ host.dispose();+ account.dispose();+ }+ });+}diff --git a/mobile/test/swarm/swarm_activity_feed_test.dart b/mobile/test/swarm/swarm_activity_feed_test.dartnew file mode 100644index 000000000..dbb7ad929--- /dev/null+++ b/mobile/test/swarm/swarm_activity_feed_test.dart@@ -0,0 +1,583 @@+import 'dart:async';+import 'dart:convert';++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_activity_feed.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 read from the server, as Desktop reads it (Tony, task 8a;+/// #2453): replies and reactions listed by `/activity`, read on every device+/// through `/activity/read` once Activity is left, the badge counted as+/// Desktop counts it, and a server before Activity kept on the phone's own+/// rows.+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ Future<SwarmSession> start(+ FakeSwarm fake, {+ MemoryKeyValueStore? store,+ bool dispose = true,+ }) async {+ final session = SwarmSession(+ accountId: me,+ request: fake.request,+ notices: SilentSystemNotices(),+ readMarks: store ?? MemoryKeyValueStore(),+ );+ if (dispose) addTearDown(session.dispose);+ // Made before the first read, as the Activity tab's badge makes it.+ session.activity;+ await session.inbox.refresh();+ await settle();+ return session;+ }++ /// A server with Activity, whose `/activity` answers [rows] as they stand.+ FakeSwarm server(+ List<Map<String, dynamic>> Function() rows, {+ String Function()? digest,+ }) {+ final fake = activityBackend(+ page: activityPage,+ activityDigest: digest ?? () => 'digest-1',+ );+ fake.routes[activityPath] = (_) => {'items': rows(), 'more': false};+ fake.routes['$activityPath/read'] = (_) => {'marked': 1};+ return fake;+ }++ List<String> keys(SwarmActivity activity, SwarmActivityFilter filter) => [+ for (final item in activity.items(filter)) item.key,+ ];++ int lists(FakeSwarm fake) => fake.calls+ .where((c) => c.method == 'GET' && c.path == activityPath)+ .length;++ List<Map<String, dynamic>?> marks(FakeSwarm fake) => [+ for (final call in fake.calls)+ if (call.method == 'POST' && call.path == '$activityPath/read') call.body,+ ];++ /// The Swarm changes on its next read (one more decision waits), its+ /// Activity digest as [digest] says: what the phone holds moves either way.+ var round = 0;+ Future<void> swarmMoves(+ SwarmSession session,+ FakeSwarm fake,+ String Function() digest,+ ) async {+ round++;+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c${round + 2}',+ derived: {+ 'decisionsWaiting': 1 + round,+ 'mentionsWaiting': 1,+ 'activityDigest': digest(),+ },+ lastChangedAt: 1 + round,+ );+ await session.inbox.reader(tab)!.refresh();+ await settle();+ }++ int chatReads(FakeSwarm fake) =>+ fake.paths.where((p) => p.startsWith(activityChatPath)).length;++ group('the server list', () {+ test('Replies and Reactions are the server rows, newest first, and no '+ 'project chat is read for them', () async {+ final fake = server(+ () => [+ activityRow('r2', minute: 9, text: 'Merged it'),+ activityRow('x1', kind: 'reaction', emoji: 'check', minute: 8),+ activityRow('r1', minute: 3, read: true),+ ],+ );+ final session = await start(fake);+ final activity = session.activity..watch();+ addTearDown(activity.unwatch);+ await settle();++ expect(keys(activity, SwarmActivityFilter.threads), [+ 'activity:$tab:r2',+ 'activity:$tab:r1',+ ]);+ expect(keys(activity, SwarmActivityFilter.reactions), [+ 'activity:$tab:x1',+ ]);+ expect(activity.label(SwarmActivityFilter.threads), 'Replies');+ expect(activity.count(SwarmActivityFilter.threads), 1);+ expect(activity.count(SwarmActivityFilter.reactions), 1);+ expect(chatReads(fake), 0, reason: 'the server lists them');+ final reply = activity.items(SwarmActivityFilter.threads).first;+ expect(activity.unread(reply), isTrue);+ expect(activity.handled(reply), isNull, reason: 'no phone-only mark');+ });++ test('a reply in a thread opens at its thread', () async {+ final fake = server(+ () => [activityRow('r1', threadId: 'root-1', messageId: 'reply-1')],+ );+ final session = await start(fake);+ final item = session.activity.items(SwarmActivityFilter.threads).single;+ expect(item.conversationId, leadChat);+ expect(item.messageId, 'root-1');+ });++ test('it is read again only when its digest moves', () async {+ var digest = 'digest-1';+ final fake = server(() => [activityRow('r1')], digest: () => digest);+ final session = await start(fake);+ final listed = lists(fake);+ expect(listed, 1);++ await swarmMoves(session, fake, () => digest);+ expect(lists(fake), listed, reason: 'the same digest reads nothing');++ digest = 'digest-2';+ await swarmMoves(session, fake, () => digest);+ expect(lists(fake), listed + 1);+ });+ });++ group('the badge', () {+ test('counts decisions and tags waiting and replies unread, as Desktop; '+ 'reactions and work do not count', () async {+ final fake = server(+ () => [+ activityRow('r1', minute: 4),+ activityRow('r2', minute: 3),+ activityRow('r3', minute: 2, read: true),+ activityRow('x1', kind: 'reaction', emoji: 'eyes', minute: 1),+ ],+ );+ final session = await start(fake);+ // decisionsWaiting 1 + mentionsWaiting 1 + 2 replies unread.+ expect(session.activity.badge, 4);+ });++ test('a Swarm the person can no longer read counts nothing', () async {+ final fake = server(() => [activityRow('r1')]);+ final session = await start(fake);+ expect(session.activity.badge, 3);++ session.inbox.reader(tab)!.revoke();+ await settle();+ expect(session.activity.badge, 0);+ expect(session.activity.items(SwarmActivityFilter.threads), isEmpty);+ });+ });++ group('marking read', () {+ test('leaving Activity marks the rows it had open read on every device, '+ 'and the badge drops', () async {+ final fake = server(+ () => [activityRow('r2', minute: 9), activityRow('r1', minute: 3)],+ );+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();+ expect(activity.badge, 4);++ activity.showing(activity.items(SwarmActivityFilter.threads));+ final row = activity.items(SwarmActivityFilter.threads).first;+ activity.unwatch();+ expect(activity.unread(row), isTrue, reason: 'bold until it is left');+ await settle();++ expect(marks(fake), [+ {'through': DateTime.utc(2026, 11, 1, 7, 9).toIso8601String()},+ ]);+ expect(activity.count(SwarmActivityFilter.threads), 0);+ final read = activity.items(SwarmActivityFilter.threads).first;+ expect(read.key, row.key);+ expect(activity.unread(read), isFalse);+ expect(activity.badge, 2);+ });++ test(+ 'rows read on another device stay bold until Activity is left',+ () async {+ var read = false;+ var digest = 'digest-1';+ final fake = server(+ () => [activityRow('r1', read: read)],+ digest: () => digest,+ );+ final session = await start(fake);+ final activity = session.activity..watch();+ addTearDown(activity.unwatch);+ await settle();+ final row = activity.items(SwarmActivityFilter.threads).single;++ read = true;+ digest = 'digest-2';+ await session.inbox.reader(tab)!.refresh();+ await settle();+ final again = activity.items(SwarmActivityFilter.threads).single;+ expect(activity.waiting(again), isFalse, reason: 'read on the server');+ expect(activity.unread(again), isTrue, reason: 'still bold here');+ expect(row.key, again.key);+ },+ );++ test('a row Activity never had open is not marked read with the others: '+ 'a newer reaction behind another filter stays unread', () async {+ final fake = server(+ () => [+ activityRow('x1', kind: 'reaction', emoji: 'check', minute: 9),+ activityRow('r2', minute: 6),+ activityRow('r1', minute: 3),+ ],+ );+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();++ // Only Replies was open.+ activity.showing(activity.items(SwarmActivityFilter.threads));+ activity.unwatch();+ await settle();++ expect(marks(fake), [+ {'through': DateTime.utc(2026, 11, 1, 7, 6).toIso8601String()},+ ]);+ expect(activity.count(SwarmActivityFilter.reactions), 1);+ });++ test('an unread row older than those open holds them all back', () async {+ final fake = server(+ () => [+ activityRow('r2', minute: 6),+ activityRow('x1', kind: 'reaction', emoji: 'check', minute: 3),+ ],+ );+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();++ activity.showing(activity.items(SwarmActivityFilter.threads));+ activity.unwatch();+ await settle();++ expect(marks(fake), isEmpty, reason: 'through would take x1 with it');+ expect(activity.count(SwarmActivityFilter.threads), 1);+ });++ test('leaving with nothing open marks nothing', () async {+ final fake = server(() => [activityRow('r1')]);+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();+ activity.unwatch();+ await settle();+ expect(marks(fake), isEmpty);+ });++ test(+ 'a mark the server refused is unread again at the next read',+ () async {+ final fake = server(() => [activityRow('r1')]);+ fake.routes['$activityPath/read'] = (_) =>+ throw const SuperTabFailure('UNAVAILABLE', 'Down', statusCode: 503);+ final session = await start(fake);+ final activity = session.activity..watch();+ await settle();+ activity.showing(activity.items(SwarmActivityFilter.threads));+ activity.unwatch();+ await settle();++ expect(marks(fake), hasLength(1));+ expect(+ activity.count(SwarmActivityFilter.threads),+ 1,+ reason: 'read again, it is unread as the server has it',+ );+ expect(activity.badge, 3);+ },+ );+ });++ group('a server before Activity', () {+ test(+ 'answering 404, it keeps the phone-built Threads and Reactions',+ () async {+ final fake = activityBackend(+ page: activityPage,+ activityDigest: () => 'digest-1',+ );+ final session = await start(fake);+ final activity = session.activity..watch();+ addTearDown(activity.unwatch);+ await settle();++ expect(lists(fake), 1);+ expect(activity.label(SwarmActivityFilter.threads), 'Threads');+ expect(keys(activity, SwarmActivityFilter.threads), [+ 'thread:$tab:root-1',+ 'thread:$tab:root-old',+ ]);+ expect(keys(activity, SwarmActivityFilter.reactions), [+ 'reaction:$tab:mine-2',+ ]);+ expect(activity.badge, 2, reason: 'what needs the person, as before');+ },+ );++ test('sending no digest, it is never asked', () async {+ final fake = activityBackend(page: activityPage);+ final session = await start(fake);+ final activity = session.activity..watch();+ addTearDown(activity.unwatch);+ await settle();++ expect(lists(fake), 0);+ expect(keys(activity, SwarmActivityFilter.threads), [+ 'thread:$tab:root-1',+ 'thread:$tab:root-old',+ ]);+ });+ });++ group('the handled marks kept on the phone', () {+ final key = 'swarm_activity.$me.$tab';++ test('go once the server lists Activity: it keeps what is read', () async {+ final store = MemoryKeyValueStore();+ await store.write(+ key,+ jsonEncode({+ 'marks': {'t:root-1': 12},+ }),+ );+ final session = await start(server(() => const []), store: store);+ await session.activity.watch2();+ expect(await store.read(key), isNull);+ });++ test('stay while the server has no Activity', () async {+ final store = MemoryKeyValueStore();+ await store.write(+ key,+ jsonEncode({+ 'marks': {'t:root-1': 12},+ }),+ );+ final session = await start(+ activityBackend(page: activityPage, activityDigest: () => 'digest-1'),+ store: store,+ );+ await session.activity.watch2();+ expect(await store.read(key), isNotNull);+ });+ });++ group('privacy', () {+ test(+ 'rows of a chat the phone does not hold — another project, a '+ 'private chat, someone else\'s Buddy chat — are left out alike',+ () async {+ final fake = server(+ () => [+ activityRow('r1', minute: 5),+ activityRow('other', conversationId: 'group-elsewhere', minute: 4),+ activityRow('buddy', conversationId: 'buddy-someone', minute: 3),+ ],+ );+ final session = await start(fake);+ expect(keys(session.activity, SwarmActivityFilter.threads), [+ 'activity:$tab:r1',+ ]);+ expect(session.activity.badge, 3, reason: 'only the held row counts');+ },+ );++ test(+ 'access lost while a list is on its way: the answer is dropped',+ () async {+ final answer = Completer<Object?>();+ final fake = server(() => [activityRow('r1')]);+ fake.routes[activityPath] = (_) => answer.future;+ final session = await start(fake);+ final feed = SwarmActivityFeed(session.inbox.reader(tab)!);+ addTearDown(feed.dispose);+ await settle();+ expect(lists(fake), 2);++ session.inbox.reader(tab)!.revoke();+ answer.complete({+ 'items': [activityRow('r1')],+ 'more': false,+ });+ await settle();+ expect(feed.items, isEmpty);+ expect(feed.fromServer, isFalse);+ expect(session.activity.items(SwarmActivityFilter.threads), isEmpty);+ expect(session.activity.badge, 0);+ },+ );++ test('rows read before access was lost are cleared with it', () async {+ final fake = server(() => [activityRow('r1')]);+ final session = await start(fake);+ final feed = SwarmActivityFeed(session.inbox.reader(tab)!);+ addTearDown(feed.dispose);+ await settle();+ expect(feed.items, hasLength(1));++ session.inbox.reader(tab)!.revoke();+ await settle();+ expect(feed.items, isEmpty, reason: 'nothing of it stays on the phone');+ expect(feed.loaded, isFalse);+ });++ test(+ 'a list answered after sign-out changes nothing and throws nothing',+ () async {+ final answer = Completer<Object?>();+ final fake = server(() => const []);+ fake.routes[activityPath] = (_) => answer.future;+ final session = await start(fake, dispose: false);+ final reader = session.inbox.reader(tab)!;+ final feed = SwarmActivityFeed(reader);+ final told = <int>[];+ feed.addListener(() => told.add(1));+ await settle();++ feed.dispose();+ session.dispose();+ answer.complete({+ 'items': [activityRow('r1')],+ 'more': false,+ });+ await settle();+ expect(feed.items, isEmpty);+ expect(told, isEmpty);+ },+ );++ test('a list asked before the Swarm was read again from nothing is not '+ 'shown over the new read', () async {+ final first = Completer<Object?>(), second = Completer<Object?>();+ var calls = 0;+ var digest = 'digest-1';+ final fake = server(() => const [], digest: () => digest);+ fake.routes[activityPath] = (_) =>+ ++calls == 1 ? first.future : second.future;+ final session = await start(fake);+ // The Swarm is read again from nothing (its access moved).+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ throw const SuperTabFailure('FORBIDDEN', 'No', statusCode: 403);+ digest = 'digest-2';+ await session.inbox.reader(tab)!.refresh();+ await settle();++ first.complete({+ 'items': [activityRow('stale')],+ 'more': false,+ });+ await settle();+ expect(+ session.activity.items(SwarmActivityFilter.threads),+ isEmpty,+ reason: 'asked under what the phone held before',+ );++ second.complete({+ 'items': [activityRow('fresh')],+ 'more': false,+ });+ await settle();+ expect(keys(session.activity, SwarmActivityFilter.threads), [+ 'activity:$tab:fresh',+ ]);+ });+ });++ group('a failed read', () {+ test('says so with no stuck loading, is not read again at every Swarm '+ 'read, and Try again brings the feature back', () async {+ var fail = true;+ final fake = server(() => [activityRow('r1')]);+ fake.routes[activityPath] = (_) => fail+ ? throw const SuperTabFailure('UNAVAILABLE', 'Down', statusCode: 503)+ : {+ 'items': [activityRow('r1')],+ 'more': false,+ };+ final session = await start(fake);+ final activity = session.activity..watch();+ addTearDown(activity.unwatch);+ await settle();++ expect(activity.unreadChats, isTrue);+ expect(activity.reading, isFalse, reason: 'no stuck loading');+ final asked = lists(fake);+ for (var i = 0; i < 3; i++) {+ await swarmMoves(session, fake, () => 'digest-1');+ }+ expect(lists(fake), asked, reason: 'bounded: the same digest waits');++ fail = false;+ activity.retry();+ await settle();+ expect(activity.unreadChats, isFalse);+ expect(keys(activity, SwarmActivityFilter.threads), ['activity:$tab:r1']);+ expect(activity.label(SwarmActivityFilter.threads), 'Replies');+ });++ test('a failed first read recovers when the digest moves', () async {+ var fail = true;+ var digest = 'digest-1';+ final fake = server(() => [activityRow('r1')], digest: () => digest);+ fake.routes[activityPath] = (_) => fail+ ? throw const SuperTabFailure('UNAVAILABLE', 'Down', statusCode: 503)+ : {+ 'items': [activityRow('r1')],+ 'more': false,+ };+ final session = await start(fake);+ expect(session.activity.items(SwarmActivityFilter.threads), isEmpty);++ fail = false;+ digest = 'digest-2';+ await session.inbox.reader(tab)!.refresh();+ await settle();+ expect(keys(session.activity, SwarmActivityFilter.threads), [+ 'activity:$tab:r1',+ ]);+ expect(session.activity.badge, 3);+ });++ test('a row this build cannot read is left out, not the list', () async {+ final fake = server(+ () => [+ activityRow('r1'),+ {'id': 'broken'},+ ],+ );+ final session = await start(fake);+ expect(keys(session.activity, SwarmActivityFilter.threads), [+ 'activity:$tab:r1',+ ]);+ });+ });+}++extension on SwarmActivity {+ /// In sight long enough for every read it asks to answer.+ Future<void> watch2() async {+ watch();+ await settle();+ unwatch();+ await settle();+ }+}diff --git a/mobile/test/swarm/swarm_activity_fixture.dart b/mobile/test/swarm/swarm_activity_fixture.dartindex e92dd1fba..4774f50dd 100644--- a/mobile/test/swarm/swarm_activity_fixture.dart+++ b/mobile/test/swarm/swarm_activity_fixture.dart@@ -48,7 +48,10 @@ Map<String, dynamic> activityThread(/// 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],/// and its thread marks by root [threadMarks] (none from an older server).+/// A server with Activity (#2453) sends [activityDigest] as it stands at+/// each read; none sends no digest, as a server before Activity.FakeSwarm activityBackend({+ String? Function()? activityDigest,Map<String, dynamic> Function()? page,int readMark = 10,Map<String, int>? threadMarks,@@ -69,9 +72,13 @@ FakeSwarm activityBackend({'readMarks': {leadChat: readMark},'threadMarks': ?(threadMarks == null ? null : {leadChat: threadMarks}),};+ Map<String, dynamic> now() => {+ ...derived,+ 'activityDigest': ?activityDigest?.call(),+ };fake.routes['/api/super-tabs/$tab/parts'] = (_) {final load = firstLoad(- derived: derived,+ derived: now(),lastChangedAt: 1,groups: [groupData(@@ -91,7 +98,7 @@ FakeSwarm activityBackend({return load;};fake.routes['/api/super-tabs/$tab/changes'] = (_) =>- changes(cursor: 'c2', derived: derived, lastChangedAt: 1);+ changes(cursor: 'c2', derived: now(), lastChangedAt: 1);fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {'decisions': [if (decision)@@ -218,3 +225,40 @@ void activitySecondSwarm(_,) => page?.call() ?? {'messages': <Object>[], 'next': null};}++/// The server's Activity of the person in Swarm [tab]: GET answers [rows]+/// as it stands, POST read is remembered by [FakeSwarm.calls].+const activityPath = '/api/super-tabs/$tab/activity';++/// One row of `/activity` (backend superTabs/activity.ts ActivityItem), made+/// at 07:[minute] on 11-01.+Map<String, dynamic> activityRow(+ String id, {+ String kind = 'reply',+ String conversationId = leadChat,+ String? messageId,+ String? threadId,+ Map<String, dynamic> actor = const {+ 'kind': 'agent',+ 'id': 'agent-lead',+ 'name': 'River',+ },+ String? emoji,+ String text = '',+ int minute = 0,+ bool read = false,+}) => {+ 'id': id,+ 'kind': kind,+ 'conversationId': conversationId,+ 'conversationTitle': 'Mobile',+ 'projectName': 'Mobile',+ 'messageId': messageId ?? 'msg-$id',+ 'messageSequence': 20 + minute,+ 'threadId': threadId,+ 'actor': actor,+ 'emoji': emoji,+ 'text': text.isEmpty ? 'Text of $id' : text,+ 'createdAt': DateTime.utc(2026, 11, 1, 7, minute).toIso8601String(),+ 'read': read,+};