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: settle a message its computer couldn't confirm, as on Desktop (Tony, task 6) (#2464)
harness-for-autonomous[bot]f1bf9f1daec9
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex 743e7cc08..8e1ef7a06 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -25,6 +25,7 @@ import 'exit_app.dart';import 'new_device_banner.dart';import 'phone_navigation.dart';import 'phone_shell_scope.dart';+import 'phone_status.dart';import 'settings_page.dart' show openPhoneSettings;import 'voice_input_controller.dart';import 'voice_input_scope.dart';@@ -585,6 +586,8 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {onMachineLinked: _followLinkedMachine,onOpenAgent: _openAgentAtHome,onShowSwarm: _showSwarm,+ canOpenMachine: (machineId) =>+ phoneMachineOpensTerminals(widget.notifier.machineStates[machineId]),// Rebuilt when the root switches, so back from Harness can reach Swarm Home.child: ListenableBuilder(listenable: _home,diff --git a/mobile/lib/phone/phone_shell_scope.dart b/mobile/lib/phone/phone_shell_scope.dartindex 2d39b919a..515d5f6e5 100644--- a/mobile/lib/phone/phone_shell_scope.dart+++ b/mobile/lib/phone/phone_shell_scope.dart@@ -11,6 +11,7 @@ class PhoneShellScope extends InheritedWidget {required this.onMachineLinked,required this.onOpenAgent,this.onShowSwarm,+ this.canOpenMachine,required super.child,});@@ -22,6 +23,10 @@ class PhoneShellScope extends InheritedWidget {/// pushing a terminal over whatever page asked. See `openAgent` in `phone_navigation.dart`.final void Function(String machineId, String agentId) onOpenAgent;+ /// This phone has [machineId] linked and can open its terminals+ /// ([onOpenAgent]). Null where nothing can be opened.+ final bool Function(String machineId)? canOpenMachine;+/// Swarm Home at the root, every page over it closed: Swarm asked for from/// the terminal (its mark, Find). Null where the shell has no Swarm Home to/// go back to, and a Swarm page is pushed instead (`openSwarmHome`).diff --git a/mobile/lib/phone/phone_status.dart b/mobile/lib/phone/phone_status.dartindex 6c07def85..1bb955c10 100644--- a/mobile/lib/phone/phone_status.dart+++ b/mobile/lib/phone/phone_status.dart@@ -46,6 +46,12 @@ bool phoneAccountSaysOnline(String? status) =>_ => false,};+/// Whether this phone can open [machine]'s terminals now: one it has, linked,+/// and not reported offline — the rule the terminal search draws "Offline" by+/// (`phone_search_catalog.dart`). A machine not heard from yet counts.+bool phoneMachineOpensTerminals(MachineState? machine) =>+ machine != null && !machine.needsLink && machine.nodeOnline != false;+/// Whether [machine] is away for real: offline by its socket's word, and the account's own record/// agrees.///diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartindex 1eb7f8695..53ab6ea55 100644--- a/mobile/lib/swarm/swarm_conversation.dart+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -504,6 +504,8 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {_outbox.clear();_replyingTo = null;_reacting.clear();+ _resolving = null;+ _resolveIds.clear();error = null;if (held) _tell();}@@ -866,6 +868,103 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {return refused == null;}+ /// The delivery a person's answer is on its way for, and the answer+ /// ([resolveDelivery]).+ (String, String)? get resolving => _resolving;+ (String, String)? _resolving;++ /// The receipt of an answer whose reply never came, by delivery and+ /// answer: the same answer again goes under it, so the backend runs it once+ /// and a message is never sent twice for one tap.+ final _resolveIds = <(String, String), String>{};++ /// Settles [message]'s unconfirmed [delivery] as the person checked it+ /// (the desktop's `_resolveDelivery`): `resend` sends it again, `received`+ /// says it arrived. Then the message and what the backend wrote are read+ /// again; a refusal says why in [error]. True once the backend took it.+ Future<bool> resolveDelivery(+ SuperTabMessage message,+ SuperTabDelivery delivery,+ String resolution,+ ) async {+ final deliveryId = delivery.id;+ if (_disposed ||+ !canPost ||+ _resolving != null ||+ deliveryId == null ||+ delivery.status != 'uncertain' ||+ !receiptCurrent(message)) {+ return false;+ }+ final key = (deliveryId, resolution);+ final operationId = _resolveIds.putIfAbsent(key, superTabOperationId);+ final epoch = _epoch, generation = reader.generation;+ bool stale() =>+ _disposed || epoch != _epoch || generation != reader.generation;+ _resolving = key;+ error = null;+ notifyListeners();+ String? refused;+ var settled = true;+ try {+ await reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ body: {+ 'operationId': operationId,+ 'command': {+ 'type': 'delivery.resolve',+ 'deliveryId': deliveryId,+ 'resolution': resolution,+ },+ },+ );+ } on SuperTabFailure catch (failure) {+ refused = failure.message;+ // A refusal did nothing; a reply lost on the way may have: the same+ // answer again goes under the same receipt.+ settled =+ failure.statusCode >= 400 &&+ failure.statusCode < 500 &&+ !const {408, 429}.contains(failure.statusCode);+ } catch (_) {+ refused = 'The action is not confirmed. Retry to check it.';+ settled = false;+ }+ // Lost access, signed out or the chat forgotten meanwhile: the answer is+ // for a chat no longer shown, and says nothing in it.+ if (_disposed) return false;+ if (stale()) {+ if (_resolving == key) {+ _resolving = null;+ notifyListeners();+ }+ return false;+ }+ if (settled) _resolveIds.remove(key);+ _resolving = null;+ error = refused;+ notifyListeners();+ // Sent again, arrived, or settled before the answer (delivered, or+ // refused as no longer needing it): the line follows what is read now.+ if (settled) {+ for (var held = _readingReceipt; held != null; held = _readingReceipt) {+ await held;+ }+ if (stale() || _receiptOf != message.id) return refused == null;+ _receiptAsked = clock.now();+ final reading = _readReceipt(message.id);+ _readingReceipt = reading;+ await Future.wait([+ reading.whenComplete(() {+ if (identical(_readingReceipt, reading)) _readingReceipt = null;+ }),+ if (refused == null) load(),+ ]);+ }+ return refused == null;+ }+/// Keeps the thread lines a page named ([thread]): one a later page said/// is kept over an older one. True when a line drawn changed.bool _keepThreads(Object? rows) {@@ -953,6 +1052,12 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {static const _receiptReadEvery = Duration(seconds: 30);static const _receiptReadFor = Duration(minutes: 10);+ /// How long a claimed or unconfirmed delivery is read again: as long as the+ /// backend lets it stand — a busy terminal holds a claim up to an hour, and+ /// a person has an hour to check an unconfirmed one (`deliverySettle.ts`+ /// `HOLD_LIMIT_MS`, `UNCERTAIN_LIMIT_MS`). Still only while on screen.+ static const _heldReadFor = Duration(minutes: 60);+String? _receiptOf;DateTime? _receiptSince, _receiptAsked;@@ -990,13 +1095,20 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {_readingReceipt = null;}+ /// The deliveries the newest own message is read again for: queued, taken+ /// by its computer (it may come back unconfirmed), or unconfirmed until a+ /// person settles it ([resolveDelivery]) or it arrives.+ static const _openDeliveries = {'queued', 'claimed', 'uncertain'};+/// 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+ /// it is on screen and its delivery is open. 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 status = own?.receiptDelivery?.status;+ if (own == null || !_openDeliveries.contains(status)) return;+ final readFor = status == 'queued' ? _receiptReadFor : _heldReadFor;final now = clock.now();if (_receiptOf != own.id) {_dropReceipt();@@ -1007,7 +1119,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {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;+ if (!answered && now.difference(_receiptSince!) >= readFor) return;_receiptAsked = now;_receiptTail = tail;late final Future<void> reading;diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex c18b8a589..cd8e9843a 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -1542,7 +1542,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>final acting = _acting == m.id;final reactions = c.reactionsOf(m);final receipt =- m.id == latestOwn?.id && m.receiptDelivery?.status == 'queued';+ m.id == latestOwn?.id &&+ const {'queued', 'uncertain'}.contains(m.receiptDelivery?.status);// 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;diff --git a/mobile/lib/swarm/swarm_message_receipt.dart b/mobile/lib/swarm/swarm_message_receipt.dartindex 6537996d7..de5e0fc0e 100644--- a/mobile/lib/swarm/swarm_message_receipt.dart+++ b/mobile/lib/swarm/swarm_message_receipt.dart@@ -4,6 +4,7 @@ import 'package:clock/clock.dart';import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:harness_mobile/phone/phone_shell_scope.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';@@ -25,13 +26,16 @@ const swarmQueuedNotice = Duration(minutes: 2);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.+/// not getting in, or when its computer could not confirm it: the desktop's+/// `SuperTabMessageReceipt` for those cases, its words and rule. Queued is in+/// amber with nothing to do (#2336); unconfirmed asks the person to check+/// the terminal, then send again or say it arrived+/// ([SwarmConversation.resolveDelivery]). 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.+/// Said only from a read of the message while it is on screen+/// ([SwarmConversation.receiptCurrent]): a row kept from before proves+/// nothing about where its delivery is now.class SwarmMessageReceipt extends StatefulWidget {const SwarmMessageReceipt({super.key,@@ -124,7 +128,7 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>// 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' ||+ !const {'queued', 'uncertain'}.contains(delivery?.status) ||agent == null ||group == null ||!(group.agentIds.contains(agent.id) || group.leadId == agent.id) ||@@ -134,6 +138,10 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>return const SizedBox.shrink();}final name = snapshot.agentName(agent.id, fallback: 'Lead');+ if (delivery!.status == 'uncertain') {+ _wakeUpAt(null, now);+ return _unconfirmed(context, c, message, delivery, agent, name);+ }final machine = snapshot.pool(agent.machineId);final observation = machine?['observation'];final receivedAt = observation is Map ? observation['receivedAt'] : null;@@ -144,7 +152,7 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>machine != null &&(readingAt == null ||now.difference(readingAt) >= _machineOfflineAfter);- final failingSince = delivery!.claimFailingSince;+ final failingSince = delivery.claimFailingSince;final failingAt = failingSince?.add(swarmClaimFailingNotice);final queuedAt = message.createdAt?.add(swarmQueuedNotice);final waiting = !offline && agent.downSince == null;@@ -180,7 +188,76 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>: "$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 _line(+ icon: offline ? LucideIcons.cloudOff : LucideIcons.clock,+ color: AppPalette.warn,+ title: title,+ note: note,+ );+ }++ /// The desktop's "Couldn't confirm delivery": its computer may have typed+ /// it without confirming, so the person checks before it goes again. Open+ /// terminal only where this phone can open that computer's terminals.+ Widget _unconfirmed(+ BuildContext context,+ SwarmConversation c,+ SuperTabMessage message,+ SuperTabDelivery delivery,+ SuperTabAgent agent,+ String name,+ ) {+ final shell = PhoneShellScope.maybeOf(context);+ final reachable =+ shell != null &&+ agent.harnessId.isNotEmpty &&+ shell.canOpenMachine?.call(agent.machineId) == true;+ final resolving = c.resolving;+ final free = c.canPost && resolving == null && delivery.id != null;+ Widget action(String label, String resolution, VoidCallback onPressed) {+ final busy = resolving == (delivery.id, resolution);+ return _ReceiptLink(+ key: ValueKey('swarm-receipt-$resolution'),+ label: label,+ busy: busy,+ dimmed: !free && !busy,+ onPressed: free ? onPressed : null,+ );+ }++ void resolve(String resolution) =>+ unawaited(c.resolveDelivery(message, delivery, resolution));+ return _line(+ icon: LucideIcons.triangleAlert,+ // As the desktop draws it: the theme's error ink, which reads on+ // either surface.+ color: Theme.of(context).colorScheme.error,+ title: "Couldn't confirm delivery",+ note:+ "$name's computer may have typed this into the terminal without "+ 'confirming. Check the terminal before sending again, or it could '+ 'run twice.',+ actions: [+ if (reachable)+ action('Open terminal', 'open', () {+ // Checked again at the tap: the phone may have lost it since.+ if (shell.canOpenMachine?.call(agent.machineId) == true) {+ shell.onOpenAgent(agent.machineId, agent.harnessId);+ }+ }),+ action('Send again', 'resend', () => resolve('resend')),+ action('It arrived', 'received', () => resolve('received')),+ ],+ );+ }++ Widget _line({+ required IconData icon,+ required Color color,+ required String title,+ required String note,+ List<Widget> actions = const [],+ }) {return Padding(padding: const EdgeInsets.only(top: AppSpace.xs),child: Column(@@ -190,11 +267,7 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>liveRegion: true,child: Row(children: [- Icon(- offline ? LucideIcons.cloudOff : LucideIcons.clock,- size: 16,- color: color,- ),+ Icon(icon, size: 16, color: color),const SizedBox(width: AppSpace.xs),Flexible(child: Text(title, style: swarmChatText(14, color: color)),@@ -224,8 +297,79 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>),),),+ // Each link's own padding sets it in from the note's edge: the+ // first is pulled back to line up with it.+ if (actions.isNotEmpty)+ Transform.translate(+ offset: const Offset(-AppSpace.s, 0),+ child: Wrap(children: actions),+ ),],),);}}++/// One answer on the line: words in the accent, 44 points tall to tap, with+/// little room to the side so the three share one line at 390 points.+class _ReceiptLink extends StatelessWidget {+ const _ReceiptLink({+ super.key,+ required this.label,+ required this.busy,+ required this.dimmed,+ required this.onPressed,+ });++ final String label;+ final bool busy, dimmed;+ final VoidCallback? onPressed;++ @override+ Widget build(BuildContext context) {+ final ink = AppPalette.swarmAccent;+ return Semantics(+ button: true,+ enabled: onPressed != null,+ label: label,+ excludeSemantics: true,+ child: Opacity(+ opacity: dimmed ? .45 : 1,+ child: InkWell(+ borderRadius: BorderRadius.circular(AppControl.radius),+ onTap: onPressed,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 44),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (busy) ...[+ SizedBox.square(+ dimension: 14,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ color: ink,+ ),+ ),+ const SizedBox(width: AppSpace.xs),+ ],+ Text(+ label,+ style: swarmChatText(+ 15,+ color: ink,+ weight: FontWeight.w500,+ height: 1.25,+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/test/phone/phone_shell_open_terminal_test.dart b/mobile/test/phone/phone_shell_open_terminal_test.dartnew file mode 100644index 000000000..f2433233d--- /dev/null+++ b/mobile/test/phone/phone_shell_open_terminal_test.dart@@ -0,0 +1,46 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'devices_fixture.dart';++/// Which computers' terminals the shell says this phone can open (a Swarm+/// chat's Open terminal follows it): one it has, linked and not reported+/// offline — the terminal search's own rule.+void main() {+ testWidgets('linked and online, or not heard from yet: yes; offline, '+ 'waiting for a link, or unknown: no', (tester) async {+ final app = DevicesApp();+ addTearDown(app.dispose);+ MachineState machine(String id) => app.machineStates[id] = MachineState(+ Machine(machineId: id, authMode: MachineAuthMode.remote, name: id),+ );+ machine('online').nodeOnline = true;+ machine('unheard');+ machine('offline').nodeOnline = false;+ machine('unlinked')+ ..nodeOnline = true+ ..needsLink = true;++ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await tester.pump();+ final opens = tester+ .widget<PhoneShellScope>(find.byType(PhoneShellScope))+ .canOpenMachine!;++ expect(opens('online'), isTrue);+ expect(opens('unheard'), isTrue);+ expect(opens('offline'), isFalse, reason: 'reported offline');+ expect(opens('unlinked'), isFalse, reason: 'waits for its password');+ expect(opens('elsewhere'), isFalse, reason: 'not this phone\'s');++ // Read at the moment it is asked: a computer that goes offline closes.+ app.machineStates['online']!.nodeOnline = false;+ expect(opens('online'), isFalse);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 1));+ });+}diff --git a/mobile/test/swarm/swarm_delivery_resolve_test.dart b/mobile/test/swarm/swarm_delivery_resolve_test.dartnew file mode 100644index 000000000..fb5decdd9--- /dev/null+++ b/mobile/test/swarm/swarm_delivery_resolve_test.dart@@ -0,0 +1,666 @@+import 'dart:async';++import 'package:clock/clock.dart';+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/phone_shell_scope.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.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 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// "Couldn't confirm delivery" under the person's newest message, and its+/// three answers (the desktop's `_resolveDelivery`): Open terminal, Send+/// again and It arrived, each sent as `delivery.resolve` and then read back.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const exact = '$messages?messageId=';+ const commands = '/api/super-tabs/$tab/commands';+ const note =+ "Lead's computer may have typed this into the terminal without "+ 'confirming. Check the terminal before sending again, or it could run '+ 'twice.';++ Map<String, dynamic> delivery({+ String status = 'uncertain',+ String agentId = 'agent-lead',+ }) => {'id': 'd1', 'agentId': agentId, 'status': status};++ Map<String, dynamic> own({+ String status = 'uncertain',+ String agentId = 'agent-lead',+ }) => {+ 'id': 'm1',+ 'conversationId': 'g1',+ 'text': 'Please start',+ 'sequence': 1,+ 'author': {'kind': 'person', 'id': me, 'name': 'tony'},+ 'deliveries': [delivery(status: status, agentId: agentId)],+ 'createdAt': clock.now().toUtc().toIso8601String(),+ };++ /// What a Swarm read says of the agents: the Lead, in this chat.+ Map<String, dynamic> swarm({+ List<String> agentIds = const ['agent-lead'],+ List<Map<String, dynamic>>? agents,+ String role = 'owner',+ int lastMessageSequence = 1,+ }) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ agentIds: agentIds,+ leadId: agentIds.contains('agent-lead') ? 'agent-lead' : null,+ lastMessageSequence: lastMessageSequence,+ ),+ ],+ agents: agents ?? [agent('agent-lead', name: 'Lead')],+ machines: [+ {+ 'machineId': 'mac-1',+ 'name': 'Team Mac',+ 'contributorId': me,+ 'observation': {'receivedAt': clock.now().millisecondsSinceEpoch},+ },+ ],+ ),+ 'members': [part(me, 1, person(me, role: role))],+ };++ /// A Swarm where chat g1's newest message is the person's, its delivery+ /// [status]; each read of that message answers [read], each command+ /// [command] (taken by default).+ ({FakeSwarm swarm, SwarmReader reader}) rig({+ String status = 'uncertain',+ Map<String, dynamic> Function()? load,+ FutureOr<Object?> Function()? read,+ FutureOr<Object?> Function(Map<String, dynamic>? body)? command,+ String agentId = 'agent-lead',+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => (load ?? swarm)();+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes[messages] = (_) => {+ 'messages': [own(status: status, agentId: agentId)],+ 'next': null,+ };+ fake.routes[exact] = (_) =>+ read?.call() ??+ {+ 'messages': [own(status: status, agentId: agentId)],+ };+ fake.routes[commands] = command ?? (_) => {'result': {}};+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: fake.request,+ );+ addTearDown(reader.dispose);+ return (swarm: fake, reader: reader);+ }++ List<Map<String, dynamic>> resolves(FakeSwarm swarm) => [+ for (final call in swarm.calls)+ if (call.method == 'POST' &&+ call.path == commands &&+ (call.body!['command'] as Map)['type'] == 'delivery.resolve')+ call.body!,+ ];++ int reads(FakeSwarm swarm) =>+ swarm.paths.where((path) => path.startsWith(exact)).length;++ /// The chat on screen, under a shell that can open [openable] computers;+ /// no shell when [shell] is false. Its newest own message read once.+ Future<SwarmConversation> show(+ WidgetTester tester,+ ({FakeSwarm swarm, SwarmReader reader}) r, {+ bool shell = true,+ Set<String> openable = const {'mac-1'},+ List<(String, String)>? opened,+ }) async {+ late SwarmConversation c;+ await tester.runAsync(() async {+ await r.reader.refresh();+ c = SwarmConversation(r.reader, 'g1');+ await c.load();+ // The Swarm's read sets off the message's own read.+ await r.reader.refresh();+ await pumpEventQueue();+ });+ // A test may close it itself.+ addTearDown(() {+ try {+ c.dispose();+ } on FlutterError catch (_) {}+ });+ Widget line = ListenableBuilder(+ listenable: c,+ builder: (_, _) => switch (c.latestOwn) {+ final m? => SwarmMessageReceipt(conversation: c, message: m),+ null => const SizedBox.shrink(),+ },+ );+ if (shell) {+ line = PhoneShellScope(+ onMachineLinked: (_) {},+ onOpenAgent: (machineId, agentId) => opened?.add((machineId, agentId)),+ canOpenMachine: openable.contains,+ child: line,+ );+ }+ await tester.pumpWidget(MaterialApp(home: Scaffold(body: line)));+ await tester.pump();+ return c;+ }++ Future<void> settle(WidgetTester tester) async {+ await tester.runAsync(pumpEventQueue);+ await tester.pump();+ }++ Finder choice(String resolution) =>+ find.byKey(ValueKey('swarm-receipt-$resolution'));++ group('the line', () {+ testWidgets('says Couldn\'t confirm delivery with the three choices', (+ tester,+ ) async {+ await show(tester, rig());+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);+ expect(find.text(note), findsOneWidget);+ expect(find.text('Open terminal'), findsOneWidget);+ expect(find.text('Send again'), findsOneWidget);+ expect(find.text('It arrived'), findsOneWidget);+ });++ testWidgets('Not delivered yet still offers nothing', (tester) async {+ await withClock(Clock.fixed(DateTime.now()), () async {+ await show(+ tester,+ rig(+ status: 'queued',+ read: () => {+ 'messages': [+ {+ ...own(status: 'queued'),+ 'createdAt': DateTime.now()+ .subtract(const Duration(minutes: 5))+ .toUtc()+ .toIso8601String(),+ },+ ],+ },+ ),+ );+ });+ expect(find.text('Not delivered yet'), findsOneWidget);+ expect(find.text('Send again'), findsNothing);+ expect(find.text('It arrived'), findsNothing);+ expect(find.text('Open terminal'), findsNothing);+ });++ testWidgets('Open terminal hides where this phone cannot open that '+ 'computer, or outside the shell', (tester) async {+ await show(tester, rig(), openable: const {'another-mac'});+ expect(find.text('Open terminal'), findsNothing);+ expect(find.text('Send again'), findsOneWidget);++ await show(tester, rig(), shell: false);+ expect(find.text('Open terminal'), findsNothing);+ expect(find.text('It arrived'), findsOneWidget);+ });++ testWidgets('kept from before and not read again, it says nothing', (+ tester,+ ) async {+ final r = rig();+ late SwarmConversation c;+ await tester.runAsync(() async {+ await r.reader.refresh();+ c = SwarmConversation(r.reader, 'g1');+ await c.load();+ });+ addTearDown(c.dispose);+ await tester.pumpWidget(+ MaterialApp(+ home: SwarmMessageReceipt(conversation: c, message: c.latestOwn!),+ ),+ );+ expect(reads(r.swarm), 0);+ expect(find.text("Couldn't confirm delivery"), findsNothing);+ });++ testWidgets('a first read that failed and then worked shows the choices', (+ tester,+ ) async {+ var failing = true;+ final r = rig(+ read: () =>+ failing ? throw const SuperTabFailure('SWARM_BUSY', 'Busy') : null,+ );+ final now = DateTime.now();+ var at = now;+ await withClock(Clock(() => at), () async {+ final c = await show(tester, r);+ expect(find.text("Couldn't confirm delivery"), findsNothing);+ failing = false;+ at = now.add(const Duration(seconds: 30));+ await tester.runAsync(() async {+ await r.reader.refresh();+ await pumpEventQueue();+ });+ await tester.pump();+ expect(c.receiptCurrent(c.latestOwn!), isTrue);+ });+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);+ expect(find.text('Send again'), findsOneWidget);+ });+ });++ group('privacy', () {+ testWidgets('an agent not in this chat, as from another project, is '+ 'named nowhere', (tester) async {+ // The same name in another project: its delivery here is not drawn.+ final r = rig(+ agentId: 'agent-other',+ load: () => swarm(+ agents: [+ agent('agent-lead', name: 'Lead'),+ agent('agent-other', name: 'Lead'),+ ],+ ),+ );+ await show(tester, r);+ expect(find.text("Couldn't confirm delivery"), findsNothing);+ expect(find.textContaining('Lead'), findsNothing);+ });++ testWidgets('an agent the Swarm does not know is named nowhere', (+ tester,+ ) async {+ await show(tester, rig(agentId: 'agent-gone'));+ expect(find.text("Couldn't confirm delivery"), findsNothing);+ });++ testWidgets('a viewer sees the line with nothing to tap', (tester) async {+ final r = rig(load: () => swarm(role: 'viewer'));+ await show(tester, r);+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);+ await tester.tap(choice('resend'));+ await tester.tap(choice('received'));+ await settle(tester);+ expect(resolves(r.swarm), isEmpty);+ });+ });++ group('each choice', () {+ for (final (label, resolution) in [+ ('Send again', 'resend'),+ ('It arrived', 'received'),+ ]) {+ testWidgets(+ '$label sends ${resolution == 'resend' ? 'it again' : 'that it arrived'}, '+ 'then the line follows the read',+ (tester) async {+ var settled = false;+ Map<String, dynamic> now() => own(+ status: settled+ ? (resolution == 'resend' ? 'superseded' : 'confirmed')+ : 'uncertain',+ );+ final r = rig(+ read: () => {+ 'messages': [now()],+ },+ command: (_) {+ settled = true;+ return {'result': {}};+ },+ );+ // The chat's own read, asked with it, says the same.+ r.swarm.routes[messages] = (_) => {+ 'messages': [now()],+ 'next': null,+ };+ final c = await show(tester, r);+ final before = reads(r.swarm);++ await tester.tap(find.text(label));+ await settle(tester);++ final sent = resolves(r.swarm);+ expect(sent, hasLength(1));+ expect(sent.single['command'], {+ 'type': 'delivery.resolve',+ 'deliveryId': 'd1',+ 'resolution': resolution,+ });+ expect(sent.single['operationId'], isA<String>());+ expect(reads(r.swarm), before + 1, reason: 'read back at once');+ expect(c.error, isNull);+ expect(c.resolving, isNull);+ expect(find.text("Couldn't confirm delivery"), findsNothing);+ },+ );+ }++ testWidgets('Open terminal opens the agent\'s terminal and sends nothing', (+ tester,+ ) async {+ final opened = <(String, String)>[];+ final r = rig();+ await show(tester, r, opened: opened);+ await tester.tap(find.text('Open terminal'));+ await settle(tester);+ expect(opened, [('mac-1', 'harness-agent-lead')]);+ expect(resolves(r.swarm), isEmpty);+ });++ testWidgets('while one answer is on its way, nothing else goes', (+ tester,+ ) async {+ final answer = Completer<Object?>();+ final r = rig(command: (_) => answer.future);+ final c = await show(tester, r);++ await tester.tap(find.text('Send again'));+ await tester.pump();+ expect(c.resolving, ('d1', 'resend'));+ await tester.tap(choice('received'));+ await tester.tap(choice('resend'));+ await tester.pump();+ expect(resolves(r.swarm), hasLength(1));++ answer.complete({'result': {}});+ await settle(tester);+ expect(c.resolving, isNull);+ });+ });++ group('failures', () {+ testWidgets('a refusal says why, gives the choices back, and a new tap '+ 'is a new answer', (tester) async {+ final r = rig(+ command: (_) => throw const SuperTabFailure(+ 'DELIVERY_REVOKED',+ 'This instruction is no longer authorized.',+ statusCode: 403,+ ),+ );+ final c = await show(tester, r);+ await tester.tap(find.text('Send again'));+ await settle(tester);++ expect(c.error, 'This instruction is no longer authorized.');+ expect(c.resolving, isNull);+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);++ await tester.tap(find.text('Send again'));+ await settle(tester);+ final sent = resolves(r.swarm);+ expect(sent, hasLength(2));+ expect(+ sent[1]['operationId'],+ isNot(sent[0]['operationId']),+ reason: 'refused: nothing was done',+ );+ });++ testWidgets('a reply lost on the way goes again under the same receipt, '+ 'so it is never sent twice', (tester) async {+ var lose = true;+ final r = rig(+ command: (_) {+ if (lose) throw Exception('connection reset');+ return {'result': {}};+ },+ );+ final c = await show(tester, r);+ final before = reads(r.swarm);+ await tester.tap(find.text('Send again'));+ await settle(tester);++ expect(c.error, 'The action is not confirmed. Retry to check it.');+ expect(c.resolving, isNull);+ expect(reads(r.swarm), before, reason: 'nothing known: not read back');+ expect(find.text('Send again'), findsOneWidget);++ lose = false;+ await tester.tap(find.text('Send again'));+ await settle(tester);+ final sent = resolves(r.swarm);+ expect(sent, hasLength(2));+ expect(sent[1]['operationId'], sent[0]['operationId']);+ expect(c.error, isNull);+ });++ testWidgets('a server error is unsure too: the same receipt again', (+ tester,+ ) async {+ var fail = true;+ final r = rig(+ command: (_) {+ if (fail) {+ throw const SuperTabFailure('INTERNAL', 'Busy', statusCode: 503);+ }+ return {'result': {}};+ },+ );+ await show(tester, r);+ await tester.tap(find.text('It arrived'));+ await settle(tester);+ fail = false;+ await tester.tap(find.text('It arrived'));+ await settle(tester);+ final sent = resolves(r.swarm);+ expect(sent[1]['operationId'], sent[0]['operationId']);+ });++ testWidgets('delivered meanwhile: the refusal is said and the line goes', (+ tester,+ ) async {+ var status = 'uncertain';+ final r = rig(+ read: () => {+ 'messages': [own(status: status)],+ },+ command: (_) {+ status = 'delivered';+ throw const SuperTabFailure(+ 'DELIVERY_RESOLVED',+ 'This delivery no longer needs checking.',+ statusCode: 400,+ );+ },+ );+ final c = await show(tester, r);+ await tester.tap(find.text('Send again'));+ await settle(tester);++ expect(c.error, 'This delivery no longer needs checking.');+ expect(c.latestOwn!.receiptDelivery!.status, 'delivered');+ expect(find.text("Couldn't confirm delivery"), findsNothing);+ });++ testWidgets('an older server without the command says so and keeps '+ 'the line', (tester) async {+ final r = rig(+ command: (_) => throw const SuperTabFailure(+ 'VALIDATION_ERROR',+ 'Invalid discriminator value.',+ statusCode: 400,+ ),+ );+ final c = await show(tester, r);+ await tester.tap(find.text('It arrived'));+ await settle(tester);+ expect(c.error, 'Invalid discriminator value.');+ expect(c.resolving, isNull);+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);+ expect(find.text('It arrived'), findsOneWidget);+ });+ });++ group('lifecycle', () {+ testWidgets('access lost while the answer is on its way: the line goes, '+ 'and the late answer says nothing', (tester) async {+ final answer = Completer<Object?>();+ final r = rig(command: (_) => answer.future);+ final c = await show(tester, r);+ await tester.tap(find.text('Send again'));+ await tester.pump();++ r.reader.revoke();+ await tester.pump();+ expect(c.messages, isEmpty);+ expect(c.resolving, isNull);+ expect(find.text("Couldn't confirm delivery"), findsNothing);++ answer.completeError(+ const SuperTabFailure('FORBIDDEN', 'Not available', statusCode: 403),+ );+ await settle(tester);+ expect(c.error, isNull);+ expect(c.resolving, isNull);+ });++ testWidgets('the Swarm read anew meanwhile: the late answer is dropped '+ 'and the choices come back', (tester) async {+ final answer = Completer<Object?>();+ final r = rig(command: (_) => answer.future);+ final c = await show(tester, r);+ final before = reads(r.swarm);+ await tester.tap(find.text('It arrived'));+ await tester.pump();++ c.reader.generation++;+ answer.completeError(+ const SuperTabFailure(+ 'DELIVERY_REVOKED',+ 'This instruction is no longer authorized.',+ statusCode: 403,+ ),+ );+ await settle(tester);+ expect(c.error, isNull);+ expect(c.resolving, isNull);+ expect(reads(r.swarm), before, reason: 'nothing read for it');+ });++ testWidgets('the chat closed meanwhile: the answer tells no one', (+ tester,+ ) async {+ final answer = Completer<Object?>();+ final r = rig(command: (_) => answer.future);+ final c = await show(tester, r);+ await tester.tap(find.text('Send again'));+ await tester.pump();+ await tester.pumpWidget(const SizedBox());+ c.dispose();+ answer.complete({'result': {}});+ await settle(tester);+ expect(resolves(r.swarm), hasLength(1));+ });++ test('an answer for a delivery no longer read is not sent', () async {+ final r = rig();+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g1');+ addTearDown(c.dispose);+ await c.load();+ final m = c.latestOwn!;+ expect(+ await c.resolveDelivery(m, m.receiptDelivery!, 'resend'),+ isFalse,+ reason: 'not read since it was kept',+ );+ expect(resolves(r.swarm), isEmpty);+ });+ });++ group('in the chat', () {+ testWidgets('Send again from the chat page goes, and the line goes with '+ 'what is read back', (tester) async {+ var settled = false;+ Map<String, dynamic> now() =>+ own(status: settled ? 'superseded' : 'uncertain');+ final fake = rig(+ read: () => {+ 'messages': [now()],+ },+ command: (_) {+ settled = true;+ return {'result': {}};+ },+ ).swarm;+ fake.routes[messages] = (_) => {+ 'messages': [now()],+ 'next': null,+ };+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'OpenHarness', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ final host = SwarmHost(+ accountId: () => me,+ account: ValueNotifier<String?>(me),+ request: fake.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ final opened = <(String, String)>[];+ await tester.pumpWidget(+ MaterialApp(+ builder: (_, child) => PhoneShellScope(+ onMachineLinked: (_) {},+ onOpenAgent: (machineId, agentId) =>+ opened.add((machineId, agentId)),+ canOpenMachine: (machineId) => machineId == 'mac-1',+ 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("Couldn't confirm delivery"), findsOneWidget);++ await tester.tap(find.text('Open terminal'));+ expect(opened, [('mac-1', 'harness-agent-lead')]);++ await tester.tap(find.text('Send again'));+ await tester.pumpAndSettle();+ expect(resolves(fake).single['command'], {+ 'type': 'delivery.resolve',+ 'deliveryId': 'd1',+ 'resolution': 'resend',+ });+ expect(find.text("Couldn't confirm delivery"), findsNothing);+ expect(find.byKey(const ValueKey('swarm-post-error')), findsNothing);++ await tester.pumpWidget(const SizedBox());+ host.dispose();+ await tester.pump(const Duration(minutes: 1));+ });+ });+}diff --git a/mobile/test/swarm/swarm_message_receipt_shots_test.dart b/mobile/test/swarm/swarm_message_receipt_shots_test.dartindex 95b01a9fb..8e6cf994f 100644--- a/mobile/test/swarm/swarm_message_receipt_shots_test.dart+++ b/mobile/test/swarm/swarm_message_receipt_shots_test.dart@@ -8,6 +8,7 @@ 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/phone/phone_shell_scope.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';@@ -19,8 +20,8 @@ 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.+/// `SWARM_RECEIPT_SHOTS` names: claims failing, nothing picked up yet, the+/// computer offline, and a delivery its computer could not confirm.final shots = Platform.environment['SWARM_RECEIPT_SHOTS'];void main() {@@ -60,7 +61,7 @@ void main() {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']) {+ for (final state in ['failing', 'waiting', 'offline', 'uncertain']) {final now = clock.now();DateTime ago(Duration age) => now.subtract(age);final fake = FakeSwarm();@@ -119,7 +120,7 @@ void main() {{'id': 'd1','agentId': 'agent-lead',- 'status': 'queued',+ 'status': state == 'uncertain' ? 'uncertain' : 'queued',if (state == 'failing')'claimFailingSince': ago(const Duration(minutes: 2)).toUtc()@@ -163,8 +164,13 @@ void main() {child: MaterialApp(debugShowCheckedModeBanner: false,theme: buildAppTheme(brightness: brightness),- builder: (_, child) =>- SwarmScope(notifier: host, child: child!),+ // A shell that can open the Lead's computer: Open terminal.+ builder: (_, child) => PhoneShellScope(+ onMachineLinked: (_) {},+ onOpenAgent: (_, _) {},+ canOpenMachine: (_) => true,+ child: SwarmScope(notifier: host, child: child!),+ ),home: const SwarmConversationPage(swarmId: tab,conversationId: 'g1',@@ -176,11 +182,11 @@ void main() {await host.session!.inbox.reader(tab)!.refresh();await tester.pumpAndSettle();expect(- find.text(- state == 'offline'- ? "River's computer is offline"- : 'Not delivered yet',- ),+ find.text(switch (state) {+ 'offline' => "River's computer is offline",+ 'uncertain' => "Couldn't confirm delivery",+ _ => 'Not delivered yet',+ }),findsOneWidget,);expect(tester.takeException(), isNull);diff --git a/mobile/test/swarm/swarm_message_receipt_test.dart b/mobile/test/swarm/swarm_message_receipt_test.dartindex a041f9db5..132ae75e1 100644--- a/mobile/test/swarm/swarm_message_receipt_test.dart+++ b/mobile/test/swarm/swarm_message_receipt_test.dart@@ -146,7 +146,8 @@ void main() {});});- test('stops once the delivery is claimed, and the row takes the claim', () {+ test('reads on while claimed, since it may come back unconfirmed; stops '+ 'once delivered', () {return withClock(moved, () async {final queued = own('m1', 1, at: now, deliveries: [delivery()]);var status = 'queued';@@ -171,9 +172,78 @@ void main() {expect(reads(r.swarm), 2);expect(c.latestOwn!.receiptDelivery!.status, 'claimed');+ status = 'delivered';+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ expect(reads(r.swarm), 3, reason: 'claimed: still asked');+ expect(c.latestOwn!.receiptDelivery!.status, 'delivered');+now = now.add(const Duration(minutes: 5));await tick(r);- expect(reads(r.swarm), 2, reason: 'claimed: nothing more to ask');+ expect(reads(r.swarm), 3, reason: 'delivered: nothing more to ask');+ });+ });++ test('a claim read past 10 minutes, as a busy terminal holds it for up '+ 'to an hour: one that turns unconfirmed then shows', () {+ return withClock(moved, () async {+ final sent = own('m1', 1, at: now, deliveries: [delivery()]);+ var status = 'claimed';+ final r = rig(+ page: [sent],+ answer: (_) => {+ 'messages': [+ {+ ...sent,+ 'deliveries': [delivery(status: status)],+ },+ ],+ },+ );+ final c = await open(r.reader);+ await tick(r);+ expect(c.latestOwn!.receiptDelivery!.status, 'claimed');+ // 25 minutes on screen, still held.+ for (var i = 0; i < 50; i++) {+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ }+ expect(reads(r.swarm), 51, reason: 'past 10 minutes: still asked');++ status = 'uncertain';+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ expect(c.latestOwn!.receiptDelivery!.status, 'uncertain');+ expect(c.receiptCurrent(c.latestOwn!), isTrue);+ });+ });++ test('a claim is read for an hour on screen, then no more', () {+ return withClock(moved, () async {+ final sent = own('m1', 1, at: now, deliveries: [delivery()]);+ final r = rig(+ page: [sent],+ answer: (_) => {+ 'messages': [+ {+ ...sent,+ 'deliveries': [delivery(status: 'claimed')],+ },+ ],+ },+ );+ await open(r.reader);+ await tick(r);+ for (var i = 0; i < 119; i++) {+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ }+ expect(reads(r.swarm), 120);+ for (var i = 0; i < 10; i++) {+ now = now.add(const Duration(seconds: 30));+ await tick(r);+ }+ expect(reads(r.swarm), 120, reason: 'past the hour');});});@@ -232,7 +302,7 @@ void main() {});});- test('asks only for the person\'s own newest, and only while queued', () {+ test('asks only for the person\'s own newest, and only while open', () {return withClock(moved, () async {final r = rig(page: [