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: an undeliverable message says Not delivered yet, as Desktop #2336 (#2346)
harness-for-autonomous[bot]4f500d8495fd
diff --git a/docs/swarms.md b/docs/swarms.mdindex 822e577b5..db183cae0 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -653,6 +653,11 @@ either:Harness keeps trying, and the line goes once the message is in. An offline computer still reads as offline instead.+The phone shows the same two lines in the same words, while the delivery is queued. Its chat reads no delivery change on+its own, so it reads your newest message again while the chat is on screen: at most every 30 seconds, until the delivery+is claimed or for 10 minutes each time the chat comes back on screen, and once more whenever a newer message arrives in+the chat. It shows nothing until such a read has worked.+Behind it, the backend writes each claim that ends busy on the delivery (`claimFailingSince`, `claimFailures`) andclears that record when a claim gets in. Every 5 minutes the delivery pass logs `[swarm-deliveries] claims failing`for a Swarm whose queued messages have failed to be claimed for 5 minutes and still fail. Prod watch alarms on thatdiff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartindex 072e429f8..9ec0eb3b2 100644--- a/mobile/lib/swarm/swarm_conversation.dart+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -1,5 +1,6 @@import 'dart:async';+import 'package:clock/clock.dart';import 'package:flutter/foundation.dart';import 'model.dart';@@ -133,6 +134,9 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {set shown(bool value) {if (_shown == value) return;_shown = value;+ // Back on screen: what the line last read may be long gone, so it is read+ // again before it is believed, under a new [_receiptReadFor].+ if (value) _dropReceipt();_markRead();}@@ -416,6 +420,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {_answeredAlerts = answered;notifyListeners();}+ _checkReceipt();}/// The prompt warnings the page last hid, as one key.@@ -445,6 +450,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {_readingOlder = null;_rereading = null;_reactionSeq = null;+ _dropReceipt();}/// The person cannot read this conversation: nothing of it stays, here or@@ -553,7 +559,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {bool again = false,bool tell = true,}) async {- final epoch = _epoch;+ final epoch = _epoch, asked = ++_readsAsked;var reacted = false;try {final tail = latest ? null : messages.lastOrNull?.sequence;@@ -594,6 +600,15 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {var changed = !_read || error != null || _refused || latest;changed |= _keepThreads(answer['threads']);for (final m in incoming) {+ if (m.id == _receiptOf) {+ // A read of it asked after this one holds where its delivery is now.+ final held = messages.where((m) => m.id == _receiptOf).firstOrNull;+ if (held != null && asked < _receiptAskedAs) {+ byId[m.id] = held;+ continue;+ }+ _receiptAskedAs = asked;+ }if (byId[m.id] case final shown? when _same(shown, m)) continue;byId[m.id] = m;changed = true;@@ -873,7 +888,25 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {a.authorName == b.authorName &&a.createdAt == b.createdAt &&a.attachments.length == b.attachments.length &&- _sameReactions(a.reactions, b.reactions);+ _sameReactions(a.reactions, b.reactions) &&+ _sameDeliveries(a, b);++ /// What the delivery line draws from: each failed claim's count changes+ /// nothing there, so it draws nothing again.+ static bool _sameDeliveries(SuperTabMessage a, SuperTabMessage b) {+ if (a.deliveries.length != b.deliveries.length) return false;+ for (var i = 0; i < a.deliveries.length; i++) {+ for (final field in const [+ 'id',+ 'agentId',+ 'status',+ 'claimFailingSince',+ ]) {+ if (a.deliveries[i][field] != b.deliveries[i][field]) return false;+ }+ }+ return true;+ }static bool _sameReactions(List<SuperTabReactionCount> a,@@ -888,6 +921,125 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {return true;}+ /// How often the person's newest message is read again while its delivery+ /// is queued, and for how long once it is on screen (Lead, 10-30): a phone+ /// pays for every read, and the chat's own reads see no delivery change.+ static const _receiptReadEvery = Duration(seconds: 30);+ static const _receiptReadFor = Duration(minutes: 10);++ String? _receiptOf;+ DateTime? _receiptSince, _receiptAsked;++ /// The newest message when it was last asked: one that came after it may+ /// have answered it, so it is read once more, even past [_receiptReadFor].+ int? _receiptTail;++ /// Reads are numbered as they are asked; [_receiptAskedAs] is the one the+ /// row held came from, so an older answer landing later cannot put it back.+ int _readsAsked = 0, _receiptAskedAs = -1;+ bool _receiptCurrent = false;+ Future<void>? _readingReceipt;++ /// The person's newest message here, written by them and not by an agent or+ /// a terminal: the only one that can carry a delivery line.+ SuperTabMessage? get latestOwn {+ for (final m in messages.reversed) {+ if (!m.fromAgent && !m.fromTerminal && m.authorId == reader.accountId) {+ return m;+ }+ }+ return null;+ }++ /// [message]'s deliveries were last read here, and that read worked: a row+ /// kept from an earlier open, or a read that failed, proves nothing about+ /// where the delivery is now.+ bool receiptCurrent(SuperTabMessage message) =>+ _receiptCurrent && _receiptOf == message.id;++ void _dropReceipt() {+ _receiptOf = _receiptSince = _receiptAsked = _receiptTail = null;+ _receiptAskedAs = -1;+ _receiptCurrent = false;+ _readingReceipt = null;+ }++ /// Reads the person's newest message again, at the Swarm's own reads, while+ /// it is on screen and its delivery is queued. No timer of its own: off+ /// screen nothing asks.+ void _checkReceipt() {+ if (!_shown || _readingReceipt != null || reader.error != null) return;+ final own = latestOwn;+ if (own == null || own.receiptDelivery?.status != 'queued') return;+ final now = clock.now();+ if (_receiptOf != own.id) {+ _dropReceipt();+ _receiptOf = own.id;+ _receiptSince = now;+ }+ final asked = _receiptAsked;+ if (asked != null && now.difference(asked) < _receiptReadEvery) return;+ final tail = messages.last.sequence;+ final answered = tail > own.sequence && tail != _receiptTail;+ if (!answered && now.difference(_receiptSince!) >= _receiptReadFor) return;+ _receiptAsked = now;+ _receiptTail = tail;+ late final Future<void> reading;+ reading = _readReceipt(own.id).whenComplete(() {+ if (identical(_readingReceipt, reading)) _readingReceipt = null;+ });+ _readingReceipt = reading;+ }++ Future<void> _readReceipt(String messageId) async {+ final epoch = _epoch, generation = reader.generation, asked = ++_readsAsked;+ bool stale() =>+ _disposed ||+ epoch != _epoch ||+ generation != reader.generation ||+ _receiptOf != messageId;+ SuperTabMessage? read;+ try {+ final answer = superTabMap(+ await reader.request(+ 'GET',+ '$messagesPath?messageId=${Uri.encodeQueryComponent(messageId)}',+ ),+ );+ if (stale()) return;+ read = [+ for (final row in answer['messages'] as List)+ SuperTabMessage.fromJson(superTabMap(row)),+ ].where((m) => m.id == messageId && m.conversationId == id).firstOrNull;+ } on SuperTabFailure catch (failure) {+ if (stale()) return;+ if (const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {+ _lose();+ error = failure.message;+ notifyListeners();+ return;+ }+ } catch (_) {+ if (stale()) return;+ }+ final fresh = read;+ final at = fresh == null+ ? -1+ : messages.indexWhere((m) => m.id == fresh.id);+ final current = at >= 0;+ // The chat's own read may have been asked after this one and landed first.+ final newest = current && asked >= _receiptAskedAs;+ if (newest) _receiptAskedAs = asked;+ final replaced = newest && !_same(messages[at], fresh!);+ if (replaced) {+ messages = List.unmodifiable([...messages]..[at] = fresh);+ }+ if (replaced || current != _receiptCurrent) {+ _receiptCurrent = current;+ notifyListeners();+ }+ }+/// A refused post's text back in the draft, before anything typed since.void _restore() {final sent = _sent;diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex 84774dadc..249bf7ae3 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -32,6 +32,7 @@ import 'swarm_outgoing_files.dart';import 'swarm_inbox.dart';import 'swarm_live_card.dart';import 'swarm_message_link.dart';+import 'swarm_message_receipt.dart';import 'swarm_message_row.dart';import 'swarm_need_rows.dart';import 'swarm_profile_sheet.dart';@@ -1331,6 +1332,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>});}final lead = pending == null ? 0 : 1;+ final latestOwn = c.latestOwn;Widget entry(_Entry entry) {final key = _keyOf(entry);@@ -1364,6 +1366,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>final lit = _lit == m.id, followed = _target == m.id;final acting = _acting == m.id;final reactions = c.reactionsOf(m);+ final receipt =+ m.id == latestOwn?.id && m.receiptDelivery?.status == 'queued';// A card's facts are its group's: only a reader of the group has// them, and a change to them draws the row again.final group = c.conversation;@@ -1382,6 +1386,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>lit,followed,acting,+ receipt,reply,quoted,view.canPost,@@ -1472,6 +1477,13 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>: null,),onLongPress: () => unawaited(_pickReaction(c, m.id)),+ receipt: receipt+ ? SwarmMessageReceipt(+ key: ValueKey('swarm-message-receipt-${m.id}'),+ conversation: c,+ message: m,+ )+ : null,below: answerIn == null? null: _AnswerIn(diff --git a/mobile/lib/swarm/swarm_message_receipt.dart b/mobile/lib/swarm/swarm_message_receipt.dartnew file mode 100644index 000000000..6537996d7--- /dev/null+++ b/mobile/lib/swarm/swarm_message_receipt.dart@@ -0,0 +1,231 @@+import 'dart:async';++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.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 'model.dart';+import 'swarm_conversation.dart';+import 'swarm_message_row.dart' show swarmChatText;+import 'swarm_thread_line.dart' show swarmAgo;++/// How long a queued delivery's claims fail before its sender is told, and how+/// long a queued message waits with no claim fields before the same: the+/// desktop's `superTabClaimFailingNotice` and `superTabQueuedNotice` (prod+/// 10-30, v1.3.71: claims failed for two hours and nothing showed).+const swarmClaimFailingNotice = Duration(seconds: 60);+const swarmQueuedNotice = Duration(minutes: 2);++/// How long a machine's reading may stand before it is called offline: the+/// desktop's `kSuperTabMachineOfflineAfter`.+const _machineOfflineAfter = Duration(seconds: 35);++/// The line under the person's newest message while its delivery is queued and+/// not getting in: the desktop's `SuperTabMessageReceipt` for those two cases,+/// its words and rule, in amber with nothing to do (#2336). A message that+/// arrived carries none, as in Slack.+///+/// Only a queued delivery: a claimed one is no longer read again+/// ([SwarmConversation.receiptCurrent]), so nothing here could tell when it+/// arrives.+class SwarmMessageReceipt extends StatefulWidget {+ const SwarmMessageReceipt({+ super.key,+ required this.conversation,+ required this.message,+ });++ final SwarmConversation conversation;+ final SuperTabMessage message;++ @override+ State<SwarmMessageReceipt> createState() => _SwarmMessageReceiptState();+}++class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>+ with WidgetsBindingObserver {+ Timer? _timer;+ DateTime? _wakeAt;+ bool _enabled = true;+ late Listenable _source;++ Listenable _sourceOf(SwarmConversation c) =>+ Listenable.merge([c, c.reader, c.reader.reads]);++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ _source = _sourceOf(widget.conversation)..addListener(_changed);+ }++ @override+ void didUpdateWidget(SwarmMessageReceipt oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (!identical(oldWidget.conversation, widget.conversation)) {+ _source.removeListener(_changed);+ _source = _sourceOf(widget.conversation)..addListener(_changed);+ }+ }++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _enabled =+ TickerMode.valuesOf(context).enabled &&+ ModalRoute.isCurrentOf(context) != false;+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ // No frame comes in the background to let the wake-up go.+ if (state != AppLifecycleState.resumed) _wakeUpAt(null, clock.now());+ _changed();+ }++ void _changed() {+ if (mounted) setState(() {});+ }++ /// One wake-up at the next threshold, kept while it stays the next: no+ /// snapshot arrives to draw the line when it is crossed.+ void _wakeUpAt(DateTime? at, DateTime now) {+ final lifecycle = WidgetsBinding.instance.lifecycleState;+ final next =+ !_enabled ||+ (lifecycle != null && lifecycle != AppLifecycleState.resumed)+ ? null+ : at;+ if (next == _wakeAt && (next == null || _timer?.isActive == true)) return;+ _timer?.cancel();+ _wakeAt = next;+ if (next != null) _timer = Timer(next.difference(now), _changed);+ }++ @override+ void dispose() {+ _timer?.cancel();+ _source.removeListener(_changed);+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final c = widget.conversation, message = widget.message;+ final reader = c.reader, snapshot = reader.snapshot, group = c.conversation;+ final delivery = message.receiptDelivery;+ final agent = delivery == null ? null : snapshot?.agent(delivery.agentId);+ final now = clock.now();+ // Said only of a recipient of this chat, from what was just read: a row+ // kept from before, or the Swarm out of reach, says nothing of where it is.+ if (snapshot == null ||+ delivery?.status != 'queued' ||+ agent == null ||+ group == null ||+ !(group.agentIds.contains(agent.id) || group.leadId == agent.id) ||+ reader.error != null ||+ !c.receiptCurrent(message)) {+ _wakeUpAt(null, now);+ return const SizedBox.shrink();+ }+ final name = snapshot.agentName(agent.id, fallback: 'Lead');+ final machine = snapshot.pool(agent.machineId);+ final observation = machine?['observation'];+ final receivedAt = observation is Map ? observation['receivedAt'] : null;+ final readingAt = receivedAt is num+ ? DateTime.fromMillisecondsSinceEpoch(receivedAt.toInt())+ : null;+ final offline =+ machine != null &&+ (readingAt == null ||+ now.difference(readingAt) >= _machineOfflineAfter);+ final failingSince = delivery!.claimFailingSince;+ final failingAt = failingSince?.add(swarmClaimFailingNotice);+ final queuedAt = message.createdAt?.add(swarmQueuedNotice);+ final waiting = !offline && agent.downSince == null;+ final stuck =+ waiting &&+ ((failingAt != null && !failingAt.isAfter(now)) ||+ (queuedAt != null && !queuedAt.isAfter(now)));+ // The earlier of the two is the next to cross.+ final upcoming = [+ failingAt,+ queuedAt,+ ].whereType<DateTime>().where((t) => t.isAfter(now));+ _wakeUpAt(+ waiting && !stuck && upcoming.isNotEmpty+ ? upcoming.reduce((a, b) => a.isBefore(b) ? a : b)+ : null,+ now,+ );+ if (!offline && !stuck) return const SizedBox.shrink();+ final host = machine?['name'] as String? ?? "$name's computer";+ final String title, note;+ if (offline) {+ title = "$name's computer is offline";+ note = readingAt == null+ ? "$host is offline. Your message goes in when it's back online."+ : "$host was last seen ${swarmAgo(now.difference(readingAt))}. "+ "Your message goes in when it's back online.";+ } else {+ title = 'Not delivered yet';+ note = failingSince != null+ ? "$host is online but couldn't take this message yet. "+ 'Harness keeps trying, and it goes in as soon as it can.'+ : "$host is online but hasn't picked this message up yet. "+ 'Harness keeps trying, and it goes in as soon as it can.';+ }+ final color = AppPalette.warn;+ return Padding(+ padding: const EdgeInsets.only(top: AppSpace.xs),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Semantics(+ liveRegion: true,+ child: Row(+ children: [+ Icon(+ offline ? LucideIcons.cloudOff : LucideIcons.clock,+ size: 16,+ color: color,+ ),+ const SizedBox(width: AppSpace.xs),+ Flexible(+ child: Text(title, style: swarmChatText(14, color: color)),+ ),+ ],+ ),+ ),+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.xs),+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: color.withValues(alpha: .09),+ borderRadius: BorderRadius.circular(AppCard.insetRadius),+ ),+ child: Padding(+ padding: const EdgeInsets.all(AppSpace.s),+ child: SizedBox(+ width: double.infinity,+ child: Text(+ note,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.45,+ ),+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dartindex 21687d44c..897b5954a 100644--- a/mobile/lib/swarm/swarm_message_row.dart+++ b/mobile/lib/swarm/swarm_message_row.dart@@ -302,6 +302,7 @@ class SwarmMessageRow extends StatelessWidget {this.reactions,this.thread,this.below,+ this.receipt,this.card,this.onLongPress,});@@ -357,6 +358,10 @@ class SwarmMessageRow extends StatelessWidget {/// PM's private line answered in the project chat.final Widget? below;+ /// Under all that: where the delivery of the person's newest message stands+ /// (swarm_message_receipt.dart); null for every other message.+ final Widget? receipt;+/// Opens its long-press sheet: reactions, Copy link to message.final VoidCallback? onLongPress;@@ -445,6 +450,7 @@ class SwarmMessageRow extends StatelessWidget {?reactions,?thread,?below,+ ?receipt,if (actions)Padding(padding: const EdgeInsets.only(top: AppSpace.s),diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dartindex 5c71ad60d..0de700099 100644--- a/mobile/test/swarm/swarm_chat_test.dart+++ b/mobile/test/swarm/swarm_chat_test.dart@@ -3473,4 +3473,96 @@ void main() {expect(key('swarm-attach'), findsNothing);});});+ group('the delivery line under the newest own message', () {+ final queued = {'id': 'd1', 'agentId': 'agent-lead', 'status': 'queued'};+ final claimed = {...queued, 'status': 'claimed'};+ const notDelivered = 'Not delivered yet';++ Map<String, dynamic> mine(+ String id,+ int sequence, {+ String? thread,+ Object? delivery,+ }) => {+ ...message(id, sequence, author: me, thread: thread, minute: sequence),+ 'deliveries': [?delivery],+ };++ Future<SwarmHost> open(WidgetTester tester, FakeSwarm fake) async {+ final host = await pump(tester, fake);+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();+ return host;+ }++ testWidgets('only the person\'s newest message carries it', (tester) async {+ await open(+ tester,+ backend([+ mine('m1', 1, delivery: queued),+ {+ ...message('m2', 2, text: 'On it', minute: 2),+ 'deliveries': [queued],+ },+ mine('m3', 3, delivery: queued),+ message('m4', 4, text: 'Still here', minute: 4),+ ]),+ );++ expect(key('swarm-message-receipt-m3'), findsOneWidget);+ expect(key('swarm-message-receipt-m1'), findsNothing);+ expect(key('swarm-message-receipt-m2'), findsNothing);+ expect(find.text(notDelivered), findsOneWidget);+ expect(find.textContaining("River's computer is online"), findsOneWidget);+ });++ testWidgets('a delivery claimed clears it, its own row alone', (+ tester,+ ) async {+ final page = [mine('m1', 1), mine('m2', 2, delivery: queued)];+ final fake = backend(page);+ var answer = page.last;+ fake.routes['$messages?messageId='] = (_) => {+ 'messages': [answer],+ };+ final host = await open(tester, fake);+ expect(find.text(notDelivered), findsOneWidget);++ answer = mine('m2', 2, delivery: claimed);+ await tester.pump(const Duration(seconds: 30));+ final built = await rowsBuilt(() async {+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();+ });++ expect(built, ['m2']);+ expect(find.text(notDelivered), findsNothing);+ expect(key('swarm-message-receipt-m2'), findsNothing);+ });++ testWidgets('sign-out while it shows: nothing of it stays', (tester) async {+ await open(tester, backend([mine('m1', 1, delivery: queued)]));+ expect(find.text(notDelivered), findsOneWidget);++ account.value = null;+ await frames(tester);++ expect(find.text(notDelivered), findsNothing);+ expect(find.textContaining('River'), findsNothing);+ });++ testWidgets('a newest own reply only in its thread leaves the chat quiet', (+ tester,+ ) async {+ await open(+ tester,+ backend([+ mine('m1', 1, delivery: queued),+ message('m2', 2, text: 'Root', minute: 2),+ mine('m3', 3, thread: 'm2', delivery: queued),+ ]),+ );+ expect(find.text(notDelivered), findsNothing);+ });+ });}diff --git a/mobile/test/swarm/swarm_message_receipt_shots_test.dart b/mobile/test/swarm/swarm_message_receipt_shots_test.dartnew file mode 100644index 000000000..95b01a9fb--- /dev/null+++ b/mobile/test/swarm/swarm_message_receipt_shots_test.dart@@ -0,0 +1,206 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Review screenshots of the delivery line in the real chat, 390 and 320 points+/// wide in both phone themes, from made-up data, to the folder+/// `SWARM_RECEIPT_SHOTS` names: claims failing, nothing picked up yet, and the+/// computer offline.+final shots = Platform.environment['SWARM_RECEIPT_SHOTS'];++void main() {+ setUpAll(() async {+ if (shots == null || !Platform.isMacOS) return;+ final sf = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {+ await (FontLoader(family)..addFont(Future.value(sf))).load();+ }+ final mono = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {+ await (FontLoader(family)..addFont(Future.value(mono))).load();+ }+ final manifest =+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;+ for (final entry in manifest.cast<Map<String, dynamic>>()) {+ final loader = FontLoader(entry['family'] as String);+ for (final font in (entry['fonts'] as List).cast<Map>()) {+ loader.addFont(rootBundle.load(font['asset'] as String));+ }+ await loader.load();+ }+ });++ testWidgets('the delivery line, in both phone themes and both widths', (+ tester,+ ) async {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ 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;+ for (final width in [390.0, 320.0]) {+ await tester.binding.setSurfaceSize(Size(width, 560));+ for (final state in ['failing', 'waiting', 'offline']) {+ final now = clock.now();+ DateTime ago(Duration age) => now.subtract(age);+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'OpenHarness', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Pilot',+ agentIds: ['agent-lead'],+ leadId: 'agent-lead',+ lastMessageSequence: 2,+ ),+ ],+ agents: [agent('agent-lead', name: 'Lead', displayName: 'River')],+ machines: [+ {+ 'machineId': 'mac-1',+ 'name': 'Team Mac',+ 'contributorId': me,+ 'observation': {+ 'receivedAt':+ (state == 'offline'+ ? ago(const Duration(minutes: 3))+ : now)+ .millisecondsSinceEpoch,+ },+ },+ ],+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[messages] = (_) => {+ 'messages': [+ {+ 'id': 'm2',+ 'conversationId': 'g1',+ 'text': 'Can you check the build on the release branch?',+ 'sequence': 2,+ 'author': {'kind': 'person', 'id': me, 'name': 'tony'},+ 'deliveries': [+ {+ 'id': 'd1',+ 'agentId': 'agent-lead',+ 'status': 'queued',+ if (state == 'failing')+ 'claimFailingSince': ago(const Duration(minutes: 2))+ .toUtc()+ .toIso8601String(),+ },+ ],+ 'createdAt': ago(const Duration(minutes: 3))+ .toUtc()+ .toIso8601String(),+ },+ {+ 'id': 'm1',+ 'conversationId': 'g1',+ 'text': 'The pilot build is ready to try.',+ 'sequence': 1,+ 'author': {+ 'kind': 'agent',+ 'id': 'agent-lead',+ 'name': 'River',+ },+ 'createdAt': ago(const Duration(minutes: 20))+ .toUtc()+ .toIso8601String(),+ },+ ],+ 'next': null,+ };+ final host = SwarmHost(+ accountId: () => me,+ account: ValueNotifier<String?>(me),+ request: fake.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (_, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmConversationPage(+ swarmId: tab,+ conversationId: 'g1',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();+ expect(+ find.text(+ state == 'offline'+ ? "River's computer is offline"+ : 'Not delivered yet',+ ),+ findsOneWidget,+ );+ expect(tester.takeException(), isNull);+ await tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File(+ '$shots/phone-receipt-$state-${brightness.name}-${width.toInt()}.png',+ ).writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ await tester.pumpWidget(const SizedBox());+ host.dispose();+ await tester.pump(const Duration(minutes: 1));+ }+ }+ }+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_message_receipt_test.dart b/mobile/test/swarm/swarm_message_receipt_test.dartnew file mode 100644index 000000000..a041f9db5--- /dev/null+++ b/mobile/test/swarm/swarm_message_receipt_test.dart@@ -0,0 +1,1212 @@+import 'dart:async';++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_message_receipt.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import 'swarm_fixture.dart';++/// The line under the person's newest message while its delivery is queued and+/// not getting in (Desktop's #2336), and the one read that keeps it honest: the+/// chat's own reads never see a delivery change.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const exact = '$messages?messageId=';+ const couldntTake =+ "Team Mac is online but couldn't take this message yet. Harness keeps trying, and it goes in as soon as it can.";+ const notPickedUp =+ "Team Mac is online but hasn't picked this message up yet. Harness keeps trying, and it goes in as soon as it can.";++ Map<String, dynamic> delivery({+ String status = 'queued',+ String agentId = 'agent-lead',+ DateTime? failingSince,+ }) => {+ 'id': 'd1',+ 'agentId': agentId,+ 'status': status,+ 'claimFailingSince': ?failingSince?.toUtc().toIso8601String(),+ };++ Map<String, dynamic> own(+ String id,+ int sequence, {+ required DateTime at,+ List<Map<String, dynamic>> deliveries = const [],+ String conversationId = 'g1',+ }) => {+ 'id': id,+ 'conversationId': conversationId,+ 'text': 'Please start',+ 'sequence': sequence,+ 'author': {'kind': 'person', 'id': me, 'name': 'tony'},+ 'deliveries': deliveries,+ 'createdAt': at.toUtc().toIso8601String(),+ };++ Map<String, dynamic> machine(+ String id, {+ String name = 'Team Mac',+ DateTime? readAt,+ }) => {+ 'machineId': id,+ 'name': name,+ 'contributorId': me,+ if (readAt != null)+ 'observation': {'receivedAt': readAt.millisecondsSinceEpoch},+ };++ /// A Swarm where chat g1 holds [page], the Lead on [machines]; every read of+ /// one message answers [answer], [page] until it is set.+ ({FakeSwarm swarm, SwarmReader reader}) rig({+ required List<Map<String, dynamic>> page,+ List<Map<String, dynamic>>? machines,+ List<Map<String, dynamic>>? agents,+ FutureOr<Object?> Function(Map<String, dynamic>? body)? answer,+ }) {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ agentIds: const ['agent-lead'],+ leadId: 'agent-lead',+ lastMessageSequence: page.first['sequence'] as int,+ ),+ ],+ agents: agents ?? [agent('agent-lead', name: 'Lead')],+ machines: machines ?? [machine('mac-1', readAt: clock.now())],+ ),+ };+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ swarm.routes[messages] = (_) => {'messages': page, 'next': null};+ swarm.routes[exact] =+ answer ?? (_) => {'messages': page.take(1).toList(), 'next': null};+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ addTearDown(reader.dispose);+ return (swarm: swarm, reader: reader);+ }++ Future<SwarmConversation> open(SwarmReader reader) async {+ await reader.refresh();+ final c = SwarmConversation(reader, 'g1');+ addTearDown(c.dispose);+ await c.load();+ return c;+ }++ /// One read of the Swarm, and what it set off answered.+ Future<void> tick(({FakeSwarm swarm, SwarmReader reader}) r) async {+ await r.reader.refresh();+ await pumpEventQueue();+ }++ int reads(FakeSwarm swarm) =>+ swarm.paths.where((path) => path.startsWith(exact)).length;++ group('reading the newest own message again', () {+ late DateTime now;+ late Clock moved;+ setUp(() {+ now = DateTime.utc(2026, 10, 30, 9);+ moved = Clock(() => now);+ });++ test('asks at the Swarm\'s reads, at most every 30 seconds', () {+ return withClock(moved, () async {+ final r = rig(+ page: [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ],+ );+ final c = await open(r.reader);+ expect(reads(r.swarm), 0);++ await tick(r);+ expect(reads(r.swarm), 1);+ expect(r.swarm.paths.last, '${exact}m1');+ expect(c.receiptCurrent(c.latestOwn!), isTrue);++ now = now.add(const Duration(seconds: 29));+ await tick(r);+ expect(reads(r.swarm), 1, reason: 'under 30 seconds');++ now = now.add(const Duration(seconds: 1));+ await tick(r);+ expect(reads(r.swarm), 2);+ });+ });++ test('stops once the delivery is claimed, and the row takes the claim', () {+ return withClock(moved, () async {+ final queued = own('m1', 1, at: now, deliveries: [delivery()]);+ var status = 'queued';+ final r = rig(+ page: [queued],+ answer: (_) => {+ 'messages': [+ {+ ...queued,+ 'deliveries': [delivery(status: status)],+ },+ ],+ },+ );+ final c = await open(r.reader);+ await tick(r);+ expect(c.latestOwn!.receiptDelivery!.status, 'queued');++ status = 'claimed';+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ expect(reads(r.swarm), 2);+ expect(c.latestOwn!.receiptDelivery!.status, 'claimed');++ now = now.add(const Duration(minutes: 5));+ await tick(r);+ expect(reads(r.swarm), 2, reason: 'claimed: nothing more to ask');+ });+ });++ test('stops after 10 minutes on screen, and the line stays as read', () {+ return withClock(moved, () async {+ final r = rig(+ page: [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ],+ );+ final c = await open(r.reader);+ await tick(r);+ for (var i = 0; i < 19; i++) {+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ }+ final asked = reads(r.swarm);+ expect(asked, 20);++ for (var i = 0; i < 10; i++) {+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ }+ expect(reads(r.swarm), asked, reason: 'past the 10 minutes');+ expect(c.receiptCurrent(c.latestOwn!), isTrue);+ });+ });++ test('never asks in the background, and asks anew once back', () {+ return withClock(moved, () async {+ final r = rig(+ page: [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ],+ );+ final c = await open(r.reader);+ await tick(r);+ expect(reads(r.swarm), 1);++ c.shown = false;+ for (var i = 0; i < 40; i++) {+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ }+ expect(reads(r.swarm), 1, reason: 'off screen nothing asks');++ c.shown = true;+ expect(+ c.receiptCurrent(c.latestOwn!),+ isFalse,+ reason: 'what it read before the background is not believed',+ );+ await tick(r);+ expect(reads(r.swarm), 2);+ expect(c.receiptCurrent(c.latestOwn!), isTrue);+ });+ });++ test('asks only for the person\'s own newest, and only while queued', () {+ return withClock(moved, () async {+ final r = rig(+ page: [+ {+ ...own('m3', 3, at: now),+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},+ 'deliveries': [delivery()],+ },+ own(+ 'm2',+ 2,+ at: now,+ deliveries: [delivery(status: 'delivered')],+ ),+ own('m1', 1, at: now, deliveries: [delivery()]),+ ],+ );+ final c = await open(r.reader);+ await tick(r);+ expect(c.latestOwn!.id, 'm2');+ expect(reads(r.swarm), 0);+ });+ });++ test(+ 'a failed read proves nothing, is retried at 30 seconds, and recovers',+ () {+ return withClock(moved, () async {+ final page = [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ];+ var failing = true;+ final r = rig(+ page: page,+ answer: (_) => failing+ ? throw const SuperTabFailure('SWARM_BUSY', 'Busy')+ : {'messages': page},+ );+ final c = await open(r.reader);+ await tick(r);+ expect(reads(r.swarm), 1);+ expect(c.receiptCurrent(c.latestOwn!), isFalse);+ expect(c.error, isNull, reason: 'the chat itself reads on');++ now = now.add(const Duration(seconds: 5));+ await tick(r);+ expect(+ reads(r.swarm),+ 1,+ reason: 'bounded: no retry before 30 seconds',+ );++ failing = false;+ now = now.add(const Duration(seconds: 25));+ await tick(r);+ expect(reads(r.swarm), 2);+ expect(c.receiptCurrent(c.latestOwn!), isTrue);+ });+ },+ );++ test('a read that is not this message of this chat proves nothing', () {+ return withClock(moved, () async {+ final page = [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ];+ var answer = <Map<String, dynamic>>[];+ final r = rig(page: page, answer: (_) => {'messages': answer});+ final c = await open(r.reader);++ await tick(r);+ expect(c.receiptCurrent(c.latestOwn!), isFalse, reason: 'empty answer');++ answer = [+ own(+ 'm1',+ 1,+ at: now,+ conversationId: 'private-chat',+ deliveries: [delivery(status: 'claimed')],+ ),+ ];+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ expect(c.receiptCurrent(c.latestOwn!), isFalse, reason: 'another chat');+ expect(c.latestOwn!.receiptDelivery!.status, 'queued');+ });+ });++ for (final code in ['FORBIDDEN', 'NOT_FOUND']) {+ test('$code: the chat is lost and nothing of it stays', () {+ return withClock(moved, () async {+ final r = rig(+ page: [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ],+ answer: (_) => throw SuperTabFailure(code, 'Not available'),+ );+ final c = await open(r.reader);+ await tick(r);+ expect(c.messages, isEmpty);+ expect(c.state, SwarmChatState.lost);+ expect(c.latestOwn, isNull);+ });+ });+ }++ test('an answer or a refusal after access ended changes nothing', () {+ return withClock(moved, () async {+ final late_ = Completer<Object?>();+ final page = [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ];+ final r = rig(page: page, answer: (_) => late_.future);+ final c = await open(r.reader);+ await tick(r);+ expect(reads(r.swarm), 1);++ r.reader.revoke();+ expect(c.messages, isEmpty);+ late_.completeError(+ const SuperTabFailure('FORBIDDEN', 'Not available'),+ );+ await pumpEventQueue();+ expect(c.messages, isEmpty);+ expect(c.error, isNull, reason: 'it says nothing of a chat let go');+ });+ });++ test('an answer after the chat closed tells no one', () {+ return withClock(moved, () async {+ final late_ = Completer<Object?>();+ final queued = own('m1', 1, at: now, deliveries: [delivery()]);+ final r = rig(page: [queued], answer: (_) => late_.future);+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g1');+ await c.load();+ await tick(r);+ expect(reads(r.swarm), 1);++ c.dispose();+ late_.complete({+ 'messages': [+ {+ ...queued,+ 'deliveries': [delivery(status: 'claimed')],+ },+ ],+ });+ await pumpEventQueue();+ });+ });++ test('an answer asked before the background is not believed after it', () {+ return withClock(moved, () async {+ final late_ = Completer<Object?>();+ final queued = own('m1', 1, at: now, deliveries: [delivery()]);+ final r = rig(page: [queued], answer: (_) => late_.future);+ final c = await open(r.reader);+ await tick(r);++ c.shown = false;+ c.shown = true;+ late_.complete({+ 'messages': [+ {+ ...queued,+ 'deliveries': [delivery(status: 'claimed')],+ },+ ],+ });+ await pumpEventQueue();+ expect(c.latestOwn!.receiptDelivery!.status, 'queued');+ expect(c.receiptCurrent(c.latestOwn!), isFalse);+ });+ });++ test('past the 10 minutes a newer message reads it once more', () {+ return withClock(moved, () async {+ final queued = own('m1', 1, at: now, deliveries: [delivery()]);+ final page = [queued];+ var status = 'queued';+ final r = rig(+ page: page,+ answer: (_) => {+ 'messages': [+ {+ ...queued,+ 'deliveries': [delivery(status: status)],+ },+ ],+ },+ );+ final c = await open(r.reader);+ await tick(r);+ now = now.add(const Duration(minutes: 11));+ await tick(r);+ final asked = reads(r.swarm);+ expect(asked, 1, reason: 'past the 10 minutes');++ // Still queued: one read for it, and none again until another comes.+ page.insert(0, {+ ...own('m2', 2, at: now),+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},+ });+ await c.load();+ await tick(r);+ expect(reads(r.swarm), asked + 1);+ now = now.add(const Duration(minutes: 1));+ await tick(r);+ expect(reads(r.swarm), asked + 1, reason: 'that message is read once');++ status = 'claimed';+ page.insert(0, {+ ...own('m3', 3, at: now),+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},+ });+ await c.load();+ await tick(r);+ expect(reads(r.swarm), asked + 2);+ expect(c.latestOwn!.receiptDelivery!.status, 'claimed');+ });+ });++ test('a newer message waits for the 30 seconds too', () {+ return withClock(moved, () async {+ final page = [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ];+ final r = rig(page: page);+ final c = await open(r.reader);+ await tick(r);+ expect(reads(r.swarm), 1);++ page.insert(0, {+ ...own('m2', 2, at: now),+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},+ });+ await c.load();+ await tick(r);+ expect(reads(r.swarm), 1, reason: 'under 30 seconds');+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ expect(reads(r.swarm), 2);+ });+ });++ test(+ 'a by-id answer asked before the chat\'s newer read keeps the newer',+ () {+ return withClock(moved, () async {+ final late_ = Completer<Object?>();+ final queued = own('m1', 1, at: now, deliveries: [delivery()]);+ final claimed = {+ ...queued,+ 'deliveries': [delivery(status: 'claimed')],+ };+ final r = rig(page: [queued], answer: (_) => late_.future);+ final c = await open(r.reader);+ await tick(r);+ expect(reads(r.swarm), 1);++ // The chat's read is asked after the by-id one, and lands first.+ r.swarm.routes[messages] = (_) => {+ 'messages': [claimed],+ 'next': null,+ };+ await c.load();+ expect(c.latestOwn!.receiptDelivery!.status, 'claimed');++ late_.complete({+ 'messages': [queued],+ });+ await pumpEventQueue();+ expect(c.latestOwn!.receiptDelivery!.status, 'claimed');+ });+ },+ );++ test(+ 'the chat\'s read asked before a by-id answer does not put it back',+ () {+ return withClock(moved, () async {+ final late_ = Completer<Object?>();+ final queued = own('m1', 1, at: now, deliveries: [delivery()]);+ final r = rig(+ page: [queued],+ answer: (_) => {+ 'messages': [+ {+ ...queued,+ 'deliveries': [delivery(status: 'claimed')],+ },+ ],+ },+ );+ final c = await open(r.reader);++ r.swarm.routes[messages] = (_) => late_.future;+ final page = c.load();+ await tick(r);+ expect(reads(r.swarm), 1);+ expect(c.latestOwn!.receiptDelivery!.status, 'claimed');++ late_.complete({+ 'messages': [queued],+ 'next': null,+ });+ await page;+ expect(c.latestOwn!.receiptDelivery!.status, 'claimed');+ });+ },+ );++ test(+ 'an answer for the message before a newer own one is not the newer',+ () {+ return withClock(moved, () async {+ final late_ = Completer<Object?>();+ final first = own('m1', 1, at: now, deliveries: [delivery()]);+ final page = [first];+ final r = rig(page: page, answer: (_) => late_.future);+ final c = await open(r.reader);+ await tick(r);++ page.insert(0, own('m2', 2, at: now, deliveries: [delivery()]));+ await c.load();+ // No read of it yet: it arrived while the other's was under way.+ await c.load();+ late_.complete({+ 'messages': [first],+ });+ await pumpEventQueue();+ expect(c.receiptCurrent(c.messages.last), isFalse);+ });+ },+ );+ });++ group('the line', () {+ /// [rigged]'s newest own message in the tree, as the chat draws it.+ Future<SwarmConversation> show(+ WidgetTester tester,+ ({FakeSwarm swarm, SwarmReader reader}) rigged,+ ) async {+ final c = await open(rigged.reader);+ await rigged.reader.refresh();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: ListenableBuilder(+ listenable: c,+ builder: (_, _) => switch (c.latestOwn) {+ final m? => SwarmMessageReceipt(conversation: c, message: m),+ null => const SizedBox.shrink(),+ },+ ),+ ),+ ),+ );+ await tester.pump();+ return c;+ }++ /// Let go of the tree: a wake-up left pending fails the test.+ Future<void> close(WidgetTester tester) async {+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ }++ testWidgets('claims failing for a minute read Not delivered yet', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(seconds: 70)),+ deliveries: [+ delivery(+ failingSince: now.subtract(const Duration(seconds: 61)),+ ),+ ],+ ),+ ],+ ),+ );+ expect(find.text('Not delivered yet'), findsOneWidget);+ expect(find.text(couldntTake), findsOneWidget);+ expect(find.text('Send again'), findsNothing);+ expect(find.byType(TextButton), findsNothing);+ await close(tester);+ });++ testWidgets('an older backend: two minutes waiting reads it, in amber', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 2, seconds: 1)),+ deliveries: [delivery()],+ ),+ ],+ ),+ );+ expect(find.text('Not delivered yet'), findsOneWidget);+ expect(find.text(notPickedUp), findsOneWidget);+ await close(tester);+ });++ testWidgets('offline still wins, in Desktop\'s words', (tester) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ machines: [+ machine('mac-1', readAt: now.subtract(const Duration(minutes: 3))),+ ],+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 5)),+ deliveries: [+ delivery(+ failingSince: now.subtract(const Duration(minutes: 5)),+ ),+ ],+ ),+ ],+ ),+ );+ expect(find.text("Lead's computer is offline"), findsOneWidget);+ expect(+ find.text(+ "Team Mac was last seen 3 min ago. Your message goes in when it's back online.",+ ),+ findsOneWidget,+ );+ expect(find.text('Not delivered yet'), findsNothing);+ await close(tester);+ });++ testWidgets('a machine with no reading is offline, with no last seen', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ machines: [machine('mac-1')],+ page: [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ],+ ),+ );+ expect(find.text("Lead's computer is offline"), findsOneWidget);+ expect(+ find.text(+ "Team Mac is offline. Your message goes in when it's back online.",+ ),+ findsOneWidget,+ );+ await close(tester);+ });++ testWidgets(+ 'a machine going quiet turns the line offline at the next read',+ (tester) async {+ final now = clock.now();+ final r = rig(+ machines: [machine('mac-1', readAt: now)],+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 3)),+ deliveries: [delivery()],+ ),+ ],+ );+ await show(tester, r);+ expect(find.text('Not delivered yet'), findsOneWidget);++ await tester.pump(const Duration(seconds: 36));+ await r.reader.refresh();+ await tester.pump();+ expect(find.text("Lead's computer is offline"), findsOneWidget);+ expect(find.text('Not delivered yet'), findsNothing);+ await close(tester);+ },+ );++ testWidgets('a stopped recipient shows no Not delivered yet', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ agents: [+ {+ ...agent('agent-lead', name: 'Lead'),+ 'downSince': now+ .subtract(const Duration(minutes: 10))+ .toUtc()+ .toIso8601String(),+ },+ ],+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 5)),+ deliveries: [+ delivery(+ failingSince: now.subtract(const Duration(minutes: 5)),+ ),+ ],+ ),+ ],+ ),+ );+ expect(find.text('Not delivered yet'), findsNothing);+ await close(tester);+ });++ testWidgets('a claimed delivery carries no line, offline or not', (+ tester,+ ) async {+ final now = clock.now();+ final queued = own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 5)),+ deliveries: [+ delivery(failingSince: now.subtract(const Duration(minutes: 5))),+ ],+ );+ await show(+ tester,+ rig(+ machines: [+ machine('mac-1', readAt: now.subtract(const Duration(minutes: 3))),+ ],+ page: [queued],+ answer: (_) => {+ 'messages': [+ {+ ...queued,+ 'deliveries': [+ delivery(+ status: 'claimed',+ failingSince: now.subtract(const Duration(minutes: 5)),+ ),+ ],+ },+ ],+ },+ ),+ );+ expect(find.text('Not delivered yet'), findsNothing);+ expect(find.text("Lead's computer is offline"), findsNothing);+ await close(tester);+ });++ testWidgets('it clears when the delivery is claimed', (tester) async {+ final now = clock.now();+ final message = own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 3)),+ deliveries: [delivery()],+ );+ var status = 'queued';+ final r = rig(+ page: [message],+ answer: (_) => {+ 'messages': [+ {+ ...message,+ 'deliveries': [delivery(status: status)],+ },+ ],+ },+ );+ await show(tester, r);+ expect(find.text('Not delivered yet'), findsOneWidget);++ status = 'claimed';+ await tester.pump(const Duration(seconds: 30));+ await r.reader.refresh();+ await tester.pump();+ expect(find.text('Not delivered yet'), findsNothing);+ await close(tester);+ });++ testWidgets('it wakes once at the threshold, with no timer churn', (+ tester,+ ) async {+ final now = clock.now();+ final r = rig(+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 1, seconds: 50)),+ deliveries: [delivery()],+ ),+ ],+ );+ await show(tester, r);+ expect(find.text('Not delivered yet'), findsNothing);++ var built = 0;+ final before = debugOnRebuildDirtyWidget;+ debugOnRebuildDirtyWidget = (element, _) {+ if (element.widget is SwarmMessageReceipt) built++;+ };+ addTearDown(() => debugOnRebuildDirtyWidget = before);++ await tester.pump(const Duration(seconds: 9));+ expect(built, 0, reason: 'nothing draws it before the threshold');+ expect(find.text('Not delivered yet'), findsNothing);++ await tester.pump(const Duration(seconds: 2));+ expect(built, 1, reason: 'one wake-up');+ expect(find.text('Not delivered yet'), findsOneWidget);++ await tester.pump(const Duration(minutes: 5));+ expect(built, 1, reason: 'crossed: no more wake-ups');+ debugOnRebuildDirtyWidget = before;+ await close(tester);+ });++ testWidgets('the first of the two thresholds wakes it, in its words', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ page: [+ own(+ 'm1',+ 1,+ at: now,+ deliveries: [+ delivery(+ failingSince: now.subtract(const Duration(seconds: 50)),+ ),+ ],+ ),+ ],+ ),+ );+ expect(find.text('Not delivered yet'), findsNothing);+ await tester.pump(const Duration(seconds: 11));+ expect(find.text(couldntTake), findsOneWidget);+ await close(tester);+ });++ testWidgets('queued for minutes keeps its line when claims start to fail', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 5)),+ deliveries: [+ delivery(+ failingSince: now.subtract(const Duration(seconds: 10)),+ ),+ ],+ ),+ ],+ ),+ );+ expect(find.text(couldntTake), findsOneWidget);+ await close(tester);+ });++ testWidgets(+ 'away from the front no wake-up waits; back, the line is drawn',+ (tester) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ // No reading to age: the minute away is not a machine going quiet.+ machines: const [],+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 1, seconds: 50)),+ deliveries: [delivery()],+ ),+ ],+ ),+ );+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ // Inactive still draws frames, so a wake-up left waiting would show.+ tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.inactive,+ );+ await tester.pump();++ var built = 0;+ final before = debugOnRebuildDirtyWidget;+ debugOnRebuildDirtyWidget = (element, _) {+ if (element.widget is SwarmMessageReceipt) built++;+ };+ addTearDown(() => debugOnRebuildDirtyWidget = before);+ await tester.pump(const Duration(minutes: 1));+ expect(built, 0, reason: 'no timer fires away from the front');+ expect(find.text('Not delivered yet'), findsNothing);+ debugOnRebuildDirtyWidget = before;++ tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ );+ await tester.pump();+ expect(find.text('Not delivered yet'), findsOneWidget);+ await close(tester);+ },+ );++ testWidgets('the Swarm out of reach says nothing, and comes back', (+ tester,+ ) async {+ final now = clock.now();+ final r = rig(+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 3)),+ deliveries: [delivery()],+ ),+ ],+ );+ await show(tester, r);+ expect(find.text('Not delivered yet'), findsOneWidget);++ final good = r.swarm.routes['/api/super-tabs/$tab/changes']!;+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) =>+ throw const SuperTabFailure('NETWORK', 'No connection');+ await r.reader.refresh();+ await tester.pump();+ expect(r.reader.error, isNotNull);+ expect(find.text('Not delivered yet'), findsNothing);++ r.swarm.routes['/api/super-tabs/$tab/changes'] = good;+ await r.reader.refresh();+ await tester.pump();+ expect(r.reader.error, isNull);+ expect(find.text('Not delivered yet'), findsOneWidget);+ await close(tester);+ });++ testWidgets('access revoked while it shows: the line goes, nothing waits', (+ tester,+ ) async {+ final now = clock.now();+ final r = rig(+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 3)),+ deliveries: [delivery()],+ ),+ ],+ );+ final c = await show(tester, r);+ expect(find.text('Not delivered yet'), findsOneWidget);++ r.reader.revoke();+ await tester.pump();+ expect(c.messages, isEmpty);+ expect(find.text('Not delivered yet'), findsNothing);+ expect(find.textContaining('Team Mac'), findsNothing);+ await close(tester);+ });++ testWidgets('an agent who is no recipient of this chat is never named', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ agents: [+ agent('agent-lead', name: 'Lead'),+ {+ ...agent('agent-secret', name: 'Secret', machineId: 'mac-2'),+ 'projectId': 'project-other',+ },+ ],+ machines: [+ machine('mac-1', readAt: now),+ machine('mac-2', name: 'Private Mac'),+ ],+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 3)),+ deliveries: [delivery(agentId: 'agent-secret')],+ ),+ ],+ ),+ );+ expect(find.textContaining('Secret'), findsNothing);+ expect(find.textContaining('Private Mac'), findsNothing);+ expect(find.text('Not delivered yet'), findsNothing);+ await close(tester);+ });++ testWidgets('an unknown agent shows nothing and does not throw', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 3)),+ deliveries: [delivery(agentId: 'agent-ghost')],+ ),+ ],+ ),+ );+ expect(find.text('Not delivered yet'), findsNothing);+ await close(tester);+ });++ testWidgets('a name reused in another project does not lend its machine', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ agents: [+ agent('agent-lead', name: 'Lead'),+ {+ ...agent('agent-twin', name: 'Lead', machineId: 'mac-2'),+ 'projectId': 'project-other',+ },+ ],+ machines: [+ machine('mac-1', readAt: now),+ machine('mac-2', name: 'Other Mac'),+ ],+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 3)),+ deliveries: [delivery()],+ ),+ ],+ ),+ );+ expect(find.text('Not delivered yet'), findsOneWidget);+ expect(find.text(notPickedUp), findsOneWidget);+ expect(find.textContaining('Other Mac'), findsNothing);+ await close(tester);+ });++ testWidgets('a machine this reader cannot see is called by its agent', (+ tester,+ ) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ machines: const [],+ page: [+ own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 3)),+ deliveries: [delivery()],+ ),+ ],+ ),+ );+ expect(find.text('Not delivered yet'), findsOneWidget);+ expect(find.textContaining("Lead's computer is online"), findsOneWidget);+ expect(find.textContaining('mac-1'), findsNothing);+ await close(tester);+ });++ testWidgets('past the 10 minutes the agent\'s answer clears the line', (+ tester,+ ) async {+ final now = clock.now();+ final queued = own(+ 'm1',+ 1,+ at: now.subtract(const Duration(minutes: 3)),+ deliveries: [delivery()],+ );+ final page = [queued];+ var status = 'queued';+ final r = rig(+ machines: const [],+ page: page,+ answer: (_) => {+ 'messages': [+ {+ ...queued,+ 'deliveries': [delivery(status: status)],+ },+ ],+ },+ );+ final c = await show(tester, r);+ expect(find.text('Not delivered yet'), findsOneWidget);++ await tester.pump(const Duration(minutes: 11));+ await r.reader.refresh();+ await tester.pump();+ expect(find.text('Not delivered yet'), findsOneWidget);++ status = 'answered';+ page.insert(0, {+ ...own('m2', 2, at: clock.now()),+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},+ });+ await c.load();+ await r.reader.refresh();+ await tester.pump();+ expect(find.text('Not delivered yet'), findsNothing);+ await close(tester);+ });++ testWidgets('below the thresholds nothing takes room', (tester) async {+ final now = clock.now();+ await show(+ tester,+ rig(+ page: [+ own('m1', 1, at: now, deliveries: [delivery()]),+ ],+ ),+ );+ expect(tester.getSize(find.byType(SwarmMessageReceipt)).height, 0);+ await close(tester);+ });+ });+}