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
Batch AB (phone): Buddy replaces Chat with PM (#2133), bold and @N (#2139), task status line (#2140) (#2154)
0xken1508b3268beec7
diff --git a/mobile/README.md b/mobile/README.mdindex cb8ff0546..493a63212 100644--- a/mobile/README.md+++ b/mobile/README.md@@ -61,6 +61,33 @@ foreground. Creating or deleting a harness updates its desk membership; explicitalso live in `PhoneDesk`. The current swarm and position remain device-local. `lib/phone/desk_groups.dart`resolves the swarm’s harnesses for navigation.+## Swarm (Settings ▸ Experimental)++`lib/swarm/` brings a Swarm (the desktop's collaborative tab, not the desk groups above) to the+phone: what needs the person first (decisions, the Product Manager's tags, work waiting on them),+the Swarms and their projects, a project's conversations, posting with @mentions, and decisions+answered with one tap. The phone has no backend route of its own for it: every read and command+goes to the Swarm read API through one of the account's machines (`AppNotifier.swarmRequest`,+the `super_tabs` relay request, end-to-end encrypted), so who can read what is the backend's+answer, the same as on the desktop. `model.dart` and `parts.dart` are copies of the desktop's,+held to them by `test/swarm/desktop_parity_test.dart`.++- **Cost.** One `SwarmSession` per signed-in account while Swarm is on. In the foreground it reads+ what needs the person every 15 seconds, and an open Swarm's changes (first load, then `/changes`)+ every 5 seconds while a screen shows it. In the background it reads nothing.+- **Notices** are local only: a foreground read that finds something new posts one while no Swarm+ screen is open (Home, a terminal). They say who asks and in which project, never the question or+ the message (`swarm_notices.dart`), because a locked phone may show them; notices to a closed or+ backgrounded app need push from the backend.+- **Choices.** `swarm_choices.dart` holds the six UX answers (the way in, the first screen, a+ project's layout, posting, notices, Undo), each the recommended one until the app's owner decides.++`integration_test/swarm_local_review_test.dart` walks the real shell's ways in (Settings ▸+Experimental, the mark on Home, Find) and these screens on a simulator against an isolated local+backend (fake SSO, in-memory MongoDB and Redis, no daemon), through the app's own Swarm path to a+stand-in machine, for review screenshots. It skips without `SWARM_LOCAL_BACKEND` and reads only+127.0.0.1.+## It is a VIEWER build, alwaysNo harness CLI runs beside this app and no agent is ever hosted here. It holds its own SSO session anddiff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xmlindex 0a65c2fdc..c19465a47 100644--- a/mobile/android/app/src/main/AndroidManifest.xml+++ b/mobile/android/app/src/main/AndroidManifest.xml@@ -13,7 +13,7 @@request, which Android confirms with its own sheet. Neither is a runtime permission. --><uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />- <!-- Taking a picture to send to an agent. Picking an EXISTING picture needs+ <!-- Taking a picture to send to an agent or into a Swarm chat. Picking an EXISTING picture needsno permission at all: image_picker goes through ACTION_GET_CONTENT / thephoto picker, which hands back one item the user chose rather thanopening the library — hence no READ_MEDIA_IMAGES here. -->diff --git a/mobile/integration_test/swarm_chat_pictures_test.dart b/mobile/integration_test/swarm_chat_pictures_test.dartnew file mode 100644index 000000000..2cb5a5bfb--- /dev/null+++ b/mobile/integration_test/swarm_chat_pictures_test.dart@@ -0,0 +1,334 @@+import 'dart:async';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_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' as grid;+import 'package:harness_mobile/swarm/swarm_attachment_store.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_message_row.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../test/swarm/swarm_fixture.dart';+import '../test/voice_fakes.dart' show MemoryKeyValueStore;++/// A picture in a Swarm chat on a simulator, a screenshot at each step: its+/// skeleton while it loads, the picture in place beside a PDF's chip, and the+/// picture full screen.+///+/// The Swarm is scripted in memory ([FakeSwarm]) and Harness's file storage+/// is answered in the app ([HttpOverrides]) with a picture drawn here: nothing+/// reaches an account, a machine, the backend or the network. The files are+/// kept in the app's real private temporary folder and emptied at the end.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_chat_pictures_test.dart+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ testWidgets('a picture in a chat, in place and full screen', (tester) async {+ final storage = _Storage(await _picture());+ final before = HttpOverrides.current;+ HttpOverrides.global = storage;+ addTearDown(() => HttpOverrides.global = before);+ await swarmAttachments.keepOnly(me);+ addTearDown(() => swarmAttachments.keepOnly(null));++ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: _swarm().request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ );+ addTearDown(host.dispose);+ final brightness = grid.AppTheme.palette.value.brightness;+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => grid.BrightnessScope(+ child: SwarmScope(notifier: host, child: child!),+ ),+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ ),+ );++ Future<void> wait(int ms) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> waitFor(Finder finder) async {+ for (var i = 0; i < 200 && finder.evaluate().isEmpty; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(finder, findsWidgets);+ }++ var step = 0;+ Future<void> shot(String name) async {+ await wait(900);+ step++;+ await binding.takeScreenshot(+ 'swarm-pictures-${step.toString().padLeft(2, '0')}-$name',+ );+ }++ final preview = find.byKey(const ValueKey('swarm-attachment-preview-f1'));++ // ① Loading: a skeleton in the picture's box, beside the PDF's chip.+ await waitFor(preview);+ await waitFor(find.textContaining('plan.pdf'));+ await shot('loading');++ // ② The picture in the same box.+ storage.hold.complete();+ await waitFor(+ find.descendant(of: preview, matching: find.byType(RawImage)),+ );+ await shot('picture');+ expect(storage.asked, hasLength(1));+ expect(storage.credentials, isEmpty, reason: 'fetched as the chip opens');++ // ③ A tap: full screen, to pinch and zoom.+ await tester.tap(preview);+ await waitFor(find.byKey(const ValueKey('swarm-attachment-viewer')));+ await shot('full-screen');++ await tester.tap(find.byKey(const ValueKey('swarm-attachment-close')));+ await wait(900);+ expect(preview, findsOneWidget);+ }, timeout: const Timeout(Duration(minutes: 2)));+}++/// A chat whose one message carries a screenshot and a PDF.+FakeSwarm _swarm() {+ Map<String, dynamic> file(String id, String name, String mime) => {+ 'id': id,+ 'name': name,+ 'mime': mime,+ 'size': 184320,+ 'url': 'https://$swarmAttachmentHost/$id/$name',+ };+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Sign in with passkeys',+ agentIds: ['agent-builder'],+ lastMessageSequence: 1,+ ),+ ],+ agents: [agent('agent-builder', displayName: 'Nova')],+ ),+ '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['/api/super-tabs/$tab/conversations/g1/messages'] = (_) => {+ 'messages': [+ {+ 'id': 'm1',+ 'conversationId': 'g1',+ 'text': 'The new sign-in sheet on the simulator, and the plan.',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'attachments': [+ file('f1', 'sign-in-sheet.png', 'image/png'),+ file('f2', 'plan.pdf', 'application/pdf'),+ ],+ 'createdAt': DateTime.now().toUtc().toIso8601String(),+ },+ ],+ 'next': null,+ };+ return fake;+}++/// A screenshot-like picture, 1200 × 1600: a sign-in sheet in outline.+Future<List<int>> _picture() async {+ const size = Size(1200, 1600);+ final recorder = ui.PictureRecorder();+ final canvas = Canvas(recorder);+ canvas.drawRect(+ Offset.zero & size,+ Paint()+ ..shader = ui.Gradient.linear(Offset.zero, Offset(0, size.height), [+ const Color(0xFF1F3A5F),+ const Color(0xFF0E1726),+ ]),+ );+ final card = RRect.fromRectAndRadius(+ const Rect.fromLTWH(120, 420, 960, 900),+ const Radius.circular(48),+ );+ canvas.drawRRect(card, Paint()..color = const Color(0xFFF5F7FA));+ final bar = Paint()..color = const Color(0xFFD5DCE6);+ for (final (top, width) in [(520.0, 520.0), (620.0, 760.0), (700.0, 640.0)]) {+ canvas.drawRRect(+ RRect.fromRectAndRadius(+ Rect.fromLTWH(200, top, width, 36),+ const Radius.circular(18),+ ),+ bar,+ );+ }+ canvas.drawRRect(+ RRect.fromRectAndRadius(+ const Rect.fromLTWH(200, 1100, 800, 120),+ const Radius.circular(60),+ ),+ Paint()..color = const Color(0xFF3B82F6),+ );+ final image = await recorder.endRecording().toImage(+ size.width.toInt(),+ size.height.toInt(),+ );+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ return png!.buffer.asUint8List();+}++/// Harness's file storage, answered in the app: [picture] for every link,+/// once [hold] completes; what was asked and with which credentials.+class _Storage extends HttpOverrides {+ _Storage(this.picture);++ final List<int> picture;+ final hold = Completer<void>();+ final asked = <Uri>[];+ final credentials = <String>[];++ @override+ HttpClient createHttpClient(SecurityContext? context) => _Client(this);+}++class _Client extends Fake implements HttpClient {+ _Client(this.storage);++ final _Storage storage;++ @override+ bool autoUncompress = true;++ @override+ Future<HttpClientRequest> openUrl(String method, Uri url) async {+ storage.asked.add(url);+ return _Request(storage);+ }++ @override+ void close({bool force = false}) {}+}++class _Request extends Fake implements HttpClientRequest {+ _Request(this.storage);++ final _Storage storage;++ @override+ bool followRedirects = true;++ @override+ int maxRedirects = 5;++ @override+ int contentLength = -1;++ @override+ bool persistentConnection = true;++ @override+ final HttpHeaders headers = _Headers();++ @override+ Future<void> addStream(Stream<List<int>> stream) => stream.drain<void>();++ @override+ Future<HttpClientResponse> close() async {+ final auth = (headers as _Headers).values['authorization'];+ if (auth != null) storage.credentials.add(auth);+ await storage.hold.future;+ return _Response(storage.picture);+ }+}++class _Headers extends Fake implements HttpHeaders {+ final values = <String, String>{};++ @override+ void set(String name, Object value, {bool preserveHeaderCase = false}) =>+ values[name.toLowerCase()] = '$value';++ @override+ void forEach(void Function(String name, List<String> values) action) =>+ values.forEach((name, value) => action(name, [value]));+}++class _Response extends Stream<List<int>> implements HttpClientResponse {+ _Response(this._bytes);++ final List<int> _bytes;++ @override+ int get statusCode => 200;++ @override+ int get contentLength => _bytes.length;++ @override+ final HttpHeaders headers = _Headers()+ ..set('content-type', 'image/png')+ ..set('cache-control', 'public, max-age=31536000, immutable');++ @override+ bool get isRedirect => false;++ @override+ bool get persistentConnection => false;++ @override+ String get reasonPhrase => 'OK';++ @override+ List<RedirectInfo> get redirects => const [];++ @override+ StreamSubscription<List<int>> listen(+ void Function(List<int> event)? onData, {+ Function? onError,+ void Function()? onDone,+ bool? cancelOnError,+ }) => Stream.value(_bytes).listen(+ onData,+ onError: onError,+ onDone: onDone,+ cancelOnError: cancelOnError,+ );++ @override+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);+}diff --git a/mobile/integration_test/swarm_chat_shots_test.dart b/mobile/integration_test/swarm_chat_shots_test.dartnew file mode 100644index 000000000..51fdc92eb--- /dev/null+++ b/mobile/integration_test/swarm_chat_shots_test.dart@@ -0,0 +1,549 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';++import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_start.dart';++import '../test/swarm/swarm_fixture.dart';+import '../test/voice_fakes.dart' show MemoryKeyValueStore;++/// Swarm's chat and start screens on a simulator, a screenshot at each step,+/// for comparing with Tony's prototype v2: the chat as the prototype fills it+/// (a reply's quote, a decision under its asker's message, an @mention), the+/// @ picker, Reply, a quote followed to its original, a post on its way; then+/// each start screen.+///+/// Every answer is scripted in memory ([FakeSwarm]): nothing reaches an+/// account, a machine or the backend.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_chat_shots_test.dart+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ testWidgets('the chat, as the prototype has it', (tester) async {+ final walk = _Walk(tester, binding, 'chat');+ final now = DateTime.now();+ DateTime at(int hour, int minute, {int day = 0}) =>+ DateTime(now.year, now.month, now.day - day, hour, minute);+ const conversation = 'g-pm';+ const messages =+ '/api/super-tabs/$tab/conversations/$conversation/messages';+ Map<String, dynamic> message(+ String id,+ int sequence,+ DateTime when,+ String text, {+ String author = 'agent-lead',+ String? replyTo,+ }) => {+ 'id': id,+ 'conversationId': conversation,+ 'text': text,+ 'sequence': sequence,+ 'replyTo': ?replyTo,+ 'author': author == me+ ? {'kind': 'person', 'id': me, 'name': 'Tony'}+ : {'kind': 'agent', 'id': author, 'name': 'River'},+ 'attachments': <Object>[],+ 'createdAt': when.toUtc().toIso8601String(),+ };+ final page = [+ message(+ 'm2',+ 2,+ at(11, 28),+ 'Where are we on the phone build?',+ author: me,+ ),+ message(+ 'm3',+ 3,+ at(11, 34),+ 'Jasper fixed the three review findings. Kai runs the iPhone test '+ 'once the phone is plugged in. I will ask you before we ship.',+ replyTo: 'm2',+ ),+ message('m4', 4, at(11, 35), 'One question before the release:'),+ message(+ 'm5',+ 5,+ at(11, 40),+ '@Kai I will plug in the iPhone 14 after lunch.',+ author: me,+ ),+ message(+ 'm6',+ 6,+ at(11, 41),+ 'Thanks. Kai starts the moment it is in.',+ replyTo: 'm5',+ ),+ ];++ final fake = FakeSwarm();+ final posted = Completer<Object?>();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ const derived = {'decisionsWaiting': 1};+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ head: headData(+ projects: [+ {+ 'id': project,+ 'name': 'openharness',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-jasper', displayName: 'Jasper'),+ agent('agent-kai', displayName: 'Kai'),+ ],+ groups: [+ groupData(+ conversation,+ title: 'tony',+ agentIds: ['agent-lead', 'agent-jasper', 'agent-kai'],+ audience: [me],+ lastMessageSequence: 6,+ ),+ groupData(+ 'g-test',+ title: 'iPhone test',+ agentIds: ['agent-kai'],+ status: 'working',+ workerId: 'agent-kai',+ ),+ ],+ derived: derived,+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'projectId': project,+ 'projectName': 'openharness',+ 'conversationId': conversation,+ 'conversationTitle': 'tony',+ 'askerName': 'River',+ 'question':+ 'Ship mobile v1 behind a flag for a week, or to everyone?',+ 'options': ['Flag 1 week', 'Everyone'],+ 'recommended': -1,+ 'createdAt': at(+ 11,+ 35,+ ).add(const Duration(seconds: 20)).toUtc().toIso8601String(),+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[messages] = (_) => {+ 'messages': page.reversed.toList(),+ 'next': {'sequence': 2, 'id': 'm2'},+ };+ fake.routes['$messages?before=2&beforeId=m2'] = (_) => {+ 'messages': [+ message('m1', 1, at(17, 2, day: 1), 'The phone build is on its way.'),+ ],+ 'next': null,+ };+ // A post stays on its way, for its screenshot.+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => posted.future;++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ _app(+ host,+ const SwarmConversationPage(swarmId: tab, conversationId: conversation),+ ),+ );+ await walk.waitFor(walk.key('swarm-ask-d1'));+ await walk.shot('chat');++ await tester.enterText(find.byType(TextField), '@');+ await walk.shot('mention-picker');+ await tester.enterText(find.byType(TextField), '@K');+ await walk.shot('mention-narrowed');+ await tester.enterText(find.byType(TextField), '');++ await tester.tap(find.text('Thanks. Kai starts the moment it is in.'));+ await walk.shot('actions');+ await tester.tap(walk.key('swarm-reply-m6'));+ await walk.shot('reply-bar');+ await tester.tap(walk.key('swarm-reply-cancel'));+ // A simulator's own keyboard hides the quote above the composer.+ FocusManager.instance.primaryFocus?.unfocus();+ await walk.wait(900);++ await tester.tap(walk.key('swarm-quote-m3'));+ await walk.wait(300);+ await walk.shot('quote-followed', settle: 0);++ await tester.enterText(find.byType(TextField), 'Sounds good.');+ await walk.wait(200);+ await tester.tap(walk.key('swarm-send'));+ await walk.shot('sending');+ posted.complete({'result': <String, dynamic>{}});+ await walk.wait();+ });++ testWidgets('the chat as it loads, reads back and starts', (tester) async {+ final walk = _Walk(tester, binding, 'loading');+ const conversation = 'g-build';+ const messages =+ '/api/super-tabs/$tab/conversations/$conversation/messages';+ final now = DateTime.now();+ const said = [+ 'Build 214 is green on CI.',+ 'The iPhone run starts after lunch, once the phone is plugged in.',+ 'Jasper fixed the three review findings.',+ 'Kai is checking the Android build.',+ 'Release notes are drafted; I will ask you before we ship.',+ ];+ Map<String, dynamic> message(int sequence) => {+ 'id': 'm$sequence',+ 'conversationId': conversation,+ 'text': said[sequence % said.length],+ 'sequence': sequence,+ 'author': {+ 'kind': 'agent',+ 'id': sequence.isEven ? 'agent-lead' : 'agent-jasper',+ 'name': sequence.isEven ? 'River' : 'Jasper',+ },+ 'attachments': <Object>[],+ 'createdAt': now+ .subtract(Duration(minutes: 3 * (60 - sequence)))+ .toUtc()+ .toIso8601String(),+ };+ Map<String, dynamic> build(int newest) => groupData(+ conversation,+ title: 'Phone build',+ agentIds: ['agent-lead', 'agent-jasper'],+ status: 'working',+ workerId: 'agent-jasper',+ lastMessageSequence: newest,+ );++ final swarm = Completer<void>();+ final first = Completer<Object?>(), earlier = Completer<Object?>();+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) async {+ await swarm.future;+ return {+ ...firstLoad(+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-jasper', displayName: 'Jasper'),+ ],+ groups: [+ build(40),+ groupData(+ 'g-new',+ title: 'Release notes',+ agentIds: ['agent-lead'],+ ),+ ],+ ),+ '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] = (_) => first.future;+ fake.routes['$messages?before=21&beforeId=m21'] = (_) => earlier.future;+ fake.routes['/api/super-tabs/$tab/conversations/g-new/messages'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ _app(+ host,+ const SwarmConversationPage(swarmId: tab, conversationId: conversation),+ ),+ );+ await walk.waitFor(walk.key('swarm-chat-skeleton'));+ await walk.shot('skeleton-and-header');++ swarm.complete();+ await walk.waitFor(find.text('Phone build'));+ await walk.shot('skeleton');++ first.complete({+ 'messages': [for (var i = 40; i > 20; i--) message(i)],+ 'next': {'sequence': 21, 'id': 'm21'},+ });+ await walk.waitFor(walk.key('swarm-message-m40'));+ await walk.shot('read');++ // Reading back when a message arrives: it waits below.+ await tester.drag(walk.key('swarm-messages'), const Offset(0, 300));+ await walk.wait();+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ lastChangedAt: 200,+ groups: [part(conversation, 9, build(41))],+ );+ fake.routes['$messages?after=40'] = (_) => {+ 'messages': [message(41)],+ 'next': null,+ };+ await host.session!.inbox.reader(tab)!.refresh();+ await walk.waitFor(walk.key('swarm-new-pill'));+ await walk.shot('new-pill');++ await tester.drag(walk.key('swarm-messages'), const Offset(0, 4000));+ await walk.waitFor(walk.key('swarm-older-loading'));+ await walk.shot('earlier-loading');+ earlier.complete({+ 'messages': [for (var i = 20; i > 0; i--) message(i)],+ 'next': null,+ });+ await walk.wait();++ // Another chat, with nothing in it yet: the app built again around it,+ // as a navigator keeps its first page.+ await tester.pumpWidget(const SizedBox());+ await tester.pumpWidget(+ _app(+ host,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g-new'),+ ),+ );+ await walk.waitFor(walk.key('swarm-chat-empty'));+ await walk.shot('empty');+ });++ testWidgets('each start screen', (tester) async {+ final walk = _Walk(tester, binding, 'start');+ const macAway = (name: 'MacBook Pro', away: true);+ const miniAway = (name: 'Mac mini', away: true);+ final cases = <(String, List<SwarmComputer>?, FakeSwarm Function())>[+ (+ 'offline',+ [macAway, miniAway],+ () => FakeSwarm()+ ..routes['/api/super-tabs/list'] = (_) => throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ ),+ ),+ (+ 'no-computer',+ const [],+ () => FakeSwarm()+ ..routes['/api/super-tabs/list'] = (_) => throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ ),+ ),+ ('no-swarm', [(name: 'MacBook Pro', away: false)], () => _empty()),+ (+ 'invited',+ [(name: 'MacBook Pro', away: false)],+ () => _empty()+ ..routes['/api/super-tabs/invitations'] = (_) => [+ {+ 'tabId': 'tab-team',+ 'name': 'Autonomous team',+ 'inviteId': 'invite-team',+ 'role': 'collaborator',+ 'expiresAt': 1893456000000,+ },+ ],+ ),+ (+ 'invites-failed',+ [(name: 'MacBook Pro', away: false)],+ () => _empty()+ ..routes['/api/super-tabs/invitations'] = (_) =>+ throw const SuperTabFailure(+ 'INTERNAL',+ 'Something went wrong.',+ statusCode: 500,+ ),+ ),+ ];+ for (final (name, list, backend) in cases) {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ notices: SilentSystemNotices(),+ features: features,+ computers: _Computers(list),+ )..foreground = false;+ final session = host.session!;+ await session.inbox.refresh();+ await tester.pumpWidget(+ _app(+ host,+ Builder(+ builder: (context) => Scaffold(+ // Home's ground, which the start screen stands on there.+ backgroundColor: Tty.of(context).ground,+ body: SafeArea(+ child: Builder(+ builder: (context) => ListenableBuilder(+ listenable: session.inbox,+ builder: (context, _) =>+ swarmStartView(context, session) ?? const SizedBox(),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ await walk.shot(name);+ await tester.pumpWidget(const SizedBox());+ host.dispose();+ }++ await tester.pumpWidget(+ _app(+ null,+ SwarmIntroPage(+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore()),+ ),+ ),+ );+ await walk.shot('intro');+ });+}++/// The account has no Swarm and no invitation.+FakeSwarm _empty() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': <Object>[],+ 'next': null,+ };+ fake.routes['/api/super-tabs/invitations'] = (_) => <Object>[];+ return fake;+}++/// [home] in the phone's dark theme, with [host]'s Swarm over it.+Widget _app(SwarmHost? host, Widget home) => grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) =>+ host == null ? child! : SwarmScope(notifier: host, child: child!),+ home: home,+ ),+);++class _Computers extends ChangeNotifier implements SwarmComputers {+ _Computers(this.computers);++ @override+ final List<SwarmComputer>? computers;++ @override+ bool get rechecking => false;++ @override+ Future<void> recheck() async {}++ @override+ void add(BuildContext context) {}+}++class _Walk {+ _Walk(this.tester, this.binding, this.name);++ final WidgetTester tester;+ final IntegrationTestWidgetsFlutterBinding binding;+ final String name;+ var _step = 0;++ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String step, {int settle = 900}) async {+ await wait(settle);+ _step++;+ await binding.takeScreenshot(+ '$name-${_step.toString().padLeft(2, '0')}-$step',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));+}diff --git a/mobile/integration_test/swarm_device_e2e_test.dart b/mobile/integration_test/swarm_device_e2e_test.dartnew file mode 100644index 000000000..32bb4adf3--- /dev/null+++ b/mobile/integration_test/swarm_device_e2e_test.dart@@ -0,0 +1,223 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';++import 'package:harness_mobile/main.dart' as app;+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/welcome/onboarding_copy.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_need_rows.dart';++/// Swarm end to end on a real phone: the real app, signed in to its owner's+/// account, reading the account's Swarms through one of its own computers.+/// Only on the owner's own phone, when they ask for the run (the mobile+/// owner, 2026-10-27): it is opt-in with `SWARM_E2E_DEVICE=true` and skips+/// otherwise, so no CI or simulator run reaches a real account.+///+/// It reads: Swarm on (in memory only; the saved switch is left as it was),+/// Swarm Home and its drawer, Harness from the project team and the terminal's mark back to Swarm Home,+/// the first project, its project chat and its ⋮ menu. It writes only when `SWARM_E2E_CHAT` names a test chat whose open+/// decision asks this person: there it posts one short line and answers that+/// decision with its first option. Nothing else is written.+///+/// flutter drive -d <phone> --keep-app-running \+/// --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_device_e2e_test.dart \+/// --dart-define=SWARM_E2E_DEVICE=true \+/// [--dart-define=SWARM_E2E_CHAT='Phone e2e']+///+/// `--keep-app-running` always: without it `flutter drive` uninstalls the app+/// (`integration_test/README.md`). Screenshots land in `HARNESS_JOURNEY_OUT`+/// (default `build/journey/`); they show the account's own Swarms, so they+/// stay with the person who ran it.+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();+ const run = bool.fromEnvironment('SWARM_E2E_DEVICE');+ const chat = String.fromEnvironment('SWARM_E2E_CHAT');++ testWidgets(+ 'Swarm on this phone, for its signed-in owner',+ (tester) async {+ var step = 0;+ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String name) async {+ // Past any page transition.+ await wait(900);+ step++;+ await binding.takeScreenshot(+ 'device-${step.toString().padLeft(2, '0')}-$name',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 30}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ if (find.byKey(const ValueKey('swarm-error')).evaluate().isNotEmpty) {+ await shot('swarm-error');+ fail('Swarm said it could not read: see the screenshot');+ }+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Future<void> waitGone(Finder finder, {int seconds = 30}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never went: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));+ Finder keyStarting(String prefix) => find.byWidgetPredicate(+ (widget) =>+ widget.key is ValueKey<String> &&+ (widget.key! as ValueKey<String>).value.startsWith(prefix),+ );++ await app.main();+ // Home, with a harness on it (or Swarm Home, Swarm saved on); or the+ // welcome, which this run cannot pass.+ final home = find.byWidgetPredicate(+ (widget) =>+ widget.key == const ValueKey('terminal-title') ||+ widget.key == const ValueKey('swarm-menu'),+ );+ for (var i = 0; i < 900 && home.evaluate().isEmpty; i++) {+ if (find.text(OnboardingCopy.welcome).evaluate().isNotEmpty) {+ fail('Sign in on the phone first, then run this again.');+ }+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(home, findsOneWidget, reason: 'Home with a harness on it');++ // Swarm on for this run only: the value, not the store's write.+ final saved = experimentalFeaturesStore.value;+ addTearDown(() => experimentalFeaturesStore.value = saved);+ experimentalFeaturesStore.value = {...saved, PhoneExperiment.swarm};++ // ① Swarm Home at the root: needs first, Buddies, the projects.+ // Its drawer, with no way to Harness; Harness from the project+ // team’s Open terminal action; the+ // terminal's mark goes back to Swarm Home.+ await waitFor(keyStarting('swarm-project-'), seconds: 60);+ await shot('swarm');+ await tester.tap(key('swarm-menu'));+ await waitFor(key('swarm-drawer-home'));+ expect(key('swarm-drawer-harness'), findsNothing);+ await shot('drawer');+ await tester.tap(key('swarm-drawer-home'));+ await waitGone(key('swarm-drawer-home'));+ await tester.tap(keyStarting('swarm-project-').first);+ await waitFor(key('swarm-project-menu'));+ await tester.tap(key('swarm-project-menu'));+ await waitFor(key('swarm-project-menu-status'));+ await tester.tap(key('swarm-project-menu-status'));+ await waitFor(key('swarm-sheet-team'));+ await tester.tap(key('swarm-sheet-team'));+ await waitFor(keyStarting('swarm-open-terminal-'));+ await tester.tap(keyStarting('swarm-open-terminal-').first);+ await waitFor(key('swarm-mark'));+ await shot('home-mark');+ await tester.tap(key('swarm-mark'));+ await waitFor(keyStarting('swarm-project-'), seconds: 60);++ // ② The first project: it opens on its project chat, read only.+ await tester.tap(keyStarting('swarm-project-').first);+ await waitFor(key('swarm-project-menu'));+ await waitFor(key('swarm-messages'));+ await wait(3000);+ await shot('project');+ // Its ⋮ menu: Buddy chat and the team's status, as it reads now.+ await tester.tap(key('swarm-project-menu'));+ await waitFor(key('swarm-project-menu-status'));+ await shot('project-menu');+ // Closed again by a tap above it, as the person would.+ await tester.tapAt(const Offset(20, 120));+ await waitGone(key('swarm-project-menu-status'));++ if (chat.isEmpty) return;++ // ③ The named test chat, from its decision on Swarm Home: one line+ // posted, and the decision answered with its first option.+ // Back, as the page's own chevron does: the shell's navigator.+ tester+ .state<NavigatorState>(+ find+ .descendant(+ of: find.byType(PhoneShell),+ matching: find.byType(Navigator),+ )+ .first,+ )+ .pop();+ await wait(1500);+ final card = find.byWidgetPredicate(+ (w) =>+ w is SwarmDecisionCard && w.need.decision.conversationTitle == chat,+ );+ // Swarm Home opens one need at a time: each decision in turn, until+ // the test chat's.+ final tried = <String>{};+ while (card.evaluate().isEmpty) {+ final next = keyStarting('swarm-need-row-decision:')+ .evaluate()+ .map((e) => (e.widget.key! as ValueKey<String>).value)+ .where((k) => !tried.contains(k))+ .firstOrNull;+ if (next == null) break;+ tried.add(next);+ await tester.ensureVisible(key(next));+ await tester.tap(key(next));+ await wait();+ }+ await waitFor(card);+ await shot('test-decision');+ // Who asks, at the top of the card, opens the chat it was asked in.+ await tester.tap(+ find.descendant(+ of: card.first,+ matching: find.byWidgetPredicate(+ (w) =>+ w.key is ValueKey<String> &&+ (w.key! as ValueKey<String>).value.startsWith(+ 'swarm-need-open-',+ ),+ ),+ ),+ );+ await waitFor(key('swarm-send'));+ final now = DateTime.now();+ final line =+ 'Phone e2e check ${now.hour.toString().padLeft(2, '0')}:'+ '${now.minute.toString().padLeft(2, '0')}';+ await tester.enterText(find.byType(TextField), line);+ await wait();+ await tester.tap(key('swarm-send'));+ await waitFor(find.text(line));+ await shot('posted');+ // The test decision's first option: `swarm-option-<decision>-0`.+ final option = keyStarting('swarm-option-').first;+ final optionKey = (tester.widget(option).key! as ValueKey<String>).value;+ final decision = optionKey.substring(+ 'swarm-option-'.length,+ optionKey.lastIndexOf('-'),+ );+ await tester.tap(option);+ await waitFor(key('swarm-undo-$decision'));+ await shot('decision-held');+ await waitGone(key('swarm-held-$decision'));+ await waitGone(key('swarm-option-$decision-0'));+ await wait(1500);+ await shot('decision-answered');+ },+ skip: !run,+ timeout: const Timeout(Duration(minutes: 5)),+ );+}diff --git a/mobile/integration_test/swarm_home_journey_test.dart b/mobile/integration_test/swarm_home_journey_test.dartnew file mode 100644index 000000000..922398a5e--- /dev/null+++ b/mobile/integration_test/swarm_home_journey_test.dart@@ -0,0 +1,569 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';++import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/terminal_page.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_drawer.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/ws/ws_conn.dart';++import '../test/swarm/swarm_fixture.dart';++/// Swarm Home in the real shell on a simulator, a screenshot at each step:+/// the app opens on Swarm Home; Needs you opens one thing at a time, a tag+/// with Done, a decision answered with one tap and its Undo; the drawer with+/// Buddies, the projects and a project's chats, and no Harness there; a+/// project on its project chat, its ⋮ menu at the top right; the Buddy chat+/// itself; Harness through an agent's notice and back with the terminal's+/// Swarm mark; and Swarm turned off, the terminal as it always was.+///+/// The Swarm is scripted here, in the app: a machine connection that never+/// dials answers the phone's Swarm requests (`super_tabs`, `action:+/// backend`) from it, as the daemon would forward them. Nothing reaches a+/// real account, machine, daemon or backend, and the switch is set in memory+/// only, so the simulator's saved settings are left as they were.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_home_journey_test.dart+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ testWidgets('Swarm Home, its drawer and a project, in the real shell', (+ tester,+ ) async {+ final swarm = _Swarm();+ final walk = _Walk(tester, binding, 'swarm-home');+ await _openShell(tester, swarm);+ final navigator = find+ .descendant(+ of: find.byType(PhoneShell),+ matching: find.byType(Navigator),+ )+ .first;+ // Back, as a page's own chevron does: the shell's navigator.+ Future<void> back() async {+ await tester.state<NavigatorState>(navigator).maybePop();+ await walk.wait(1200);+ }++ Future<void> drawer() async {+ await tester.tap(walk.key('swarm-menu'));+ await walk.waitFor(walk.key('swarm-drawer-home'));+ }++ // ① The app opens on Swarm Home: Needs you, one thing open; Buddies;+ // the projects, bold with something new. No terminal yet.+ await walk.waitFor(walk.key('swarm-need-decision:d1'));+ await walk.waitFor(walk.key('swarm-project-$tab-$project'));+ expect(find.byType(TerminalPage), findsNothing);+ expect(walk.key('swarm-need-row-mention:m1'), findsOneWidget);+ await walk.shot('home');++ // ② The tag opens in the decision's place, with Done.+ await tester.tap(walk.key('swarm-need-row-mention:m1'));+ await walk.waitFor(walk.key('swarm-done-m1'));+ expect(walk.key('swarm-option-d1-0'), findsNothing);+ await walk.shot('tag-open');++ // ③ The decision again: one tap holds the answer with Undo, then it+ // goes, and the next thing opens.+ await tester.tap(walk.key('swarm-need-row-decision:d1'));+ await walk.waitFor(walk.key('swarm-option-d1-0'));+ await tester.tap(walk.key('swarm-option-d1-0'));+ await walk.waitFor(walk.key('swarm-undo-d1'));+ await walk.shot('decision-held');+ await walk.waitGone(walk.key('swarm-need-decision:d1'));+ await walk.waitFor(walk.key('swarm-done-m1'));+ expect(swarm.answered, [0]);+ await walk.shot('decision-answered');++ // ④ Done on the tag: only the waiting work is left.+ await tester.tap(walk.key('swarm-done-m1'));+ await walk.waitGone(walk.key('swarm-need-mention:m1'));+ expect(swarm.done, ['m1']);+ await walk.shot('tag-done');++ // ⑤ The drawer: Swarm Home, the projects with their initial and team+ // line, then Settings, and no Harness; a project's arrow lists its chats,+ // Buddy chat first, where Chat with PM was (#2090).+ await drawer();+ expect(walk.key('swarm-drawer-settings'), findsOneWidget);+ expect(walk.key('swarm-drawer-harness'), findsNothing);+ await walk.shot('drawer');+ await tester.tap(walk.key('swarm-drawer-chats-$tab-$project'));+ await walk.waitFor(walk.key('swarm-drawer-buddy-chat-$tab-$project'));+ await walk.waitFor(walk.key('swarm-drawer-chat-$leadChat'));+ await walk.shot('drawer-chats');++ // ⑥ A project's name opens it on its project chat, its ⋮ menu at the+ // top right and nothing under the header.+ await tester.tap(walk.key('swarm-drawer-project-$tab-$project'));+ await walk.waitFor(walk.key('swarm-project-menu'));+ expect(find.byType(SwarmProjectPage), findsOneWidget);+ await walk.shot('project');++ // ⑥½ The menu: Buddy chat and the team's status, which opens the+ // project's work, then each agent, in a sheet over the chat.+ await tester.tap(walk.key('swarm-project-menu'));+ await walk.waitFor(walk.key('swarm-project-menu-status'));+ await walk.wait();+ await walk.shot('project-menu');+ await tester.tap(walk.key('swarm-project-menu-status'));+ await walk.waitFor(walk.key('swarm-team-close'));+ await walk.wait();+ await walk.shot('work');+ await tester.tap(walk.key('swarm-sheet-team'));+ await walk.wait();+ await walk.shot('team');+ await tester.tap(walk.key('swarm-team-close'));+ await walk.waitGone(walk.key('swarm-team-close'));++ // ⑦ The Buddy chat, from the menu: the person and their Buddy alone,+ // the PM's private line to them read as "River (PM) → you".+ await tester.tap(walk.key('swarm-project-menu'));+ await walk.waitFor(walk.key('swarm-project-menu-buddy-chat'));+ await tester.tap(walk.key('swarm-project-menu-buddy-chat'));+ await walk.waitFor(find.byType(SwarmConversationPage));+ await walk.waitFor(find.textContaining('Passkeys are ready'));+ await walk.waitFor(find.text('River (PM) → you'));+ FocusManager.instance.primaryFocus?.unfocus();+ await walk.shot('buddy-chat');+ await back();+ await back();+ await walk.waitFor(walk.key('swarm-menu'));++ // ⑧ Open terminal from the project team: Harness at the root. Its Swarm mark goes back to Swarm Home.+ await _openTerminal(tester, walk);+ await walk.waitFor(walk.key('swarm-mark'));+ await walk.wait(1500);+ await walk.shot('harness');+ await tester.tap(walk.key('swarm-mark'));+ await walk.waitFor(walk.key('swarm-menu'));+ expect(walk.key('tty-back'), findsNothing, reason: 'Home, not a page');+ await walk.shot('home-from-mark');++ // ⑨ Swarm off: the terminal, as it always was.+ experimentalFeaturesStore.value = const {};+ await walk.waitFor(find.byKey(const ValueKey('terminal-title')));+ expect(walk.key('swarm-menu'), findsNothing);+ await walk.wait(1500);+ await walk.shot('swarm-off');+ }, timeout: const Timeout(Duration(minutes: 3)));++ testWidgets('Home is where it was left, after Harness and back', (+ tester,+ ) async {+ final walk = _Walk(tester, binding, 'swarm-home-kept');+ await _openShell(tester, _Swarm(more: 8));+ final list = find+ .descendant(+ of: find.byType(SwarmPage),+ matching: find.byType(Scrollable),+ )+ .first;+ double offset() => tester.state<ScrollableState>(list).position.pixels;++ // ① Home, scrolled down to its projects.+ await walk.waitFor(walk.key('swarm-home-buddy-$tab-$project'));+ await tester.drag(list, const Offset(0, -500));+ await walk.wait(1200);+ final scrolled = offset();+ expect(scrolled, greaterThan(0));+ await walk.shot('home-scrolled');++ // ② Harness, from the project team.+ await _openTerminal(tester, walk);+ await walk.waitFor(walk.key('swarm-mark'));+ await walk.wait(1500);+ await walk.shot('harness');++ // ③ Back to Home with the Swarm mark: scrolled where it was.+ await tester.tap(walk.key('swarm-mark'));+ await walk.waitFor(walk.key('swarm-menu'));+ expect(offset(), scrolled);+ await walk.shot('home-back');+ }, timeout: const Timeout(Duration(minutes: 2)));+}++/// The real shell on [swarm], Swarm on, with one machine of the account+/// connected and its one agent listed; its notifier.+Future<AppNotifier> _openShell(WidgetTester tester, _Swarm swarm) async {+ const machine = Machine(+ machineId: 'mac-1',+ authMode: MachineAuthMode.remote,+ name: 'Studio Mac',+ );+ final agents = [+ <String, dynamic>{+ 'id': 'harness-agent-builder',+ 'name': 'passkeys',+ 'sessionId': 'session-review',+ 'engine': 'claude',+ 'status': 'active',+ 'terminal': {'available': true},+ 'project': {'name': 'harness', 'cwd': '/srv/harness'},+ 'updatedAt': DateTime.now().toUtc().toIso8601String(),+ },+ ];+ final notifier = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(storage: _Memory()),+ configStore: null,+ connectionForTest: (machineId) =>+ _ScriptedConn(machineId, agents, swarm.fake),+ );+ addTearDown(notifier.dispose);+ notifier+ ..currentUser = const CurrentUserProfile(id: me, email: '[email protected]')+ ..machines = [machine];+ notifier.machineStates[machine.machineId] = MachineState(machine)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = [for (final json in agents) Agent.fromJson(json)];+ // In memory only: the value, not the store's write.+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ addTearDown(() => experimentalFeaturesStore.value = const {});++ await tester.pumpWidget(_phone(PhoneShell(notifier: notifier)));+ return notifier;+}++/// Open an agent explicitly from the project's team; Home keeps its scroll.+Future<void> _openTerminal(WidgetTester tester, _Walk walk) async {+ // Each tap past its page's transition: mid-slide, a page is off to the+ // right, and the one sliding out still answers its finder.+ Future<void> tap(String key) async {+ await walk.waitFor(walk.key(key));+ await walk.wait(900);+ await tester.tap(walk.key(key));+ }++ await tap('swarm-menu');+ await walk.waitFor(walk.key('swarm-drawer-home'));+ // Below a Buddy row for every project.+ await tester.scrollUntilVisible(+ walk.key('swarm-drawer-project-$tab-$project'),+ 200,+ scrollable: find+ .descendant(+ of: find.byType(SwarmDrawer),+ matching: find.byType(Scrollable),+ )+ .first,+ );+ await tap('swarm-drawer-project-$tab-$project');+ await tap('swarm-project-menu');+ await tap('swarm-project-menu-status');+ await tap('swarm-sheet-team');+ await tap('swarm-open-terminal-agent-builder');+}++/// One Swarm, "Phone Swarm", as the backend would send it: Mobile app (River+/// its Product Manager, Nova waiting on the person, Kai working, Atlas+/// down), Website (Cleo), a decision and a tag for the person, and their+/// Buddy Wren in Mobile app with its chat. A decision answered and a tag done+/// leave.+/// [more] projects besides, for a Home taller than the screen.+class _Swarm {+ _Swarm({int more = 0}) {+ const web = 'project-2';+ const webLead = 'group-lead-web';+ Map<String, dynamic> inWeb(Map<String, dynamic> row) => {+ ...row,+ 'projectId': web,+ };+ Map<String, dynamic> projectRow(String id, String name, String lead) => {+ 'id': id,+ 'name': name,+ 'ownerId': me,+ 'leadConversationId': lead,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ };+ Map<String, dynamic> derived() => {+ 'decisionsWaiting': answered.isEmpty ? 1 : 0,+ 'mentionsWaiting': done.isEmpty ? 1 : 0,+ };+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ derived: derived(),+ head: headData(+ projects: [+ projectRow(project, 'Mobile app', leadChat),+ projectRow(web, 'Website', webLead),+ for (var i = 1; i <= more; i++)+ projectRow('project-more-$i', 'Project $i', 'lead-more-$i'),+ ],+ ),+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ agent('agent-kai', displayName: 'Kai'),+ {+ ...agent('agent-atlas', displayName: 'Atlas'),+ 'downSince': '2026-10-27T01:00:00.000Z',+ },+ inWeb(agent('agent-cleo', name: 'Lead', displayName: 'Cleo')),+ buddyData('agent-wren', displayName: 'Wren'),+ ],+ groups: [+ groupData(+ 'g1',+ title: 'Sign in with passkeys',+ number: 4,+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'needs_human',+ lastMessageSequence: 9,+ ),+ groupData(+ 'g-kai',+ title: 'Offline drafts',+ number: 6,+ agentIds: ['agent-kai'],+ status: 'working',+ workerId: 'agent-kai',+ lastMessageSequence: 20,+ ),+ groupData(+ 'g-atlas',+ title: 'Search page',+ number: 5,+ agentIds: ['agent-atlas'],+ lastMessageSequence: 3,+ ),+ buddyChatData('buddy-me', agentIds: ['agent-wren']),+ inWeb(+ groupData(+ webLead,+ title: 'Website',+ agentIds: ['agent-cleo'],+ leadId: 'agent-cleo',+ ),+ ),+ ],+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived());+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ if (answered.isEmpty)+ {+ 'id': 'd1',+ 'projectName': 'Mobile app',+ 'conversationId': 'g1',+ 'conversationTitle': 'Sign in with passkeys',+ 'askerName': 'River',+ 'question':+ 'Turn passkeys on for everyone, or behind a flag for the '+ 'first week?',+ 'options': ['Behind a flag', 'On for everyone'],+ 'recommended': 0,+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [+ if (done.isEmpty)+ {+ 'id': 'm1',+ 'projectName': 'Mobile app',+ 'conversationId': 'g1',+ 'conversationTitle': 'Sign in with passkeys',+ 'messageId': 'msg-1',+ 'leadName': 'River',+ 'text': 'Can you check the copy on the sign-in sheet?',+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (body) {+ final command = body?['command'] as Map<String, dynamic>? ?? const {};+ switch (command['type']) {+ case 'decision.answer':+ answered.add(command['choice'] as int);+ case 'mention.done':+ done.add(command['mentionId'] as String);+ }+ return {'result': <String, dynamic>{}};+ };+ fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/conversations/buddy-me/messages'] = (_) => {+ 'messages': [+ _message('pm-1', 'buddy-me', 1, me, 'How close are passkeys?'),+ _message(+ 'pm-2',+ 'buddy-me',+ 2,+ 'agent-lead',+ 'Passkeys are ready behind a flag. Nova is waiting on one '+ 'decision from you, and Atlas is down on Search page.',+ ),+ ],+ 'next': null,+ };+ }++ final fake = FakeSwarm();+ final answered = <int>[];+ final done = <String>[];++ static Map<String, dynamic> _message(+ String id,+ String conversationId,+ int sequence,+ String authorId,+ String text,+ ) => {+ 'id': id,+ 'conversationId': conversationId,+ 'text': text,+ 'sequence': sequence,+ 'author': authorId == me+ ? {'kind': 'person', 'id': me, 'name': 'Sam'}+ : {'kind': 'agent', 'id': authorId, 'name': 'River'},+ 'createdAt': '2026-10-27T0$sequence:00:00.000Z',+ };+}++/// The app's own theme, as `app_shell.dart` builds it, around [home].+Widget _phone(Widget home) {+ final brightness = grid.AppTheme.palette.value.brightness;+ grid.AppTheme.brightness.value = brightness;+ return MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => grid.BrightnessScope(child: child!),+ home: home,+ );+}++/// An account machine that never dials: it lists [_agents], and answers the+/// phone's Swarm requests (`super_tabs`, `action: backend`) from [_swarm] as+/// the daemon answers them (cli/src/superTabs/service.ts): the value, or the+/// refusal's code, words and status. Everything else gets nothing.+class _ScriptedConn extends WsConn {+ _ScriptedConn(String machineId, this._agents, this._swarm)+ : super(+ wsBaseUrl: 'ws://journey.invalid',+ autonomousEnv: 'test',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ final List<Map<String, dynamic>> _agents;+ final FakeSwarm _swarm;++ @override+ bool get isReady => true;++ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}++ @override+ Future<void> connect() async {}++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type == 'agents_list') return {'agents': _agents};+ if (type != 'super_tabs' || payload['action'] != 'backend') return {};+ try {+ final value = await _swarm.request(+ payload['method'] as String,+ payload['path'] as String,+ body: payload['body'] as Map<String, dynamic>?,+ );+ return {'ok': true, 'value': value};+ } on SuperTabFailure catch (failure) {+ return {+ 'error': failure.code,+ 'detail': failure.message,+ 'status': failure.statusCode,+ };+ }+ }+}++/// A walk's waits and its numbered screenshots, `<name>-NN-<step>`.+class _Walk {+ _Walk(this.tester, this.binding, this.name);++ final WidgetTester tester;+ final IntegrationTestWidgetsFlutterBinding binding;+ final String name;+ var _step = 0;++ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String step) async {+ // Past any page transition.+ await wait(900);+ _step++;+ await binding.takeScreenshot(+ '$name-${_step.toString().padLeft(2, '0')}-$step',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Future<void> waitGone(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never went: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));+}++class _Memory implements LocalKeyValueStore {+ final values = <String, String>{};++ @override+ Future<String?> read(String key) async => values[key];++ @override+ Future<void> write(String key, String value) async => values[key] = value;++ @override+ Future<void> delete(String key) async => values.remove(key);+}diff --git a/mobile/integration_test/swarm_home_loading_shots_test.dart b/mobile/integration_test/swarm_home_loading_shots_test.dartnew file mode 100644index 000000000..0cd851de8--- /dev/null+++ b/mobile/integration_test/swarm_home_loading_shots_test.dart@@ -0,0 +1,204 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_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' as grid;+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../test/swarm/swarm_fixture.dart';+import '../test/voice_fakes.dart' show MemoryKeyValueStore;++/// Swarm Home and its drawer while they read, on a simulator, a screenshot+/// at each step: before the list answers (rows on their way in Needs you,+/// Buddies and the projects, and in the drawer); the Swarm read while+/// what waits on the person is still being read; then everything read.+///+/// Every answer is scripted in memory ([FakeSwarm]) and held until the step+/// that shows it: nothing reaches an account, a machine or the backend.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_home_loading_shots_test.dart+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ testWidgets('Swarm Home and its drawer while they read', (tester) async {+ final walk = _Walk(tester, binding, 'home-loading');+ const web = 'project-2';+ final fake = FakeSwarm();+ Completer<void> held(String path, Object? Function() answer) {+ final gate = Completer<void>();+ fake.routes[path] = (_) async {+ await gate.future;+ return answer();+ };+ return gate;+ }++ final listed = held(+ '/api/super-tabs/list',+ () => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ },+ );+ final read = held(+ '/api/super-tabs/$tab/parts',+ () => firstLoad(+ derived: const {'decisionsWaiting': 1},+ head: headData(+ projects: [+ {+ 'id': project,+ 'name': 'Mobile',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ {+ 'id': web,+ 'name': 'Web',+ 'ownerId': me,+ 'leadConversationId': 'group-lead-web',+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ {+ ...agent('agent-cleo', name: 'Lead', displayName: 'Cleo'),+ 'projectId': web,+ },+ ],+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ number: 4,+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 9,+ ),+ {+ ...groupData(+ 'group-lead-web',+ title: 'Web',+ agentIds: ['agent-cleo'],+ leadId: 'agent-cleo',+ ),+ 'projectId': web,+ },+ ],+ ),+ );+ final asked = held(+ '/api/super-tabs/$tab/decisions?state=open',+ () => {+ 'decisions': [+ {+ 'id': 'd1',+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'askerName': 'River',+ 'question': 'Ship the login fix behind a flag?',+ 'options': ['Yes', 'No'],+ },+ ],+ },+ );+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: const {'decisionsWaiting': 1});++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmPage(),+ ),+ ),+ );++ await walk.waitFor(walk.key('swarm-projects-loading'));+ await walk.shot('home-before-list');+ await tester.tap(walk.key('swarm-menu'));+ await walk.shot('drawer-before-list');+ await tester.tap(walk.key('swarm-drawer-close'));+ await walk.wait();++ listed.complete();+ read.complete();+ await walk.waitFor(walk.key('swarm-project-$tab-$project'));+ expect(walk.key('swarm-needs-loading'), findsOneWidget);+ await walk.shot('home-asks-reading');++ asked.complete();+ await walk.waitFor(walk.key('swarm-need-decision:d1'));+ await walk.shot('home-read');+ await tester.tap(walk.key('swarm-menu'));+ await walk.shot('drawer-read');+ });+}++class _Walk {+ _Walk(this.tester, this.binding, this.name);++ final WidgetTester tester;+ final IntegrationTestWidgetsFlutterBinding binding;+ final String name;+ var _step = 0;++ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String step, {int settle = 900}) async {+ await wait(settle);+ _step++;+ await binding.takeScreenshot(+ '$name-${_step.toString().padLeft(2, '0')}-$step',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));+}diff --git a/mobile/integration_test/swarm_icon_badge_shots_test.dart b/mobile/integration_test/swarm_icon_badge_shots_test.dartnew file mode 100644index 000000000..6b3e9623d--- /dev/null+++ b/mobile/integration_test/swarm_icon_badge_shots_test.dart@@ -0,0 +1,175 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_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' as grid;+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../test/swarm/swarm_fixture.dart';+import '../test/voice_fakes.dart' show MemoryKeyValueStore;++/// The app icon's count on a simulator, through the real notice centre and+/// its `harness/app_badge` bridge: a decision, a tag and work waiting on the+/// person, so the drawer's waiting badge and the icon both say 3. With+/// `--dart-define=SWARM_BADGE_STEP=clear` the person then signs out, and the+/// icon's count goes.+///+/// The icon is on the home screen, outside the app: the host takes that+/// screenshot once the run ends (`xcrun simctl io <sim> screenshot`). The OS+/// draws a count only once badges are allowed, so the notification prompt+/// this run shows is answered on the simulator.+///+/// Every answer is scripted in memory ([FakeSwarm]): nothing reaches an+/// account, a machine or the backend.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_icon_badge_shots_test.dart+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();+ const step = String.fromEnvironment(+ 'SWARM_BADGE_STEP',+ defaultValue: 'count',+ );++ testWidgets("the app icon's count", (tester) async {+ final walk = _Walk(tester, binding, 'icon-badge-$step');+ final notices = LocalSystemNotices();+ // The prompt waits on the simulator until it is answered there, for up to+ // two minutes; the count is set whatever it says.+ unawaited(notices.requestPermission());+ for (var i = 0; i < 120 && await notices.enabled() != true; i++) {+ await Future<void>.delayed(const Duration(seconds: 1));+ }++ const derived = {'decisionsWaiting': 1, 'mentionsWaiting': 1};+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ derived: derived,+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ ],+ groups: [+ {+ ...groupData('g1', title: 'Fix login', number: 4, status: 'blocked'),+ 'assignment': {+ 'id': 'attempt-g1',+ 'agentId': 'agent-builder',+ 'status': 'blocked',+ 'result': 'No access to the repository.',+ },+ },+ ],+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'askerName': 'River',+ 'question': 'Ship the login fix behind a flag?',+ 'options': ['Yes', 'No'],+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [+ {+ 'id': 'm1',+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'messageId': 'msg-1',+ 'leadName': 'River',+ 'text': 'Can you check the copy?',+ },+ ],+ };++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: notices,+ features: features,+ );+ // Ending the session is a sign-out, which takes the count off the icon:+ // the count step leaves it up for the home screen's screenshot.+ if (step == 'clear') addTearDown(host.dispose);+ await tester.pumpWidget(+ grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmPage(),+ ),+ ),+ );++ await walk.waitFor(walk.key('swarm-need-decision:d1'));+ expect(host.session!.inbox.needs, hasLength(3));+ await tester.tap(walk.key('swarm-menu'));+ await walk.shot('drawer');++ if (step == 'clear') {+ account.value = null;+ await walk.wait();+ expect(host.session, isNull);+ }+ });+}++class _Walk {+ _Walk(this.tester, this.binding, this.name);++ final WidgetTester tester;+ final IntegrationTestWidgetsFlutterBinding binding;+ final String name;+ var _step = 0;++ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String step, {int settle = 900}) async {+ await wait(settle);+ _step++;+ await binding.takeScreenshot(+ '$name-${_step.toString().padLeft(2, '0')}-$step',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));+}diff --git a/mobile/integration_test/swarm_local_review_test.dart b/mobile/integration_test/swarm_local_review_test.dartnew file mode 100644index 000000000..79547b001--- /dev/null+++ b/mobile/integration_test/swarm_local_review_test.dart@@ -0,0 +1,464 @@+import 'dart:convert';+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';++import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/terminal_page.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/ws/ws_conn.dart';++/// Swarm on the phone against an isolated local backend, a screenshot at each+/// step. First the real shell: Home without Swarm, Settings ▸ Experimental,+/// then Swarm Home at the root, Harness from the project team, and the terminal's Swarm mark and Find's Swarm command+/// back to Swarm Home, all through the app's own Swarm path to one account+/// machine. Then the screens: what needs the person and the Swarms, a+/// project, a chat, a post with a mention, and a decision answered with one+/// tap and its Undo.+///+/// The backend is the local backend recipe's (in-memory MongoDB and Redis, a+/// fake SSO, no daemon), seeded with one Swarm whose open decision and tag are+/// for the owner. Its "machine" is a connection that forwards the phone's+/// Swarm requests to that backend over plain HTTP, as the daemon would, so+/// nothing here reaches a real account, machine or daemon: it refuses any+/// backend but 127.0.0.1 and knows only the recipe's fake owner token. Without+/// `SWARM_LOCAL_BACKEND` it skips. The screens test answers the decision, so+/// seed again before another run.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_local_review_test.dart \+/// --dart-define=SWARM_LOCAL_BACKEND=http://127.0.0.1:18085+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();+ const backend = String.fromEnvironment('SWARM_LOCAL_BACKEND');++ testWidgets(+ "the real shell's ways in: Settings, Home's mark, Find",+ (tester) async {+ final local = _LocalBackend.open(backend);+ addTearDown(local.close);+ final accountId = await local.accountId();+ final walk = _Walk(tester, binding, 'shell');++ const machine = Machine(+ machineId: 'review-machine',+ authMode: MachineAuthMode.remote,+ name: 'Studio Mac',+ );+ final agents = [+ <String, dynamic>{+ 'id': 'agent-review',+ 'name': 'passkeys',+ 'sessionId': 'session-review',+ 'engine': 'claude',+ 'status': 'active',+ 'terminal': {'available': true},+ 'project': {'name': 'harness', 'cwd': '/srv/harness'},+ 'updatedAt': DateTime.now().toUtc().toIso8601String(),+ },+ ];+ final notifier = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(storage: _Memory()),+ configStore: null,+ connectionForTest: (machineId) =>+ _ForwardingConn(machineId, agents, local),+ );+ addTearDown(notifier.dispose);+ notifier+ ..currentUser = CurrentUserProfile(+ id: accountId,+ email: '[email protected]',+ )+ ..machines = [machine];+ notifier.machineStates[machine.machineId] = MachineState(machine)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = [for (final json in agents) Agent.fromJson(json)];+ // Swarm starts off, and is turned off again however this ends: the+ // switch below writes this simulator's state file.+ experimentalFeaturesStore.value = const {};+ addTearDown(+ () => experimentalFeaturesStore.set(PhoneExperiment.swarm, false),+ );++ await tester.pumpWidget(_phone(PhoneShell(notifier: notifier)));+ // Back, as the page's own chevron does: the shell's navigator.+ Future<void> back() async {+ await tester+ .state<NavigatorState>(+ find+ .descendant(+ of: find.byType(PhoneShell),+ matching: find.byType(Navigator),+ )+ .first,+ )+ .maybePop();+ await walk.wait(1200);+ }++ // ① Home with Swarm off: no mark.+ await walk.waitFor(find.byKey(const ValueKey('terminal-title')));+ await walk.wait(1500);+ expect(walk.key('swarm-mark'), findsNothing);+ await walk.shot('home-off');++ // ② The harness menu, then Settings ▸ Experimental ▸ Swarm.+ await tester.tap(find.byKey(const ValueKey('terminal-title')));+ await walk.waitFor(find.text('Settings'));+ await walk.shot('menu');+ await tester.tap(find.text('Settings'));+ final row = walk.key('settings-experiment-swarm');+ await walk.waitFor(find.byType(Scrollable));+ await walk.wait();+ await tester.scrollUntilVisible(+ row,+ 200,+ scrollable: find.byType(Scrollable).last,+ );+ await tester.tap(find.descendant(of: row, matching: find.text('Swarm')));+ await walk.wait();+ expect(experimentalFeaturesStore.isOn(PhoneExperiment.swarm), isTrue);+ await walk.shot('settings-experimental');++ // ③ Back: Swarm Home is the root now, what needs the person first.+ await back();+ // The menu, if it stayed under Settings.+ if (find.text('Settings').evaluate().isNotEmpty) await back();+ await walk.waitFor(find.textContaining('River asks you'));+ await walk.shot('swarm-home');++ // ④ Open terminal from the project team: the terminal, its mark with how many+ // things need the person; the mark goes back to Swarm Home.+ Future<void> harness() async {+ await tester.tap(walk.keyStarting('swarm-project-').first);+ await walk.waitFor(walk.key('swarm-project-menu'));+ await tester.tap(walk.key('swarm-project-menu'));+ await walk.waitFor(walk.key('swarm-project-menu-status'));+ await tester.tap(walk.key('swarm-project-menu-status'));+ await walk.waitFor(walk.key('swarm-sheet-team'));+ await tester.tap(walk.key('swarm-sheet-team'));+ await walk.waitFor(walk.keyStarting('swarm-open-terminal-'));+ await tester.tap(walk.keyStarting('swarm-open-terminal-').first);+ await walk.waitFor(walk.key('swarm-mark-count'));+ }++ await harness();+ expect(find.text('3'), findsOneWidget);+ await walk.shot('home-mark');+ await tester.tap(walk.key('swarm-mark'));+ await walk.waitFor(find.textContaining('River asks you'));+ await walk.shot('swarm-from-home');+ await harness();++ // ⑤ Find, a swipe right on the terminal: its Swarm command.+ await tester.timedDrag(+ find.byType(TerminalPage),+ const Offset(260, 0),+ const Duration(milliseconds: 300),+ );+ await walk.waitFor(find.byType(TextField));+ await tester.enterText(find.byType(TextField).last, 'swarm');+ // Find's command row is its title alone, the match highlighted.+ final command = find.text('Swarm', findRichText: true);+ await walk.waitFor(command);+ FocusManager.instance.primaryFocus?.unfocus();+ await walk.shot('find');+ await tester.tap(command.last);+ await walk.waitFor(find.textContaining('River asks you'));+ await walk.shot('swarm-from-find');+ },+ skip: backend.isEmpty,+ timeout: const Timeout(Duration(minutes: 3)),+ );++ testWidgets(+ 'Swarm on the phone, as the owner',+ (tester) async {+ final local = _LocalBackend.open(backend);+ addTearDown(local.close);+ final accountId = await local.accountId();+ final walk = _Walk(tester, binding, 'screens');++ final account = ValueNotifier<String?>(accountId);+ final features = ExperimentalFeaturesStore(storage: _Memory())+ ..value = {PhoneExperiment.swarm};+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: local.request,+ notices: SilentSystemNotices(),+ features: features,+ );+ addTearDown(host.dispose);++ await tester.pumpWidget(+ _phone(+ const SwarmPage(),+ scope: (child) => SwarmScope(notifier: host, child: child),+ ),+ );++ // ① What needs the person, across every Swarm, then the Swarms.+ await walk.waitFor(find.textContaining('River asks you'));+ await walk.waitFor(walk.keyStarting('swarm-project-'));+ await walk.shot('swarm');++ // ② A project: its project chat, its ⋮ menu at the top right with+ // Buddy chat and the team's status; the status opens its work by+ // latest.+ await tester.tap(find.text('Mobile app').last);+ await walk.waitFor(walk.key('swarm-project-menu'));+ await walk.shot('project');+ await tester.tap(walk.key('swarm-project-menu'));+ await walk.waitFor(walk.key('swarm-project-menu-status'));+ await walk.wait();+ await walk.shot('project-menu');+ await tester.tap(walk.key('swarm-project-menu-status'));+ await walk.waitFor(walk.key('swarm-team-close'));+ await walk.wait();+ await walk.shot('project-work');++ // ③ The chat the decision was asked in, over the sheet.+ await tester.tap(find.textContaining('Sign in with passkeys').last);+ await walk.waitFor(+ find.textContaining('One thing I cannot decide alone'),+ );+ await walk.shot('chat');++ // ④ Posting: @ picks an agent, the text names it, Send.+ await tester.enterText(find.byType(TextField), '@');+ await walk.waitFor(find.text('Nova'));+ await walk.shot('mention');+ await tester.tap(find.text('Nova').last);+ await walk.wait();+ const post = '@Nova flag it for the first week, then on for everyone.';+ await tester.enterText(find.byType(TextField), post);+ await walk.wait();+ await walk.shot('posting');+ await tester.tap(walk.key('swarm-send'));+ await walk.waitFor(find.text(post));+ await walk.wait(1000);+ FocusManager.instance.primaryFocus?.unfocus();+ await walk.shot('posted');++ // ⑤ The decision: one tap holds the answer with Undo, then it goes.+ const question =+ 'Turn passkeys on for everyone, or behind a flag for the first week?';+ await tester.tap(walk.keyStarting('swarm-option-').first);+ await walk.waitFor(walk.keyStarting('swarm-undo-'));+ await walk.shot('decision-held');+ await walk.waitGone(find.text(question));+ await walk.wait(1500);+ await walk.shot('decision-answered');++ // ⑥ Back on the Swarm page, what still needs the person: the chat,+ // the sheet, then the project.+ tester.state<NavigatorState>(find.byType(Navigator))+ ..pop()+ ..pop()+ ..pop();+ await walk.wait(1500);+ await walk.shot('swarm-after');+ },+ skip: backend.isEmpty,+ timeout: const Timeout(Duration(minutes: 3)),+ );+}++/// The app's own theme, as `app_shell.dart` builds it, around [home].+Widget _phone(Widget home, {Widget Function(Widget child)? scope}) {+ final brightness = grid.AppTheme.palette.value.brightness;+ grid.AppTheme.brightness.value = brightness;+ return MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) {+ final themed = grid.BrightnessScope(child: child!);+ return scope == null ? themed : scope(themed);+ },+ home: home,+ );+}++/// The local backend recipe's server, as its fake owner.+class _LocalBackend {+ _LocalBackend._(this.base);++ factory _LocalBackend.open(String backend) {+ final base = Uri.parse(backend);+ if (base.scheme != 'http' || base.host != '127.0.0.1') {+ fail('A local review reads only a loopback backend: $backend');+ }+ return _LocalBackend._(base);+ }++ final Uri base;+ final _client = HttpClient();++ void close() => _client.close(force: true);++ Future<String> accountId() async {+ final me = await request('GET', '/api/auth/me') as Map;+ return (me['user'] as Map)['id'] as String;+ }++ /// One call: the backend's data, or its refusal as a [SuperTabFailure].+ Future<Object?> request(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ final call = await _client.openUrl(method, base.resolve(path));+ call.headers+ ..set('authorization', 'Bearer local-owner-token')+ ..set('x-autonomous-env', 'prod');+ if (body != null) {+ call.headers.contentType = ContentType.json;+ call.write(jsonEncode(body));+ }+ final response = await call.close();+ final answer =+ jsonDecode(await response.transform(utf8.decoder).join()) as Map;+ if (answer['success'] != true) {+ final error = answer['error'] as Map? ?? const {};+ throw SuperTabFailure(+ error['code'] as String? ?? 'ERROR',+ error['message'] as String? ?? 'Failed.',+ statusCode: response.statusCode,+ );+ }+ return answer['data'];+ }+}++/// An account machine that never dials: it lists [_agents], and forwards the+/// phone's Swarm requests (`super_tabs`, `action: backend`) to [_backend] and+/// answers as the daemon does (cli/src/superTabs/service.ts): the value, or+/// the refusal's code, words and status. Everything else gets nothing.+class _ForwardingConn extends WsConn {+ _ForwardingConn(String machineId, this._agents, this._backend)+ : super(+ wsBaseUrl: 'ws://review.invalid',+ autonomousEnv: 'test',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ final List<Map<String, dynamic>> _agents;+ final _LocalBackend _backend;++ @override+ bool get isReady => true;++ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}++ @override+ Future<void> connect() async {}++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type == 'agents_list') return {'agents': _agents};+ if (type != 'super_tabs' || payload['action'] != 'backend') return {};+ try {+ final value = await _backend.request(+ payload['method'] as String,+ payload['path'] as String,+ body: payload['body'] as Map<String, dynamic>?,+ );+ return {'ok': true, 'value': value};+ } on SuperTabFailure catch (failure) {+ return {+ 'error': failure.code,+ 'detail': failure.message,+ 'status': failure.statusCode,+ };+ }+ }+}++/// A walk's waits and its numbered screenshots, `<name>-NN-<step>`.+class _Walk {+ _Walk(this.tester, this.binding, this.name);++ final WidgetTester tester;+ final IntegrationTestWidgetsFlutterBinding binding;+ final String name;+ var _step = 0;++ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String step) async {+ // Past any page transition.+ await wait(900);+ _step++;+ await binding.takeScreenshot(+ '$name-${_step.toString().padLeft(2, '0')}-$step',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Future<void> waitGone(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never went: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ Finder keyStarting(String prefix) => find.byWidgetPredicate(+ (widget) =>+ widget.key is ValueKey<String> &&+ (widget.key! as ValueKey<String>).value.startsWith(prefix),+ );+}++class _Memory implements LocalKeyValueStore {+ final values = <String, String>{};++ @override+ Future<String?> read(String key) async => values[key];++ @override+ Future<void> write(String key, String value) async => values[key] = value;++ @override+ Future<void> delete(String key) async => values.remove(key);+}diff --git a/mobile/integration_test/swarm_models_devices_shots_test.dart b/mobile/integration_test/swarm_models_devices_shots_test.dartnew file mode 100644index 000000000..e12d2f24a--- /dev/null+++ b/mobile/integration_test/swarm_models_devices_shots_test.dart@@ -0,0 +1,229 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_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' as grid;+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_start.dart';++import '../test/swarm/swarm_fixture.dart';+import '../test/voice_fakes.dart' show MemoryKeyValueStore;++/// The drawer's Your models and Your devices, and the pages they open, on a+/// simulator in dark and in light, a screenshot at each step.+///+/// Every answer is scripted in memory ([FakeSwarm]): nothing reaches an+/// account, a machine or the backend.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_models_devices_shots_test.dart+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ for (final (theme, palette) in [+ ('dark', HarnessPalette.graphite),+ ('light', HarnessPalette.paper),+ ]) {+ testWidgets('Your models and Your devices, $theme', (tester) async {+ final walk = _Walk(tester, binding, 'models-devices-$theme');+ grid.AppTheme.palette.value = palette;+ grid.AppTheme.brightness.value = palette.brightness;+ final host = SwarmHost(+ accountId: () => me,+ account: ValueNotifier<String?>(me),+ request: _backend().request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ computers: _Computers(),+ );+ addTearDown(host.dispose);+ await tester.pumpWidget(+ grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: palette.brightness),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmPage(),+ ),+ ),+ );++ await walk.waitFor(walk.key('swarm-project-$tab-$project'));+ await tester.tap(walk.key('swarm-menu'));+ await walk.waitFor(walk.key('swarm-drawer-models'));+ await walk.shot('drawer');++ await tester.tap(walk.key('swarm-drawer-models'));+ await walk.waitFor(walk.key('swarm-models-api-$tab'));+ await walk.shot('models');++ await tester.tap(walk.key('tty-back'));+ await walk.wait(900);+ await tester.tap(walk.key('swarm-menu'));+ await walk.waitFor(walk.key('swarm-drawer-devices'));+ await tester.tap(walk.key('swarm-drawer-devices'));+ await walk.waitFor(walk.key('swarm-device-0'));+ await walk.shot('devices');+ });+ }+}++/// One Swarm, "Phone Swarm", whose models are on: two APIs and a local model+/// on the grid, and a model shared with Diego's Mac alone.+FakeSwarm _backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ Map<String, dynamic> machine(+ String id,+ String name,+ List<Map<String, dynamic>> models,+ ) => {+ 'machineId': id,+ 'name': name,+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'localModels': models,+ },+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) {+ final data = firstLoad();+ (data['head'] as Map)['data'] = {+ ...headData(+ projects: [+ for (final (id, name) in [+ (project, 'Mobile'),+ ('project-2', 'Website'),+ ])+ {+ 'id': id,+ 'name': name,+ 'ownerId': me,+ 'leadConversationId': id == project ? leadChat : 'lead-$id',+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ 'localModels': {'grid': 'swarm-grid', 'enabled': true, 'ready': true},+ };+ data['machines'] = [+ part(+ 'mac-1',+ 1,+ machine('mac-1', 'MacbookPro.local', [+ {+ 'grid': 'swarm-grid',+ 'model': 'moonshotai/kimi-k3',+ 'name': 'moonshotai/kimi-k3 · OpenRouter',+ 'kind': 'api',+ },+ {+ 'grid': 'swarm-grid',+ 'model': 'deepseek/deepseek-v4.1-flash',+ 'name': 'deepseek/deepseek-v4.1-flash · OpenRouter',+ 'kind': 'api',+ },+ ]),+ ),+ part(+ 'mac-2',+ 2,+ machine('mac-2', 'Studio Mac', [+ {+ 'grid': 'swarm-grid',+ 'model': 'qwen3-coder-30b',+ 'name': 'Qwen3 Coder 30B',+ 'kind': 'local',+ },+ ]),+ ),+ part(+ 'mac-3',+ 3,+ machine('mac-3', "Diego's Mac", [+ {+ 'grid': 'diego-grid',+ 'model': 'llama-4-scout',+ 'name': 'Llama 4 Scout',+ 'kind': 'shared',+ },+ ]),+ ),+ ];+ return data;+ };+ 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>[],+ };+ return fake;+}++/// The person's computers: two online, one away.+class _Computers extends ChangeNotifier implements SwarmComputers {+ @override+ final List<SwarmComputer> computers = const [+ (name: 'Studio Mac', away: false),+ (name: 'MacBook Pro', away: false),+ (name: 'Office iMac', away: true),+ ];++ @override+ bool get rechecking => false;++ @override+ Future<void> recheck() async {}++ @override+ void add(BuildContext context) {}+}++class _Walk {+ _Walk(this.tester, this.binding, this.name);++ final WidgetTester tester;+ final IntegrationTestWidgetsFlutterBinding binding;+ final String name;+ var _step = 0;++ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String step, {int settle = 900}) async {+ await wait(settle);+ _step++;+ await binding.takeScreenshot(+ '$name-${_step.toString().padLeft(2, '0')}-$step',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));+}diff --git a/mobile/integration_test/swarm_profile_shots_test.dart b/mobile/integration_test/swarm_profile_shots_test.dartnew file mode 100644index 000000000..64c3a545c--- /dev/null+++ b/mobile/integration_test/swarm_profile_shots_test.dart@@ -0,0 +1,326 @@+import 'dart:typed_data';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_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' as grid;+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_face.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../test/swarm/swarm_fixture.dart';+import '../test/voice_fakes.dart' show MemoryKeyValueStore;++/// Avatars, status and the profile sheet on a simulator, a screenshot at+/// each step, in the dark theme and then the light one: a chat with each+/// author's face and a status, a person's sheet, the profile sheet, the menu's+/// "You" row and the project page's work.+///+/// Every answer is scripted in memory ([FakeSwarm]) and the uploaded photo is+/// drawn here: nothing reaches an account, a machine or the backend.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_profile_shots_test.dart+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ for (final palette in [HarnessPalette.graphite, HarnessPalette.mist]) {+ final theme = palette.isDark ? 'dark' : 'light';+ testWidgets('avatars and status, $theme', (tester) async {+ grid.AppTheme.palette.value = palette;+ grid.AppTheme.brightness.value = palette.brightness;+ final walk = _Walk(tester, binding, 'profile-$theme');+ final photo = await tester.runAsync(_photo);+ final host = _host(_backend());+ addTearDown(host.dispose);++ await tester.pumpWidget(+ _app(+ host,+ photo!,+ palette,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ ),+ );+ await walk.waitFor(walk.key('swarm-message-m3'));+ await walk.decode();+ await walk.shot('chat');++ await tester.tap(walk.key('swarm-author-m1'));+ await walk.shot('person');+ await tester.tapAt(const Offset(200, 120));+ await walk.wait();++ await tester.tap(walk.key('swarm-author-m3'));+ await walk.wait();+ await tester.tap(walk.key('swarm-person-edit'));+ await walk.shot('profile');+ await tester.drag(+ find.byType(SingleChildScrollView).last,+ const Offset(0, -500),+ );+ await walk.shot('profile-status');+ await tester.tap(walk.key('swarm-status-☕'));+ await walk.wait(300);+ await tester.tap(walk.key('swarm-status-clears-hour'));+ await walk.shot('profile-status-chosen');++ await tester.pumpWidget(+ _app(host, photo, palette, const SwarmPage()),+ );+ await walk.wait(1500);+ await tester.tap(walk.key('swarm-menu'));+ await walk.shot('menu');++ await tester.pumpWidget(+ _app(+ host,+ photo,+ palette,+ const SwarmProjectPage(swarmId: tab, projectId: project),+ ),+ );+ await walk.decode();+ await walk.shot('project');+ });+ }+}++/// A photo as one would upload: a warm gradient with a sun in it.+Future<Uint8List> _photo() async {+ const side = 256.0;+ final recorder = ui.PictureRecorder();+ final canvas = ui.Canvas(recorder);+ canvas.drawRect(+ const ui.Rect.fromLTWH(0, 0, side, side),+ ui.Paint()+ ..shader = ui.Gradient.linear(+ const ui.Offset(0, 0),+ const ui.Offset(side, side),+ const [ui.Color(0xFFFFB347), ui.Color(0xFFD9488B)],+ ),+ );+ canvas.drawCircle(+ const ui.Offset(side * .62, side * .38),+ side * .18,+ ui.Paint()..color = const ui.Color(0xFFFFF1C1),+ );+ final image = await recorder.endRecording().toImage(256, 256);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ return bytes!.buffer.asUint8List();+}++const _tony = 'person-tony';+const _photoLink = 'https://storage.googleapis.com/avatars/river.png?sig=1';++FakeSwarm _backend() {+ final fake = FakeSwarm();+ final now = DateTime.now().toUtc();+ var me_ = <String, dynamic>{+ ...person(me),+ 'email': '[email protected]',+ 'avatar': {'kind': 'preset', 'key': 'fox'},+ 'status': {+ 'text': 'Focusing',+ 'emoji': '🎯',+ 'until': now.add(const Duration(hours: 2)).toIso8601String(),+ },+ };+ final derived = {+ 'avatars': {'agent:agent-lead': _photoLink},+ };+ Map<String, dynamic> members() => {+ 'members': [+ part(me, 1, me_),+ part(_tony, 1, {+ ...person(_tony, role: 'collaborator'),+ 'email': '[email protected]',+ 'status': {'text': 'At lunch', 'emoji': '🍽️', 'until': null},+ }),+ ],+ };+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/invitations'] = (_) => <Object>[];+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ derived: derived,+ agents: [+ {+ ...agent('agent-lead', name: 'Lead', displayName: 'River'),+ 'avatar': {'kind': 'upload'},+ },+ {+ ...agent('agent-builder', displayName: 'Nova'),+ 'avatar': {'kind': 'preset', 'key': 'owl'},+ },+ agent('agent-pike', displayName: 'Pike'),+ ],+ groups: [+ groupData(+ 'g1',+ title: 'Avatars on the phone',+ number: 509,+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ lastMessageSequence: 3,+ ),+ groupData(+ 'g2',+ title: 'Reactions',+ number: 510,+ agentIds: ['agent-pike'],+ status: 'working',+ workerId: 'agent-pike',+ ),+ ],+ ),+ ...members(),+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c2', derived: derived),+ ...members(),+ };+ fake.routes['/api/super-tabs/$tab/groups'] = (_) => {+ 'groups': <Object>[],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (body) {+ final command = body!['command'] as Map<String, dynamic>;+ if (command['type'] == 'member.status') {+ me_ = {...me_..remove('status'), 'status': ?command['status']};+ }+ return {'ok': true};+ };+ Map<String, dynamic> message(+ String id,+ int sequence,+ String text,+ Map<String, dynamic> author,+ ) => {+ 'id': id,+ 'conversationId': 'g1',+ 'text': text,+ 'sequence': sequence,+ 'author': author,+ 'attachments': <Object>[],+ 'createdAt': now+ .subtract(Duration(minutes: 10 - sequence))+ .toIso8601String(),+ };+ fake.routes['/api/super-tabs/$tab/conversations/g1/messages'] = (_) => {+ 'messages': [+ message('m1', 1, 'Can the phone show our pictures yet?', {+ 'kind': 'person',+ 'id': _tony,+ 'name': '[email protected]',+ }),+ message(+ 'm2',+ 2,+ 'Yes: photos, built-in pictures, and a status beside your face.',+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ ),+ message('m3', 3, 'Great, trying it now.', {+ 'kind': 'person',+ 'id': me,+ 'name': '[email protected]',+ }),+ ],+ 'next': null,+ };+ return fake;+}++SwarmHost _host(FakeSwarm fake) {+ final account = ValueNotifier<String?>(me);+ return SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ uploadAvatar: ({required tabId, required png}) async => 'upload-1',+ )..foreground = false;+}++/// [home] in [palette], with [host]'s Swarm over it and [photo] as every+/// uploaded picture.+Widget _app(+ SwarmHost host,+ Uint8List photo,+ HarnessPalette palette,+ Widget home,+) {+ final image = MemoryImage(photo);+ return grid.BrightnessScope(+ child: MaterialApp(+ // A new app per screen: no sheet of the last one stays open over it.+ key: ValueKey(home.runtimeType),+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: palette.brightness),+ builder: (context, child) => SwarmScope(+ notifier: host,+ child: SwarmAvatarImages(image: (_) => image, child: child!),+ ),+ home: home,+ ),+ );+}++class _Walk {+ _Walk(this.tester, this.binding, this.name);++ final WidgetTester tester;+ final IntegrationTestWidgetsFlutterBinding binding;+ final String name;+ var _step = 0;++ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ /// Lets pictures decode, which happens outside the test's frames.+ Future<void> decode() async {+ for (var i = 0; i < 10; i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 50)),+ );+ await tester.pump();+ }+ }++ Future<void> shot(String step, {int settle = 900}) async {+ await wait(settle);+ _step++;+ await binding.takeScreenshot(+ '$name-${_step.toString().padLeft(2, '0')}-$step',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));+}diff --git a/mobile/integration_test/swarm_project_loading_shots_test.dart b/mobile/integration_test/swarm_project_loading_shots_test.dartnew file mode 100644index 000000000..ec4298fb9--- /dev/null+++ b/mobile/integration_test/swarm_project_loading_shots_test.dart@@ -0,0 +1,255 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_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' as grid;+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../test/swarm/swarm_fixture.dart';+import '../test/voice_fakes.dart' show MemoryKeyValueStore;++/// A Swarm project page while it reads, on a simulator, a screenshot at each+/// step: its header and line on their way while the Swarm is read, its sheet's+/// work and team then, the page read on its project chat, a pull in the sheet,+/// and hundreds of older chats opened.+///+/// Every answer is scripted in memory ([FakeSwarm]) and held until the step+/// that shows it: nothing reaches an account, a machine or the backend.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_project_loading_shots_test.dart+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ testWidgets('a Swarm project page while it reads', (tester) async {+ final walk = _Walk(tester, binding, 'project-loading');+ final fake = FakeSwarm();+ Completer<void> held(String path, Object? Function() answer) {+ final gate = Completer<void>();+ fake.routes[path] = (_) async {+ await gate.future;+ return answer();+ };+ return gate;+ }++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ final read = held(+ '/api/super-tabs/$tab/parts',+ () => firstLoad(+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ agent('agent-reviewer', name: 'Reviewer', displayName: 'Ken'),+ ],+ groups: [+ groupData(+ leadChat,+ title: 'Mobile',+ agentIds: ['agent-lead'],+ leadId: 'agent-lead',+ ),+ // Work held by an agent, as work going on is: its avatar and a+ // line under its title.+ for (final (i, (title, worker)) in [+ ('Fix login', 'agent-builder'),+ ('Skeleton rows on Home', 'agent-reviewer'),+ ('Lazy project list', 'agent-builder'),+ ].indexed)+ groupData(+ 'g$i',+ title: title,+ number: 4 + i,+ agentIds: ['agent-lead', worker],+ status: 'working',+ workerId: worker,+ lastMessageSequence: 9 - i,+ ),+ ],+ ),+ );+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =+ (_) => {+ 'messages': [+ {+ 'id': 'm1',+ 'conversationId': leadChat,+ 'text': 'Morning: Fix login is next, then the skeleton rows.',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'createdAt': '2026-10-28T01:00:00.000Z',+ },+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ Completer<void>? pulled;+ fake.routes['/api/super-tabs/$tab/changes'] = (_) async {+ await pulled?.future;+ return changes(cursor: 'c2');+ };+ fake.routes['/api/super-tabs/$tab/groups?dormant=1&projectId=$project'] =+ (_) => {+ 'groups': [+ for (var i = 0; i < 300; i++)+ part(+ 'old-$i',+ 100 + i,+ groupData(+ 'old-$i',+ title: 'Old work ${300 - i}',+ lastMessageSequence: 1000 - i,+ dormant: true,+ ),+ ),+ ],+ 'next': null,+ };++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: Builder(+ builder: (context) => Stack(+ children: [+ const SwarmProjectPage(swarmId: tab, projectId: project),+ // The sheet as the page opens it, before the page can.+ Positioned(+ right: 0,+ bottom: 0,+ child: SizedBox.square(+ key: const ValueKey('shots-sheet'),+ dimension: 1,+ child: GestureDetector(+ onTap: () => showSwarmProjectSheet(+ context,+ swarmId: tab,+ projectId: project,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );++ await walk.waitFor(walk.key('swarm-project-loading'));+ expect(find.text('This project is no longer in the Swarm.'), findsNothing);+ await walk.shot('page-reading');+ await tester.tap(walk.key('shots-sheet'), warnIfMissed: false);+ await walk.waitFor(walk.key('swarm-work-loading'));+ await walk.shot('work-reading');+ await tester.tap(walk.key('swarm-sheet-team'));+ await walk.waitFor(walk.key('swarm-team-loading'));+ await walk.shot('team-reading');++ read.complete();+ await walk.waitFor(walk.key('swarm-agent-agent-builder'));+ await walk.shot('team-read');+ await tester.tap(walk.key('swarm-team-close'));+ await walk.waitFor(walk.key('swarm-project-menu'));+ await walk.waitFor(find.textContaining('Fix login is next'));+ await walk.shot('page-read');++ // The sheet's work: a pull reads the Swarm again, then the older chats.+ await tester.tap(walk.key('swarm-project-menu'));+ await walk.waitFor(walk.key('swarm-project-menu-status'));+ await tester.tap(walk.key('swarm-project-menu-status'));+ await walk.waitFor(walk.key('swarm-conversation-g0'));+ pulled = Completer<void>();+ await tester.fling(+ walk.key('swarm-conversation-g0'),+ const Offset(0, 300),+ 1000,+ );+ await walk.shot('work-pulled', settle: 500);+ pulled.complete();+ await walk.wait();++ final sheetList = find+ .descendant(+ of: find.byType(SwarmProjectSheet),+ matching: find.byType(Scrollable),+ )+ .first;+ await tester.tap(walk.key('swarm-older'));+ await walk.waitFor(walk.key('swarm-conversation-old-0'));+ await tester.drag(sheetList, const Offset(0, -500));+ await walk.shot('older-open');+ await tester.scrollUntilVisible(+ walk.key('swarm-conversation-old-299'),+ 600,+ maxScrolls: 100,+ scrollable: sheetList,+ );+ await walk.shot('older-last');+ });+}++class _Walk {+ _Walk(this.tester, this.binding, this.name);++ final WidgetTester tester;+ final IntegrationTestWidgetsFlutterBinding binding;+ final String name;+ var _step = 0;++ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String step, {int settle = 900}) async {+ await wait(settle);+ _step++;+ await binding.takeScreenshot(+ '$name-${_step.toString().padLeft(2, '0')}-$step',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));+}diff --git a/mobile/integration_test/swarm_reactions_shots_test.dart b/mobile/integration_test/swarm_reactions_shots_test.dartnew file mode 100644index 000000000..bb67e7568--- /dev/null+++ b/mobile/integration_test/swarm_reactions_shots_test.dart@@ -0,0 +1,234 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_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' as grid;+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 '../test/swarm/swarm_fixture.dart';+import '../test/voice_fakes.dart' show MemoryKeyValueStore;++/// Reactions in a Swarm chat on a simulator, dark then light, a screenshot at+/// each step: the counts under messages with the reader's own marked, the+/// long-press picker, a pick counted at once, and a held count naming who+/// gave it.+///+/// Every answer is scripted in memory ([FakeSwarm]): nothing reaches an+/// account, a machine or the backend.+///+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/swarm_reactions_shots_test.dart+///+/// Screenshots land in `HARNESS_JOURNEY_OUT` (default `build/journey/`).+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final mode = palette.brightness == Brightness.dark ? 'dark' : 'light';+ testWidgets('reactions in a chat, $mode', (tester) async {+ grid.AppTheme.palette.value = palette;+ grid.AppTheme.brightness.value = palette.brightness;+ addTearDown(() {+ grid.AppTheme.palette.value = HarnessPalette.graphite;+ grid.AppTheme.brightness.value = Brightness.dark;+ });+ final walk = _Walk(tester, binding, 'reactions-$mode');+ const conversation = 'g-build';+ const messages =+ '/api/super-tabs/$tab/conversations/$conversation/messages';+ final now = DateTime.now();+ var picked = false;+ Map<String, dynamic> message(+ String id,+ int sequence,+ int minute,+ String text, {+ String author = 'agent-lead',+ Map<String, List<(String, String)>> reactions = const {},+ }) => {+ 'id': id,+ 'conversationId': conversation,+ 'text': text,+ 'sequence': sequence,+ 'author': author == me+ ? {'kind': 'person', 'id': me, 'name': 'Tony'}+ : {+ 'kind': 'agent',+ 'id': author,+ 'name': author == 'agent-lead' ? 'River' : 'Jasper',+ },+ 'attachments': <Object>[],+ 'reactions': [+ for (final MapEntry(key: emoji, value: by) in reactions.entries)+ {+ 'emoji': emoji,+ 'count': by.length,+ 'by': [+ for (final (kind, who) in by) {'kind': kind, 'id': who},+ ],+ },+ ],+ 'createdAt': DateTime(+ now.year,+ now.month,+ now.day,+ 11,+ minute,+ ).toUtc().toIso8601String(),+ };+ List<Map<String, dynamic>> page() => [+ message('m1', 1, 20, 'Where are we on the phone build?', author: me),+ message(+ 'm2',+ 2,+ 24,+ 'Build 214 is green on CI. Kai runs the iPhone test after lunch.',+ reactions: {+ 'thumbs_up': [('person', me), ('person', 'person-diego')],+ 'rocket': [('agent', 'agent-jasper')],+ },+ ),+ message(+ 'm3',+ 3,+ 31,+ 'Jasper fixed the three review findings.',+ author: 'agent-jasper',+ reactions: {+ 'tada': [+ ('agent', 'agent-lead'),+ ('person', 'person-diego'),+ if (picked) ('person', me),+ ],+ 'eyes': [('person', 'person-diego')],+ },+ ),+ message('m4', 4, 33, 'I will ask you before we ship.'),+ ];++ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-jasper', displayName: 'Jasper'),+ ],+ groups: [+ groupData(+ conversation,+ title: 'Phone build',+ agentIds: ['agent-lead', 'agent-jasper'],+ status: 'working',+ workerId: 'agent-jasper',+ lastMessageSequence: 4,+ ),+ ],+ ),+ 'members': [+ part(me, 1, person(me)),+ part('person-diego', 1, person('person-diego', role: 'collaborator')),+ ],+ };+ 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': page().reversed.toList(),+ 'next': null,+ 'reactionSeq': picked ? 1 : 0,+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (_) {+ picked = true;+ return {'result': <String, dynamic>{}};+ };++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: palette.brightness),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmConversationPage(+ swarmId: tab,+ conversationId: conversation,+ ),+ ),+ ),+ );+ await walk.waitFor(walk.key('swarm-reaction-m2-thumbs_up'));+ await walk.shot('counts');++ await tester.longPress(+ find.text('Jasper fixed the three review findings.'),+ );+ await walk.shot('picker');++ await tester.tap(walk.key('swarm-react-tada'));+ await walk.shot('picked');++ await tester.longPress(walk.key('swarm-reaction-m3-tada'));+ await walk.shot('who-reacted', settle: 300);+ await walk.wait(2500);+ });+ }+}++class _Walk {+ _Walk(this.tester, this.binding, this.name);++ final WidgetTester tester;+ final IntegrationTestWidgetsFlutterBinding binding;+ final String name;+ var _step = 0;++ Future<void> wait([int ms = 600]) async {+ for (var elapsed = 0; elapsed < ms; elapsed += 100) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Future<void> shot(String step, {int settle = 900}) async {+ await wait(settle);+ _step++;+ await binding.takeScreenshot(+ '$name-${_step.toString().padLeft(2, '0')}-$step',+ );+ }++ Future<void> waitFor(Finder finder, {int seconds = 20}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ Finder key(String value) => find.byKey(ValueKey(value));+}diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swiftindex 068807a00..2f335dcc3 100644--- a/mobile/ios/Runner/AppDelegate.swift+++ b/mobile/ios/Runner/AppDelegate.swift@@ -1,6 +1,8 @@+import AVFoundationimport AudioToolboximport AuthenticationServicesimport Flutter+import Speechimport UIKitimport UserNotifications@@ -24,6 +26,330 @@ import UserNotificationsSignInPageChannel.register(with: engineBridge.pluginRegistry)HandoffChannel.register(with: engineBridge.pluginRegistry)ChimeChannel.register(with: engineBridge.pluginRegistry)+ AppBadgeChannel.register(with: engineBridge.pluginRegistry)+ DictationChannel.register(with: engineBridge.pluginRegistry)+ }+}++/// `harness/dictation` — the phone's own speech recognizer, the one the keyboard's dictation uses+/// (Dart: `SwarmChannelDictation` in `lib/swarm/swarm_dictation.dart`): a Swarm chat's message box+/// fills with the words as they are said.+///+/// `access` asks for speech recognition, then the microphone, the first time, and answers `allowed`,+/// `denied` (speech recognition refused or restricted: Dart records and has the backend transcribe,+/// as before) or `noMic`. `start` takes Dart's `take` and a `locale`, and answers false when the+/// phone has no recognizer for it now. Then, each with the take: `words` (the recognizer's latest+/// best guess, `text`; `final` once it says that guess is finished; `from` and `to`, where its words+/// begin and end in the session's audio, 0 when it gives no times — Dart works out what is done from+/// these), `level` (the microphone's RMS, ten a second), `paused` whenever the recognizer ends a+/// session by itself, and once `end` — `done`, `noSpeech` or `failed`. `stop` ends listening, and the+/// last words and the end follow; `cancel` ends it with nothing more said.+///+/// ⚠️ **A take listens until it is stopped** (Tony, 10-29: "until I tap"). iOS ends a recognizer's+/// session by itself — after a pause, a long silence, its own minute — and the microphone is kept+/// open through that: `paused` says so, and Dart's `resume` starts the next session at once, false+/// when it cannot. Only a call or another app taking the audio (an interruption) ends the take as+/// `failed`. The screen does not dim or lock meanwhile: talking is not a touch.+///+/// ⚠️ **Set as the keyboard's dictation is** (Tony, 10-29: "exactly like the keyboard"): the+/// dictation hint, punctuation, live guesses, no contextual words — and on the phone or on Apple's+/// servers as the recognizer chooses, not forced on the phone, where Vietnamese can be heard worse.+/// Nothing heard is logged or kept here.+final class DictationChannel {+ private static var shared: DictationChannel?++ private let channel: FlutterMethodChannel++ /// The take listening now.+ private var current: Take?++ static func register(with registry: FlutterPluginRegistry) {+ guard let messenger = registry.registrar(forPlugin: "HarnessDictation")?.messenger() else { return }+ shared = DictationChannel(messenger: messenger)+ }++ private init(messenger: FlutterBinaryMessenger) {+ channel = FlutterMethodChannel(name: "harness/dictation", binaryMessenger: messenger)+ channel.setMethodCallHandler { [weak self] call, result in+ self?.handle(call, result: result)+ }+ }++ private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {+ let arguments = call.arguments as? [String: Any]+ let take = arguments?["take"] as? Int+ switch call.method {+ case "access":+ Self.access { result($0) }+ case "start":+ guard let take, let locale = arguments?["locale"] as? String else {+ result(FlutterError(code: "bad-args", message: "A take and a locale", details: nil))+ return+ }+ result(start(take, locale: locale))+ case "resume":+ guard let current, current.id == take else {+ result(false)+ return+ }+ result(resume(current))+ case "stop":+ if let current, current.id == take { stop(current) }+ result(nil)+ case "cancel":+ if current?.id == take { finish(nil) }+ result(nil)+ default:+ result(FlutterMethodNotImplemented)+ }+ }++ /// Speech recognition, then the microphone: asked the first time, and answered at once after.+ private static func access(_ answer: @escaping (String) -> Void) {+ SFSpeechRecognizer.requestAuthorization { status in+ guard status == .authorized else {+ DispatchQueue.main.async { answer("denied") }+ return+ }+ let microphone: (Bool) -> Void = { granted in+ DispatchQueue.main.async { answer(granted ? "allowed" : "noMic") }+ }+ if #available(iOS 17.0, *) {+ AVAudioApplication.requestRecordPermission(completionHandler: microphone)+ } else {+ AVAudioSession.sharedInstance().requestRecordPermission(microphone)+ }+ }+ }++ /// Listens for [take] in [locale]: the microphone opens, and the recognizer's first session+ /// starts. False, with nothing open, when it cannot.+ private func start(_ take: Int, locale: String) -> Bool {+ finish(nil)+ guard let recognizer = SFSpeechRecognizer(locale: Locale(identifier: locale)),+ recognizer.isAvailable+ else { return false }++ let session = AVAudioSession.sharedInstance()+ let engine = AVAudioEngine()+ let feed = Feed()+ var measured = 0.0+ let heard: AVAudioNodeTapBlock = { [weak self] buffer, _ in+ feed.append(buffer)+ let now = CACurrentMediaTime()+ guard now - measured >= 0.1, let rms = Self.rms(buffer) else { return }+ measured = now+ DispatchQueue.main.async {+ guard let self, self.current?.id == take else { return }+ self.channel.invokeMethod("level", arguments: ["take": take, "rms": rms])+ }+ }+ let input = engine.inputNode+ do {+ try session.setCategory(.record, mode: .measurement, options: .duckOthers)+ try session.setActive(true, options: .notifyOthersOnDeactivation)+ let format = input.outputFormat(forBus: 0)+ guard format.sampleRate > 0, format.channelCount > 0 else {+ try? session.setActive(false, options: .notifyOthersOnDeactivation)+ return false+ }+ input.installTap(onBus: 0, bufferSize: 1024, format: format, block: heard)+ engine.prepare()+ try engine.start()+ } catch {+ input.removeTap(onBus: 0)+ engine.stop()+ try? session.setActive(false, options: .notifyOthersOnDeactivation)+ return false+ }++ let listening = Take(+ id: take, recognizer: recognizer, engine: engine, feed: feed,+ idleWas: UIApplication.shared.isIdleTimerDisabled)+ current = listening+ // A call, a timer's alarm, another app's audio: the microphone is gone, and the take with it.+ listening.interruption = NotificationCenter.default.addObserver(+ forName: AVAudioSession.interruptionNotification, object: session, queue: .main+ ) { [weak self] note in+ let type = (note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt)+ .flatMap(AVAudioSession.InterruptionType.init(rawValue:))+ guard let self, self.current === listening, type == .began else { return }+ self.finish("failed")+ }+ UIApplication.shared.isIdleTimerDisabled = true+ listen(listening)+ return true+ }++ /// A new session of the recognizer's in [take], fed by the microphone from now on.+ private func listen(_ take: Take) {+ let request = SFSpeechAudioBufferRecognitionRequest()+ request.shouldReportPartialResults = true+ request.taskHint = .dictation+ request.contextualStrings = []+ if #available(iOS 16.0, *) { request.addsPunctuation = true }+ take.session += 1+ let session = take.session+ take.feed.request = request+ take.task = take.recognizer.recognitionTask(with: request) { [weak self] result, error in+ let text = result?.bestTranscription.formattedString+ let segments = result?.bestTranscription.segments ?? []+ let from = segments.first?.timestamp ?? 0+ let to = segments.last.map { $0.timestamp + $0.duration } ?? 0+ // Finished: the session's last guess, or one the recognizer marks as the end of what was said+ // before a pause, after which it may start its words over.+ let finished = result.map { $0.isFinal || $0.speechRecognitionMetadata != nil } ?? false+ let final = result?.isFinal ?? false+ // "No speech detected": ended, or given up, before a word was heard.+ let silent = (error as NSError?).map { $0.domain == "kAFAssistantErrorDomain" && $0.code == 1110 }+ DispatchQueue.main.async {+ guard let self, self.current === take, take.session == session, take.task != nil else { return }+ if let text {+ self.channel.invokeMethod(+ "words",+ arguments: ["take": take.id, "text": text, "final": finished, "from": from, "to": to])+ }+ guard final || silent != nil else { return }+ take.task = nil+ take.feed.request = nil+ let end = final ? "done" : silent == true ? "noSpeech" : "failed"+ if take.stopping {+ self.finish(end)+ } else {+ self.channel.invokeMethod("paused", arguments: ["take": take.id, "end": end])+ }+ }+ }+ }++ /// The next session, after the recognizer ended one by itself. False when the take cannot go on:+ /// it is stopping, its microphone stopped, or the recognizer cannot be had now.+ private func resume(_ take: Take) -> Bool {+ if take.task != nil { return true }+ guard !take.stopping, take.engine.isRunning, take.recognizer.isAvailable else { return false }+ listen(take)+ return true+ }++ /// No more audio for [take]: the session's last words, then the end — at once when no session is+ /// listening, between one the recognizer ended and the next.+ private func stop(_ take: Take) {+ take.stopping = true+ take.engine.stop()+ take.engine.inputNode.removeTap(onBus: 0)+ guard let request = take.feed.request else {+ finish("done")+ return+ }+ take.feed.request = nil+ request.endAudio()+ }++ /// Closes the take listening now, and says how it ended — or nothing, for a cancel.+ private func finish(_ end: String?) {+ guard let take = current else { return }+ current = nil+ take.task?.cancel()+ take.task = nil+ take.engine.stop()+ take.engine.inputNode.removeTap(onBus: 0)+ take.feed.request?.endAudio()+ take.feed.request = nil+ if let interruption = take.interruption { NotificationCenter.default.removeObserver(interruption) }+ try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)+ UIApplication.shared.isIdleTimerDisabled = take.idleWas+ if let end { channel.invokeMethod("end", arguments: ["take": take.id, "end": end]) }+ }++ /// How loud [buffer] is, 0…1 of full scale.+ private static func rms(_ buffer: AVAudioPCMBuffer) -> Double? {+ guard let samples = buffer.floatChannelData?[0], buffer.frameLength > 0 else { return nil }+ let count = Int(buffer.frameLength)+ var sum: Float = 0+ for index in 0..<count { sum += samples[index] * samples[index] }+ return Double((sum / Float(count)).squareRoot())+ }+}++/// One take, from `start` to its end: the microphone open throughout, its tap on the engine's+/// input, while the recognizer's sessions come and go in it ([DictationChannel]).+private final class Take {+ let id: Int+ let recognizer: SFSpeechRecognizer+ let engine: AVAudioEngine+ let feed: Feed++ /// Whether the screen was kept awake before the take, as it is again after.+ let idleWas: Bool++ /// The recognizer's session now, and its number: what an earlier one still says lands nowhere.+ var task: SFSpeechRecognitionTask?+ var session = 0++ /// `stop` was asked: the session ending now is the take's last.+ var stopping = false+ var interruption: NSObjectProtocol?++ init(id: Int, recognizer: SFSpeechRecognizer, engine: AVAudioEngine, feed: Feed, idleWas: Bool) {+ self.id = id+ self.recognizer = recognizer+ self.engine = engine+ self.feed = feed+ self.idleWas = idleWas+ }+}++/// Where the microphone's audio goes: the request of the recognizer's session now. Changed on the+/// main thread while the tap appends to it on the audio thread, so behind a lock.+private final class Feed {+ private let lock = NSLock()+ private var current: SFSpeechAudioBufferRecognitionRequest?++ var request: SFSpeechAudioBufferRecognitionRequest? {+ get {+ lock.lock()+ defer { lock.unlock() }+ return current+ }+ set {+ lock.lock()+ defer { lock.unlock() }+ current = newValue+ }+ }++ func append(_ buffer: AVAudioPCMBuffer) {+ lock.lock()+ defer { lock.unlock() }+ current?.append(buffer)+ }+}++/// `harness/app_badge` — the app icon's count (Dart: `setSwarmBadge` in `lib/notify/system_notices.dart`):+/// what the Swarms ask of the person, the drawer's waiting count. `set` takes the count; zero takes it+/// off. Drawn only where the person allowed badges with the notification prompt.+enum AppBadgeChannel {+ static func register(with registry: FlutterPluginRegistry) {+ guard let messenger = registry.registrar(forPlugin: "HarnessAppBadge")?.messenger() else { return }+ let channel = FlutterMethodChannel(name: "harness/app_badge", binaryMessenger: messenger)+ channel.setMethodCallHandler { call, result in+ guard call.method == "set" else { result(FlutterMethodNotImplemented); return }+ guard let count = call.arguments as? Int, count >= 0 else {+ result(FlutterError(code: "bad_count", message: "A count of zero or more.", details: nil))+ return+ }+ if #available(iOS 16.0, *) {+ // The completion can run off the main thread; Flutter is answered on it.+ UNUserNotificationCenter.current().setBadgeCount(count) { error in+ DispatchQueue.main.async {+ result(error.map { FlutterError(code: "badge", message: $0.localizedDescription, details: nil) })+ }+ }+ } else {+ UIApplication.shared.applicationIconBadgeNumber = count+ result(nil)+ }+ }}}diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plistindex b6a985b4c..da55332a9 100644--- a/mobile/ios/Runner/Info.plist+++ b/mobile/ios/Runner/Info.plist@@ -37,12 +37,16 @@<false/><key>LSRequiresIPhoneOS</key><true/>- <!-- Taking a picture to send to an agent. Only the camera needs a string on- iOS 15: picking from the library goes through PHPicker, which runs out of- process and grants nothing, so NSPhotoLibraryUsageDescription would never- be shown and is deliberately absent. -->+ <!-- Taking a picture to send to an agent or into a Swarm chat. Picking from+ the library goes through PHPicker, which runs out of process and grants+ nothing, and the Swarm chat asks for no metadata, so iOS does not show+ NSPhotoLibraryUsageDescription today. It is set anyway, in plain words,+ so a library read that does ask (a future iOS, or a picker option) says+ why rather than ending the app. --><key>NSCameraUsageDescription</key>- <string>Scan the code on your computer to connect, or take a photo to send to an agent.</string>+ <string>Scan the code on your computer to connect, or take a photo to send to an agent or a Swarm chat.</string>+ <key>NSPhotoLibraryUsageDescription</key>+ <string>Choose photos to send to an agent or a Swarm chat. Harness sees only the photos you pick.</string><!-- What iOS shows when the app first reaches an address on the local network.Computers are reached through the relay, so today that is a backend on aLAN address in development, or the debugger in a debug build. Set here, it@@ -51,12 +55,18 @@which only adds its own when the app has none. --><key>NSLocalNetworkUsageDescription</key><string>Connect to the computers running Harness on your local network.</string>- <!-- Voice input, what tapping a terminal opens. Asked for on the first tap,- not at launch. The microphone alone: the recording is transcribed by- the Harness backend (`/api/voice/stt`, the dial's own path), not by the- OS, so there is no Speech Recognition permission to ask for. -->+ <!-- Voice input, what tapping a terminal's mic opens. Asked for on the+ first tap, not at launch. A terminal's recording is transcribed by the+ Harness backend (`/api/voice/stt`, the dial's own path), not by the OS. --><key>NSMicrophoneUsageDescription</key>- <string>Talk to an agent in a terminal instead of typing.</string>+ <string>Talk instead of typing, in a terminal or a chat.</string>+ <!-- A Swarm chat's mic: the phone's own recognizer, the keyboard's+ dictation, writes the words into the message box as they are said+ (`DictationChannel` in AppDelegate.swift). Asked for on its first tap,+ before the microphone. Refused, the chat records and the backend+ transcribes, as a terminal does. -->+ <key>NSSpeechRecognitionUsageDescription</key>+ <string>Show what you say in a chat's message box as you say it.</string><!-- Save Image and Save Video in the share sheet of a terminal's mediapreview (`phone/media_preview_page.dart`). Adding to the library is allit does, and iOS ends the app at that button when this string isdiff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartindex 7414c9596..45832d018 100644--- a/mobile/lib/api/api_client.dart+++ b/mobile/lib/api/api_client.dart@@ -6,6 +6,7 @@ import '../auth/auth_session.dart';import '../core/config.dart';import '../core/models.dart';import '../logging/http_log.dart';+import '../swarm/swarm_request.dart' show SuperTabFailure;import '../viewer/device_ack.dart';import '../viewer/device_log.dart';import '../viewer/device_log_sync.dart'@@ -338,6 +339,91 @@ class ApiClient {final data = unwrapApiResponse(res) as Map<String, dynamic>;return (data['transcript'] as String? ?? '').trim();}+ // -- Swarm chat files (backend only: the viewer's own SSO session signs it) --++ /// Sends one file for a message in [conversationId] of Swarm [tabId] and+ /// answers the backend's `{attachment: {...}}` — `POST+ /// /api/super-tabs/:tabId/attachments`, the form Desktop sends.+ ///+ /// Straight to the backend with the token this viewer holds, unlike every+ /// other Swarm call, which one of the account's machines forwards+ /// (`AppNotifier.swarmRequest`): the backend takes a chat file only from the+ /// client itself, and a machine forwards only JSON. [onProgress] is told the+ /// part sent, from 0 to 1. A refusal throws a [SuperTabFailure] carrying the+ /// backend's code, worded as Desktop's `superTabUploadRefusal`.+ Future<Map<String, dynamic>> uploadSwarmAttachment({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+ }) async {+ final body = multipartFileBody(+ fields: {'conversationId': conversationId},+ field: 'file',+ filename: name,+ fileContentType: mime,+ file: bytes,+ boundary: 'harness-${DateTime.now().microsecondsSinceEpoch}',+ );+ final res = await _dio.post(+ '/api/super-tabs/${Uri.encodeComponent(tabId)}/attachments',+ data: body.bytes,+ cancelToken: cancel,+ onSendProgress: (sent, total) {+ if (total > 0) onProgress(sent / total);+ },+ options: Options(+ contentType: body.contentType,+ // Ten megabytes on a phone connection; the chat's own watchdog gives+ // up on an upload that stops moving.+ sendTimeout: const Duration(minutes: 5),+ receiveTimeout: const Duration(minutes: 1),+ ),+ );+ final data = res.data;+ if (res.statusCode == 200 && data is Map && data['success'] == true) {+ return Map<String, dynamic>.from(data['data'] as Map);+ }+ final error = data is Map ? data['error'] : null;+ final code = error is Map ? error['code'] as String? : null;+ final message = error is Map ? error['message'] as String? : null;+ throw SuperTabFailure(+ code ?? 'UPLOAD_FAILED',+ message ??+ switch (code) {+ 'FORBIDDEN' => 'You can’t send files in this conversation.',+ 'ATTACHMENT_TOO_LARGE' => 'That file is over 10 MB.',+ _ => 'Could not upload the file. Try again.',+ },+ statusCode: res.statusCode ?? 0,+ );+ }++ // -- Swarm avatars (backend only: the computer a Swarm call goes through carries text) --++ /// Uploads [png] as an avatar picture of the Swarm [tabId] and answers the+ /// upload's id — `POST /api/super-tabs/:tabId/avatars` (backend+ /// superTabs/profile.ts); a `member.avatar` command then makes it the+ /// person's.+ Future<String> uploadSwarmAvatar(String tabId, Uint8List png) async {+ final body = multipartFileBody(+ field: 'file',+ filename: 'avatar.png',+ fileContentType: 'image/png',+ file: png,+ boundary: 'harness-${DateTime.now().microsecondsSinceEpoch}',+ );+ final res = await _dio.post(+ '/api/super-tabs/${Uri.encodeComponent(tabId)}/avatars',+ data: body.bytes,+ options: Options(contentType: body.contentType),+ );+ final data = unwrapApiResponse(res) as Map<String, dynamic>;+ return (data['avatar'] as Map<String, dynamic>)['id'] as String;+ }}class ApiException implements Exception {diff --git a/mobile/lib/api/multipart_body.dart b/mobile/lib/api/multipart_body.dartindex 719f0d778..8200b5bca 100644--- a/mobile/lib/api/multipart_body.dart+++ b/mobile/lib/api/multipart_body.dart@@ -1,28 +1,47 @@import 'dart:convert';import 'dart:typed_data';-/// A `multipart/form-data` body holding one file, as plain bytes.+/// A `multipart/form-data` body holding [fields], then one file, as plain bytes.////// Built by hand rather than with Dio's `FormData`, because a `FormData` can be/// sent exactly once: [BearerAuthInterceptor] answers a 401 by refreshing the/// token and re-sending the SAME request, and a finalized `FormData` throws/// there instead of going out again. Bytes go out as many times as asked.+///+/// Names are escaped as Dio's `FormData` escapes them (a quote and a line break+/// percent-encoded), so a file's name cannot end its header early.({Uint8List bytes, String contentType}) multipartFileBody({+ Map<String, String> fields = const {},required String field,required String filename,required String fileContentType,required Uint8List file,required String boundary,}) {- final head =- '--$boundary\r\n'- 'Content-Disposition: form-data; name="$field"; filename="$filename"\r\n'- 'Content-Type: $fileContentType\r\n\r\n';+ final head = StringBuffer();+ for (final MapEntry(:key, :value) in fields.entries) {+ head+ ..write('--$boundary\r\n')+ ..write('Content-Disposition: form-data; name="${_escape(key)}"\r\n\r\n')+ ..write('$value\r\n');+ }+ head+ ..write('--$boundary\r\n')+ ..write(+ 'Content-Disposition: form-data; name="${_escape(field)}"; '+ 'filename="${_escape(filename)}"\r\n',+ )+ ..write('Content-Type: $fileContentType\r\n\r\n');final bytes =(BytesBuilder(copy: false)- ..add(utf8.encode(head))+ ..add(utf8.encode(head.toString()))..add(file)..add(utf8.encode('\r\n--$boundary--\r\n'))).takeBytes();return (bytes: bytes, contentType: 'multipart/form-data; boundary=$boundary');}++String _escape(String value) => value+ .replaceAll('\r', '%0D')+ .replaceAll('\n', '%0A')+ .replaceAll('"', '%22');diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dartindex d072de08b..e37be018c 100644--- a/mobile/lib/e2ee/envelope.dart+++ b/mobile/lib/e2ee/envelope.dart@@ -79,6 +79,9 @@ const Set<String> encryptedDownTypes = {// A Harness OS computer managed from here (`AppNotifier.osDevice`, CLI services/osDevice.ts): its// update, and its Wi-Fi with the password. A `MACHINE_REQUESTS` type in the CLI.'os_device',+ // Swarm (`AppNotifier.swarmRequest`, CLI superTabs/service.ts): the machine forwards the call to the+ // backend, and the answer is the Swarm's conversations and decisions. A `MACHINE_REQUESTS` type in the CLI.+ 'super_tabs','codex_profiles_list','codex_profile_link',// Asks the machine to read its OWN agent accounts' usage (cli/src/lib/accountUsage.ts). Missingdiff --git a/mobile/lib/notify/system_notices.dart b/mobile/lib/notify/system_notices.dartindex 12cfdc961..e7091d935 100644--- a/mobile/lib/notify/system_notices.dart+++ b/mobile/lib/notify/system_notices.dart@@ -1,4 +1,5 @@import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';import 'package:flutter_local_notifications/flutter_local_notifications.dart';import 'package:harness_mobile/core/last_opened_agent.dart';@@ -17,6 +18,44 @@ typedef AgentNoticeMessage = ({String body,});+/// Where a Swarm notice leads: the Swarm, and the conversation it is about.+typedef SwarmNoticeTarget = ({+ String swarmId,+ String conversationId,+ String? messageId,+ String? decisionId,+});++/// One notice about what a Swarm asks of the person. [key] names it, so the+/// same need posted twice replaces itself; [subtitle] says where it is.+typedef SwarmNoticeMessage = ({+ String key,+ String title,+ String subtitle,+ String body,+ SwarmNoticeTarget target,+});++/// The notification centre's Swarm notices: decisions asked of the person,+/// Lead tags, work waiting on them.+///+/// Not on [SystemNotices], whose stand-ins would all have to answer it:+/// [LocalSystemNotices] and [SilentSystemNotices] carry both.+abstract interface class SwarmNotices {+ Future<void> showSwarm(SwarmNoticeMessage message);++ /// Takes the notice [key] names back down: its need was met somewhere else.+ Future<void> cancelSwarm(String key);++ /// Shows [count] on the app icon: what the Swarms ask of the person, the+ /// drawer's waiting count. Zero takes it off.+ Future<void> setSwarmBadge(int count);++ /// The Swarm notice tapped last — what the shell opens. Reset to null by+ /// whoever acts on it.+ ValueNotifier<SwarmNoticeTarget?> get openedSwarm;+}+/// The OS notification centre, as far as the phone uses it.////// An interface so the notifier's tests never reach a platform plugin — see@@ -47,13 +86,16 @@ abstract interface class SystemNotices {}/// Nothing leaves the process. What a test notifier is given.-class SilentSystemNotices implements SystemNotices {+class SilentSystemNotices implements SystemNotices, SwarmNotices {@overridefinal opened = ValueNotifier<AgentRef?>(null);@overridefinal openedDevice = ValueNotifier<String?>(null);+ @override+ final openedSwarm = ValueNotifier<SwarmNoticeTarget?>(null);+@overrideFuture<bool?> requestPermission() async => null;@@ -65,6 +107,15 @@ class SilentSystemNotices implements SystemNotices {@overrideFuture<void> showAccountNotice({required String key, required String title, required String body}) async {}++ @override+ Future<void> showSwarm(SwarmNoticeMessage message) async {}++ @override+ Future<void> cancelSwarm(String key) async {}++ @override+ Future<void> setSwarmBadge(int count) async {}}/// Whether the OS lets this app post notices right now — Settings ▸ Notifications reads it. Null@@ -90,11 +141,21 @@ const noticesWhen =/// is `machine\nagent`, so the two never read as each other.const _devicePayload = 'device:';+/// What a Swarm notice's payload starts with: `swarm:<swarm>/<conversation>`, each part+/// URI-encoded, with no newline — so it never reads as an agent's or a device's.+const _swarmPayload = 'swarm:';++/// The Android channel, iOS thread and iOS category of Swarm notices.+const _swarmChannel = 'swarm-needs-you';++/// `harness/app_badge` — the app icon's count (Swift: `AppBadgeChannel` in `ios/Runner/AppDelegate.swift`).+const _appBadge = MethodChannel('harness/app_badge');+/// The real centre, through flutter_local_notifications.////// Started lazily on first use, so a launch that never needs it — and every/// test — pays nothing for it.-class LocalSystemNotices implements SystemNotices {+class LocalSystemNotices implements SystemNotices, SwarmNotices {LocalSystemNotices([FlutterLocalNotificationsPlugin? plugin]): _plugin = plugin ?? FlutterLocalNotificationsPlugin();@@ -107,6 +168,9 @@ class LocalSystemNotices implements SystemNotices {@overridefinal openedDevice = ValueNotifier<String?>(null);+ @override+ final openedSwarm = ValueNotifier<SwarmNoticeTarget?>(null);+/// One Android channel per kind, so a person can silence finished turns and/// still hear questions — the two are not equally urgent. Also the iOS/// thread each kind is grouped under.@@ -142,6 +206,17 @@ class LocalSystemNotices implements SystemNotices {requestAlertPermission: false,requestBadgePermission: false,requestSoundPermission: false,+ // A Swarm notice on a phone that hides previews still says who asks+ // and where.+ notificationCategories: [+ DarwinNotificationCategory(+ _swarmChannel,+ options: {+ DarwinNotificationCategoryOption.hiddenPreviewShowTitle,+ DarwinNotificationCategoryOption.hiddenPreviewShowSubtitle,+ },+ ),+ ],),),onDidReceiveNotificationResponse: (response) => _open(response.payload),@@ -155,6 +230,10 @@ class LocalSystemNotices implements SystemNotices {}void _open(String? payload) {+ if (decodeSwarmPayload(payload) case final target?) {+ openedSwarm.value = target;+ return;+ }// A device notice carries `device:<key>` — no newline, so it never reads as an agent's payload.if (payload != null && payload.startsWith(_devicePayload)) {openedDevice.value = payload.substring(_devicePayload.length);@@ -172,7 +251,7 @@ class LocalSystemNotices implements SystemNotices {.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()- ?.requestPermissions(alert: true, sound: true);+ ?.requestPermissions(alert: true, sound: true, badge: true);final android = await _plugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin@@ -264,6 +343,61 @@ class LocalSystemNotices implements SystemNotices {}}+ @override+ Future<void> showSwarm(SwarmNoticeMessage message) async {+ try {+ await _init();+ await _plugin.show(+ id: swarmNoticeIdFor(message.key),+ title: message.title,+ body: message.body,+ payload: encodeSwarmPayload(message.target),+ notificationDetails: NotificationDetails(+ android: AndroidNotificationDetails(+ _swarmChannel,+ 'Swarm needs you',+ channelDescription:+ 'A Swarm asks you to decide, tags you, or has work waiting on you.',+ importance: Importance.high,+ priority: Priority.high,+ subText: message.subtitle,+ // Hidden on a secure lock screen set to hide private content.+ visibility: NotificationVisibility.private,+ ),+ iOS: DarwinNotificationDetails(+ subtitle: message.subtitle,+ threadIdentifier: _swarmChannel,+ categoryIdentifier: _swarmChannel,+ ),+ ),+ );+ } catch (error) {+ appLog.warn('notify', 'swarm notice failed', error: error);+ }+ }++ @override+ Future<void> cancelSwarm(String key) async {+ try {+ await _init();+ await _plugin.cancel(id: swarmNoticeIdFor(key));+ } catch (error) {+ appLog.warn('notify', 'swarm cancel failed', error: error);+ }+ }++ /// iOS only: Android has no count of its own on the icon — launchers draw a dot from the+ /// notices posted.+ @override+ Future<void> setSwarmBadge(int count) async {+ if (defaultTargetPlatform != TargetPlatform.iOS) return;+ try {+ await _appBadge.invokeMethod<void>('set', count);+ } catch (error) {+ appLog.warn('notify', 'swarm badge failed', error: error);+ }+ }+@overrideFuture<void> cancel(AgentRef agent) async {try {@@ -298,6 +432,53 @@ int accountNoticeIdFor(String key) {return hash;}+/// A stable, positive id per Swarm notice — the same FNV-1a, over its own key, so it never lands+/// on an agent's or an account's.+@visibleForTesting+int swarmNoticeIdFor(String key) {+ var hash = 0x811c9dc5;+ for (final unit in 'swarm\n$key'.codeUnits) {+ hash = ((hash ^ unit) * 0x01000193) & 0x7fffffff;+ }+ return hash;+}++@visibleForTesting+String encodeSwarmPayload(SwarmNoticeTarget target) =>+ '$_swarmPayload${Uri.encodeComponent(target.swarmId)}'+ '/${Uri.encodeComponent(target.conversationId)}'+ '${target.messageId != null+ ? '/message/${Uri.encodeComponent(target.messageId!)}'+ : target.decisionId != null+ ? '/decision/${Uri.encodeComponent(target.decisionId!)}'+ : ''}';++@visibleForTesting+SwarmNoticeTarget? decodeSwarmPayload(String? payload) {+ if (payload == null || !payload.startsWith(_swarmPayload)) return null;+ final parts = payload.substring(_swarmPayload.length).split('/');+ if ((parts.length != 2 && parts.length != 4) || parts.any((p) => p.isEmpty)) {+ return null;+ }+ if (parts.length == 4 && !const ['message', 'decision'].contains(parts[2])) {+ return null;+ }+ try {+ return (+ swarmId: Uri.decodeComponent(parts[0]),+ conversationId: Uri.decodeComponent(parts[1]),+ messageId: parts.length == 4 && parts[2] == 'message'+ ? Uri.decodeComponent(parts[3])+ : null,+ decisionId: parts.length == 4 && parts[2] == 'decision'+ ? Uri.decodeComponent(parts[3])+ : null,+ );+ } on ArgumentError {+ return null;+ }+}+@visibleForTestingString encodeAgentPayload(AgentRef agent) =>'${agent.machineId}\n${agent.agentId}';diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dartindex 9a2dfb0b8..c1e617824 100644--- a/mobile/lib/phone/agent_home.dart+++ b/mobile/lib/phone/agent_home.dart@@ -20,6 +20,7 @@ import 'daemon_chip.dart';import 'desk_groups.dart';import 'link_page.dart';import 'machines_tab.dart';+import 'out_of_sight.dart';import 'phone_navigation.dart' show phoneRoute;import 'settings_page.dart' show PhoneSettingsButton;import 'tty_controls.dart';@@ -839,9 +840,11 @@ class _AgentHomeState extends State<AgentHome>}@override- Widget build(BuildContext context) => ListenableBuilder(+ Widget build(BuildContext context) => ListenWhileInSight(+ // Out of sight under Swarm Home it builds nothing, however busy the app is, and catches up+ // when shown ([OutOfSight]).listenable: widget.notifier,- builder: (context, _) {+ builder: (context) {if (kTypingTrace) typingCount('home.build');AppTheme.watch(context);// Signed in from a scanned "Add phone" QR: once its computer is here and locked, pair withdiff --git a/mobile/lib/phone/out_of_sight.dart b/mobile/lib/phone/out_of_sight.dartnew file mode 100644index 000000000..00a15c2ca--- /dev/null+++ b/mobile/lib/phone/out_of_sight.dart@@ -0,0 +1,90 @@+import 'package:flutter/widgets.dart';++/// A part of the screen kept built but out of sight: Harness under Swarm Home, and Swarm Home+/// under Harness (`SwarmHomeRoot`). Kept so the person comes back to it as they left it, it should+/// cost nothing meanwhile — what is under it stops listening to the app while [hidden], and catches+/// up once shown ([ListenWhileInSight]).+///+/// ⚠️ **Not `TickerMode`, though that also goes off out of sight.** `TickerMode` is off as well for+/// a page covered by another one and for the pages the agent pager keeps beside the one on screen,+/// and those still act on what the app tells them (a question raising the keyboard, a machine just+/// unlocked opening its new-agent form). This is off only where nothing can be seen or done.+class OutOfSight extends InheritedWidget {+ const OutOfSight({super.key, required this.hidden, required super.child});++ final bool hidden;++ /// Whether [context] is out of sight; in sight with no [OutOfSight] above it.+ static bool of(BuildContext context) =>+ context.dependOnInheritedWidgetOfExactType<OutOfSight>()?.hidden ?? false;++ @override+ bool updateShouldNotify(OutOfSight oldWidget) => hidden != oldWidget.hidden;+}++/// A [ListenableBuilder] that stops while [OutOfSight]: it neither listens to [listenable] nor+/// builds, and what is under it stays as it was last drawn. Shown again, it builds once, with what+/// is there now, and listens again.+class ListenWhileInSight extends StatefulWidget {+ const ListenWhileInSight({+ super.key,+ required this.listenable,+ required this.builder,+ });++ final Listenable listenable;+ final WidgetBuilder builder;++ @override+ State<ListenWhileInSight> createState() => _ListenWhileInSightState();+}++class _ListenWhileInSightState extends State<ListenWhileInSight> {+ bool _hidden = false;+ bool _listening = false;++ /// What was built last. Handed back unchanged while out of sight, so the framework leaves+ /// everything under it alone — a rebuild from above included.+ Widget? _drawn;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _hidden = OutOfSight.of(context);+ _listen(!_hidden);+ }++ @override+ void didUpdateWidget(ListenWhileInSight oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (identical(oldWidget.listenable, widget.listenable)) return;+ if (_listening) oldWidget.listenable.removeListener(_changed);+ _listening = false;+ _listen(!_hidden);+ }++ @override+ void dispose() {+ _listen(false);+ super.dispose();+ }++ void _listen(bool on) {+ if (on == _listening) return;+ _listening = on;+ if (on) {+ widget.listenable.addListener(_changed);+ } else {+ widget.listenable.removeListener(_changed);+ }+ }++ void _changed() => setState(() {});++ @override+ Widget build(BuildContext context) {+ final drawn = _drawn;+ if (_hidden && drawn != null) return drawn;+ return _drawn = widget.builder(context);+ }+}diff --git a/mobile/lib/phone/phone_navigation.dart b/mobile/lib/phone/phone_navigation.dartindex 61aa02ab9..2b60104bb 100644--- a/mobile/lib/phone/phone_navigation.dart+++ b/mobile/lib/phone/phone_navigation.dart@@ -13,13 +13,28 @@ import 'phone_shell_scope.dart';/// Every phone page slides in the iOS way, and goes back with the edge swipe — unless/// [swipeToGoBack] is off, which is how a page that wants the horizontal axis for itself keeps it.-Route<void> phoneRoute(WidgetBuilder builder, {bool swipeToGoBack = true}) =>- swipeToGoBack- ? CupertinoPageRoute<void>(builder: builder)- : _NoSwipeBackRoute<void>(builder: builder);+///+/// [listensForItself] is a promise that the page reads nothing from the app in `build` without+/// listening to it: the shell then stops rebuilding the whole stack on every tick of the app while+/// it is up ([phoneRouteListensForItself]). Left off, the page is rebuilt from above as it always+/// was.+Route<void> phoneRoute(+ WidgetBuilder builder, {+ bool swipeToGoBack = true,+ bool listensForItself = false,+}) => _PhoneRoute<void>(+ builder: builder,+ swipeToGoBack: swipeToGoBack,+ listensForItself: listensForItself,+);-/// A phone page that slides and animates exactly like every other one, but cannot be dragged away-/// from the left edge.+/// [route] was pushed with `listensForItself` ([phoneRoute]): nothing on it needs the stack+/// rebuilt from above.+bool phoneRouteListensForItself(Route<Object?> route) =>+ route is _PhoneRoute && route.listensForItself;++/// A phone page. With [swipeToGoBack] off it slides and animates exactly like every other one, but+/// cannot be dragged away from the left edge.////// ⚠️ **It turns off the GESTURE only, and that distinction is the whole point.** `popGestureEnabled`/// is read by `_CupertinoBackGestureDetector` and by nothing else, so every other way out still@@ -35,11 +50,18 @@ Route<void> phoneRoute(WidgetBuilder builder, {bool swipeToGoBack = true}) =>////// A machine keeps the gesture: there is no pager under it competing for the axis, and it is a plain/// pushed page like any other.-class _NoSwipeBackRoute<T> extends CupertinoPageRoute<T> {- _NoSwipeBackRoute({required super.builder});+class _PhoneRoute<T> extends CupertinoPageRoute<T> {+ _PhoneRoute({+ required super.builder,+ required this.swipeToGoBack,+ required this.listensForItself,+ });++ final bool swipeToGoBack;+ final bool listensForItself;@override- bool get popGestureEnabled => false;+ bool get popGestureEnabled => swipeToGoBack && super.popGestureEnabled;}/// Where a tap on a machine goes. A machine this device holds no link to opens on ITS password@@ -93,7 +115,7 @@ void openAgent(agentId: agentId,neighbours: swipeNeighbours,),- // The horizontal axis belongs to the pager here — see [_NoSwipeBackRoute]. The way out is the+ // The horizontal axis belongs to the pager here — see [_PhoneRoute]. The way out is the// header's back band, and on Android the back button as well.swipeToGoBack: false,);diff --git a/mobile/lib/phone/phone_search_actions.dart b/mobile/lib/phone/phone_search_actions.dartindex 78701bfdf..439f3f070 100644--- a/mobile/lib/phone/phone_search_actions.dart+++ b/mobile/lib/phone/phone_search_actions.dart@@ -57,8 +57,7 @@ List<PhoneCommand> phoneSearchCommands(id: 'swarm.open',title: 'Swarm',detail: 'Experimental · your Swarms',- run: () =>- Navigator.of(context).push(phoneRoute((_) => const SwarmPage())),+ run: () => openSwarmHome(context),),PhoneCommand(id: 'app.settings',diff --git a/mobile/lib/phone/phone_search_field.dart b/mobile/lib/phone/phone_search_field.dartindex caebc4e50..87d712133 100644--- a/mobile/lib/phone/phone_search_field.dart+++ b/mobile/lib/phone/phone_search_field.dart@@ -134,7 +134,7 @@ class _QueryInput extends StatelessWidget {//// `border` alone is the wrong half of the fix: it is the fallback, and// the app's `inputDecorationTheme` fills the named states in —- // `focusedBorder` is a 1.5px accent outline at [AppControl.radius] (8).+ // `focusedBorder` is a 1.5px accent outline at [AppControl.radius] (10).// This box is [AppCard.radius] (12), so focusing drew a second, tighter// blue rectangle INSIDE the rim. Naming each state is what keeps the// theme from reaching past `border`.diff --git a/mobile/lib/phone/phone_sheet.dart b/mobile/lib/phone/phone_sheet.dartindex 9060ebbe4..b8def755b 100644--- a/mobile/lib/phone/phone_sheet.dart+++ b/mobile/lib/phone/phone_sheet.dart@@ -408,9 +408,7 @@ class _PhoneSheetRoute<T> extends ModalBottomSheetRoute<T> {required super.showDragHandle,required super.isScrollControlled,}) : super(- shape: const RoundedRectangleBorder(- borderRadius: BorderRadius.vertical(top: Radius.circular(10)),- ),+ shape: AppControl.sheetShape,modalBarrierColor: Colors.black.withValues(alpha: kSheetVeilOpacity),);diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex f421ed08e..0f4fbe90e 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -1,23 +1,41 @@import 'dart:async';+import 'dart:io' show Platform;+import 'package:flutter/cupertino.dart' show CupertinoPageRoute;import 'package:flutter/material.dart';import 'package:harness_mobile/state/app_state.dart';+import '../notify/system_notices.dart';import '../p2p/phone_terminal_p2p.dart';+import '../swarm/swarm_attachment_store.dart';+import '../swarm/swarm_computers.dart';+import '../swarm/swarm_conversation_page.dart';+import '../swarm/swarm_dictation.dart';+import '../swarm/swarm_home_root.dart';+import '../swarm/swarm_page.dart';+import '../swarm/swarm_profile.dart';+import '../swarm/swarm_session.dart';import 'agent_home.dart';import 'approve_sign_in.dart';import 'browser_handoff.dart';import 'devices_page.dart';import 'exit_app.dart';import 'new_device_banner.dart';+import 'phone_navigation.dart';import 'phone_shell_scope.dart';+import 'settings_page.dart' show openPhoneSettings;+import 'voice_input_controller.dart';+import 'voice_input_scope.dart';import 'welcome/connect_code.dart';/// The signed-in phone app: one page stack, rooted in [AgentHome] — the terminal the phone opens/// on and stays on. Machines and Settings are pages pushed onto it, from the terminal's menu and/// from Find.///+/// While Settings ▸ Experimental ▸ Swarm is on, the root is Swarm Home instead, with Harness (the+/// same [AgentHome]) one tap away in its drawer ([SwarmHomeRoot], [SwarmHomeChoice]).+////// ⚠️ **One stack, no tabs.** There were three — Agents, Machines, Settings — each with its own/// navigator under a bottom bar. The bar was hidden once the terminal became the home screen, and/// with no bar there was no way to reach the other two: they were built out of sight and never@@ -42,6 +60,29 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {/// The nested navigator's own — see the note at the `HeroControllerScope` below.final _heroController = HeroController();+ /// Swarm, while Settings ▸ Experimental ▸ Swarm is on: one session for the signed-in account,+ /// read while the app is in front, for every page under this shell ([SwarmScope]).+ late final SwarmHost _swarm;++ /// The app's computers as Swarm's start screens read them; they hear only a computer coming,+ /// going or changing state.+ late final _swarmComputers = AppSwarmComputers(widget.notifier);++ /// Keeps Swarm's picture files to the signed-in account: emptied on sign-out, Swarm off, another+ /// account and a Swarm's removal.+ late final SwarmAttachmentKeeper _swarmFiles;++ /// What the stack's root shows: Swarm Home while Swarm is on, until the person goes to Harness.+ late final _home = SwarmHomeChoice(_swarm.features);++ /// The centre's Swarm notices: the app's own centre carries them; a stand-in that does not+ /// (a test's) gets a silent one.+ late final SwarmNotices _swarmNotices =+ switch (widget.notifier.agentNotices.system) {+ final SwarmNotices notices => notices,+ _ => SilentSystemNotices(),+ };+@overridevoid initState() {super.initState();@@ -58,13 +99,50 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {final notices = widget.notifier.agentNotices.system;notices.opened.addListener(_openNoticedAgent);notices.openedDevice.addListener(_openNoticedDevice);+ final state = WidgetsBinding.instance.lifecycleState;+ _swarm = SwarmHost(+ accountId: () => widget.notifier.currentUser?.id,+ account: widget.notifier,+ request: widget.notifier.swarmRequest,+ upload: widget.notifier.swarmUpload,+ notices: _swarmNotices,+ // Swarm Home's start screens: which computers the account has, and+ // whether any is online.+ computers: _swarmComputers,+ // A photo goes straight to the backend with this app's own sign-in;+ // the computer a Swarm call goes through carries text only.+ uploadAvatar: swarmAvatarUploadVia(+ (tabId, png) => widget.notifier.api.uploadSwarmAvatar(tabId, png),+ ),+ // A chat's mic hears as a terminal's does: through the backend's+ // speech-to-text, or sample mode's, which records nothing.+ voice: () =>+ VoiceInputScope.maybeOf(context)?.create() ??+ VoiceInputController(+ transcriber: (wav, lang) =>+ widget.notifier.api.transcribeVoice(wav, lang: lang),+ ),+ // And first through the iPhone's own recognizer, the words in the box+ // as they are said. Not in sample mode, which opens no microphone.+ dictation: Platform.isIOS && VoiceInputScope.maybeOf(context) == null+ ? SwarmChannelDictation()+ : null,+ )..foreground = state == null || _inFront(state);+ _swarmFiles = SwarmAttachmentKeeper(_swarm);+ _swarmNotices.openedSwarm.addListener(_openNoticedSwarm);+ // Install tap callbacks and read the launch payload even when no new notice+ // arrives. Checking permission does not ask for it.+ unawaited(noticesEnabled(notices));// A tap that launched the app is read before this shell exists, so its value is already set and// no listener will ever fire for it: take it once the navigator is up.- if (notices.opened.value != null || notices.openedDevice.value != null) {+ if (notices.opened.value != null ||+ notices.openedDevice.value != null ||+ _swarmNotices.openedSwarm.value != null) {WidgetsBinding.instance.addPostFrameCallback((_) {if (!mounted) return;_openNoticedAgent();_openNoticedDevice();+ _openNoticedSwarm();});}// A computer's sign-in QR read before this phone was signed in: the sign-in was the way to@@ -90,6 +168,11 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {widget.notifier.agentNotices.system.openedDevice.removeListener(_openNoticedDevice,);+ _swarmNotices.openedSwarm.removeListener(_openNoticedSwarm);+ _home.dispose();+ _swarmFiles.dispose();+ _swarm.dispose();+ _swarmComputers.dispose();_linkedMachineId.dispose();_openAgentRequest.dispose();_heroController.dispose();@@ -128,8 +211,11 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {/// No waiting and no timeout here, which is what this used to be full of. The machine is still/// connecting at this point and [AgentHome] is already watching for exactly that — it holds/// whatever is on screen while the machine dials, then opens the first agent it reports.- void _followLinkedMachine(String machineId) =>- _linkedMachineId.value = machineId;+ void _followLinkedMachine(String machineId) {+ ++_navigationRequest;+ _linkedMachineId.value = machineId;+ _home.showHarness();+ }/// An agent somebody picked — from search, the new-agent form, the attention list — for/// [AgentHome] to put on screen. A notifier for the reason [_linkedMachineId] is one.@@ -143,13 +229,22 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {/// person had finished with. The stack is emptied back to its root instead and the root terminal/// switches agent, so there is never anything to go back to.void _openAgentAtHome(String machineId, String agentId) {+ ++_navigationRequest;_navigator.currentState?.popUntil((route) => route.isFirst);// Reset first, so picking the agent already requested last time still notifies._openAgentRequest.value = null;_openAgentRequest.value = (machineId: machineId, agentId: agentId);+ _home.showHarness();setState(() => _canPop = false);}+ /// Swarm Home, from the terminal's Swarm mark or Find: back to the root.+ void _showSwarm() {+ ++_navigationRequest;+ _navigator.currentState?.popUntil((route) => route.isFirst);+ _home.showSwarm();+ }+/// The computer whose sign-in QR (`harness login --qr`) the welcome screen read before this phone/// was signed in ([AppNotifier.pendingComputerSignIn]): the approval it asked for, now that it can/// be given. Spent here whatever the answer — a code is one computer's sign-in, once.@@ -178,7 +273,65 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {final agent = opened.value;if (agent == null) return;opened.value = null;- _openAgentAtHome(agent.machineId, agent.agentId);+ if (_swarm.session case final session?) {+ unawaited(_openSwarmAgent(session, agent.machineId, agent.agentId));+ } else {+ _openAgentAtHome(agent.machineId, agent.agentId);+ }+ }++ // Shared by notification reads, explicit root changes and route transitions.+ int _navigationRequest = 0;++ Future<void> _openSwarmAgent(+ SwarmSession session,+ String machineId,+ String harnessId,+ ) async {+ final request = ++_navigationRequest;+ // Join the cold-start read; a background tap must use the current assignment.+ await session.inbox.refresh();+ if (!mounted ||+ _swarm.session != session ||+ request != _navigationRequest) {+ return;+ }+ for (final swarm in session.inbox.swarms) {+ final snapshot = session.inbox.reader(swarm.id)?.snapshot;+ if (snapshot == null) continue;+ for (final agent in snapshot.agents) {+ if (agent.machineId != machineId || agent.harnessId != harnessId) {+ continue;+ }+ final groups = snapshot.conversations.where(+ (g) =>+ !g.closed && !snapshot.isProjectLead(g.id) && g.audience == null,+ );+ final assigned = groups.where(+ (g) =>+ g.assignment?['agentId'] == agent.id &&+ !const ['done', 'cancelled'].contains(g.assignment?['status']),+ );+ final member = groups.where((g) => g.agentIds.contains(agent.id));+ final conversationId =+ assigned.firstOrNull?.id ??+ member.firstOrNull?.id ??+ snapshot.projectById(agent.projectId)?.leadConversationId;+ if (conversationId != null) {+ _showNoticedChat((+ swarmId: swarm.id,+ conversationId: conversationId,+ messageId: null,+ decisionId: null,+ ));+ return;+ }+ }+ }+ _showSwarm();+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ const SnackBar(content: Text('This agent’s chat is unavailable.')),+ );}/// A tapped "new device" notice: that device's page. One this phone has just been told of opens as@@ -192,6 +345,43 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {unawaited(_showDevice(pub));}+ /// A tapped Swarm notice: Swarm Home, and over it the conversation the notice was about — back+ /// from it is the rest of what Swarm asks of the person.+ void _openNoticedSwarm() {+ final opened = _swarmNotices.openedSwarm;+ final target = opened.value;+ if (target == null || _navigator.currentState == null) return;+ opened.value = null;+ // Swarm off cancels its notices. A stale tap must not open a disabled UI.+ if (_swarm.session == null) return;+ _showNoticedChat(target);+ }++ void _showNoticedChat(SwarmNoticeTarget target) {+ ++_navigationRequest;+ final navigator = _navigator.currentState;+ if (navigator == null) return;+ navigator.popUntil((route) => route.isFirst);+ _home.showSwarm();+ unawaited(+ navigator.push(+ phoneRoute(+ (_) => SwarmConversationPage(+ swarmId: target.swarmId,+ conversationId: target.conversationId,+ messageId: target.messageId,+ decisionId: target.decisionId,+ ),+ listensForItself: true,+ ),+ ),+ );+ }++ /// In front of the person: resumed, or only covered for a moment (the app switcher, a call).+ static bool _inFront(AppLifecycleState state) =>+ state == AppLifecycleState.resumed || state == AppLifecycleState.inactive;+Future<void> _showDevice(String key) async {final navigator = _navigator.currentState;if (navigator == null) return;@@ -218,6 +408,8 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {/// who was looking straight at it, with a network that would have answered at once.@overridevoid didChangeAppLifecycleState(AppLifecycleState state) {+ // Swarm is read only in front of the person.+ _swarm.foreground = _inFront(state);if (state == AppLifecycleState.inactive) {// The app switcher coming up is `inactive`, and a swipe there can end the app without it// ever reaching `paused` — so the machine cache is written here as well. See@@ -284,10 +476,17 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {/// with a route under it pops that route instead. `pop`, not `maybePop`: this shell's own/// [PopScope] is what refuses the pop, and asking the route again would land straight back here.Future<void> _back() async {+ ++_navigationRequest;final handled = await _navigator.currentState?.maybePop() ?? false;if (!mounted) return;_syncCanPop();- if (handled || !confirmsExitOnBack) return;+ if (handled) return;+ // Harness, reached from Swarm Home's drawer: back is Swarm Home, the app's Home.+ if (_home.harnessOverSwarm) {+ _home.showSwarm();+ return;+ }+ if (!confirmsExitOnBack) return;final route = ModalRoute.of(context);if (route != null && !route.isFirst) {// Only while it is still on top: a sheet pushed meanwhile is what the next press closes.@@ -297,23 +496,51 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {await confirmExitApp(context);}+ /// The pages on the stack that count on being rebuilt from here — see [_LeansOnShell].+ late final _leaning = _LeansOnShell(() => ++_navigationRequest);++ /// The page stack, made once and handed through every rebuild of the shell untouched, so that+ /// nothing on the stack is rebuilt from here unless a page there needs it ([build]).+ ///+ /// ⚠️ **Not made afresh in [build], and it used to be.** The shell rebuilds itself whenever a+ /// push or pop changes whether it can go back ([_syncCanPop]) — that is, on every push, during+ /// the push's own animation. A fresh stack each time told every route on it that the world had+ /// changed, so opening a project or a chat built Swarm Home again under the page sliding in.+ late final Widget _stack = _pages();+/// The page stack. A fresh widget each call — what makes the [Navigator] tell every route on it/// that the world may have changed (`Route.changedExternalState`), and so rebuild every page.- Widget _pages() => HeroControllerScope(- controller: _heroController,- child: Navigator(- key: _navigator,- // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.- // `NavigatorState._updateEffectiveObservers` appends the scope's controller- // to `widget.observers` itself, so listing it here registers it twice and- // trips "A HeroController can not be shared by multiple Navigators" — which- // reads like a sharing bug and is really a double-subscription by one- // navigator.- onGenerateRoute: (_) => MaterialPageRoute<void>(- builder: (_) => AgentHome(- notifier: widget.notifier,- openMachineId: _linkedMachineId,- openAgent: _openAgentRequest,+ // Under [SwarmScope], so every page on the stack can reach the account's Swarm.+ Widget _pages() => SwarmScope(+ notifier: _swarm,+ child: HeroControllerScope(+ controller: _heroController,+ child: Navigator(+ key: _navigator,+ // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.+ // `NavigatorState._updateEffectiveObservers` appends the scope's controller+ // to `widget.observers` itself, so listing it here registers it twice and+ // trips "A HeroController can not be shared by multiple Navigators" — which+ // reads like a sharing bug and is really a double-subscription by one+ // navigator.+ observers: [_leaning],+ // ⚠️ **The same kind of route as every page pushed over it ([phoneRoute]).** The root was+ // a `MaterialPageRoute` under Cupertino pages, and the two hand their transition to each+ // other: each push and pop changed the shape of the tree around the root's page, so+ // Swarm Home was taken out and put back — and built again — as a project or chat slid in.+ onGenerateRoute: (_) => CupertinoPageRoute<void>(+ builder: (_) => SwarmHomeRoot(+ choice: _home,+ harness: AgentHome(+ notifier: widget.notifier,+ openMachineId: _linkedMachineId,+ openAgent: _openAgentRequest,+ ),+ swarm: (_) => SwarmPage(+ onSettings: (context) =>+ openPhoneSettings(context, widget.notifier),+ ),+ ),),),),@@ -321,19 +548,23 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {@overrideWidget build(BuildContext context) {- // Made once per build of the shell, and handed through the [ListenableBuilder] below — see the- // note there.- final pages = _pages();return PhoneShellScope(onMachineLinked: _followLinkedMachine,onOpenAgent: _openAgentAtHome,- child: PopScope<Object?>(- // False while the stack has somewhere to go back to, so the gesture reaches [_handleBack]- // instead of leaving the app. True at its root: the press then belongs to the system —- // except on Android, where the root asks before the app is left ([confirmExitApp]), so- // every press is the shell's.- canPop: !confirmsExitOnBack && !_canPop,- onPopInvokedWithResult: _handleBack,+ onShowSwarm: _showSwarm,+ // Rebuilt when the root switches, so back from Harness can reach Swarm Home.+ child: ListenableBuilder(+ listenable: _home,+ builder: (context, child) => PopScope<Object?>(+ // False while the stack has somewhere to go back to, so the gesture reaches [_handleBack]+ // instead of leaving the app. True at its root: the press then belongs to the system —+ // except on Android, where the root asks before the app is left ([confirmExitApp]), so+ // every press is the shell's — and except at Harness over Swarm Home, which back leaves+ // for Swarm Home.+ canPop: !confirmsExitOnBack && !_canPop && !_home.harnessOverSwarm,+ onPopInvokedWithResult: _handleBack,+ child: child!,+ ),child: NotificationListener<NavigationNotification>(onNotification: _onNavigation,child: Scaffold(@@ -351,10 +582,13 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {// burst. The home screen listens to the notifier for itself ([AgentHome]), so at the// root the stack is handed through untouched. A page PUSHED over it may not listen —// it may read the notifier in `build` and count on being rebuilt — so while one is up- // the stack is rebuilt on every tick exactly as before.+ // the stack is rebuilt on every tick exactly as before, unless it was pushed as one+ // that listens for itself (Swarm's project and chat pages, [phoneRoute]). Opening a+ // project or a chat then rebuilds nothing under it: on Tony's iPhone 14 those pushes+ // were the slowest frames of the app (20–42 ms of layout and paint, 2026-10-27).body: ListenableBuilder(listenable: widget.notifier,- child: pages,+ child: _stack,builder: (context, pages) => Column(children: [// A device this phone had never trusted joined the account (device key log).@@ -379,9 +613,7 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {builder: (context) => MediaQuery.removePadding(context: context,removeTop: NewDeviceBanner.showing(widget.notifier),- child: (_navigator.currentState?.canPop() ?? false)- ? _pages()- : pages!,+ child: _leaning.any ? _pages() : pages!,),),),@@ -394,3 +626,52 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {);}}++/// The pages pushed over the stack's root that may read the app in `build` without listening to+/// it, and so count on the shell rebuilding the stack on every tick: every pushed page but those+/// that listen for themselves ([phoneRouteListensForItself]). The root listens for itself.+///+/// Told by the [Navigator] of every route that comes and goes. Read by the shell on each tick; it+/// rebuilds nothing by itself.+class _LeansOnShell extends NavigatorObserver {+ _LeansOnShell(this.onNavigation);++ /// A newer route wins over notification navigation still waiting on a read.+ final VoidCallback onNavigation;++ final _pushed = <Route<Object?>>{};++ /// A page that needs the stack rebuilt from above is on it.+ bool get any => _pushed.isNotEmpty;++ void _add(Route<Object?>? route) {+ if (route == null || route.isFirst) return;+ if (phoneRouteListensForItself(route)) return;+ _pushed.add(route);+ }++ @override+ void didPush(Route<Object?> route, Route<Object?>? previousRoute) {+ onNavigation();+ _add(route);+ }++ @override+ void didPop(Route<Object?> route, Route<Object?>? previousRoute) {+ onNavigation();+ _pushed.remove(route);+ }++ @override+ void didRemove(Route<Object?> route, Route<Object?>? previousRoute) {+ onNavigation();+ _pushed.remove(route);+ }++ @override+ void didReplace({Route<Object?>? newRoute, Route<Object?>? oldRoute}) {+ onNavigation();+ _pushed.remove(oldRoute);+ _add(newRoute);+ }+}diff --git a/mobile/lib/phone/phone_shell_scope.dart b/mobile/lib/phone/phone_shell_scope.dartindex 772442986..2d39b919a 100644--- a/mobile/lib/phone/phone_shell_scope.dart+++ b/mobile/lib/phone/phone_shell_scope.dart@@ -10,6 +10,7 @@ class PhoneShellScope extends InheritedWidget {super.key,required this.onMachineLinked,required this.onOpenAgent,+ this.onShowSwarm,required super.child,});@@ -21,6 +22,11 @@ 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;+ /// 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`).+ final VoidCallback? onShowSwarm;+/// Null outside the shell — a page pumped on its own in a test simply has nowhere to go.static PhoneShellScope? maybeOf(BuildContext context) =>context.getInheritedWidgetOfExactType<PhoneShellScope>();diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dartindex c4bedd091..526718e06 100644--- a/mobile/lib/phone/settings_page.dart+++ b/mobile/lib/phone/settings_page.dart@@ -18,6 +18,7 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/shared/theme/appearance_prefs_store.dart';import 'package:harness_mobile/shared/theme/color_palette.dart';import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/swarm/swarm_start.dart' show SwarmIntroPage;import 'package:harness_mobile/terminal/terminal_font_store.dart';import 'package:harness_mobile/terminal/terminal_theme_store.dart';@@ -679,6 +680,13 @@ class _ExperimentRow extends StatelessWidget {final on = store.isOn(experiment);void toggle(bool next) {HapticFeedback.selectionClick();+ // Swarm is turned on from its page, which says first what it does; off, it goes at once.+ if (next && experiment == PhoneExperiment.swarm) {+ unawaited(+ Navigator.of(context).push(phoneRoute((_) => SwarmIntroPage(features: store))),+ );+ return;+ }unawaited(store.set(experiment, next));}diff --git a/mobile/lib/phone/sheet_list.dart b/mobile/lib/phone/sheet_list.dartindex 3c7191199..da5dccee7 100644--- a/mobile/lib/phone/sheet_list.dart+++ b/mobile/lib/phone/sheet_list.dart@@ -140,7 +140,7 @@ class _SheetRowState extends State<SheetRow> {@overrideWidget build(BuildContext context) {AppTheme.watch(context);- const corner = Radius.circular(AppCard.radius);+ const corner = Radius.circular(AppControl.rowRadius);final subtitle = widget.subtitle;final trailing = widget.trailing;return Semantics(diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex 17c2c9af7..88d79d4af 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -55,6 +55,7 @@ import 'delete_agent.dart';import 'held_height.dart';import 'machines_tab.dart';import 'new_agent_chooser.dart';+import 'out_of_sight.dart';import 'phone_sheet.dart';import 'phone_status.dart';import 'settings_page.dart';@@ -81,6 +82,7 @@ import 'welcome/focus_hints.dart';import 'package:harness_mobile/demo/sample_mode.dart';import 'package:harness_mobile/notify/notifications_ask.dart';+import 'package:harness_mobile/swarm/swarm_mark.dart';import 'voice_input_controller.dart';@@ -826,7 +828,6 @@ class _TerminalPageState extends State<TerminalPage>WidgetsBinding.instance.addObserver(this);_lifecycle =WidgetsBinding.instance.lifecycleState ?? AppLifecycleState.resumed;- widget.notifier.addListener(_onNotifier);// A session already taking input when the page comes ticks nothing to raise from.WidgetsBinding.instance.addPostFrameCallback((_) {if (mounted) _raiseForFirstSession();@@ -839,6 +840,25 @@ class _TerminalPageState extends State<TerminalPage>// Which of the page's rebuilds an inherited widget asked for — against// `page.update` (its parent) and `page.build` (all of them).if (kTypingTrace) typingCount('page.deps');+ _listenToApp(!OutOfSight.of(context));+ }++ /// Whether [_onNotifier] is listening.+ bool _listeningToApp = false;++ /// Listens to the app only while this page can be seen. Out of sight+ /// (Harness under Swarm Home, [OutOfSight]) every tick of the app was a+ /// read of the facts, and a rebuild whenever one moved, for a page nobody+ /// is looking at. Shown again, the rebuild that brings it back reads the+ /// facts afresh in [build], so nothing is missed.+ void _listenToApp(bool on) {+ if (on == _listeningToApp) return;+ _listeningToApp = on;+ if (on) {+ widget.notifier.addListener(_onNotifier);+ } else {+ widget.notifier.removeListener(_onNotifier);+ }}/// Releases the resize hold when this page is parked mid-animation.@@ -849,7 +869,7 @@ class _TerminalPageState extends State<TerminalPage>void didUpdateWidget(TerminalPage oldWidget) {super.didUpdateWidget(oldWidget);if (kTypingTrace) typingCount('page.update');- if (!identical(oldWidget.notifier, widget.notifier)) {+ if (_listeningToApp && !identical(oldWidget.notifier, widget.notifier)) {oldWidget.notifier.removeListener(_onNotifier);widget.notifier.addListener(_onNotifier);}@@ -902,7 +922,7 @@ class _TerminalPageState extends State<TerminalPage>_scrollback.dispose();_dropFindBack();_find?.dispose();- widget.notifier.removeListener(_onNotifier);+ _listenToApp(false);_daemon?.noteQuestion(this,machineId: widget.machineId,@@ -2940,8 +2960,14 @@ class _TerminalPageState extends State<TerminalPage>// The paired daemon at the title's right end: its// sprite, a tap from its sheet. Nothing outside the// signed-in shell (the sample). See `daemon_chip.dart`.- daemon: const DaemonChip(- margin: EdgeInsets.only(left: 12),+ // Before it, while Swarm is on: what the Swarms ask of+ // the person, a tap from them. See `swarm_mark.dart`.+ daemon: const Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ SwarmMark(margin: EdgeInsets.only(left: 12)),+ DaemonChip(margin: EdgeInsets.only(left: 12)),+ ],),// Only over a screen: with none, [_MachineAway] says it// in the terminal's place, and saying it twice is noise.@@ -4650,15 +4676,37 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {@overridevoid initState() {super.initState();- widget.terminal?.addListener(_output);widget.reading.addListener(_toggled);terminalFontStore.addListener(_changed);}+ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _listenToOutput(!OutOfSight.of(context));+ }++ /// Whether [_output] is listening.+ bool _listeningToOutput = false;++ /// Follows the output only while the terminal can be seen. Out of sight+ /// (Harness under Swarm Home, [OutOfSight]) the output stays in the buffer,+ /// and the rebuild that shows the terminal again places it by what is there+ /// then.+ void _listenToOutput(bool on) {+ if (on == _listeningToOutput) return;+ _listeningToOutput = on;+ if (on) {+ widget.terminal?.addListener(_output);+ } else {+ widget.terminal?.removeListener(_output);+ }+ }+@overridevoid didUpdateWidget(_AnchoredTerminal old) {super.didUpdateWidget(old);- if (!identical(old.terminal, widget.terminal)) {+ if (_listeningToOutput && !identical(old.terminal, widget.terminal)) {old.terminal?.removeListener(_output);widget.terminal?.addListener(_output);}@@ -4672,7 +4720,7 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {@overridevoid dispose() {- widget.terminal?.removeListener(_output);+ _listenToOutput(false);widget.reading.removeListener(_toggled);terminalFontStore.removeListener(_changed);super.dispose();diff --git a/mobile/lib/phone/voice_input_controller.dart b/mobile/lib/phone/voice_input_controller.dartindex 18361bfd9..4d55e5497 100644--- a/mobile/lib/phone/voice_input_controller.dart+++ b/mobile/lib/phone/voice_input_controller.dart@@ -97,6 +97,22 @@ class VoiceInputController extends ChangeNotifier {/// mid-take is the one that take is heard in.final ValueListenable<String> _language;+ /// What a take that reaches [maxTake] does instead of ending there: null ends it and transcribes+ /// it ([stopListening]), its words kept for the next send — the terminal's way.+ ///+ /// The Swarm composer takes it over: it puts the words in the message box, and while a system+ /// prompt covers the app it holds the take open, since nothing may be sent to be transcribed that+ /// the person cannot see.+ Future<void> Function()? onTakeLimit;++ /// Asked once a take's recording is in hand, right before it goes to [transcriber]: until it+ /// answers the take waits, and false drops it. Null sends every take — the terminal's way.+ ///+ /// The Swarm composer holds a take here while a system prompt covers the app: the microphone+ /// takes a moment to close, a prompt can come up in it, and nothing may be sent to be transcribed+ /// that the person cannot see.+ Future<bool> Function()? mayTranscribe;+VoiceInputStatus _status = VoiceInputStatus.idle;String _heard = '';String? _notice;@@ -210,11 +226,14 @@ class VoiceInputController extends ChangeNotifier {unawaited(_recorder.cancel());return;}- _takeLimit = Timer(maxTake, () => unawaited(stopListening()));+ _takeLimit = Timer(maxTake, _reachLimit);_takeClock = Stopwatch()..start();_setStatus(VoiceInputStatus.listening);}+ /// [maxTake] has passed: the take ends, unless [onTakeLimit] takes it over.+ void _reachLimit() => unawaited((onTakeLimit ?? stopListening)());+/// Ends the take and transcribes it.Future<void> stopListening() async {if (_status == VoiceInputStatus.starting) {@@ -421,6 +440,14 @@ class VoiceInputController extends ChangeNotifier {_setStatus(VoiceInputStatus.idle, notice: VoiceNotice.noSound);return _Take.failed;}+ if (mayTranscribe case final mayTranscribe?) {+ final go = await mayTranscribe();+ if (take != _take) return _Take.failed;+ if (!go) {+ _setStatus(VoiceInputStatus.idle);+ return _Take.failed;+ }+ }final language = _language.value;final words = await transcriber(recording.wav, language);// The count, never the words: a transcript is what someone said.@@ -463,7 +490,7 @@ class VoiceInputController extends ChangeNotifier {_pretendLevel.value =0.15 + 0.6 * syllable * (0.6 + 0.4 * _pretendRandom.nextDouble());});- _takeLimit = Timer(maxTake, () => unawaited(stopListening()));+ _takeLimit = Timer(maxTake, _reachLimit);_takeClock = Stopwatch()..start();_setStatus(VoiceInputStatus.listening);}diff --git a/mobile/lib/phone/voice_mic_face.dart b/mobile/lib/phone/voice_mic_face.dartindex f9c79e2c6..1f9bf286e 100644--- a/mobile/lib/phone/voice_mic_face.dart+++ b/mobile/lib/phone/voice_mic_face.dart@@ -446,6 +446,9 @@ class _DotsState extends State<_Dots> with SingleTickerProviderStateMixin {/// Five bars that move with the voice while the mic listens: short at silence, tall when loud,/// each on its own phase so they never move as one block. They idle gently when there is no/// level to follow, so the mic never looks frozen while it is recording.+///+/// ⚠️ Under Reduce Motion they hold their shape but still rise and fall with the voice: built+/// on the level's changes too, not only the wave's ticks, which stop there (Lead, 10-29).class _LiveBars extends StatefulWidget {const _LiveBars({required this.color,@@ -471,6 +474,9 @@ class _LiveBarsState extends State<_LiveBars>/// The level, eased toward what the microphone reports, so the bars glide.double _shown = 0;+ /// What rebuilds the bars: the wave's ticks, and the level's changes.+ late Listenable _ticks = _ticksOf(widget.level);+static const _weights = [0.55, 0.85, 1.0, 0.8, 0.5];static const double _bar = 4;static const double _gap = 4;@@ -486,6 +492,7 @@ class _LiveBarsState extends State<_LiveBars>@overridevoid didUpdateWidget(_LiveBars old) {super.didUpdateWidget(old);+ if (widget.level != old.level) _ticks = _ticksOf(widget.level);if (widget.animate && !_wave.isAnimating) unawaited(_wave.repeat());if (!widget.animate) _wave.stop();}@@ -496,13 +503,16 @@ class _LiveBarsState extends State<_LiveBars>super.dispose();}+ Listenable _ticksOf(ValueListenable<double>? level) =>+ level == null ? _wave : Listenable.merge([_wave, level]);+@overrideWidget build(BuildContext context) => RepaintBoundary(child: AnimatedBuilder(- animation: _wave,+ animation: _ticks,builder: (context, _) {final target = (widget.level?.value ?? 0.15).clamp(0.0, 1.0);- _shown += (target - _shown) * 0.35;+ _shown = widget.animate ? _shown + (target - _shown) * 0.35 : target;return Row(mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.center,diff --git a/mobile/lib/phone/welcome/phone_welcome.dart b/mobile/lib/phone/welcome/phone_welcome.dartindex 9ffc989b2..084b766bc 100644--- a/mobile/lib/phone/welcome/phone_welcome.dart+++ b/mobile/lib/phone/welcome/phone_welcome.dart@@ -7,6 +7,7 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/auth/sign_in_provider.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/swarm/swarm_home_cache.dart';import '../exit_app.dart';import '../tty.dart';@@ -68,6 +69,7 @@ class PhoneWelcome extends StatefulWidget {this.sendCode,this.signIn,this.scanCamera,+ this.swarmHome,});final AppNotifier notifier;@@ -80,6 +82,9 @@ class PhoneWelcome extends StatefulWidget {/// real one.final Widget? scanCamera;+ /// The Swarm Home kept on this phone ([SwarmHomeCache.device] when null).+ final SwarmHomeCache? swarmHome;+@overrideState<PhoneWelcome> createState() => _PhoneWelcomeState();}@@ -113,6 +118,14 @@ class _PhoneWelcomeState extends State<PhoneWelcome> {static const _codeLength = 4;static const _resendAfter = 30;+ @override+ void initState() {+ super.initState();+ // Signed out, so the last Swarm Home goes: a session that ended while the app was not running+ // never had a signed-in shell to clear it ([SwarmHost]).+ unawaited((widget.swarmHome ?? SwarmHomeCache.device()).clear());+ }+@overridevoid dispose() {_resendTimer?.cancel();diff --git a/mobile/lib/settings/experimental_features.dart b/mobile/lib/settings/experimental_features.dartindex c41ee9927..19987e746 100644--- a/mobile/lib/settings/experimental_features.dart+++ b/mobile/lib/settings/experimental_features.dart@@ -14,9 +14,14 @@ import 'package:harness_mobile/core/local_key_value_store.dart';/// migration and a backend release. These exist to try a feature on one phone while it is being/// built (owner, 2026-10-26), so they live in this phone's state file.enum PhoneExperiment {- /// Swarm on the phone, while its screens are built. Its way in, the Swarm command in Find, is- /// offered only while this is on (`phone/phone_search_actions.dart`).- swarm('swarm', 'Swarm', 'Open your Swarms from Find. Still taking shape.');+ /// Swarm on the phone, while its screens are built. Its ways in, the Swarm mark on Home's title+ /// (`swarm/swarm_mark.dart`) and the Swarm command in Find (`phone/phone_search_actions.dart`),+ /// are offered only while this is on.+ swarm(+ 'swarm',+ 'Swarm',+ 'Open your Swarms from Home or Find. Still taking shape.',+ );const PhoneExperiment(this.id, this.label, this.description);diff --git a/mobile/lib/shared/theme/app_icon_size.dart b/mobile/lib/shared/theme/app_icon_size.dartnew file mode 100644index 000000000..495557f6f--- /dev/null+++ b/mobile/lib/shared/theme/app_icon_size.dart@@ -0,0 +1,10 @@+/// Icon sizes on the phone, as the Phone section of+/// `desktop/design/desktop-design-system.md` gives them: one step larger than+/// Desktop's 16 and 20, for a thumb.+abstract final class AppIconSize {+ /// An icon beside text: a row's mark, a chip's ✕.+ static const double besideText = 20;++ /// An icon alone in a control: the composer's + and @, a sheet row's mark.+ static const double standalone = 24;+}diff --git a/mobile/lib/shared/theme/app_ink.dart b/mobile/lib/shared/theme/app_ink.dartnew file mode 100644index 000000000..c1c067e0b--- /dev/null+++ b/mobile/lib/shared/theme/app_ink.dart@@ -0,0 +1,9 @@+import 'package:flutter/painting.dart';++/// Ink that sits on a colour of its own rather than on a surface.+abstract final class AppInk {+ /// A letter or glyph on a solid fill: the accent, an avatar's disc, a+ /// count's badge. Every fill it goes on is measured for white+ /// (`AppPalette.accent`, `avatarFill`, `avatarPalette`), in both themes.+ static const Color onFill = Color(0xFFFFFFFF);+}diff --git a/mobile/lib/shared/theme/app_space.dart b/mobile/lib/shared/theme/app_space.dartnew file mode 100644index 000000000..8f9b86e83--- /dev/null+++ b/mobile/lib/shared/theme/app_space.dart@@ -0,0 +1,13 @@+/// The phone's spacing, as the Phone section of+/// `desktop/design/desktop-design-system.md` gives it: Desktop's scale of 4, 8,+/// 12, 16 and 24, and a 16-point side inset for a screen's content.+abstract final class AppSpace {+ static const double xs = 4;+ static const double s = 8;+ static const double m = 12;+ static const double l = 16;+ static const double xl = 24;++ /// A screen's content from its left and right edges.+ static const double screenInset = l;+}diff --git a/mobile/lib/shared/theme/app_theme.dart b/mobile/lib/shared/theme/app_theme.dartindex 4036401d5..ed4dcc7b0 100644--- a/mobile/lib/shared/theme/app_theme.dart+++ b/mobile/lib/shared/theme/app_theme.dart@@ -298,7 +298,11 @@ abstract final class AppPalette {/// Slightly deeper in dark, where the tile stands on charcoal (2.63:1 against/// the panel) rather than on white (5.26:1).static Color get avatarFill =>- AppTheme.pick(const Color(0xFF5369AC), const Color(0xFF4B5F9B));+ AppTheme.pick(const Color(0xFF5369AC), avatarFillDark);++ /// [avatarFill] in the dark theme. A person in a Swarm chat wears it in+ /// both themes.+ static const avatarFillDark = Color(0xFF4B5F9B);/// The colours a member's circle is drawn in, one per person — see/// `memberAvatarSlot`, which decides which of them an address takes.@@ -764,10 +768,9 @@ abstract final class AppMenu {static const Color rimDark = Color(0x1FFFFFFF);static Color get rim => AppTheme.pick(rimLight, rimDark);- /// A menu panel's rounding. On the §3 ladder this is the *panel* step (10),- /// one below a content card (12) and above the rows inside it (8) — a child is- /// never rounder than its parent.- static const double panelRadius = 10;+ /// A menu panel's rounding: Desktop's popover radius (16), as the Phone+ /// section of desktop/design/desktop-design-system.md has it.+ static const double panelRadius = AppControl.menuRadius;/// Deeper than Material's menu default (8): this panel opens over chrome that/// already carries a lift of its own, and at 8 it reads as lying *on* that@@ -858,16 +861,9 @@ abstract final class AppCard {static Color get highlightEdge =>AppTheme.pick(const Color(0x0A000000), const Color(0x1FFFFFFF));- /// Corner rounding, on macOS's scale rather than iOS's.- ///- /// A Mac window is ~10 and a sheet/popover ~12; iOS and the web round far- /// harder, and at 18 a card read as an iOS sheet that had wandered onto a- /// desktop. It also disagreed with the buttons *inside* it ([AppControl.radius]- /// is 8), so a card and its own action were speaking two shape languages.- ///- /// The inset tile drops to 8 to match those buttons: an inset sits inside a- /// card, and nesting a rounder box inside a less-round one is what makes a- /// tile look pasted on rather than set in.+ /// Corner rounding, the same as Desktop's cards: 12, with the inset tile one+ /// step tighter at 8 — nesting a rounder box inside a less-round one is what+ /// makes a tile look pasted on rather than set in.static const double radius = 12;static const double insetRadius = 8;@@ -980,6 +976,14 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {style: _outlinedButtonStyle(scheme),),textButtonTheme: TextButtonThemeData(style: _textButtonStyle()),+ iconButtonTheme: IconButtonThemeData(+ style: ButtonStyle(+ tapTargetSize: _touchTarget,+ visualDensity: _touchDensity,+ // Material's 40-point drawing, given back the step [_touchDensity] takes.+ minimumSize: const WidgetStatePropertyAll(Size(40, 40 + _densityStep)),+ ),+ ),useMaterial3: true,brightness: brightness,colorScheme: scheme,@@ -1170,8 +1174,7 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {// Fill, rim and elevation come from [AppMenu] so a Material popup cannot// disagree with a MenuAnchor about what a menu looks like.//- // The radius does not: [AppControl.menuRadius] (6) is the §3 step for- // *Material's own* popup, which draws tighter than the app's panel (10).+ // The radius too: [AppControl.menuRadius], Desktop's popover radius.popupMenuTheme: PopupMenuThemeData(color: panelFill,surfaceTintColor: Colors.transparent,@@ -1199,6 +1202,7 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {shape: Border(),collapsedShape: Border(),),+ bottomSheetTheme: const BottomSheetThemeData(shape: AppControl.sheetShape),dialogTheme: DialogThemeData(// The raised block's own fill, not a menu's and not a card's. §9.3: a// dialog that takes `windowBg` merges with the page, and one that takes@@ -1206,11 +1210,10 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {// both invisible in light, both plain in dark.backgroundColor: dialogFill,surfaceTintColor: Colors.transparent,- // The card radius, not a number of its own. This was 18 — the iOS- // action-sheet curve, and the app's cards had already come down to 12 for- // macOS without the dialogs following.+ // Desktop's dialog radius, as the Phone section of the design system has+ // it: one step rounder than the cards a dialog may hold.shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(AppCard.radius),+ borderRadius: BorderRadius.circular(AppControl.dialogRadius),),),// ⚠️ [AppPalette.accentOnSurface], NOT `colorScheme.primary`.@@ -1247,9 +1250,10 @@ ThemeData buildAppTheme({Brightness brightness = Brightness.light}) {/// The one set of numbers every button in the app is built from.///-/// macOS controls are compact, squarish and quiet: a 13pt semibold label in a-/// ~32px capsule with a small radius — not the tall, wide, fully-round buttons-/// Material defaults to. Before this existed each call site invented its own,+/// Desktop's control recipe: a ~32px capsule button and softly rounded fields,+/// not the tall, wide buttons Material defaults to; a smaller control reaches+/// the 44pt touch target through `TouchTarget`. Before this existed each call+/// site invented its own,/// which is how the app ended up with seven button heights, three shape systems/// and six label sizes. Change a number here, not at a call site.abstract final class AppControl {@@ -1270,14 +1274,28 @@ abstract final class AppControl {/// one.static const double heightField = 36;- /// Corner radius. Apple's push buttons are gently rounded, not stadium — a- /// pill reads as a "chip" on macOS, not as a button.- static const double radius = 8;+ /// Text-field radius, Desktop's 10. Action buttons use the shared capsule+ /// shape, as on Desktop.+ static const double radius = 10;++ /// Menu/popover radius, Desktop's 16.+ static const double menuRadius = 16;- /// A menu/popover's rounding. Tighter than a button's: macOS menus are nearly- /// square-cornered, and rounding one like an iOS action sheet is one of the- /// louder tells that a desktop app was drawn to phone conventions.- static const double menuRadius = 6;+ /// Dialog radius, Desktop's 20.+ static const double dialogRadius = 20;++ /// A bottom sheet's top corners: the card radius (12). Desktop has no+ /// sheets; the design system's Phone section lists this as phone-only.+ static const double sheetRadius = AppCard.radius;++ /// A row inside a sheet or a card of rows, Desktop's row radius: one step+ /// tighter than the sheet around it.+ static const double rowRadius = 10;++ /// Every bottom sheet's shape, the theme's and each caller's.+ static const ShapeBorder sheetShape = RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(sheetRadius)),+ );/// The air between a menu panel and the control it hangs off.///@@ -1755,9 +1773,19 @@ TextStyle _fieldTextStyle(Color color) => TextStyle(/// the `Icon` itself still has to be handed this size at the call site.const double kFieldIconSize = 18;-RoundedRectangleBorder get _buttonShape => RoundedRectangleBorder(- borderRadius: BorderRadius.circular(AppControl.radius),-);+StadiumBorder get _buttonShape => const StadiumBorder();++// Every themed button reaches the phone's 44-point touch target on its own,+// without a `TouchTarget` at the call site: Material's padded target lays the+// button out at least 48 tall and sends a tap anywhere in that box to it, and+// one density step down makes that 44 (`minTouchTarget`). The density step+// also takes 4 off the button's own box and vertical padding, so the styles+// below give it back: the button is DRAWN exactly as before. Its layout box is+// what grows, so a row holding a 32-point button is at least 44 tall.+const MaterialTapTargetSize _touchTarget = MaterialTapTargetSize.padded;+const VisualDensity _touchDensity = VisualDensity(vertical: -1);+const double _densityStep = 4;+const EdgeInsets _densityPadding = EdgeInsets.symmetric(vertical: _densityStep);/// The primary action: a solid accent capsule./// A filled button that destroys something.@@ -1777,15 +1805,12 @@ ButtonStyle dangerButtonStyle() => FilledButton.styleFrom();ButtonStyle _filledButtonStyle() => FilledButton.styleFrom(- minimumSize: Size(0, AppControl.heightScaled),- padding: AppControl.paddingScaled,+ minimumSize: Size(0, AppControl.heightScaled + _densityStep),+ padding: AppControl.paddingScaled + _densityPadding,shape: _buttonShape,textStyle: _buttonTextStyle,- // Material pads every button out to a 48px tap target — on a desktop app- // that leaves a 32px button floating in a 48px box and wrecks every row it- // sits in.- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- visualDensity: VisualDensity.standard,+ tapTargetSize: _touchTarget,+ visualDensity: _touchDensity,// Its own wash, not [AppSurface.hoverFill]: this button already carries the// accent as a FILL, so the hover has to read against that rather than against// the page. White at 12% lifts the accent a step without turning it into a@@ -1797,24 +1822,24 @@ ButtonStyle _filledButtonStyle() => FilledButton.styleFrom(/// The secondary action: a hairline rim, no fill — Apple's "bordered" button.ButtonStyle _outlinedButtonStyle(ColorScheme scheme) =>OutlinedButton.styleFrom(- minimumSize: Size(0, AppControl.heightScaled),- padding: AppControl.paddingScaled,+ minimumSize: Size(0, AppControl.heightScaled + _densityStep),+ padding: AppControl.paddingScaled + _densityPadding,shape: _buttonShape,textStyle: _buttonTextStyle,side: BorderSide(color: scheme.outline),foregroundColor: scheme.onSurface,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- visualDensity: VisualDensity.standard,+ tapTargetSize: _touchTarget,+ visualDensity: _touchDensity,);/// The tertiary action: text only, for the quiet way out of a dialog.ButtonStyle _textButtonStyle() => TextButton.styleFrom(- minimumSize: Size(0, AppControl.heightScaled),- padding: AppControl.paddingSmallScaled,+ minimumSize: Size(0, AppControl.heightScaled + _densityStep),+ padding: AppControl.paddingSmallScaled + _densityPadding,shape: _buttonShape,textStyle: _buttonTextStyle,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- visualDensity: VisualDensity.standard,+ tapTargetSize: _touchTarget,+ visualDensity: _touchDensity,// ⚠️ Without this a text button has NO hover state at all.//// `splashFactory: NoSplash` turns Material's ripple off app-wide — right, itdiff --git a/mobile/lib/shared/theme/app_type.dart b/mobile/lib/shared/theme/app_type.dartnew file mode 100644index 000000000..4303a178a--- /dev/null+++ b/mobile/lib/shared/theme/app_type.dart@@ -0,0 +1,227 @@+import 'package:flutter/widgets.dart';++import 'app_theme.dart';++/// The phone's type scale: Desktop's `AppType` roles at a thumb's sizes.+///+/// The same role names, faces and weights as `desktop/lib/shared/theme/+/// app_type.dart`; only the sizes differ, as the Phone section of+/// `desktop/design/desktop-design-system.md` lists them.+///+/// ```+/// display sans 34 semibold one per screen: a page title, sign-in+/// title sans 22 semibold a settings pane, a hero card, a figure+/// heading sans 17 semibold a section, a sheet title, a card title+/// label sans 17 medium buttons, rows, list items, links+/// mono mono 13 regular commands, source text, paths+/// monoLabel mono 12 medium terminal labels, compact code+/// monoMeta mono 11 regular shortcut keys, identifiers, code metadata+/// body sans 17 regular prose: descriptions, explanations+/// caption sans 13 regular metadata, footnotes+/// ```+///+/// Every style takes the same optional arguments, so a call site states its+/// role and only then its colour, weight or figures.+abstract final class AppType {+ static const double displaySize = 34;+ static const double titleSize = 22;+ static const double headingSize = 17;+ static const double bodySize = 17;+ static const double captionSize = 13;+ static const double monoSize = 13;+ static const double monoLabelSize = 12;+ static const double monoMetaSize = 11;++ static TextStyle display({+ Color? color,+ FontWeight? fontWeight,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ }) => _sans(+ displaySize,+ fontWeight ?? AppFont.semibold,+ color,+ fontStyle,+ height,+ letterSpacing,+ fontFeatures,+ );++ static TextStyle title({+ Color? color,+ FontWeight? fontWeight,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ }) => _sans(+ titleSize,+ fontWeight ?? AppFont.semibold,+ color,+ fontStyle,+ height,+ letterSpacing,+ fontFeatures,+ );++ static TextStyle heading({+ Color? color,+ FontWeight? fontWeight,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ }) => _sans(+ headingSize,+ fontWeight ?? AppFont.semibold,+ color,+ fontStyle,+ height,+ letterSpacing,+ fontFeatures,+ );++ static TextStyle body({+ Color? color,+ FontWeight? fontWeight,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ }) => _sans(+ bodySize,+ fontWeight ?? AppFont.regular,+ color,+ fontStyle,+ height,+ letterSpacing,+ fontFeatures,+ );++ static TextStyle label({+ Color? color,+ FontWeight? fontWeight,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ }) => _sans(+ bodySize,+ fontWeight ?? AppFont.medium,+ color,+ fontStyle,+ height,+ letterSpacing,+ fontFeatures,+ );++ static TextStyle caption({+ Color? color,+ FontWeight? fontWeight,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ }) => _sans(+ captionSize,+ fontWeight ?? AppFont.regular,+ color,+ fontStyle,+ height,+ letterSpacing,+ fontFeatures,+ );++ static TextStyle mono({+ Color? color,+ FontWeight? fontWeight,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ }) => _mono(+ monoSize,+ fontWeight ?? AppFont.regular,+ color,+ fontStyle,+ height,+ letterSpacing,+ fontFeatures,+ );++ static TextStyle monoLabel({+ Color? color,+ FontWeight? fontWeight,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ }) => _mono(+ monoLabelSize,+ fontWeight ?? AppFont.medium,+ color,+ fontStyle,+ height,+ letterSpacing,+ fontFeatures,+ );++ static TextStyle monoMeta({+ Color? color,+ FontWeight? fontWeight,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ }) => _mono(+ monoMetaSize,+ fontWeight ?? AppFont.regular,+ color,+ fontStyle,+ height,+ letterSpacing,+ fontFeatures,+ );++ static TextStyle _sans(+ double size,+ FontWeight weight,+ Color? color,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ ) => TextStyle(+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: size,+ fontWeight: weight,+ color: color,+ fontStyle: fontStyle,+ height: height,+ letterSpacing: letterSpacing ?? AppFont.trackingFor(size),+ fontFeatures: fontFeatures,+ );++ static TextStyle _mono(+ double size,+ FontWeight weight,+ Color? color,+ FontStyle? fontStyle,+ double? height,+ double? letterSpacing,+ List<FontFeature>? fontFeatures,+ ) => TextStyle(+ fontFamily: AppFont.mono,+ fontFamilyFallback: AppFont.monoFallback,+ fontSize: size,+ fontWeight: weight,+ color: color,+ fontStyle: fontStyle,+ height: height,+ letterSpacing: letterSpacing,+ fontFeatures: fontFeatures,+ );+}diff --git a/mobile/lib/shared/theme/swarm_tokens_set_b.dart b/mobile/lib/shared/theme/swarm_tokens_set_b.dartnew file mode 100644index 000000000..141ba8267--- /dev/null+++ b/mobile/lib/shared/theme/swarm_tokens_set_b.dart@@ -0,0 +1,20 @@+import 'package:flutter/painting.dart';++/// Ink the phone's Swarm cards need that the shared theme has no role for.+abstract final class SwarmInk {+ /// Dark ink on the warning fill: a count waiting on the person.+ static const Color onWarning = Color(0xFF1A1200);+}++/// What a ship line's confetti is thrown in: six bright hues, the same in both+/// themes, because confetti is celebration and not chrome.+abstract final class SwarmConfetti {+ static const colors = <Color>[+ Color(0xffff6b6b),+ Color(0xffffc145),+ Color(0xff4ecdc4),+ Color(0xff5b8def),+ Color(0xffb084f5),+ Color(0xff6ad08a),+ ];+}diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 810d801b4..d825b355c 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -84,6 +84,8 @@ import '../phone/phone_name_store.dart';import '../viewer/device_log.dart';import '../viewer/device_history.dart';import '../viewer/device_log_sync.dart';+import '../swarm/swarm_notices.dart';+import '../swarm/swarm_request.dart';enum AppStatus { bootstrapping, unauthenticated, authenticated }@@ -2606,6 +2608,8 @@ class AppNotifier extends ChangeNotifier {if (nextStatus == ConnectionStatus.connected) {// The first computer to answer ends the launch.launchMeasurement?.ready();+ // Back with a new sign-in, maybe: a Swarm read it refused may be asked of it again.+ _swarmRefused.remove(machineId);_refreshDeviceLogAfterReconnect();machine.needsLink = false;// Let in: a later refusal is a new story ([_redialOnceVouched], [_settleTrust]).@@ -6298,6 +6302,283 @@ class AppNotifier extends ChangeNotifier {notifyListeners();}+ /// The machine the Swarm was last asked through, kept while it stays up so the reads of one+ /// screen do not hop between computers.+ String? _swarmMachineId;++ /// Machines that refused a Swarm read another machine then answered: passed over until they+ /// reconnect ([_onConnectionStatus]).+ ///+ /// ⚠️ Kept up, a refusing machine was asked for every read. On the owner's iPhone (2026-10-27)+ /// the phone moved to a Team sign-in computer while the owner's Mac was briefly offline, then+ /// read through it from 14:26 to 14:37 while the server refused every read, the Mac connected+ /// all along — until the Team computer itself was marked offline.+ final _swarmRefused = <String>{};++ /// How long a Swarm call waits for a computer on its way back — a socket redialling — before it+ /// says there is none.+ @visibleForTesting+ Duration swarmReconnectWait = const Duration(seconds: 8);++ /// The machine the phone asks the Swarm through: one of the account's own whose socket is up —+ /// the one asked last while it stays so, else the first by id, as the web build picks+ /// (`desktop/lib/state/app_state.dart` `sharedTabsTarget`) — never one that refused. Null with+ /// none up, or none but those in [except].+ MachineState? _swarmMachine({Set<MachineState> except = const {}}) {+ bool usable(MachineState? machine) =>+ machine != null &&+ !except.contains(machine) &&+ machine.connectionStatus == ConnectionStatus.connected &&+ !machine.needsLink &&+ machine.nodeOnline != false &&+ !_swarmRefused.contains(machine.machine.machineId);+ final kept = machineStates[_swarmMachineId];+ if (usable(kept)) return kept;+ MachineState? best;+ for (final machine in machineStates.values) {+ if (!usable(machine)) continue;+ if (best == null ||+ machine.machine.machineId.compareTo(best.machine.machineId) < 0) {+ best = machine;+ }+ }+ // Looking past [except] chooses nothing yet: the read through it decides.+ if (except.isEmpty) _swarmMachineId = best?.machine.machineId;+ return best;+ }++ /// One Swarm backend call ([method] on [path], `/api/super-tabs…`), forwarded by one of the+ /// account's own machines with its session (`super_tabs`, `action: backend`,+ /// cli/src/superTabs/service.ts). The phone holds no Swarm credential: the machine checks that+ /// this connection is its owner's, and the backend what that account may read. Answers the+ /// backend's value; a refusal — the backend's, the machine's, or none to ask — is a+ /// [SuperTabFailure], and an answer that lands after the account changed is dropped.+ ///+ /// A refusal is asked again through each other machine that is up, one after another, up to+ /// [_swarmAsksPerCall] in all. One that answers shows the refusals before it were those+ /// machines' own — a Team sign-in the server will not read the person's Swarm for, say — and+ /// they are passed over until they reconnect. Refusals alone pass over none: on #1802's review+ /// a Team computer's refusal of its own once passed over the Mac that had said the person left+ /// the Swarm. A command asked twice is the same command, under its operation id.+ ///+ /// With none answering, a refusal saying the person lost the Swarm stands over every other,+ /// as everywhere: what was read of it must go. Otherwise, with no other machine up to ask, one+ /// on its way back is waited for as below. With none, refusals from every machine up while+ /// another of the account's is away tell nothing yet: no computer, so the list is read again+ /// and Swarm soon retries ([SwarmInbox]). On the owner's iPhone (2026-10-27, 15:06) Swarm+ /// showed a Team sign-in's refusal instead, and stayed on it until its next 15-second read,+ /// 14 seconds after the Mac was back. With no other machine of the account, the last refusal+ /// is the read's own.+ ///+ /// Nor is one read lost on the way — a timeout, a socket dropped — the end of it: it is asked+ /// again through another computer that is up. With none up but one redialling, the call waits+ /// [swarmReconnectWait] for it: Swarm said "Connect one of your computers" for 10 to 25 seconds+ /// at a time on the owner's iPhone (2026-10-27) while the computer stayed connected.+ Future<Object?> swarmRequest(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ var machine = _swarmMachine() ?? await _swarmMachineBack();+ if (machine == null) throw _swarmNoComputer();+ final asked = <MachineState>{}, refused = <MachineState>[];+ SuperTabFailure? lost;+ late Object failure;+ late StackTrace trace;+ while (machine != null) {+ asked.add(machine);+ try {+ final value = await _swarmRequestVia(machine, method, path, body);+ _swarmRefused.addAll([for (final m in refused) m.machine.machineId]);+ _swarmMachineId = machine.machine.machineId;+ return value;+ } on SuperTabFailure catch (refusal, stack) {+ if (refusal.code == 'ACCOUNT_CHANGED') rethrow;+ (failure, trace) = (refusal, stack);+ refused.add(machine);+ if (const {'FORBIDDEN', 'NOT_FOUND'}.contains(refusal.code)) {+ lost ??= refusal;+ }+ } catch (error, stack) {+ (failure, trace) = (error, stack);+ }+ if (asked.length == _swarmAsksPerCall) break;+ machine =+ _swarmMachine(except: asked) ??+ (failure is SuperTabFailure+ ? await _swarmMachineBack(except: asked)+ : null);+ }+ if (lost != null) throw lost;+ if (machine == null &&+ failure is SuperTabFailure &&+ _swarmAnyOther(asked)) {+ throw _swarmNoComputer();+ }+ Error.throwWithStackTrace(failure, trace);+ }++ /// Sends one Swarm chat file to the backend ([SwarmUpload]): straight from this phone with its own+ /// sign-in ([ApiClient.uploadSwarmAttachment]), not through a machine as [swarmRequest] goes — the+ /// backend takes a chat file only from the client, and a machine forwards only JSON. An answer+ /// that lands after the account changed is dropped.+ Future<Map<String, dynamic>> swarmUpload({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+ }) async {+ final revision = _authRevision;+ void stillThisAccount() {+ if (!_authWorkCurrent(revision)) {+ throw const SuperTabFailure(+ 'ACCOUNT_CHANGED',+ 'The account changed. Open Swarm again.',+ );+ }+ }++ try {+ final answer = await api.uploadSwarmAttachment(+ tabId: tabId,+ conversationId: conversationId,+ name: name,+ mime: mime,+ bytes: bytes,+ cancel: cancel,+ onProgress: onProgress,+ );+ stillThisAccount();+ return answer;+ } catch (_) {+ stillThisAccount();+ rethrow;+ }+ }++ /// How many machines one Swarm call asks at most, one after another.+ static const _swarmAsksPerCall = 5;++ /// No computer to ask the Swarm through, with the list read again.+ SuperTabFailure _swarmNoComputer() {+ _swarmListAgain();+ return const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ );+ }++ /// Another of the account's machines than those [asked] could be asked once it is up: linked,+ /// and not passed over.+ bool _swarmAnyOther(Set<MachineState> asked) => machineStates.values.any(+ (other) =>+ !asked.contains(other) &&+ !other.needsLink &&+ !_swarmRefused.contains(other.machine.machineId),+ );++ /// When the computer list was last read again for Swarm: at most once in [_swarmListGap].+ DateTime? _swarmListedAt;+ static const _swarmListGap = Duration(seconds: 2);++ /// No computer to ask: the list is read again, as a refresh by hand would. What it says of each+ /// one can be stale — a computer reported off at launch whose socket waits parked for a word+ /// that it is back — and with any socket up, nothing else reads it again ([_rereadMachinesWhileDeaf]).+ /// Swarm's own retries set the pace ([SwarmInbox]).+ void _swarmListAgain() {+ final now = DateTime.now();+ final last = _swarmListedAt;+ if (last != null && now.difference(last) < _swarmListGap) return;+ _swarmListedAt = now;+ _rereadMachines();+ }++ /// A computer that comes up within [swarmReconnectWait], when one is on its way: dialling or+ /// redialling, linked, not reported off, and not passed over — nor in [except]. Null otherwise.+ Future<MachineState?> _swarmMachineBack({+ Set<MachineState> except = const {},+ }) async {+ bool coming(MachineState machine) =>+ !except.contains(machine) &&+ (machine.connectionStatus == ConnectionStatus.connecting ||+ machine.connectionStatus == ConnectionStatus.reconnecting) &&+ !machine.needsLink &&+ machine.nodeOnline != false &&+ !_swarmRefused.contains(machine.machine.machineId);+ if (!machineStates.values.any(coming)) return null;+ final back = Completer<MachineState?>();+ void look() {+ if (back.isCompleted) return;+ final machine = _swarmMachine(except: except);+ if (machine != null || !machineStates.values.any(coming)) {+ back.complete(machine);+ }+ }++ addListener(look);+ final timer = Timer(swarmReconnectWait, () {+ if (!back.isCompleted) back.complete(null);+ });+ try {+ return await back.future;+ } finally {+ timer.cancel();+ removeListener(look);+ }+ }++ Future<Object?> _swarmRequestVia(+ MachineState machine,+ String method,+ String path,+ Map<String, dynamic>? body,+ ) async {+ final revision = _authRevision;+ void stillThisAccount() {+ if (!_authWorkCurrent(revision)) {+ throw const SuperTabFailure(+ 'ACCOUNT_CHANGED',+ 'The account changed. Open Swarm again.',+ );+ }+ }++ final Map<String, dynamic> answer;+ try {+ answer = await _conn(machine.machine.machineId).request(+ 'super_tabs',+ payload: {+ 'action': 'backend',+ 'method': method,+ 'path': path,+ 'body': ?body,+ },+ timeout: const Duration(seconds: 30),+ );+ } on WsRequestFailure catch (failure) {+ stillThisAccount();+ throw SuperTabFailure(+ failure.code,+ failure.detail ?? 'Could not reach this Swarm.',+ );+ } catch (_) {+ stillThisAccount();+ rethrow;+ }+ stillThisAccount();+ if (answer['error'] != null) {+ throw SuperTabFailure(+ answer['error'].toString(),+ answer['detail'] as String? ?? 'Could not reach this Swarm.',+ statusCode: (answer['status'] as num?)?.toInt() ?? 0,+ );+ }+ return answer['value'];+ }+Future<Map<String, dynamic>> connectors(String machineId,Map<String, dynamic> payload, {@@ -11046,6 +11327,15 @@ final appStateProvider = Provider<AppNotifier>((ref) {configStore: ConfigStore(),paneLayoutStore: PaneLayoutStore(),);+ // The app icon's Swarm count: a launch that starts signed out has no+ // Swarm session to take the last account's number off.+ if (app.agentNotices.system case final SwarmNotices notices) {+ swarmBadgeOffWhileSignedOut(+ app,+ signedOut: () => app.status == AppStatus.unauthenticated,+ notices: notices,+ );+ }app.bootstrap();return app;});diff --git a/mobile/lib/swarm/identity.dart b/mobile/lib/swarm/identity.dartnew file mode 100644index 000000000..934a0f3fd--- /dev/null+++ b/mobile/lib/swarm/identity.dart@@ -0,0 +1,3 @@+/// How a person is named in the Swarm: their email's name, as the desktop+/// names them (`desktop/lib/super_tabs/identity.dart`).+String superTabPersonName(String email) => email.split('@').first;diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartnew file mode 100644index 000000000..3fd115f95--- /dev/null+++ b/mobile/lib/swarm/model.dart@@ -0,0 +1,944 @@+import 'identity.dart' show superTabPersonName;+import 'profile_model.dart';++export 'profile_model.dart';++/// Backend records are independent of the desktop's visible panes and tab layout.+Map<String, dynamic> superTabMap(Object? value) => value is Map+ ? Map<String, dynamic>.from(value)+ : throw const FormatException('Invalid Swarm response.');++String _text(Map<String, dynamic> value, String key) => value[key] is String+ ? value[key] as String+ : throw FormatException('Missing Swarm $key.');++List<T> _list<T>(Object? value, T Function(Map<String, dynamic>) read) =>+ value is List+ ? List.unmodifiable(value.map((row) => read(superTabMap(row))))+ : throw const FormatException('Invalid Swarm list.');++/// [rows] by id; the first row wins where two share one, as a scan would.+Map<String, T> _byId<T>(List<T> rows, String Function(T row) idOf) => {+ for (final row in rows.reversed) idOf(row): row,+};++/// Work that waits on a person: the agent needs a decision (`needs_human`) or+/// is stuck (`blocked`). Both stay active work until the agent moves on.+bool superTabWorkWaits(Object? status) =>+ status == 'needs_human' || status == 'blocked';++/// How a work status reads in the app. `blocked` is what the agent calls it;+/// people read Stuck. Statuses this build does not know read as sent.+String superTabWorkStatusLabel(String status) =>+ status == 'blocked' ? 'stuck' : status.replaceAll('_', ' ');++class SuperTabPerson {+ SuperTabPerson.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ email = _text(row, 'email'),+ role = _text(row, 'role'),+ generation = row['generation'] as String?,+ avatar = SuperTabAvatarPicture.fromJson(row['avatar']),+ status = SuperTabPersonStatus.fromJson(row['status']);+ final String id, email, role;+ final SuperTabAvatarPicture? avatar;+ final SuperTabPersonStatus? status;++ /// Their status while it lasts.+ SuperTabPersonStatus? statusAt(DateTime now) =>+ status?.shownAt(now) == true ? status : null;++ /// This membership: a new one each time the person joins the Swarm. Null+ /// from a backend that does not send it.+ final String? generation;+ bool get canWrite => role == 'owner' || role == 'collaborator';+}++class SuperTabAgent {+ SuperTabAgent.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ hasProjectId = row['projectId'] != null,+ projectId = row['projectId'] as String? ?? 'lead',+ name = _text(row, 'name'),+ displayName = row['displayName'] as String?,+ machineId = _text(row, 'machineId'),+ harnessId = _text(row, 'harnessId'),+ contributorId = _text(row, 'contributorId'),+ machineOwnerId =+ row['machineOwnerId'] as String? ?? _text(row, 'contributorId'),+ role = row['role'] as String?,+ roleId = row['roleId'] as String?,+ buddyOf = switch (row['buddyOf']) {+ {'personId': final String person} => person,+ _ => null,+ },+ limitedUntil = DateTime.tryParse(row['limitedUntil'] as String? ?? ''),+ avatar = SuperTabAvatarPicture.fromJson(row['avatar']),+ downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),+ confidential = row['confidential'] == true,+ configuration = Map.unmodifiable(superTabMap(row['configuration']));+ final String id, projectId, name, machineId, harnessId, contributorId;++ /// Set by its contributor or its project's Lead; null draws its pattern.+ final SuperTabAvatarPicture? avatar;++ /// Until when routing skips it: its machine saw a usage limit on its screen+ /// (spec/2026-10-23-lead-sees-agent-terminal.md). Null when none was seen.+ final DateTime? limitedUntil;++ /// Since when its machine has reported its session gone, or its host confirmed a stop (backend machines.ts). Null+ /// while it runs.+ final DateTime? downSince;++ /// The account whose computer runs it; a contributor may run agents on a computer another account shared with them.+ final String machineOwnerId;++ /// Its session read private chats: a Product Manager, now or before, or an agent in a private chat. Only the person+ /// whose computer runs it may watch it, but every member watches the current Product Manager, view only+ /// (backend projects.ts `watchClosed`, terminal_unavailable.dart `superTabTerminalPrivate`).+ final bool confidential;+ // Keep the legacy default for callers while allowing group-based roster ownership.+ final bool hasProjectId;+ final String? displayName;+ // Absent until the backend sends one; an agent without a role is a Builder.+ final String? role;+ final String? roleId;+ bool get isReviewer => role == 'reviewer';++ /// A person's private agent for one project (spec: Buddies, 10-28); it+ /// never takes work. The backend gives it no role, only its person.+ bool get isBuddy => buddyOf != null;++ /// The person whose Buddy it is; null for any other agent.+ final String? buddyOf;+ final Map<String, dynamic> configuration;+ String get engine => configuration['engine'] as String? ?? '';+}++class SuperTabTask {+ SuperTabTask.fromJson(Map<String, dynamic> row)+ : goal = _text(row, 'goal'),+ changes = _text(row, 'changes'),+ constraints = _text(row, 'constraints'),+ owns = List.unmodifiable((row['owns'] as List).cast<String>());++ final String goal, changes, constraints;+ final List<String> owns;+}++class SuperTabConversation {+ SuperTabConversation.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ // The Product Managers' conversation belongs to no project; a group from+ // before projects belongs to the first.+ projectId =+ row['projectId'] as String? ?? (row['kind'] == 'leads' ? '' : 'lead'),+ kind = row['kind'] as String?,+ buddyOwnerId = row['buddyOwnerId'] as String?,+ number = (row['number'] as num?)?.toInt(),+ title = _text(row, 'title'),+ leadId = row['leadId'] as String?,+ agentIds = List.unmodifiable((row['agentIds'] as List).cast<String>()),+ archived = row['archived'] == true,+ dormant = row['dormant'] == true,+ // A Buddy chat names no audience: its person alone reads it.+ audience = row['kind'] == 'buddy' && row['buddyOwnerId'] is String+ ? List.unmodifiable([row['buddyOwnerId'] as String])+ : row['audience'] is Map+ ? List.unmodifiable([+ for (final person+ in superTabMap(row['audience'])['people'] as List? ??+ const [])+ if (person is Map && person['id'] is String) person['id'],+ ])+ : null,+ checks = _list(+ row['checks'] ?? const [],+ (check) => Map<String, dynamic>.unmodifiable(check),+ ),+ pullRequestUrls = List.unmodifiable(+ (row['pullRequestUrls'] as List?)?.whereType<String>() ??+ const <String>[],+ ),+ brief = _text(row, 'brief'),+ task = row['task'] is Map+ ? SuperTabTask.fromJson(superTabMap(row['task']))+ : null,+ lastMessageSequence = (row['lastMessageSequence'] as num?)?.toInt() ?? 0,+ lastMainSequence = (row['lastMainSequence'] as num?)?.toInt(),+ reactionSeq = (row['reactionSeq'] as num?)?.toInt() ?? 0,+ assignment = row['assignment'] == null+ ? null+ : Map.unmodifiable(superTabMap(row['assignment'])),+ liveness = row['liveness'] is Map+ ? Map.unmodifiable(superTabMap(row['liveness']))+ : null,+ leadAction = row['leadAction'] is Map+ ? Map.unmodifiable(superTabMap(row['leadAction']))+ : null;+ final String id, projectId, title, brief;++ /// What the backend calls it apart from a workgroup: `leads` for the Product+ /// Managers' conversation, `buddy` for a person's chat with their Buddy.+ final String? kind;+ bool get isBuddyChat => kind == 'buddy';++ /// The person a Buddy chat belongs to; only they read it.+ final String? buddyOwnerId;+ final SuperTabTask? task;+ final int? number;+ String get label => number == null ? title : '#$number $title';+ final String? leadId;+ final List<String> agentIds;+ final bool archived;++ /// A private conversation's people, who read it with the project's Lead+ /// and nobody else; null for a conversation the project shares.+ final List<String>? audience;++ /// Out of the Swarm's active groups: archived, or finished and quiet for a+ /// day. Read on demand; a new message brings it back.+ final bool dormant;++ /// Listed with the project's closed groups, not its active ones.+ bool get closed => archived || dormant;+ final List<Map<String, dynamic>> checks;++ /// Persisted links may be absent on older backends; loaded messages still supply links.+ final List<String> pullRequestUrls;+ final int lastMessageSequence;++ /// Its newest message in the main stream: a reply only in its thread+ /// leaves it. Null from a backend before threads, or before this+ /// conversation's first message since.+ final int? lastMainSequence;++ /// The newest message that makes it unread, as the desktop's+ /// `SuperTabController.unread` counts it: a reply only in its thread does+ /// not, though the phone, with no thread view yet, shows it in the chat.+ int get mainSequence => lastMainSequence ?? lastMessageSequence;++ /// Moves whenever a reaction here is added or taken back (backend+ /// reactions.ts): the messages shown are read again for their counts.+ final int reactionSeq;+ final Map<String, dynamic>? assignment;++ /// Whether its task waits on purpose or is stuck, as the server last found+ /// it (`state`, `why`, `since`, `personId`); absent while it is working,+ /// and from older backends. Read as the desktop's model reads it+ /// (desktop_parity_test); the phone shows none of it yet.+ final Map<String, dynamic>? liveness;++ /// The Product Manager's last action on its task (`kind`, `at`); read as+ /// [liveness] is.+ final Map<String, dynamic>? leadAction;+}++class SuperTabRole {+ SuperTabRole.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ name = _text(row, 'name'),+ kind = _text(row, 'kind'),+ version = _text(row, 'version');++ final String id, name, kind, version;+}++class SuperTabProject {+ SuperTabProject.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ name = _text(row, 'name'),+ ownerId = _text(row, 'ownerId'),+ leadConversationId = _text(row, 'leadConversationId'),+ skillMode = row['skillMode'] == 'default' ? 'default' : 'orchestration',+ skillSet =+ const {'default', 'orchestration', 'custom'}.contains(row['skillSet'])+ ? row['skillSet'] as String+ : row['skillMode'] == 'default'+ ? 'default'+ : 'orchestration',+ roles = row['roles'] is List+ ? _list(row['roles'], SuperTabRole.fromJson)+ : null,+ isPrivate = row['visibility'] == 'private',+ memberIds = [+ for (final member in row['members'] as List? ?? const [])+ superTabMap(member)['id'] as String,+ ],+ updateMinutes = (row['updateMinutes'] as num?)?.toInt() ?? 5,+ repository = row['repository'] is Map+ ? Map.unmodifiable(superTabMap(row['repository']))+ : null;+ final String id, name, ownerId, leadConversationId;+ final String skillMode;+ final String skillSet;+ final List<SuperTabRole>? roles;+ final bool isPrivate;+ final List<String> memberIds;+ final int updateMinutes;+ final Map<String, dynamic>? repository;+}++class SuperTabSnapshot {+ SuperTabSnapshot.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ name = _text(row, 'name'),+ ownerId = _text(row, 'ownerId'),+ paused = row['paused'] == true,+ project = row['project'] == null+ ? null+ : Map.unmodifiable(superTabMap(row['project'])),+ people = _list(row['people'], SuperTabPerson.fromJson),+ agents = _list(row['agents'], SuperTabAgent.fromJson),+ machines = _list(+ row['machines'] ?? const [],+ (m) => Map<String, dynamic>.unmodifiable(m),+ ),+ conversations = _list(+ row['conversations'],+ SuperTabConversation.fromJson,+ ),+ invitations = _list(+ row['invitations'],+ (row) => Map<String, dynamic>.unmodifiable(row),+ ),+ leadsConversationId = row['leadsConversationId'] as String?,+ startEfforts = Map.unmodifiable({+ for (final start+ in row['starts'] is List ? row['starts'] as List : const [])+ if (start case {+ 'harnessId': final String harness,+ 'request': {'effort': final String effort},+ })+ harness: effort,+ }),+ localModels = SuperTabLocalModels.read(row['localModels']),+ mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0,+ mentionsDigest = row['mentionsDigest'] as String?,+ decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,+ decisionsDigest = row['decisionsDigest'] as String?,+ readMarks = Map.unmodifiable({+ if (row['readMarks'] case final Map marks)+ for (final MapEntry(:key, :value) in marks.entries)+ if (key is String && value is num) key: value.toInt(),+ }),+ buddiesEnabled = row['buddies'] == true,+ buddyStarts = List.unmodifiable([+ for (final start+ in row['starts'] is List ? row['starts'] as List : const [])+ if (start case {'request': {'buddyOf': Map _}})+ Map<String, dynamic>.unmodifiable(superTabMap(start)),+ ]) {+ if (row['version'] != 1) {+ throw const FormatException('Update Harness to open this Swarm.');+ }+ projects = _list(+ row['projects'] ??+ [+ {+ 'id': 'lead',+ 'name': name,+ 'ownerId': ownerId,+ 'leadConversationId': 'lead',+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ if (project != null) 'repository': project,+ },+ ],+ SuperTabProject.fromJson,+ );+ }+ final String id, name, ownerId;+ final Map<String, dynamic>? project;+ final bool paused;++ /// The Swarm's Buddies setting: off unless its owner turned it on, and off+ /// from a backend before Buddies.+ final bool buddiesEnabled;++ /// The starts of Buddies, oldest first: a Buddy's add is under way while+ /// its start has neither a harness nor an error.+ final List<Map<String, dynamic>> buddyStarts;+ final List<SuperTabPerson> people;+ final List<SuperTabAgent> agents;+ final List<Map<String, dynamic>> machines;+ final List<SuperTabConversation> conversations;+ late final List<SuperTabProject> projects;+ final List<Map<String, dynamic>> invitations;++ /// The effort each started agent's start asked for, by harness id. Empty where the starts are not read (a view+ /// kept on this device leaves them out).+ final Map<String, String> startEfforts;++ /// Where the projects' Product Managers talk, Swarm-wide; null in a Swarm+ /// from before it (spec 2026-10-23-leads-see-and-talk.md).+ final String? leadsConversationId;++ /// The Local models add-on, once the owner has turned it on; null before.+ final SuperTabLocalModels? localModels;++ /// The reader's tags still waiting for them, Swarm-wide; 0 from a backend+ /// before tags (spec 2026-10-24-lead-mentions.md).+ final int mentionsWaiting;++ /// Which tags wait, as a digest that moves when they change though the+ /// count may not; null from a backend before it (superTabs/mentions.ts).+ final String? mentionsDigest;++ /// Decisions asked of the reader and not yet answered, Swarm-wide; 0 from a+ /// backend before decisions (backend superTabs/decisions.ts).+ final int decisionsWaiting;++ /// Which decisions wait, as a digest that moves when they change though the+ /// count may not; null from a backend before it (superTabs/decisions.ts).+ final String? decisionsDigest;++ /// The reader's own read marks kept on the server (backend readMarks.ts): the newest message sequence read, by+ /// conversation, on any of their devices. Never another person's.+ final Map<String, int> readMarks;+ // Built on first use: a read is never changed, and lookups run per row on+ // every build.+ late final _conversationsById = _byId(conversations, (c) => c.id);+ late final _agentsById = _byId(agents, (a) => a.id);+ late final _projectsById = _byId(projects, (p) => p.id);+ late final _projectsByLead = <String, SuperTabProject>{+ for (final p in projects.reversed)+ ?conversation(p.leadConversationId)?.leadId: p,+ };++ SuperTabConversation? conversation(String id) => _conversationsById[id];+ SuperTabAgent? agent(String id) => _agentsById[id];+ SuperTabProject? projectById(String id) => _projectsById[id];++ SuperTabProject? projectFor(String conversationId) {+ final group = conversation(conversationId);+ return group == null ? null : projectById(group.projectId);+ }++ bool isProjectLead(String conversationId) =>+ projects.any((p) => p.leadConversationId == conversationId);++ SuperTabProject? leadProjectForAgent(String agentId) =>+ _projectsByLead[agentId];++ bool isLead(String agentId) => leadProjectForAgent(agentId) != null;++ SuperTabRole? activeRoleForAgent(SuperTabAgent agent) {+ final leadProject = leadProjectForAgent(agent.id);+ final roleKind = leadProject != null+ ? 'lead'+ : agent.isReviewer+ ? 'reviewer'+ : 'builder';+ final project = leadProject ?? projectById(agent.projectId);+ if (project?.skillSet != 'custom') return null;+ final roles = project?.roles ?? const <SuperTabRole>[];+ return roles+ .where((role) => role.id == agent.roleId && role.kind == roleKind)+ .firstOrNull ??+ roles.where((role) => role.kind == roleKind).firstOrNull;+ }++ String? leadProtectionReason(String agentId) {+ final project = leadProjectForAgent(agentId);+ if (project == null) return null;+ return '${agentName(agentId)} is the Product Manager of project ${project.name}. Delete the project first.';+ }++ /// The agents of a workgroup whose role is Reviewer.+ List<SuperTabAgent> reviewers(SuperTabConversation group) => [+ for (final id in group.agentIds)+ if (agent(id) case final a? when a.isReviewer) a,+ ];++ String agentName(String id, {String fallback = 'Agent'}) {+ final found = agent(id);+ return found?.displayName ?? found?.name ?? fallback;+ }++ /// [machineId]'s contribution to this Swarm, if it has one.+ Map<String, dynamic>? pool(String machineId) =>+ machines.where((m) => m['machineId'] == machineId).firstOrNull;++ /// The Mac a Harness Team account's pool is part of: the machine its pool names as `hostMachineId` (stamped by the+ /// backend), while that Mac is in this Swarm too, from the same person (docs/plans/2026-10-24-swarm-team-account.md).+ /// Null for every other pool, a machine used only for agents included.+ String? _macOf(Map<String, dynamic>? team) {+ final host = team?['hostMachineId'];+ if (host is! String || host == team!['machineId']) return null;+ final mac = pool(host);+ return mac != null &&+ mac['hostMachineId'] == null &&+ mac['contributorId'] == team['contributorId']+ ? host+ : null;+ }++ /// Every Harness Team account's pool in [machineId]'s row: one, or more once the account was set up again and its old+ /// pool is still listed (backend superTabs/machines.ts `teamPoolsOf`). The backend changes them with the Mac.+ List<Map<String, dynamic>> teamPoolsOf(String machineId) => [+ for (final m in machines)+ if (_macOf(m) == machineId) m,+ ];++ /// The one of them that runs teammates' work on the Mac: not being removed, and the last to report (backend+ /// superTabs/machines.ts `teamPoolOf`). Null when there is none.+ Map<String, dynamic>? teamPoolOf(String machineId) {+ num reported(Map<String, dynamic> m) => switch (m['observation']) {+ {'receivedAt': final num at} => at,+ _ => -1,+ };+ Map<String, dynamic>? best;+ for (final m in teamPoolsOf(machineId)) {+ if (m['removal'] != null) continue;+ // Removed (`harness team remove` deletes its machine): the server reads a live account never so, and the Mac is a+ // Mac without one again, which its owner can set up from its row (local Team account run, 2026-10-28).+ if (m['teamWork'] case {'code': 'TEAM_ACCOUNT_REQUIRED'}) continue;+ if (best == null || reported(m) >= reported(best)) best = m;+ }+ return best;+ }++ /// The pool whose reading [accountId] sees for the machine row [machineId]: the Mac's Harness Team account for+ /// everyone but the Mac's own contributor, since it runs their agents, also while the owner is away from the Mac; the+ /// machine's own pool otherwise. The Machines view reads a machine by this one rule.+ Map<String, dynamic>? readingPoolOf(String machineId, String? accountId) {+ final own = pool(machineId), team = teamPoolOf(machineId);+ final contributor =+ own?['contributorId'] as String? ??+ agents+ .where((a) => placeOf(a.machineId) == machineId)+ .firstOrNull+ ?.contributorId;+ return team != null && contributor != accountId ? team : own;+ }++ /// The machine [machineId] is shown as in this Swarm, one row per computer: the Mac, for its Harness Team account+ /// while that Mac is in the Swarm too; [machineId] itself otherwise.+ String placeOf(String machineId) => _macOf(pool(machineId)) ?? machineId;++ /// Whether more than one person can start work here: teammates' agents are a question only then.+ bool get hasTeammates => people.where((p) => p.role != 'viewer').length > 1;++ // Resolve the person shown in chat from the same identity as the roster.+ // Recorded labels remain the fallback for agents no longer in the Swarm.+ String authorName(SuperTabMessage message) => message.fromAgent+ ? agentName(message.authorId, fallback: message.authorName)+ : superTabPersonName(message.authorName);+}++/// The Swarm's Local models add-on (docs/plans/2026-10-23-swarm-local-models.md): its grid, whether it is on, and what the+/// owner's computer last reported about setting the grid up (`ready` null until it has).+class SuperTabLocalModels {+ const SuperTabLocalModels({+ required this.grid,+ required this.enabled,+ this.ready,+ this.error,+ });++ static SuperTabLocalModels? read(Object? value) {+ if (value is! Map || value['grid'] is! String) return null;+ return SuperTabLocalModels(+ grid: value['grid'] as String,+ enabled: value['enabled'] == true,+ ready: value['ready'] is bool ? value['ready'] as bool : null,+ error: value['error'] is String ? value['error'] as String : null,+ );+ }++ final String grid;+ final bool enabled;+ final bool? ready;+ final String? error;+}++/// One model the Swarm can start Builders on now, as a machine's fresh reading says: on the Swarm's grid (`local`, a+/// member's engine; `api`, an API a member shares), usable from any machine; or shared with the machine's owner and+/// offered by them (`shared`), usable on that machine alone.+typedef SuperTabLocalModelRow = ({+ String grid,+ String model,+ String name,+ String machine,+ String kind,+});++/// Every model the Swarm can use now, once each, from the machines' fresh readings (backend `MACHINE_FRESH_MS`).+List<SuperTabLocalModelRow> superTabLocalModelRows(+ SuperTabSnapshot? snapshot, {+ required DateTime now,+ Duration freshFor = const Duration(seconds: 45),+}) {+ final local = snapshot?.localModels;+ if (local == null || !local.enabled) return const [];+ final rows = <SuperTabLocalModelRow>[];+ for (final pool in snapshot!.machines) {+ final observation = pool['observation'];+ if (observation is! Map) continue;+ final at = observation['receivedAt'];+ if (at is! num ||+ now.difference(DateTime.fromMillisecondsSinceEpoch(at.toInt())) >+ freshFor) {+ continue;+ }+ for (final m+ in observation['localModels'] is List+ ? observation['localModels'] as List+ : const []) {+ // Still starting (the grid does not list it yet): not usable by the Swarm now.+ if (m is! Map ||+ m['grid'] is! String ||+ m['model'] is! String ||+ m['starting'] == true) {+ continue;+ }+ final grid = m['grid'] as String, model = m['model'] as String;+ if (rows.any((r) => r.grid == grid && r.model == model)) continue;+ rows.add((+ grid: grid,+ model: model,+ name: m['name'] is String ? m['name'] as String : model,+ machine: pool['name'] as String? ?? 'A machine',+ kind: m['kind'] is String+ ? m['kind'] as String+ : grid == local.grid+ ? 'local'+ : 'shared',+ ));+ }+ }+ return rows;+}++/// One model a machine serves on the Swarm's grid, as its last reading says.+typedef SuperTabServedModel = ({String model, String name});++/// The models [pool]'s reading says it serves on [grid]. A reading older than [freshFor] says nothing (backend+/// `MACHINE_FRESH_MS`), as the route reads it.+List<SuperTabServedModel> superTabServedModels(+ Map<String, dynamic>? pool,+ String grid, {+ required DateTime now,+ Duration freshFor = const Duration(seconds: 45),+}) {+ final observation = pool?['observation'];+ if (observation is! Map) return const [];+ final at = observation['receivedAt'];+ if (at is! num ||+ now.difference(DateTime.fromMillisecondsSinceEpoch(at.toInt())) >+ freshFor) {+ return const [];+ }+ return [+ for (final m+ in observation['localModels'] is List+ ? observation['localModels'] as List+ : const [])+ if (m is Map &&+ m['grid'] == grid &&+ m['model'] is String &&+ m['starting'] != true)+ (+ model: m['model'] as String,+ name: m['name'] is String+ ? m['name'] as String+ : m['model'] as String,+ ),+ ];+}++class SuperTabRouteChoice {+ const SuperTabRouteChoice(this.id, this.title);+ final String id, title;+}++/// The routing decision a Lead message reports: who got the task and why.+class SuperTabRoute {+ SuperTabRoute._(+ this.decisionId,+ this.via,+ this.p,+ this.belowFloor,+ this.why,+ this.fallback,+ this.pick,+ this.alternatives,+ );+ static SuperTabRoute? fromSource(Map<String, dynamic> s) {+ final pick = s['pick'];+ final decisionId = s['decisionId'];+ if (s['kind'] != 'route' ||+ decisionId is! String ||+ pick is! Map ||+ pick['id'] is! String ||+ pick['title'] is! String) {+ return null;+ }+ final via = s['via'];+ final why = s['why'];+ final alternatives = s['alternatives'];+ return SuperTabRoute._(+ decisionId,+ via is String ? via : 'order',+ s['p'] is num ? (s['p'] as num).toDouble() : null,+ s['belowFloor'] == true,+ why is String ? why : '',+ s['fallback'] is String ? s['fallback'] as String : null,+ SuperTabRouteChoice(pick['id'] as String, pick['title'] as String),+ [+ if (alternatives is List)+ for (final a in alternatives)+ if (a is Map && a['id'] is String && a['title'] is String)+ SuperTabRouteChoice(a['id'] as String, a['title'] as String),+ ],+ );+ }++ /// The Lead's reason for the task. Why the policy order decided, when it did,+ /// is [fallback]: `unsure` or `unavailable`.+ final String decisionId, via, why;+ final String? fallback;+ final double? p;+ final bool belowFloor;+ final SuperTabRouteChoice pick;+ final List<SuperTabRouteChoice> alternatives;+}++/// A file sent with a message. The chat never loads [url] by itself.+class SuperTabAttachment {+ SuperTabAttachment.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ name = _text(row, 'name'),+ mime = _text(row, 'mime'),+ size = (row['size'] as num).toInt(),+ url = _text(row, 'url');+ final String id, name, mime, url;+ final int size;++ /// The kinds the backend serves to be seen in place; every other kind is+ /// served as a download.+ bool get isImage => const {+ 'image/png',+ 'image/jpeg',+ 'image/gif',+ 'image/webp',+ }.contains(mime);+}++/// A message's files. A row that does not read is left out, so one bad row+/// cannot hide the page of messages it came in.+List<SuperTabAttachment> _attachments(Object? rows) => List.unmodifiable([+ if (rows is List)+ for (final row in rows) ?_tryAttachment(row),+]);++SuperTabAttachment? _tryAttachment(Object? row) {+ try {+ return SuperTabAttachment.fromJson(superTabMap(row));+ } catch (_) {+ return null;+ }+}++/// Messages in the order a conversation shows them: by sequence, then id, as+/// the backend pages them (messages from before the parts migration can share+/// a sequence).+int superTabMessageOrder(SuperTabMessage a, SuperTabMessage b) {+ final bySequence = a.sequence.compareTo(b.sequence);+ return bySequence != 0 ? bySequence : a.id.compareTo(b.id);+}++/// Where a conversation's older history continues: the message a page ended+/// on (docs/design/2026-10-26-swarm-state-parts.md, section 4.6).+class SuperTabPage {+ const SuperTabPage(this.sequence, this.id);+ SuperTabPage.of(SuperTabMessage message) : this(message.sequence, message.id);++ /// The backend's `next`, or null at the start of the conversation.+ static SuperTabPage? read(Object? next) => switch (next) {+ {'sequence': final num sequence, 'id': final String id} => SuperTabPage(+ sequence.toInt(),+ id,+ ),+ null => null,+ _ => throw const FormatException('Invalid Swarm page.'),+ };++ final int sequence;+ final String id;+ Map<String, dynamic> toJson() => {'sequence': sequence, 'id': id};+}++/// Optional timing/hold fields keep messages from older backends readable.+class SuperTabDelivery {+ SuperTabDelivery.fromJson(Map<String, dynamic> row)+ : id = row['id'] as String?,+ agentId = row['agentId'] as String? ?? '',+ status = row['status'] as String? ?? '',+ holdReason = row['holdReason'] as String?,+ holdSince = _date(row['holdSince']),+ deliveredAt = _date(row['deliveredAt']),+ answeredAt = _date(row['answeredAt']),+ updatedAt = _date(row['updatedAt']);+ final String? id, holdReason;+ final String agentId, status;+ final DateTime? holdSince, deliveredAt, answeredAt, updatedAt;+ static DateTime? _date(Object? value) =>+ value is String ? DateTime.tryParse(value) : null;+ bool get pending => status == 'queued' || status == 'claimed';+ bool get delivered => status == 'delivered' || status == 'confirmed';++ // One line cannot promise arrival while another recipient still waits.+ int get receiptOrder => switch (status) {+ 'uncertain' => 0,+ 'queued' || 'claimed' => 1,+ 'cancelled' => 2,+ 'delivered' || 'confirmed' => 3,+ 'answered' => 4,+ _ => 5,+ };+}++/// What a page says about one thread (backend threads.ts): the line under its+/// root, and who it marks unread for. Read as the desktop's model reads it+/// (desktop_parity_test); the phone shows none of it yet.+class SuperTabThread {+ SuperTabThread.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ replies = (row['replies'] as num).toInt(),+ lastSequence = (row['lastSequence'] as num).toInt(),+ lastAt = DateTime.tryParse(row['lastAt'] as String? ?? ''),+ authors = List.unmodifiable(+ (row['authors'] as List? ?? const []).map(superTabMap),+ ),+ people = List.unmodifiable(+ (row['people'] as List? ?? const []).whereType<String>(),+ );+ final String id;+ final int replies, lastSequence;+ final DateTime? lastAt;++ /// The newest distinct reply authors, newest first: the first wrote the+ /// last reply.+ final List<Map<String, dynamic>> authors;++ /// People who wrote in the thread or were tagged in it.+ final List<String> people;+}++class SuperTabMessage {+ SuperTabMessage.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ conversationId = _text(row, 'conversationId'),+ text = _text(row, 'text'),+ replyTo = row['replyTo'] as String?,+ thread = row['thread'] as String?,+ alsoInChat = row['alsoInChat'] == true,+ sequence = (row['sequence'] as num).toInt(),+ author = Map.unmodifiable(superTabMap(row['author'])),+ source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),+ createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),+ attachments = _attachments(row['attachments']),+ reactions = List.unmodifiable(+ SuperTabReactionCount.listFromJson(row['reactions']),+ ),+ mentions = List.unmodifiable(+ (row['mentions'] as List?)?.whereType<String>() ?? const <String>[],+ ),+ deliveries = _list(+ row['deliveries'] ?? const [],+ (d) => Map<String, dynamic>.unmodifiable(d),+ );+ final String id, conversationId, text;+ final String? replyTo;++ /// The root of this message's thread: its own id for a top-level message,+ /// null for one written before threads (its replies stay inline quotes).+ final String? thread;++ /// A thread reply also shown in the conversation's main stream.+ final bool alsoInChat;+ bool get threadReply => thread != null && thread != id;++ /// Whether the main stream lists it: a thread reply only when also sent.+ /// The phone, with no thread view yet, shows every reply in the chat.+ bool get inMainStream => !threadReply || alsoInChat;+ final int sequence;+ final Map<String, dynamic> author;+ final Map<String, dynamic> source;+ final DateTime? createdAt;+ final List<SuperTabAttachment> attachments;+ final List<SuperTabReactionCount> reactions;++ /// The people a Lead tagged in this message, by person id.+ final List<String> mentions;+ final List<Map<String, dynamic>> deliveries;+ // Preserve the recorded identity for history and for removed agents. Views+ // with a current roster resolve the visible name through Snapshot.authorName.+ String get authorName =>+ (fromAgent ? author['displayName'] as String? : null) ??+ author['name'] as String? ??+ 'Unknown';+ String get authorId => author['id'] as String? ?? '';+ bool get fromAgent => author['kind'] == 'agent';+ bool get fromTerminal => source['kind'] == 'native';+ SuperTabRoute? get route => SuperTabRoute.fromSource(source);+ bool get routeOverride => source['kind'] == 'route-override';++ /// The person a Buddy's proposal speaks for, from the tag the server writes+ /// on it; null for every other message, whatever its text says.+ String? get proposalOwnerId =>+ source['kind'] == 'buddy-proposal' ? source['personId'] as String? : null;++ /// A note the backend writes about a terminal: a Lead's typing, or an alert.+ bool get terminalEvent =>+ source['kind'] == 'terminal-input' || source['kind'] == 'terminal-alert';+ String? get terminalNote {+ if (!fromTerminal) return null;+ final phase = source['phase'];+ if (phase == 'gap') return 'Terminal recording interrupted';+ final operator =+ superTabMap(source['operator'] ?? const {})['name'] as String?;+ return phase == 'prompt' && operator != null+ ? 'Terminal input · session opened by $operator'+ : 'Terminal answer';+ }++ SuperTabDelivery? get receiptDelivery {+ final rows = deliveries.map(SuperTabDelivery.fromJson).toList();+ rows.sort((a, b) => a.receiptOrder.compareTo(b.receiptOrder));+ return rows.firstOrNull;+ }+}++/// The `remote` a daemon reports for a project: `host/owner/repo`, already+/// without credentials or transport (the CLI's `canonicalRepository`). A port+/// there may be SSH's, so only a plain host is read as an HTTPS address.+final _canonicalRemote = RegExp(+ r'^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}/\S+$',+ caseSensitive: false,+);++/// A remote may contain a developer's embedded credential. Never share it.+/// Contributed machines clone this address, so a daemon's canonical remote+/// becomes the HTTPS URL that Harness's GitHub project source also clones.+String? superTabRepositoryUrl(String? remote) {+ if (remote == null || remote.isEmpty) return null;+ if (remote.startsWith('git@') && !remote.contains('://')) return remote;+ final address = _canonicalRemote.hasMatch(remote)+ ? 'https://$remote'+ : remote;+ final uri = Uri.tryParse(address);+ if (uri == null ||+ uri.host.isEmpty ||+ !['https', 'http', 'ssh', 'git'].contains(uri.scheme)) {+ return null;+ }+ if (uri.userInfo.isNotEmpty &&+ !(uri.scheme == 'ssh' && uri.userInfo == 'git')) {+ return null;+ }+ return address;+}diff --git a/mobile/lib/swarm/parts.dart b/mobile/lib/swarm/parts.dartnew file mode 100644index 000000000..ccfc45143--- /dev/null+++ b/mobile/lib/swarm/parts.dart@@ -0,0 +1,418 @@+import 'package:collection/collection.dart' show DeepCollectionEquality;++import 'model.dart';++/// The response shape a Swarm read answers in (docs/design/2026-10-26-swarm-state-parts.md, section 4), mirrored by+/// hand from backend `superTabs/read/contract.ts` (final at cd004bf5c). A first load of any other format is from a+/// backend this build cannot read.+const superTabReadFormat = 2;++/// The part lists a first load and a change read carry, by their names there. The head is a single part.+const _lists = [+ 'members',+ 'agents',+ 'groups',+ 'machines',+ 'starts',+ 'progress',+];++/// What one change read or dormant page did to the store.+class SuperTabPartsChange {+ const SuperTabPartsChange({+ required this.changed,+ this.removedGroups = const {},+ this.dormantGroups = const {},+ this.readMarksOnly = false,+ });++ /// Some part or a derived value is new: what the screens draw may differ.+ final bool changed;++ /// Groups whose part was deleted: nothing of them stays on this device.+ final Set<String> removedGroups;++ /// Groups that left the active set: they stay readable on demand.+ final Set<String> dormantGroups;++ /// Only the reader's read marks moved: the page around the view, not what a saved view holds.+ final bool readMarksOnly;+}++/// The parts of one Swarm as this reader last saw them (section 5.1): every part by kind and key at the newest+/// version read, the values worked out at read time (`derived`), and where the next change read starts. The screens+/// keep reading the old whole-Swarm shape, which [state] builds from the parts.+class SuperTabParts {+ SuperTabParts._(+ this._head,+ this._derived, {+ required this.cursor,+ required this.epoch,+ required this.lastChangedAt,+ required this.githubApp,+ });++ /// A first load (section 4.3). Throws a [FormatException] for a response of another format.+ factory SuperTabParts.firstLoad(Map<String, dynamic> answer) {+ if (answer['format'] != superTabReadFormat) {+ throw const FormatException('Update Harness to open this Swarm.');+ }+ // Read marks are held apart from the other derived values (_readMarks).+ final derived = Map.of(superTabMap(answer['derived'] ?? const {}));+ final marks = derived.remove('readMarks');+ final parts = SuperTabParts._(+ _envelope(answer['head'], live: true),+ derived,+ cursor: _cursor(answer),+ epoch: _int(answer['epoch']),+ // Null for a Swarm with no part changed yet (contract.ts `ReadMeta`).+ lastChangedAt: _int(answer['lastChangedAt'] ?? 0),+ githubApp: answer['githubApp'] == true,+ );+ parts._seen['head'] = _int(parts._head['version']);+ for (final kind in _lists) {+ final held = parts._live[kind] = <String, Map<String, dynamic>>{};+ for (final raw in answer[kind] as List? ?? const []) {+ final part = _envelope(raw, live: true);+ held[part['key'] as String] = part;+ parts._seen['$kind:${part['key']}'] = _int(part['version']);+ }+ }+ parts._takeReadMarks(marks);+ return parts;+ }++ /// What [toJson] kept, or a [FormatException] for anything else.+ factory SuperTabParts.fromJson(Map<String, dynamic> json) {+ final parts = SuperTabParts.firstLoad(superTabMap(json['load']));+ for (final raw in json['dormant'] as List? ?? const []) {+ final part = _envelope(raw, live: true);+ parts._dormant[part['key'] as String] = part;+ }+ parts._stale.addAll(+ (json['stale'] as List? ?? const []).whereType<String>(),+ );+ final seen = json['seen'];+ if (seen is Map) {+ for (final entry in seen.entries) {+ if (entry.key is String && entry.value is num) {+ parts._seen[entry.key as String] = (entry.value as num).toInt();+ }+ }+ }+ parts._takeReadMarks(json['readMarks']);+ return parts;+ }++ /// Where the next change read starts: opaque, the server's (section 4.2).+ String cursor;++ /// The visibility epoch of the last read. The server answers a change read with a reload when it moves.+ int epoch;++ /// The newest change of any part, in epoch milliseconds (spec ruling 8): what tells a list or a cache that this+ /// Swarm changed. 0 before any part changed.+ int lastChangedAt;++ /// Whether the backend has the GitHub app, as the first load says.+ final bool githubApp;++ Map<String, dynamic> _head;+ Map<String, dynamic> _derived;+ final _live = <String, Map<String, Map<String, dynamic>>>{};++ /// Groups out of the active set whose data this reader has: read on demand, or held when they went dormant.+ final _dormant = <String, Map<String, dynamic>>{};++ /// The newest version seen of every part, deleted and dormant ones included: an older copy the overlap sends+ /// again never replaces it or brings it back (section 4.4).+ final _seen = <String, int>{};++ /// The reader's own read marks by conversation (backend readMarks.ts), the highest each read sent: a first load+ /// sends them all, a change read only those moved since its cursor.+ final _readMarks = <String, int>{};++ /// Keeps the higher of each mark in [marks] and the one held; whether any moved.+ bool _takeReadMarks(Object? marks) {+ var moved = false;+ if (marks is! Map) return moved;+ for (final MapEntry(:key, :value) in marks.entries) {+ if (key is! String || value is! num) continue;+ if ((_readMarks[key] ?? 0) >= value) continue;+ _readMarks[key] = value.toInt();+ moved = true;+ }+ return moved;+ }++ /// Dormant groups held with their data from before a stub closed them: a read by id at the stub's version is+ /// their current data.+ final _stale = <String>{};++ /// The values worked out at read time, as the last read sent them.+ Map<String, dynamic> get derived => _derived;++ /// Whether this reader holds group [groupId], active or dormant.+ bool holdsGroup(String groupId) =>+ _live['groups']?.containsKey(groupId) == true ||+ _dormant.containsKey(groupId);++ /// Dormant groups held with data from before a stub closed them, to read again by id.+ List<String> get staleGroups => _stale.toList();++ /// Keeps [groupId]'s held data as it is: it cannot be read again.+ void forgetStale(String groupId) => _stale.remove(groupId);++ /// Whether [groupId] is a dormant group this reader holds.+ bool isDormant(String groupId) => _dormant.containsKey(groupId);++ /// Merges one change read (section 4.4): a higher version wins, a tombstone removes the part, a dormant stub moves+ /// the group out of the active ones, `derived` is replaced, and the cursor moves. A reload answer is the caller's.+ SuperTabPartsChange apply(Map<String, dynamic> changes) {+ var changed = false;+ final removed = <String>{}, dormant = <String>{};+ if (changes['head'] != null) {+ final head = _envelope(changes['head'], live: true);+ if (_newer('head', head)) {+ _head = head;+ changed = true;+ }+ }+ for (final kind in _lists) {+ final held = _live.putIfAbsent(kind, () => {});+ for (final raw in changes[kind] as List? ?? const []) {+ final part = _envelope(raw, live: false);+ final key = part['key'] as String;+ if (!_newer('$kind:$key', part)) continue;+ changed = true;+ if (part['deleted'] == true) {+ held.remove(key);+ if (kind == 'groups') {+ _dormant.remove(key);+ _stale.remove(key);+ _readMarks.remove(key);+ removed.add(key);+ }+ } else if (kind == 'groups' && part['dormant'] == true) {+ final last = held.remove(key) ?? _dormant[key];+ if (last != null) {+ _stale.add(key);+ _dormant[key] = {+ ...last,+ 'version': part['version'],+ 'changedAt': part['changedAt'],+ 'data': {...superTabMap(last['data']), 'dormant': true},+ };+ }+ dormant.add(key);+ } else {+ if (part['data'] == null) {+ throw const FormatException('A Swarm part arrived without data.');+ }+ held[key] = part;+ if (kind == 'groups') {+ _dormant.remove(key);+ _stale.remove(key);+ }+ }+ }+ }+ final derived = Map.of(superTabMap(changes['derived'] ?? const {}));+ final marksMoved = _takeReadMarks(derived.remove('readMarks'));+ if (!const DeepCollectionEquality().equals(derived, _derived)) {+ _derived = derived;+ changed = true;+ }+ cursor = _cursor(changes);+ epoch = _int(changes['epoch'] ?? epoch);+ lastChangedAt = _int(changes['lastChangedAt'] ?? lastChangedAt);+ return SuperTabPartsChange(+ changed: changed || marksMoved,+ removedGroups: removed,+ dormantGroups: dormant,+ readMarksOnly: marksMoved && !changed,+ );+ }++ /// Takes dormant groups read on demand (section 4.5): a page of the dormant list, or one group by id. Each is kept+ /// unless this reader already holds a newer version of it; one that is active here at a lower version moves out.+ SuperTabPartsChange addDormant(List groups) {+ var changed = false;+ final active = _live.putIfAbsent('groups', () => {});+ for (final raw in groups) {+ final part = _envelope(raw, live: true);+ final key = part['key'] as String;+ final current =+ _stale.contains(key) && _int(part['version']) == _seen['groups:$key'];+ if (!current && !_newer('groups:$key', part)) continue;+ _stale.remove(key);+ changed = true;+ if (superTabMap(part['data'])['dormant'] == true) {+ active.remove(key);+ _dormant[key] = part;+ } else {+ active[key] = part;+ _dormant.remove(key);+ }+ }+ return SuperTabPartsChange(changed: changed);+ }++ /// The old whole-Swarm shape (section 5.1, "Reassemble a state"), from the head, the parts and `derived`. Active+ /// groups come first in the order they were read, then the dormant groups held.+ Map<String, dynamic> get state {+ final agentsDerived = _derivedMap('agents');+ final machinesDerived = _derivedMap('machines');+ final avatars = _derivedMap('avatars');+ final state = <String, dynamic>{+ ...superTabMap(_head['data']),+ 'format': superTabReadFormat,+ 'people': [+ for (final p in _data('members'))+ _avatarLink(p, avatars['person:${p['id']}']),+ ],+ 'agents': [+ for (final agent in _data('agents'))+ _avatarLink(+ _overlay(+ agent,+ agentsDerived[agent['id']],+ keepNull: 'workDecision',+ ),+ avatars['agent:${agent['id']}'],+ ),+ ],+ 'conversations': [+ ..._data('groups'),+ for (final part in _dormant.values) superTabMap(part['data']),+ ],+ 'machines': [+ for (final machine in _data('machines'))+ _overlay(machine, machinesDerived[machine['machineId']]),+ ],+ 'starts': [for (final start in _data('starts')) start],+ 'githubApp': githubApp,+ };+ if (_derived['otherProjectsWork'] case final List work) {+ state['otherProjectsWork'] = work;+ }+ if (_derived['mentionsWaiting'] case final num waiting) {+ state['mentionsWaiting'] = waiting.toInt();+ }+ if (_derived['mentionsDigest'] case final String digest) {+ state['mentionsDigest'] = digest;+ }+ if (_derived['decisionsWaiting'] case final num waiting) {+ state['decisionsWaiting'] = waiting.toInt();+ }+ if (_derived['decisionsDigest'] case final String digest) {+ state['decisionsDigest'] = digest;+ }+ if (_readMarks.isNotEmpty) state['readMarks'] = Map.of(_readMarks);+ return state;+ }++ /// What to keep on this device to read the same store back ([SuperTabParts.fromJson]).+ Map<String, dynamic> toJson() => {+ 'load': {+ 'format': superTabReadFormat,+ 'cursor': cursor,+ 'epoch': epoch,+ 'lastChangedAt': lastChangedAt,+ 'githubApp': githubApp,+ 'head': _head,+ for (final kind in _lists)+ kind: (_live[kind] ?? const {}).values.toList(),+ 'derived': _derived,+ },+ 'dormant': _dormant.values.toList(),+ 'seen': Map<String, int>.of(_seen),+ 'stale': _stale.toList(),+ 'readMarks': Map<String, int>.of(_readMarks),+ };++ /// [json] (from [toJson]) without what the screens never draw: agent starts carry their tasks, and project+ /// progress is never shown. A store read back from it gets them again as they change.+ static Map<String, dynamic> drawnOnly(Map<String, dynamic> json) {+ const undrawn = {'starts', 'progress'};+ final seen = json['seen'];+ return {+ ...json,+ 'load': {+ ...superTabMap(json['load']),+ for (final kind in undrawn) kind: const <dynamic>[],+ },+ 'seen': {+ if (seen is Map)+ for (final entry in seen.entries)+ if (!undrawn.contains((entry.key as String).split(':').first))+ entry.key: entry.value,+ },+ };+ }++ Iterable<Map<String, dynamic>> _data(String kind) =>+ (_live[kind] ?? const {}).values.map((part) => superTabMap(part['data']));++ Map<String, dynamic> _derivedMap(String name) =>+ _derived[name] is Map ? superTabMap(_derived[name]) : const {};++ /// [record] with its uploaded avatar's signed link from this read (backend avatarLinks.ts), which never stays in a part.+ static Map<String, dynamic> _avatarLink(+ Map<String, dynamic> record,+ Object? link,+ ) {+ final avatar = record['avatar'];+ final uploaded =+ link is String && avatar is Map && avatar['kind'] == 'upload';+ if (!uploaded) return record;+ return {+ ...record,+ 'avatar': {...avatar, 'url': link},+ };+ }++ /// [record] with the derived values over it. A null [keepNull] value means the stored one stands.+ static Map<String, dynamic> _overlay(+ Map<String, dynamic> record,+ Object? derived, {+ String? keepNull,+ }) {+ if (derived is! Map) return record;+ final next = {...record};+ for (final entry in derived.entries) {+ if (entry.key == keepNull && entry.value == null) continue;+ next[entry.key as String] = entry.value;+ }+ return next;+ }++ /// Whether [part] is newer than what was seen of [id], recording it when it is.+ bool _newer(String id, Map<String, dynamic> part) {+ final version = _int(part['version']);+ final seen = _seen[id];+ if (seen != null && version <= seen) return false;+ _seen[id] = version;+ return true;+ }++ static Map<String, dynamic> _envelope(Object? raw, {required bool live}) {+ final part = superTabMap(raw);+ if (part['key'] is! String || part['version'] is! num) {+ throw const FormatException('Invalid Swarm part.');+ }+ if (live && part['data'] is! Map) {+ throw const FormatException('A Swarm part arrived without data.');+ }+ return part;+ }++ static String _cursor(Map<String, dynamic> answer) =>+ answer['cursor'] is String+ ? answer['cursor'] as String+ : throw const FormatException('Missing Swarm cursor.');++ static int _int(Object? value) => value is num+ ? value.toInt()+ : throw const FormatException('Invalid Swarm read.');+}diff --git a/mobile/lib/swarm/profile_model.dart b/mobile/lib/swarm/profile_model.dartnew file mode 100644index 000000000..0443451e2--- /dev/null+++ b/mobile/lib/swarm/profile_model.dart@@ -0,0 +1,152 @@+/// Avatars, status lines and reactions as the backend sends them+/// (backend superTabs/profile.ts and reactions.ts). Only Swarm members read+/// them; a value this build does not know reads as absent.+library;++/// What a member or agent shows instead of the default.+sealed class SuperTabAvatarPicture {+ const SuperTabAvatarPicture();++ static SuperTabAvatarPicture? fromJson(Object? value) => switch (value) {+ {'kind': 'upload', 'url': final String url} => SuperTabUploadedAvatar.of(+ url,+ ),+ {'kind': 'preset', 'key': final String key}+ when superTabAvatarPresets.containsKey(key) =>+ SuperTabPresetAvatar(key),+ _ => null,+ };+}++/// Where the backend's private avatar bucket serves its signed links+/// (backend superTabs/avatarLinks.ts): Cloud Storage's own host.+const kSuperTabAvatarHost = String.fromEnvironment(+ 'SUPER_TAB_AVATARS_HOST',+ defaultValue: 'storage.googleapis.com',+);++/// Where the chat files' CDN serves them, the same setting as the chat files'+/// own host. A server without an avatar bucket keeps pictures there too, in+/// [kSuperTabAvatarFolder].+const kSuperTabAvatarCdnHost = String.fromEnvironment(+ 'SUPER_TAB_ATTACHMENTS_HOST',+ defaultValue: 'cdn.harness.autonomous.ai',+);++/// The folder a server without an avatar bucket keeps pictures in, among the+/// chat files (backend avatarLinks.ts): it links nothing outside it.+const kSuperTabAvatarFolder = 'avatars';++/// A picture someone uploaded, through the link a member read carries: https,+/// and only on the avatar host (a private bucket's signed link) or in the+/// avatars folder on the chat files' CDN (a server without an avatar bucket,+/// Ken 2026-10-28). Never a chat file, and never an outside address.+class SuperTabUploadedAvatar extends SuperTabAvatarPicture {+ const SuperTabUploadedAvatar._(this.url);+ final Uri url;++ static SuperTabUploadedAvatar? of(String value) {+ final url = Uri.tryParse(value);+ if (url == null || url.scheme != 'https') return null;+ if (url.host == kSuperTabAvatarHost) return SuperTabUploadedAvatar._(url);+ final path = url.pathSegments;+ final inFolder =+ path.length > 1 &&+ path.first == kSuperTabAvatarFolder &&+ path+ .skip(1)+ .every((part) => part.isNotEmpty && part != '..' && part != '.');+ return url.host == kSuperTabAvatarCdnHost && inFolder+ ? SuperTabUploadedAvatar._(url)+ : null;+ }+}++class SuperTabPresetAvatar extends SuperTabAvatarPicture {+ const SuperTabPresetAvatar(this.key);+ final String key;+ String get glyph => superTabAvatarPresets[key]!;+}++/// The pictures a person may pick (backend AVATAR_PRESETS), in offer order.+const superTabAvatarPresets = {+ 'fox': '🦊',+ 'owl': '🦉',+ 'cat': '🐱',+ 'panda': '🐼',+ 'octopus': '🐙',+ 'cactus': '🌵',+ 'rocket': '🚀',+ 'sun': '🌞',+};++/// A person's short status. Shown until [until] passes.+class SuperTabPersonStatus {+ const SuperTabPersonStatus({required this.text, this.emoji, this.until});+ final String text;+ final String? emoji;+ final DateTime? until;++ static SuperTabPersonStatus? fromJson(Object? value) => switch (value) {+ {'text': final String text} when text.trim().isNotEmpty =>+ SuperTabPersonStatus(+ text: text,+ emoji: value['emoji'] is String ? value['emoji'] as String : null,+ until: DateTime.tryParse(value['until'] as String? ?? ''),+ ),+ _ => null,+ };++ String get label => emoji == null ? text : '$emoji $text';+ bool shownAt(DateTime now) => until == null || now.isBefore(until!);+}++/// The status emoji a person may pick, with the words each offers+/// (backend STATUS_EMOJI).+const superTabStatusPresets = [+ ('🎯', 'Focusing'),+ ('☕', 'Coffee break'),+ ('🍽️', 'At lunch'),+ ('🌴', 'Out of office'),+ ('🚶', 'Away'),+ ('🤒', 'Out sick'),+];++/// The reactions a message can carry, in the order counts show.+enum SuperTabReactionEmoji {+ thumbsUp('thumbs_up', '👍'),+ tada('tada', '🎉'),+ heart('heart', '❤️'),+ laugh('laugh', '😄'),+ eyes('eyes', '👀'),+ rocket('rocket', '🚀');++ const SuperTabReactionEmoji(this.key, this.glyph);+ final String key, glyph;++ static SuperTabReactionEmoji? of(Object? key) =>+ values.where((e) => e.key == key).firstOrNull;+}++/// One emoji's count on one message, and who gave it.+class SuperTabReactionCount {+ const SuperTabReactionCount(this.emoji, this.by);+ final SuperTabReactionEmoji emoji;+ final List<({String kind, String id})> by;+ int get count => by.length;++ bool includes(String kind, String id) =>+ by.any((who) => who.kind == kind && who.id == id);++ static List<SuperTabReactionCount> listFromJson(Object? value) => [+ if (value is List)+ for (final row in value)+ if (row case {'emoji': final Object key}+ when SuperTabReactionEmoji.of(key) != null)+ SuperTabReactionCount(SuperTabReactionEmoji.of(key)!, [+ for (final who in row['by'] as List? ?? const [])+ if (who case {'kind': final String kind, 'id': final String id})+ (kind: kind, id: id),+ ]),+ ];+}diff --git a/mobile/lib/swarm/swarm_asks.dart b/mobile/lib/swarm/swarm_asks.dartnew file mode 100644index 000000000..5244992ff--- /dev/null+++ b/mobile/lib/swarm/swarm_asks.dart@@ -0,0 +1,429 @@+import 'dart:async';++import 'package:collection/collection.dart' show DeepCollectionEquality;+import 'package:flutter/foundation.dart';++import 'model.dart';+import 'swarm_reader.dart';+import 'swarm_request.dart';++/// Something the Swarm asks of the reader, wherever it came from: a decision to+/// answer or a Lead's tag.+abstract interface class SwarmAskItem {+ String get id;+ String get projectName;+ String get conversationId;+ String get conversationTitle;+ DateTime? get createdAt;+}++/// One question an agent asked the reader: options, the one it recommends and+/// what an answer unblocks (backend superTabs/decisions.ts). The desktop's+/// `SuperTabDecision` (`desktop/lib/super_tabs/decisions.dart`), field for field.+class SuperTabDecision implements SwarmAskItem {+ SuperTabDecision.fromJson(Map<String, dynamic> row)+ : id = row['id'] as String,+ batchId = row['batchId'] as String? ?? row['id'] as String,+ projectId = row['projectId'] as String? ?? '',+ projectName = row['projectName'] as String? ?? '',+ conversationId = row['conversationId'] as String,+ conversationTitle = row['conversationTitle'] as String? ?? '',+ askerName = row['askerName'] as String? ?? 'Agent',+ question = row['question'] as String? ?? '',+ options = List.unmodifiable([+ for (final option in row['options'] as List? ?? const []) '$option',+ ]),+ recommended = (row['recommended'] as num?)?.toInt() ?? 0,+ unblocks = row['unblocks'] as String? ?? '',+ choice = (row['choice'] as num?)?.toInt(),+ note = row['note'] as String?,+ createdAt = DateTime.tryParse(row['createdAt'] as String? ?? '');+ @override+ final String id, projectName, conversationId, conversationTitle;+ final String batchId, projectId, askerName, question, unblocks;+ final List<String> options;+ final int recommended;++ /// The option the reader chose; null while it is open.+ final int? choice;+ final String? note;+ @override+ final DateTime? createdAt;+}++/// A Lead's tag of the reader in one message (spec 2026-10-24-lead-mentions.md).+/// The desktop's `SuperTabMention` (`desktop/lib/super_tabs/notifications.dart`).+class SuperTabMention implements SwarmAskItem {+ SuperTabMention.fromJson(Map<String, dynamic> row)+ : id = row['id'] as String,+ projectId = row['projectId'] as String? ?? '',+ projectName = row['projectName'] as String? ?? '',+ conversationId = row['conversationId'] as String,+ conversationTitle = row['conversationTitle'] as String? ?? '',+ messageId = row['messageId'] as String,+ leadName = row['leadName'] as String? ?? 'Lead',+ text = row['text'] as String? ?? '',+ createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),+ resolvedBy = row['resolvedBy'] as String?;+ @override+ final String id, projectName, conversationId, conversationTitle;+ final String projectId, messageId, leadName, text;+ @override+ final DateTime? createdAt;++ /// `reply` or `done` once it moved to Earlier; null while it waits.+ final String? resolvedBy;+}++/// The reader's open decisions and waiting tags in one Swarm, read from the+/// backend whenever the Swarm's counts move, or the Swarm changes while one+/// waits — the desktop's `SuperTabDecisions` and `SuperTabMentions` in one,+/// open and waiting only: the phone shows what still needs the person.+class SwarmAsks extends ChangeNotifier {+ SwarmAsks(this.reader) {+ reader.addListener(_changed);+ reader.reads.addListener(_swarmRead);+ reader.firstLoads.addListener(_loadAsked);+ _changed();+ }++ final SwarmReader reader;+ List<SuperTabDecision> decisions = const [];+ List<SuperTabMention> mentions = const [];+ String? error;++ /// What waits for the person here is not read yet since the Swarm was last+ /// read from nothing: Home shows its skeleton meanwhile, never a false+ /// "Nothing needs you". False once that read answers, either way; when the+ /// Swarm's counts say nothing waits; when the Swarm itself could not be+ /// read; and when the reader may no longer read it.+ bool get loading =>+ !reader.accessRevoked &&+ !reader.updateRequired &&+ !(reader.snapshot == null && reader.error != null) &&+ _settled != reader.generation;++ /// The [SwarmReader.generation] whose asks were read, or need none.+ int _settled = -1;++ /// Decisions being answered: their buttons wait for the backend.+ final Set<String> answering = {};++ /// Answers sent whose reply never came, by decision: sent again under the+ /// same receipt and choice until one is confirmed, so the backend applies+ /// the answer once and no other is offered meanwhile.+ final _unconfirmed = <String, ({String operationId, int choice})>{};++ /// Tags being marked done, tags whose Done failed (with what to say on+ /// them), and tags confirmed done that a list read before then may still+ /// hold: a Done shows the moment it is tapped, and the tag goes the moment+ /// it is confirmed, not at the next read — on the owner's iPhone+ /// (2026-10-27) it took 10 seconds, with no sign the tap counted.+ final _finishing = <String>{}, _done = <String>{};+ final _notDone = <String, String>{};++ /// [mention] is being marked done.+ bool finishing(SuperTabMention mention) => _finishing.contains(mention.id);++ /// What to say on [mention] after its Done failed; null otherwise.+ String? notDone(SuperTabMention mention) => _notDone[mention.id];++ /// The option sent for [decision] and not confirmed: [answer] sends it+ /// again.+ int? unconfirmed(SuperTabDecision decision) =>+ _unconfirmed[decision.id]?.choice;++ /// An ask that arrived after the first read: what a phone notice tells.+ void Function(SwarmAskItem item)? onArrived;++ ({int decisions, int mentions})? _counts;++ /// The rows [decisions] and [mentions] were made from: a read answering the+ /// same keeps them as they are, and tells nobody.+ List<Map<String, dynamic>> _openRows = const [], _waitingRows = const [];+ static const _same = DeepCollectionEquality();+ int _lastChangedAt = -1, _generation = -1;++ /// The lists asked for alongside a first load ([SwarmReader.firstLoads]),+ /// so they need not wait behind it: used for the Swarm that load reads, and+ /// for no other.+ ({int load, Future<List<List<Map<String, dynamic>>>> rows})? _along;++ // Null until the first read: asks waiting then are not news.+ Set<String>? _seen;+ Future<void>? _loading;+ bool _dirty = false, _failed = false, _disposed = false;++ String get _path => '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}';++ /// An ask can arrive while another is answered, leaving a count as it was,+ /// so any change of the Swarm is read while one waits. With none waiting+ /// and none just answered, nothing is. A Swarm read again from nothing is+ /// read again here too: the reader's access may have moved; and one the+ /// reader may no longer read keeps nothing here.+ void _changed() {+ final snapshot = reader.snapshot;+ if (snapshot == null) {+ if (reader.accessRevoked) _clear();+ return;+ }+ final counts = (+ decisions: snapshot.decisionsWaiting,+ mentions: snapshot.mentionsWaiting,+ );+ final reloaded = reader.generation != _generation;+ final along = _along;+ if (reloaded) _along = null;+ final moved = counts != _counts || reloaded;+ if (!moved && reader.lastChangedAt == _lastChangedAt) return;+ _lastChangedAt = reader.lastChangedAt;+ _generation = reader.generation;+ _counts = counts;+ // What was read before may be of chats the reader can no longer see:+ // none of it stays while the new read runs, nor if that read fails.+ if (reloaded && (decisions.isNotEmpty || mentions.isNotEmpty)) {+ _empty();+ notifyListeners();+ }+ if (counts.decisions == 0 && counts.mentions == 0) {+ _seen ??= {};+ if (!moved || (decisions.isEmpty && mentions.isEmpty)) return _settle();+ }+ final rows = reloaded && along?.load == reader.heldLoad ? along : null;+ unawaited(load(along: rows?.rows));+ }++ /// A first load is asked for: the lists are asked with it.+ void _loadAsked() {+ if (_disposed || reader.accessRevoked) return;+ final rows = _fetch()..ignore();+ _along = (load: reader.firstLoads.value, rows: rows);+ }++ /// Nothing to read for the Swarm as it is: [loading] ends.+ void _settle() {+ if (_settled == reader.generation) return;+ _settled = reader.generation;+ notifyListeners();+ }++ /// Each read of the Swarm, changed or not: a move of its last-change time+ /// alone tells only here ([SwarmReader.lastChangedAt]), and a read that+ /// failed is tried again, as the Swarm staying as it was tells nothing.+ void _swarmRead() {+ _changed();+ if (_failed && _loading == null) unawaited(load());+ }++ void _clear() {+ final held = decisions.isNotEmpty || mentions.isNotEmpty || error != null;+ _empty();+ error = null;+ _unconfirmed.clear();+ _done.clear();+ _notDone.clear();+ _counts = null;+ _failed = false;+ if (held) notifyListeners();+ }++ void _empty() {+ decisions = const [];+ mentions = const [];+ _openRows = _waitingRows = const [];+ }++ /// Joins a read under way, and has it read once more when asked again.+ /// [along] is what was read alongside the Swarm's first load, used in+ /// place of a first read of the lists.+ Future<void> load({Future<List<List<Map<String, dynamic>>>>? along}) {+ if (_disposed || reader.accessRevoked) return Future.value();+ if (_loading case final running?) {+ _dirty = true;+ return running;+ }+ return _loading = () async {+ var rows = along;+ do {+ _dirty = false;+ if (!await _read(rows)) _dirty = true;+ rows = null;+ } while (_dirty && !_disposed);+ }().whenComplete(() => _loading = null);+ }++ Future<List<List<Map<String, dynamic>>>> _fetch() => Future.wait([+ _rows('decisions?state=open', 'decisions'),+ _rows('mentions?state=waiting', 'mentions'),+ ]);++ Future<List<Map<String, dynamic>>> _rows(String path, String key) async {+ final Object? answer;+ try {+ answer = await reader.request('GET', '$_path/$path');+ } on SuperTabFailure catch (failure) {+ // A backend from before decisions or tags has no list: nothing to show.+ if (failure.statusCode == 404) return const [];+ rethrow;+ }+ return [+ for (final row in superTabMap(answer)[key] as List) superTabMap(row),+ ];+ }++ /// False when lists read [along] a first load disagree with its counts:+ /// something moved between the two answers, so they are read again.+ Future<bool> _read(Future<List<List<Map<String, dynamic>>>>? along) async {+ // An answer from before the Swarm was read again from nothing, or taken+ // away, may hold asks the reader can no longer see: it is not applied.+ final generation = reader.generation;+ final counts = _counts;+ try {+ final [openRows, waitingRows] = await (along ?? _fetch());+ if (_disposed || reader.generation != generation) return true;+ if (along != null &&+ (openRows.length != counts?.decisions ||+ waitingRows.length != counts?.mentions)) {+ return false;+ }+ final waitingIds = {for (final row in waitingRows) row['id']};+ // Done here and no longer waiting there: the backend caught up.+ _done.removeWhere((id) => !waitingIds.contains(id));+ final notDone = _notDone.length;+ _notDone.removeWhere((id, _) => !waitingIds.contains(id));+ final waiting = [+ for (final row in waitingRows)+ if (!_done.contains(row['id'])) row,+ ];+ var changed =+ error != null || notDone != _notDone.length || _settled != generation;+ _settled = generation;+ if (!_same.equals(openRows, _openRows)) {+ _openRows = openRows;+ decisions = List.unmodifiable(openRows.map(SuperTabDecision.fromJson));+ changed = true;+ }+ if (!_same.equals(waiting, _waitingRows)) {+ _waitingRows = waiting;+ mentions = List.unmodifiable(waiting.map(SuperTabMention.fromJson));+ changed = true;+ }+ error = null;+ _failed = false;+ // No longer open: answered, by this answer or another.+ _unconfirmed.removeWhere((id, _) => !decisions.any((d) => d.id == id));+ final seen = _seen;+ final now = <SwarmAskItem>[...decisions, ...mentions];+ _seen = {...?seen, for (final ask in now) ask.id};+ if (seen != null) {+ for (final ask in now) {+ if (!seen.contains(ask.id)) onArrived?.call(ask);+ }+ }+ if (changed) notifyListeners();+ } catch (_) {+ if (_disposed || reader.generation != generation) return true;+ const failed = 'Could not load what is waiting for you. Try again.';+ final told = error == failed && _failed && _settled == generation;+ error = failed;+ _failed = true;+ _settled = generation;+ if (!told) notifyListeners();+ }+ return true;+ }++ Future<void> _command(Map<String, dynamic> command, {String? operationId}) =>+ reader.request(+ 'POST',+ '$_path/commands',+ body: {+ 'operationId': operationId ?? superTabOperationId(),+ 'command': command,+ },+ );++ /// The reader's one-tap answer, sent once. Any reader may answer what was+ /// asked of them, viewers included. An answer not confirmed is sent again+ /// as it was, whatever [choice] says; a decision the backend has answered+ /// already (by this answer, its reply lost, or another device) is read+ /// back.+ Future<bool> answer(SuperTabDecision decision, int choice) async {+ if (_disposed || !answering.add(decision.id)) return false;+ final sent = _unconfirmed[decision.id] ??= (+ operationId: superTabOperationId(),+ choice: choice,+ );+ notifyListeners();+ try {+ await _command({+ 'type': 'decision.answer',+ 'decisionId': decision.id,+ 'choice': sent.choice,+ }, operationId: sent.operationId);+ } on SuperTabFailure catch (failure) {+ if (failure.code != 'DECISION_ANSWERED') {+ // A definitive refusal changed nothing: another answer may be sent.+ // A lost reply keeps its receipt, so a retry is the same answer.+ final status = failure.statusCode;+ final refused =+ status >= 400 && status < 500 && status != 408 && status != 429;+ if (refused) _unconfirmed.remove(decision.id);+ error = refused+ ? failure.message+ : 'Could not send your answer. Try again.';+ return false;+ }+ } catch (_) {+ error = 'Could not send your answer. Try again.';+ return false;+ } finally {+ answering.remove(decision.id);+ if (!_disposed) notifyListeners();+ }+ _unconfirmed.remove(decision.id);+ error = null;+ await load();+ unawaited(reader.refresh());+ return true;+ }++ /// The reader is finished with [mention]: [finishing] at once, out of+ /// [mentions] once the backend confirms it. A failure says so on that tag+ /// alone ([notDone]); the tag stays, to be marked again.+ Future<bool> done(SuperTabMention mention) async {+ if (_disposed || !_finishing.add(mention.id)) return false;+ _notDone.remove(mention.id);+ notifyListeners();+ try {+ await _command({'type': 'mention.done', 'mentionId': mention.id});+ } catch (_) {+ if (_disposed) return false;+ _finishing.remove(mention.id);+ _notDone[mention.id] = 'Not marked done. Try again.';+ notifyListeners();+ return false;+ }+ if (_disposed) return false;+ _finishing.remove(mention.id);+ _done.add(mention.id);+ mentions = List.unmodifiable(mentions.where((m) => m.id != mention.id));+ _waitingRows = [+ for (final row in _waitingRows)+ if (row['id'] != mention.id) row,+ ];+ notifyListeners();+ await load();+ unawaited(reader.refresh());+ return true;+ }++ @override+ void dispose() {+ _disposed = true;+ reader.removeListener(_changed);+ reader.reads.removeListener(_swarmRead);+ reader.firstLoads.removeListener(_loadAsked);+ super.dispose();+ }+}diff --git a/mobile/lib/swarm/swarm_attach.dart b/mobile/lib/swarm/swarm_attach.dartnew file mode 100644index 000000000..38a98329f--- /dev/null+++ b/mobile/lib/swarm/swarm_attach.dart@@ -0,0 +1,343 @@+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/shared/theme/app_icon_size.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/shared/widgets/touch_target.dart';++import 'swarm_conversation.dart';+import 'swarm_file_picker.dart';+import 'swarm_message_row.dart'+ show swarmChatCard, swarmChatHair, swarmFileSize;+import 'swarm_outgoing_files.dart';+import 'swarm_style.dart';++/// The composer's + sheet: Photo library, Camera and Files, as Tony approved the mockup+/// (2026-10-28). Null is the person closing it.+Future<SwarmPickSource?> showSwarmAttachSheet(BuildContext context) =>+ showModalBottomSheet<SwarmPickSource>(+ context: context,+ backgroundColor: AppGlass.rowFill,+ shape: AppControl.sheetShape,+ builder: (context) => const _AttachSheet(),+ );++class _AttachSheet extends StatelessWidget {+ const _AttachSheet();++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ Widget row(+ SwarmPickSource source,+ String key,+ IconData icon,+ String title,+ String detail,+ ) => Semantics(+ button: true,+ label: '$title. $detail',+ excludeSemantics: true,+ child: InkWell(+ key: ValueKey(key),+ borderRadius: BorderRadius.circular(AppControl.radius),+ onTap: () => Navigator.of(context).pop(source),+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: minTouchTarget),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.m,+ vertical: AppSpace.s,+ ),+ child: Row(+ children: [+ Icon(+ icon,+ size: AppIconSize.standalone,+ color: AppPalette.textPrimary,+ ),+ const SizedBox(width: AppSpace.l),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ title,+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ Text(+ detail,+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );++ return SafeArea(+ top: false,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.s,+ AppSpace.l,+ AppSpace.l,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // The grabber: a capsule as wide as the two largest steps.+ Center(+ child: Container(+ width: AppSpace.xl + AppSpace.m,+ height: AppSpace.xs,+ margin: const EdgeInsets.only(bottom: AppSpace.s),+ decoration: ShapeDecoration(+ color: AppGlass.hair,+ shape: const StadiumBorder(),+ ),+ ),+ ),+ row(+ SwarmPickSource.library,+ 'swarm-attach-library',+ LucideIcons.image,+ 'Photo library',+ 'Pick several at once',+ ),+ row(+ SwarmPickSource.camera,+ 'swarm-attach-camera',+ LucideIcons.camera,+ 'Camera',+ 'Take a photo',+ ),+ row(+ SwarmPickSource.files,+ 'swarm-attach-files',+ LucideIcons.file,+ 'Files',+ 'PDFs, logs, zips',+ ),+ ],+ ),+ ),+ );+ }+}++/// The phone refused [source], and only its Settings turns it back on: Not now, or Open+/// Settings. True for Open Settings.+Future<bool> showSwarmAccessOff(+ BuildContext context,+ SwarmPickSource source,+) async {+ final camera = source == SwarmPickSource.camera;+ final open = await showDialog<bool>(+ context: context,+ // The theme's dialog: its fill and Desktop's dialog radius.+ builder: (context) => AlertDialog(+ title: Text(+ camera ? 'Camera access is off' : 'Photos access is off',+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ content: Text(+ camera+ ? 'Allow Harness to use the camera in Settings to take a photo.'+ : 'Allow Harness to use your photos in Settings to attach them.',+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ actions: [+ SwarmButton(+ label: 'Not now',+ style: SwarmButtonStyle.link,+ onPressed: () => Navigator.of(context).pop(false),+ ),+ SwarmButton(+ label: 'Open Settings',+ style: SwarmButtonStyle.fill,+ onPressed: () => Navigator.of(context).pop(true),+ ),+ ],+ ),+ );+ return open ?? false;+}++/// The files going with the next post, one chip each in a row that scrolls sideways: a picture's+/// thumbnail or a file's mark, its name, its size — or, going up, how much has gone — and ✕ to+/// take it off. Nothing while there are none.+class SwarmOutgoingChips extends StatelessWidget {+ const SwarmOutgoingChips({super.key, required this.conversation});++ final SwarmConversation conversation;++ @override+ Widget build(BuildContext context) {+ final files = conversation.files.files;+ if (files.isEmpty) return const SizedBox.shrink();+ return SizedBox(+ height: _chipHeight + AppSpace.s,+ child: ListView.separated(+ key: const ValueKey('swarm-outgoing'),+ scrollDirection: Axis.horizontal,+ padding: const EdgeInsets.only(bottom: AppSpace.s),+ itemCount: files.length,+ separatorBuilder: (_, _) => const SizedBox(width: AppSpace.s),+ itemBuilder: (context, i) => _Chip(+ file: files[i],+ progress: conversation.isUploading(files[i])+ ? conversation.uploadProgress(files[i]) ?? 0+ : null,+ onRemove: () => conversation.files.remove(files[i]),+ ),+ ),+ );+ }+}++/// A chip's thumbnail: the 44-point target less a step, so the chip with its inset is a target and+/// a step tall.+const _thumbnail = minTouchTarget - AppSpace.s;+const _chipHeight = _thumbnail + 2 * AppSpace.s;++class _Chip extends StatelessWidget {+ const _Chip({+ required this.file,+ required this.progress,+ required this.onRemove,+ });++ final SwarmOutgoingFile file;++ /// How much has gone up, from 0 to 1, while it goes up; null otherwise.+ final double? progress;+ final VoidCallback onRemove;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ final picture = swarmMimeForName(file.name).startsWith('image/');+ final mark = Icon(+ picture ? LucideIcons.image : LucideIcons.file,+ size: AppIconSize.besideText,+ color: AppPalette.textSecondary,+ );+ final going = progress;+ return Container(+ key: ValueKey('swarm-outgoing-${file.name}'),+ // A long name gives way first: a chip takes at most most of the row.+ constraints: BoxConstraints(+ maxWidth: MediaQuery.sizeOf(context).width * .6,+ minHeight: _chipHeight,+ ),+ padding: const EdgeInsets.only(left: AppSpace.s),+ decoration: BoxDecoration(+ color: swarmChatCard(tty),+ border: Border.all(color: swarmChatHair(tty)),+ borderRadius: BorderRadius.circular(AppControl.radius),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ ClipRRect(+ borderRadius: BorderRadius.circular(AppCard.insetRadius),+ child: SizedBox.square(+ dimension: _thumbnail,+ child: picture+ ? Image.memory(+ file.bytes,+ fit: BoxFit.cover,+ // Decoded small: a thumbnail, not the photo — three+ // pixels a point, a phone's sharpest.+ cacheWidth: (_thumbnail * 3).round(),+ gaplessPlayback: true,+ errorBuilder: (_, _, _) => Center(child: mark),+ )+ : Center(child: mark),+ ),+ ),+ const SizedBox(width: AppSpace.s),+ Flexible(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ file.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(color: AppPalette.textPrimary),+ ),+ if (going == null)+ Text(+ swarmFileSize(file.bytes.length),+ style: AppType.caption(+ color: AppPalette.textFaint,+ fontFeatures: const [FontFeature.tabularFigures()],+ ),+ )+ else+ Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ SizedBox(+ width: minTouchTarget,+ child: ClipPath(+ clipper: const ShapeBorderClipper(+ shape: StadiumBorder(),+ ),+ child: LinearProgressIndicator(+ value: going,+ minHeight: AppSpace.xs,+ color: AppPalette.accent,+ backgroundColor: swarmChatHair(tty),+ ),+ ),+ ),+ const SizedBox(width: AppSpace.s),+ Text(+ '${(going * 100).round()}%',+ style: AppType.caption(+ color: AppPalette.textFaint,+ fontFeatures: const [FontFeature.tabularFigures()],+ ),+ ),+ ],+ ),+ ],+ ),+ ),+ Semantics(+ button: true,+ label: 'Remove ${file.name}',+ excludeSemantics: true,+ child: GestureDetector(+ key: ValueKey('swarm-outgoing-remove-${file.name}'),+ behavior: HitTestBehavior.opaque,+ onTap: onRemove,+ child: SizedBox.square(+ dimension: minTouchTarget,+ child: Icon(+ LucideIcons.x,+ size: AppIconSize.besideText,+ color: AppPalette.textSecondary,+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_attachment.dart b/mobile/lib/swarm/swarm_attachment.dartnew file mode 100644index 000000000..c0a27068f--- /dev/null+++ b/mobile/lib/swarm/swarm_attachment.dart@@ -0,0 +1,333 @@+import 'dart:async';+import 'dart:io';+import 'dart:math' as math;++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/phone_navigation.dart';+import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' show AppControl;+import 'package:harness_mobile/shared/widgets/skeleton.dart';++import 'model.dart';+import 'swarm_attachment_store.dart';+import 'swarm_style.dart';++/// A message's file: a picture on Harness's file storage shows in place+/// ([_Preview]); every other file, and a picture that cannot be shown, is+/// [chip].+class SwarmAttachment extends StatelessWidget {+ const SwarmAttachment({+ super.key,+ required this.file,+ required this.link,+ required this.chip,+ this.store,+ });++ final SuperTabAttachment file;++ /// [file]'s link, when it is on Harness's file storage — the only place a+ /// picture is fetched from, as the chip only opens a link from there.+ final Uri? link;+ final Widget chip;++ /// Where the picture is kept; the app's own ([swarmAttachments]) by default.+ final SwarmAttachmentStore? store;++ @override+ Widget build(BuildContext context) {+ final url = link;+ if (!file.isImage || url == null) return chip;+ return _Preview(+ file: file,+ url: url,+ chip: chip,+ store: store ?? swarmAttachments,+ );+ }+}++/// The widest a picture shows in a message.+const _previewWidth = 240.0;++/// A picture in its message: a skeleton in a fixed 4:3 box while it loads,+/// then the picture filling the same box, so the chat never moves under the+/// reader. The backend sends no picture's size, so the box cannot take its+/// shape; the whole picture is a tap away ([SwarmAttachmentViewer]).+class _Preview extends StatefulWidget {+ const _Preview({+ required this.file,+ required this.url,+ required this.chip,+ required this.store,+ });++ final SuperTabAttachment file;+ final Uri url;+ final Widget chip;+ final SwarmAttachmentStore store;++ @override+ State<_Preview> createState() => _PreviewState();+}++class _PreviewState extends State<_Preview> {+ late Future<File> _local;++ /// The store's turn [_local] was asked in ([SwarmAttachmentStore.turns]):+ /// the file is for whoever the store kept files for then, and opens full+ /// screen only while that holds.+ late int _turn;++ /// The picture could not be fetched or decoded: the chip, which still opens it.+ bool _failed = false;++ @override+ void initState() {+ super.initState();+ widget.store.turns.addListener(_turned);+ _ask();+ }++ @override+ void didUpdateWidget(_Preview old) {+ super.didUpdateWidget(old);+ if (old.url == widget.url && identical(old.store, widget.store)) return;+ old.store.turns.removeListener(_turned);+ widget.store.turns.addListener(_turned);+ _ask();+ }++ @override+ void dispose() {+ widget.store.turns.removeListener(_turned);+ super.dispose();+ }++ void _ask() {+ _turn = widget.store.turns.value;+ _local = widget.store.file(widget.url);+ _failed = false;+ }++ /// The files kept changed hands: the picture is asked for again, for+ /// whoever they are kept for now.+ void _turned() {+ if (widget.store.turns.value != _turn) setState(_ask);+ }++ void _fail() {+ if (!mounted || _failed) return;+ setState(() => _failed = true);+ }++ @override+ Widget build(BuildContext context) {+ if (_failed) return widget.chip;+ return LayoutBuilder(+ builder: (context, constraints) {+ final width = math.min(constraints.maxWidth, _previewWidth);+ final height = width * 3 / 4;+ final skeleton = Skeleton(+ width: width,+ height: height,+ radius: AppControl.rowRadius,+ );+ return Padding(+ padding: const EdgeInsets.only(top: AppSpace.s),+ child: FutureBuilder<File>(+ future: _local,+ builder: (context, local) {+ if (local.hasError) {+ // After this frame: the chip replaces the whole preview.+ WidgetsBinding.instance.addPostFrameCallback((_) => _fail());+ return skeleton;+ }+ // Only the file this future answered: while a new one is asked+ // (after a turn), the last one is another holder's.+ final file = local.connectionState == ConnectionState.done+ ? local.data+ : null;+ return Semantics(+ button: file != null,+ image: true,+ label: 'Picture: ${widget.file.name}',+ excludeSemantics: true,+ child: GestureDetector(+ key: ValueKey('swarm-attachment-preview-${widget.file.id}'),+ onTap: file == null ? null : () => _open(context, file),+ child: SizedBox(+ width: width,+ height: height,+ child: file == null+ ? skeleton+ : ClipRRect(+ borderRadius: BorderRadius.circular(+ AppControl.rowRadius,+ ),+ child: Image(+ // Decoded at the box's size, not the picture's.+ image: ResizeImage(+ FileImage(file),+ width:+ (width *+ MediaQuery.devicePixelRatioOf(+ context,+ ))+ .round(),+ ),+ fit: BoxFit.cover,+ gaplessPlayback: true,+ frameBuilder: (_, image, frame, synchronous) =>+ frame == null && !synchronous+ ? skeleton+ : image,+ errorBuilder: (_, _, _) {+ WidgetsBinding.instance.addPostFrameCallback(+ (_) => _fail(),+ );+ return skeleton;+ },+ ),+ ),+ ),+ ),+ );+ },+ ),+ );+ },+ );+ }++ /// Opens [file] full screen, bound to the turn it was asked in, as of the+ /// tap: the viewer is built a frame later, after a change could come.+ void _open(BuildContext context, File file) {+ final turn = _turn;+ if (turn != widget.store.turns.value) return;+ final name = widget.file.name;+ final store = widget.store;+ unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => SwarmAttachmentViewer(+ name: name,+ file: file,+ store: store,+ turn: turn,+ ),+ listensForItself: true,+ ),+ ),+ );+ }+}++/// A picture full screen, to pinch and zoom; its name and a close at the top.+///+/// It shows a file [store] keeps for one account, so it goes when that+/// changes ([SwarmAttachmentStore.turns]: another account, sign-out, Swarm+/// off, a Swarm leaving the list): blank at once, its decoded picture let go,+/// and closed.+class SwarmAttachmentViewer extends StatefulWidget {+ const SwarmAttachmentViewer({+ super.key,+ required this.name,+ required this.file,+ required this.store,+ required this.turn,+ });++ final String name;+ final File file;+ final SwarmAttachmentStore store;++ /// The store's turn [file] was asked in: shown only while it holds, so a+ /// change between the tap and the first frame shows nothing either.+ final int turn;++ @override+ State<SwarmAttachmentViewer> createState() => _ViewerState();+}++class _ViewerState extends State<SwarmAttachmentViewer> {+ /// The decoded picture, as last drawn.+ ImageProvider? _picture;+ bool _gone = false;++ @override+ void initState() {+ super.initState();+ widget.store.turns.addListener(_turned);+ if (widget.store.turns.value != widget.turn) {+ _gone = true;+ WidgetsBinding.instance.addPostFrameCallback((_) => _close());+ }+ }++ @override+ void dispose() {+ widget.store.turns.removeListener(_turned);+ super.dispose();+ }++ void _turned() {+ if (_gone || widget.store.turns.value == widget.turn) return;+ setState(() => _gone = true);+ unawaited(_picture?.evict());+ _close();+ }++ void _close() {+ if (!mounted) return;+ final route = ModalRoute.of(context);+ if (route != null && route.isActive) {+ Navigator.of(context).removeRoute(route);+ }+ }++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ final screen = MediaQuery.sizeOf(context).width;+ final ratio = MediaQuery.devicePixelRatioOf(context);+ // Twice the screen, so a zoom stays sharp without holding the picture at+ // its full size.+ final picture = _picture = ResizeImage(+ FileImage(widget.file),+ width: (screen * ratio * 2).round(),+ );+ return Scaffold(+ key: const ValueKey('swarm-attachment-viewer'),+ backgroundColor: tty.ground,+ body: SafeArea(+ child: Column(+ children: [+ SwarmTopBar(+ leading: SwarmIconButton(+ key: const ValueKey('swarm-attachment-close'),+ icon: LucideIcons.x300,+ label: 'Close',+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ title: _gone ? '' : widget.name,+ ),+ Expanded(+ child: _gone+ ? const SizedBox.expand()+ : InteractiveViewer(+ maxScale: 4,+ child: Center(+ child: Image(image: picture, fit: BoxFit.contain),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_attachment_store.dart b/mobile/lib/swarm/swarm_attachment_store.dartnew file mode 100644index 000000000..b94311989--- /dev/null+++ b/mobile/lib/swarm/swarm_attachment_store.dart@@ -0,0 +1,297 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:flutter/foundation.dart';+import 'package:flutter_cache_manager/flutter_cache_manager.dart';++import 'package:harness_mobile/logging/app_log.dart';++import 'swarm_session.dart';++/// The folder, under the app's private temporary folder, that the phone keeps+/// Swarm's files in: one folder per account inside it.+const _folder = 'swarm-attachments';++/// A file nobody opens for this long goes.+const swarmAttachmentStale = Duration(days: 7);++/// At most this many files are kept; the least recently opened go first.+const swarmAttachmentCap = 200;++/// The phone's copies of Swarm's files, for the pictures shown in a chat+/// ([SwarmAttachment]).+///+/// Fetched exactly as the chip opens them: the public link on Harness's file+/// storage, with no credential of the app's. Kept in the app's private+/// temporary folder (never backed up, never seen by another app), for one+/// account only ([keepOnly]); a file goes after [swarmAttachmentStale]+/// unopened, and the oldest past [swarmAttachmentCap].+///+/// Emptied by [SwarmAttachmentKeeper] on sign-out, Swarm turned off, another+/// account, and a Swarm leaving the account's list.+class SwarmAttachmentStore {+ SwarmAttachmentStore({+ Future<Directory> Function()? root,+ this._fileService,+ this._files,+ }) : _root = root ?? (() => IOFileSystem.createDirectory(_folder));++ final Future<Directory> Function() _root;+ final FileService? _fileService;+ final FileSystem Function(Directory folder)? _files;++ /// The account files are kept for; null while nobody's are.+ String? _account;++ /// Moves the moment the files kept stop being what they were: another+ /// account, nobody's, or the account's emptied ([clear]). Asked for, not+ /// done: a screen showing a kept file lets it go at once, not after the+ /// emptying, which waits for fetches under way.+ ValueListenable<int> get turns => _turns;+ final _turns = ValueNotifier(0);++ /// The account [keepOnly] was last asked to keep files for.+ String? _asked;++ /// Whether [keepOnly] has emptied all but [_account]'s files: until it+ /// has, the folder may hold what an earlier run, or another account, left.+ bool _kept = false;++ /// Whether [_account]'s own files are to go too: a [clear] that failed.+ /// The next [keepOnly] empties them.+ bool _clearOwed = false;++ /// The fetches under way. Emptying waits for them, so none writes into a+ /// folder already emptied, and the cache is never closed under one.+ final _fetching = <Future<void>>{};++ /// The account's cache, opened by the first file asked for after a change.+ Future<CacheManager>? _cache;++ /// [keepOnly] and [clear] one after the other, never over each other.+ Future<void> _changing = Future.value();++ /// [url]'s file, fetched the first time and kept after. Throws while nobody's+ /// files are kept. Asked while they are being emptied, it waits for that.+ Future<File> file(Uri url) async {+ await _changing;+ final account = _account;+ if (account == null) throw StateError('No account to keep files for.');+ final fetch = _fetch(account, url);+ final done = fetch.then<void>((_) {}, onError: (Object _) {});+ _fetching.add(done);+ try {+ return await fetch;+ } finally {+ _fetching.remove(done);+ }+ }++ Future<File> _fetch(String account, Uri url) async =>+ (await (_cache ??= _cacheFor(account))).getSingleFile(url.toString());++ /// Keeps [accountId]'s files and empties every other account's; with null+ /// (nobody signed in, or Swarm off) empties everything. A file that could+ /// not go throws, after the rest went; the next call tries again.+ Future<void> keepOnly(String? accountId) {+ final turned = accountId != _asked;+ _asked = accountId;+ final change = _serially(() async {+ if (accountId != _account) {+ _account = accountId;+ _kept = _clearOwed = false;+ }+ if (_kept && !_clearOwed) return;+ await _close();+ final root = await _root();+ if (await root.exists()) {+ final keep = accountId == null || _clearOwed ? null : _name(accountId);+ (Object, StackTrace)? failed;+ await for (final entry in root.list(followLinks: false)) {+ if (entry.uri.pathSegments.lastWhere((s) => s.isNotEmpty) == keep) {+ continue;+ }+ try {+ await _delete(entry);+ } catch (error, stack) {+ failed ??= (error, stack);+ }+ }+ if (failed case (final error, final stack)) {+ Error.throwWithStackTrace(error, stack);+ }+ }+ _kept = true;+ _clearOwed = false;+ });+ if (turned) _turn();+ return change;+ }++ /// Empties the account's files: a Swarm left its list. One that could not+ /// go throws, and the next [keepOnly] empties them.+ Future<void> clear() {+ final change = _serially(() async {+ await _close();+ final account = _account;+ if (account == null) return;+ _clearOwed = true;+ await _delete(await _folderOf(account));+ _clearOwed = false;+ });+ _turn();+ return change;+ }++ /// Tells of a change once it is queued, so a file asked for on hearing of+ /// it waits for the change, and is the new holder's.+ void _turn() => _turns.value++;++ /// Runs [change] after the changes before it and the fetches under way. One+ /// that fails holds up none after it.+ Future<void> _serially(Future<void> Function() change) {+ final run = _changing.then((_) async {+ await Future.wait([..._fetching]);+ await change();+ });+ _changing = run.catchError((Object _) {});+ return run;+ }++ Future<void> _close() async {+ final cache = _cache;+ _cache = null;+ await (await cache)?.dispose();+ }++ Future<CacheManager> _cacheFor(String account) async {+ final folder = await _folderOf(account);+ final key = '$_folder/${_name(account)}';+ return CacheManager(+ Config(+ key,+ stalePeriod: swarmAttachmentStale,+ maxNrOfCacheObjects: swarmAttachmentCap,+ // In the account's folder, so emptying it takes what was kept and the+ // record of it together.+ repo: JsonCacheInfoRepository.withFile(+ File('${folder.path}/index.json'),+ ),+ fileSystem: _files?.call(folder) ?? IOFileSystem(key),+ fileService: _fileService ?? HttpFileService(),+ ),+ );+ }++ Future<Directory> _folderOf(String account) async =>+ Directory('${(await _root()).path}/${_name(account)}');++ /// An account's folder name: its id, written so no id can reach outside.+ static String _name(String account) =>+ base64Url.encode(utf8.encode(account)).replaceAll('=', '');++ /// Deletes [entry]; one already gone is no failure, any other is thrown.+ static Future<void> _delete(FileSystemEntity entry) async {+ try {+ await entry.delete(recursive: true);+ } on PathNotFoundException {+ // Already gone.+ }+ }+}++/// The app's one store of Swarm's files.+final swarmAttachments = SwarmAttachmentStore();++/// Keeps [store] to the account whose Swarm [host] reads: the files go on+/// sign-out, Swarm turned off and another account ([SwarmAttachmentStore.keepOnly]),+/// and when a Swarm leaves the account's list ([SwarmAttachmentStore.clear]).+/// The shell's, for its lifetime; at start it empties what no one now signed+/// in left behind.+class SwarmAttachmentKeeper {+ SwarmAttachmentKeeper(+ this.host, {+ SwarmAttachmentStore? store,+ this.retry = const Duration(minutes: 1),+ }) : store = store ?? swarmAttachments {+ host.addListener(_hostChanged);+ _hostChanged();+ }++ final SwarmHost host;+ final SwarmAttachmentStore store;++ /// How long after a failed emptying it is tried again; twice as long after+ /// each failure in a row, up to [_retryAtMost].+ final Duration retry;++ static const _retryAtMost = Duration(hours: 1);++ /// The wait before the next try, while emptying keeps failing.+ Duration? _wait;+ Timer? _again;+ bool _disposed = false;++ SwarmSession? _session;++ /// The Swarms last read in the account's list; null until it is read.+ Set<String>? _listed;++ void _hostChanged() {+ final session = host.session;+ if (!identical(session, _session)) {+ _session?.inbox.removeListener(_listChanged);+ _session = session;+ _listed = null;+ session?.inbox.addListener(_listChanged);+ }+ _emptying(store.keepOnly(session?.accountId));+ _listChanged();+ }++ void _listChanged() {+ final inbox = _session?.inbox;+ if (inbox == null || !inbox.loaded) return;+ final listed = {for (final swarm in inbox.swarms) swarm.id};+ final before = _listed;+ _listed = listed;+ if (before != null && !listed.containsAll(before)) {+ _emptying(store.clear());+ }+ }++ /// Emptying runs on its own. One that fails says so in the app's log and is+ /// tried again ([retry]): for the account signed in then, which also+ /// empties what a failed [SwarmAttachmentStore.clear] left.+ void _emptying(Future<void> emptying) => unawaited(+ emptying.then(+ (_) {+ _wait = null;+ },+ onError: (Object error, StackTrace stack) {+ appLog.failure(+ 'swarm',+ 'Swarm files could not be emptied',+ error: error,+ stackTrace: stack,+ );+ if (_disposed) return;+ final next = _wait == null ? retry : _wait! * 2;+ final wait = _wait = next > _retryAtMost ? _retryAtMost : next;+ _again?.cancel();+ _again = Timer(+ wait,+ () => _emptying(store.keepOnly(host.session?.accountId)),+ );+ },+ ),+ );++ void dispose() {+ _disposed = true;+ _again?.cancel();+ host.removeListener(_hostChanged);+ _session?.inbox.removeListener(_listChanged);+ }+}diff --git a/mobile/lib/swarm/swarm_buddy.dart b/mobile/lib/swarm/swarm_buddy.dartnew file mode 100644index 000000000..0f7a172ce--- /dev/null+++ b/mobile/lib/swarm/swarm_buddy.dart@@ -0,0 +1,414 @@+import 'package:flutter/foundation.dart';++import 'identity.dart';+import 'model.dart';+import 'swarm_reader.dart';+import 'swarm_request.dart';++/// What the phone knows of Buddies (spec: Buddies, 10-28; in every Swarm+/// since #2090, where they replaced Chat with PM): each person's Buddy chat in+/// each project, where the PM's private lines to them land, and the Buddy that+/// may run in it. Read from a Swarm's raw state, as [SwarmReader.partners] is:+/// the model the phone shares with the desktop (`model.dart`, held to it by+/// `desktop_parity_test.dart`) does not carry Buddies on this branch yet.+@immutable+class SwarmBuddies {+ const SwarmBuddies._({+ required this.chatOwners,+ required this.buddyOwners,+ required this.ownChats,+ required this.ownBuddies,+ required this.ownStarts,+ });++ /// Nothing read yet, or nothing left to read.+ static const none = SwarmBuddies._(+ chatOwners: {},+ buddyOwners: {},+ ownChats: {},+ ownBuddies: {},+ ownStarts: [],+ );++ /// [state]'s Buddies, as [accountId] reads them. A group or agent from+ /// before projects belongs to the first, as the model reads it.+ factory SwarmBuddies.read(Map<String, dynamic> state, String accountId) {+ final chatOwners = <String, String>{};+ final ownChats = <String, String>{};+ for (final row in _rows(state['conversations'])) {+ if (row case {+ 'kind': 'buddy',+ 'id': final String id,+ 'buddyOwnerId': final String owner,+ }) {+ chatOwners[id] = owner;+ if (owner == accountId) {+ ownChats.putIfAbsent(row['projectId'] as String? ?? 'lead', () => id);+ }+ }+ }+ final buddyOwners = <String, String>{};+ final ownBuddies = <String, String>{};+ for (final row in _rows(state['agents'])) {+ if (row case {+ 'id': final String id,+ 'buddyOf': {'personId': final String person},+ }) {+ buddyOwners[id] = person;+ if (person == accountId) {+ ownBuddies.putIfAbsent(+ row['projectId'] as String? ?? 'lead',+ () => id,+ );+ }+ }+ }+ return SwarmBuddies._(+ chatOwners: Map.unmodifiable(chatOwners),+ buddyOwners: Map.unmodifiable(buddyOwners),+ ownChats: Map.unmodifiable(ownChats),+ ownBuddies: Map.unmodifiable(ownBuddies),+ ownStarts: List.unmodifiable([+ for (final row in _rows(state['starts']))+ if (row+ case {'request': {'buddyOf': {'personId': final String person}}}+ when person == accountId)+ Map<String, dynamic>.unmodifiable(row),+ ]),+ );+ }++ /// Every Buddy chat the read holds, anyone's, with the person it belongs+ /// to: none of them is a workgroup.+ final Map<String, String> chatOwners;++ /// Every Buddy the read holds, anyone's, with the person it belongs to.+ final Map<String, String> buddyOwners;++ /// The reader's own Buddy chat in each project, by project id.+ final Map<String, String> ownChats;++ /// The reader's own Buddy in each project, its agent id by project id.+ final Map<String, String> ownBuddies;++ /// The starts of the reader's own Buddies, oldest first: one is under way+ /// while it has neither a harness nor an error.+ final List<Map<String, dynamic>> ownStarts;++ static Iterable<Map<String, dynamic>> _rows(Object? list) => [+ if (list is List)+ for (final row in list)+ if (row is Map) Map<String, dynamic>.from(row),+ ];+}++/// Each read's Buddies, by agent id, kept with its snapshot: the read's+/// [SwarmBuddies], marked on the UI isolate as the read is shown+/// ([swarmMarkBuddies]), since a snapshot worked out on another isolate+/// arrives without what was kept with it.+final _buddiesOf = Expando<Set<String>>('swarm buddies');++/// Marks [snapshot]'s Buddies as [buddies], read from the same state, for+/// [swarmIsBuddy].+void swarmMarkBuddies(SuperTabSnapshot snapshot, SwarmBuddies buddies) =>+ _buddiesOf[snapshot] = buddies.buddyOwners.keys.toSet();++/// Whether agent [agentId] of [snapshot] is someone's Buddy: a person's own+/// helper, never one of the team (Ken, 10-29). The phone's Agents lists and+/// their counts leave it out; the person's own shows only under Buddies.+bool swarmIsBuddy(SuperTabSnapshot snapshot, String agentId) =>+ _buddiesOf[snapshot]?.contains(agentId) ?? false;++/// [snapshot]'s agents without its Buddies ([swarmIsBuddy]): the team, as+/// its lists and counts show it.+Iterable<SuperTabAgent> swarmTeamAgents(SuperTabSnapshot snapshot) =>+ snapshot.agents.where((a) => !swarmIsBuddy(snapshot, a.id));++/// The person's own Buddy chat in [projectId]; null while the read holds none+/// (none opened yet, or quiet for a day and left out of a first load).+SuperTabConversation? swarmBuddyChat(SwarmReader reader, String projectId) =>+ switch (reader.buddies.ownChats[projectId]) {+ final id? => reader.snapshot?.conversation(id),+ null => null,+ };++/// The person's own Buddy in [projectId]; null while none runs there.+SuperTabAgent? swarmBuddy(SwarmReader reader, String projectId) =>+ switch (reader.buddies.ownBuddies[projectId]) {+ final id? => reader.snapshot?.agent(id),+ null => null,+ };++/// Whether [conversationId] is a Buddy chat, anyone's.+bool swarmIsBuddyChat(SwarmReader reader, String conversationId) =>+ reader.buddies.chatOwners.containsKey(conversationId);++/// Whether [conversationId] is the person's own Buddy chat, in any project.+bool swarmIsOwnBuddyChat(SwarmReader reader, String conversationId) =>+ reader.buddies.chatOwners[conversationId] == reader.accountId;++/// Whether [message] is one of the PM's private lines to the person: its+/// project's Lead writing in the person's own Buddy chat, where it writes but+/// cannot read (#2090; the desktop's `_shownAuthor`).+bool swarmIsPmLine(SwarmReader reader, SuperTabMessage message) {+ if (!message.fromAgent ||+ !swarmIsOwnBuddyChat(reader, message.conversationId)) {+ return false;+ }+ final snapshot = reader.snapshot;+ final project = snapshot?.projectFor(message.conversationId);+ return project != null &&+ snapshot!.conversation(project.leadConversationId)?.leadId ==+ message.authorId;+}++/// The newest start of the person's Buddy in [projectId]: under way while it+/// has neither a harness nor an error, failed with an error (the desktop's+/// `SuperTabController.buddyStart`).+Map<String, dynamic>? swarmBuddyStart(SwarmReader reader, String projectId) {+ final chat = reader.buddies.ownChats[projectId];+ for (final start in reader.buddies.ownStarts.reversed) {+ final request = start['request'] as Map;+ if (request['projectId'] == projectId ||+ (chat != null && request['conversationId'] == chat)) {+ return start;+ }+ }+ return null;+}++/// The engines a Buddy runs on (spec: Buddies, 10-28), as people read them.+const swarmBuddyEngines = {'claude': 'Claude', 'codex': 'Codex'};++/// Engines a Buddy cannot run on yet, and why, in the backend's own words+/// (`CODEX_BUDDY_REFUSAL`, backend superTabs/buddyContract.ts), as the+/// desktop's `kBuddyEngineRefusals` has them (desktop_parity_test): Start+/// your Buddy offers them turned off, with this beside them.+const swarmBuddyEngineRefusals = {+ 'codex':+ 'A Codex Buddy is not available yet: Codex would run some commands '+ 'outside its sandbox without asking. Choose Claude Code.',+};++/// The engine Start again asks for: the Buddy's own, or Claude Code in place+/// of one the server refuses, which it would refuse again (the desktop's+/// `buddyRestartEngine`).+String swarmBuddyRestartEngine(String engine) =>+ swarmBuddyEngineRefusals.containsKey(engine) ? 'claude' : engine;++/// Start again's label: "Start with Claude Code" where it changes the engine.+String swarmBuddyRestartLabel(String engine) =>+ swarmBuddyRestartEngine(engine) == engine+ ? 'Start again'+ : 'Start with Claude Code';++/// An engine as people read it: "Claude", "Codex".+String swarmBuddyEngineName(String engine) =>+ swarmBuddyEngines[engine] ??+ (engine.isEmpty ? 'Agent' : engine[0].toUpperCase() + engine.substring(1));++/// The person's Buddy in [projectId] by its name, or plain "Buddy" while none+/// runs (docs/naming-system.md: Buddies).+String swarmBuddyName(SwarmReader reader, String projectId) =>+ switch (swarmBuddy(reader, projectId)) {+ final agent? => reader.snapshot!.agentName(agent.id, fallback: 'Buddy'),+ null => 'Buddy',+ };++/// How the person's Buddy in [projectId] stands, in a quiet word after its+/// name: "starting" while a start is under way, "not started" with none+/// running, "offline" while it is down; null while it runs (the desktop's+/// Buddies rows).+String? swarmBuddyNote(SwarmReader reader, String projectId) {+ final agent = swarmBuddy(reader, projectId);+ if (agent != null) return agent.downSince == null ? null : 'offline';+ final start = swarmBuddyStart(reader, projectId);+ return start != null && start['harnessId'] == null && start['error'] == null+ ? 'starting'+ : 'not started';+}++/// Whether the person may write in [reader]'s Swarm: start or remove a+/// Buddy. A viewer may not.+bool swarmCanWrite(SwarmReader reader) =>+ reader.snapshot?.people+ .where((p) => p.id == reader.accountId)+ .firstOrNull+ ?.canWrite ??+ false;++/// A machine a Buddy may start on, as Start your Buddy lists it.+typedef SwarmBuddyMachine = ({String id, String name});++/// The person's own machines in the Swarm: a Buddy runs only there, like a+/// Lead, whatever its engine (Ken, 10-28). Not a machine someone else shared+/// with them, and not another person's; the backend refuses any other (the+/// desktop's `buddyMachines`).+List<SwarmBuddyMachine> swarmBuddyMachines(SwarmReader reader) => [+ for (final m in reader.snapshot?.machines ?? const <Map<String, dynamic>>[])+ if (m['hostMachineId'] == null &&+ m['contributorId'] == reader.accountId &&+ m['machineId'] is String)+ (id: m['machineId'] as String, name: _machineName(m['name'])),+];++/// The machine [machineId] by its name in the Swarm, as a Buddy's chat+/// says what it runs on; "another machine" while the Swarm names none (the+/// desktop's `buddyMachineName`).+String swarmBuddyMachineName(SwarmReader reader, String machineId) =>+ _machineName(+ reader.snapshot?.pool(machineId)?['name'],+ fallback: 'another machine',+ );++/// A machine's name without its `.local`, as the desktop shows it.+String _machineName(Object? name, {String fallback = 'Your machine'}) {+ const suffix = '.local';+ if (name is! String || name.isEmpty) return fallback;+ return name.length > suffix.length && name.toLowerCase().endsWith(suffix)+ ? name.substring(0, name.length - suffix.length)+ : name;+}++/// A person of [reader]'s Swarm by the name it shows them by: their address+/// before the @; "its owner" while the Swarm does not list them (the+/// desktop's `buddyPersonName`).+String swarmBuddyPersonName(SwarmReader reader, String personId) {+ final email = reader.snapshot?.people+ .where((p) => p.id == personId)+ .firstOrNull+ ?.email;+ return email == null || email.isEmpty+ ? 'its owner'+ : superTabPersonName(email);+}++/// Opens the person's Buddy chat in [projectId], on the server first when+/// the read holds none: every person has one in each project before any+/// Buddy (backend buddy.chat), so the PM's private lines never drop. One+/// request per person, membership and project, as the desktop's+/// `openBuddyChat` sends it, so a second tap or another device gets the same+/// chat back. Answers its id — the chat opened on it looks it up as it reads+/// its messages — or null when the server named none; a refusal throws.+Future<String?> openSwarmBuddyChat(SwarmReader reader, String projectId) async {+ if (swarmBuddyChat(reader, projectId) case final chat?) return chat.id;+ final generation = reader.snapshot?.people+ .where((p) => p.id == reader.accountId)+ .firstOrNull+ ?.generation;+ var operation =+ 'buddy-chat-$projectId-${reader.accountId}-${generation ?? ''}';+ // The backend's operation ids are at most 160 characters.+ if (operation.length > 160) operation = operation.substring(0, 160);+ final result = await _command(reader, {+ 'type': 'buddy.chat',+ 'projectId': projectId,+ }, operation: operation);+ return result['conversationId'] as String?;+}++/// Starts the person's Buddy in [projectId] on [machineId] with [engine]+/// (backend buddy.create; a Buddy that is down is replaced), then reads the+/// Swarm again, so its start shows. Answers its chat's id; a refusal throws.+Future<String?> startSwarmBuddy(+ SwarmReader reader, {+ required String projectId,+ required String machineId,+ required String engine,+}) async {+ final result = await _command(reader, {+ 'type': 'buddy.create',+ 'projectId': projectId,+ 'machineId': machineId,+ 'engine': engine,+ });+ await reader.refresh();+ return result['conversationId'] as String?;+}++/// Removes the person's Buddy in [projectId]: its session stops and its chat+/// stays. Reads the Swarm again; a refusal throws.+Future<void> removeSwarmBuddy(SwarmReader reader, String projectId) async {+ await _command(reader, {'type': 'buddy.remove', 'projectId': projectId});+ await reader.refresh();+}++/// What the person does to their Buddy in one project from its chat: start+/// it, start it again, remove it. One at a time — a second tap while one is+/// under way does nothing — and what went wrong with the last, as a sentence+/// to show; it lasts until the next.+class SwarmBuddyActions extends ChangeNotifier {+ SwarmBuddyActions(this.reader, this.projectId);++ final SwarmReader reader;+ final String projectId;++ bool _busy = false, _disposed = false;+ String? _error;++ /// One is under way.+ bool get busy => _busy;++ /// What went wrong with the last one; null when it went through.+ String? get error => _error;++ /// Starts the Buddy on [machineId] with [engine] ([startSwarmBuddy]).+ Future<void> start({required String machineId, required String engine}) =>+ _run(+ () => startSwarmBuddy(+ reader,+ projectId: projectId,+ machineId: machineId,+ engine: engine,+ ),+ "Couldn't start your Buddy. Try again.",+ );++ /// Removes the Buddy ([removeSwarmBuddy]); its chat stays.+ Future<void> remove() => _run(+ () => removeSwarmBuddy(reader, projectId),+ "Couldn't remove your Buddy. Try again.",+ );++ Future<void> _run(Future<Object?> Function() act, String fallback) async {+ if (_busy || _disposed) return;+ _busy = true;+ _error = null;+ notifyListeners();+ try {+ await act();+ } on SuperTabFailure catch (failure) {+ _error = failure.message;+ } catch (_) {+ _error = fallback;+ }+ _busy = false;+ if (!_disposed) notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ super.dispose();+ }+}++/// Sends [command] to [reader]'s Swarm and answers its result.+Future<Map<String, dynamic>> _command(+ SwarmReader reader,+ Map<String, dynamic> command, {+ String? operation,+}) async {+ final answer = superTabMap(+ await reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ body: {+ 'operationId': operation ?? superTabOperationId(),+ 'command': command,+ },+ ),+ );+ final result = answer['result'];+ return result is Map ? Map<String, dynamic>.from(result) : const {};+}diff --git a/mobile/lib/swarm/swarm_buddy_chat.dart b/mobile/lib/swarm/swarm_buddy_chat.dartnew file mode 100644index 000000000..c17b9b1a1--- /dev/null+++ b/mobile/lib/swarm/swarm_buddy_chat.dart@@ -0,0 +1,530 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/phone_sheet.dart';+import 'package:harness_mobile/shared/theme/app_icon_size.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/shared/widgets/touch_target.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'model.dart';+import 'swarm_buddy.dart';+import 'swarm_conversation_page.dart';+import 'swarm_reader.dart';+import 'swarm_request.dart';+import 'swarm_row.dart';+import 'swarm_style.dart';++/// Opens the person's Buddy chat in [projectId] over [context]'s page, on the+/// server first when the read holds none ([openSwarmBuddyChat]). Answers what+/// went wrong as a sentence to show, or null once it is open.+Future<String?> openSwarmBuddy(+ BuildContext context,+ SwarmReader reader,+ String swarmId,+ String projectId,+) async {+ final String? id;+ try {+ id = await openSwarmBuddyChat(reader, projectId);+ } on SuperTabFailure catch (failure) {+ return failure.message;+ } catch (_) {+ return 'Could not open your Buddy chat. Try again.';+ }+ if (id == null) return 'Your Buddy chat is not ready yet. Try again.';+ if (context.mounted) openSwarmConversation(context, swarmId, id);+ return null;+}++/// The person's Buddy in [projectId] as a face: its own, or a plain "B" for+/// Buddy while none runs.+class SwarmBuddyAvatar extends StatelessWidget {+ const SwarmBuddyAvatar({+ super.key,+ required this.reader,+ required this.projectId,+ this.size = 32,+ });++ final SwarmReader reader;+ final String projectId;+ final double size;++ @override+ Widget build(BuildContext context) => switch (swarmBuddy(reader, projectId)) {+ final agent? => SwarmAvatar(+ id: agent.id,+ name: swarmBuddyName(reader, projectId),+ picture: agent.avatar,+ size: size,+ ),+ null => SwarmAvatar(+ id: 'buddy:${reader.tabId}/$projectId',+ name: 'Buddy',+ size: size,+ ),+ };+}++/// Under the person's Buddy chat's header (#2090; the desktop's+/// `SuperTabBuddyBar`): what their Buddy runs on and who else can see its+/// terminal, and, while it is down, Start again. With no Buddy, how its start+/// is going, or — with none under way — Start your Buddy, for a person who+/// may write: the chat is there before any Buddy. Under all of it, what went+/// wrong with the last start or removal. Nothing for a viewer with no Buddy.+class SwarmBuddyBar extends StatelessWidget {+ const SwarmBuddyBar({super.key, required this.actions});++ final SwarmBuddyActions actions;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return ListenableBuilder(+ listenable: Listenable.merge([actions.reader, actions]),+ builder: (context, _) {+ final reader = actions.reader;+ final canWrite = swarmCanWrite(reader);+ final error = actions.error;+ final body = switch (swarmBuddy(reader, actions.projectId)) {+ final agent? => _running(reader, agent, canWrite),+ null => _starting(reader, canWrite),+ };+ if (body == null && error == null) return const SizedBox.shrink();+ return DecoratedBox(+ key: const ValueKey('swarm-buddy-bar'),+ decoration: BoxDecoration(+ border: Border(bottom: BorderSide(color: AppGlass.hair)),+ ),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.xs,+ AppSpace.screenInset,+ AppSpace.s,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ ?body,+ if (error != null)+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.xs),+ child: SwarmRow.line(+ error,+ key: const ValueKey('swarm-buddy-error'),+ lines: 3,+ color: AppColors.danger,+ ),+ ),+ ],+ ),+ ),+ );+ },+ );+ }++ /// "Claude on MacBook Pro · only you can read this chat", and, while it+ /// is down, that it is offline with Start again.+ Widget _running(SwarmReader reader, SuperTabAgent agent, bool canWrite) {+ final where = [+ '${swarmBuddyEngineName(agent.engine)} on '+ '${swarmBuddyMachineName(reader, agent.machineId)}',+ agent.machineOwnerId == reader.accountId+ ? 'only you can read this chat'+ : '${swarmBuddyPersonName(reader, agent.machineOwnerId)} can see '+ 'its terminal',+ ].join(' · ');+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ SwarmRow.line(+ where,+ key: const ValueKey('swarm-buddy-where'),+ lines: 2,+ ),+ if (agent.downSince != null)+ _Line(+ key: const ValueKey('swarm-buddy-offline'),+ text:+ '${swarmBuddyName(reader, actions.projectId)} is offline. '+ 'Your chat stays.',+ engine: agent.engine,+ again: canWrite+ ? () => unawaited(+ actions.start(+ machineId: agent.machineId,+ engine: swarmBuddyRestartEngine(agent.engine),+ ),+ )+ : null,+ busy: actions.busy,+ ),+ ],+ );+ }++ /// A start under way, or one that failed with Start again; with none,+ /// Start your Buddy. Null for a viewer, who starts none.+ Widget? _starting(SwarmReader reader, bool canWrite) {+ final start = swarmBuddyStart(reader, actions.projectId);+ final error = start?['error'];+ if (start == null || (error is! String && start['harnessId'] != null)) {+ return canWrite ? _BuddyStart(actions: actions) : null;+ }+ final request = start['request'] as Map;+ final engine = request['engine'] as String? ?? '';+ final machineId = request['machineId'] as String? ?? '';+ if (error is String) {+ return _Line(+ key: const ValueKey('swarm-buddy-failed'),+ text: "Couldn't start: $error",+ engine: engine,+ again: canWrite && machineId.isNotEmpty+ ? () => unawaited(+ actions.start(+ machineId: machineId,+ engine: swarmBuddyRestartEngine(engine),+ ),+ )+ : null,+ busy: actions.busy,+ );+ }+ return SwarmRow.line(+ 'Starting ${swarmBuddyEngineName(engine)} on '+ '${swarmBuddyMachineName(reader, machineId)}…',+ key: const ValueKey('swarm-buddy-starting'),+ lines: 2,+ );+ }+}++/// What happened to the Buddy, in a line, and Start again at its end for a+/// person who may write: "Start with Claude Code" for an [engine] the server+/// refuses.+class _Line extends StatelessWidget {+ const _Line({+ super.key,+ required this.text,+ required this.engine,+ required this.again,+ required this.busy,+ });++ final String text;+ final String engine;+ final VoidCallback? again;+ final bool busy;++ @override+ Widget build(BuildContext context) => Row(+ children: [+ Expanded(+ child: Text(text, style: AppType.body(color: AppPalette.textPrimary)),+ ),+ if (again != null)+ SwarmButton(+ key: const ValueKey('swarm-buddy-start-again'),+ label: swarmBuddyRestartLabel(engine),+ style: SwarmButtonStyle.link,+ busy: busy,+ busyLabel: 'Starting…',+ onPressed: again,+ ),+ ],+ );+}++/// A Buddy chat with no Buddy: one tap on Start starts one, on the person's+/// own machine and with Claude unless they pick otherwise (mockup, Tony+/// 10-29). With no machine of theirs in the Swarm, it says to add one.+class _BuddyStart extends StatefulWidget {+ const _BuddyStart({required this.actions});++ final SwarmBuddyActions actions;++ @override+ State<_BuddyStart> createState() => _BuddyStartState();+}++class _BuddyStartState extends State<_BuddyStart> {+ String? _machine;+ String _engine = 'claude';++ Future<void> _pickMachine(List<SwarmBuddyMachine> machines, String chosen) =>+ showPhoneSheet(+ context,+ title: 'Machine',+ actions: [+ for (final m in machines)+ PhoneSheetAction(+ icon: m.id == chosen ? LucideIcons.check : LucideIcons.laptop,+ label: m.name,+ onTap: () {+ if (mounted) setState(() => _machine = m.id);+ },+ ),+ ],+ );++ @override+ Widget build(BuildContext context) {+ final actions = widget.actions;+ final machines = swarmBuddyMachines(actions.reader);+ final machine =+ machines.where((m) => m.id == _machine).firstOrNull ??+ machines.firstOrNull;+ final busy = actions.busy;+ return Column(+ key: const ValueKey('swarm-buddy-start'),+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ 'Start your Buddy to brainstorm here',+ style: AppType.body(+ color: AppPalette.textPrimary,+ fontWeight: FontWeight.w600,+ ),+ ),+ if (machine == null)+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.xs),+ child: SwarmRow.line(+ 'A Buddy runs on one of your own machines. Add one of yours to '+ 'this Swarm first.',+ key: const ValueKey('swarm-buddy-no-machine'),+ lines: 3,+ ),+ )+ else ...[+ _Field(+ label: 'Machine',+ child: Semantics(+ button: true,+ label: 'Machine, ${machine.name}',+ excludeSemantics: true,+ child: InkWell(+ key: const ValueKey('swarm-buddy-machine'),+ borderRadius: BorderRadius.circular(AppControl.radius),+ onTap: busy+ ? null+ : () => unawaited(_pickMachine(machines, machine.id)),+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: minTouchTarget),+ child: Row(+ children: [+ Expanded(+ child: Text(+ machine.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ ),+ Icon(+ LucideIcons.chevronDown,+ size: AppIconSize.besideText,+ color: AppPalette.textSecondary,+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ _Field(+ label: 'Agent',+ child: Wrap(+ spacing: AppSpace.s,+ runSpacing: AppSpace.xs,+ children: [+ for (final MapEntry(:key, :value) in swarmBuddyEngines.entries)+ Semantics(+ selected: key == _engine,+ child: SwarmButton(+ key: ValueKey('swarm-buddy-engine-$key'),+ label: value,+ icon: key == _engine ? LucideIcons.check : null,+ // One the server refuses is offered turned off.+ onPressed:+ busy || swarmBuddyEngineRefusals.containsKey(key)+ ? null+ : () => setState(() => _engine = key),+ ),+ ),+ ],+ ),+ ),+ for (final refusal in swarmBuddyEngineRefusals.values)+ Padding(+ padding: const EdgeInsets.only(+ left: _Field._labelWidth,+ top: AppSpace.xs,+ ),+ child: SwarmRow.line(refusal, lines: 3),+ ),+ const SizedBox(height: AppSpace.s),+ SwarmButton(+ key: const ValueKey('swarm-buddy-start-button'),+ label: 'Start',+ style: SwarmButtonStyle.fill,+ wide: true,+ busy: busy,+ busyLabel: 'Starting…',+ onPressed: () => unawaited(+ actions.start(machineId: machine.id, engine: _engine),+ ),+ ),+ ],+ ],+ );+ }+}++/// One choice of Start your Buddy: its name, then what is chosen.+class _Field extends StatelessWidget {+ const _Field({required this.label, required this.child});++ final String label;+ final Widget child;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.only(top: AppSpace.xs),+ child: Row(+ children: [+ SizedBox(+ width: _labelWidth,+ child: Text(+ label,+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ ),+ Expanded(child: child),+ ],+ ),+ );++ /// Wide enough for "Machine" at the largest text the chat allows.+ static const _labelWidth = AppSpace.xl * 3;+}++/// At the end of the person's Buddy chat's header, while their Buddy runs+/// and they may write: ⋮, whose one row, Remove Buddy, asks first, then+/// stops it; the chat stays (the desktop's Buddy options). Nothing+/// otherwise.+class SwarmBuddyMenuButton extends StatelessWidget {+ const SwarmBuddyMenuButton({super.key, required this.actions});++ final SwarmBuddyActions actions;++ Future<void> _open(BuildContext context) => showPhoneSheet(+ context,+ title: swarmBuddyName(actions.reader, actions.projectId),+ actions: [+ PhoneSheetAction(+ icon: LucideIcons.userMinus,+ label: 'Remove Buddy',+ destructive: true,+ onTap: () => unawaited(_confirmRemove(context)),+ ),+ ],+ );++ Future<void> _confirmRemove(BuildContext context) async {+ if (!context.mounted) return;+ final remove = await showDialog<bool>(+ context: context,+ builder: (context) => AlertDialog(+ title: Text(+ 'Remove Buddy?',+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ content: Text(+ 'Its session stops. Your chat stays, and adding a Buddy here again '+ 'picks it up.',+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ actions: [+ SwarmButton(+ key: const ValueKey('swarm-buddy-remove-cancel'),+ label: 'Cancel',+ style: SwarmButtonStyle.link,+ onPressed: () => Navigator.of(context).pop(false),+ ),+ SwarmButton(+ key: const ValueKey('swarm-buddy-remove-confirm'),+ label: 'Remove',+ style: SwarmButtonStyle.fill,+ onPressed: () => Navigator.of(context).pop(true),+ ),+ ],+ ),+ );+ if (remove == true) await actions.remove();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return ListenableBuilder(+ listenable: Listenable.merge([actions.reader, actions]),+ builder: (context, _) {+ final reader = actions.reader;+ if (swarmBuddy(reader, actions.projectId) == null ||+ !swarmCanWrite(reader)) {+ return const SizedBox.shrink();+ }+ final busy = actions.busy;+ final ink = AppPalette.textPrimary;+ return Semantics(+ key: const ValueKey('swarm-buddy-menu'),+ button: true,+ enabled: !busy,+ label: busy ? 'Working on your Buddy…' : 'Buddy options',+ excludeSemantics: true,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: busy+ ? null+ : () {+ HapticFeedback.selectionClick();+ unawaited(_open(context));+ },+ child: SizedBox.square(+ dimension: minTouchTarget,+ child: Align(+ alignment: AlignmentDirectional.centerEnd,+ child: busy+ ? SizedBox.square(+ dimension: AppIconSize.besideText,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ color: ink,+ backgroundColor: ink.withValues(alpha: .35),+ ),+ )+ : Icon(+ LucideIcons.ellipsisVertical300,+ size: AppIconSize.standalone,+ color: ink,+ ),+ ),+ ),+ ),+ );+ },+ );+ }+}diff --git a/mobile/lib/swarm/swarm_chat_cache.dart b/mobile/lib/swarm/swarm_chat_cache.dartnew file mode 100644index 000000000..3a6ed4d01--- /dev/null+++ b/mobile/lib/swarm/swarm_chat_cache.dart@@ -0,0 +1,130 @@+import 'package:flutter/foundation.dart';++import 'model.dart';+import 'swarm_reader.dart';++/// What a closed chat held: its messages, oldest first, where the earlier+/// ones start, and the reaction counter they were read with.+typedef SwarmChatKept = ({+ List<SuperTabMessage> messages,+ SuperTabPage? before,+ int? reactionSeq,+});++/// The chats last read on this phone, so one opened again shows at once what+/// was read and reads only what is newer ([SwarmConversation]). In memory+/// only: nothing of a chat is written to the device.+///+/// A chat is kept for the reader that read it, and only while that reader's+/// Swarm read still has it. A read that leaves it out (the person taken out+/// of it), a read again from nothing, or the reader's access ending forgets+/// it — the person leaving the Swarm, signing out or turning Swarm off each+/// takes the reader's access away before it goes ([SwarmReader.revoke]).+abstract final class SwarmChatCache {+ /// How many chats are kept: the one closed longest ago goes first.+ static const size = 10;++ /// How many of a chat's messages are kept: the newest, a page of them as+ /// the backend reads it. Those before are read again as earlier messages.+ static const page = 100;++ /// Oldest first.+ static final _kept = <(SwarmReader, String), _Kept>{};++ /// The readers with a chat kept, each told to [_check] at its reads.+ static final _watched = <SwarmReader, VoidCallback>{};++ /// What [reader] last kept of chat [id], while it may still show it.+ static SwarmChatKept? take(SwarmReader reader, String id) {+ final kept = _kept[(reader, id)];+ if (kept == null || !_holds(reader, id, kept.generation)) return null;+ return (+ messages: kept.messages,+ before: kept.before,+ reactionSeq: kept.reactionSeq,+ );+ }++ /// Keeps chat [id] as [reader] read it — its newest [page] of [messages],+ /// oldest first, and where the earlier ones start — as the newest kept;+ /// unless its Swarm's read no longer has it, or nothing of it was read.+ static void keep(+ SwarmReader reader,+ String id, {+ required List<SuperTabMessage> messages,+ required SuperTabPage? before,+ int? reactionSeq,+ }) {+ _kept.remove((reader, id));+ if (messages.length > page) {+ messages = List.unmodifiable(messages.sublist(messages.length - page));+ before = SuperTabPage.of(messages.first);+ }+ if (messages.isNotEmpty && _holds(reader, id, reader.generation)) {+ _kept[(reader, id)] = _Kept(+ messages,+ before,+ reader.generation,+ reactionSeq,+ );+ while (_kept.length > size) {+ _kept.remove(_kept.keys.first);+ }+ }+ _settle();+ }++ /// Forgets chat [id] of [reader]: the person can no longer read it.+ static void drop(SwarmReader reader, String id) {+ if (_kept.remove((reader, id)) != null) _settle();+ }++ @visibleForTesting+ static int get length => _kept.length;++ @visibleForTesting+ static void clear() {+ _kept.clear();+ _settle();+ }++ /// [reader] may still show chat [id] as read under [generation].+ static bool _holds(SwarmReader reader, String id, int generation) =>+ !reader.accessRevoked &&+ reader.generation == generation &&+ reader.snapshot?.conversation(id) != null;++ /// [reader] read its Swarm, or lost it: what it can no longer show goes.+ static void _check(SwarmReader reader) {+ _kept.removeWhere(+ (key, kept) =>+ key.$1 == reader && !_holds(reader, key.$2, kept.generation),+ );+ _settle();+ }++ /// Each reader with a chat kept is watched, and no other.+ static void _settle() {+ final holding = {for (final (reader, _) in _kept.keys) reader};+ for (final reader in _watched.keys.toList()) {+ if (!holding.contains(reader)) {+ reader.removeListener(_watched.remove(reader)!);+ }+ }+ for (final reader in holding) {+ if (_watched.containsKey(reader)) continue;+ final check = _watched[reader] = () => _check(reader);+ reader.addListener(check);+ }+ }+}++class _Kept {+ _Kept(this.messages, this.before, this.generation, this.reactionSeq);+ final List<SuperTabMessage> messages;+ final SuperTabPage? before;+ final int? reactionSeq;++ /// The reader's [SwarmReader.generation] it was read under.+ final int generation;+}diff --git a/mobile/lib/swarm/swarm_choices.dart b/mobile/lib/swarm/swarm_choices.dartnew file mode 100644index 000000000..695900e86--- /dev/null+++ b/mobile/lib/swarm/swarm_choices.dart@@ -0,0 +1,34 @@+/// How Swarm looks and behaves on the phone, one choice per question asked of+/// the mobile app's owner (2026-10-27). Each is the recommended answer, taken+/// while the owner had not answered (Lead's call); a different answer is a+/// change here, and in the one place each names.+library;++/// 1. The way in. True: Find, and a Swarm mark on Home's title with how many+/// things wait on the person (`swarm_mark.dart`). False: Find only.+const swarmHomeMark = true;++/// 2. The first screen. True: what needs the person across every Swarm comes+/// first, the Swarms under it. False: the Swarms first, needs after them+/// (`swarm_page.dart`).+const swarmNeedsFirst = true;++// 3. A project opens on its project chat: prototype B (Tony, 2026-10-28),+// with nothing under the header and a ⋮ menu at its end (Tony, 2026-10-29):+// Buddy chat (Chat with PM until #2090), and the team's status in words,+// which opens its work (by latest activity, quiet and archived work behind+// "Older") and its team in a sheet (`swarm_project_page.dart`). Tony's answer,+// so no choice is left here.++/// 4. Posting: text, @mentions and files — from the photo library, the camera+/// or Files, by Desktop's limits (Tony, 2026-10-28). False: files are opened,+/// not sent (`swarm_conversation_page.dart`).+const swarmSendsFiles = true;++/// 5. Notices: on the phone while Harness is open; push to a closed app is+/// backend work for later. False posts none (`swarm_session.dart`).+const swarmLocalNotices = true;++/// 6. A decision's answer cannot be changed once sent: one tap holds it this+/// long, with Undo, before it goes. Zero sends at once.+const swarmUndoWindow = Duration(seconds: 3);diff --git a/mobile/lib/swarm/swarm_computers.dart b/mobile/lib/swarm/swarm_computers.dartnew file mode 100644index 000000000..3be74f9dd--- /dev/null+++ b/mobile/lib/swarm/swarm_computers.dart@@ -0,0 +1,83 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/widgets.dart';++import '../core/models.dart';+import '../phone/phone_navigation.dart';+import '../phone/phone_status.dart';+import '../phone/welcome/your_computer.dart';+import '../state/app_state.dart';+import 'swarm_start.dart';++/// The account's computers for Swarm's start screens, from the app's own+/// machine list: each one's name, and whether it is away for real+/// ([phoneMachineAway]) — the socket down and the account's list agreeing.+///+/// Tells only when that changes, or one more computer's socket is up (what+/// a Swarm read waiting for a computer needs, `SwarmInbox.computerUp`) — not+/// at every change of the app's state, which moves with every frame a+/// terminal sends.+class AppSwarmComputers extends ChangeNotifier implements SwarmComputers {+ AppSwarmComputers(this.notifier) {+ notifier.addListener(_changed);+ _changed();+ }++ final AppNotifier notifier;++ List<SwarmComputer>? _computers;+ bool _rechecking = false;++ /// How many computers' sockets are up.+ int _up = 0;++ @override+ List<SwarmComputer>? get computers => _computers;++ @override+ bool get rechecking => _rechecking;++ void _changed() {+ final computers = notifier.machinesAnswered+ ? List<SwarmComputer>.unmodifiable([+ for (final machine in notifier.machineStates.values)+ (+ name: machine.machine.displayName,+ away: phoneMachineAway(machine),+ ),+ ])+ : null;+ final rechecking = notifier.machinesRefreshing;+ final up = notifier.machineStates.values+ .where((m) => m.connectionStatus == ConnectionStatus.connected)+ .length;+ final cameUp = up > _up;+ _up = up;+ if (!cameUp &&+ listEquals(computers, _computers) &&+ rechecking == _rechecking) {+ return;+ }+ _computers = computers;+ _rechecking = rechecking;+ notifyListeners();+ }++ /// The machines tab's Try again: the account's list read again.+ @override+ Future<void> recheck() => notifier.retryMachines();++ /// The machines tab's Add computer (`welcome/your_computer.dart`).+ @override+ void add(BuildContext context) => unawaited(+ Navigator.of(context)+ .push(phoneRoute((_) => YourComputerPage(notifier: notifier))),+ );++ @override+ void dispose() {+ notifier.removeListener(_changed);+ super.dispose();+ }+}diff --git a/mobile/lib/swarm/swarm_connection_notice.dart b/mobile/lib/swarm/swarm_connection_notice.dartnew file mode 100644index 000000000..5fbde6e27--- /dev/null+++ b/mobile/lib/swarm/swarm_connection_notice.dart@@ -0,0 +1,115 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/shared/theme/app_icon_size.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 'swarm_inbox.dart';+import 'swarm_start.dart';+import 'swarm_style.dart';++/// Home's card while no computer answers a Swarm read ([SwarmInbox.noComputer]):+/// the computers connecting, or offline, and Try again. Over what Home has —+/// the Home kept, or rows on their way — never a screen in its place: one+/// once took Home's place after a force-quit, with the Mac connecting all+/// along (owner's iPhone, 2026-10-28).+class SwarmConnectionNotice extends StatefulWidget {+ const SwarmConnectionNotice({+ super.key,+ required this.inbox,+ required this.computers,+ });++ final SwarmInbox inbox;++ /// The account's computers; null outside the shell, read as offline.+ final SwarmComputers? computers;++ @override+ State<SwarmConnectionNotice> createState() => _SwarmConnectionNoticeState();+}++class _SwarmConnectionNoticeState extends State<SwarmConnectionNotice> {+ /// Try again is looking: for the computers, then the Swarms through them.+ bool _looking = false;++ Future<void> _tryAgain() async {+ if (_looking) return;+ setState(() => _looking = true);+ try {+ await widget.computers?.recheck();+ await widget.inbox.refresh();+ } catch (_) {+ // Nothing found: the card stays, ready to try again.+ } finally {+ if (mounted) setState(() => _looking = false);+ }+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: Listenable.merge([widget.inbox, ?widget.computers]),+ builder: (context, _) {+ AppTheme.watch(context);+ final computers = widget.computers;+ // One not away for real is on its way back: its socket redialling.+ final connecting =+ computers?.computers?.any((computer) => !computer.away) ?? false;+ return SwarmGroup(+ key: const ValueKey('swarm-connection'),+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.m,+ AppSpace.m,+ AppSpace.xs,+ AppSpace.m,+ ),+ child: Row(+ children: [+ Icon(+ connecting+ ? LucideIcons.monitor300+ : LucideIcons.monitorOff300,+ size: AppIconSize.besideText,+ color: AppPalette.textSecondary,+ ),+ const SizedBox(width: AppSpace.m),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ connecting+ ? 'Connecting to your computers…'+ : 'Your computers are offline.',+ style: AppType.label(color: AppPalette.textPrimary),+ ),+ Text(+ widget.inbox.swarms.isEmpty+ ? 'Turn one on and open Harness.'+ : 'Showing your last update.',+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ],+ ),+ ),+ SwarmButton(+ label: 'Try again',+ style: SwarmButtonStyle.link,+ busy: _looking || (computers?.rechecking ?? false),+ busyLabel: 'Looking…',+ onPressed: () => unawaited(_tryAgain()),+ ),+ ],+ ),+ ),+ ],+ );+ },+ );+}diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartnew file mode 100644index 000000000..5f344c5cb--- /dev/null+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -0,0 +1,914 @@+import 'dart:async';++import 'package:dio/dio.dart' show CancelToken;+import 'package:flutter/foundation.dart';++import 'model.dart';+import 'swarm_chat_cache.dart';+import 'swarm_outgoing_files.dart';+import 'swarm_reader.dart';+import 'swarm_request.dart';++/// One conversation on the phone: its messages and what the person posts to+/// it — the desktop's `SuperTabController` messages and composer, for one+/// conversation at a time.+///+/// Messages are read as the latest page when opened, older pages on demand,+/// and new ones when the Swarm's read says the conversation moved past the+/// last one shown (`lastMessageSequence`): no read of its own while nothing+/// was posted. Keep the [reader] shown while this is on screen. A chat read+/// before shows at once what was read then ([SwarmChatCache]) and reads on+/// from it.+///+/// A conversation the Swarm's read no longer has hides its messages at once+/// and is asked for by id, as a closed one is in no full read; one it never+/// had is asked for while its messages are read. One the person cannot read+/// keeps nothing here: messages, draft and a post not confirmed.+class SwarmConversation extends ChangeNotifier {+ /// [shown] and [heldAt] as they are from the start, so what it kept is+ /// read only as far as it is seen.+ SwarmConversation(+ this.reader,+ this.id, {+ this.uploadTimeout = const Duration(minutes: 2),+ this._shown = true,+ this._heldAt,+ }) {+ _listed = conversation != null;+ if (SwarmChatCache.take(reader, id) case final kept?) {+ messages = kept.messages;+ _before = kept.before;+ _reactionSeq = kept.reactionSeq;+ _read = _kept = true;+ _markRead();+ }+ reader.addListener(_swarmChanged);+ reader.reads.addListener(_swarmChanged);+ files.addListener(_filesChanged);+ }++ final SwarmReader reader;+ final String id;++ /// How long an upload may go without a byte moving before the send gives up.+ final Duration uploadTimeout;++ /// The files waiting to go with the next post. They stay in memory, and go+ /// when the chat closes: only what the person typed is kept, and only while+ /// the chat is open.+ final files = SwarmOutgoingFiles();++ /// The files of a post are on their way to the backend, before the post.+ bool uploading = false;++ /// Oldest first.+ List<SuperTabMessage> messages = const [];++ /// On screen, no other screen covers it and Harness is in front: what it+ /// shows is read ([SwarmReader.readMarks]), now and as new messages come.+ bool get shown => _shown;+ bool _shown;+ set shown(bool value) {+ if (_shown == value) return;+ _shown = value;+ _markRead();+ }++ /// While the person reads back, the newest message they saw at the foot,+ /// or the one a notice opened the chat at: those after it are unseen and+ /// unread until they go down to them. Null at the foot.+ String? get heldAt => _heldAt;+ String? _heldAt;+ set heldAt(String? value) {+ if (_heldAt == value) return;+ _heldAt = value;+ _markRead();+ }++ /// Read through the newest message seen, while it is [shown]: [heldAt]+ /// once it is read, else the last.+ void _markRead() {+ if (!_shown) return;+ final held = _heldAt;+ final at = held == null ? -1 : messages.lastIndexWhere((m) => m.id == held);+ final seen = held == null+ ? messages.lastOrNull+ : at < 0+ ? null+ : messages[at];+ if (seen != null) reader.readMarks?.markRead(id, seen.sequence);+ }++ /// What the last read or post could not do, as a sentence.+ String? error;++ /// A post is on its way.+ bool sending = false;++ /// Tells the composer what changed in it — the draft, the message it+ /// answers, a post leaving it — while this notifier itself tells the+ /// messages: a letter typed draws none of them again.+ Listenable get composer => _composer;+ final _composer = _Changes();++ SuperTabPage? _before;+ bool _read = false, _lost = false, _disposed = false;++ /// The backend refused the person this conversation: [SwarmChatState.lost]+ /// until a read of it succeeds.+ bool _refused = false;++ /// The Swarm's read has had it since it was last forgotten: one that then+ /// leaves the read hides its messages at once, where one never in it (a+ /// closed one, looked for by id) keeps those read meanwhile.+ late bool _listed;++ /// The messages are those kept from when the chat was last open, not yet+ /// read on from.+ bool _kept = false;++ /// A read told no one ([readBackTo]): told once it is done.+ bool _untold = false;+ Future<void>? _reading, _readingOlder, _locating, _rereading;++ /// The reaction counter ([SuperTabConversation.reactionSeq]) the page+ /// shown was read with: null until a read of that page said it.+ int? _reactionSeq;++ /// The person's reactions on their way, by message and emoji, each adding+ /// (true) or taking back: counted in [reactionsOf] until the backend has+ /// them.+ final _reacting = <(String, SuperTabReactionEmoji), bool>{};++ /// Moves when what was read is dropped: a read asked for before then+ /// answers nothing.+ int _epoch = 0;+ String _draft = '';++ /// Agents mentioned in the draft, by id, with the token that names them.+ final _mentions = <String, String>{};++ /// The post on its way, then — while its answer never came — retried under+ /// the same operation id, so the backend runs it once.+ Map<String, dynamic>? _pending;++ /// What the draft was when [_pending] left it: a refusal puts it back.+ ({+ String draft,+ Map<String, String> mentions,+ SuperTabMessage? replyTo,+ List<SwarmOutgoingFile> files,+ })?+ _sent;++ /// Files already uploaded for the post being sent, with their ids, so a+ /// retry sends the ids rather than uploading the files again.+ final _uploaded = <SwarmOutgoingFile, String>{};++ /// How much of each file going up has gone, from 0 to 1.+ final _progress = <SwarmOutgoingFile, double>{};++ /// The files of the upload under way; [_uploadRun] moves when it is given+ /// up, so an answer that lands after is dropped.+ List<SwarmOutgoingFile>? _uploading;+ int _uploadRun = 0;+ CancelToken? _cancel;++ SuperTabMessage? _replyingTo;++ String get _path =>+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}'+ '/conversations/${Uri.encodeComponent(id)}/messages';++ SuperTabConversation? get conversation => reader.snapshot?.conversation(id);++ /// Earlier messages wait to be read.+ bool get hasOlder => _before != null;++ /// Where the chat stands: the page draws a skeleton, its messages, or+ /// "not open" from it.+ SwarmChatState get state => _refused+ ? SwarmChatState.lost+ : _read+ ? SwarmChatState.loaded+ : _locating != null+ ? SwarmChatState.locating+ : SwarmChatState.loading;++ /// A post was sent and not confirmed: [send] retries it.+ bool get unconfirmed => _pending != null && !sending;++ /// The post on its way or not confirmed, out of the draft: drawn at the+ /// foot of the chat, "Sending…" and then [unconfirmed], until it is read+ /// back.+ ({String text, String? replyTo, List<SwarmOutgoingFile> files})? get pending {+ final command = _pending?['command'] as Map?;+ if (command == null) return null;+ return (+ text: command['text'] as String,+ replyTo: command['replyTo'] as String?,+ files: _sent?.files ?? const [],+ );+ }++ /// The composer may post now: there is text or a file, and no post or+ /// upload is under way.+ bool get canSend =>+ canPost &&+ _pending == null &&+ !sending &&+ !uploading &&+ (_draft.trim().isNotEmpty || files.files.isNotEmpty);++ /// Whether [file] is still on its way to the backend in a send.+ bool isUploading(SwarmOutgoingFile file) =>+ uploading &&+ (_uploading?.contains(file) ?? false) &&+ !_uploaded.containsKey(file);++ /// How much of [file] has gone up, from 0 to 1, while it is going up.+ double? uploadProgress(SwarmOutgoingFile file) => _progress[file];++ /// The message the draft answers: the reply bar over the composer, and the+ /// post's `replyTo`.+ SuperTabMessage? get replyingTo => _replyingTo;+ set replyingTo(SuperTabMessage? message) {+ _replyingTo = message;+ _composer.changed();+ }++ /// The person may post here: a writer of the Swarm, in a conversation that+ /// is not archived.+ bool get canPost {+ final snapshot = reader.snapshot;+ final group = conversation;+ if (snapshot == null || group == null || group.archived) return false;+ return snapshot.people+ .where((p) => p.id == reader.accountId)+ .firstOrNull+ ?.canWrite ??+ false;+ }++ String get draft => _draft;+ set draft(String value) {+ _draft = value;+ _mentions.removeWhere((_, token) => !containsMention(value, token));+ _composer.changed();+ }++ /// Whether [text] names [token] as a word of its own: the desktop's rule.+ static bool containsMention(String text, String token) =>+ RegExp('(?:^|\\s)${RegExp.escape(token)}(?=\$|\\s|[.,!?;:])')+ .hasMatch(text);++ /// The name typed after an @ that ends the draft — what the mention picker+ /// narrows to; null while the draft does not end in one.+ String? get mentionQuery =>+ RegExp(r'(?:^|\s)@(\S*)$').firstMatch(_draft)?.group(1);++ /// [agentId]'s name in place of the @ being typed ([mentionQuery]), as+ /// [mention] adds it.+ void completeMention(String agentId) {+ if (mentionQuery case final query?) {+ _draft = _draft.substring(0, _draft.length - query.length - 1);+ }+ mention(agentId);+ }++ /// Adds [agentId]'s name to the draft; the post goes to it while the name+ /// stays in the text.+ void mention(String agentId) {+ final snapshot = reader.snapshot;+ if (snapshot == null) return;+ final token = '@${snapshot.agentName(agentId)}';+ final spaced = _draft.isEmpty || RegExp(r'\s$').hasMatch(_draft);+ _draft = '$_draft${spaced ? '' : ' '}$token ';+ _mentions[agentId] = token;+ _composer.changed();+ }++ /// The agents a post can mention: those in this conversation.+ List<SuperTabAgent> get mentionable {+ final snapshot = reader.snapshot;+ final group = conversation;+ if (snapshot == null || group == null) return const [];+ return [for (final agentId in group.agentIds) ?snapshot.agent(agentId)];+ }++ /// The Swarm was read, changed or not.+ void _swarmChanged() {+ if (_disposed) return;+ if (reader.accessRevoked) {+ _lose();+ return;+ }+ if (reader.snapshot == null) return;+ final group = conversation;+ if (group == null) {+ if (_listed) {+ _listed = false;+ if (messages.isNotEmpty || _read) {+ _forget();+ notifyListeners();+ }+ }+ // Asked for by id until it is known unreadable; an ask that failed is+ // made again at the Swarm's next read.+ if (!_lost) unawaited(_locate());+ return;+ }+ _listed = true;+ if (_lost) _lost = _refused = false;+ final tail = messages.lastOrNull?.sequence ?? 0;+ if (!_read || group.lastMessageSequence > tail) {+ unawaited(load());+ } else if (_reactionSeq case final seq? when group.reactionSeq > seq) {+ // A reaction changed on a message already shown, here or on another+ // device.+ unawaited(_reread());+ }+ }++ /// Asks the reader for this conversation by id: a closed one comes back,+ /// and [_swarmChanged] reads it; one the person cannot read is lost.+ Future<void> _locate() => _locating ??= () async {+ try {+ if (!await reader.loadConversation(id) && !_disposed) {+ _lost = true;+ _lose();+ }+ } catch (_) {+ // Not known either way: asked again at the Swarm's next read.+ }+ }().whenComplete(() => _locating = null);++ /// Drops the messages read, and the answer of any read under way.+ void _forget() {+ messages = const [];+ _before = null;+ _read = false;+ _epoch++;+ _reading = null;+ _readingOlder = null;+ _rereading = null;+ _reactionSeq = null;+ }++ /// The person cannot read this conversation: nothing of it stays, here or+ /// kept for the next open.+ void _lose() {+ SwarmChatCache.drop(reader, id);+ final held =+ !_refused ||+ messages.isNotEmpty ||+ _read ||+ _draft.isNotEmpty ||+ _pending != null ||+ _replyingTo != null ||+ error != null;+ _refused = true;+ _forget();+ _draft = '';+ _mentions.clear();+ _pending = null;+ _sent = null;+ _replyingTo = null;+ _reacting.clear();+ error = null;+ if (held) _tell();+ }++ /// The latest page the first time, then what came after the newest shown;+ /// a conversation the Swarm's read does not have is asked for by id at the+ /// same time. Joins a read under way.+ Future<void> load() {+ if (_disposed) return Future.value();+ final locating = reader.snapshot != null && conversation == null+ ? _locate()+ : null;+ var reading = _reading;+ if (reading == null) {+ late final Future<void> read;+ read = _load(older: false).whenComplete(() {+ if (identical(_reading, read)) _reading = null;+ });+ reading = _reading = read;+ }+ return locating == null ? reading : Future.wait([locating, reading]);+ }++ /// The page before the oldest shown.+ Future<void> loadOlder() => _older(tell: true);++ /// Reads earlier pages until [messageId] is among the messages, the first+ /// one is reached or [pages] were read, and tells the chat once at the end+ /// rather than at each page: a quote followed to its original draws the+ /// chat once. True once the message is there.+ Future<bool> readBackTo(String messageId, {int pages = 50}) async {+ bool has() => messages.any((m) => m.id == messageId);+ var read = 0;+ try {+ while (!_disposed && !has() && hasOlder && read < pages) {+ await _older(tell: false);+ read++;+ if (error != null) break;+ }+ } finally {+ if (_untold && !_disposed) {+ _untold = false;+ notifyListeners();+ }+ }+ return has();+ }++ /// Reads the page shown again for its reaction counts; joins a read of it+ /// under way.+ Future<void> _reread() {+ if (_disposed) return Future.value();+ if (_rereading case final reading?) return reading;+ late final Future<void> reading;+ reading = _load(older: false, again: true).whenComplete(() {+ if (identical(_rereading, reading)) _rereading = null;+ });+ return _rereading = reading;+ }++ Future<void> _older({required bool tell}) {+ if (!hasOlder) return Future.value();+ if (_readingOlder case final reading?) return reading;+ late final Future<void> reading;+ reading = _load(older: true, tell: tell).whenComplete(() {+ if (identical(_readingOlder, reading)) _readingOlder = null;+ });+ return _readingOlder = reading;+ }++ /// One page: the one before the oldest shown, else what came after the+ /// newest — or, with [latest] or none shown, the latest page; with [again],+ /// the page that ends at the newest shown. Tells the chat what changed+ /// unless [tell] is false, which leaves it [_untold].+ Future<void> _load({+ required bool older,+ bool latest = false,+ bool again = false,+ bool tell = true,+ }) async {+ final epoch = _epoch;+ var reacted = false;+ try {+ final tail = latest ? null : messages.lastOrNull?.sequence;+ final before = _before;+ final query = older+ ? '?before=${before!.sequence}'+ '&beforeId=${Uri.encodeQueryComponent(before.id)}'+ : tail == null+ ? ''+ : again+ ? '?before=${tail + 1}'+ : '?after=$tail';+ final answer = superTabMap(await reader.request('GET', '$_path$query'));+ if (_disposed || epoch != _epoch) return;+ final incoming = [+ for (final row in answer['messages'] as List)+ SuperTabMessage.fromJson(superTabMap(row)),+ ];+ if (incoming.any((m) => m.conversationId != id)) {+ throw const FormatException('A different conversation was returned.');+ }+ if (!older && !again && _kept) {+ _kept = false;+ // More than a page came after what was kept: the latest page, as a+ // first open reads it, where reading on would leave a gap.+ if (tail != null && answer['next'] != null) {+ await _load(older: false, latest: true, tell: tell);+ return;+ }+ }+ // A message read again as it was stays the one shown, and a read that+ // brings nothing new tells no one: the chat draws nothing again.+ final byId = latest+ ? <String, SuperTabMessage>{}+ : {for (final m in messages) m.id: m};+ var changed = !_read || error != null || _refused || latest;+ for (final m in incoming) {+ if (byId[m.id] case final shown? when _same(shown, m)) continue;+ byId[m.id] = m;+ changed = true;+ }+ if (changed) {+ messages = List.unmodifiable(+ byId.values.toList()..sort(superTabMessageOrder),+ );+ }+ if (older || !_read || latest) {+ final before = SuperTabPage.read(answer['next']);+ changed |=+ before?.sequence != _before?.sequence || before?.id != _before?.id;+ _before = before;+ }+ // The counter the page shown was read with; a read of what came after+ // it that says a reaction changed since reads that page again.+ if ((answer['reactionSeq'] as num?)?.toInt() case final seq?+ when !older) {+ if (again || tail == null) {+ _reactionSeq = seq;+ } else {+ reacted = seq > (_reactionSeq ?? -1);+ }+ }+ _read = true;+ _refused = false;+ error = null;+ if (!older) _markRead();+ if (!changed) {+ if (reacted) await _reread();+ return;+ }+ } on SuperTabFailure catch (failure) {+ if (_disposed || epoch != _epoch) return;+ if (const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) _lose();+ error = failure.message;+ } catch (_) {+ if (_disposed || epoch != _epoch) return;+ error = 'Could not load messages. Try again.';+ }+ if (tell) {+ notifyListeners();+ } else {+ _untold = true;+ }+ if (reacted) await _reread();+ }++ /// Posts the draft and its [files], to the agents mentioned in it and as a+ /// reply to [replyingTo] — or, while a post is [unconfirmed], sends that one+ /// again. The files go up first, one by one, the draft and the files staying+ /// in the composer meanwhile; then the post leaves the draft at once, with+ /// the files, and shows as [pending] until it is read back. True once the+ /// backend took it.+ Future<bool> send() async {+ if (sending || uploading || _disposed || !canPost) return false;+ var pending = _pending;+ if (pending == null) {+ final outgoing = files.files;+ if ((_draft.trim().isEmpty && outgoing.isEmpty) || conversation == null) {+ return false;+ }+ final ids = await _uploadAll(outgoing);+ if (ids == null || _disposed) return false;+ pending = _compose(ids);+ if (pending == null) return false;+ _sent = (+ draft: _draft,+ mentions: Map.of(_mentions),+ replyTo: _replyingTo,+ files: outgoing,+ );+ _draft = '';+ _mentions.clear();+ _replyingTo = null;+ // Only what goes with this post: more may have been added meanwhile.+ for (final file in outgoing) {+ files.remove(file);+ }+ }+ _pending = pending;+ sending = true;+ error = null;+ _tell();+ try {+ await reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ body: pending,+ );+ } on SuperTabFailure catch (failure) {+ // A definitive refusal made no change: the text goes back to the draft+ // to correct. A lost answer keeps its receipt, so a retry is the same+ // post.+ final status = failure.statusCode;+ if (status >= 400 && status < 500 && status != 408 && status != 429) {+ // A refusal of the files themselves sends them up once more; one of+ // the post (a mention, a recipient) leaves them uploaded.+ if (failure.code.contains('ATTACHMENT')) {+ for (final file in _sent?.files ?? const <SwarmOutgoingFile>[]) {+ _uploaded.remove(file);+ }+ }+ _pending = null;+ _restore();+ }+ error = failure.message;+ return false;+ } catch (_) {+ error = 'Your message is not confirmed. Send again to check it.';+ return false;+ } finally {+ sending = false;+ if (!_disposed) _tell();+ }+ for (final file in _sent?.files ?? const <SwarmOutgoingFile>[]) {+ _uploaded.remove(file);+ }+ unawaited(reader.refresh());+ // Shown as on its way until the read that brings it back.+ await load();+ if (_disposed || !identical(_pending, pending)) return true;+ _pending = null;+ _sent = null;+ _tell();+ return true;+ }++ /// Uploads each of [outgoing] that has not gone up yet and returns their+ /// ids, or null with [error] set when one could not. The draft and the+ /// files stay where they are.+ Future<List<String>?> _uploadAll(List<SwarmOutgoingFile> outgoing) async {+ if (outgoing.isEmpty) return const [];+ final run = ++_uploadRun;+ uploading = true;+ error = null;+ _uploading = outgoing;+ _uploaded.removeWhere((file, _) => !outgoing.contains(file));+ _tell();+ try {+ final ids = <String>[];+ for (final file in outgoing) {+ var id = _uploaded[file];+ if (id == null) {+ final answer = await _uploadFile(file);+ if (run != _uploadRun) return null;+ id = superTabMap(answer['attachment'])['id'] as String;+ _uploaded[file] = id;+ _progress.remove(file);+ _composer.changed();+ }+ ids.add(id);+ }+ return ids;+ } catch (failure) {+ if (!_disposed && run == _uploadRun) {+ error = failure is SuperTabFailure+ ? failure.message+ : failure is TimeoutException+ ? 'The upload stopped moving. Try again.'+ : 'Could not upload ${outgoing.length == 1 ? 'the file' : 'the files'}. Try again.';+ }+ return null;+ } finally {+ if (run == _uploadRun) {+ uploading = false;+ _uploading = null;+ _progress.clear();+ if (!_disposed) _tell();+ }+ }+ }++ /// Sends [file] to the backend and returns its attachment. Gives up when no+ /// byte has moved for [uploadTimeout], or when the upload is given up.+ Future<Map<String, dynamic>> _uploadFile(SwarmOutgoingFile file) async {+ final token = _cancel = CancelToken();+ Timer? watchdog;+ var stalled = false;+ void watch() {+ watchdog?.cancel();+ watchdog = Timer(uploadTimeout, () {+ stalled = true;+ token.cancel('stalled');+ });+ }++ watch();+ try {+ // The token also ends a transport that ignores it.+ return await Future.any([+ reader.upload(+ tabId: reader.tabId,+ conversationId: id,+ name: file.name,+ mime: swarmMimeForName(file.name),+ bytes: file.bytes,+ cancel: token,+ onProgress: (sent) {+ if (token.isCancelled) return;+ watch();+ _progress[file] = sent;+ _composer.changed();+ },+ ),+ token.whenCancel.then<Map<String, dynamic>>(+ (cancelled) => throw cancelled,+ ),+ ]);+ } catch (_) {+ if (stalled) throw TimeoutException('The upload stopped moving.');+ rethrow;+ } finally {+ watchdog?.cancel();+ }+ }++ /// Gives up the files on their way: the composer is free again, and the+ /// draft and the files stay.+ void cancelUpload() {+ if (!uploading) return;+ _cancel?.cancel('given up');+ _uploadRun++;+ uploading = false;+ _uploading = null;+ _progress.clear();+ if (!_disposed) _tell();+ }++ /// Taking a file off while the files go up gives the upload up.+ void _filesChanged() {+ final going = _uploading;+ if (uploading && going != null && !files.files.toSet().containsAll(going)) {+ cancelUpload();+ }+ _composer.changed();+ }++ /// [message]'s counts as the person sees them: their own reaction on its+ /// way already counted, or already taken back.+ List<SuperTabReactionCount> reactionsOf(SuperTabMessage message) {+ var counts = message.reactions;+ for (final MapEntry(key: (messageId, emoji), value: on)+ in _reacting.entries) {+ if (messageId == message.id) counts = _toggled(counts, emoji, on);+ }+ return counts;+ }++ /// [counts] with the person's [emoji] added ([on]) or taken back.+ List<SuperTabReactionCount> _toggled(+ List<SuperTabReactionCount> counts,+ SuperTabReactionEmoji emoji,+ bool on,+ ) {+ final me = (kind: 'person', id: reader.accountId);+ final was = counts.where((r) => r.emoji == emoji).firstOrNull?.by;+ final by = [...?was?.where((who) => who != me), if (on) me];+ return List.unmodifiable(+ [+ for (final r in counts)+ if (r.emoji != emoji) r,+ if (by.isNotEmpty) SuperTabReactionCount(emoji, by),+ ]..sort((a, b) => a.emoji.index.compareTo(b.emoji.index)),+ );+ }++ /// Adds the person's [emoji] to [message], or takes it back when it is+ /// already theirs (the desktop's `react`): counted at once, sent, then the+ /// page shown is read again so the counts are the backend's. A refusal+ /// takes it back and says why in [error]. True once the backend took it.+ Future<bool> react(+ SuperTabMessage message,+ SuperTabReactionEmoji emoji,+ ) async {+ final key = (message.id, emoji);+ if (_disposed || !canPost || _reacting.containsKey(key)) return false;+ final on = !reactionsOf(message)+ .any((r) => r.emoji == emoji && r.includes('person', reader.accountId));+ _reacting[key] = on;+ error = null;+ notifyListeners();+ String? refused;+ try {+ await reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ body: {+ 'operationId': superTabOperationId(),+ 'command': {+ 'type': 'message.react',+ 'conversationId': id,+ 'messageId': message.id,+ 'emoji': emoji.key,+ 'on': on,+ },+ },+ );+ } on SuperTabFailure catch (failure) {+ refused = failure.message;+ } catch (_) {+ refused = 'Your reaction did not go through. Try again.';+ }+ if (refused == null && !_disposed) {+ // A read of the page begun before the backend had it would not show+ // it: the read that counts it starts after.+ if (_rereading case final reading?) await reading;+ await _reread();+ }+ if (_disposed) return refused == null;+ _reacting.remove(key);+ if (refused != null) error = refused;+ notifyListeners();+ return refused == null;+ }++ /// A post moved between the composer and the messages: both are told.+ void _tell() {+ notifyListeners();+ _composer.changed();+ }++ /// What a row draws of a message, the same in [a] as in [b].+ static bool _same(SuperTabMessage a, SuperTabMessage b) =>+ a.sequence == b.sequence &&+ a.text == b.text &&+ a.replyTo == b.replyTo &&+ a.authorName == b.authorName &&+ a.createdAt == b.createdAt &&+ a.attachments.length == b.attachments.length &&+ _sameReactions(a.reactions, b.reactions);++ static bool _sameReactions(+ List<SuperTabReactionCount> a,+ List<SuperTabReactionCount> b,+ ) {+ if (a.length != b.length) return false;+ for (var i = 0; i < a.length; i++) {+ if (a[i].emoji != b[i].emoji || !listEquals(a[i].by, b[i].by)) {+ return false;+ }+ }+ return true;+ }++ /// A refused post's text back in the draft, before anything typed since.+ void _restore() {+ final sent = _sent;+ _sent = null;+ if (sent == null) return;+ _draft = _draft.trim().isEmpty ? sent.draft : '${sent.draft}\n$_draft';+ _mentions.addAll(sent.mentions);+ _replyingTo ??= sent.replyTo;+ if (sent.files.isNotEmpty) {+ final since = files.files;+ files+ ..clear()+ ..add([...sent.files, ...since]);+ }+ }++ Map<String, dynamic>? _compose([List<String> attachmentIds = const []]) {+ final text = _draft.trim();+ final group = conversation;+ if ((text.isEmpty && attachmentIds.isEmpty) || group == null) return null;+ return {+ 'operationId': superTabOperationId(),+ 'command': {+ 'type': 'message.send',+ 'conversationId': id,+ 'text': text,+ 'replyTo': _replyingTo?.id,+ 'recipientIds': [+ for (final MapEntry(key: agentId, value: token) in _mentions.entries)+ if (containsMention(text, token) &&+ group.agentIds.contains(agentId))+ agentId,+ ],+ if (attachmentIds.isNotEmpty) 'attachmentIds': attachmentIds,+ },+ };+ }++ @override+ void dispose() {+ _disposed = true;+ _cancel?.cancel('closed');+ _uploadRun++;+ files+ ..removeListener(_filesChanged)+ ..clear()+ ..dispose();+ // Shown at once when opened again, while the person can still read it.+ if (_read && !_refused) {+ SwarmChatCache.keep(+ reader,+ id,+ messages: messages,+ before: _before,+ reactionSeq: _reactionSeq,+ );+ }+ reader.removeListener(_swarmChanged);+ reader.reads.removeListener(_swarmChanged);+ _composer.dispose();+ super.dispose();+ }+}++/// Where a chat stands: its first page on its way, looked for by id (one no+/// full read of its Swarm has), read, or not open to the person — said only+/// once the backend refused it.+enum SwarmChatState { loading, locating, loaded, lost }++/// A notifier told from outside it: the conversation's [composer].+class _Changes extends ChangeNotifier {+ void changed() => notifyListeners();+}diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartnew file mode 100644index 000000000..c4d2a0a7e--- /dev/null+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -0,0 +1,2402 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/core/app_settings.dart';+import 'package:harness_mobile/phone/composing_keyboard.dart';+import 'package:harness_mobile/phone/phone_navigation.dart';+import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/phone/tty_controls.dart';+import 'package:harness_mobile/shared/theme/app_icon_size.dart';+import 'package:harness_mobile/shared/theme/app_ink.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/shared/widgets/skeleton.dart';++import 'identity.dart';+import 'model.dart';+import 'swarm_attach.dart';+import 'swarm_buddy.dart';+import 'swarm_buddy_chat.dart';+import 'swarm_choices.dart';+import 'swarm_conversation.dart';+import 'swarm_face.dart';+import 'swarm_file_picker.dart';+import 'swarm_outgoing_files.dart';+import 'swarm_inbox.dart';+import 'swarm_message_row.dart';+import 'swarm_need_rows.dart';+import 'swarm_profile_sheet.dart';+import 'swarm_project_page.dart';+import 'swarm_reactions.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';+import 'swarm_voice.dart';+import 'team_glance.dart';++/// Opens [conversationId] of Swarm [swarmId] over the current page.+void openSwarmConversation(+ BuildContext context,+ String swarmId,+ String conversationId,+) => unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => SwarmConversationPage(+ swarmId: swarmId,+ conversationId: conversationId,+ ),+ listensForItself: true,+ ),+ ),+);++/// Opens this app's page in the phone's Settings, where a refused camera is turned back on.+/// Replaced in tests, where there is no Settings to open.+@visibleForTesting+Future<bool> Function() openSwarmSettings = openAppSettings;++/// One conversation: its messages, newest at the foot, older ones on demand —+/// each with who wrote it, their role and when, follow-ups grouped, a reply's+/// quote leading to its original; the decisions asked of the person in it;+/// and, for a writer, a composer that posts text, as a reply or with+/// @mentions of the conversation's agents picked as they are typed, and with+/// files from the photo library, the camera or Files ([swarmSendsFiles]). A+/// post shows at once and says when it is not confirmed.+class SwarmConversationPage extends StatefulWidget {+ const SwarmConversationPage({+ super.key,+ required this.swarmId,+ required this.conversationId,+ this.title,+ this.subtitle,+ this.action,+ this.below,+ this.messageId,+ this.decisionId,+ this.mention,+ });++ final String swarmId, conversationId;+ final String? messageId, decisionId;++ /// An agent to @mention in the draft as the chat opens: the PM, as its+ /// private line is answered in the project chat.+ final String? mention;++ /// The header's lines in place of the chat's name and its project: a+ /// project's chat is its project's screen, under the project's name and+ /// who is in it (`swarm_project_page.dart`).+ final String? title, subtitle;++ /// At the header's end: a project's ⋮ menu. The person's own Buddy chat+ /// has its own, Remove Buddy, when this is null.+ final Widget? action;++ /// Under the header: a project's team in one line.+ final Widget? below;++ @override+ State<SwarmConversationPage> createState() => _SwarmConversationPageState();+}++class _SwarmConversationPageState extends State<SwarmConversationPage>+ with WidgetsBindingObserver {+ SwarmSession? _session;+ SwarmConversation? _conversation;+ final _text = TextEditingController();+ final _focus = FocusNode(debugLabel: 'Swarm composer');++ /// What the last pick left out, or why it could not pick, over the files.+ final _attachNote = ValueNotifier<String?>(null);++ /// A picker is up: one at a time.+ bool _picking = false;++ /// The composer's mic, while the shell can hear one ([SwarmScope.voiceOf]).+ SwarmVoice? _voice;+ final _scroll = ScrollController();++ /// The message whose actions are open (Reply, Copy), by a tap on it.+ String? _acting;++ /// A quote followed to its original: the original being brought into view,+ /// the one lit for a moment on arrival, the search through earlier pages,+ /// and what to say when it cannot be found.+ String? _target, _lit;+ String? _decisionTarget;+ bool _noticeHandled = false;+ final _targetKey = GlobalKey();+ Timer? _litTimer;+ bool _finding = false;+ String? _note;++ /// Earlier messages are read on their own as the person nears the top;+ /// "Earlier messages" is offered only once that read failed.+ bool _loadingOlder = false, _olderFailed = false;++ /// No other screen covers this one.+ bool _visible = true;++ /// Harness is in front, as the shell counts it (resumed, or the app+ /// switcher over it).+ bool _inFront = _isInFront(WidgetsBinding.instance.lifecycleState);++ static bool _isInFront(AppLifecycleState? state) =>+ state == null ||+ state == AppLifecycleState.resumed ||+ state == AppLifecycleState.inactive;++ /// What it shows is seen: read ([SwarmConversation.shown]).+ bool get _seen => _visible && _inFront;++ bool _watching = false;++ /// What the chat draws of its Swarm's read, told to the page only when+ /// something drawn changed ([_ChatView]).+ final _view = ValueNotifier<_ChatView?>(null);++ /// The newest message shown when the person began reading back: those+ /// after it wait below, so what they read stays where it is, and the pill+ /// says how many. Null at the foot.+ final _held = ValueNotifier<String?>(null);++ /// Each entry's row as last built, with what it was built from ([_row]).+ final _rows = <String, ({Object inputs, Widget row})>{};++ /// What [_shown] was made from; the messages by id, and each entry's+ /// place in [_shown] by its key.+ Object? _madeFrom;+ var _byId = <String, SuperTabMessage>{};+ var _placeOf = <String, int>{};++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ _text.addListener(_typed);+ _scroll.addListener(_scrolled);+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ _inFront = _isInFront(state);+ _conversation?.shown = _seen;+ }++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ // Off while a screen pushed over this one covers it.+ _visible = TickerMode.valuesOf(context).enabled;+ _conversation?.shown = _seen;+ if (_voice == null) {+ if (SwarmScope.voiceOf(context) case final create?) {+ _voice = SwarmVoice(+ create: create,+ dictation: SwarmScope.dictationOf(context),+ draft: () => _conversation?.draft ?? '',+ write: (text) => _conversation?.draft = text,+ send: _spoken,+ );+ }+ }+ // A covered chat hears nothing: its take goes with it.+ if (!_visible) _voice?.hide();+ final session = SwarmScope.of(context);+ if (session == _session) {+ _watch();+ return;+ }+ _close();+ _session = session?..enter();+ session?.inbox.addListener(_attach);+ _attach(rebuild: false);+ }++ /// Opens the conversation once its Swarm has been read: at once, or when+ /// the account's Swarms are first read — a notice tapped at launch opens+ /// this page before then. Until then the chat is a skeleton, or not open+ /// once the Swarms read do not have its own.+ void _attach({bool rebuild = true}) {+ final session = _session;+ if (session == null || _conversation != null) return;+ final reader = session.inbox.reader(widget.swarmId);+ if (reader == null) {+ if (rebuild && mounted) setState(() {});+ return;+ }+ session.inbox.removeListener(_attach);+ // Set before what the chat kept is shown, so it is read only as far as+ // it is seen: opened at a message, through it until the person goes+ // down to the foot.+ final c = _conversation = SwarmConversation(+ reader,+ widget.conversationId,+ shown: _seen,+ heldAt: widget.messageId ?? _held.value,+ );+ c.composer.addListener(_drafted);+ if (widget.mention case final agentId?) c.mention(agentId);+ reader.addListener(_see);+ session.inbox.addListener(_see);+ _see();+ _watch();+ unawaited(+ c.load().then((_) {+ if (!mounted || _conversation != c || _noticeHandled) return;+ if (widget.messageId case final messageId?) {+ _noticeHandled = true;+ unawaited(_jumpTo(c, messageId));+ }+ }),+ );+ if (rebuild && mounted) setState(() {});+ }++ /// Its Swarm is watched while the chat is open and visible, so it is read+ /// every few seconds only then ([SwarmSession.watch]).+ void _watch() {+ final watch = _conversation != null && _visible;+ if (watch == _watching) return;+ _watching = watch;+ if (watch) {+ _session?.watch(widget.swarmId);+ } else {+ _session?.unwatch(widget.swarmId);+ }+ }++ /// The chat's [_ChatView] made again from what its Swarm's read and asks+ /// say now.+ void _see() {+ final session = _session, c = _conversation;+ if (session == null || c == null) return;+ final view = _view.value = _ChatView.of(session, c, _view.value);+ _seeBuddy(c, view.buddyProject);+ final decisionId = widget.decisionId;+ if (!_noticeHandled &&+ decisionId != null &&+ _view.value!.decisions.any((need) => need.decision.id == decisionId)) {+ _noticeHandled = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || _conversation != c) return;+ setState(() => _decisionTarget = decisionId);+ _reveal(c, decisionId, 0);+ });+ }+ }++ /// What the person does to their Buddy from its chat, while this is their+ /// own Buddy chat in [project] ([SwarmBuddyActions]).+ SwarmBuddyActions? _buddy;++ void _seeBuddy(SwarmConversation c, String? project) {+ final kept = _buddy;+ if (kept?.reader == c.reader && kept?.projectId == project) return;+ kept?.dispose();+ _buddy = project == null ? null : SwarmBuddyActions(c.reader, project);+ }++ void _close() {+ final session = _session;+ session?.inbox+ ?..removeListener(_attach)+ ..removeListener(_see);+ if (_conversation case final c?) {+ c.composer.removeListener(_drafted);+ c.reader.removeListener(_see);+ c.dispose();+ }+ _buddy?.dispose();+ _buddy = null;+ _rows.clear();+ _madeFrom = null;+ if (_watching) session?.unwatch(widget.swarmId);+ _watching = false;+ _conversation = null;+ session?.leave();+ _session = null;+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ _close();+ _voice?.dispose();+ _view.dispose();+ _held.dispose();+ _litTimer?.cancel();+ _text.dispose();+ _focus.dispose();+ _attachNote.dispose();+ _scroll.dispose();+ super.dispose();+ }++ /// What the person typed, into the draft.+ void _typed() {+ final c = _conversation;+ if (c != null && c.draft != _text.text) c.draft = _text.text;+ }++ /// The draft changed under the field — a mention added, a post sent.+ void _drafted() {+ final draft = _conversation?.draft;+ if (draft == null || draft == _text.text) return;+ _text.value = TextEditingValue(+ text: draft,+ selection: TextSelection.collapsed(offset: draft.length),+ );+ }++ /// The second tap on the mic ended a take: what is in the box goes, as Send+ /// would send it. Nothing when the box is empty, the chat is covered, or a+ /// post is already on its way.+ void _spoken() {+ final c = _conversation;+ if (c == null || !_visible || c.draft.trim().isEmpty || !c.canSend) return;+ _send(c);+ }++ /// The composer's +: the sheet, then the picker it names, its files into+ /// [c]'s. A refusal of the camera or photos offers the phone's Settings.+ Future<void> _pickFiles(SwarmConversation c) async {+ if (_picking) return;+ _picking = true;+ try {+ final source = await showSwarmAttachSheet(context);+ if (source == null || !mounted || _conversation != c) return;+ final outcome = await addSwarmPicked(+ c.files,+ source,+ stillWanted: () => mounted && _conversation == c,+ );+ if (!mounted || _conversation != c) return;+ switch (outcome) {+ case SwarmPicked(:final note):+ _attachNote.value = note;+ case SwarmPickFailed(:final message):+ _attachNote.value = message;+ case SwarmPickDenied(:final source):+ _attachNote.value = null;+ if (await showSwarmAccessOff(context, source)) {+ unawaited(openSwarmSettings());+ }+ }+ } finally {+ _picking = false;+ }+ }++ /// How far up the chat the person reads back, past which a message that+ /// arrives waits below instead of pushing up what they read.+ static const _readingBack = 48.0;++ void _scrolled() {+ _nearTop();+ if (!_scroll.hasClients) return;+ final back = _scroll.offset > _readingBack;+ // At the foot all is seen; reading back, only what was seen at the foot+ // before, or the message a notice opened the chat at.+ if (_conversation case final c?) {+ if (!back) {+ c.heldAt = null;+ } else {+ c.heldAt ??= c.messages.lastOrNull?.id;+ }+ }+ if (back == (_held.value != null)) return;+ _held.value = back ? _conversation?.messages.lastOrNull?.id : null;+ }++ /// How close to the oldest message shown the earlier ones start to be+ /// read: a screen's height ahead, so they are there before the person is.+ void _nearTop() {+ final c = _conversation;+ if (c == null ||+ !c.hasOlder ||+ _loadingOlder ||+ _olderFailed ||+ _finding ||+ !_scroll.hasClients) {+ return;+ }+ final position = _scroll.position;+ // The list runs from the foot: what is after the view is above it.+ if (position.extentAfter < position.viewportDimension) {+ unawaited(_loadOlder(c));+ }+ }++ /// Reads the page before the oldest message shown. The list is drawn from+ /// its foot, so what arrives above leaves what the person reads in place.+ Future<void> _loadOlder(SwarmConversation c) async {+ if (_loadingOlder || !c.hasOlder) return;+ setState(() {+ _loadingOlder = true;+ _olderFailed = false;+ });+ final shown = c.messages.length;+ await c.loadOlder();+ if (!mounted || _conversation != c) return;+ setState(() {+ _loadingOlder = false;+ // A read that failed, or brought nothing new while more is said to be+ // there, is not tried again on its own: it would be read over and over.+ _olderFailed =+ c.hasOlder && (c.error != null || c.messages.length == shown);+ });+ }++ /// Sends the draft, back at the foot of the chat where the post shows.+ void _send(SwarmConversation c) {+ _target = null;+ _attachNote.value = null;+ if (_scroll.hasClients && _scroll.offset > 0) {+ unawaited(+ _scroll.animateTo(+ 0,+ duration: const Duration(milliseconds: 250),+ curve: Curves.easeOut,+ ),+ );+ }+ unawaited(_post(c));+ }++ /// Sends [c]'s draft, or its post not confirmed again. Once the backend+ /// took it the keyboard goes down, unless the next message is already being+ /// typed; a post refused or not confirmed keeps it up, to send again.+ Future<void> _post(SwarmConversation c) async {+ final sent = await c.send();+ if (sent && mounted && _conversation == c && c.draft.isEmpty) {+ _focus.unfocus();+ }+ }++ void _reply(SwarmConversation c, SuperTabMessage message) {+ c.replyingTo = message;+ setState(() => _acting = null);+ _focus.requestFocus();+ }++ /// How many earlier pages a quote's original is looked for in: as many as+ /// a tag opens through on the desktop.+ static const _findPages = 50;++ /// Brings [messageId] into view and lights it — read in from earlier pages+ /// when it is further back — or says why it cannot.+ Future<void> _jumpTo(SwarmConversation c, String messageId) async {+ if (_finding) return;+ setState(() {+ _decisionTarget = null;+ _finding = true;+ _note = null;+ });+ // Read back page by page with no redraw between them: the chat is drawn+ // once, with the original among the messages.+ final found = await c.readBackTo(messageId, pages: _findPages);+ if (!mounted || _conversation != c) return;+ setState(() {+ _finding = false;+ _note = found+ ? null+ : c.error != null+ ? "Couldn't read the original message. Try again."+ : c.hasOlder+ ? 'The original message is too far back.'+ : 'The original message is no longer in this chat.';+ if (found) _target = messageId;+ });+ if (!found) {+ // Nothing to read back to: at the foot, all is seen.+ if (!_scroll.hasClients || _scroll.offset <= _readingBack) {+ c.heldAt = null;+ }+ return;+ }+ _reveal(c, messageId, 0);+ _litTimer?.cancel();+ setState(() => _lit = messageId);+ _litTimer = Timer(const Duration(seconds: 2), () {+ if (mounted) setState(() => _lit = null);+ });+ }++ /// The list builds only the rows near what is shown: it jumps near the+ /// target by its place in the list until its row is built, then brings it+ /// to the middle (the desktop's `_revealTarget`).+ void _reveal(SwarmConversation c, String messageId, int attempt) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || (_target != messageId && _decisionTarget != messageId)) {+ return;+ }+ if (_targetKey.currentContext case final row?) {+ unawaited(+ Scrollable.ensureVisible(+ row,+ alignment: 0.5,+ duration: const Duration(milliseconds: 250),+ ),+ );+ return;+ }+ final shown = _shown;+ final index = shown.indexWhere(+ (entry) => _decisionTarget == messageId+ ? entry is _AskEntry && entry.need.decision.id == messageId+ : entry is _MessageEntry && entry.message.id == messageId,+ );+ if (!_scroll.hasClients || index < 0 || attempt > 20) return;+ final position = _scroll.position;+ position.jumpTo(+ (position.maxScrollExtent * (index + 1) / shown.length).clamp(+ 0,+ position.maxScrollExtent,+ ),+ );+ _reveal(c, messageId, attempt + 1);+ });+ WidgetsBinding.instance.scheduleFrame();+ }++ /// What the list draws, newest first: kept for [_reveal] to find a row's+ /// place by.+ List<_Entry> _shown = const [];++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ final session = _session;+ final c = _conversation;+ return Scaffold(+ backgroundColor: tty.ground,+ body: SafeArea(+ child: session == null+ ? Align(+ alignment: Alignment.topLeft,+ child: TtyBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ )+ : c == null+ ? _unopened(context, session, tty)+ : ValueListenableBuilder(+ valueListenable: _view,+ builder: (context, view, _) =>+ _page(context, session, c, view!, tty),+ ),+ ),+ );+ }++ /// Before the account's Swarms are read: a skeleton under a placeholder+ /// header — or, once they are read without this chat's Swarm, not open.+ Widget _unopened(BuildContext context, SwarmSession session, Tty tty) {+ final inbox = session.inbox;+ final error = inbox.error;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ _header(+ context,+ tty,+ title: widget.title ?? (inbox.loaded ? 'Chat' : null),+ project: widget.subtitle,+ action: widget.action,+ ),+ ?widget.below,+ Expanded(+ child: inbox.loaded+ ? _said(_notOpen)+ : error != null+ ? _said(error)+ : const _ChatSkeleton(),+ ),+ ],+ );+ }++ static const _notOpen = 'This chat is not open to you.';++ /// What the chat says in place of its messages.+ Widget _said(String text, {Key? key}) => Padding(+ padding: const EdgeInsets.all(Tty.origin),+ child: Text(+ text,+ key: key,+ style: swarmChatText(15, color: AppPalette.textSecondary),+ ),+ );++ /// The back button, then the chat's name and its project under it — or,+ /// while the chat is not known yet ([title] null), placeholders of their+ /// size — and [action] at its end.+ Widget _header(+ BuildContext context,+ Tty tty, {+ required String? title,+ String? project,+ Widget? action,+ }) => Padding(+ key: const ValueKey('swarm-chat-header'),+ padding: const EdgeInsets.fromLTRB(0, AppSpace.xs, _headerEnd, AppSpace.xs),+ child: Row(+ children: [+ TtyBackButton(onPressed: () => Navigator.of(context).maybePop()),+ Expanded(+ child: title == null+ ? Column(+ key: const ValueKey('swarm-header-placeholder'),+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SkeletonText(+ style: tty.style(+ size: TtySize.title,+ weight: FontWeight.w600,+ ),+ width: 140,+ ),+ SkeletonText(style: swarmChatText(13), width: 72),+ ],+ )+ : Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ title,+ key: const ValueKey('swarm-title'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tty.style(+ size: TtySize.title,+ weight: FontWeight.w600,+ ),+ ),+ if (project != null)+ Text(+ project,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(+ 13,+ color: AppPalette.textSecondary,+ ),+ ),+ ],+ ),+ ),+ // The screen's side margin from its edge: the header's own end+ // inset, and the rest of the margin.+ if (action != null)+ Padding(+ padding: const EdgeInsetsDirectional.only(+ start: AppSpace.s,+ end: AppSpace.screenInset - _headerEnd,+ ),+ child: action,+ ),+ ],+ ),+ );++ /// The header's inset at its end.+ static const _headerEnd = AppSpace.s;++ /// The header and the composer follow [view] — the header [c] too, until+ /// the chat is known; the messages, and what is said under them, follow+ /// [c]; the composer follows what is typed.+ Widget _page(+ BuildContext context,+ SwarmSession session,+ SwarmConversation c,+ _ChatView view,+ Tty tty,+ ) => Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // Placeholders until the chat is known, unless it is not open.+ ListenableBuilder(+ listenable: c,+ builder: (context, _) => _header(+ context,+ tty,+ title:+ widget.title ??+ (view.known || c.state == SwarmChatState.lost+ ? view.title+ : null),+ project: widget.subtitle ?? view.project,+ // The person's own Buddy chat: Remove Buddy.+ action:+ widget.action ??+ switch (_buddy) {+ final buddy? => SwarmBuddyMenuButton(actions: buddy),+ null => null,+ },+ ),+ ),+ ?widget.below,+ if (_buddy case final buddy?) SwarmBuddyBar(actions: buddy),+ Expanded(+ child: Stack(+ children: [+ Positioned.fill(+ child: ListenableBuilder(+ listenable: Listenable.merge([c, _held]),+ builder: (context, _) =>+ _messages(context, session, c, view, tty),+ ),+ ),+ Positioned(+ left: 0,+ right: 0,+ bottom: 8,+ child: ListenableBuilder(+ listenable: Listenable.merge([c, _held]),+ builder: (context, _) => switch (_waiting(c)) {+ 0 => const SizedBox.shrink(),+ final count => Center(+ child: _NewPill(count: count, onTap: _toFoot),+ ),+ },+ ),+ ),+ ],+ ),+ ),+ ListenableBuilder(+ listenable: c,+ builder: (context, _) {+ final note = _finding ? 'Finding the original message…' : _note;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (note != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.s,+ AppSpace.screenInset,+ 0,+ ),+ child: Text(+ note,+ key: const ValueKey('swarm-find-note'),+ style: swarmChatText(13.5, color: AppPalette.textSecondary),+ ),+ ),+ // Unless the body says it already: not open, or no conversation+ // and nothing read.+ if (c.error case final error?+ when c.state != SwarmChatState.lost &&+ (view.known || c.messages.isNotEmpty))+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.s,+ AppSpace.screenInset,+ 0,+ ),+ child: Text(+ error,+ key: const ValueKey('swarm-post-error'),+ style: swarmChatText(13.5, color: tty.red),+ ),+ ),+ ],+ );+ },+ ),+ if (view.canPost)+ ListenableBuilder(+ listenable: Listenable.merge([c.composer, _voice]),+ builder: (context, _) => _composer(c, tty, hint: view.hint),+ )+ else if (view.known)+ Padding(+ padding: const EdgeInsets.all(AppSpace.l),+ child: Text(+ view.archived+ ? 'This chat is archived.'+ : 'You can read this chat, not post in it.',+ key: const ValueKey('swarm-read-only'),+ style: swarmChatText(13.5, color: AppPalette.textSecondary),+ ),+ ),+ ],+ );++ /// Opens [projectId]'s chat with [pmId] mentioned in its draft: the PM's+ /// private line answered where the PM reads, and everyone with it.+ void _answerIn(String projectId, String pmId) => unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => SwarmProjectPage(+ swarmId: widget.swarmId,+ projectId: projectId,+ mention: pmId,+ ),+ listensForItself: true,+ ),+ ),+ );++ /// [m]'s author as a quote names them: the person's own messages are+ /// "You".+ String _quoted(SwarmConversation c, SuperTabMessage m) =>+ !m.fromAgent && m.authorId == c.reader.accountId ? 'You' : _nameOf(c, m);++ /// [m]'s author by name; in the person's own Buddy chat the PM's private+ /// lines read as lines to them, "River (PM) → you": the PM writes there but+ /// cannot read it (#2090).+ String _nameOf(SwarmConversation c, SuperTabMessage m) {+ final name = c.reader.snapshot?.authorName(m) ?? m.authorName;+ return swarmIsPmLine(c.reader, m) ? '$name (PM) → you' : name;+ }++ SwarmLook _lookOf(SwarmConversation c, SuperTabMessage m) =>+ c.reader.snapshot?.authorLook(m) ?? (picture: null, status: null);++ static SwarmLook _agentLook(SuperTabAgent? agent) =>+ (picture: agent?.avatar, status: null);++ /// Who gave a reaction, by name and never by email: "You", an agent's+ /// name, another person's email name.+ String _reactorName(SwarmConversation c, String kind, String id) {+ if (kind == 'person' && id == c.reader.accountId) return 'You';+ final snapshot = c.reader.snapshot;+ if (kind == 'agent') return snapshot?.agentName(id) ?? 'Agent';+ final email = snapshot?.people.where((p) => p.id == id).firstOrNull?.email;+ return email == null ? 'Someone' : superTabPersonName(email);+ }++ /// The reaction picker over message [id]: the pick reacts to the message+ /// as it is by then.+ Future<void> _pickReaction(SwarmConversation c, String id) async {+ SuperTabMessage? shown() => c.messages.where((m) => m.id == id).firstOrNull;+ final message = shown();+ if (message == null) return;+ final emoji = await showSwarmReactionPicker(+ context,+ reactions: c.reactionsOf(message),+ readerId: c.reader.accountId,+ );+ if (emoji == null || !mounted) return;+ if (shown() case final now?) await c.react(now, emoji);+ }++ /// The messages, newest at the foot, with the decisions asked among them.+ /// The entries are made again only when what they are made from changed,+ /// and each row is the one built before while it draws the same ([_row]):+ /// a new message builds its own row alone.+ ///+ /// Until the first page is read, skeleton bubbles; "not open" only once+ /// the backend refused the chat; a chat read with nothing in it says so.+ Widget _messages(+ BuildContext context,+ SwarmSession session,+ SwarmConversation c,+ _ChatView view,+ Tty tty,+ ) {+ final state = c.state;+ if (state == SwarmChatState.lost) return _said(c.error ?? _notOpen);+ if (c.messages.isEmpty && c.pending == null) {+ if (state != SwarmChatState.loaded) {+ // A first read that failed: said under the chat once it is known,+ // here until then.+ if (c.error case final error?) {+ return view.known ? const SizedBox.shrink() : _said(error);+ }+ return const _ChatSkeleton();+ }+ if (view.decisions.isEmpty) {+ return _said(+ 'No messages yet.',+ key: const ValueKey('swarm-chat-empty'),+ );+ }+ }+ final snapshot = c.reader.snapshot;+ final messages = c.messages;+ final from = (messages, view.decisions, c.hasOlder, _held.value);+ if (from != _madeFrom) {+ // Read back: the messages after the newest shown then wait below, and+ // so do decisions asked after it.+ final held = _held.value;+ final at = held == null+ ? -1+ : messages.lastIndexWhere((m) => m.id == held);+ final shown = at < 0 ? messages : messages.sublist(0, at + 1);+ final last = shown.lastOrNull?.createdAt;+ final asks = at < 0 || last == null+ ? view.decisions+ : [+ for (final need in view.decisions)+ if (!(need.decision.createdAt?.isAfter(last) ?? false)) need,+ ];+ _shown = _timeline(shown, asks, hasOlder: c.hasOlder).reversed.toList();+ _byId = {for (final m in messages) m.id: m};+ _placeOf = {for (final (i, entry) in _shown.indexed) _keyOf(entry): i};+ _rows.removeWhere((key, _) => !_placeOf.containsKey(key));+ _madeFrom = from;+ }+ final entries = _shown;+ final byId = _byId;+ final pending = c.pending;+ // A page shorter than the screen never scrolls: look once it is drawn.+ if (c.hasOlder && !_loadingOlder && !_olderFailed) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _nearTop();+ });+ }+ final lead = pending == null ? 0 : 1;++ Widget entry(_Entry entry) {+ final key = _keyOf(entry);+ switch (entry) {+ case _DayEntry(:final day):+ final today = DateUtils.dateOnly(DateTime.now());+ return _row(key, (day, today), () => _Day(day: day, today: today));+ case _MessageEntry(message: final m, :final grouped):+ final reply = m.replyTo == null ? null : byId[m.replyTo];+ final name = _nameOf(c, m);+ final look = _lookOf(c, m);+ final pm = swarmIsPmLine(c.reader, m);+ // "River (PM) → you" says the role already.+ final role = m.fromAgent && !pm ? view.roles[m.authorId] : null;+ // The PM cannot read this chat: its line is answered in the+ // project chat, where everyone reads it (Tony, mockup A, 10-29).+ final answerIn = pm && view.canPost ? view.buddyProject : null;+ final quoted = reply == null ? null : _quoted(c, reply);+ final lit = _lit == m.id, followed = _target == m.id;+ final acting = _acting == m.id;+ final reactions = c.reactionsOf(m);+ return _row(+ key,+ (+ m,+ name,+ swarmLookKey(look),+ role,+ grouped,+ lit,+ followed,+ acting,+ reply,+ quoted,+ view.canPost,+ view.mentions,+ reactions,+ answerIn,+ view.project,+ ),+ () => SwarmMessageRow(+ key: followed ? _targetKey : null,+ message: m,+ name: name,+ look: look,+ role: role,+ mentions: view.mentions,+ grouped: grouped,+ lit: lit,+ followed: followed,+ quote: m.replyTo == null+ ? null+ : SwarmQuote(+ key: ValueKey('swarm-quote-${m.id}'),+ author: quoted,+ text: reply?.text,+ onTap: () => unawaited(_jumpTo(c, m.replyTo!)),+ ),+ actions: acting,+ onTap: () =>+ setState(() => _acting = _acting == m.id ? null : m.id),+ onReply: view.canPost ? () => _reply(c, m) : null,+ onAuthor: m.fromAgent+ ? null+ : () => unawaited(+ showSwarmPerson(+ context,+ swarmId: widget.swarmId,+ personId: m.authorId,+ ),+ ),+ reactions: SwarmReactionBar(+ messageId: m.id,+ reactions: reactions,+ readerId: c.reader.accountId,+ nameOf: (kind, id) => _reactorName(c, kind, id),+ onReact: view.canPost+ ? (emoji) => unawaited(c.react(m, emoji))+ : null,+ ),+ onLongPress: view.canPost+ ? () => unawaited(_pickReaction(c, m.id))+ : null,+ below: answerIn == null+ ? null+ : _AnswerIn(+ key: ValueKey('swarm-answer-in-${m.id}'),+ project: view.project ?? 'the project chat',+ onTap: () => _answerIn(answerIn, m.authorId),+ ),+ ),+ );+ case _AskEntry(:final need, :final grouped):+ final asker = snapshot == null ? null : swarmAsker(snapshot, need);+ final role = asker == null ? null : view.roles[asker.id];+ return _row(+ key,+ (+ need,+ grouped,+ asker?.id,+ role,+ swarmLookKey(_agentLook(asker)),+ _decisionTarget == need.decision.id,+ ),+ () => KeyedSubtree(+ key: _decisionTarget == need.decision.id ? _targetKey : null,+ child: _Ask(+ session: session,+ need: need,+ grouped: grouped,+ askerId: asker?.id,+ role: role,+ picture: asker?.avatar,+ ),+ ),+ );+ }+ }++ return ListView.builder(+ key: const ValueKey('swarm-messages'),+ controller: _scroll,+ reverse: true,+ padding: _listPadding,+ itemCount: lead + entries.length + (c.hasOlder ? 1 : 0),+ // A row keeps its element when a message or a post moves the others'+ // places.+ findChildIndexCallback: (key) {+ if (key is! ValueKey<String>) return null;+ if (key.value == _pendingKey) return lead == 1 ? 0 : null;+ if (key.value == _olderKey) {+ return c.hasOlder ? lead + entries.length : null;+ }+ final at = _placeOf[key.value];+ return at == null ? null : lead + at;+ },+ itemBuilder: (context, index) {+ if (index < lead) {+ final reply = pending!.replyTo == null ? null : byId[pending.replyTo];+ final mine = c.messages.reversed+ .where((m) => !m.fromAgent && m.authorId == c.reader.accountId)+ .firstOrNull;+ return _Pending(+ key: const ValueKey(_pendingKey),+ name: mine == null ? 'You' : _nameOf(c, mine),+ look:+ c.reader.snapshot?.personLook(c.reader.accountId) ??+ (picture: null, status: null),+ text: pending.text,+ files: pending.files,+ mentions: view.mentions,+ sending: c.sending,+ quote: pending.replyTo == null+ ? null+ : SwarmQuote(+ author: reply == null ? null : _quoted(c, reply),+ text: reply?.text,+ ),+ onSendAgain: () => unawaited(_post(c)),+ );+ }+ if (index - lead < entries.length) {+ return entry(entries[index - lead]);+ }+ // Read on their own near the top, behind skeleton bubbles; the link+ // only once that read failed.+ return KeyedSubtree(+ key: const ValueKey(_olderKey),+ child: _olderFailed+ ? Center(+ child: _Link(+ key: const ValueKey('swarm-older-messages'),+ label: 'Earlier messages',+ onTap: () => unawaited(_loadOlder(c)),+ ),+ )+ : Semantics(+ label: 'Loading earlier messages',+ child: const Column(+ key: ValueKey('swarm-older-loading'),+ children: [+ _SkeletonBubble(lines: 2, width: 0.7),+ _SkeletonBubble(lines: 1, width: 0.45),+ ],+ ),+ ),+ );+ },+ );+ }++ static const _pendingKey = 'swarm-row-pending', _olderKey = 'swarm-row-older';++ /// The key a row of [entry] keeps wherever it moves in the list.+ static String _keyOf(_Entry entry) => switch (entry) {+ _DayEntry(:final day) => 'swarm-row-day-${day.toIso8601String()}',+ _MessageEntry(:final message) => 'swarm-row-m-${message.id}',+ _AskEntry(:final need) => 'swarm-row-${need.key}',+ };++ /// [key]'s row as built from [inputs]: the one built before while they are+ /// the same — a widget given again as it was is not built again — else a+ /// new one from [build].+ Widget _row(String key, Object inputs, Widget Function() build) {+ final kept = _rows[key];+ if (kept != null && kept.inputs == inputs) return kept.row;+ final row = KeyedSubtree(key: ValueKey(key), child: build());+ _rows[key] = (inputs: inputs, row: row);+ return row;+ }++ /// How many messages wait below while the person reads back.+ int _waiting(SwarmConversation c) {+ final held = _held.value;+ if (held == null) return 0;+ final at = c.messages.lastIndexWhere((m) => m.id == held);+ return at < 0 ? 0 : c.messages.length - at - 1;+ }++ /// Back to the foot, where the messages that waited show.+ void _toFoot() {+ if (!_scroll.hasClients) return;+ unawaited(+ _scroll.animateTo(+ 0,+ duration: const Duration(milliseconds: 250),+ curve: Curves.easeOut,+ ),+ );+ }++ /// The @ picker while a name is typed, the reply bar while the draft+ /// answers a message, what the last pick left out, the files going with the+ /// post, what the mic could not hear, then +, a field that grows with what+ /// is typed, the mic and a round Send. An @ is typed in the field: it has no+ /// button of its own.+ Widget _composer(SwarmConversation c, Tty tty, {required String hint}) {+ final snapshot = c.reader.snapshot;+ final query = c.mentionQuery;+ final replying = c.replyingTo;+ // One post at a time: one not confirmed is sent again from where it shows.+ // Files alone are a post too.+ final canSend = c.canSend;+ return Container(+ decoration: BoxDecoration(+ color: Color.alphaBlend(tty.text.withValues(alpha: 0.02), tty.ground),+ border: Border(top: BorderSide(color: swarmChatHair(tty))),+ ),+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.m,+ vertical: AppSpace.s,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (query != null && snapshot != null)+ _MentionPicker(+ agents: c.mentionable,+ snapshot: snapshot,+ query: query,+ onPick: (agent) {+ c.completeMention(agent.id);+ _focus.requestFocus();+ },+ ),+ if (replying != null)+ Padding(+ key: const ValueKey('swarm-reply-bar'),+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ 0,+ 0,+ AppSpace.xs,+ ),+ child: Row(+ children: [+ Expanded(+ child: Container(+ padding: const EdgeInsets.only(left: AppSpace.s),+ decoration: BoxDecoration(+ border: Border(+ left: BorderSide(+ color: AppPalette.textFaint,+ width: 3,+ ),+ ),+ ),+ child: Text.rich(+ TextSpan(+ children: [+ const TextSpan(text: 'Reply to '),+ TextSpan(+ text: _quoted(c, replying) == 'You'+ ? 'you'+ : _quoted(c, replying),+ style: TextStyle(color: AppPalette.textPrimary),+ ),+ TextSpan(+ text:+ ': ${replying.text.replaceAll(RegExp(r'\s+'), ' ')}',+ ),+ ],+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(+ 13.5,+ color: AppPalette.textSecondary,+ ),+ ),+ ),+ ),+ _Round(+ key: const ValueKey('swarm-reply-cancel'),+ label: 'Cancel reply',+ onTap: () => c.replyingTo = null,+ child: Icon(+ LucideIcons.x,+ size: 18,+ color: AppPalette.textSecondary,+ ),+ ),+ ],+ ),+ ),+ ValueListenableBuilder(+ valueListenable: _attachNote,+ builder: (context, note, _) => note == null+ ? const SizedBox.shrink()+ : Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ 0,+ AppSpace.xs,+ AppSpace.s,+ ),+ child: Text(+ note,+ key: const ValueKey('swarm-attach-note'),+ style: AppType.caption(color: tty.yellow),+ ),+ ),+ ),+ if (_voice?.notice case final notice?)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ 0,+ AppSpace.xs,+ AppSpace.s,+ ),+ child: Text(+ notice,+ key: const ValueKey('swarm-voice-note'),+ style: AppType.caption(color: tty.yellow),+ ),+ ),+ // Quiet: nothing went wrong, the words stay in the box.+ if (_voice?.stopped case final stopped?)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ 0,+ AppSpace.xs,+ AppSpace.s,+ ),+ child: Text(+ stopped,+ key: const ValueKey('swarm-voice-stopped'),+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ),+ SwarmOutgoingChips(conversation: c),+ Row(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ if (swarmSendsFiles)+ _Round(+ key: const ValueKey('swarm-attach'),+ label: 'Attach files',+ onTap: c.uploading || c.files.room <= 0+ ? null+ : () => unawaited(_pickFiles(c)),+ child: Icon(+ LucideIcons.plus,+ size: AppIconSize.standalone,+ color: c.uploading || c.files.room <= 0+ ? AppPalette.textFaint+ : AppPalette.textSecondary,+ ),+ ),+ const SizedBox(width: 6),+ Expanded(+ child: _MessageField(+ controller: _text,+ focus: _focus,+ hint: hint,+ ),+ ),+ if (_voice case final voice?)+ SwarmVoiceMic(voice: voice)+ else+ const SizedBox(width: 6),+ _Round(+ key: const ValueKey('swarm-send'),+ label: 'Send',+ fill: canSend ? AppPalette.accent : ttyRaised(tty),+ onTap: canSend ? () => _send(c) : null,+ child: Icon(+ LucideIcons.arrowUp,+ size: 20,+ color: canSend ? AppInk.onFill : AppPalette.textFaint,+ ),+ ),+ ],+ ),+ ],+ ),+ );+ }+}++/// What the chat draws of its Swarm's read and of what is asked of the+/// person in it: its header, whether they can post, the names an @mention is+/// marked for, each agent's role and the decisions open in it. Made again at+/// each read and equal to the one before when nothing drawn changed, so a read+/// that moved nothing here draws nothing again.+@immutable+class _ChatView {+ const _ChatView({+ required this.known,+ required this.title,+ required this.project,+ required this.canPost,+ required this.archived,+ required this.names,+ required this.mentions,+ required this.roles,+ required this.mentionable,+ required this.decisions,+ required this.buddyProject,+ required this.hint,+ });++ /// [c] as its Swarm's read and asks have it now. The decisions of [before]+ /// are kept while each still draws the same.+ factory _ChatView.of(+ SwarmSession session,+ SwarmConversation c,+ _ChatView? before,+ ) {+ final reader = c.reader;+ final snapshot = reader.snapshot;+ final group = c.conversation;+ final agents = snapshot?.agents ?? const <SuperTabAgent>[];+ final names = [for (final agent in agents) snapshot!.agentName(agent.id)];+ // The person's own Buddy chat (#2090): named after their Buddy, and+ // holding every question the PM asked them in its project, as on Desktop.+ final buddyProject = group != null && swarmIsOwnBuddyChat(reader, group.id)+ ? group.projectId+ : null;+ final buddy = buddyProject == null+ ? null+ : swarmBuddyName(reader, buddyProject);+ final project = snapshot?.projects+ .where((p) => p.id == group?.projectId)+ .firstOrNull+ ?.name;+ // A chat not open to the person shows none of its questions either, even+ // while the decisions read has not caught up.+ final decisions = [+ for (final need in session.inbox.needs)+ if (group != null &&+ need is SwarmDecisionNeed &&+ need.swarmId == reader.tabId &&+ (need.conversationId == c.id ||+ (buddyProject != null &&+ need.decision.projectId == buddyProject)))+ need,+ ];+ return _ChatView(+ known: group != null,+ title: group == null ? 'Chat' : buddy ?? group.label,+ project: buddy != null && project != null ? '#$project' : project,+ canPost: c.canPost,+ archived: group?.archived ?? false,+ names: names,+ mentions: before != null && listEquals(before.names, names)+ ? before.mentions+ : SwarmMentions(names),+ roles: {+ for (final agent in agents)+ agent.id: ?swarmAgentRole(snapshot!, agent.id),+ },+ mentionable: [for (final agent in c.mentionable) agent.id],+ decisions: before != null && _sameAsks(before.decisions, decisions)+ ? before.decisions+ : List.unmodifiable(decisions),+ buddyProject: buddyProject,+ // "Message Wren"; plain while no Buddy runs to read it.+ hint: buddyProject != null && swarmBuddy(reader, buddyProject) != null+ ? 'Message $buddy'+ : 'Message',+ );+ }++ /// The conversation is in the Swarm's read.+ final bool known;+ final String title;+ final String? project;+ final bool canPost, archived;++ /// The Swarm's agents by name, and the @mentions of them marked in+ /// messages: made again only when a name changed.+ final List<String> names;+ final SwarmMentions mentions;++ /// Each agent's compact role, by agent id: PM, Dev or Rev.+ final Map<String, String> roles;++ /// The agents a post can mention, by id.+ final List<String> mentionable;+ final List<SwarmDecisionNeed> decisions;++ /// The project whose Buddy chat of the person's own this is; null for any+ /// other chat.+ final String? buddyProject;++ /// What the empty composer says.+ final String hint;++ /// Whether [a] and [b] draw the same decisions, in the same order.+ static bool _sameAsks(List<SwarmDecisionNeed> a, List<SwarmDecisionNeed> b) {+ if (a.length != b.length) return false;+ for (var i = 0; i < a.length; i++) {+ final x = a[i].decision, y = b[i].decision;+ if (a[i].key != b[i].key ||+ x.askerName != y.askerName ||+ x.question != y.question ||+ x.unblocks != y.unblocks ||+ x.recommended != y.recommended ||+ x.createdAt != y.createdAt ||+ !listEquals(x.options, y.options)) {+ return false;+ }+ }+ return true;+ }++ @override+ bool operator ==(Object other) =>+ other is _ChatView &&+ other.known == known &&+ other.title == title &&+ other.project == project &&+ other.canPost == canPost &&+ other.archived == archived &&+ listEquals(other.names, names) &&+ mapEquals(other.roles, roles) &&+ listEquals(other.mentionable, mentionable) &&+ identical(other.decisions, decisions) &&+ other.buddyProject == buddyProject &&+ other.hint == hint;++ @override+ int get hashCode => Object.hash(+ known,+ title,+ project,+ canPost,+ archived,+ Object.hashAll(names),+ Object.hashAll(mentionable),+ decisions,+ buddyProject,+ hint,+ );+}++/// One row of the chat.+sealed class _Entry {}++/// Where a day starts.+final class _DayEntry extends _Entry {+ _DayEntry(this.day);+ final DateTime day;+}++final class _MessageEntry extends _Entry {+ _MessageEntry(this.message, {required this.grouped});+ final SuperTabMessage message;++ /// Drawn under the one before, with no avatar, name or time.+ final bool grouped;+}++/// A decision asked of the person, in its place among the messages.+final class _AskEntry extends _Entry {+ _AskEntry(this.need, {this.grouped = false});+ final SwarmDecisionNeed need;++ /// Drawn under its asker's message just before it, as part of it.+ final bool grouped;+}++/// [messages] (oldest first) with the [asks] put where they were asked and a+/// divider where each day starts. An ask from before the messages read so far+/// — while there are [hasOlder] ones — goes at the foot instead, so a question+/// still open is never out of sight behind "Earlier messages".+List<_Entry> _timeline(+ List<SuperTabMessage> messages,+ List<SwarmDecisionNeed> asks, {+ required bool hasOlder,+}) {+ final grouped = swarmGroupedMessages(messages);+ final oldest = messages.map((m) => m.createdAt).nonNulls.firstOrNull;+ bool before(DateTime? asked, DateTime? at) =>+ asked != null && at != null && asked.isBefore(at);+ final waiting = <SwarmDecisionNeed>[], late = <SwarmDecisionNeed>[];+ for (final ask in asks) {+ (hasOlder && before(ask.decision.createdAt, oldest) ? late : waiting).add(+ ask,+ );+ }+ waiting.sort((a, b) {+ final x = a.decision.createdAt, y = b.decision.createdAt;+ if (x == null || y == null) return x == null ? (y == null ? 0 : 1) : -1;+ return x.compareTo(y);+ });++ final rows = <(_Entry, DateTime?)>[];+ // An ask right after its asker's own message — "One question before the+ // release:" — is drawn as part of it.+ void ask(SwarmDecisionNeed need) {+ final asked = need.decision.createdAt;+ final last = rows.lastOrNull?.$1;+ final at = last is _MessageEntry ? last.message.createdAt : null;+ final grouped =+ last is _MessageEntry &&+ last.message.fromAgent &&+ last.message.authorName == need.decision.askerName &&+ asked != null &&+ at != null &&+ !asked.isBefore(at) &&+ asked.difference(at) <= const Duration(minutes: 5);+ rows.add((_AskEntry(need, grouped: grouped), asked));+ }++ var next = 0;+ for (final m in messages) {+ while (next < waiting.length &&+ before(waiting[next].decision.createdAt, m.createdAt)) {+ ask(waiting[next]);+ next++;+ }+ // Grouped only right under a message: not under a question.+ final under = rows.isNotEmpty && rows.last.$1 is _MessageEntry;+ rows.add((+ _MessageEntry(m, grouped: under && grouped.contains(m.id)),+ m.createdAt,+ ));+ }+ waiting.skip(next).forEach(ask);+ for (final need in late) {+ rows.add((_AskEntry(need), need.decision.createdAt));+ }++ final timeline = <_Entry>[];+ DateTime? day;+ for (final (row, at) in rows) {+ if (at != null) {+ final local = DateUtils.dateOnly(at.toLocal());+ if (local != day) {+ day = local;+ timeline.add(_DayEntry(local));+ }+ }+ timeline.add(row);+ }+ return timeline;+}++const _weekdays = [+ 'Monday',+ 'Tuesday',+ 'Wednesday',+ 'Thursday',+ 'Friday',+ 'Saturday',+ 'Sunday',+];+const _months = [+ 'Jan',+ 'Feb',+ 'Mar',+ 'Apr',+ 'May',+ 'Jun',+ 'Jul',+ 'Aug',+ 'Sep',+ 'Oct',+ 'Nov',+ 'Dec',+];++/// A day divider's words for [day] (local): Today, Yesterday, the weekday+/// within the week, else the date — with its year when it is not this one.+String swarmDayLabel(DateTime day, DateTime now) {+ final date = DateUtils.dateOnly(day), today = DateUtils.dateOnly(now);+ // In hours, rounded: a day across a clock change is 23 or 25 of them.+ final days = (today.difference(date).inHours / 24).round();+ if (days == 0) return 'Today';+ if (days == 1) return 'Yesterday';+ if (days > 1 && days < 7) return _weekdays[date.weekday - 1];+ final short = '${date.day} ${_months[date.month - 1]}';+ return date.year == today.year ? short : '$short ${date.year}';+}++/// The ids of [messages] (oldest first) drawn as follow-ups under the one+/// before: the same author within five minutes on the same day, short, with+/// no question, line break or reply, and at most three to a run — the+/// desktop's `SuperTabMessageRow.groupsWith`.+Set<String> swarmGroupedMessages(List<SuperTabMessage> messages) {+ bool joins(SuperTabMessage current, SuperTabMessage previous) {+ bool plain(SuperTabMessage m) =>+ m.replyTo == null &&+ m.text.length <= 280 &&+ !m.text.contains('\n') &&+ !m.text.contains('?') &&+ !m.text.contains('?');+ if (!plain(current) ||+ !plain(previous) ||+ current.authorId.isEmpty ||+ current.authorId != previous.authorId ||+ current.authorName != previous.authorName ||+ current.author['kind'] != previous.author['kind'] ||+ current.author['membershipGeneration'] !=+ previous.author['membershipGeneration']) {+ return false;+ }+ final now = current.createdAt, before = previous.createdAt;+ if (now == null || before == null) return false;+ final elapsed = now.difference(before);+ return !elapsed.isNegative &&+ elapsed <= const Duration(minutes: 5) &&+ DateUtils.isSameDay(now.toLocal(), before.toLocal());+ }++ final joined = <String>{};+ var first = 0;+ for (var i = 1; i < messages.length; i++) {+ if (i - first < 3 &&+ joins(messages[i], messages[i - 1]) &&+ joins(messages[i], messages[first])) {+ joined.add(messages[i].id);+ } else {+ first = i;+ }+ }+ return joined;+}++/// An agent's role as its compact badge says it (the Naming System): PM for+/// a project's Product Manager, Rev for a reviewer, Dev for an engineer;+/// none for a person, a Buddy (no engineer, though it runs as one; Desktop+/// shows it none either), or an agent no longer in the Swarm.+String? swarmRole(SuperTabSnapshot snapshot, SuperTabMessage message) {+ if (!message.fromAgent) return null;+ return swarmAgentRole(snapshot, message.authorId);+}++String? swarmAgentRole(SuperTabSnapshot snapshot, String agentId) {+ if (snapshot.isLead(agentId)) return 'PM';+ final agent = snapshot.agent(agentId);+ if (agent == null || agent.isBuddy) return null;+ return agent.isReviewer ? 'Rev' : 'Dev';+}++/// The agent asking [need], found by the name it asked under: a decision+/// names its asker, not their id.+SuperTabAgent? swarmAsker(SuperTabSnapshot snapshot, SwarmDecisionNeed need) =>+ snapshot.agents+ .where((a) => snapshot.agentName(a.id) == need.decision.askerName)+ .firstOrNull;++/// Around the chat's column of messages, and of the skeleton standing in for+/// them.+const _listPadding = EdgeInsets.fromLTRB(+ AppSpace.m,+ AppSpace.xs,+ AppSpace.m,+ AppSpace.m,+);++/// The chat's first page on its way: bubbles in the shape of messages, at+/// the foot where they will show. Each has a fixed number of lines, so none+/// changes height as it breathes.+class _ChatSkeleton extends StatelessWidget {+ const _ChatSkeleton();++ /// Each bubble's lines and its last line's width, newest last.+ static const _bubbles = [+ (2, 0.6),+ (1, 0.4),+ (3, 0.75),+ (1, 0.55),+ (2, 0.35),+ (1, 0.65),+ (2, 0.5),+ ];++ @override+ Widget build(BuildContext context) => Semantics(+ label: 'Loading messages',+ child: SingleChildScrollView(+ key: const ValueKey('swarm-chat-skeleton'),+ // From the foot, as the messages are; those that do not fit are cut+ // off at the top.+ reverse: true,+ physics: const NeverScrollableScrollPhysics(),+ padding: _listPadding,+ child: Column(+ children: [+ for (final (lines, width) in _bubbles)+ _SkeletonBubble(lines: lines, width: width),+ ],+ ),+ ),+ );+}++/// A message in outline: avatar, name, then [lines] lines of text, the last+/// [width] of the row wide — in the metrics of a real one.+class _SkeletonBubble extends StatelessWidget {+ const _SkeletonBubble({required this.lines, required this.width});++ final int lines;+ final double width;++ @override+ Widget build(BuildContext context) {+ final text = swarmChatText(16, height: 1.42);+ return Padding(+ padding: SwarmMessageFrame.padding(),+ child: SwarmMessageFrame(+ key: const ValueKey('swarm-skeleton-bubble'),+ grouped: false,+ avatar: const Skeleton(+ width: SwarmChatAvatar.size,+ height: SwarmChatAvatar.size,+ shape: BoxShape.circle,+ ),+ header: SkeletonText(+ style: swarmChatText(13.5, weight: FontWeight.w600),+ width: 88,+ ),+ body: [+ Padding(+ padding: const EdgeInsets.only(top: SwarmMessageFrame.bodyGap),+ child: Column(+ children: [+ for (var line = 1; line <= lines; line++)+ SkeletonText(+ style: text,+ widthFactor: line == lines ? width : 0.92,+ ),+ ],+ ),+ ),+ ],+ ),+ );+ }+}++/// Where a day starts: Today, Yesterday, the weekday or the date.+class _Day extends StatelessWidget {+ const _Day({required this.day, required this.today});++ final DateTime day, today;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Padding(+ padding: const EdgeInsets.fromLTRB(0, AppSpace.l, 0, AppSpace.s),+ child: Text(+ swarmDayLabel(day, today),+ textAlign: TextAlign.center,+ style: Tty.of(context).style(color: AppPalette.textFaint, size: 12.5),+ ),+ );+ }+}++/// How many messages arrived below while the person read back; a tap goes+/// down to them.+class _NewPill extends StatelessWidget {+ const _NewPill({required this.count, required this.onTap});++ static const double _height = 36;++ final int count;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ label: count == 1 ? '1 new message' : '$count new messages',+ excludeSemantics: true,+ child: GestureDetector(+ key: const ValueKey('swarm-new-pill'),+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ // 44 to tap, 36 to see.+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: AppSpace.xs),+ child: Container(+ height: _height,+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.l),+ decoration: BoxDecoration(+ color: AppPalette.accent,+ // An action button's capsule.+ borderRadius: BorderRadius.circular(_height / 2),+ boxShadow: AppSurface.shadow,+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ const Icon(LucideIcons.arrowDown, size: 16, color: AppInk.onFill),+ const SizedBox(width: 6),+ Text(+ '$count new',+ style: swarmChatText(+ 14,+ color: AppInk.onFill,+ weight: FontWeight.w600,+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+}++/// The person's post on its way: "Sending…", then — its answer lost — "Not+/// confirmed" with Send again, until it is read back.+class _Pending extends StatelessWidget {+ const _Pending({+ super.key,+ required this.name,+ required this.text,+ required this.files,+ required this.mentions,+ required this.sending,+ required this.quote,+ required this.onSendAgain,+ required this.look,+ });++ final String name, text;++ /// The files going with it, already uploaded: shown as chips that open+ /// nothing until the post is read back with their links.+ final List<SwarmOutgoingFile> files;++ /// The person's own face.+ final SwarmLook look;+ final SwarmMentions mentions;+ final bool sending;+ final Widget? quote;+ final VoidCallback onSendAgain;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Padding(+ key: const ValueKey('swarm-pending'),+ padding: SwarmMessageFrame.padding(),+ child: SwarmMessageFrame(+ grouped: false,+ avatar: SwarmChatAvatar(+ name: name,+ id: '',+ agent: false,+ picture: look.picture,+ status: look.status,+ ),+ header: SwarmMessageHeader(+ name: name,+ agent: false,+ trailing: Text(+ sending ? 'Sending…' : 'Not confirmed',+ style: tty.style(+ color: sending ? AppPalette.textFaint : tty.yellow,+ size: 12.5,+ ),+ ),+ ),+ body: [+ ?quote,+ if (text.isNotEmpty)+ Padding(+ padding: const EdgeInsets.only(top: SwarmMessageFrame.bodyGap),+ child: Text.rich(+ mentions.span(+ text,+ swarmChatText(+ 16,+ height: 1.42,+ color: sending+ ? AppPalette.textSecondary+ : AppPalette.textPrimary,+ ),+ ),+ ),+ ),+ for (final file in files)+ SwarmFileChip(+ file: SuperTabAttachment.fromJson({+ 'id': '',+ 'name': file.name,+ 'mime': swarmMimeForName(file.name),+ 'size': file.bytes.length,+ 'url': '',+ }),+ link: null,+ ),+ if (!sending)+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.s),+ child: SwarmSmallButton(+ key: const ValueKey('swarm-resend-post'),+ icon: LucideIcons.rotateCw,+ label: 'Send again',+ onTap: onSendAgain,+ ),+ ),+ ],+ ),+ );+ }+}++/// A decision asked of the person, among the messages: from its asker, a card+/// with the question and its options side by side.+class _Ask extends StatelessWidget {+ const _Ask({+ required this.session,+ required this.need,+ required this.grouped,+ required this.askerId,+ required this.role,+ required this.picture,+ });++ final SwarmSession session;++ /// The picture its asker chose.+ final SuperTabAvatarPicture? picture;+ final SwarmDecisionNeed need;+ final bool grouped;++ /// Its asker in the Swarm and their role; null for one no longer in it.+ final String? askerId, role;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ final decision = need.decision;+ final at = decision.createdAt?.toLocal();+ String two(int n) => n.toString().padLeft(2, '0');+ return Padding(+ key: ValueKey('swarm-ask-${decision.id}'),+ padding: SwarmMessageFrame.padding(grouped: grouped),+ child: SwarmMessageFrame(+ grouped: grouped,+ avatar: SwarmChatAvatar(+ name: decision.askerName,+ id: askerId ?? decision.askerName,+ agent: true,+ pm: role == 'PM',+ picture: picture,+ ),+ header: SwarmMessageHeader(+ name: decision.askerName,+ agent: true,+ role: role,+ trailing: at == null+ ? null+ : Text(+ '${two(at.hour)}:${two(at.minute)}',+ style: tty.style(color: AppPalette.textFaint, size: 12.5),+ ),+ ),+ body: [+ Container(+ width: double.infinity,+ margin: const EdgeInsets.only(top: AppSpace.s),+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.m,+ AppSpace.l,+ AppSpace.l,+ ),+ decoration: BoxDecoration(+ color: swarmChatCard(tty),+ border: Border.all(color: swarmChatHair(tty)),+ borderRadius: BorderRadius.circular(AppCard.radius),+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(decision.question, style: swarmChatText(16, height: 1.4)),+ if (decision.unblocks.isNotEmpty) ...[+ const SizedBox(height: 4),+ Text(+ 'Unblocks: ${decision.unblocks}',+ style: swarmChatText(13.5, color: AppPalette.textSecondary),+ ),+ ],+ const SizedBox(height: 14),+ // Its answer held, sending or dropped: told by the session+ // and the Swarm's asks, not by the chat around it.+ ListenableBuilder(+ listenable: Listenable.merge([+ session,+ ?session.inbox.asks(need.swarmId),+ ]),+ builder: (context, _) => SwarmDecisionAnswer(+ session: session,+ need: need,+ fillRecommended: true,+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ );+ }+}++/// The chat's agents whose name starts with what follows the @ being typed,+/// over the composer: each with its role and what it is doing.+class _MentionPicker extends StatelessWidget {+ const _MentionPicker({+ required this.agents,+ required this.snapshot,+ required this.query,+ required this.onPick,+ });++ final List<SuperTabAgent> agents;+ final SuperTabSnapshot snapshot;+ final String query;+ final ValueChanged<SuperTabAgent> onPick;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ final glances = {+ for (final glance in swarmTeamGlance(snapshot).agents)+ glance.agent.id: glance,+ };+ final prefix = query.toLowerCase();+ final shown = [+ for (final agent in agents)+ if (snapshot.agentName(agent.id).toLowerCase().startsWith(prefix))+ agent,+ ];+ return Container(+ key: const ValueKey('swarm-mention-picker'),+ margin: const EdgeInsets.only(bottom: AppSpace.s),+ constraints: const BoxConstraints(maxHeight: 220),+ clipBehavior: Clip.antiAlias,+ decoration: BoxDecoration(+ color: swarmChatCard(tty),+ border: Border.all(color: swarmChatHair(tty)),+ borderRadius: BorderRadius.circular(AppMenu.panelRadius),+ boxShadow: AppSurface.shadow,+ ),+ child: shown.isEmpty+ ? Padding(+ padding: const EdgeInsets.all(AppSpace.l),+ child: Text(+ 'No agent by that name.',+ style: swarmChatText(14, color: AppPalette.textSecondary),+ ),+ )+ : ListView(+ shrinkWrap: true,+ padding: EdgeInsets.zero,+ children: [+ for (final agent in shown)+ TtyTap(+ key: ValueKey('swarm-pick-${agent.id}'),+ semanticsLabel: snapshot.agentName(agent.id),+ minHeight: 52,+ onTap: () => onPick(agent),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ ),+ child: Row(+ children: [+ SwarmChatAvatar(+ name: snapshot.agentName(agent.id),+ id: agent.id,+ agent: true,+ pm: snapshot.isLead(agent.id),+ picture: agent.avatar,+ ),+ const SizedBox(width: 10),+ Expanded(+ child: Row(+ children: [+ Flexible(+ child: Text(+ snapshot.agentName(agent.id),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(+ 16,+ weight: FontWeight.w500,+ ),+ ),+ ),+ if (swarmAgentRole(snapshot, agent.id)+ case final role?) ...[+ const SizedBox(width: 6),+ SwarmRoleBadge(role),+ ],+ ],+ ),+ ),+ if (glances[agent.id] case final glance?) ...[+ Container(+ width: 7,+ height: 7,+ decoration: BoxDecoration(+ color: _stateColor(tty, glance.state),+ shape: BoxShape.circle,+ ),+ ),+ const SizedBox(width: 6),+ Text(+ glance.label,+ style: swarmChatText(+ 13,+ color: AppPalette.textSecondary,+ ),+ ),+ ],+ ],+ ),+ ),+ ),+ ],+ ),+ );+ }+}++/// The dot beside what an agent is doing: green working, yellow waiting or+/// stuck, red down or limited, faint idle.+Color _stateColor(Tty tty, SwarmAgentState state) => switch (state) {+ SwarmAgentState.working => tty.green,+ SwarmAgentState.waiting || SwarmAgentState.stuck => tty.yellow,+ SwarmAgentState.down || SwarmAgentState.limited => tty.red,+ _ => AppPalette.textFaint,+};++/// Under the PM's private line in the person's Buddy chat: Answer in #project,+/// and that everyone there reads the answer.+class _AnswerIn extends StatelessWidget {+ const _AnswerIn({super.key, required this.project, required this.onTap});++ /// "#Mobile".+ final String project;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: AppSpace.s,+ children: [+ SwarmButton(+ label: 'Answer in $project',+ style: SwarmButtonStyle.link,+ onPressed: onTap,+ ),+ Text(+ 'Everyone there reads it',+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ],+ );+}++/// The composer's field: one rounded line that grows with what is typed, up+/// to five, in the app's own face.+class _MessageField extends StatelessWidget {+ const _MessageField({+ required this.controller,+ required this.focus,+ required this.hint,+ });++ final TextEditingController controller;+ final FocusNode focus;+ final String hint;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return GestureDetector(+ // A tap anywhere in the pill — not only on the text — takes the keyboard.+ behavior: HitTestBehavior.opaque,+ onTap: focus.requestFocus,+ child: Container(+ key: const ValueKey('swarm-field'),+ constraints: const BoxConstraints(minHeight: 44),+ alignment: Alignment.centerLeft,+ // One line rests at the 44 of the buttons beside it.+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ vertical: AppSpace.s,+ ),+ decoration: BoxDecoration(+ color: ttyRaised(tty),+ border: Border.all(color: swarmChatHair(tty)),+ // A text field's rounded rectangle.+ borderRadius: BorderRadius.circular(AppControl.radius),+ ),+ child: TextSelectionTheme(+ data: TextSelectionThemeData(+ cursorColor: AppPalette.accentOnSurface,+ selectionColor: AppPalette.accentOnSurface.withValues(alpha: 0.3),+ selectionHandleColor: AppPalette.accentOnSurface,+ ),+ child: TextField(+ controller: controller,+ focusNode: focus,+ minLines: 1,+ maxLines: 5,+ keyboardType: TextInputType.multiline,+ textInputAction: TextInputAction.newline,+ textCapitalization: TextCapitalization.sentences,+ // The keyboard's own composing, left on: Vietnamese Telex on iOS+ // rides on autocorrection. See `ComposingKeyboard`.+ autocorrect: ComposingKeyboard.autocorrect,+ enableSuggestions: ComposingKeyboard.enableSuggestions,+ smartDashesType: SmartDashesType.disabled,+ smartQuotesType: SmartQuotesType.disabled,+ cursorColor: AppPalette.accentOnSurface,+ cursorWidth: 2,+ style: swarmChatText(16, height: 22 / 16),+ decoration: InputDecoration(+ isCollapsed: true,+ // No minimum of its own: the pill's 44 is the field's height.+ constraints: const BoxConstraints(),+ filled: false,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ disabledBorder: InputBorder.none,+ contentPadding: EdgeInsets.zero,+ hintText: hint,+ hintStyle: swarmChatText(+ 16,+ height: 22 / 16,+ color: AppPalette.textFaint,+ ),+ ),+ ),+ ),+ ),+ );+ }+}++/// A round 44pt button: @, Send, the reply bar's ✕. [fill] draws it solid.+class _Round extends StatelessWidget {+ const _Round({+ super.key,+ required this.label,+ required this.onTap,+ required this.child,+ this.fill,+ });++ final String label;+ final VoidCallback? onTap;+ final Widget child;+ final Color? fill;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ enabled: onTap != null,+ label: label,+ excludeSemantics: true,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: Container(+ width: 44,+ height: 44,+ alignment: Alignment.center,+ decoration: BoxDecoration(color: fill, shape: BoxShape.circle),+ child: child,+ ),+ ),+ );+}++/// A link in the accent: Earlier messages.+class _Link extends StatelessWidget {+ const _Link({super.key, required this.label, required this.onTap});++ final String label;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => TtyTap(+ semanticsLabel: label,+ onTap: onTap,+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.l),+ child: Text(+ label,+ style: swarmChatText(15, color: AppPalette.accentOnSurface),+ ),+ ),+ );+}diff --git a/mobile/lib/swarm/swarm_devices_page.dart b/mobile/lib/swarm/swarm_devices_page.dartnew file mode 100644index 000000000..a48f52225--- /dev/null+++ b/mobile/lib/swarm/swarm_devices_page.dart@@ -0,0 +1,126 @@+import 'package:flutter/material.dart';++import 'package:harness_mobile/phone/out_of_sight.dart';+import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_start.dart';+import 'swarm_style.dart';++/// Your devices, from the drawer: the account's computers, each online or+/// not, from the list Swarm's start screens read ([SwarmComputers]). Read+/// only. Desktop's Your devices shows the hardware plugged into computers;+/// the phone has no read of that, so it lists the computers (Tony,+/// 2026-10-28).+class SwarmDevicesPage extends StatelessWidget {+ const SwarmDevicesPage({super.key});++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ final computers = SwarmScope.computersOf(context);+ return Scaffold(+ backgroundColor: tty.ground,+ body: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SwarmTopBar(+ leading: SwarmBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ title: 'Your devices',+ ),+ Expanded(+ child: computers == null+ ? const SizedBox.shrink()+ : ListenWhileInSight(+ listenable: computers,+ builder: (context) => RefreshIndicator(+ onRefresh: computers.recheck,+ child: ListView(+ physics: const AlwaysScrollableScrollPhysics(),+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ 0,+ AppSpace.m,+ MediaQuery.paddingOf(context).bottom + 28,+ ),+ children: [+ const SwarmCaption('Your computers', first: true),+ switch (computers.computers) {+ null => SwarmSkeletonRows(+ id: 'swarm-devices-loading',+ rows: 3,+ round: true,+ ),+ [] => const _NoComputer(),+ final list => SwarmGroup(+ children: [+ for (final (i, computer) in list.indexed)+ _ComputerRow(+ key: ValueKey('swarm-device-$i'),+ computer,+ ),+ ],+ ),+ },+ ],+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }+}++/// One computer, as a Home row: a dot, its name, and Online or Offline at+/// its right.+class _ComputerRow extends StatelessWidget {+ const _ComputerRow(this.computer, {super.key});++ final SwarmComputer computer;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final online = !computer.away;+ return SwarmRow(+ leading: Container(+ width: 9,+ height: 9,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: online ? AppColors.success : null,+ border: online+ ? null+ : Border.all(color: AppPalette.textFaint, width: 1.5),+ ),+ ),+ title: computer.name,+ trailing: SwarmRow.line(online ? 'Online' : 'Offline'),+ onTap: null,+ );+ }+}++/// No computer: a line under the caption, as Home's empty states are.+class _NoComputer extends StatelessWidget {+ const _NoComputer();++ @override+ Widget build(BuildContext context) => Padding(+ key: const ValueKey('swarm-devices-none'),+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: SwarmRow.line('No computers on your account yet.', lines: 2),+ );+}diff --git a/mobile/lib/swarm/swarm_dictation.dart b/mobile/lib/swarm/swarm_dictation.dartnew file mode 100644index 000000000..78a1aabc2--- /dev/null+++ b/mobile/lib/swarm/swarm_dictation.dart@@ -0,0 +1,329 @@+import 'dart:async';+import 'dart:math' as math;++import 'package:flutter/services.dart';++/// What the person said about the phone's speech recognizer and its+/// microphone, asked the first time a chat's mic is tapped.+enum SwarmDictationAccess {+ /// Both allowed: words show as they are said.+ allowed,++ /// Speech recognition refused or restricted: the chat records and has the+ /// backend transcribe instead, as before.+ denied,++ /// The microphone refused: nothing can be heard either way.+ noMic,+}++/// How a take with the phone's own recognizer ended ([SwarmDictation.start]'s+/// `onEnd`).+enum SwarmDictationEnd {+ /// Stopped, with its last words delivered.+ done,++ /// Stopped, and nothing was said in its last session.+ noSpeech,++ /// The recognizer failed, or cannot go on: what it delivered so far stays,+ /// the rest is lost.+ failed,+}++/// The phone's own speech recognizer, the one the keyboard's dictation uses+/// (Tony, 10-28): its words come back while the person is still talking.+/// iOS only ([SwarmChannelDictation]); elsewhere a chat records and the+/// backend transcribes.+///+/// One take at a time: [start] ends any earlier one without a word.+abstract interface class SwarmDictation {+ /// Asks for speech recognition and the microphone the first time; after+ /// that, what the person answered.+ Future<SwarmDictationAccess> access();++ /// Listens in [locale] (`vi-VN`) until [stop] or [cancel] (Tony, 10-29:+ /// "until I tap"). False when the phone has no recognizer for it now.+ /// [onWords] hears every word so far each time — revised as the recognizer+ /// changes its mind — [onLevel] how loud the voice is over the room (0…1),+ /// and [onEnd] once: after [stop], or when listening cannot go on.+ Future<bool> start(+ String locale, {+ required void Function(String words) onWords,+ required void Function(double level) onLevel,+ required void Function(SwarmDictationEnd end) onEnd,+ });++ /// Stops listening: the last words, then [start]'s `onEnd`.+ Future<void> stop();++ /// Stops listening and drops anything still to come: no more words, and no+ /// `onEnd`.+ Future<void> cancel();+}++/// The recognizer's locale for a code from `voiceLanguages`: Vietnamese for+/// one it does not know.+String swarmDictationLocale(String language) => switch (language) {+ 'en' => 'en-US',+ 'es' => 'es-ES',+ 'fr' => 'fr-FR',+ 'ja' => 'ja-JP',+ 'it' => 'it-IT',+ _ => 'vi-VN',+};++/// [SwarmDictation] over `harness/dictation` (iOS: `DictationChannel` in+/// `AppDelegate.swift`, `SFSpeechRecognizer`).+///+/// Each take has a number of its own, sent with every call and said back with+/// every event, so words from a take already ended land nowhere.+///+/// ⚠️ **Its guesses replace each other ([_stitched]), never add up.** The+/// recognizer says its latest best guess at the words not yet finished, and+/// rewrites it as it goes ("1", "Một 2", "123"); only a guess it says is+/// finished, or one its next words begin after in the take's audio — on the+/// phone it can start over after a pause, without a word — is kept, once, in+/// front of what it says next. Never a guess by how the words look: Tony's+/// 'một hai ba bốn năm' came out as 'Một 2 12345' that way (10-29).+///+/// ⚠️ **A take outlasts the recognizer's sessions ([_resume]).** iOS ends a+/// session by itself — after a pause, a long silence, its own minute — and+/// the native side says so (`paused`) with the microphone still on: what it+/// said is kept, and a new session starts at once.+class SwarmChannelDictation implements SwarmDictation {+ SwarmChannelDictation({MethodChannel? channel, DateTime Function()? clock})+ : _channel = channel ?? const MethodChannel('harness/dictation'),+ _clock = clock ?? DateTime.now {+ _channel.setMethodCallHandler(_heard);+ }++ final MethodChannel _channel;+ final DateTime Function() _clock;+ int _take = 0;+ ({+ void Function(String) words,+ void Function(double) level,+ void Function(SwarmDictationEnd) end,+ })?+ _to;++ /// What the recognizer has finished saying in this take, and its guess at+ /// what comes after: where that ends in the take's audio, and whether it+ /// said that guess was finished.+ String _done = '', _guess = '';+ double _guessTo = 0;+ bool _guessFinished = false;++ /// How far a guess may begin before the last one ended and still be new+ /// words: the recognizer's own times overlap a little at a word's edge.+ static const _overlap = 0.05;++ /// [stop] was asked: a session ending now is the take's last.+ bool _stopping = false;++ /// When sessions ended since the recognizer last said a word. [_quick] of+ /// them within [_quickWithin] is a recognizer that cannot hear now —+ /// offline, or broken — rather than one waiting through a silence.+ final List<DateTime> _pauses = [];+ static const _quick = 3;+ static const _quickWithin = Duration(seconds: 2);++ /// The microphone's last [_roomWindow] levels, in dB, a tenth of a second+ /// each: the quietest of them is the room, and the wave shows how far the+ /// voice is above it ([_level]) — whatever the microphone's own gain, which+ /// the recognizer's audio session leaves low.+ final List<double> _recent = [];+ static const _roomWindow = 30;++ /// The quietest a room is taken to be: below it, near-digital silence.+ static const _silence = -75.0;++ /// A voice [_overRoom] dB over the room starts the wave, and [_overRoom] ++ /// [_range] fills it.+ static const _overRoom = 3.0, _range = 25.0;++ @override+ Future<SwarmDictationAccess> access() async {+ try {+ return switch (await _channel.invokeMethod<String>('access')) {+ 'allowed' => SwarmDictationAccess.allowed,+ 'noMic' => SwarmDictationAccess.noMic,+ _ => SwarmDictationAccess.denied,+ };+ } on PlatformException {+ return SwarmDictationAccess.denied;+ } on MissingPluginException {+ return SwarmDictationAccess.denied;+ }+ }++ @override+ Future<bool> start(+ String locale, {+ required void Function(String words) onWords,+ required void Function(double level) onLevel,+ required void Function(SwarmDictationEnd end) onEnd,+ }) async {+ final take = ++_take;+ _to = (words: onWords, level: onLevel, end: onEnd);+ _done = _guess = '';+ _guessTo = 0;+ _guessFinished = false;+ _stopping = false;+ _pauses.clear();+ _recent.clear();+ try {+ final started = await _channel.invokeMethod<bool>('start', {+ 'take': take,+ 'locale': locale,+ });+ if (started != true && take == _take) _to = null;+ return started == true;+ } on PlatformException {+ if (take == _take) _to = null;+ return false;+ }+ }++ @override+ Future<void> stop() async {+ _stopping = true;+ try {+ await _channel.invokeMethod<void>('stop', {'take': _take});+ } on PlatformException {+ _ended(_take, SwarmDictationEnd.failed);+ }+ }++ @override+ Future<void> cancel() async {+ final take = _take++;+ _to = null;+ try {+ await _channel.invokeMethod<void>('cancel', {'take': take});+ } on PlatformException {+ // Nothing more is wanted from it either way.+ }+ }++ Future<void> _heard(MethodCall call) async {+ final arguments = call.arguments;+ if (arguments is! Map || arguments['take'] != _take) return;+ final to = _to;+ if (to == null) return;+ switch (call.method) {+ case 'words':+ if (arguments['text'] case final String text) {+ _pauses.clear();+ to.words(+ _stitched(+ text,+ finished: arguments['final'] == true,+ from: _seconds(arguments['from']),+ to: _seconds(arguments['to']),+ ),+ );+ }+ case 'level':+ if (arguments['rms'] case final num rms) {+ to.level(_level(rms.toDouble()));+ }+ case 'paused':+ await _resume(_take);+ case 'end':+ _ended(_take, switch (arguments['end']) {+ 'done' => SwarmDictationEnd.done,+ 'noSpeech' => SwarmDictationEnd.noSpeech,+ _ => SwarmDictationEnd.failed,+ });+ }+ }++ /// The recognizer ended its session by itself: its words are kept, and the+ /// take listens on in a new one — unless it is stopping, or sessions keep+ /// ending at once with nothing heard, or the phone will not start another.+ Future<void> _resume(int take) async {+ if (_stopping) return;+ _done = _joined(_done, _guess);+ _guess = '';+ _guessTo = 0;+ _guessFinished = false;+ final now = _clock();+ _pauses+ ..removeWhere((at) => now.difference(at) > _quickWithin)+ ..add(now);+ if (_pauses.length >= _quick) return _giveUp(take);+ var resumed = false;+ try {+ resumed =+ await _channel.invokeMethod<bool>('resume', {'take': take}) == true;+ } on PlatformException {+ resumed = false;+ }+ if (!resumed && take == _take && !_stopping) _giveUp(take);+ }++ /// Listening cannot go on: the take ends as failed, its words kept.+ void _giveUp(int take) {+ _ended(take, SwarmDictationEnd.failed);+ unawaited(cancel());+ }++ /// How far [rms] (0…1 of full scale) is above the room, for the wave.+ double _level(double rms) {+ if (rms <= 0) return 0;+ final db = 20 * math.log(rms) / math.ln10;+ _recent.add(db);+ if (_recent.length > _roomWindow) _recent.removeAt(0);+ final room = math.max(_recent.reduce(math.min), _silence);+ return ((db - room - _overRoom) / _range).clamp(0.0, 1.0);+ }++ /// Every word of the take so far: what is [_done], then [guess], the+ /// recognizer's latest — which replaces the last, unless that one is done.+ ///+ /// The last guess is done when this one begins after it ended in the take's+ /// audio ([from], [to]: seconds, 0 where the recognizer gives none). Without+ /// both times, when the recognizer said it was [finished] and this one is not the+ /// same words again with more after them, as a recognizer that keeps the+ /// whole take in each guess says it.+ String _stitched(+ String guess, {+ required bool finished,+ required double from,+ required double to,+ }) {+ final timed = from > 0 && _guessTo > 0;+ final after = timed && from >= _guessTo - _overlap;+ final again = _plain(guess).join(' ').startsWith(_plain(_guess).join(' '));+ if (_guess.isNotEmpty && (after || (!timed && _guessFinished && !again))) {+ _done = _joined(_done, _guess);+ }+ _guess = guess;+ _guessTo = to;+ _guessFinished = finished;+ return _joined(_done, guess);+ }++ static double _seconds(Object? value) =>+ value is num && value.isFinite ? value.toDouble() : 0;++ /// [text]'s words without case or punctuation, to be compared.+ static List<String> _plain(String text) => text+ .toLowerCase()+ .replaceAll(RegExp(r'[^\p{L}\p{N}\s]', unicode: true), '')+ .split(RegExp(r'\s+'))+ .where((word) => word.isNotEmpty)+ .toList();++ static String _joined(String kept, String text) =>+ kept.isEmpty || text.isEmpty ? '$kept$text' : '$kept $text';++ void _ended(int take, SwarmDictationEnd end) {+ if (take != _take) return;+ final to = _to;+ _to = null;+ to?.end(end);+ }+}diff --git a/mobile/lib/swarm/swarm_drawer.dart b/mobile/lib/swarm/swarm_drawer.dartnew file mode 100644index 000000000..bf37c72bb--- /dev/null+++ b/mobile/lib/swarm/swarm_drawer.dart@@ -0,0 +1,771 @@+import 'dart:async';++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/phone_navigation.dart';+import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/shared/widgets/skeleton.dart';++import 'identity.dart';+import 'model.dart';+import 'swarm_buddy.dart';+import 'swarm_buddy_chat.dart';+import 'swarm_devices_page.dart';+import 'swarm_face.dart';+import 'swarm_inbox.dart';+import 'swarm_leaderboard.dart';+import 'swarm_models_page.dart';+import 'swarm_project_page.dart';+import 'swarm_reader.dart';+import 'swarm_machines.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';+import 'swarm_task_status.dart';+import 'swarm_unread.dart';++/// Swarm Home's drawer, from the left edge like the desktop's sidebar, as the+/// approved prototype draws it: its title and a close button; Swarm Home+/// with what waits on the person; Buddies, the person's Buddy chat in each+/// project (Tony, 2026-10-29, as on the desktop since #2090); the projects,+/// each with its initial and its name, no team line (Team at a glance is+/// gone, as on the desktop) — its name opens the project, its arrow lists+/// its chats: Buddy chat, the project chat, its leaderboard, then its work,+/// what waits on the person first; then Your models and Your devices, read+/// only; then Settings at its foot. A row closes the drawer before it opens+/// anything. A chat, a Buddy or a project with something new is bold, with+/// the tags waiting in it as `@N` ([swarmChatNews], [swarmProjectNews]),+/// as Tony approved (2026-10-29).+class SwarmDrawer extends StatefulWidget {+ const SwarmDrawer({+ super.key,+ required this.session,+ required this.onProject,+ required this.onBuddy,+ required this.onChat,+ this.onSettings,+ this.onProfile,+ });++ /// The account's Swarm; null while there is none to read.+ final SwarmSession? session;++ /// A project's page.+ final void Function(String swarmId, String projectId) onProject;++ /// The person's Buddy chat in a project, opened on the server first when+ /// it has none yet.+ final void Function(String swarmId, String projectId) onBuddy;++ /// One chat.+ final void Function(String swarmId, String conversationId) onChat;++ /// Settings over Swarm Home, opened from the context it is given.+ final void Function(BuildContext context)? onSettings;++ /// The person's own profile in a Swarm; null offers none.+ final void Function(String swarmId)? onProfile;++ @override+ State<SwarmDrawer> createState() => _SwarmDrawerState();+}++class _SwarmDrawerState extends State<SwarmDrawer> {+ /// Projects whose chats are listed, as `swarmId/projectId`.+ final _open = <String>{};++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ final session = widget.session;+ final inbox = session?.inbox;+ final navigator = Navigator.of(context);+ void close() => Scaffold.of(context).closeDrawer();+ void then(VoidCallback action) {+ close();+ action();+ }++ final swarms = inbox?.swarms ?? const <SwarmListing>[];+ final several = swarms.length > 1;+ final waiting = inbox?.needs.length ?? 0;+ return Drawer(+ width: MediaQuery.sizeOf(context).width * .86,+ backgroundColor: AppPalette.panelBg,+ shape: Border(right: BorderSide(color: AppGlass.hair)),+ child: SafeArea(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ // The title over the rows' words.+ padding: const EdgeInsets.fromLTRB(+ AppSpace.s + SwarmDrawerRow.inset,+ AppSpace.xs,+ AppSpace.s,+ AppSpace.s,+ ),+ child: Row(+ children: [+ Expanded(+ child: Text(+ 'Swarm',+ style: tty.style(size: 17, weight: FontWeight.w600),+ ),+ ),+ SwarmIconButton(+ key: const ValueKey('swarm-drawer-close'),+ icon: LucideIcons.x300,+ label: 'Close menu',+ onPressed: close,+ ),+ ],+ ),+ ),+ Expanded(+ child: ListView(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.s,+ 0,+ AppSpace.s,+ AppSpace.m,+ ),+ children: [+ // Who you are in each Swarm, first: the way to your+ // picture and status.+ if (widget.onProfile case final onProfile?)+ for (final swarm in swarms)+ if (inbox!.reader(swarm.id) case final reader?)+ _You(+ key: ValueKey('swarm-drawer-you-${swarm.id}'),+ reader: reader,+ swarmName: several ? swarm.name : null,+ onTap: () => then(() => onProfile(swarm.id)),+ ),+ SwarmDrawerRow(+ key: const ValueKey('swarm-drawer-home'),+ leading: const _Glyph(LucideIcons.network300),+ title: 'Swarm Home',+ selected: true,+ badge: waiting > 0 ? SwarmBadge(waiting, warn: true) : null,+ onTap: close,+ ),+ ..._buddies(swarms, inbox, then),+ // Before the list (and no Home kept), and for a Swarm+ // still to be read, its projects are rows on their way; one+ // that could not be read lists none.+ if (inbox != null &&+ !inbox.loaded &&+ inbox.swarms.isEmpty &&+ inbox.error == null) ...[+ const _Caption('Projects'),+ _ProjectsLoading('swarm-drawer-loading'),+ ],+ for (final swarm in swarms)+ ...switch (inbox!.reader(swarm.id)) {+ final SwarmReader reader+ when reader.snapshot?.projects.isNotEmpty ?? false =>+ _projects(session!, swarm, reader, several, then),+ SwarmReader(snapshot: null, error: null) || null => [+ _Caption(several ? swarm.name : 'Projects'),+ _ProjectsLoading('swarm-drawer-loading-${swarm.id}'),+ ],+ _ => const <Widget>[],+ },+ for (final swarm in swarms)+ if (inbox?.reader(swarm.id) case final reader?)+ SwarmMachinesSection(+ key: ValueKey('swarm-machine-section-${swarm.id}'),+ reader: reader,+ swarmName: several ? swarm.name : null,+ open: (id) => then(+ () =>+ unawaited(showSwarmMachine(context, reader, id)),+ ),+ ),+ // The Swarm's models and the account's computers, read+ // only, as Desktop's sidebar has them under its projects.+ const _Caption(''),+ SwarmDrawerRow(+ key: const ValueKey('swarm-drawer-models'),+ leading: const _Glyph(LucideIcons.brain300),+ title: 'Your models',+ trailing: true,+ onTap: () => then(+ () => navigator.push(+ phoneRoute(+ (_) => const SwarmModelsPage(),+ listensForItself: true,+ ),+ ),+ ),+ ),+ if (SwarmScope.computersOf(context) != null)+ SwarmDrawerRow(+ key: const ValueKey('swarm-drawer-devices'),+ leading: const _Glyph(LucideIcons.laptop300),+ title: 'Your devices',+ trailing: true,+ onTap: () => then(+ () => navigator.push(+ phoneRoute(+ (_) => const SwarmDevicesPage(),+ listensForItself: true,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ if (widget.onSettings case final settings?)+ DecoratedBox(+ decoration: BoxDecoration(+ border: Border(top: BorderSide(color: AppGlass.hair)),+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.s,+ vertical: AppSpace.s,+ ),+ child: SwarmDrawerRow(+ key: const ValueKey('swarm-drawer-settings'),+ leading: const _Glyph(LucideIcons.settings2300),+ title: 'Settings',+ onTap: () => then(() => settings(context)),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }++ /// Buddies: the person's Buddy chat in each project of each Swarm read,+ /// there from the start (#2090); a viewer, who starts no Buddy, sees only+ /// the chats they have. The project is in brackets once there are several,+ /// with its Swarm where there are several Swarms.+ List<Widget> _buddies(+ List<SwarmListing> swarms,+ SwarmInbox? inbox,+ void Function(VoidCallback action) then,+ ) {+ final rows = [+ for (final swarm in swarms)+ if (inbox?.reader(swarm.id) case final reader?)+ for (final project in reader.snapshot?.projects ?? const [])+ if (swarmBuddyChat(reader, project.id) != null ||+ swarmCanWrite(reader))+ (swarm: swarm, reader: reader, project: project),+ ];+ if (rows.isEmpty) return const [];+ final several = swarms.length > 1;+ return [+ const _Caption('Buddies'),+ for (final (:swarm, :reader, :project) in rows)+ SwarmDrawerRow(+ key: ValueKey('swarm-drawer-buddy-${swarm.id}-${project.id}'),+ leading: SwarmBuddyAvatar(reader: reader, projectId: project.id),+ title: swarmBuddyName(reader, project.id),+ news: switch (swarmBuddyChat(reader, project.id)) {+ final chat? => swarmChatNews(reader, inbox!.asks(swarm.id), chat),+ null => swarmNoNews,+ },+ asides: [+ if (rows.length > 1)+ several+ ? '(${project.name} · ${swarm.name})'+ : '(${project.name})',+ ?swarmBuddyNote(reader, project.id),+ ],+ onTap: () => then(() => widget.onBuddy(swarm.id, project.id)),+ ),+ ];+ }++ /// A Swarm's projects under its caption, what is new in each worked out+ /// once for them all ([swarmProjectNews]).+ List<Widget> _projects(+ SwarmSession session,+ SwarmListing swarm,+ SwarmReader reader,+ bool several,+ void Function(VoidCallback action) then,+ ) {+ final snapshot = reader.snapshot!;+ final news = swarmProjectNews(reader, session.inbox.asks(swarm.id));+ return [+ _Caption(several ? swarm.name : 'Projects'),+ for (final project in snapshot.projects)+ ..._project(+ session,+ swarm.id,+ snapshot,+ project,+ news[project.id] ?? swarmNoNews,+ then,+ ),+ ];+ }++ /// A project's row, and while its arrow is open, its chats ([_chats]).+ List<Widget> _project(+ SwarmSession session,+ String swarmId,+ SuperTabSnapshot snapshot,+ SuperTabProject project,+ SwarmRowNews news,+ void Function(VoidCallback action) then,+ ) {+ final id = '$swarmId/${project.id}';+ final open = _open.contains(id);+ return [+ Row(+ children: [+ Expanded(+ child: SwarmDrawerRow(+ key: ValueKey('swarm-drawer-project-$swarmId-${project.id}'),+ leading: SwarmProjectTile(project.name),+ title: project.name,+ news: news,+ onTap: () => then(() => widget.onProject(swarmId, project.id)),+ ),+ ),+ _Disclosure(+ key: ValueKey('swarm-drawer-chats-$swarmId-${project.id}'),+ open: open,+ label: '${open ? 'Hide' : 'Show'} the chats of ${project.name}',+ onTap: () =>+ setState(() => open ? _open.remove(id) : _open.add(id)),+ ),+ ],+ ),+ if (open) ..._chats(session, swarmId, snapshot, project, then),+ ];+ }++ /// An open project's chats: Buddy chat, the project chat, its+ /// leaderboard, then its work — what waits on the person first, the rest+ /// by latest activity, each with its task's status line under its name+ /// ([SwarmTaskLine]). Worked out only while it is open: a closed project+ /// costs its row alone.+ List<Widget> _chats(+ SwarmSession session,+ String swarmId,+ SuperTabSnapshot snapshot,+ SuperTabProject project,+ void Function(VoidCallback action) then,+ ) {+ final lead = snapshot.conversation(project.leadConversationId);+ final reader = session.inbox.reader(swarmId);+ final work = swarmProjectWork(+ snapshot,+ project,+ buddies: reader?.buddies ?? SwarmBuddies.none,+ ).active;+ final waits = swarmWaitingOnYou(session.inbox, swarmId);+ final asks = session.inbox.asks(swarmId);+ SwarmRowNews news(SuperTabConversation? g) => reader == null || g == null+ ? swarmNoNews+ : swarmChatNews(reader, asks, g);+ final personName = swarmTaskPersonName(snapshot);+ // A task's line under its name, as on the desktop (#2125); its trailing+ // edge stays the tags'.+ SwarmDrawerRow chat(+ SuperTabConversation g,+ String title, {+ bool task = false,+ }) => SwarmDrawerRow(+ key: ValueKey('swarm-drawer-chat-${g.id}'),+ title: title,+ sub: true,+ news: news(g),+ detail: task ? SwarmTaskLine(g, personName: personName) : null,+ onTap: () => then(() => widget.onChat(swarmId, g.id)),+ );+ final buddyChat = reader == null+ ? null+ : swarmBuddyChat(reader, project.id);+ return [+ if (reader != null && (buddyChat != null || swarmCanWrite(reader)))+ SwarmDrawerRow(+ key: ValueKey('swarm-drawer-buddy-chat-$swarmId-${project.id}'),+ title: 'Buddy chat',+ sub: true,+ news: news(buddyChat),+ onTap: () => then(() => widget.onBuddy(swarmId, project.id)),+ ),+ if (lead != null) chat(lead, 'Project chat'),+ SwarmDrawerRow(+ key: ValueKey('swarm-drawer-leaderboard-$swarmId-${project.id}'),+ title: 'Leaderboard',+ sub: true,+ onTap: () =>+ then(() => openSwarmLeaderboard(context, swarmId, project.id)),+ ),+ for (final g in work)+ if (waits.contains(g.id)) chat(g, g.label, task: true),+ for (final g in work)+ if (!waits.contains(g.id)) chat(g, g.label, task: true),+ ];+ }+}++/// The person as a Swarm shows them: their face, and their status while it+/// lasts; nothing until the Swarm is read with them in it.+class _You extends StatelessWidget {+ const _You({+ super.key,+ required this.reader,+ required this.swarmName,+ required this.onTap,+ });++ final SwarmReader reader;++ /// The Swarm's name, where there are several.+ final String? swarmName;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: reader,+ builder: (context, _) {+ final me = reader.snapshot?.person(reader.accountId);+ if (me == null) return const SizedBox.shrink();+ return SwarmUntil(+ until: me.status?.until,+ builder: (context) {+ final status = me.statusAt(clock.now());+ // A Home kept for a cold start holds no email.+ final name = me.email.isEmpty ? 'You' : superTabPersonName(me.email);+ return SwarmDrawerRow(+ leading: SwarmAvatar(+ id: me.id,+ name: name,+ picture: me.avatar,+ status: status,+ ),+ title: swarmName == null ? name : '$name · $swarmName',+ detail: Text(+ status?.label ?? 'Set a status',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(+ color: status == null+ ? AppPalette.textFaint+ : AppPalette.textSecondary,+ ),+ ),+ onTap: onTap,+ );+ },+ );+ },+ );+}++/// A row's glyph, in a 32-point box so titles line up with a project's tile.+class _Glyph extends StatelessWidget {+ const _Glyph(this.icon);++ static const double width = 32;++ final IconData icon;++ @override+ Widget build(BuildContext context) => SizedBox(+ width: width,+ child: Icon(icon, size: 22, color: AppPalette.textSecondary),+ );+}++/// A caption over a run of the drawer's rows; empty, a gap.+class _Caption extends StatelessWidget {+ const _Caption(this.text);++ final String text;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.fromLTRB(+ SwarmDrawerRow.inset,+ AppSpace.l,+ SwarmDrawerRow.inset,+ AppSpace.s,+ ),+ child: Text(+ text,+ style: AppType.caption(+ color: Color.lerp(AppPalette.textFaint, AppPalette.textSecondary, .5),+ height: 1.2,+ ),+ ),+ );+}++/// A project's arrow: right while its chats are hidden, down while listed.+class _Disclosure extends StatelessWidget {+ const _Disclosure({+ super.key,+ required this.open,+ required this.label,+ required this.onTap,+ });++ final bool open;+ final String label;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ label: label,+ excludeSemantics: true,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ HapticFeedback.selectionClick();+ onTap();+ },+ child: SizedBox(+ width: 44,+ height: SwarmDrawerRow.height,+ child: Icon(+ open ? LucideIcons.chevronDown300 : LucideIcons.chevronRight300,+ size: 18,+ color: AppPalette.textFaint,+ ),+ ),+ ),+ );+}++/// One row of the drawer: a glyph or a project's tile, a title, quiet words+/// after it ([asides]) and maybe a line under it, a count; selected, it sits+/// on a rounded fill. A chat under its project ([sub]) is shorter, quieter,+/// and lined up with the project's name. Something new in it ([news]) sets+/// its title in bold, with no dot, and the tags waiting in it as `@N` at its+/// trailing edge (desktop design system: Unread, Mentions).+class SwarmDrawerRow extends StatelessWidget {+ const SwarmDrawerRow({+ super.key,+ this.leading,+ required this.title,+ this.detail,+ this.badge,+ this.selected = false,+ this.sub = false,+ this.trailing = false,+ this.asides = const [],+ this.news = swarmNoNews,+ required this.onTap,+ });++ final Widget? leading;+ final String title;++ /// Quiet words after the title, such as a Buddy's project in brackets and+ /// "offline"; they give way first when the row is narrow.+ final List<String> asides;+ final Widget? detail;+ final Widget? badge;+ final bool selected;++ /// A chat under its project.+ final bool sub;++ /// Opens a page of its own: a chevron at its right.+ final bool trailing;++ /// What is new in it: unread or tagged ([swarmChatNews]).+ final SwarmRowNews news;+ final VoidCallback? onTap;++ /// Every row but a chat under its project clears this, for a thumb.+ static const double height = 52;++ /// From a row's edges to its words.+ static const double inset = AppSpace.m;++ /// Around a row's words; a chat's start under its project's name.+ static const padding = EdgeInsets.symmetric(+ horizontal: inset,+ vertical: AppSpace.s,+ );++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Material(+ color: selected ? AppSurface.selectedFill : Colors.transparent,+ borderRadius: BorderRadius.circular(AppControl.rowRadius),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: onTap == null+ ? null+ : () {+ HapticFeedback.selectionClick();+ onTap!();+ },+ child: ConstrainedBox(+ constraints: BoxConstraints(minHeight: sub ? 44 : height),+ child: Padding(+ padding: sub+ ? padding.copyWith(+ left: padding.left + _Glyph.width + AppSpace.m,+ )+ : padding,++ child: Row(+ children: [+ if (leading case final leading?) ...[+ leading,+ const SizedBox(width: AppSpace.m),+ ],+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Row(+ children: [+ Flexible(+ // Unread is heard in words, as the bold is seen;+ // tags say their own.+ child: Semantics(+ label: news.bold && news.tags == 0+ ? 'Unread messages'+ : null,+ child: Text(+ title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: switch ((sub, news.bold)) {+ (_, true) => AppType.label(+ color: AppPalette.textPrimary,+ fontWeight: AppFont.semibold,+ ),+ (true, false) => AppType.body(+ color: AppPalette.textSecondary,+ ),+ (false, false) => AppType.label(+ color: AppPalette.textPrimary,+ ),+ },+ ),+ ),+ ),+ for (final aside in asides) ...[+ const SizedBox(width: 8),+ Flexible(+ child: Text(+ aside,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(+ color: AppPalette.textFaint,+ ),+ ),+ ),+ ],+ ],+ ),+ if (detail case final detail?) ...[+ const SizedBox(height: 2),+ detail,+ ],+ ],+ ),+ ),+ if (news.tags > 0) ...[+ const SizedBox(width: 12),+ SwarmTags(news.tags),+ ],+ if (badge case final badge?) ...[+ const SizedBox(width: 12),+ badge,+ ],+ if (trailing) ...[+ const SizedBox(width: 12),+ Icon(+ LucideIcons.chevronRight300,+ size: 18,+ color: AppPalette.textFaint,+ ),+ ],+ ],+ ),+ ),+ ),+ ),+ );+ }+}++/// A Swarm's projects on their way: two rows in the shape of a project's+/// [SwarmDrawerRow], as tall as the rows that replace them, fading towards+/// the last; one "Loading" to a screen reader. Keyed [id]; its row `i`,+/// `$id-$i`.+class _ProjectsLoading extends StatelessWidget {+ _ProjectsLoading(this.id) : super(key: ValueKey(id));++ final String id;++ static const _rows = 2;++ @override+ Widget build(BuildContext context) => SkeletonBlock(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (var i = 0; i < _rows; i++)+ Opacity(+ opacity: skeletonFade(i, _rows, depth: .4),+ child: _ProjectLoading(+ key: ValueKey('$id-$i'),+ width: i.isEven ? .45 : .6,+ ),+ ),+ ],+ ),+ );+}++/// One project's row on its way: its tile and a bar for its name, as tall as+/// the line it stands for.+class _ProjectLoading extends StatelessWidget {+ const _ProjectLoading({super.key, required this.width});++ /// The name's share of the row's words.+ final double width;++ @override+ Widget build(BuildContext context) => ConstrainedBox(+ constraints: const BoxConstraints(minHeight: SwarmDrawerRow.height),+ child: Padding(+ padding: SwarmDrawerRow.padding,+ child: Row(+ children: [+ const Skeleton(+ width: _Glyph.width,+ height: _Glyph.width,+ radius: AppCard.insetRadius,+ ),+ const SizedBox(width: AppSpace.m),+ // The real row's metrics: its title alone.+ Expanded(+ child: SkeletonText(style: AppType.label(), widthFactor: width),+ ),+ ],+ ),+ ),+ );+}diff --git a/mobile/lib/swarm/swarm_face.dart b/mobile/lib/swarm/swarm_face.dartnew file mode 100644index 000000000..b3895103b--- /dev/null+++ b/mobile/lib/swarm/swarm_face.dart@@ -0,0 +1,257 @@+import 'dart:async';++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'model.dart';++/// What a person or an agent wears inside their round mark, as the desktop+/// draws it (`desktop/lib/super_tabs/avatar_art.dart`): the picture they+/// uploaded, the built-in one they picked on a wash of [tint], or [fallback]+/// — their initial — when they have neither, while an upload loads, and when+/// it cannot.+class SwarmFace extends StatelessWidget {+ const SwarmFace({+ super.key,+ required this.picture,+ required this.size,+ required this.tint,+ required this.fallback,+ });++ final SuperTabAvatarPicture? picture;+ final double size;+ final Color tint;+ final Widget fallback;++ @override+ Widget build(BuildContext context) => switch (picture) {+ SuperTabUploadedAvatar(:final url) => ClipOval(+ child: Image(+ image: SwarmAvatarImages.of(context, url),+ width: size,+ height: size,+ fit: BoxFit.cover,+ // A link signed anew keeps the picture shown while it loads.+ gaplessPlayback: true,+ frameBuilder: (context, child, frame, synchronous) =>+ frame == null && !synchronous ? fallback : child,+ errorBuilder: (context, _, _) => fallback,+ ),+ ),+ SuperTabPresetAvatar(:final glyph) => Container(+ width: size,+ height: size,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: tint.withValues(alpha: .18),+ shape: BoxShape.circle,+ ),+ child: Text(+ glyph,+ textScaler: TextScaler.noScaling,+ style: TextStyle(fontSize: size * .58, height: 1),+ ),+ ),+ null => fallback,+ };+}++/// Where an uploaded avatar's picture is read from: its signed link+/// (backend avatarLinks.ts), over the network. Tests hand in bytes instead.+class SwarmAvatarImages extends InheritedWidget {+ const SwarmAvatarImages({+ super.key,+ required this.image,+ required super.child,+ });++ final ImageProvider Function(Uri url) image;++ static ImageProvider of(BuildContext context, Uri url) =>+ context.dependOnInheritedWidgetOfExactType<SwarmAvatarImages>()?.image(+ url,+ ) ??+ swarmAvatarImage(url);++ @override+ bool updateShouldNotify(SwarmAvatarImages old) => old.image != image;+}++/// The links of the photos drawn while this account has been signed in.+final _drawnLinks = <String>{};++/// The uploaded picture at [url], over the network, remembered so that+/// [swarmForgetAvatarImages] can let it go. Never kept on disk.+ImageProvider swarmAvatarImage(Uri url) {+ _drawnLinks.add(url.toString());+ return NetworkImage(url.toString());+}++/// Lets go of every photo drawn, as the account leaves: none of another+/// account's people stays in memory.+void swarmForgetAvatarImages() {+ // Nothing drawn, nothing to let go: and no painting needed to know it.+ if (_drawnLinks.isEmpty) return;+ final cache = PaintingBinding.instance.imageCache;+ for (final link in _drawnLinks) {+ cache.evict(NetworkImage(link), includeLive: true);+ }+ _drawnLinks.clear();+}++/// [face], [size] round, with a person's [status] emoji at its corner while+/// the status lasts; then it goes by itself. Read as [name] and the status.+class SwarmStatusFace extends StatelessWidget {+ const SwarmStatusFace({+ super.key,+ required this.face,+ required this.name,+ required this.size,+ required this.status,+ });++ final Widget face;+ final String name;+ final double size;+ final SuperTabPersonStatus? status;++ @override+ Widget build(BuildContext context) {+ if (status == null) return face;+ return SwarmUntil(+ until: status!.until,+ builder: (context) {+ final shown = status!.shownAt(clock.now()) ? status : null;+ if (shown == null) return face;+ final badge = (size * .5).clamp(12.0, 22.0);+ return Semantics(+ label: '$name, ${shown.label}',+ excludeSemantics: true,+ child: SizedBox.square(+ dimension: size,+ child: Stack(+ clipBehavior: Clip.none,+ children: [+ face,+ if (shown.emoji case final emoji?)+ Positioned(+ right: -badge * .25,+ bottom: -badge * .25,+ child: Container(+ key: const ValueKey('swarm-status-badge'),+ width: badge,+ height: badge,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: AppPalette.panelBg,+ shape: BoxShape.circle,+ border: Border.all(color: AppGlass.hair, width: .5),+ ),+ child: Text(+ emoji,+ textScaler: TextScaler.noScaling,+ style: TextStyle(fontSize: badge * .66, height: 1),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ },+ );+ }+}++/// Builds [builder] again at [until], when something it shows runs out (a+/// status that clears itself), even when nothing else changes on the page:+/// the desktop's `SuperTabUntil`.+class SwarmUntil extends StatefulWidget {+ const SwarmUntil({super.key, required this.until, required this.builder});+ final DateTime? until;+ final WidgetBuilder builder;++ @override+ State<SwarmUntil> createState() => _SwarmUntilState();+}++class _SwarmUntilState extends State<SwarmUntil> {+ Timer? _timer;++ @override+ void initState() {+ super.initState();+ _schedule();+ }++ @override+ void didUpdateWidget(SwarmUntil old) {+ super.didUpdateWidget(old);+ if (old.until != widget.until) _schedule();+ }++ void _schedule() {+ _timer?.cancel();+ _timer = null;+ final until = widget.until;+ if (until == null) return;+ final left = until.difference(clock.now());+ if (left.isNegative) return;+ _timer = Timer(left + const Duration(milliseconds: 1), () {+ if (mounted) setState(() {});+ });+ }++ @override+ void dispose() {+ _timer?.cancel();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => widget.builder(context);+}++/// What a person or an agent wears: the picture they chose and, for a+/// person, their status.+typedef SwarmLook = ({+ SuperTabAvatarPicture? picture,+ SuperTabPersonStatus? status,+});++final _peopleById = Expando<Map<String, SuperTabPerson>>();++/// Who wears what in a Swarm as last read.+extension SwarmLooks on SuperTabSnapshot {+ /// The member [id]; looked up per row on every build, so kept by id once+ /// per read, as the snapshot's own lookups are.+ SuperTabPerson? person(String id) =>+ (_peopleById[this] ??= {for (final p in people.reversed) p.id: p})[id];++ SwarmLook agentLook(String id) => (picture: agent(id)?.avatar, status: null);++ SwarmLook personLook(String id) {+ final found = person(id);+ return (picture: found?.avatar, status: found?.status);+ }++ SwarmLook authorLook(SuperTabMessage message) => message.fromAgent+ ? agentLook(message.authorId)+ : personLook(message.authorId);+}++/// The same for two looks drawn alike, though each read makes new ones: what+/// a row kept as it was compares.+Object swarmLookKey(SwarmLook look) => (+ switch (look.picture) {+ SuperTabUploadedAvatar(:final url) => url,+ SuperTabPresetAvatar(:final key) => key,+ null => null,+ },+ look.status?.text,+ look.status?.emoji,+ look.status?.until,+);diff --git a/mobile/lib/swarm/swarm_file_picker.dart b/mobile/lib/swarm/swarm_file_picker.dartnew file mode 100644index 000000000..293dd9823--- /dev/null+++ b/mobile/lib/swarm/swarm_file_picker.dart@@ -0,0 +1,232 @@+import 'dart:io';++import 'package:file_selector/file_selector.dart' show openFiles;+import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:image_picker/image_picker.dart';+import 'package:path/path.dart' as p;+import 'package:path_provider/path_provider.dart';++import 'swarm_outgoing_files.dart';++/// Where the attach sheet of a phone Swarm chat takes files from.+enum SwarmPickSource { library, camera, files }++/// What one pick did to a chat's files.+sealed class SwarmPickOutcome {+ const SwarmPickOutcome();+}++/// The files picked were taken, or nothing was picked. [note] says what was left out, if anything.+class SwarmPicked extends SwarmPickOutcome {+ const SwarmPicked(this.note);+ final String? note;+}++/// The phone refused the app [source] — the camera, or photos — and only Settings turns it back on.+class SwarmPickDenied extends SwarmPickOutcome {+ const SwarmPickDenied(this.source);+ final SwarmPickSource source;+}++/// The picker could not be opened, or there is no room left for a file.+class SwarmPickFailed extends SwarmPickOutcome {+ const SwarmPickFailed(this.message);+ final String message;+}++/// Photos are scaled to at most this many pixels on their long side and sent as JPEG at+/// [_photoQuality]: a phone's own photo can be past the 10 MB a file may be, and a HEIC one is not+/// a picture Desktop shows. A PNG or a GIF keeps its kind.+const double _photoMaxSide = 4096;+const int _photoQuality = 85;++/// The system's photo picker for up to [limit] photos — PHPicker on iOS, the photo picker on+/// Android. Neither asks for a permission: each hands over only the photos the person chose, and+/// no metadata is asked for, which on iOS would ask for the whole library. Empty is the person+/// backing out. Replaced in tests, where there is no picker to open.+@visibleForTesting+Future<List<XFile>> Function(int limit) pickSwarmPhotos = (limit) =>+ ImagePicker().pickMultiImage(+ limit: limit,+ maxWidth: _photoMaxSide,+ maxHeight: _photoMaxSide,+ imageQuality: _photoQuality,+ requestFullMetadata: false,+ );++/// The camera, for one photo; asks for the camera the first time. Null is the person backing out.+@visibleForTesting+Future<XFile?> Function() takeSwarmPhoto = () => ImagePicker().pickImage(+ source: ImageSource.camera,+ maxWidth: _photoMaxSide,+ maxHeight: _photoMaxSide,+ imageQuality: _photoQuality,+ requestFullMetadata: false,+);++/// The system's document picker for any number of files — Files on iOS, the Storage Access+/// Framework on Android — with no storage permission. Empty is the person backing out.+@visibleForTesting+Future<List<XFile>> Function() pickSwarmFiles = () => openFiles();++/// The app's own temporary folders, where the pickers leave their copies: Dart's temporary folder+/// (the app's `tmp/` on iOS, where image_picker and the document picker copy to) and the one+/// path_provider names (the cache folder on Android, where both copy to). Replaced in tests.+@visibleForTesting+Future<List<String>> Function() swarmPickerCopyFolders = () async => [+ Directory.systemTemp.path,+ (await getTemporaryDirectory()).path,+];++/// Opens [source] and adds what the person picks to [files], by Desktop's limits: ten files a+/// message, 10 MB each — reading no more files than there is room for, and naming any left out,+/// over the size or empty. Photos are named `photo.jpg`, `photo-2.jpg`… since a picker names them by+/// no name a person would know; other files keep their own.+///+/// Each picker hands over its own copy of the file in the app's private temporary folder; it is+/// read into memory and deleted at once, kept or not, so no photo stays on the phone. A file+/// outside those folders is read and left where it is. Nothing is+/// added once [stillWanted] fails: the chat closed while its picker was up.+Future<SwarmPickOutcome> addSwarmPicked(+ SwarmOutgoingFiles files,+ SwarmPickSource source, {+ bool Function() stillWanted = _always,+}) async {+ final room = files.room;+ if (room <= 0) {+ return const SwarmPickFailed(+ 'Attach at most $swarmAttachmentMaxFiles files.',+ );+ }+ final List<XFile> picked;+ try {+ picked = switch (source) {+ SwarmPickSource.library => await pickSwarmPhotos(room),+ SwarmPickSource.camera => [?await takeSwarmPhoto()],+ SwarmPickSource.files => await pickSwarmFiles(),+ };+ } on PlatformException catch (error) {+ // A refusal arrives as one rather than as a cancel, and it is the one failure the person can+ // do something about.+ if (error.code == 'camera_access_denied') {+ return const SwarmPickDenied(SwarmPickSource.camera);+ }+ if (error.code == 'photo_access_denied') {+ return const SwarmPickDenied(SwarmPickSource.library);+ }+ return SwarmPickFailed(+ source == SwarmPickSource.camera+ ? 'Could not open the camera.'+ : 'Could not open the picker.',+ );+ }+ final copies = await _copyFolders();+ void delete(XFile file) => _delete(file, copies);+ // The chat can have closed while the picker was up — signed out, say: nothing goes into it.+ if (!stillWanted()) {+ for (final file in picked) {+ delete(file);+ }+ return const SwarmPicked(null);+ }+ final photos = source != SwarmPickSource.files;+ final taken = {for (final file in files.files) file.name};+ final read = <SwarmOutgoingFile>[];+ final oversized = <String>[], empty = <String>[];+ var surplus = 0;+ String? unreadable;+ for (final file in picked) {+ // Past the room left, a file is counted, never read: forty 9 MB files+ // picked at once would otherwise all be held in memory to be refused.+ if (read.length >= room) {+ surplus++;+ delete(file);+ continue;+ }+ final own = file.name.isEmpty ? 'file' : file.name;+ final name = photos ? swarmFreeName(_photoName(own), taken) : own;+ try {+ final bytes = await _read(file);+ if (bytes == null) {+ oversized.add(name);+ } else if (bytes.isEmpty) {+ empty.add(name);+ } else {+ read.add(SwarmOutgoingFile(name, bytes));+ }+ } catch (_) {+ unreadable ??= name;+ } finally {+ delete(file);+ }+ }+ final notes = [+ ?files.add(read, oversized: oversized, surplus: surplus),+ if (empty.length == 1) '${empty.single} is empty.',+ if (empty.length > 1) '${empty.length} files are empty.',+ if (unreadable != null) 'Could not read $unreadable.',+ ];+ return SwarmPicked(notes.isEmpty ? null : notes.join(' '));+}++bool _always() => true;++/// [file]'s bytes, or null when it is past the limit, which is measured before it is read so a+/// large file is never held whole.+Future<Uint8List?> _read(XFile file) async {+ int? size;+ try {+ size = await file.length();+ } catch (_) {+ // No size to read is no reason to refuse yet: the read says whether the file is there.+ }+ if (size != null && size > swarmAttachmentMaxBytes) return null;+ final bytes = await file.readAsBytes();+ return bytes.length > swarmAttachmentMaxBytes ? null : bytes;+}++/// [swarmPickerCopyFolders], each as its real path; none when they cannot be read, and then+/// nothing is deleted.+Future<List<String>> _copyFolders() async {+ try {+ return [for (final folder in await swarmPickerCopyFolders()) _real(folder)];+ } catch (_) {+ return const [];+ }+}++/// [path] with its links resolved (iOS reaches the app's folders through `/private`), or as given+/// when it is not there to resolve.+String _real(String path) {+ try {+ return File(path).resolveSymbolicLinksSync();+ } catch (_) {+ return p.normalize(p.absolute(path));+ }+}++/// Deletes the picker's copy of [file] — only when it lies in one of the app's own temporary+/// [folders], where image_picker and file_selector put the copies they hand over. A file anywhere+/// else could be the person's original, and is never touched. At once rather than awaited: one+/// small file, gone before anything else runs.+void _delete(XFile file, List<String> folders) {+ if (kIsWeb || file.path.isEmpty) return;+ final path = _real(file.path);+ if (!folders.any((folder) => p.isWithin(folder, path))) return;+ try {+ File(path).deleteSync();+ } catch (_) {+ // Already gone, or never written: nothing of it is left to keep.+ }+}++/// `photo` with the kind of the picker's file: `.jpg` unless it kept a PNG or a GIF.+String _photoName(String picked) {+ final dot = picked.lastIndexOf('.');+ final extension = dot < 0 ? '' : picked.substring(dot + 1).toLowerCase();+ return switch (extension) {+ 'png' || 'gif' || 'webp' => 'photo.$extension',+ _ => 'photo.jpg',+ };+}diff --git a/mobile/lib/swarm/swarm_home_cache.dart b/mobile/lib/swarm/swarm_home_cache.dartnew file mode 100644index 000000000..43b74ae52--- /dev/null+++ b/mobile/lib/swarm/swarm_home_cache.dart@@ -0,0 +1,200 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:cryptography/cryptography.dart';+import 'package:cryptography/dart.dart';+import 'package:flutter_secure_storage/flutter_secure_storage.dart';++import '../core/harness_file_store.dart';+import '../e2ee/bytes.dart';+import 'swarm_home_view.dart';++export 'swarm_home_view.dart';++/// One Swarm of the Home kept: its listing and its view.+typedef SwarmHomeEntry = ({String id, String name, SwarmHomeSwarm view});++/// The Keychain item the kept Home is sealed under.+abstract interface class SwarmHomeKey {+ Future<String?> read();+ Future<void> write(String value);+ Future<void> delete();+}++/// [SwarmHomeKey] in the iOS Keychain (Android: Keystore-backed), readable+/// after the first unlock and never carried to another device or a backup.+class KeychainSwarmHomeKey implements SwarmHomeKey {+ const KeychainSwarmHomeKey();++ static const _storage = FlutterSecureStorage(+ iOptions: IOSOptions(+ accessibility: KeychainAccessibility.first_unlock_this_device,+ ),+ );+ static const _name = 'swarm_home_key';++ @override+ Future<String?> read() => _storage.read(key: _name);++ @override+ Future<void> write(String value) => _storage.write(key: _name, value: value);++ @override+ Future<void> delete() => _storage.delete(key: _name);+}++/// The last Swarm Home of the signed-in account, kept so a cold start draws+/// it at once and reads after (owner, 2026-10-27). Only what Home draws+/// ([swarmHomeSwarm]), sealed with ChaCha20-Poly1305 under a random key in+/// the Keychain, in [file] beside the app's state. One account's at a time.+///+/// A view that does not open — no key, another account's, a damaged file —+/// is none, and goes: never an error. [clear] takes the key too, so a file+/// left behind opens for nobody.+class SwarmHomeCache {+ SwarmHomeCache({required this.key, required this.file});++ /// The device's: the Keychain, and a file beside the app's state.+ factory SwarmHomeCache.device() => SwarmHomeCache(+ key: const KeychainSwarmHomeKey(),+ file: File('${HarnessFileStore.shared.directory.path}/swarm-home.bin'),+ );++ final SwarmHomeKey key;+ final File file;++ static const _format = 1;+ static const _aead = DartChacha20.poly1305Aead();+ static const _nonceBytes = 12, _macBytes = 16;++ Future<void> _tail = Future.value();++ /// One operation at a time: a clear is never undone by a write before it.+ Future<T> _serial<T>(Future<T> Function() action) {+ final run = _tail.then((_) => action());+ _tail = run.then((_) {}, onError: (Object _) {});+ return run;+ }++ /// [accountId]'s Home as kept, or null: none, or none that opens.+ Future<List<SwarmHomeEntry>?> read(String accountId) => _serial(() async {+ try {+ if (!await file.exists()) return null;+ final secret = await key.read();+ final opened = secret == null+ ? null+ : _open(b64d(secret), await file.readAsBytes());+ final kept = opened == null ? null : _entries(opened, accountId);+ if (kept == null) await _forget();+ return kept;+ } catch (_) {+ await _forget();+ return null;+ }+ });++ /// Keeps [swarms] as [accountId]'s Home. Best effort: a Keychain or disk+ /// that refuses keeps nothing, and says nothing.+ Future<void> write(String accountId, List<SwarmHomeEntry> swarms) =>+ _serial(() async {+ try {+ var secret = await key.read();+ if (secret == null) {+ secret = b64e(secureRandomBytes(32));+ await key.write(secret);+ }+ final clear = utf8.encode(+ jsonEncode({+ 'format': _format,+ 'account': accountId,+ 'swarms': [+ for (final s in swarms)+ {+ 'id': s.id,+ 'name': s.name,+ 'state': s.view.state,+ 'partners': s.view.partners,+ },+ ],+ }),+ );+ final nonce = secureRandomBytes(_nonceBytes);+ final box = _aead.encryptSync(+ clear,+ secretKey: SecretKeyData(b64d(secret)),+ nonce: nonce,+ );+ await file.parent.create(recursive: true);+ await File('${file.path}.next')+ .writeAsBytes(box.concatenation(), flush: true);+ await File('${file.path}.next').rename(file.path);+ } catch (_) {+ await _forget();+ }+ });++ /// Nothing kept: no view, and no key it could be opened with.+ Future<void> clear() => _serial(() async {+ await _forget();+ try {+ await key.delete();+ } catch (_) {}+ });++ Future<void> _forget() async {+ for (final path in [file.path, '${file.path}.next']) {+ try {+ await File(path).delete();+ } on FileSystemException {+ // Not there.+ }+ }+ }++ static Map<String, dynamic>? _open(Uint8List secret, Uint8List sealed) {+ if (sealed.length < _nonceBytes + _macBytes) return null;+ try {+ final clear = _aead.decryptSync(+ SecretBox.fromConcatenation(+ sealed,+ nonceLength: _nonceBytes,+ macLength: _macBytes,+ ),+ secretKey: SecretKeyData(secret),+ );+ final json = jsonDecode(utf8.decode(clear));+ return json is Map<String, dynamic> ? json : null;+ } on SecretBoxAuthenticationError {+ return null;+ }+ }++ static List<SwarmHomeEntry>? _entries(+ Map<String, dynamic> kept,+ String accountId,+ ) {+ if (kept['format'] != _format || kept['account'] != accountId) return null;+ return [+ for (final raw in kept['swarms'] as List)+ if (raw case {+ 'id': final String id,+ 'name': final String name,+ 'state': final Map<String, dynamic> state,+ 'partners': final Map<String, dynamic> partners,+ })+ (+ id: id,+ name: name,+ view: (+ state: state,+ partners: {+ for (final MapEntry(:key, :value) in partners.entries)+ if (value is String) key: value,+ },+ ),+ ),+ ];+ }+}diff --git a/mobile/lib/swarm/swarm_home_keeper.dart b/mobile/lib/swarm/swarm_home_keeper.dartnew file mode 100644index 000000000..f311df7b3--- /dev/null+++ b/mobile/lib/swarm/swarm_home_keeper.dart@@ -0,0 +1,84 @@+import 'dart:async';++import 'swarm_home_cache.dart';+import 'swarm_reader.dart';++/// [reader] holds only the view kept ([SwarmHomeCache]), no read of its+/// own: a first load moves its generation. What it shows is the last+/// update's, not now — a first read that failed changes none of it.+bool swarmHomeKept(SwarmReader? reader) =>+ reader != null && reader.generation == 0 && reader.snapshot != null;++/// What keeps an inbox's Home in its [SwarmHomeCache]: at once when a Swarm+/// was read again from nothing, left the list, or its access ended — what was+/// kept may hold what the person can no longer read. Any other change is kept+/// at most once each [wait], and what is left when Harness goes behind+/// ([flush]), so a busy Swarm costs one write in a while, not one a read. No+/// timer: nothing outlives the screens.+class SwarmHomeKeeper {+ SwarmHomeKeeper(this.cache, this.accountId, {required this.wait});++ final SwarmHomeCache cache;+ final String accountId;+ final Duration wait;++ /// Each Swarm's [SwarmReader.generation] as last kept.+ var _kept = <String, int>{};+ DateTime? _wrote;+ bool _pending = false;++ /// The account's Home as kept, or null.+ Future<List<SwarmHomeEntry>?> restore() => cache.read(accountId);++ /// The Swarms listed now ([swarms]) as their [readers] hold them. Nothing+ /// while all that is held is what was kept, and nothing has left.+ void keep(+ Map<String, SwarmReader> readers,+ List<({String id, String name})> swarms,+ ) {+ final read = readers.entries.any(+ (e) => e.value.generation != (_kept[e.key] ?? 0),+ );+ final left = _kept.keys.any((id) => !readers.containsKey(id));+ if (read || left) return _write(readers, swarms);+ if (readers.values.every((r) => r.generation == 0)) return;+ final last = _wrote;+ if (last == null || DateTime.now().difference(last) >= wait) {+ return _write(readers, swarms);+ }+ _pending = true;+ }++ /// Harness goes behind: a change not kept yet is kept now.+ void flush(+ Map<String, SwarmReader> readers,+ List<({String id, String name})> swarms,+ ) {+ if (_pending) _write(readers, swarms);+ }++ void _write(+ Map<String, SwarmReader> readers,+ List<({String id, String name})> swarms,+ ) {+ _pending = false;+ _wrote = DateTime.now();+ _kept = {for (final e in readers.entries) e.key: e.value.generation};+ unawaited(+ cache.write(accountId, [+ for (final swarm in swarms)+ if (readers[swarm.id] case final reader?+ when !reader.accessRevoked && reader.snapshot != null)+ (+ id: swarm.id,+ name: swarm.name,+ view: swarmHomeSwarm(+ reader.snapshot!,+ reader.partners,+ buddies: reader.buddies,+ ),+ ),+ ]),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_home_root.dart b/mobile/lib/swarm/swarm_home_root.dartnew file mode 100644index 000000000..a72cd1669--- /dev/null+++ b/mobile/lib/swarm/swarm_home_root.dart@@ -0,0 +1,135 @@+import 'package:flutter/widgets.dart';++import '../phone/out_of_sight.dart';+import '../settings/experimental_features.dart';++/// What the root of the phone's stack shows. While Settings ▸ Experimental ▸+/// Swarm is on, Swarm Home, until something opens an agent; while it is off,+/// the terminal, as it always was. Turning Swarm on makes Swarm Home the root+/// again.+///+/// The shell's, for its lifetime: the root is built once, inside the+/// navigator's `onGenerateRoute`, so it listens rather than being handed a+/// value.+class SwarmHomeChoice extends ChangeNotifier {+ SwarmHomeChoice(this.features) : _on = features.isOn(PhoneExperiment.swarm) {+ features.addListener(_switched);+ }++ final ExperimentalFeaturesStore features;+ bool _on, _harness = false;++ /// Swarm Home is the root.+ bool get swarm => _on && !_harness;++ /// Harness is the root, with Swarm Home to go back to.+ bool get harnessOverSwarm => _on && _harness;++ void showHarness() {+ if (_harness) return;+ _harness = true;+ notifyListeners();+ }++ void showSwarm() {+ if (!_harness) return;+ _harness = false;+ notifyListeners();+ }++ void _switched() {+ final on = features.isOn(PhoneExperiment.swarm);+ if (on == _on) return;+ _on = on;+ _harness = false;+ notifyListeners();+ }++ @override+ void dispose() {+ features.removeListener(_switched);+ super.dispose();+ }+}++/// The root of the phone's stack: Swarm Home or [harness], as [choice] says.+///+/// Each is built the first time it is shown, and then kept, out of sight,+/// while the other is up: the person comes back to it as they left it — the+/// terminal attached, Home scrolled where it was. Out of sight it paints and+/// builds nothing, takes no touches or focus, and its animations and its+/// listening stop ([OutOfSight]). With Swarm off the terminal is all there is,+/// exactly as before Swarm Home.+class SwarmHomeRoot extends StatefulWidget {+ const SwarmHomeRoot({+ super.key,+ required this.choice,+ required this.harness,+ required this.swarm,+ });++ final SwarmHomeChoice choice;+ final Widget harness;++ /// Swarm Home; made the first time it is shown.+ final WidgetBuilder swarm;++ @override+ State<SwarmHomeRoot> createState() => _SwarmHomeRootState();+}++class _SwarmHomeRootState extends State<SwarmHomeRoot> {+ /// Keep each one's state while the other comes and goes beside it.+ final _harness = GlobalKey(debugLabel: 'harness');+ final _swarm = GlobalKey(debugLabel: 'swarm');++ /// Each as last shown: handed back unchanged while it is out of sight, so a+ /// rebuild of this root (the shell rebuilding the stack under a page pushed+ /// over it) leaves it alone. Null until it is first shown; Swarm Home's+ /// goes again with Swarm turned off.+ Widget? _harnessShown, _swarmShown;++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: widget.choice,+ builder: (context, _) {+ final choice = widget.choice;+ final swarm = choice.swarm;+ if (!swarm) _harnessShown = widget.harness;+ if (swarm) _swarmShown = widget.swarm(context);+ if (!swarm && !choice.harnessOverSwarm) _swarmShown = null;+ return Stack(+ fit: StackFit.expand,+ children: [+ // The terminal holds its output in its buffer while out of sight,+ // and draws it once shown (xterm's own `renderingEnabled`, off with+ // the tickers).+ if (_harnessShown case final harness?)+ _Kept(key: _harness, hidden: swarm, child: harness),+ if (_swarmShown case final home?)+ _Kept(key: _swarm, hidden: !swarm, child: home),+ ],+ );+ },+ );+}++/// [child] at the root, or kept out of sight while [hidden].+class _Kept extends StatelessWidget {+ const _Kept({super.key, required this.hidden, required this.child});++ final bool hidden;+ final Widget child;++ @override+ Widget build(BuildContext context) => Offstage(+ offstage: hidden,+ child: TickerMode(+ enabled: !hidden,+ child: ExcludeFocus(+ excluding: hidden,+ child: OutOfSight(hidden: hidden, child: child),+ ),+ ),+ );+}diff --git a/mobile/lib/swarm/swarm_home_view.dart b/mobile/lib/swarm/swarm_home_view.dartnew file mode 100644index 000000000..bbc4b7cfd--- /dev/null+++ b/mobile/lib/swarm/swarm_home_view.dart@@ -0,0 +1,126 @@+import 'model.dart';+import 'swarm_buddy.dart';++/// One Swarm as Home last drew it: a state [SuperTabSnapshot.fromJson] reads,+/// thinned to what Home, its drawer and a project's rows draw, and each+/// conversation's partner ([swarmPartners]). Its Buddy chats and Buddies say+/// whose they are, as a read does, for [SwarmBuddies.read].+typedef SwarmHomeSwarm = ({+ Map<String, dynamic> state,+ Map<String, String> partners,+});++/// [snapshot] thinned to what Home draws: its projects, its agents by name,+/// engine and status, each conversation's title, project, people and work+/// status, and the built-in pictures people and agents wear. Nothing a chat+/// holds — no message, brief, check, task, question or email, no photo or+/// status — nor machines, starts or what waits on the person, which come+/// with the next read. [buddies] marks the Buddy chats and Buddies, so none+/// is drawn as work before that read.+SwarmHomeSwarm swarmHomeSwarm(+ SuperTabSnapshot snapshot,+ Map<String, String> partners, {+ SwarmBuddies buddies = SwarmBuddies.none,+}) => (+ state: {+ 'version': 1,+ 'id': snapshot.id,+ 'name': snapshot.name,+ 'ownerId': snapshot.ownerId,+ 'paused': snapshot.paused,+ 'leadsConversationId': ?snapshot.leadsConversationId,+ 'projects': [for (final p in snapshot.projects) _project(p)],+ 'people': [+ for (final p in snapshot.people)+ {'id': p.id, 'email': '', 'role': p.role, 'avatar': ?_preset(p.avatar)},+ ],+ 'agents': [+ for (final a in snapshot.agents)+ {+ ..._agent(a),+ if (buddies.buddyOwners[a.id] case final owner?)+ 'buddyOf': {'personId': owner},+ },+ ],+ 'conversations': [+ for (final c in snapshot.conversations)+ {+ ..._conversation(c),+ if (buddies.chatOwners[c.id] case final owner?) ...{+ 'kind': 'buddy',+ 'buddyOwnerId': owner,+ },+ },+ ],+ 'machines': const <Object>[],+ 'starts': const <Object>[],+ 'invitations': const <Object>[],+ },+ partners: {...partners},+);++/// A built-in picture by its name. An uploaded one is not kept: its signed+/// link opens the picture, and comes again with the next read.+Map<String, dynamic>? _preset(SuperTabAvatarPicture? avatar) =>+ switch (avatar) {+ SuperTabPresetAvatar(:final key) => {'kind': 'preset', 'key': key},+ _ => null,+ };++Map<String, dynamic> _project(SuperTabProject p) => {+ 'id': p.id,+ 'name': p.name,+ 'ownerId': p.ownerId,+ 'leadConversationId': p.leadConversationId,+ 'visibility': p.isPrivate ? 'private' : 'public',+ 'members': [+ for (final id in p.memberIds) {'id': id},+ ],+ 'skillMode': p.skillMode,+ 'skillSet': p.skillSet,+ 'updateMinutes': p.updateMinutes,+};++Map<String, dynamic> _agent(SuperTabAgent a) => {+ 'id': a.id,+ 'projectId': a.hasProjectId ? a.projectId : null,+ 'name': a.name,+ 'displayName': ?a.displayName,+ 'machineId': a.machineId,+ 'harnessId': a.harnessId,+ 'contributorId': a.contributorId,+ 'machineOwnerId': a.machineOwnerId,+ 'role': ?a.role,+ 'roleId': ?a.roleId,+ 'limitedUntil': ?a.limitedUntil?.toIso8601String(),+ 'downSince': ?a.downSince?.toIso8601String(),+ 'avatar': ?_preset(a.avatar),+ 'configuration': {+ for (final key in const ['engine', 'model', 'effort'])+ if (a.configuration[key] case final String value) key: value,+ },+};++Map<String, dynamic> _conversation(SuperTabConversation c) => {+ 'id': c.id,+ 'projectId': c.projectId,+ 'number': ?c.number,+ 'title': c.title,+ 'leadId': ?c.leadId,+ 'agentIds': c.agentIds,+ 'archived': c.archived,+ 'dormant': c.dormant,+ if (c.audience case final people?)+ 'audience': {+ 'people': [+ for (final id in people) {'id': id},+ ],+ },+ 'brief': '',+ if (c.assignment case final work?)+ 'assignment': {+ 'id': work['id'],+ 'agentId': work['agentId'],+ 'status': work['status'],+ },+};diff --git a/mobile/lib/swarm/swarm_inbox.dart b/mobile/lib/swarm/swarm_inbox.dartnew file mode 100644index 000000000..7bc468b65--- /dev/null+++ b/mobile/lib/swarm/swarm_inbox.dart@@ -0,0 +1,596 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import '../core/local_key_value_store.dart';+import 'model.dart';+import 'swarm_asks.dart';+import 'swarm_buddy.dart';+import 'swarm_home_cache.dart';+import 'swarm_home_keeper.dart';+import 'swarm_read_marks.dart';+import 'swarm_reader.dart';+import 'swarm_request.dart';+import 'waiting_work.dart';++/// One of the account's Swarms, as the list names it.+typedef SwarmListing = ({String id, String name});++/// What the Swarm page says when the account's server has no Swarm list:+/// one from before Swarm v1, whose one-Swarm route reads "list" as a Swarm's+/// id and answers that it is unavailable (the owner's iPhone, 2026-10-27).+const swarmServerTooOld =+ 'Your Harness server does not support Swarm on the phone yet.';++/// An invitation to a Swarm, as the person's invitations list it: the+/// Swarm's name and the role offered, nothing read of the Swarm itself.+typedef SwarmInvitation = ({+ String tabId,+ String name,+ String inviteId,+ String role,+});++/// Something a Swarm asks of the person, with the Swarm it is in.+sealed class SwarmNeed {+ SwarmNeed(this.swarmId);+ final String swarmId;++ /// The conversation it is about, to open from it.+ String get conversationId;++ /// Stable across reads: what a notice is keyed by.+ String get key;+}++/// A decision asked of the person, answered with one tap.+class SwarmDecisionNeed extends SwarmNeed {+ SwarmDecisionNeed(super.swarmId, this.decision);+ final SuperTabDecision decision;+ @override+ String get conversationId => decision.conversationId;+ @override+ String get key => 'decision:${decision.id}';+}++/// A Lead's tag of the person.+class SwarmMentionNeed extends SwarmNeed {+ SwarmMentionNeed(super.swarmId, this.mention);+ final SuperTabMention mention;+ @override+ String get conversationId => mention.conversationId;+ @override+ String get key => 'mention:${mention.id}';+}++/// Work waiting on the person ([swarmWaitingWork]).+class SwarmWorkNeed extends SwarmNeed {+ SwarmWorkNeed(super.swarmId, this.work);+ final SwarmWaitingWork work;+ @override+ String get conversationId => work.conversation.id;+ @override+ String get key =>+ 'work:$swarmId:${work.conversation.id}:'+ '${work.conversation.assignment?['id']}:${work.status}';+}++/// The account's Swarms on this phone, and everything they ask of the person+/// in one list ([needs]): open decisions first, then Lead tags, then work+/// waiting on them.+///+/// Each read is the list, then one change read per Swarm (whose `derived`+/// counts say whether there are decisions or tags to read). It reads only+/// while [shown], as a [SwarmReader] does. One per account: a Swarm that+/// leaves the list is dropped with everything read of it.+class SwarmInbox extends ChangeNotifier {+ SwarmInbox({+ required this.accountId,+ required this.request,+ this.upload = refuseSwarmUpload,+ this.pollInterval = const Duration(seconds: 15),+ SwarmHomeCache? homeCache,+ Duration homeWait = const Duration(seconds: 30),+ this.readMarks,+ }) : _home = homeCache == null+ ? null+ : SwarmHomeKeeper(homeCache, accountId, wait: homeWait) {+ if (_home != null) unawaited(_restore());+ }++ /// Keeps the last Home ([SwarmHomeCache]), so a cold start draws it at once.+ final SwarmHomeKeeper? _home;++ /// Where each Swarm's read marks are kept on the phone ([SwarmReadMarks]);+ /// null keeps them in memory only.+ final LocalKeyValueStore? readMarks;++ /// Draws the Home kept until the list is read: each Swarm's reader holds+ /// the view kept, which its first read replaces. One that does not read+ /// back is not drawn.+ Future<void> _restore() async {+ final kept = await _home!.restore();+ if (kept == null || _disposed || loaded || swarms.isNotEmpty) return;+ final shown = <SwarmListing>[];+ for (final swarm in kept) {+ final SuperTabSnapshot snapshot;+ try {+ snapshot = SuperTabSnapshot.fromJson(swarm.view.state);+ } on FormatException {+ continue;+ }+ final buddies = SwarmBuddies.read(swarm.view.state, accountId);+ swarmMarkBuddies(snapshot, buddies);+ _readers.putIfAbsent(swarm.id, () => _open(swarm.id))+ ..snapshot = snapshot+ ..partners = swarm.view.partners+ ..buddies = buddies;+ shown.add((id: swarm.id, name: swarm.name));+ }+ swarms = List.unmodifiable(shown);+ _rebuild(told: true);+ }++ final String accountId;+ final SwarmRequest request;++ /// Handed to each Swarm's reader, for its chats' files.+ final SwarmUpload upload;+ final Duration pollInterval;++ /// The account's Swarms, in the list's order.+ List<SwarmListing> swarms = const [];++ /// What the Swarms ask of the person, across all of them.+ List<SwarmNeed> needs = const [];++ /// What the last read of the list could not do; null once one succeeds.+ String? error;++ /// True once the list has been read.+ bool loaded = false;++ /// Invitations waiting for the person, read only while they have no Swarm.+ List<SwarmInvitation> invitations = const [];++ /// The last read of the invitations failed, while there is no Swarm: not "no invitation".+ /// Those read before stay meanwhile.+ bool invitationsFailed = false;++ /// Invitations being accepted.+ final Set<String> joining = {};++ /// What the last [join] could not do; null once one succeeds.+ String? joinError;++ /// Invitations put off with Not now: not offered again this session, and+ /// left as they are on the server.+ final _putOff = <String>{};++ /// The last read of the list failed for want of a computer to ask.+ bool get noComputer => _away != null;++ /// Accepts [invitation] (the desktop's Tab invites), under one receipt per+ /// invitation so a retry is the same accept, then reads the list.+ Future<bool> join(SwarmInvitation invitation) async {+ if (_disposed || !joining.add(invitation.inviteId)) return false;+ joinError = null;+ notifyListeners();+ try {+ await request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(invitation.tabId)}/commands',+ body: {+ 'operationId': 'accept-${invitation.inviteId}',+ 'command': {'type': 'invite.accept', 'inviteId': invitation.inviteId},+ },+ );+ } on SuperTabFailure catch (failure) {+ joinError = failure.message;+ return false;+ } catch (_) {+ joinError = 'Could not join. Try again.';+ return false;+ } finally {+ joining.remove(invitation.inviteId);+ if (!_disposed) notifyListeners();+ }+ await refresh();+ return true;+ }++ /// Leaves [invitation] for now: it stays on the server, and the start+ /// screen goes on to what else there is.+ void notNow(SwarmInvitation invitation) {+ if (!_putOff.add(invitation.inviteId)) return;+ invitations = List.unmodifiable(+ invitations.where((other) => other.inviteId != invitation.inviteId),+ );+ joinError = null;+ notifyListeners();+ }++ /// The person's invitations; none from a server without the list, which+ /// reads "invitations" as a Swarm's id and answers that it is not found. A+ /// read that fails, or answers anything but the list, throws: it is not "no+ /// invitation" (#1802's review).+ Future<List<SwarmInvitation>> _invitations() async {+ final Object? answer;+ try {+ answer = await request('GET', '/api/super-tabs/invitations');+ } on SuperTabFailure catch (failure) {+ // A server with the invitations never answers them "not found".+ if (failure.statusCode == 404) return const [];+ rethrow;+ }+ if (answer is! List) throw const FormatException('Missing invitations');+ final invitations = <SwarmInvitation>[];+ for (final raw in answer) {+ if (raw+ case {+ 'tabId': final String tabId,+ 'name': final String name,+ 'inviteId': final String inviteId,+ }+ when raw['role'] is String?) {+ if (_putOff.contains(inviteId)) continue;+ invitations.add((+ tabId: tabId,+ name: name,+ inviteId: inviteId,+ role: raw['role'] as String? ?? '',+ ));+ } else {+ throw const FormatException('Invalid invitation');+ }+ }+ return invitations;+ }++ /// An ask or waiting work that arrived after its Swarm's first read: what a+ /// phone notice tells.+ void Function(SwarmNeed need)? onArrived;++ final _readers = <String, SwarmReader>{};+ final _asks = <String, SwarmAsks>{};++ /// Each Swarm's waiting work as last seen: null until its first read, whose+ /// waiting work is not news.+ final _workSeen = <String, Set<String>>{};+ Future<void>? _refreshing;+ Timer? _poll;+ bool _shown = false, _disposed = false;++ /// A read of the list is under way: what its Swarms tell meanwhile is+ /// told once, at its end.+ bool _polling = false;++ /// A Swarm's reader or asks told of a change since the last notify.+ bool _below = false;++ /// While no computer can be asked, the next read comes this soon — 2 seconds, doubling up to+ /// [pollInterval] — so Swarm is back within seconds of one coming up, not at the next poll.+ /// Null once a read gets through.+ Duration? _away;++ /// [id]'s reader, while it is listed.+ SwarmReader? reader(String id) => _readers[id];++ /// [id]'s decisions and tags, while it is listed.+ SwarmAsks? asks(String id) => _asks[id];++ bool get shown => _shown;++ /// One of the account's computers came up: while none could be asked, the+ /// list is read now, not at the next quick try ([_away]) — at a cold start+ /// the socket comes up after the first read failed, and that try was 2 to+ /// 8 seconds off. A read under way is read again once it ends.+ void computerUp() {+ if (_disposed || !_shown || !noComputer) return;+ if (_refreshing case final reading?) {+ unawaited(reading.whenComplete(computerUp));+ return;+ }+ _poll?.cancel();+ _poll = null;+ unawaited(_tick());+ }++ /// On screen (or wanted for notices): reads at once and every+ /// [pollInterval] after. Otherwise reads nothing.+ set shown(bool value) {+ if (_shown == value) return;+ _shown = value;+ _poll?.cancel();+ _poll = null;+ if (value) {+ unawaited(_tick());+ } else {+ _home?.flush(_readers, swarms);+ }+ }++ Future<void> _tick() async {+ await refresh();+ if (_disposed || !_shown) return;+ _poll?.cancel();+ _poll = Timer(_away ?? pollInterval, () => unawaited(_tick()));+ }++ /// One read now, joining one under way.+ Future<void> refresh() {+ if (_disposed) return Future.value();+ return _refreshing ??= _read().whenComplete(() => _refreshing = null);+ }++ /// What a screen draws of the inbox itself: a read that leaves it as it+ /// was tells nobody.+ Object get _face =>+ (swarms, error, loaded, invitations, invitationsFailed, noComputer);++ Future<void> _read() async {+ final before = _face;+ _polling = true;+ try {+ final (:listed, :changedAt) = await _list();+ List<SwarmInvitation>? invited = const [];+ Object? unread;+ if (listed.isEmpty) {+ try {+ invited = await _invitations();+ } catch (failure) {+ (invited, unread) = (null, failure);+ }+ }+ if (_disposed) return;+ if (!listEquals(listed, swarms)) swarms = listed;+ // What was read of them stays while they cannot be read again.+ if (invited != null && !listEquals(invited, invitations)) {+ invitations = invited;+ }+ invitationsFailed = unread != null;+ loaded = true;+ error = null;+ _away = unread is SuperTabFailure && unread.code == 'MACHINE_UNAVAILABLE'+ ? _sooner()+ : null;+ final ids = {for (final swarm in listed) swarm.id};+ for (final id in _readers.keys.toList()) {+ if (!ids.contains(id)) _drop(id);+ }+ for (final swarm in listed) {+ _readers.putIfAbsent(swarm.id, () => _open(swarm.id));+ }+ await Future.wait([+ for (final swarm in listed)+ if (_due(swarm.id, changedAt[swarm.id] ?? 0))+ _readers[swarm.id]!.refresh(),+ ]);+ } on SuperTabFailure catch (failure) {+ if (_disposed) return;+ error = failure.message;+ _away = failure.code == 'MACHINE_UNAVAILABLE' ? _sooner() : null;+ } catch (_) {+ if (_disposed) return;+ error = 'Could not load your Swarms. Try again.';+ _away = null;+ } finally {+ _polling = false;+ }+ _rebuild(told: _face != before);+ }++ /// The next quick read while no computer can be asked ([_away]).+ Duration _sooner() {+ final next = _away == null ? const Duration(seconds: 2) : _away! * 2;+ return next < pollInterval ? next : pollInterval;+ }++ /// Whether a poll reads Swarm [id] again, listed as last changed at+ /// [listedAt]: only when there may be something new. Its last change+ /// moved; it holds no Swarm yet, or its last read failed; or an ask waits+ /// in it, or its asks could not be read — decisions and tags are not+ /// parts, and one answered or done on another device moves no last-change+ /// time.+ bool _due(String id, int listedAt) {+ final reader = _readers[id]!, asks = _asks[id]!;+ final snapshot = reader.snapshot;+ return snapshot == null ||+ reader.error != null ||+ reader.lastChangedAt != listedAt ||+ snapshot.decisionsWaiting > 0 ||+ snapshot.mentionsWaiting > 0 ||+ asks.decisions.isNotEmpty ||+ asks.mentions.isNotEmpty ||+ asks.error != null;+ }++ /// Every page of the list before any is applied: a failed page cannot drop+ /// Swarms (the desktop's `refreshTabs`). With each Swarm's last change, 0+ /// for one never changed.+ Future<({List<SwarmListing> listed, Map<String, int> changedAt})>+ _list() async {+ final listed = <String, SwarmListing>{};+ final changedAt = <String, int>{};+ final cursors = <String>{};+ String? after;+ do {+ final Object? answer;+ try {+ answer = await request(+ 'GET',+ '/api/super-tabs/list'+ '${after == null ? '' : '?after=${Uri.encodeQueryComponent(after)}'}',+ );+ } on SuperTabFailure catch (failure) {+ // A server with the list never answers it "not found".+ if (failure.statusCode != 404) rethrow;+ throw SuperTabFailure(+ 'SWARM_UNSUPPORTED',+ swarmServerTooOld,+ statusCode: failure.statusCode,+ );+ }+ final page = superTabMap(answer);+ if (page['tabs'] is! List) throw const FormatException('Missing tabs');+ for (final raw in page['tabs'] as List) {+ final row = superTabMap(raw);+ if (row['id'] is! String || row['name'] is! String) {+ throw const FormatException('Invalid tab');+ }+ final id = row['id'] as String;+ listed[id] = (id: id, name: row['name'] as String);+ changedAt[id] = (row['lastChangedAt'] as num?)?.toInt() ?? 0;+ }+ after = page['next'] as String?;+ if (after != null && !cursors.add(after)) {+ throw const FormatException('Repeated tab cursor');+ }+ } while (after != null);+ return (listed: listed.values.toList(), changedAt: changedAt);+ }++ SwarmReader _open(String id) {+ final reader = SwarmReader(+ tabId: id,+ accountId: accountId,+ request: request,+ upload: upload,+ )..addListener(_relay);+ reader.readMarks = SwarmReadMarks(reader, store: readMarks)+ ..addListener(_relay);+ _asks[id] = SwarmAsks(reader)+ ..onArrived = ((ask) => onArrived?.call(switch (ask) {+ final SuperTabDecision decision => SwarmDecisionNeed(id, decision),+ final SuperTabMention mention => SwarmMentionNeed(id, mention),+ _ => throw StateError('Unknown ask $ask'),+ }))+ ..addListener(_asked);+ return reader;+ }++ /// A Swarm off the list ([lost]), or the inbox closing: what a screen+ /// still holds of it is taken back ([SwarmReader.revoke]) before it is+ /// dropped.+ void _drop(String id, {bool lost = true}) {+ _asks.remove(id)?.dispose();+ final reader = _readers.remove(id)?..removeListener(_relay);+ if (reader != null) {+ final marks = reader.readMarks;+ // Lost, it is revoked first, so its read marks leave the phone too;+ // the inbox closing keeps them, written now, for the next one.+ if (!lost) marks?.dispose();+ reader.revoke();+ if (lost) marks?.dispose();+ reader.dispose();+ }+ _workSeen.remove(id);+ }++ /// A Swarm's reader told of a change: what it holds is drawn through the+ /// inbox (Home's projects, the work waiting), so it is told on, once per+ /// list read at most.+ void _relay() {+ _below = true;+ if (!_polling) _rebuild();+ }++ /// A Swarm's asks told of a change: shown at once, poll or not. A Done or+ /// an answer is the person's own tap, and a slow read of another Swarm+ /// must not hold it back.+ void _asked() {+ _below = true;+ _rebuild();+ }++ /// Works out [needs] again; notifies when they, the inbox itself ([told])+ /// or a Swarm below it changed.+ void _rebuild({bool told = false}) {+ if (_disposed) return;+ final decisions = <SwarmNeed>[], mentions = <SwarmNeed>[];+ final work = <SwarmNeed>[];+ for (final MapEntry(key: id, value: reader) in _readers.entries) {+ final snapshot = reader.snapshot;+ if (snapshot == null) continue;+ final asks = _asks[id]!;+ decisions.addAll([+ for (final d in asks.decisions) SwarmDecisionNeed(id, d),+ ]);+ mentions.addAll([for (final m in asks.mentions) SwarmMentionNeed(id, m)]);+ final waiting = [+ for (final w in swarmWaitingWork(+ snapshot,+ accountId,+ partners: reader.partners,+ ))+ SwarmWorkNeed(id, w),+ ];+ final seen = _workSeen[id];+ if (seen != null) {+ for (final need in waiting) {+ if (!seen.contains(need.key)) onArrived?.call(need);+ }+ }+ // The Home kept is not a read: what it shows waiting is not seen.+ if (reader.generation > 0) {+ _workSeen[id] = {for (final need in waiting) need.key};+ }+ work.addAll(waiting);+ }+ int newest(SwarmNeed a, SwarmNeed b) =>+ (_at(b) ?? DateTime(0)).compareTo(_at(a) ?? DateTime(0));+ final next = [+ ...decisions..sort(newest),+ ...mentions..sort(newest),+ ...work,+ ];+ final same = _sameNeeds(next, needs);+ if (!same) needs = List.unmodifiable(next);+ final tell = told || !same || _below;+ _below = false;+ if (!tell) return;+ notifyListeners();+ _home?.keep(_readers, swarms);+ }++ /// The same asks of the same reads, in the same order: decisions and tags+ /// as their [SwarmAsks] keeps them, work of the same snapshot.+ static bool _sameNeeds(List<SwarmNeed> a, List<SwarmNeed> b) {+ if (a.length != b.length) return false;+ for (var n = 0; n < a.length; n++) {+ final same = switch ((a[n], b[n])) {+ (+ SwarmDecisionNeed(decision: final x),+ SwarmDecisionNeed(decision: final y),+ ) =>+ identical(x, y),+ (+ SwarmMentionNeed(mention: final x),+ SwarmMentionNeed(mention: final y),+ ) =>+ identical(x, y),+ (final SwarmWorkNeed x, final SwarmWorkNeed y) =>+ x.key == y.key && identical(x.work.snapshot, y.work.snapshot),+ _ => false,+ };+ if (!same || a[n].swarmId != b[n].swarmId) return false;+ }+ return true;+ }++ static DateTime? _at(SwarmNeed need) => switch (need) {+ SwarmDecisionNeed(:final decision) => decision.createdAt,+ SwarmMentionNeed(:final mention) => mention.createdAt,+ SwarmWorkNeed() => null,+ };++ @override+ void dispose() {+ _disposed = true;+ _poll?.cancel();+ for (final id in _readers.keys.toList()) {+ _drop(id, lost: false);+ }+ super.dispose();+ }+}diff --git a/mobile/lib/swarm/swarm_leaderboard.dart b/mobile/lib/swarm/swarm_leaderboard.dartnew file mode 100644index 000000000..14facd557--- /dev/null+++ b/mobile/lib/swarm/swarm_leaderboard.dart@@ -0,0 +1,843 @@+import 'dart:async';++import 'package:clock/clock.dart';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/phone_navigation.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/shared/widgets/touch_target.dart';++import 'identity.dart';+import 'model.dart';+import 'swarm_leaderboard_reader.dart';+import 'swarm_reader.dart';+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';++/// Opens [projectId]'s leaderboard over [context]'s page.+void openSwarmLeaderboard(+ BuildContext context,+ String swarmId,+ String projectId,+) => unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => SwarmLeaderboardPage(swarmId: swarmId, projectId: projectId),+ listensForItself: true,+ ),+ ),+);++/// One project's leaderboard, built as the design system's Numbers and+/// rankings at phone sizes, the same structure as the desktop's Humans: the+/// team's week first, as quiet text with the week picker beside it; then a row+/// for each person: their rank as a bold numeral in its own column, the face+/// they chose, their name over their non-zero numbers in words, the change+/// against last week and their points, the one emphasized number. The+/// viewer's own row has the selected fill. A row opens the person's week in a+/// sheet. No cups, medals or emoji.+///+/// People are named from the members its Swarm already read; the board+/// itself is read on open, on a pull, on another week, and every few minutes+/// while the app is in front ([SwarmLeaderboardReader]).+class SwarmLeaderboardPage extends StatefulWidget {+ const SwarmLeaderboardPage({+ super.key,+ required this.swarmId,+ required this.projectId,+ this.now = DateTime.now,+ });++ final String swarmId, projectId;++ /// What tells this week from the ones before.+ final DateTime Function() now;++ @override+ State<SwarmLeaderboardPage> createState() => _SwarmLeaderboardPageState();+}++class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {+ SwarmSession? _session;++ /// The Swarm's reader, for the members' names; null until it is listed.+ SwarmReader? _swarm;+ SwarmLeaderboardReader? _board;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final session = SwarmScope.of(context);+ if (session == _session) return;+ _session?.inbox.removeListener(_attach);+ _session?.leave();+ _session = session?..enter();+ // Another account, or none: nothing of the last one's board stays, and+ // its reads stop.+ _forget();+ session?.inbox.addListener(_attach);+ _attach();+ // Not listed yet: the inbox tells when it is.+ if (_swarm == null) unawaited(session?.inbox.refresh());+ }++ /// Follows the Swarm's reader once the inbox has one, and reads the board+ /// through it.+ void _attach() {+ final session = _session;+ final swarm = session?.inbox.reader(widget.swarmId);+ if (session == null || swarm == null || identical(swarm, _swarm)) return;+ _swarm?.removeListener(_changed);+ _swarm = swarm..addListener(_changed);+ _board?.dispose();+ _board = SwarmLeaderboardReader(+ tabId: swarm.tabId,+ projectId: widget.projectId,+ request: swarm.request,+ inFront: () => session.inbox.shown,+ )..addListener(_changed);+ _board!.start();+ _changed();+ }++ void _changed() {+ if (mounted) setState(() {});+ }++ void _forget() {+ _swarm?.removeListener(_changed);+ _swarm = null;+ _board?.dispose();+ _board = null;+ }++ @override+ void dispose() {+ _session?.inbox.removeListener(_attach);+ _session?.leave();+ _swarm?.removeListener(_changed);+ _board?.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final snapshot = _swarm?.snapshot;+ final project = snapshot?.projects+ .where((p) => p.id == widget.projectId)+ .firstOrNull;+ return Scaffold(+ backgroundColor: AppPalette.windowBg,+ body: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SwarmTopBar(+ leading: SwarmBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ title: 'Leaderboard',+ subtitle: project?.name,+ ),+ Expanded(+ child: RefreshIndicator(+ onRefresh: _board?.refresh ?? () async {},+ child: ListView(+ physics: const AlwaysScrollableScrollPhysics(),+ // Rows draw their own inner gap, so their content meets the+ // screen's side inset.+ padding: EdgeInsets.fromLTRB(+ AppSpace.screenInset - AppSpace.s,+ 0,+ AppSpace.screenInset - AppSpace.s,+ MediaQuery.paddingOf(context).bottom + AppSpace.xl,+ ),+ children: _body(context, snapshot),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }++ List<Widget> _body(BuildContext context, SuperTabSnapshot? snapshot) {+ final reader = _board;+ final board = reader?.board;+ final current = swarmWeekOf(widget.now());+ // Signed out, or Swarm turned off: no account's board to show.+ if (_session == null) return const [];+ if (reader != null && reader.unavailable) {+ return [+ const SizedBox(height: AppSpace.m),+ SwarmRow.line(+ "This Swarm's server has no leaderboard yet.",+ key: const ValueKey('swarm-leaderboard-unavailable'),+ lines: 2,+ ),+ ];+ }+ // The members name the people; until the Swarm is read, the rows wait.+ final error = reader?.error ?? (snapshot == null ? _swarm?.error : null);+ final people = snapshot?.people ?? const <SuperTabPerson>[];+ SuperTabPerson? personOf(String id) =>+ people.where((p) => p.id == id).firstOrNull;+ String nameOf(SwarmScore score) => switch (personOf(score.personId)) {+ final person? => score.displayName ?? superTabPersonName(person.email),+ null => 'Former member',+ };+ final week = swarmWeekName(reader?.week, current);+ final pickWeek = reader == null+ ? null+ : () => unawaited(_pickWeek(context, reader, current));+ final columns = board == null || board.people.isEmpty+ ? null+ : _Columns.of(context, board.people);+ final viewer = _swarm?.accountId;+ return [+ _TeamLine(+ week: week,+ shipped: board?.shipped,+ before: board?.shippedBefore,+ onWeek: pickWeek,+ ),+ if (error != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.s,+ 0,+ AppSpace.s,+ AppSpace.s,+ ),+ child: SwarmRow.line(+ error,+ key: const ValueKey('swarm-leaderboard-error'),+ lines: 3,+ ),+ ),+ if (board == null || snapshot == null)+ if (error == null)+ SwarmSkeletonRows(+ id: 'swarm-leaderboard-loading',+ rows: 4,+ round: true,+ )+ else+ Align(+ alignment: Alignment.centerLeft,+ child: SwarmButton(+ label: 'Try again',+ onPressed: () => unawaited(+ Future.wait([+ ?reader?.refresh(),+ if (snapshot == null) ?_swarm?.refresh(),+ ]),+ ),+ ),+ )+ else if (board.people.isEmpty)+ SwarmRow.line('Nobody is on the board yet.')+ else+ for (final score in board.people)+ _PersonRow(+ score: score,+ person: personOf(score.personId),+ name: nameOf(score),+ own: score.personId == viewer,+ columns: columns!,+ onTap: () => unawaited(+ _showPerson(+ context,+ score,+ personOf(score.personId),+ nameOf(score),+ ),+ ),+ ),+ ];+ }++ /// The four weeks the board keeps, this one first, in a sheet.+ Future<void> _pickWeek(+ BuildContext context,+ SwarmLeaderboardReader reader,+ int current,+ ) async {+ final shown = reader.week ?? current;+ final week = await showModalBottomSheet<int>(+ context: context,+ backgroundColor: AppGlass.rowFill,+ showDragHandle: true,+ shape: AppControl.sheetShape,+ builder: (context) => _Sheet(+ title: 'Week',+ closeKey: 'swarm-leaderboard-week-close',+ children: [+ for (var back = 0; back < 4; back++)+ _WeekOption(+ key: ValueKey('swarm-leaderboard-week-$back'),+ label: swarmWeekName(current - back * swarmWeekMs, current),+ selected: shown == current - back * swarmWeekMs,+ onTap: () =>+ Navigator.of(context).pop(current - back * swarmWeekMs),+ ),+ ],+ ),+ );+ if (week == null || !mounted) return;+ await reader.showWeek(week == current ? null : week);+ }++ /// [score]'s week in a sheet, as the desktop shows it when a name is+ /// clicked.+ Future<void> _showPerson(+ BuildContext context,+ SwarmScore score,+ SuperTabPerson? person,+ String name,+ ) => showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: AppGlass.rowFill,+ showDragHandle: true,+ shape: AppControl.sheetShape,+ builder: (context) => _Sheet(+ key: const ValueKey('swarm-leaderboard-sheet'),+ title: name,+ leading: SwarmAvatar(+ id: score.personId,+ name: name,+ picture: person?.avatar,+ ),+ closeKey: 'swarm-leaderboard-sheet-close',+ children: [+ for (final (label, value) in swarmPersonWeek(score))+ _WeekLine(label: label, value: value),+ ],+ ),+ );+}++/// Figures of one width, so a column of numbers holds row under row.+const _figures = [FontFeature.tabularFigures()];++/// Numbers and rankings: the rank a bold numeral in secondary ink, the points+/// the one emphasized number, 0 included.+TextStyle _rankStyle() => AppType.label(+ fontWeight: FontWeight.w700,+ color: AppPalette.textSecondary,+ fontFeatures: _figures,+);+TextStyle _pointsStyle() => AppType.label(+ fontWeight: FontWeight.w600,+ color: AppPalette.textPrimary,+ fontFeatures: _figures,+);+TextStyle _trendStyle(Color color) =>+ AppType.caption(color: color, fontFeatures: _figures);++/// The trend arrow's size in Numbers and rankings, the same on both.+const _trendIconSize = 14.0;++/// The team's week as quiet text, "19 shipped this week · 11 last week" (no+/// hover on a phone, so the week before is said), the week picker beside it.+class _TeamLine extends StatelessWidget {+ const _TeamLine({+ required this.week,+ required this.shipped,+ required this.before,+ required this.onWeek,+ });++ /// "This week", "Last week", …: the week shown.+ final String week;++ /// Null until the board is read.+ final int? shipped, before;+ final VoidCallback? onWeek;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final shipped = this.shipped, before = this.before;+ final earlier = week == 'This week' ? 'last week' : 'the week before';+ return Padding(+ key: const ValueKey('swarm-leaderboard-team'),+ padding: const EdgeInsets.only(left: AppSpace.s, bottom: AppSpace.xs),+ child: Row(+ children: [+ Expanded(+ child: shipped == null+ ? const SizedBox.shrink()+ : Text(+ '$shipped shipped ${week.toLowerCase()} · '+ '$before $earlier',+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ),+ _WeekButton(label: week, onTap: onWeek),+ ],+ ),+ );+ }+}++/// The board's fixed numeric columns, each as wide as its widest value at the+/// current text size, so rank, trend and points line up on every row.+class _Columns {+ const _Columns({required this.rank, required this.points, this.trend});++ factory _Columns.of(BuildContext context, List<SwarmScore> scores) {+ final scaler = MediaQuery.textScalerOf(context);+ double width(String text, TextStyle style) {+ final painter = TextPainter(+ text: TextSpan(text: text, style: style),+ textDirection: TextDirection.ltr,+ textScaler: scaler,+ )..layout();+ final width = painter.width;+ painter.dispose();+ return width;+ }++ // Digits are of one width, so the longest number is the widest.+ String widest(Iterable<int> values) => values+ .map((value) => '$value')+ .fold('0', (a, b) => b.length > a.length ? b : a);+ final changes = [+ for (final score in scores)+ if (score.prevWeekPoints case final before? when before != score.points)+ (score.points - before).abs(),+ ];+ return _Columns(+ rank: width(widest(scores.map((score) => score.rank)), _rankStyle()),+ points: width(+ widest(scores.map((score) => score.points)),+ _pointsStyle(),+ ),+ trend: changes.isEmpty+ ? null+ : _trendIconSize ++ width(widest(changes), _trendStyle(AppPalette.textSecondary)),+ );+ }++ final double rank, points;++ /// Null when no one on the board moved against last week.+ final double? trend;+}++/// One person on the board: rank, face, name over their numbers, change+/// against last week and points, at least a thumb tall; the viewer's own row+/// in the selected fill.+class _PersonRow extends StatelessWidget {+ const _PersonRow({+ required this.score,+ required this.person,+ required this.name,+ required this.own,+ required this.columns,+ required this.onTap,+ });++ final SwarmScore score;++ /// Null for someone who has left.+ final SuperTabPerson? person;+ final String name;+ final bool own;+ final _Columns columns;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final id = score.personId;+ final numbers = swarmNumbers(score);+ final trend = swarmTrend(score);+ Widget column(String kind, double width, Widget? child) => Padding(+ padding: const EdgeInsets.only(left: AppSpace.s),+ child: SizedBox(+ key: ValueKey('swarm-leaderboard-$kind-$id'),+ width: width,+ child: Align(alignment: Alignment.centerRight, child: child),+ ),+ );+ final radius = BorderRadius.circular(AppControl.radius);+ return Material(+ color: own ? AppSurface.selectedFill : Colors.transparent,+ borderRadius: radius,+ clipBehavior: Clip.antiAlias,+ child: Semantics(+ key: ValueKey('swarm-leaderboard-person-$id'),+ button: true,+ // What the row shows, the numbers in full: none at zero.+ label: [+ '$name, place ${score.rank}, ${score.points} points',+ ...numbers,+ ?trend,+ ].join(', '),+ excludeSemantics: true,+ child: InkWell(+ borderRadius: radius,+ onTap: () {+ HapticFeedback.selectionClick();+ onTap();+ },+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: minTouchTarget),+ child: Padding(+ padding: const EdgeInsets.all(AppSpace.s),+ child: Row(+ children: [+ SizedBox(+ key: ValueKey('swarm-leaderboard-rank-$id'),+ width: columns.rank,+ child: Text(+ '${score.rank}',+ maxLines: 1,+ textAlign: TextAlign.right,+ style: _rankStyle(),+ ),+ ),+ const SizedBox(width: AppSpace.m),+ SwarmAvatar(+ id: id,+ name: name,+ picture: person?.avatar,+ status: person?.statusAt(clock.now()),+ ),+ const SizedBox(width: AppSpace.m),+ Expanded(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ if (numbers.isNotEmpty)+ _Numbers(+ key: ValueKey('swarm-leaderboard-meta-$id'),+ parts: numbers,+ ),+ ],+ ),+ ),+ if (columns.trend case final width?)+ column(+ 'trend-column',+ width,+ trend == null ? null : _Trend(score: score),+ ),+ column(+ 'points',+ columns.points,+ Text('${score.points}', maxLines: 1, style: _pointsStyle()),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}++/// A person's numbers joined by a spaced middle dot. Where the line does not+/// fit, whole items fall off its end, never part of a word; the person's+/// sheet has them all. A first item too wide even alone wraps between its+/// words.+class _Numbers extends StatelessWidget {+ const _Numbers({super.key, required this.parts});++ final List<String> parts;++ @override+ Widget build(BuildContext context) {+ final style = AppType.caption(color: AppPalette.textSecondary);+ final scaler = MediaQuery.textScalerOf(context);+ return LayoutBuilder(+ builder: (context, constraints) {+ bool fits(String text) {+ final painter = TextPainter(+ text: TextSpan(text: text, style: style),+ textDirection: TextDirection.ltr,+ textScaler: scaler,+ maxLines: 1,+ )..layout(maxWidth: constraints.maxWidth);+ final fits = !painter.didExceedMaxLines;+ painter.dispose();+ return fits;+ }++ var shown = parts.length;+ while (shown > 1 && !fits(parts.take(shown).join(' · '))) {+ shown--;+ }+ final text = parts.take(shown).join(' · ');+ return Text(+ text,+ maxLines: fits(text) ? 1 : 2,+ overflow: TextOverflow.ellipsis,+ style: style,+ );+ },+ );+ }+}++/// An arrow and the change against last week, by shape and colour both: up in+/// the online green, down in the theme's error ink.+class _Trend extends StatelessWidget {+ const _Trend({required this.score});++ final SwarmScore score;++ @override+ Widget build(BuildContext context) {+ final change = score.points - score.prevWeekPoints!;+ final color = change > 0+ ? AppPalette.online+ : Theme.of(context).colorScheme.error;+ return Row(+ key: ValueKey('swarm-leaderboard-trend-${score.personId}'),+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(+ change > 0 ? LucideIcons.arrowUp300 : LucideIcons.arrowDown300,+ size: _trendIconSize,+ color: color,+ ),+ Text('${change.abs()}', style: _trendStyle(color)),+ ],+ );+ }+}++/// The week shown and its arrow: opens the week picker.+class _WeekButton extends StatelessWidget {+ const _WeekButton({required this.label, required this.onTap});++ final String label;+ final VoidCallback? onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ label: 'Week: $label',+ excludeSemantics: true,+ child: InkWell(+ key: const ValueKey('swarm-leaderboard-week'),+ borderRadius: BorderRadius.circular(AppControl.radius),+ onTap: onTap == null+ ? null+ : () {+ HapticFeedback.selectionClick();+ onTap!();+ },+ child: ConstrainedBox(+ constraints: const BoxConstraints(+ minHeight: minTouchTarget,+ minWidth: minTouchTarget,+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(label, style: AppType.body(color: AppPalette.textPrimary)),+ const SizedBox(width: AppSpace.xs),+ Icon(+ LucideIcons.chevronDown300,+ size: _iconSize,+ color: AppPalette.textSecondary,+ ),+ ],+ ),+ ),+ ),+ ),+ );+}++/// An icon beside text, at the Phone section's size.+const _iconSize = 20.0;++/// A bottom sheet of the page under its drag handle: a title with maybe a+/// mark before it and a close button, and its rows.+class _Sheet extends StatelessWidget {+ const _Sheet({+ super.key,+ required this.title,+ required this.closeKey,+ required this.children,+ this.leading,+ });++ final String title, closeKey;+ final Widget? leading;+ final List<Widget> children;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return SafeArea(+ top: false,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ 0,+ AppSpace.screenInset,+ AppSpace.l,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.only(bottom: AppSpace.s),+ child: Row(+ children: [+ if (leading case final leading?) ...[+ leading,+ const SizedBox(width: AppSpace.m),+ ],+ Expanded(+ child: Text(+ title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ ),+ SwarmIconButton(+ key: ValueKey(closeKey),+ icon: LucideIcons.x300,+ label: 'Close',+ onPressed: () => Navigator.of(context).pop(),+ ),+ ],+ ),+ ),+ ...children,+ ],+ ),+ ),+ );+ }+}++/// A week in the picker; the one shown is checked.+class _WeekOption extends StatelessWidget {+ const _WeekOption({+ super.key,+ required this.label,+ required this.selected,+ required this.onTap,+ });++ final String label;+ final bool selected;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ selected: selected,+ label: label,+ excludeSemantics: true,+ child: InkWell(+ borderRadius: BorderRadius.circular(AppControl.radius),+ onTap: () {+ HapticFeedback.selectionClick();+ onTap();+ },+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: minTouchTarget),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),+ child: Row(+ children: [+ Expanded(+ child: Text(+ label,+ style: AppType.body(+ color: AppPalette.textPrimary,+ fontWeight: selected ? FontWeight.w600 : null,+ ),+ ),+ ),+ if (selected)+ Icon(+ LucideIcons.check300,+ size: _iconSize,+ color: AppPalette.accent,+ ),+ ],+ ),+ ),+ ),+ ),+ );+}++/// One line of a person's week: what it counts, then what they did.+class _WeekLine extends StatelessWidget {+ const _WeekLine({required this.label, required this.value});++ final String label, value;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.symmetric(vertical: AppSpace.s),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ // The labels' column: as wide as the widest of them, "Unblocked".+ SizedBox(+ width: _labelWidth(context),+ child: Text(+ label,+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ ),+ const SizedBox(width: AppSpace.m),+ Expanded(+ child: Text(+ value,+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ ),+ ],+ ),+ );++ static double _labelWidth(BuildContext context) {+ final painter = TextPainter(+ text: TextSpan(+ text: 'Unblocked',+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ textDirection: TextDirection.ltr,+ textScaler: MediaQuery.textScalerOf(context),+ )..layout();+ final width = painter.width;+ painter.dispose();+ return width;+ }+}diff --git a/mobile/lib/swarm/swarm_leaderboard_reader.dart b/mobile/lib/swarm/swarm_leaderboard_reader.dartnew file mode 100644index 000000000..4da366b6e--- /dev/null+++ b/mobile/lib/swarm/swarm_leaderboard_reader.dart@@ -0,0 +1,288 @@+/// The leaderboard read's answer, how the board writes its numbers, and the+/// reader that keeps one project's board current (the desktop's+/// `desktop/lib/super_tabs/leaderboard` model, format and reader); the page+/// is `swarm_leaderboard.dart`.+library;++import 'dart:async';++import 'package:flutter/foundation.dart';++import 'swarm_request.dart';++/// A place among the top three with points.+enum SwarmMedal { gold, silver, bronze }++const swarmWeekMs = 7 * 86400000;+const _minute = 60000, _hour = 3600000;++int _int(Object? value) => value is num ? value.round() : 0;+int? _optional(Object? value) => value is num ? value.round() : null;+Map<String, dynamic> _map(Object? value) =>+ value is Map ? value.cast<String, dynamic>() : const {};++/// One project's week as the leaderboard read answers it+/// (`backend/src/superTabs/leaderboard/contract.ts`): what it shipped, and+/// each person who reads the project with their points, most first. The+/// desktop's `SuperTabLeaderboard` (`desktop/lib/super_tabs/leaderboard`),+/// kept to what the phone shows.+class SwarmLeaderboard {+ SwarmLeaderboard.fromJson(Map<String, dynamic> json)+ : week = _int(json['week']),+ shipped = _int(_map(_map(json['goal'])['thisWeek'])['shipped']),+ shippedBefore = _int(_map(_map(json['goal'])['lastWeek'])['shipped']),+ people = List.unmodifiable([+ for (final row in json['people'] as List? ?? const [])+ if (row is Map) SwarmScore.fromJson(_map(row)),+ ]);++ /// The week's Monday 00:00 UTC, in epoch milliseconds.+ final int week;++ /// What the project shipped in the week.+ final int shipped;++ /// What it shipped the week before.+ final int shippedBefore;++ /// Most points first.+ final List<SwarmScore> people;+}++/// One person's week on the board.+class SwarmScore {+ SwarmScore.fromJson(Map<String, dynamic> json)+ : personId = json['personId'] as String? ?? '',+ points = _int(json['points']),+ rank = _int(json['rank']),+ medal = SwarmMedal.values.asNameMap()[json['medal']],+ shipped = _int(_map(json['shipped'])['count']),+ medianAskToShipMs = _optional(_map(json['shipped'])['medianAskToShipMs']),+ unblocked = _int(_map(json['unblocked'])['count']),+ unblockedMs = _int(_map(json['unblocked'])['agentMs']),+ medianAnswerMs = _optional(_map(json['unblocked'])['medianAnswerMs']),+ lentMachines = _int(_map(json['lent'])['machines']),+ lentMs = _int(_map(json['lent'])['agentMs']),+ streakDays = _int(json['streakDays']),+ displayName = switch (json['displayName']) {+ final String name when name.isNotEmpty => name,+ _ => null,+ },+ prevWeekPoints = _optional(json['prevWeekPoints']);++ final String personId;++ /// [rank] 1 has the most points; people with the same points share one.+ final int points, rank;+ final SwarmMedal? medal;+ final int shipped, unblocked, lentMachines, streakDays;++ /// Agent time the person's answers freed, and agent time run on their+ /// machines.+ final int unblockedMs, lentMs;+ final int? medianAskToShipMs, medianAnswerMs;++ /// The profile name; null from a server before names.+ final String? displayName;++ /// The same scoring for the week before; null from a server before it.+ final int? prevWeekPoints;+}++/// "6 min" under an hour, then hours with one decimal unless whole: "3 h",+/// "3.1 h" (the desktop's `leaderboardDuration`).+String swarmDuration(int ms) {+ if (ms < _hour) return '${(ms / _minute).round()} min';+ final rounded = (ms / _hour * 10).round() / 10;+ return rounded == rounded.roundToDouble()+ ? '${rounded.round()} h'+ : '${rounded.toStringAsFixed(1)} h';+}++/// Whole agent-hours, as the points count them.+int swarmHours(int ms) => (ms / _hour).round();++/// "8 shipped", "1 unblocked", "40 hours lent": each number that would not+/// read zero, in words (the desktop's `leaderboardNumbers`).+List<String> swarmNumbers(SwarmScore score) {+ final hours = swarmHours(score.lentMs);+ return [+ if (score.shipped > 0) '${score.shipped} shipped',+ if (score.unblocked > 0) '${score.unblocked} unblocked',+ if (hours > 0) '${_plural(hours, 'hour')} lent',+ ];+}++/// "up 8 from last week", "down 4 …"; null when level, or from a server+/// without last week (the desktop's `leaderboardTrend`).+String? swarmTrend(SwarmScore score) {+ final before = score.prevWeekPoints;+ if (before == null || before == score.points) return null;+ final change = score.points - before;+ return '${change > 0 ? 'up' : 'down'} ${change.abs()} from last week';+}++String _plural(int count, String one) =>+ '$count ${count == 1 ? one : '${one}s'}';++/// The Monday 00:00 UTC of the week [now] is in.+int swarmWeekOf(DateTime now) {+ final utc = now.toUtc();+ final day = DateTime.utc(utc.year, utc.month, utc.day);+ return day+ .subtract(Duration(days: day.weekday - DateTime.monday))+ .millisecondsSinceEpoch;+}++/// "This week", "Last week", "2 weeks ago", from the week's Monday and this+/// one's; null is this week.+String swarmWeekName(int? week, int currentWeek) {+ final back = week == null ? 0 : ((currentWeek - week) / swarmWeekMs).round();+ return switch (back) {+ 0 => 'This week',+ 1 => 'Last week',+ _ => '$back weeks ago',+ };+}++/// Reads one project's leaderboard: once [start]ed, at once and every+/// [every] while the app is in front ([inFront]); the board sums a week, so+/// it moves slowly. A failed refresh keeps the last board and says why (the+/// desktop's `SuperTabLeaderboardReader`).+class SwarmLeaderboardReader extends ChangeNotifier {+ SwarmLeaderboardReader({+ required this.tabId,+ required this.projectId,+ required this.request,+ required this.inFront,+ this.every = const Duration(minutes: 5),+ });++ final String tabId, projectId;+ final SwarmRequest request;+ final bool Function() inFront;+ final Duration every;++ /// The week as last read; null before a read of the week shown lands.+ SwarmLeaderboard? board;++ /// Why the last read failed; null once one succeeds.+ String? error;++ /// The server has no leaderboard: it is from before one.+ bool unavailable = false;++ /// The Monday of the week shown; null for this week.+ int? week;++ int _read = 0;+ Timer? _timer;+ bool _disposed = false;++ bool get loading => board == null && error == null && !unavailable;++ /// Reads now, and every [every] after while the app is in front.+ void start() {+ _timer ??= Timer.periodic(every, (_) {+ if (inFront()) unawaited(refresh());+ });+ unawaited(refresh());+ }++ /// Shows another week, null for this one.+ Future<void> showWeek(int? week) {+ if (week == this.week) return Future.value();+ this.week = week;+ // Another week's numbers under this week's name would mislead until the+ // read lands.+ board = null;+ error = null;+ _notify();+ return refresh();+ }++ Future<void> refresh() async {+ if (_disposed) return;+ final read = ++_read, week = this.week;+ try {+ final answer = await request(+ 'GET',+ '/api/super-tabs/${Uri.encodeComponent(tabId)}/leaderboard'+ '?projectId=${Uri.encodeQueryComponent(projectId)}'+ '${week == null ? '' : '&week=$week'}',+ );+ if (read != _read || _disposed) return;+ if (answer is! Map) throw const FormatException();+ board = SwarmLeaderboard.fromJson(answer.cast<String, dynamic>());+ error = null;+ unavailable = false;+ } on SuperTabFailure catch (failure) {+ if (read != _read || _disposed) return;+ if (failure.statusCode == 404) {+ board = null;+ error = null;+ unavailable = true;+ } else {+ error = failure.message;+ }+ } catch (_) {+ if (read != _read || _disposed) return;+ error = "Couldn't read the leaderboard.";+ }+ _notify();+ }++ void _notify() {+ if (!_disposed) notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ _timer?.cancel();+ super.dispose();+ }+}++/// A person's week as the desktop's `LeaderboardPersonWeek` words it: the+/// points and place, what landed, what they answered, what they lent, and+/// their streak.+List<(String, String)> swarmPersonWeek(SwarmScore score) {+ String median(int? ms, String what) =>+ ms == null ? '' : ' · median ${swarmDuration(ms)}$what';+ return [+ (+ 'Points',+ score.medal == null+ ? '${score.points} this week'+ : '${score.points} this week · place ${score.rank}',+ ),+ (+ 'Shipped',+ score.shipped == 0+ ? 'Nothing landed yet'+ : '${_plural(score.shipped, 'ask')} landed'+ '${median(score.medianAskToShipMs, ' to ship')}',+ ),+ (+ 'Unblocked',+ score.unblocked == 0+ ? 'Nothing answered yet'+ : '${score.unblocked} answered${median(score.medianAnswerMs, '')}'+ ' · ${swarmDuration(score.unblockedMs)} of agent time freed',+ ),+ (+ 'Lent',+ score.lentMachines == 0+ ? 'Nothing lent yet'+ : '${_plural(score.lentMachines, 'machine')}'+ ' · ${swarmHours(score.lentMs)} agent-hours',+ ),+ (+ 'Streak',+ score.streakDays == 0+ ? 'No streak yet'+ : '${_plural(score.streakDays, 'day')} shipping',+ ),+ ];+}diff --git a/mobile/lib/swarm/swarm_machines.dart b/mobile/lib/swarm/swarm_machines.dartnew file mode 100644index 000000000..9eeea0512--- /dev/null+++ b/mobile/lib/swarm/swarm_machines.dart@@ -0,0 +1,517 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../phone/phone_sheet.dart';+import '../shared/theme/app_icon_size.dart';+import '../shared/theme/app_space.dart';+import '../shared/theme/app_theme.dart';+import '../shared/theme/app_type.dart';+import 'identity.dart';+import 'model.dart';+import 'swarm_buddy.dart';+import 'swarm_reader.dart';+import 'swarm_style.dart';+import 'team_glance.dart';++/// Swarm inventory only: never the account's private linked-computer list.+/// Backend-filtered parts and Desktop's readingPoolOf own visibility.+class SwarmMachinesSection extends StatefulWidget {+ const SwarmMachinesSection({+ super.key,+ required this.reader,+ required this.open,+ this.swarmName,+ });+ final SwarmReader reader;+ final String? swarmName;+ final void Function(String machineId) open;++ @override+ State<SwarmMachinesSection> createState() => _SwarmMachinesSectionState();+}++class _SwarmMachinesSectionState extends State<SwarmMachinesSection> {+ bool _expanded = true;++ @override+ Widget build(BuildContext context) => _MachineRead(+ reader: widget.reader,+ builder: (context, snapshot, refreshing) {+ AppTheme.watch(context);+ final ids = <String>{+ for (final m in snapshot?.machines ?? <Map<String, dynamic>>[])+ if (m['machineId'] case final String id) id,+ for (final a in snapshot?.agents ?? <SuperTabAgent>[]) a.machineId,+ }.where((id) => snapshot!.placeOf(id) == id).toList();+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Semantics(+ expanded: _expanded,+ child: _tap(+ key: ValueKey('swarm-machines-${widget.reader.tabId}'),+ onTap: () => setState(() => _expanded = !_expanded),+ child: Row(+ children: [+ Expanded(+ child: Text(+ widget.swarmName == null+ ? 'Machines'+ : 'Machines · ${widget.swarmName}',+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ),+ Icon(+ _expanded+ ? LucideIcons.chevronDown300+ : LucideIcons.chevronRight300,+ size: AppIconSize.besideText,+ color: AppPalette.textSecondary,+ ),+ ],+ ),+ ),+ ),+ if (_expanded)+ if (ids.isEmpty)+ Padding(+ padding: const EdgeInsets.all(AppSpace.m),+ child: Text(+ widget.reader.accessRevoked+ ? 'Access ended'+ : snapshot == null+ ? widget.reader.error ?? 'Reading machines…'+ : 'No machines yet',+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ )+ else+ for (final id in ids)+ _machineRow(+ _MachineView(+ snapshot!,+ id,+ widget.reader,+ refreshing: refreshing,+ ),+ ),+ ],+ );+ },+ );++ Widget _machineRow(_MachineView view) => _tap(+ key: ValueKey('swarm-machine-${widget.reader.tabId}-${view.id}'),+ onTap: () => widget.open(view.id),+ child: Row(+ children: [+ Icon(+ view.laptop ? LucideIcons.laptop300 : LucideIcons.monitor300,+ size: AppIconSize.besideText,+ color: AppPalette.textSecondary,+ ),+ const SizedBox(width: AppSpace.m),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ view.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.label(color: AppPalette.textPrimary),+ ),+ if (view.agents.isNotEmpty)+ Text(+ '${view.agents.length} ${view.agents.length == 1 ? 'agent' : 'agents'}',+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ],+ ),+ ),+ if (view.owner case final owner?) ...[+ const SizedBox(width: AppSpace.s),+ SwarmAvatar(+ id: owner.id,+ name: superTabPersonName(owner.email),+ picture: owner.avatar,+ size: AppIconSize.standalone,+ ),+ ],+ const SizedBox(width: AppSpace.s),+ Semantics(+ label: view.status,+ child: Text(+ view.offline ? '○' : '●',+ style: AppType.caption(+ color: view.live ? AppPalette.online : AppPalette.textFaint,+ ),+ ),+ ),+ ],+ ),+ );+}++Widget _tap({Key? key, required VoidCallback onTap, required Widget child}) =>+ Material(+ color: Colors.transparent,+ child: InkWell(+ key: key,+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 52),+ child: Padding(+ padding: const EdgeInsets.all(AppSpace.s),+ child: child,+ ),+ ),+ ),+ );++/// A read-only sheet that keeps following the same reader as the drawer.+Future<void> showSwarmMachine(+ BuildContext context,+ SwarmReader reader,+ String id,+) => Navigator.of(context, rootNavigator: true).push(+ phoneSheetRoute<void>(+ context,+ builder: (_) => SwarmMachineSheet(reader: reader, machineId: id),+ ),+);++class SwarmMachineSheet extends StatelessWidget {+ const SwarmMachineSheet({+ super.key,+ required this.reader,+ required this.machineId,+ });+ final SwarmReader reader;+ final String machineId;++ @override+ Widget build(BuildContext context) => _MachineRead(+ reader: reader,+ builder: (context, snapshot, refreshing) {+ AppTheme.watch(context);+ if (snapshot == null ||+ (snapshot.pool(machineId) == null &&+ !snapshot.agents.any(+ (a) => snapshot.placeOf(a.machineId) == machineId,+ ))) {+ return SafeArea(+ child: Padding(+ padding: const EdgeInsets.all(AppSpace.xl),+ child: Text(+ reader.accessRevoked+ ? 'Access ended'+ : 'Machine no longer available',+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ ),+ );+ }+ final view = _MachineView(+ snapshot,+ machineId,+ reader,+ refreshing: refreshing,+ );+ final r = view.resources;+ final total = _number(r['memoryTotalBytes']);+ final used = _number(r['memoryUsedBytes']);+ final diskTotal =+ _number(r['projectDiskTotalBytes']) ?? _number(r['diskTotalBytes']);+ final diskFree = r['projectDiskTotalBytes'] == null+ ? _number(r['diskFreeBytes'])+ : _number(r['projectDiskFreeBytes']);+ final agents = swarmTeamGlance(snapshot).agents.where(+ (a) =>+ snapshot.placeOf(a.agent.machineId) == machineId &&+ a.agent.downSince == null,+ );+ return SafeArea(+ child: SingleChildScrollView(+ padding: const EdgeInsets.all(AppSpace.screenInset),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ view.name,+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ ),+ IconButton(+ tooltip: 'Close',+ onPressed: () => Navigator.of(context).pop(),+ icon: const Icon(+ LucideIcons.x300,+ size: AppIconSize.standalone,+ ),+ ),+ ],+ ),+ _detail('Status', view.status),+ if (view.owner case final owner?)+ _detail('Owner', superTabPersonName(owner.email)),+ _heading('Hardware'),+ if (view.dim)+ _detail('Readings', 'Current readings unavailable')+ else ...[+ _detail('CPU', _percent(r['cpuPercent'])),+ _detail('GPU', _percent(r['gpuPercent'])),+ _detail(+ 'RAM',+ total == null || used == null+ ? 'Unavailable'+ : '${_bytes((total - used).clamp(0, total))} free of ${_bytes(total)}',+ ),+ _detail(+ 'SSD',+ diskFree == null+ ? 'Unavailable'+ : '${_bytes(diskFree)} free${diskTotal == null ? '' : ' of ${_bytes(diskTotal)}'}',+ ),+ for (final (label, field) in [+ ('Device', 'deviceType'),+ ('Chip', 'chip'),+ ('System', 'os'),+ ])+ if (r[field] case final String text) _detail(label, text),+ ],+ _heading('Model allowances'),+ if (view.dim)+ _detail('Allowances', 'Current allowances unavailable')+ else+ for (final engine in ['claude', 'codex'])+ ..._allowance(view, engine),+ _heading('Agents'),+ if (agents.isEmpty)+ _detail('Running here', 'No agents running')+ else+ for (final a in agents)+ _detail(+ a.name,+ '${a.agent.isReviewer+ ? 'Rev'+ : a.agent.name == 'Lead'+ ? 'PM'+ : 'Dev'} · ${a.label}',+ ),+ ],+ ),+ ),+ );+ },+ );+}++Widget _heading(String title) => Padding(+ padding: const EdgeInsets.only(top: AppSpace.xl, bottom: AppSpace.s),+ child: Text(title, style: AppType.heading(color: AppPalette.textPrimary)),+);++Widget _detail(String label, String text) => Padding(+ padding: const EdgeInsets.symmetric(vertical: AppSpace.xs),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(+ flex: 2,+ child: Text(+ label,+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ),+ const SizedBox(width: AppSpace.m),+ Expanded(+ flex: 3,+ child: Text(+ text,+ textAlign: TextAlign.right,+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ ),+ ],+ ),+);++double? _number(Object? v) => v is num && v.isFinite ? v.toDouble() : null;+String _percent(Object? value) => switch (_number(value)) {+ final n? => '${n.clamp(0, 100).round()}% in use',+ null => 'Unavailable',+};+String _bytes(num bytes) =>+ '${(bytes / 1073741824).toStringAsFixed(bytes % 1073741824 == 0 ? 0 : 1)} GB';++List<Widget> _allowance(_MachineView view, String engine) {+ final quota = (view.observation['quotas'] as List? ?? [])+ .map(superTabMap)+ .where((q) => q['engine'] == engine)+ .firstOrNull;+ final windows = (quota?['windows'] as List? ?? []).map(superTabMap).toList();+ DateTime? reset(Object? raw) => raw is num+ ? DateTime.fromMillisecondsSinceEpoch(+ raw > 100000000000 ? raw.toInt() : (raw * 1000).toInt(),+ )+ : raw is String+ ? DateTime.tryParse(raw)+ : null;+ final known =+ quota?['known'] == true &&+ windows.isNotEmpty &&+ windows.every(+ (w) =>+ _number(w['usedPercent']) != null &&+ !(reset(w['resetsAt'])?.isBefore(DateTime.now()) ?? false),+ );+ final name = engine == 'claude' ? 'Claude' : 'Codex';+ if (!known) return [_detail(name, 'Allowance unavailable')];+ return [+ for (final w in windows)+ _detail(+ name,+ '${w['name'] ?? 'Allowance'}: ${(100 - _number(w['usedPercent'])!).clamp(0, 100).round()}% left'+ '${reset(w['resetsAt']) == null ? '' : '\nResets ${_resetIn(reset(w['resetsAt'])!)}'}',+ ),+ ];+}++String _resetIn(DateTime at) {+ final minutes = at.difference(DateTime.now()).inMinutes;+ return minutes <= 0+ ? 'now'+ : minutes < 60+ ? 'in ${minutes}m'+ : 'in ${minutes ~/ 60}h ${minutes % 60}m';+}++class _MachineView {+ _MachineView(+ this.snapshot,+ this.id,+ SwarmReader reader, {+ required bool refreshing,+ }) {+ final pool = snapshot.pool(id);+ agents = swarmTeamAgents(snapshot)+ .where(+ (a) => snapshot.placeOf(a.machineId) == id && a.downSince == null,+ )+ .toList();+ owner = snapshot.people+ .where(+ (p) =>+ p.id ==+ (pool?['contributorId'] ?? agents.firstOrNull?.contributorId),+ )+ .firstOrNull;+ name = pool?['name'] as String? ?? 'Unavailable machine';+ final reading = snapshot.readingPoolOf(id, reader.accountId);+ observation = superTabMap(+ reading?['observation'] ?? const <String, dynamic>{},+ );+ resources = superTabMap(+ observation['resources'] ?? const <String, dynamic>{},+ );+ final received = _number(observation['receivedAt']);+ final age = received == null+ ? null+ : DateTime.now().difference(+ DateTime.fromMillisecondsSinceEpoch(received.toInt()),+ );+ offline = age == null || age >= const Duration(seconds: 35);+ live =+ !offline &&+ age! < const Duration(seconds: 20) &&+ reader.error == null &&+ !refreshing;+ dim = offline || reader.error != null || refreshing;+ status = reader.error != null+ ? "Can't reach Harness"+ : refreshing+ ? 'Refreshing…'+ : offline+ ? 'Offline'+ : reading?['paused'] == true+ ? 'New work paused'+ : live+ ? 'Online'+ : 'Late';+ }+ final SuperTabSnapshot snapshot;+ final String id;+ late final String name, status;+ late final SuperTabPerson? owner;+ late final List<SuperTabAgent> agents;+ late final Map<String, dynamic> observation, resources;+ late final bool offline, live, dim;+ bool get laptop =>+ (resources['deviceType'] as String? ?? name).toLowerCase().contains(+ 'book',+ ) ||+ name.toLowerCase().contains('laptop');+}++/// Only a clock tick is new here; all network reads remain the existing+/// changed-parts reader's. A foreground return hides pre-background readings.+class _MachineRead extends StatefulWidget {+ const _MachineRead({required this.reader, required this.builder});+ final SwarmReader reader;+ final Widget Function(BuildContext, SuperTabSnapshot?, bool) builder;+ @override+ State<_MachineRead> createState() => _MachineReadState();+}++class _MachineReadState extends State<_MachineRead>+ with WidgetsBindingObserver {+ Timer? _tick;+ int? _returnRead;+ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ _start();+ }++ void _start() {+ _tick?.cancel();+ _tick = Timer.periodic(const Duration(seconds: 1), (_) {+ if (mounted) setState(() {});+ });+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) {+ _tick?.cancel();+ if (state == AppLifecycleState.resumed) {+ _returnRead = widget.reader.reads.value;+ _start();+ setState(() {});+ }+ }++ @override+ void dispose() {+ _tick?.cancel();+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: Listenable.merge([widget.reader, widget.reader.reads]),+ builder: (context, _) => widget.builder(+ context,+ widget.reader.accessRevoked ? null : widget.reader.snapshot,+ _returnRead != null && widget.reader.reads.value <= _returnRead!,+ ),+ );+}diff --git a/mobile/lib/swarm/swarm_mark.dart b/mobile/lib/swarm/swarm_mark.dartnew file mode 100644index 000000000..f6f124685--- /dev/null+++ b/mobile/lib/swarm/swarm_mark.dart@@ -0,0 +1,63 @@+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/phone/tty_controls.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';++import 'swarm_choices.dart';+import 'swarm_page.dart';+import 'swarm_session.dart';++/// Swarm on Home's title ([swarmHomeMark]): its mark, and how many things the+/// Swarms ask of the person, in the terminal's yellow while any do. A tap+/// goes back to Swarm Home ([openSwarmHome]). Nothing while Swarm is off or+/// outside the shell.+class SwarmMark extends StatelessWidget {+ const SwarmMark({super.key, this.margin = EdgeInsets.zero});++ final EdgeInsets margin;++ @override+ Widget build(BuildContext context) {+ final session = SwarmScope.of(context);+ if (!swarmHomeMark || session == null) return const SizedBox.shrink();+ return ListenableBuilder(+ listenable: session.inbox,+ builder: (context, _) {+ final tty = Tty.of(context);+ final count = session.inbox.needs.length;+ final color = count > 0 ? tty.yellow : tty.dim;+ return Padding(+ padding: margin,+ child: TtyTap(+ key: const ValueKey('swarm-mark'),+ semanticsLabel: count == 0+ ? 'Swarm'+ : 'Swarm, $count ${count == 1 ? 'needs' : 'need'} you',+ onTap: () => openSwarmHome(context),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(LucideIcons.network300, size: 18, color: color),+ if (count > 0) ...[+ const SizedBox(width: 4),+ TtyText(+ '$count',+ key: const ValueKey('swarm-mark-count'),+ color: color,+ weight: FontWeight.w600,+ size: TtySize.meta,+ ),+ ],+ ],+ ),+ ),+ ),+ );+ },+ );+ }+}diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dartnew file mode 100644index 000000000..6b18f5138--- /dev/null+++ b/mobile/lib/swarm/swarm_message_row.dart@@ -0,0 +1,677 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:url_launcher/url_launcher.dart';++import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/phone/tty_controls.dart';+import 'package:harness_mobile/shared/theme/app_ink.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'model.dart';+import 'swarm_attachment.dart';+import 'swarm_face.dart';+import 'swarm_ship_row.dart';++/// The host the backend serves message files from: a link anywhere else is+/// not opened (the desktop's `attachmentLink`).+const swarmAttachmentHost = String.fromEnvironment(+ 'SUPER_TAB_ATTACHMENTS_HOST',+ defaultValue: 'cdn.harness.autonomous.ai',+);++/// [url] as a link to open, or null unless it is https on+/// [swarmAttachmentHost]: a message's url is whatever its sender's row says.+Uri? swarmAttachmentLink(String url) {+ final link = Uri.tryParse(url);+ return link != null &&+ link.scheme == 'https' &&+ link.host == swarmAttachmentHost+ ? link+ : null;+}++/// The chat's prose in the app's own face, as prototype v2 draws it: the+/// messages, quotes, names and the field. Times, roles and day dividers stay+/// in the terminal's.+TextStyle swarmChatText(+ double size, {+ Color? color,+ FontWeight weight = FontWeight.w400,+ double height = 1.35,+}) => TextStyle(+ fontSize: size,+ height: height,+ color: color ?? AppPalette.textPrimary,+ fontWeight: weight,+);++/// The hairline around the chat's cards, picker and field.+Color swarmChatHair(Tty tty) => tty.text.withValues(alpha: 0.12);++/// The ground of a card in the chat: a decision, the picker, a file.+Color swarmChatCard(Tty tty) =>+ Color.alphaBlend(tty.text.withValues(alpha: 0.05), tty.ground);++/// The names an @mention in a message is marked for, as the desktop and the+/// prototype mark them: the pattern that finds them is made once for every+/// message drawn with them.+class SwarmMentions {+ SwarmMentions(List<String> names)+ : names = List.unmodifiable(names),+ _pattern = names.isEmpty+ ? null+ : RegExp(+ // Longest first, so "@Nova2" is not read as "@Nova".+ '(?<![\\w@])@(?:${([...names]..sort((a, b) => b.length.compareTo(a.length))).map(RegExp.escape).join('|')})(?![\\w])',+ caseSensitive: false,+ );++ final List<String> names;+ final RegExp? _pattern;++ /// [text] with each @mention of one of [names] marked.+ TextSpan span(String text, TextStyle style) {+ final pattern = _pattern;+ if (pattern == null || !text.contains('@')) {+ return TextSpan(text: text, style: style);+ }+ return TextSpan(style: style, children: _marked(text, pattern));+ }+}++List<InlineSpan> _marked(String text, RegExp pattern) {+ final spans = <InlineSpan>[];+ var at = 0;+ for (final match in pattern.allMatches(text)) {+ if (match.start > at) {+ spans.add(TextSpan(text: text.substring(at, match.start)));+ }+ spans.add(+ TextSpan(+ text: match[0],+ style: TextStyle(+ color: AppPalette.accentOnSurface,+ backgroundColor: AppPalette.accentOnSurface.withValues(alpha: 0.13),+ fontWeight: FontWeight.w500,+ ),+ ),+ );+ at = match.end;+ }+ if (at < text.length) spans.add(TextSpan(text: text.substring(at)));+ return spans;+}++/// A message's frame: avatar, then who wrote it, their role and [trailing]+/// (its time) — none of it for a follow-up — then [body]. With [onAvatar],+/// the avatar and the room beside it are one thumb-sized target.+class SwarmMessageFrame extends StatelessWidget {+ const SwarmMessageFrame({+ super.key,+ required this.avatar,+ required this.grouped,+ required this.header,+ required this.body,+ this.onAvatar,+ this.avatarKey,+ this.avatarLabel,+ });++ final Widget avatar;+ final bool grouped;+ final Widget header;+ final List<Widget> body;+ final VoidCallback? onAvatar;+ final Key? avatarKey;++ /// What the avatar's target is read as.+ final String? avatarLabel;++ /// The avatar's column: the avatar and the room after it, a thumb wide.+ static const double column = 44;++ /// Around a message in the chat's column, a post's and a skeleton's too;+ /// one [grouped] under the message before it leaves no room above.+ static EdgeInsets padding({bool grouped = false}) => EdgeInsets.fromLTRB(+ AppSpace.s,+ grouped ? 0 : AppSpace.s,+ AppSpace.s,+ AppSpace.s,+ );++ /// Between a message's header and its words.+ static const double bodyGap = AppSpace.xs;++ @override+ Widget build(BuildContext context) => Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(+ width: column,+ child: grouped+ ? null+ : onAvatar == null+ ? Align(alignment: Alignment.topLeft, child: avatar)+ : Semantics(+ button: true,+ label: avatarLabel,+ child: GestureDetector(+ key: avatarKey,+ behavior: HitTestBehavior.opaque,+ onTap: onAvatar,+ child: SizedBox(+ height: column,+ child: Align(alignment: Alignment.topLeft, child: avatar),+ ),+ ),+ ),+ ),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [if (!grouped) header, ...body],+ ),+ ),+ ],+ );+}++/// One message: avatar, who wrote it, their role and when — none of it for a+/// follow-up — then what it answers, its text, its files and its+/// [reactions]. A tap opens its actions, a long-press [onLongPress]; lit for+/// a moment when a quote leads to it.+class SwarmMessageRow extends StatelessWidget {+ const SwarmMessageRow({+ super.key,+ required this.message,+ required this.name,+ required this.look,+ required this.role,+ required this.mentions,+ required this.grouped,+ required this.lit,+ this.followed = false,+ required this.quote,+ required this.actions,+ required this.onTap,+ required this.onReply,+ this.onAuthor,+ this.reactions,+ this.below,+ this.onLongPress,+ });++ final SuperTabMessage message;+ final String name;++ /// What its author wears.+ final SwarmLook look;+ final String? role;++ final SwarmMentions mentions;+ final bool grouped, lit, actions;++ /// The row a quote led to: lit, then fading. Only it animates — a fade on+ /// every row would give each its own ticker.+ final bool followed;+ final Widget? quote;+ final VoidCallback onTap;++ /// Null where the person cannot post.+ final VoidCallback? onReply;++ /// Who wrote it, in a sheet; null where nothing opens.+ final VoidCallback? onAuthor;++ /// Drawn under its text and files: its reaction counts.+ final Widget? reactions;++ /// Under its reactions: what the person may do with it besides Reply — the+ /// PM's private line answered in the project chat.+ final Widget? below;++ /// Null where the person cannot post: picks a reaction.+ final VoidCallback? onLongPress;++ @override+ Widget build(BuildContext context) {+ // A ship line is a card, not a message from its author.+ if (swarmShips(message)) {+ return SwarmShipRow(+ key: ValueKey('swarm-message-${message.id}'),+ message: message,+ );+ }+ // A row kept as it was is not built again: it follows a theme or font+ // change itself.+ AppTheme.watch(context);+ final tty = Tty.of(context);+ final at = message.createdAt?.toLocal();+ String two(int n) => n.toString().padLeft(2, '0');+ final key = ValueKey('swarm-message-${message.id}');+ final padding = SwarmMessageFrame.padding(grouped: grouped);+ final frame = SwarmMessageFrame(+ grouped: grouped,+ onAvatar: onAuthor,+ avatarKey: ValueKey('swarm-author-${message.id}'),+ avatarLabel: name,+ avatar: SwarmChatAvatar(+ name: name,+ id: message.authorId,+ agent: message.fromAgent,+ pm: role == 'PM',+ picture: look.picture,+ status: look.status,+ ),+ header: SwarmMessageHeader(+ name: name,+ agent: message.fromAgent,+ role: role,+ trailing: at == null+ ? null+ : Text(+ '${two(at.hour)}:${two(at.minute)}',+ style: tty.style(color: AppPalette.textFaint, size: 12.5),+ ),+ ),+ body: [+ if (lit) SizedBox(key: ValueKey('swarm-lit-${message.id}')),+ ?quote,+ if (message.text.isNotEmpty)+ Semantics(+ button: true,+ hint: 'Reply to this message',+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: Padding(+ padding: const EdgeInsets.only(top: SwarmMessageFrame.bodyGap),+ child: SizedBox(+ width: double.infinity,+ child: Text.rich(+ mentions.span(+ message.text,+ swarmChatText(16, height: 1.42),+ ),+ ),+ ),+ ),+ ),+ ),+ for (final file in message.attachments)+ SwarmAttachment(+ file: file,+ link: swarmAttachmentLink(file.url),+ chip: SwarmFileChip(+ file: file,+ link: swarmAttachmentLink(file.url),+ ),+ ),+ ?reactions,+ ?below,+ if (actions)+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.s),+ child: Wrap(+ spacing: 6,+ runSpacing: 6,+ children: [+ if (onReply case final reply?)+ SwarmSmallButton(+ key: ValueKey('swarm-reply-${message.id}'),+ icon: LucideIcons.reply,+ label: 'Reply',+ onTap: reply,+ ),+ SwarmSmallButton(+ icon: LucideIcons.copy,+ label: 'Copy',+ onTap: () => unawaited(+ Clipboard.setData(ClipboardData(text: message.text)),+ ),+ ),+ ],+ ),+ ),+ ],+ );+ final held = onLongPress == null+ ? frame+ : GestureDetector(+ behavior: HitTestBehavior.translucent,+ onLongPress: onLongPress,+ child: frame,+ );+ if (!followed) return Padding(key: key, padding: padding, child: held);+ return AnimatedContainer(+ key: key,+ duration: const Duration(milliseconds: 600),+ curve: Curves.easeOut,+ padding: padding,+ decoration: BoxDecoration(+ color: lit+ ? AppPalette.accentOnSurface.withValues(alpha: 0.16)+ : Colors.transparent,+ borderRadius: BorderRadius.circular(AppControl.rowRadius),+ ),+ child: held,+ );+ }+}++/// A message's first line: who, in what role, then [trailing] — its time,+/// or how its post is going.+class SwarmMessageHeader extends StatelessWidget {+ const SwarmMessageHeader({+ super.key,+ required this.name,+ required this.agent,+ this.role,+ this.trailing,+ });++ final String name;+ final bool agent;+ final String? role;+ final Widget? trailing;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Wrap(+ spacing: 6,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ Text(+ name,+ style: swarmChatText(+ 13.5,+ color: agent ? tty.cyan : tty.green,+ weight: FontWeight.w600,+ ),+ ),+ if (role case final role?) SwarmRoleBadge(role),+ ?trailing,+ ],+ );+ }+}++/// A role's compact badge: PM, Dev, Rev.+class SwarmRoleBadge extends StatelessWidget {+ const SwarmRoleBadge(this.label, {super.key});++ final String label;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Container(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ decoration: BoxDecoration(+ border: Border.all(color: swarmChatHair(tty)),+ borderRadius: BorderRadius.circular(AppCard.insetRadius),+ ),+ child: Text(+ label,+ style: tty+ .style(+ color: AppPalette.textSecondary,+ weight: FontWeight.w600,+ size: 11,+ )+ .copyWith(height: 16 / 11, letterSpacing: 0.44),+ ),+ );+ }+}++/// Who wrote a message, in a circle: an agent's initial on its own deep+/// colour — blue for a Product Manager, as the prototype has River — the+/// person's on theirs, white on each — or the picture they chose, and a+/// person's status emoji while it lasts.+class SwarmChatAvatar extends StatelessWidget {+ const SwarmChatAvatar({+ super.key,+ required this.name,+ required this.id,+ required this.agent,+ this.pm = false,+ this.picture,+ this.status,+ });++ static const double size = 32;++ /// The member palette's hues in the order the chat has always given them,+ /// so no one's colour moves: the [pm]'s blue first, then the six an agent+ /// takes by its id (blue, teal, violet, amber, rose, green, slate).+ static final _agents = [+ for (final hue in const [0, 1, 5, 3, 4, 2, 7])+ AppPalette.avatarPalette[hue],+ ];++ final String name, id;+ final bool agent;++ /// A project's Product Manager: the prototype's blue, kept for them alone.+ final bool pm;++ /// What they chose to wear; null wears the initial.+ final SuperTabAvatarPicture? picture;++ /// A person's status; null for an agent.+ final SuperTabPersonStatus? status;++ @override+ Widget build(BuildContext context) {+ final fill = !agent+ ? AppPalette.avatarFillDark+ : pm+ ? _agents.first+ : _agents[1 ++ id.codeUnits.fold(0, (a, b) => a + b) % (_agents.length - 1)];+ final initial = name.trim().isEmpty+ ? '?'+ : name.trim().characters.first.toUpperCase();+ return SwarmStatusFace(+ name: name,+ size: size,+ status: status,+ face: SwarmFace(+ picture: picture,+ size: size,+ tint: fill,+ fallback: Container(+ width: size,+ height: size,+ alignment: Alignment.center,+ decoration: BoxDecoration(color: fill, shape: BoxShape.circle),+ child: Text(+ initial,+ style: swarmChatText(+ 13.5,+ color: AppInk.onFill,+ weight: FontWeight.w600,+ ),+ ),+ ),+ ),+ );+ }+}++/// What a reply answers: its author and the start of its text, or that it+/// is not loaded. A tap leads to it.+class SwarmQuote extends StatelessWidget {+ const SwarmQuote({super.key, this.author, this.text, this.onTap});++ /// Null while the original is not loaded.+ final String? author, text;+ final VoidCallback? onTap;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ final quote = Container(+ width: double.infinity,+ margin: const EdgeInsets.symmetric(vertical: AppSpace.xs),+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.m,+ vertical: AppSpace.s,+ ),+ decoration: BoxDecoration(+ color: tty.text.withValues(alpha: 0.05),+ border: Border(left: BorderSide(color: AppPalette.textFaint, width: 3)),+ borderRadius: const BorderRadius.horizontal(+ left: Radius.circular(4),+ right: Radius.circular(10),+ ),+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (author case final author?)+ Text(+ author,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(13.5, weight: FontWeight.w600),+ ),+ Text(+ text ?? "The original message isn't loaded.",+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(14, color: AppPalette.textSecondary),+ ),+ ],+ ),+ );+ if (onTap == null) return quote;+ return Semantics(+ button: true,+ label: 'Go to the quoted message',+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: quote,+ ),+ );+ }+}++/// A message's action — Reply, Copy, Send again: small, rounded, raised.+class SwarmSmallButton extends StatelessWidget {+ const SwarmSmallButton({+ super.key,+ required this.icon,+ required this.label,+ required this.onTap,+ });++ final IconData icon;+ final String label;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Semantics(+ button: true,+ label: label,+ excludeSemantics: true,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: Container(+ constraints: const BoxConstraints(minHeight: 36),+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.m),+ decoration: BoxDecoration(+ color: ttyRaised(tty),+ border: Border.all(color: swarmChatHair(tty)),+ borderRadius: BorderRadius.circular(AppControl.radius),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(icon, size: 16, color: AppPalette.textPrimary),+ const SizedBox(width: 8),+ Text(label, style: swarmChatText(14, weight: FontWeight.w500)),+ ],+ ),+ ),+ ),+ );+ }+}++/// A file's size as a chat shows it: whole kilobytes, rounded up, or megabytes to one place.+String swarmFileSize(int bytes) {+ final kb = (bytes / 1024).ceil();+ return kb < 1024 ? '$kb KB' : '${(kb / 1024).toStringAsFixed(1)} MB';+}++/// A message's file: opened in the browser when its link is the backend's.+class SwarmFileChip extends StatelessWidget {+ const SwarmFileChip({super.key, required this.file, required this.link});++ final SuperTabAttachment file;+ final Uri? link;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ final size = swarmFileSize(file.size);+ final url = link;+ final color = url == null ? AppPalette.textFaint : tty.blue;+ return Padding(+ padding: const EdgeInsets.only(top: AppSpace.s),+ child: Semantics(+ button: url != null,+ label: 'File: ${file.name}, $size',+ excludeSemantics: true,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: url == null+ ? null+ : () => unawaited(+ launchUrl(url, mode: LaunchMode.inAppBrowserView),+ ),+ child: Container(+ constraints: const BoxConstraints(minHeight: 40),+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.m),+ decoration: BoxDecoration(+ color: swarmChatCard(tty),+ border: Border.all(color: swarmChatHair(tty)),+ borderRadius: BorderRadius.circular(AppControl.radius),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(LucideIcons.file, size: 16, color: color),+ const SizedBox(width: 8),+ Flexible(+ child: Text(+ file.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(14, color: color),+ ),+ ),+ const SizedBox(width: 8),+ Text(+ size,+ style: swarmChatText(13, color: AppPalette.textFaint),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_models_page.dart b/mobile/lib/swarm/swarm_models_page.dartnew file mode 100644index 000000000..b6049f137--- /dev/null+++ b/mobile/lib/swarm/swarm_models_page.dart@@ -0,0 +1,234 @@+import 'package:flutter/material.dart';++import 'package:harness_mobile/phone/out_of_sight.dart';+import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'model.dart';+import 'swarm_inbox.dart';+import 'swarm_reader.dart';+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';++/// One model on Your models: its name, who serves an API ([provider]), and+/// the computer that offers it.+typedef SwarmModelRow = ({String name, String? provider, String machine});++/// The models a Swarm can use now, by what each is — the words of Desktop's+/// machine details: [apis] a member shares, [local] models of members' own+/// running on the Swarm's grid, and models shared with one machine's owner,+/// usable on that machine alone ([oneComputer]).+class SwarmModelList {+ const SwarmModelList(this.apis, this.local, this.oneComputer);++ final List<SwarmModelRow> apis, local, oneComputer;++ bool get isEmpty => apis.isEmpty && local.isEmpty && oneComputer.isEmpty;+}++/// What [snapshot]'s machines' fresh readings say the Swarm can use now+/// ([superTabLocalModelRows]), or null while its owner has not turned its+/// models on.+SwarmModelList? swarmModelList(+ SuperTabSnapshot snapshot, {+ required DateTime now,+}) {+ final models = snapshot.localModels;+ if (models == null || !models.enabled) return null;+ final apis = <SwarmModelRow>[], local = <SwarmModelRow>[];+ final oneComputer = <SwarmModelRow>[];+ for (final row in superTabLocalModelRows(snapshot, now: now)) {+ switch (row.kind) {+ case 'api':+ // As Desktop names an API model: its own name without the+ // provider's path; who serves it is in its label after the dot.+ final dot = row.name.lastIndexOf(' · ');+ apis.add((+ name: row.model.substring(row.model.lastIndexOf('/') + 1),+ provider: dot < 0 ? null : row.name.substring(dot + 3),+ machine: row.machine,+ ));+ case 'shared':+ oneComputer.add((name: row.name, provider: null, machine: row.machine));+ default:+ local.add((name: row.name, provider: null, machine: row.machine));+ }+ }+ return SwarmModelList(apis, local, oneComputer);+}++/// Your models, from the drawer: for each of the account's Swarms, the models+/// it can use now. Read only — running and sharing models is on a computer.+class SwarmModelsPage extends StatelessWidget {+ const SwarmModelsPage({super.key, this.now = DateTime.now});++ final DateTime Function() now;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ final session = SwarmScope.of(context);+ return Scaffold(+ backgroundColor: tty.ground,+ body: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SwarmTopBar(+ leading: SwarmBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ title: 'Your models',+ subtitle: 'What the Swarm can use now',+ ),+ Expanded(+ child: session == null+ ? const SizedBox.shrink()+ : ListenWhileInSight(+ listenable: session.inbox,+ builder: (context) => RefreshIndicator(+ onRefresh: session.inbox.refresh,+ child: ListView(+ physics: const AlwaysScrollableScrollPhysics(),+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ 0,+ AppSpace.m,+ MediaQuery.paddingOf(context).bottom + 28,+ ),+ children: _body(session.inbox),+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }++ List<Widget> _body(SwarmInbox inbox) {+ final swarms = inbox.swarms;+ if (swarms.isEmpty) {+ return [+ const SizedBox(height: 6),+ if (inbox.loaded)+ _line(+ 'swarm-models-no-swarm',+ 'No Swarm yet. Start one on your computer.',+ )+ else+ SwarmSkeletonRows(id: 'swarm-models-loading', rows: 3),+ ];+ }+ // With several Swarms, each one's captions start with its name, as+ // Home's do.+ final several = swarms.length > 1;+ return [+ for (final (i, swarm) in swarms.indexed)+ ..._swarm(+ swarm.id,+ inbox.reader(swarm.id),+ name: several ? swarm.name : null,+ first: i == 0,+ ),+ ];+ }++ List<Widget> _swarm(+ String id,+ SwarmReader? reader, {+ required String? name,+ required bool first,+ }) {+ String caption(String text) => name == null ? text : '$name · $text';+ // The Swarm's own caption, over what stands for its models; with one+ // Swarm, the page's caption is it.+ List<Widget> alone(Widget child) => [+ if (name != null)+ SwarmCaption(name, first: first)+ else if (first)+ const SizedBox(height: 6),+ child,+ ];+ final snapshot = reader?.snapshot;+ if (snapshot == null) {+ return alone(switch (reader?.error) {+ final error? => SwarmGroup(+ key: ValueKey('swarm-models-error-$id'),+ children: [+ SwarmRow(+ title: error,+ detail: SwarmRow.line('Pull down to try again.'),+ onTap: null,+ ),+ ],+ ),+ null => SwarmSkeletonRows(id: 'swarm-models-loading-$id', rows: 3),+ });+ }+ final list = swarmModelList(snapshot, now: now());+ if (list == null) {+ return alone(+ _line(+ 'swarm-models-off-$id',+ "Models aren't set up for this Swarm yet. "+ 'Its owner sets them up on a computer.',+ ),+ );+ }+ if (list.isEmpty) {+ return alone(+ _line(+ 'swarm-models-none-$id',+ 'No models are running for this Swarm right now.',+ ),+ );+ }+ var top = first;+ List<Widget> section(String title, List<SwarmModelRow> rows, String kind) {+ if (rows.isEmpty) return const [];+ final heading = SwarmCaption(caption(title), first: top);+ top = false;+ return [+ heading,+ SwarmGroup(+ key: ValueKey('swarm-models-$kind-$id'),+ children: [+ for (final row in rows)+ SwarmRow(+ title: row.name,+ detail: SwarmRow.line(switch (kind) {+ 'api' => 'Shared by ${row.machine}',+ 'local' => 'Runs on ${row.machine}',+ _ => '${row.machine} only',+ }),+ trailing: row.provider == null+ ? null+ : SwarmRow.line(row.provider!),+ onTap: null,+ ),+ ],+ ),+ ];+ }++ return [+ ...section('API models', list.apis, 'api'),+ ...section('Local models', list.local, 'local'),+ ...section('On one computer only', list.oneComputer, 'one'),+ ];+ }+}++/// What a page says where it has nothing to list: a line under its caption,+/// as Home's empty states are.+Widget _line(String id, String text) => Padding(+ key: ValueKey(id),+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: SwarmRow.line(text, lines: 2),+);diff --git a/mobile/lib/swarm/swarm_need_rows.dart b/mobile/lib/swarm/swarm_need_rows.dartnew file mode 100644index 000000000..a9a244098--- /dev/null+++ b/mobile/lib/swarm/swarm_need_rows.dart@@ -0,0 +1,555 @@+import 'dart:async';+import 'dart:math' as math;++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../shared/theme/app_space.dart';+import '../shared/theme/app_theme.dart';+import '../shared/theme/app_type.dart';+import '../theme/app_theme.dart' show AppColors;+import 'swarm_asks.dart';+import 'swarm_inbox.dart';+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';++/// Opens where a need was asked: a Swarm's conversation.+typedef SwarmOpen = void Function(String swarmId, String conversationId);++/// A need's glyph: a question for a decision, @ for a tag, a clock for work+/// waiting on the person.+IconData swarmNeedIcon(SwarmNeed need) => switch (need) {+ SwarmDecisionNeed() => LucideIcons.circleQuestionMark300,+ SwarmMentionNeed() => LucideIcons.atSign300,+ SwarmWorkNeed() => LucideIcons.clock300,+};++/// The project a need was asked in.+String _projectOf(SwarmNeed need) => switch (need) {+ SwarmDecisionNeed(:final decision) => decision.projectName,+ SwarmMentionNeed(:final mention) => mention.projectName,+ SwarmWorkNeed(:final work) => work.project.name,+};++/// One thing a Swarm asks of the person, open on Swarm Home: its glyph, who+/// asks and in which project — a tap there opens where it was asked — what+/// they ask, and what the person can do: a decision's options, Done on a+/// tag ("Done…" until confirmed, a failure said under it), Open chat on work+/// waiting on them.+class SwarmNeedRow extends StatelessWidget {+ const SwarmNeedRow({+ super.key,+ required this.session,+ required this.need,+ required this.onOpen,+ });++ final SwarmSession session;+ final SwarmNeed need;+ final SwarmOpen onOpen;++ void _open() => onOpen(need.swarmId, need.conversationId);++ @override+ Widget build(BuildContext context) => switch (need) {+ final SwarmDecisionNeed decision => SwarmDecisionCard(+ key: ValueKey('swarm-need-${need.key}'),+ session: session,+ need: decision,+ onOpen: _open,+ ),+ SwarmMentionNeed(:final mention) => _mention(mention),+ SwarmWorkNeed(:final work) => _NeedCard(+ key: ValueKey('swarm-need-${need.key}'),+ need: need,+ onOpen: _open,+ body: work.question ?? work.conversation.label,+ actions: SwarmButton(+ key: ValueKey('swarm-need-chat-${need.key}'),+ label: 'Open chat',+ style: SwarmButtonStyle.fill,+ wide: true,+ onPressed: _open,+ ),+ ),+ };++ /// A Lead's tag: Done says "Done…" the moment it is tapped, the tag goes+ /// once confirmed, and a failure is said under it.+ Widget _mention(SuperTabMention mention) {+ final asks = session.inbox.asks(need.swarmId);+ return _NeedCard(+ key: ValueKey('swarm-need-${need.key}'),+ need: need,+ onOpen: _open,+ body: mention.text.isNotEmpty ? mention.text : mention.conversationTitle,+ actions: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ Expanded(+ child: SwarmButton(+ key: ValueKey('swarm-done-${mention.id}'),+ label: 'Done',+ style: SwarmButtonStyle.fill,+ busy: asks?.finishing(mention) ?? false,+ busyLabel: 'Done…',+ onPressed: () => unawaited(asks?.done(mention)),+ ),+ ),+ const SizedBox(width: 8),+ SwarmButton(+ key: ValueKey('swarm-need-chat-${need.key}'),+ label: 'Open chat',+ style: SwarmButtonStyle.link,+ onPressed: _open,+ ),+ ],+ ),+ if (asks?.notDone(mention) case final failure?) ...[+ const SizedBox(height: 8),+ Text(+ failure,+ key: ValueKey('swarm-not-done-${mention.id}'),+ style: AppType.caption(color: AppColors.danger, height: 1.35),+ ),+ ],+ ],+ ),+ );+ }+}++/// Who asks, in a few words: "River asks you", "Nova is stuck".+String swarmNeedTitle(SwarmNeed need) => switch (need) {+ SwarmDecisionNeed(:final decision) => '${decision.askerName} asks you',+ SwarmMentionNeed(:final mention) => '${mention.leadName} tagged you',+ SwarmWorkNeed(:final work) =>+ work.status == 'blocked'+ ? '${work.agentName} is stuck'+ : '${work.agentName} needs you',+};++/// A need on Swarm Home while another is open there: its glyph, who asks and+/// one line of what, a tap to open it in its place. A decision whose answer+/// is held for Undo says so.+class SwarmNeedLine extends StatelessWidget {+ const SwarmNeedLine({+ super.key,+ required this.session,+ required this.need,+ required this.onTap,+ });++ final SwarmSession session;+ final SwarmNeed need;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final line = switch (need) {+ final SwarmDecisionNeed decision => switch (session.held(decision)) {+ final choice? =>+ 'Sending “${_option(decision.decision.options, choice)}”',+ null => decision.decision.question,+ },+ SwarmMentionNeed(:final mention) =>+ mention.text.isNotEmpty ? mention.text : mention.conversationTitle,+ SwarmWorkNeed(:final work) => work.question ?? work.conversation.label,+ };+ return SwarmRow(+ leading: Icon(+ swarmNeedIcon(need),+ size: 20,+ color: AppPalette.textSecondary,+ ),+ title: swarmNeedTitle(need),+ detail: line.isEmpty ? null : SwarmRow.line(line),+ chevron: LucideIcons.chevronDown300,+ onTap: onTap,+ );+ }+}++/// The line height of a need's title, which its glyph is centred on.+const _titleHeight = 1.3;++/// An open need: its glyph in the warning colour, who asks and where — a tap+/// there opens where it was asked, when [onOpen] is given — then [body] and+/// [actions].+class _NeedCard extends StatelessWidget {+ const _NeedCard({+ super.key,+ required this.need,+ required this.body,+ required this.actions,+ this.onOpen,+ });++ final SwarmNeed need;+ final String body;+ final Widget actions;+ final VoidCallback? onOpen;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final project = _projectOf(need);+ final header = Text.rich(+ TextSpan(+ children: [+ TextSpan(text: swarmNeedTitle(need)),+ if (project.isNotEmpty)+ TextSpan(+ text: ' · $project',+ style: AppType.caption(+ color: AppPalette.textSecondary,+ fontWeight: AppFont.regular,+ ),+ ),+ ],+ ),+ style: AppType.label(color: AppPalette.textPrimary, height: _titleHeight),+ );+ return Padding(+ padding: const EdgeInsets.all(AppSpace.l),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ // As tall as the title's first line, the glyph centred in it.+ SizedBox(+ height: AppType.bodySize * _titleHeight,+ child: Center(+ child: Icon(+ swarmNeedIcon(need),+ size: 20,+ color: AppColors.warning,+ ),+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (onOpen case final open?)+ GestureDetector(+ key: ValueKey('swarm-need-open-${need.key}'),+ behavior: HitTestBehavior.opaque,+ onTap: open,+ child: header,+ )+ else+ header,+ if (body.isNotEmpty) ...[+ const SizedBox(height: 6),+ Text.rich(+ _mentions(body),+ style: AppType.body(+ color: AppPalette.textPrimary,+ height: 1.4,+ ),+ ),+ ],+ const SizedBox(height: 14),+ actions,+ ],+ ),+ ),+ ],+ ),+ );+ }+}++/// [text] with each @name in the accent, on a faint wash.+TextSpan _mentions(String text) {+ final spans = <InlineSpan>[];+ var at = 0;+ for (final match in RegExp(r'@[\w.-]+').allMatches(text)) {+ if (match.start > at) {+ spans.add(TextSpan(text: text.substring(at, match.start)));+ }+ spans.add(+ TextSpan(+ text: match[0],+ style: TextStyle(+ color: AppPalette.swarmAccent,+ backgroundColor: AppPalette.swarmAccent.withValues(alpha: .13),+ fontWeight: FontWeight.w500,+ ),+ ),+ );+ at = match.end;+ }+ if (at < text.length) spans.add(TextSpan(text: text.substring(at)));+ return TextSpan(children: spans);+}++/// A decision asked of the person: who asks, the question, and what can be+/// done with it ([SwarmDecisionAnswer]).+class SwarmDecisionCard extends StatelessWidget {+ const SwarmDecisionCard({+ super.key,+ required this.session,+ required this.need,+ this.onOpen,+ });++ final SwarmSession session;+ final SwarmDecisionNeed need;++ /// Opens the conversation it was asked in; null where it is already open.+ final VoidCallback? onOpen;++ @override+ Widget build(BuildContext context) => _NeedCard(+ need: need,+ onOpen: onOpen,+ body: need.decision.question,+ actions: SwarmDecisionAnswer(session: session, need: need),+ );+}++/// What can be done with an open decision, as the prototype draws it on+/// Swarm Home and in a chat alike: its options side by side. One tap holds+/// the answer for the session's Undo window — a bar drains while it waits —+/// then sends it; an answer cannot be changed once sent. In a chat's card+/// ([fillRecommended]) the recommended option is filled.+class SwarmDecisionAnswer extends StatelessWidget {+ const SwarmDecisionAnswer({+ super.key,+ required this.session,+ required this.need,+ this.fillRecommended = false,+ });++ final SwarmSession session;+ final SwarmDecisionNeed need;+ final bool fillRecommended;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final decision = need.decision;+ final asks = session.inbox.asks(need.swarmId);+ final held = session.held(need);+ final sending = asks?.answering.contains(decision.id) ?? false;+ final note = AppType.caption(color: AppColors.warning, height: 1.35);+ final Widget actions;+ if (held != null) {+ actions = _Held(+ key: ValueKey('swarm-held-box-${decision.id}-$held'),+ label: 'Sending “${_option(decision.options, held)}”',+ labelKey: ValueKey('swarm-held-${decision.id}'),+ window: session.undoWindow,+ action: SwarmButton(+ key: ValueKey('swarm-undo-${decision.id}'),+ label: 'Undo',+ style: SwarmButtonStyle.link,+ onPressed: () => session.undo(need),+ ),+ );+ } else if (sending) {+ actions = const _Held(label: 'Sending…');+ } else if (asks?.unconfirmed(decision) case final choice?) {+ // Sent, and maybe taken: only the same answer may go again.+ actions = _Held(+ label: '“${_option(decision.options, choice)}” is not confirmed.',+ action: SwarmButton(+ key: ValueKey('swarm-resend-${decision.id}'),+ label: 'Send again',+ style: SwarmButtonStyle.link,+ onPressed: () => unawaited(asks!.answer(decision, choice)),+ ),+ );+ } else {+ actions = Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (session.dropped(need)) ...[+ Text(+ 'Not sent, choose again.',+ key: ValueKey('swarm-dropped-${decision.id}'),+ style: note,+ ),+ const SizedBox(height: 8),+ ],+ _Options(+ labels: decision.options,+ filled: fillRecommended ? decision.recommended : null,+ keyOf: (index) => ValueKey('swarm-option-${decision.id}-$index'),+ onTap: (index) => session.hold(need, index),+ ),+ ],+ );+ }+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ actions,+ if (asks?.error case final error?) ...[+ const SizedBox(height: 8),+ Text(error, style: note.copyWith(color: AppColors.danger)),+ ],+ ],+ );+ }+}++String _option(List<String> options, int index) =>+ index >= 0 && index < options.length ? options[index] : 'Option $index';++/// A decision's options, as many to a line as fit at 120 points or more,+/// sharing it evenly; a long one wraps inside its button. The [filled] one,+/// if any, is filled and read as recommended.+class _Options extends StatelessWidget {+ const _Options({+ required this.labels,+ required this.keyOf,+ required this.onTap,+ this.filled,+ });++ final List<String> labels;+ final Key Function(int index) keyOf;+ final void Function(int index) onTap;+ final int? filled;++ static const _gap = 8.0, _least = 120.0;++ @override+ Widget build(BuildContext context) => LayoutBuilder(+ builder: (context, constraints) {+ final perLine = math.max(+ 1,+ ((constraints.maxWidth + _gap) / (_least + _gap)).floor(),+ );+ final lines = [+ for (var start = 0; start < labels.length; start += perLine)+ [+ for (+ var i = start;+ i < math.min(start + perLine, labels.length);+ i+++ )+ i,+ ],+ ];+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final (n, line) in lines.indexed) ...[+ if (n > 0) const SizedBox(height: _gap),+ IntrinsicHeight(+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final (j, index) in line.indexed) ...[+ if (j > 0) const SizedBox(width: _gap),+ Expanded(+ child: switch (SwarmButton(+ key: keyOf(index),+ label: labels[index],+ style: index == filled+ ? SwarmButtonStyle.fill+ : SwarmButtonStyle.plain,+ onPressed: () => onTap(index),+ )) {+ final button when index == filled => Semantics(+ button: true,+ label: '${labels[index]} (recommended)',+ onTap: () => onTap(index),+ excludeSemantics: true,+ child: button,+ ),+ final button => button,+ },+ ),+ ],+ ],+ ),+ ),+ ],+ ],+ );+ },+ );+}++/// An answer on its way: its words in a field, maybe a way to take it back,+/// and — while it is held — a bar that drains over [window].+class _Held extends StatelessWidget {+ const _Held({+ super.key,+ required this.label,+ this.labelKey,+ this.action,+ this.window,+ });++ final String label;+ final Key? labelKey;+ final Widget? action;+ final Duration? window;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return ClipRRect(+ borderRadius: BorderRadius.circular(AppControl.rowRadius),+ child: ColoredBox(+ color: AppPalette.swarmSearchSurface,+ child: Stack(+ children: [+ ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 48),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.xs,+ AppSpace.xs,+ AppSpace.xs,+ ),+ child: Row(+ children: [+ Expanded(+ child: Text(+ label,+ key: labelKey,+ style: AppType.body(+ color: AppPalette.textPrimary,+ height: 1.3,+ ),+ ),+ ),+ ?action,+ ],+ ),+ ),+ ),+ if (window case final window? when window > Duration.zero)+ Positioned(+ left: 0,+ right: 0,+ bottom: 0,+ child: TweenAnimationBuilder<double>(+ tween: Tween(begin: 1, end: 0),+ duration: window,+ builder: (context, left, _) => FractionallySizedBox(+ alignment: Alignment.centerLeft,+ widthFactor: left,+ child: Container(height: 3, color: AppPalette.accent),+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_notices.dart b/mobile/lib/swarm/swarm_notices.dartnew file mode 100644index 000000000..771b47964--- /dev/null+++ b/mobile/lib/swarm/swarm_notices.dart@@ -0,0 +1,119 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import '../notify/system_notices.dart';+import 'swarm_inbox.dart';++/// The notice that tells the person about [need]: who asks, and in which+/// project.+///+/// A notice can be read on a locked phone, and neither platform lets this app+/// hide one part of it there for sure: so what is asked, and the conversation+/// it is in, are read in the app only (Lead, 2026-10-27). The one place to+/// change if notices may say more.+SwarmNoticeMessage swarmNotice(SwarmNeed need) {+ final (title, project, body) = switch (need) {+ SwarmDecisionNeed(:final decision) => (+ '${decision.askerName} asks you',+ decision.projectName,+ 'Open Harness to answer.',+ ),+ SwarmMentionNeed(:final mention) => (+ '${mention.leadName} tagged you',+ mention.projectName,+ 'Open Harness to read it.',+ ),+ SwarmWorkNeed(:final work) when work.status == 'blocked' => (+ '${work.agentName} is stuck',+ work.project.name,+ 'Open Harness to see why.',+ ),+ SwarmWorkNeed(:final work) => (+ '${work.agentName} needs you',+ work.project.name,+ 'Open Harness to answer.',+ ),+ };+ return (+ key: need.key,+ title: title,+ subtitle: project,+ body: body,+ target: (+ swarmId: need.swarmId,+ conversationId: need.conversationId,+ messageId: need is SwarmMentionNeed ? need.mention.messageId : null,+ decisionId: need is SwarmDecisionNeed ? need.decision.id : null,+ ),+ );+}++/// Posts a notice for each need that arrives ([SwarmInbox.onArrived]) unless+/// the person is already looking at it ([quiet]), and takes it down once the+/// need is gone ([settle]): answered on the desktop, done, or no longer+/// waiting.+///+/// The app icon counts the needs, as the drawer's waiting badge does, on each+/// read and whether or not a notice was posted; it is set only when the count+/// changes, and the first read sets it even at zero, over what an earlier run+/// left there.+class SwarmAnnouncer {+ SwarmAnnouncer(this.notices, {required this.quiet});++ final SwarmNotices notices;++ /// The person sees [need] where they are: no notice.+ final bool Function(SwarmNeed need) quiet;++ /// Keys of the notices posted and not yet taken down.+ final _posted = <String>{};++ /// The count on the app icon; null before the first read.+ int? _badge;++ void announce(SwarmNeed need) {+ if (quiet(need)) return;+ final notice = swarmNotice(need);+ _posted.add(notice.key);+ unawaited(notices.showSwarm(notice));+ }++ /// Takes down the notices of needs not in [needs], and counts [needs] on+ /// the app icon.+ void settle(List<SwarmNeed> needs) {+ final open = {for (final need in needs) need.key};+ for (final key in _posted.where((key) => !open.contains(key)).toList()) {+ _posted.remove(key);+ unawaited(notices.cancelSwarm(key));+ }+ if (needs.length != _badge) {+ _badge = needs.length;+ unawaited(notices.setSwarmBadge(needs.length));+ }+ }++ /// Takes every notice and the icon's count down: the account that saw them+ /// signed out, or Swarm was turned off.+ void clear() => settle(const []);+}++/// Takes the app icon's count off each time [app] finds nobody signed in+/// ([signedOut]), and at once if it already knows. A launch that starts+/// signed out never makes a Swarm session, whose end ([SwarmAnnouncer.clear])+/// would have taken the last account's count off. Lives as long as [app].+void swarmBadgeOffWhileSignedOut(+ Listenable app, {+ required bool Function() signedOut,+ required SwarmNotices notices,+}) {+ var off = false;+ void check() {+ final now = signedOut();+ if (now && !off) unawaited(notices.setSwarmBadge(0));+ off = now;+ }++ app.addListener(check);+ check();+}diff --git a/mobile/lib/swarm/swarm_outgoing_files.dart b/mobile/lib/swarm/swarm_outgoing_files.dartnew file mode 100644index 000000000..79fd96f8e--- /dev/null+++ b/mobile/lib/swarm/swarm_outgoing_files.dart@@ -0,0 +1,132 @@+import 'package:flutter/foundation.dart';++/// What the backend allows one message to carry (the desktop's+/// `kSuperTabAttachmentMaxBytes` and `kSuperTabAttachmentMaxFiles`,+/// backend `superTabs/attachments.ts`).+const swarmAttachmentMaxBytes = 10 * 1024 * 1024;+const swarmAttachmentMaxFiles = 10;++/// One file waiting to go with a message: its bytes in memory only, never+/// written anywhere on the phone.+@immutable+class SwarmOutgoingFile {+ const SwarmOutgoingFile(this.name, this.bytes);++ final String name;+ final Uint8List bytes;+}++/// The files waiting to go with the next message in a chat — the desktop's+/// `HarnessAttachments` with a Swarm chat's limits, wording and all. Held in+/// memory until sent, or until the chat closes.+class SwarmOutgoingFiles extends ChangeNotifier {+ final _files = <SwarmOutgoingFile>[];++ List<SwarmOutgoingFile> get files => List.unmodifiable(_files);++ /// How many more files fit.+ int get room => swarmAttachmentMaxFiles - _files.length;++ /// Adds the files that fit, replacing one of the same name. Returns what+ /// to tell the person about any left out — past the count, over the size,+ /// or both — or null when all were taken.+ /// [oversized] names files already known to be over the limit, which were+ /// never read into memory to be refused here; [surplus] counts those the+ /// picker already left out for want of room.+ String? add(+ Iterable<SwarmOutgoingFile> files, {+ Iterable<String> oversized = const [],+ int surplus = 0,+ }) {+ final tooLarge = [...oversized];+ var over = surplus;+ for (final file in files) {+ if (file.bytes.isEmpty) continue;+ if (file.bytes.length > swarmAttachmentMaxBytes) {+ tooLarge.add(file.name);+ continue;+ }+ _files.removeWhere((kept) => kept.name == file.name);+ if (_files.length >= swarmAttachmentMaxFiles) {+ over++;+ continue;+ }+ _files.add(file);+ }+ notifyListeners();+ const limit = '${swarmAttachmentMaxBytes ~/ (1024 * 1024)} MB';+ // Both limits can leave files out at once; each says so.+ final notes = [+ if (over > 0) 'Attach at most $swarmAttachmentMaxFiles files.',+ if (tooLarge.length == 1) '${tooLarge.single} is over $limit.',+ if (tooLarge.length > 1) '${tooLarge.length} files are over $limit.',+ ];+ return notes.isEmpty ? null : notes.join(' ');+ }++ /// Adds photos beside what is there: the camera and the library name every+ /// photo alike, so one whose name is taken is numbered, not swapped in (the+ /// desktop's `addPasted`).+ String? addNumbered(+ Iterable<SwarmOutgoingFile> files, {+ Iterable<String> oversized = const [],+ int surplus = 0,+ }) {+ final taken = {for (final file in _files) file.name};+ return add(+ [+ for (final file in files)+ SwarmOutgoingFile(swarmFreeName(file.name, taken), file.bytes),+ ],+ oversized: oversized,+ surplus: surplus,+ );+ }++ void remove(SwarmOutgoingFile file) {+ if (_files.remove(file)) notifyListeners();+ }++ void clear() {+ if (_files.isEmpty) return;+ _files.clear();+ notifyListeners();+ }+}++/// [name], or `name-2.ext`, `name-3.ext`… — the first not in [taken], which+/// then holds it.+String swarmFreeName(String name, Set<String> taken) {+ final dot = name.lastIndexOf('.');+ final stem = dot > 0 ? name.substring(0, dot) : name;+ final extension = dot > 0 ? name.substring(dot) : '';+ var candidate = name;+ for (var count = 2; !taken.add(candidate); count++) {+ candidate = '$stem-$count$extension';+ }+ return candidate;+}++/// The content type a file of this [name] is sent as: the kinds a chat shows+/// or opens, and `application/octet-stream` for the rest (the desktop's+/// `mimeForName`).+String swarmMimeForName(String name) {+ final dot = name.lastIndexOf('.');+ final extension = dot < 0 ? '' : name.substring(dot + 1).toLowerCase();+ return _mimes[extension] ?? 'application/octet-stream';+}++const _mimes = {+ 'png': 'image/png',+ 'jpg': 'image/jpeg',+ 'jpeg': 'image/jpeg',+ 'gif': 'image/gif',+ 'webp': 'image/webp',+ 'pdf': 'application/pdf',+ 'json': 'application/json',+ 'zip': 'application/zip',+ 'txt': 'text/plain',+ 'log': 'text/plain',+ 'md': 'text/markdown',+ 'csv': 'text/csv',+};diff --git a/mobile/lib/swarm/swarm_page.dart b/mobile/lib/swarm/swarm_page.dartindex 96015e3b5..8b2794956 100644--- a/mobile/lib/swarm/swarm_page.dart+++ b/mobile/lib/swarm/swarm_page.dart@@ -1,54 +1,538 @@+import 'dart:async';+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:harness_mobile/phone/out_of_sight.dart';+import 'package:harness_mobile/phone/phone_navigation.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';import 'package:harness_mobile/phone/tty.dart';-import 'package:harness_mobile/phone/tty_controls.dart';-import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'swarm_buddy.dart';+import 'swarm_buddy_chat.dart';+import 'swarm_choices.dart';+import 'swarm_connection_notice.dart';+import 'swarm_conversation_page.dart';+import 'swarm_drawer.dart';+import 'swarm_home_keeper.dart';+import 'swarm_inbox.dart';+import 'swarm_profile_sheet.dart';+import 'swarm_need_rows.dart';+import 'swarm_project_page.dart';+import 'swarm_reader.dart';+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_start.dart';+import 'swarm_style.dart';+import 'swarm_unread.dart';++/// Swarm Home from anywhere in the shell: every page closed and Swarm Home+/// the root again ([PhoneShellScope.onShowSwarm]). Without the shell — a+/// page pumped on its own — a Swarm page over [context]'s.+void openSwarmHome(BuildContext context) {+ if (PhoneShellScope.maybeOf(context)?.onShowSwarm case final show?) {+ show();+ return;+ }+ unawaited(Navigator.of(context).push(phoneRoute((_) => const SwarmPage())));+}-/// Swarm on the phone: where its screens go as they are built.+/// Swarm Home: what every Swarm of the account asks of the person ("Needs+/// you"), one thing open at a time; Buddies, the person's Buddy chat in each+/// project; then the projects, each with its team in a line+/// ([swarmNeedsFirst] orders needs and the rest). Its drawer ([SwarmDrawer])+/// is the way to everything else.///-/// Reached only from the Swarm command in Find, which is offered only while Settings ▸-/// Experimental ▸ Swarm is on ([PhoneExperiment.swarm]). Until the first screen lands, this page-/// says so, and where the switch is.-class SwarmPage extends StatelessWidget {- const SwarmPage({super.key});+/// The phone's Home while Settings ▸ Experimental ▸ Swarm is on; pushed over+/// another page it has a back button instead of the drawer. Its top bar holds+/// the menu and its title in one line, as the approved prototype draws it.+/// Reads the account's [SwarmSession] from the shell; with none, says why.+class SwarmPage extends StatefulWidget {+ const SwarmPage({super.key, this.onSettings});++ /// Settings over Swarm Home, from the drawer.+ final void Function(BuildContext context)? onSettings;++ @override+ State<SwarmPage> createState() => _SwarmPageState();+}++class _SwarmPageState extends State<SwarmPage> {+ SwarmSession? _session;++ /// Kept out of sight under Harness ([OutOfSight]), as it was left: it is no+ /// Swarm screen meanwhile — a notice still tells what arrives — and draws+ /// nothing new. Shown again, it reads the Swarms as on any return to Home.+ bool _hidden = false;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final session = SwarmScope.of(context);+ final hidden = OutOfSight.of(context);+ if (session == _session && hidden == _hidden) return;+ if (!_hidden) _session?.leave();+ _session = session;+ _hidden = hidden;+ if (hidden || session == null) return;+ session.enter();+ unawaited(session.inbox.refresh());+ }++ @override+ void dispose() {+ if (!_hidden) _session?.leave();+ super.dispose();+ }++ void _openProject(BuildContext context, String swarmId, String projectId) =>+ unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => SwarmProjectPage(swarmId: swarmId, projectId: projectId),+ listensForItself: true,+ ),+ ),+ );++ /// The need open on Home, by its key; null opens the first.+ String? _focus;++ /// The Buddy chat being opened, as `swarmId/projectId`, and why the last+ /// one did not open.+ String? _buddyOpening;+ String? _buddyError;++ /// The person's Buddy chat in [projectId], opened on the server first when+ /// they have none yet. One at a time.+ Future<void> _openBuddy(String swarmId, String projectId) async {+ final reader = _session?.inbox.reader(swarmId);+ if (reader == null || _buddyOpening != null) return;+ setState(() {+ _buddyOpening = '$swarmId/$projectId';+ _buddyError = null;+ });+ final error = await openSwarmBuddy(context, reader, swarmId, projectId);+ if (!mounted) return;+ setState(() {+ _buddyOpening = null;+ _buddyError = error;+ });+ }@overrideWidget build(BuildContext context) {AppTheme.watch(context);final tty = Tty.of(context);+ final session = _session;+ // Pushed over another page: a page under Home's own route, never one over+ // it. Home builds while a page slides in over it (a Buddy chat opening),+ // and is not built again once that page goes, so the navigator's canPop+ // would leave the back button for good.+ final pushed = ModalRoute.isFirstOf(context) == false;return Scaffold(backgroundColor: tty.ground,+ // Home's drawer; a Swarm page pushed over another page has its back+ // button instead. None out of sight: one closing as Harness took the+ // screen would stop there, its animation off, and be found half open.+ drawer: pushed || _hidden+ ? null+ : ListenableBuilder(+ listenable: Listenable.merge([?session, ?session?.inbox]),+ builder: (context, _) => SwarmDrawer(+ session: session,+ onProject: (swarmId, projectId) =>+ _openProject(context, swarmId, projectId),+ onBuddy: (swarmId, projectId) =>+ unawaited(_openBuddy(swarmId, projectId)),+ onChat: (swarmId, conversationId) =>+ openSwarmConversation(context, swarmId, conversationId),+ onSettings: widget.onSettings,+ onProfile: (swarmId) =>+ unawaited(showSwarmProfile(context, swarmId: swarmId)),+ ),+ ),body: SafeArea(+ bottom: false,child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- Align(- alignment: Alignment.centerLeft,- child: TtyBackButton(- onPressed: () => Navigator.of(context).maybePop(),- ),- ),- Padding(- padding: const EdgeInsets.fromLTRB(Tty.origin, 8, Tty.origin, 0),- child: TtyText(- PhoneExperiment.swarm.label,- size: TtySize.display,- weight: FontWeight.w600,- ),- ),- Padding(- padding: const EdgeInsets.fromLTRB(Tty.origin, 16, Tty.origin, 0),- child: Text(- 'Swarm on the phone is still being built. '- 'Turn it off in Settings ▸ Experimental.',- key: const ValueKey('swarm-building'),- style: tty.style(color: tty.faint, size: TtySize.row),+ if (session == null)+ _topBar(context, pushed: pushed)+ else+ ListenWhileInSight(+ listenable: Listenable.merge([session, session.inbox]),+ builder: (context) => _topBar(+ context,+ pushed: pushed,+ updating: _updating(session.inbox),+ ),),+ Expanded(+ child: session == null+ ? const _Unavailable()+ : ListenWhileInSight(+ listenable: Listenable.merge([session, session.inbox]),+ // Before there is a Swarm to show, a start screen in+ // place of the body, under the same top bar.+ builder: (context) =>+ swarmStartView(context, session) ??+ RefreshIndicator(+ onRefresh: session.inbox.refresh,+ child: ListView(+ physics: const AlwaysScrollableScrollPhysics(),+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ 0,+ AppSpace.m,+ MediaQuery.paddingOf(context).bottom ++ AppSpace.xl,+ ),+ children: _body(context, session, tty),+ ),+ ),+ ),),],),),);}++ /// Home's top bar: the menu or back button and its title, with a quiet+ /// "Updating…" under it while it shows the Home kept ([_updating]).+ Widget _topBar(+ BuildContext context, {+ required bool pushed,+ bool updating = false,+ }) => SwarmTopBar(+ leading: pushed+ ? SwarmBackButton(onPressed: () => Navigator.of(context).maybePop())+ : const _MenuButton(),+ title: 'Swarm',+ subtitle: updating ? 'Updating…' : null,+ );++ List<Widget> _body(BuildContext context, SwarmSession session, Tty tty) {+ final inbox = session.inbox;+ // No computer answering: a card that says so over what Home has, never a+ // screen in its place, and no red line besides.+ final notice = inbox.noComputer+ ? SwarmConnectionNotice(+ inbox: inbox,+ computers: SwarmScope.computersOf(context),+ )+ : null;+ final error = notice == null ? inbox.error : null;+ // Before the list there is nothing to read, unless a Home was kept; a+ // list that could not be read says so alone, without rows on their way.+ if (!inbox.loaded && inbox.swarms.isEmpty) {+ return [+ ?notice,+ if (error != null)+ _error(error, key: 'swarm-error')+ else+ ..._reading(first: notice == null),+ ];+ }+ final several = inbox.swarms.length > 1;+ final empty = _emptyNeeds(inbox);+ List<Widget> needs({required bool first}) => [+ SwarmCaption('Needs you', count: inbox.needs.length, first: first),+ if (inbox.needs.isNotEmpty)+ SwarmGroup(children: _needs(context, session))+ else+ switch (empty) {+ _EmptyNeeds.reading => SwarmSkeletonRows(+ id: 'swarm-needs-loading',+ rows: 1,+ ),+ _EmptyNeeds.unread => _error(+ 'Could not load what is waiting for you. Try again.',+ key: 'swarm-needs-unread',+ top: 0,+ ),+ _EmptyNeeds.none => Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: SwarmRow.line(+ 'Nothing needs you.',+ key: const ValueKey('swarm-needs-none'),+ ),+ ),+ },+ ];+ // The person's Buddy chat in each project, there from the start (#2090);+ // a viewer, who starts no Buddy, sees only the chats they have.+ final buddies = [+ for (final swarm in inbox.swarms)+ if (inbox.reader(swarm.id) case final reader?)+ for (final project in reader.snapshot?.projects ?? const [])+ if (swarmBuddyChat(reader, project.id) != null ||+ swarmCanWrite(reader))+ SwarmRow(+ key: ValueKey('swarm-home-buddy-${swarm.id}-${project.id}'),+ leading: SwarmBuddyAvatar(+ reader: reader,+ projectId: project.id,+ ),+ title: swarmBuddyName(reader, project.id),+ news: switch (swarmBuddyChat(reader, project.id)) {+ final chat? => swarmChatNews(+ reader,+ inbox.asks(swarm.id),+ chat,+ ),+ null => swarmNoNews,+ },+ detail: SwarmRow.line(+ [+ project.name,+ if (several) swarm.name,+ swarmBuddyNote(reader, project.id) ??+ swarmBuddyEngineName(+ swarmBuddy(reader, project.id)!.engine,+ ),+ ].join(' · '),+ ),+ trailing: _buddyOpening == '${swarm.id}/${project.id}'+ ? SwarmRow.line('Opening…')+ : null,+ chevron: null,+ onTap: () => unawaited(_openBuddy(swarm.id, project.id)),+ ),+ ];+ // Swarms listed and still to be read: their rows are on their way.+ final reading = [+ for (final swarm in inbox.swarms)+ if (_unread(inbox.reader(swarm.id))) swarm.id,+ ];+ List<Widget> swarms({required bool first}) => [+ if (buddies.isNotEmpty || reading.isNotEmpty) ...[+ SwarmCaption('Buddies', first: first),+ if (buddies.isNotEmpty) SwarmGroup(children: buddies),+ for (final (i, id) in reading.indexed) ...[+ if (buddies.isNotEmpty || i > 0) const SizedBox(height: 8),+ SwarmSkeletonRows(id: 'swarm-buddy-loading-$id', round: true),+ ],+ ],+ if (_buddyError case final error?)+ _error(error, key: 'swarm-buddy-error', top: 8),+ for (final (i, swarm) in inbox.swarms.indexed) ...[+ SwarmCaption(+ several ? swarm.name : 'Projects',+ first: first && buddies.isEmpty && reading.isEmpty && i == 0,+ ),+ switch (inbox.reader(swarm.id)) {+ final SwarmReader reader when reader.snapshot != null => SwarmGroup(+ children: _projects(context, swarm.id, reader),+ ),+ SwarmReader(error: final error?) => SwarmGroup(+ children: [+ SwarmRow(+ title: error,+ detail: SwarmRow.line('Pull down to try again.'),+ onTap: null,+ ),+ ],+ ),+ _ => SwarmSkeletonRows(+ id: 'swarm-projects-loading-${swarm.id}',+ titleOnly: true,+ ),+ },+ ],+ if (inbox.swarms.isEmpty) ...[+ SwarmCaption('Your Swarms', first: first && buddies.isEmpty),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: SwarmRow.line(+ 'No Swarm yet. Start one on your computer.',+ lines: 2,+ ),+ ),+ ],+ ];+ final first = notice == null;+ return [+ ?notice,+ if (error != null) _error(error, key: 'swarm-error'),+ ...swarmNeedsFirst+ ? [...needs(first: first), ...swarms(first: false)]+ : [...swarms(first: first), ...needs(first: false)],+ ];+ }++ /// Home before the list answers: Needs you, Buddies and the projects+ /// as rows on their way, in the order Home shows them; under a card, its+ /// first caption not [first].+ List<Widget> _reading({bool first = true}) {+ List<Widget> needs({required bool first}) => [+ SwarmCaption('Needs you', first: first),+ SwarmSkeletonRows(id: 'swarm-needs-loading', rows: 1),+ ];+ List<Widget> swarms({required bool first}) => [+ SwarmCaption('Buddies', first: first),+ SwarmSkeletonRows(id: 'swarm-buddy-loading', round: true),+ const SwarmCaption('Projects'),+ SwarmSkeletonRows(id: 'swarm-projects-loading', titleOnly: true),+ ];+ return swarmNeedsFirst+ ? [...needs(first: first), ...swarms(first: false)]+ : [...swarms(first: first), ...needs(first: false)];+ }++ /// What went wrong, in the danger colour, up to three lines.+ Widget _error(String text, {required String key, double top = 6}) => Padding(+ padding: EdgeInsets.fromLTRB(AppSpace.xs, top, AppSpace.xs, 0),+ child: SwarmRow.line(+ text,+ key: ValueKey(key),+ lines: 3,+ color: AppColors.danger,+ ),+ );++ /// Every need, one open with its options or Done, the others a line each+ /// that opens it in its place. The one open is the person's pick while it+ /// waits, else the first: answered or done, the next one opens.+ List<Widget> _needs(BuildContext context, SwarmSession session) {+ final needs = session.inbox.needs;+ final open = needs.firstWhere(+ (need) => need.key == _focus,+ orElse: () => needs.first,+ );+ return [+ for (final need in needs)+ if (need == open)+ SwarmNeedRow(+ session: session,+ need: need,+ onOpen: (swarmId, conversationId) =>+ openSwarmConversation(context, swarmId, conversationId),+ )+ else+ SwarmNeedLine(+ key: ValueKey('swarm-need-row-${need.key}'),+ session: session,+ need: need,+ onTap: () => setState(() => _focus = need.key),+ ),+ ];+ }++ /// A Swarm's projects, each its tile and its name, no team line (Team at+ /// a glance is gone, as on the desktop): bold with something new in it,+ /// and its tags waiting as `@N` ([swarmProjectNews]).+ List<Widget> _projects(+ BuildContext context,+ String swarmId,+ SwarmReader reader,+ ) {+ final snapshot = reader.snapshot!;+ if (snapshot.projects.isEmpty) {+ return [const SwarmRow(title: 'No project yet', onTap: null)];+ }+ final news = swarmProjectNews(reader, _session?.inbox.asks(swarmId));+ return [+ for (final project in snapshot.projects)+ SwarmRow(+ key: ValueKey('swarm-project-$swarmId-${project.id}'),+ leading: SwarmProjectTile(project.name),+ title: project.name,+ news: news[project.id] ?? swarmNoNews,+ onTap: () => _openProject(context, swarmId, project.id),+ ),+ ];+ }+}++/// Home shows the Home kept, not read again yet: the list not read, or a+/// Swarm on it holding only what was kept. Not while no computer answers:+/// the card says so then ([SwarmConnectionNotice]).+bool _updating(SwarmInbox inbox) =>+ inbox.swarms.isNotEmpty &&+ !inbox.noComputer &&+ (!inbox.loaded ||+ inbox.swarms.any((swarm) => swarmHomeKept(inbox.reader(swarm.id))));++/// Why Needs you is empty.+enum _EmptyNeeds {+ /// A Swarm, or what waits on the person in it, is still being read.+ reading,++ /// Something could not be read: "nothing" is not known.+ unread,++ /// Everything was read, and nothing needs the person.+ none,+}++/// A Swarm listed and still to be read: no snapshot yet, and no reason it+/// could not be read.+bool _unread(SwarmReader? reader) =>+ reader == null || (reader.snapshot == null && reader.error == null);++/// Why [inbox]'s Needs you is empty: still reading while a Swarm, or what+/// waits on the person in it since it was last read in full, is not read yet.+_EmptyNeeds _emptyNeeds(SwarmInbox inbox) {+ var reading = false, unread = false;+ for (final swarm in inbox.swarms) {+ switch (inbox.reader(swarm.id)) {+ case SwarmReader(snapshot: _?):+ if (inbox.asks(swarm.id) case final asks?) {+ if (asks.loading) {+ reading = true;+ } else if (asks.error != null) {+ unread = true;+ }+ }+ case SwarmReader(error: _?):+ unread = true;+ case _:+ reading = true;+ }+ }+ if (reading) return _EmptyNeeds.reading;+ return unread ? _EmptyNeeds.unread : _EmptyNeeds.none;+}++/// No session: Swarm is off, or nobody is signed in on this phone.+class _Unavailable extends StatelessWidget {+ const _Unavailable();++ @override+ Widget build(BuildContext context) => ListView(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.s,+ AppSpace.screenInset,+ AppSpace.xl,+ ),+ children: [+ Text(+ 'Swarm is off on this phone, or you are signed out. '+ 'Turn it on in Settings ▸ Experimental.',+ key: const ValueKey('swarm-unavailable'),+ style: AppType.body(color: AppPalette.textSecondary, height: 1.45),+ ),+ ],+ );+}++/// Opens Home's drawer: the top bar's 44-point box, the drawer's mark.+class _MenuButton extends StatelessWidget {+ const _MenuButton();++ @override+ Widget build(BuildContext context) => SwarmIconButton(+ key: const ValueKey('swarm-menu'),+ icon: LucideIcons.menu300,+ size: 24,+ label: 'Menu',+ onPressed: () => Scaffold.of(context).openDrawer(),+ );}diff --git a/mobile/lib/swarm/swarm_pm_chat.dart b/mobile/lib/swarm/swarm_pm_chat.dartnew file mode 100644index 000000000..cfbfe92ad--- /dev/null+++ b/mobile/lib/swarm/swarm_pm_chat.dart@@ -0,0 +1,13 @@+import 'model.dart';++/// The name of [project]'s Product Manager: the agent leading its project+/// chat; null while it has none.+String? swarmPmName(SuperTabSnapshot snapshot, SuperTabProject project) {+ final leadId = swarmPmId(snapshot, project);+ return leadId == null ? null : snapshot.agentName(leadId);+}++/// The id of [project]'s Product Manager, for its avatar; null while it has+/// none.+String? swarmPmId(SuperTabSnapshot snapshot, SuperTabProject project) =>+ snapshot.conversation(project.leadConversationId)?.leadId;diff --git a/mobile/lib/swarm/swarm_profile.dart b/mobile/lib/swarm/swarm_profile.dartnew file mode 100644index 000000000..2a6c70d75--- /dev/null+++ b/mobile/lib/swarm/swarm_profile.dart@@ -0,0 +1,163 @@+import 'dart:typed_data';+import 'dart:ui' as ui;++import 'package:dio/dio.dart';++import 'package:harness_mobile/api/api_client.dart';++import 'model.dart';+import 'swarm_face.dart';+import 'swarm_reader.dart';+import 'swarm_request.dart';++/// What the backend takes as an avatar (superTabs/attachments.ts).+const kSwarmAvatarMaxBytes = 1024 * 1024;++/// The side of the square picture uploaded: sharp at every size it is shown.+const kSwarmAvatarPixels = 256;++/// Sends one avatar picture of the Swarm [tabId] and returns its upload's id+/// (`POST /api/super-tabs/:tabId/avatars`); a command then makes it someone's.+/// Straight to the backend with the phone's own sign-in: the computer a+/// Swarm call goes through carries text only.+typedef SwarmAvatarUpload = Future<String> Function({+ required String tabId,+ required Uint8List png,+});++/// [send] — `ApiClient.uploadSwarmAvatar` — as a [SwarmAvatarUpload] whose+/// failures read as the Swarm's do.+SwarmAvatarUpload swarmAvatarUploadVia(+ Future<String> Function(String tabId, Uint8List png) send,+) => ({required tabId, required png}) async {+ try {+ return await send(tabId, png);+ } on ApiException catch (refusal) {+ throw SuperTabFailure(+ 'AVATAR_REFUSED',+ refusal.message,+ statusCode: refusal.status ?? 0,+ );+ } on DioException catch (failure) {+ throw SuperTabFailure(+ 'AVATAR_NOT_SENT',+ 'The picture was not sent: ${describeApiError(failure)}',+ );+ }+};++/// The reader's own avatar and status in one Swarm, as the desktop sets them+/// (`desktop/lib/super_tabs/profile_actions.dart`). Each is its own command,+/// safe to send again; the answer is null when it went through, and the+/// Swarm is read at once, or else the sentence to show.+class SwarmProfile {+ SwarmProfile({required this.reader, this.upload});++ final SwarmReader reader;++ /// Null where this build cannot send a picture: only the built-in ones.+ final SwarmAvatarUpload? upload;++ bool get canUpload => upload != null;++ /// Only a member who may write changes how they show.+ bool get canEdit =>+ reader.snapshot?.person(reader.accountId)?.canWrite ?? false;++ Future<String?> setStatus(SuperTabPersonStatus? status) => _send({+ 'type': 'member.status',+ 'status': status == null+ ? null+ : {+ 'text': status.text,+ 'emoji': ?status.emoji,+ if (status.until case final until?)+ 'until': until.toUtc().toIso8601String(),+ },+ });++ /// [preset], or back to the initial when null.+ Future<String?> setAvatar(SuperTabPresetAvatar? preset) => _send({+ 'type': 'member.avatar',+ 'avatar': preset == null ? null : {'kind': 'preset', 'key': preset.key},+ });++ /// [picked] as its middle square at [kSwarmAvatarPixels], uploaded, then+ /// made the avatar.+ Future<String?> uploadAvatar(Uint8List picked) async {+ if (!canEdit) return _readOnly;+ final upload = this.upload;+ if (upload == null) {+ return 'Pictures can’t be sent from here. Pick one of the pictures '+ 'instead.';+ }+ try {+ final png = await swarmAvatarPng(picked);+ if (png.length > kSwarmAvatarMaxBytes) {+ return 'That picture is over 1 MB.';+ }+ final id = await upload(tabId: reader.tabId, png: png);+ return await _send({+ 'type': 'member.avatar',+ 'avatar': {'kind': 'upload', 'id': id},+ });+ } on SuperTabFailure catch (failure) {+ return failure.message;+ }+ }++ Future<String?> _send(Map<String, dynamic> command) async {+ if (!canEdit) return _readOnly;+ try {+ await reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ body: {'operationId': superTabOperationId(), 'command': command},+ );+ } on SuperTabFailure catch (failure) {+ return failure.message;+ }+ await reader.refresh();+ return null;+ }+}++const _readOnly = 'You have read-only access to this Swarm.';++/// [picked] cropped to its middle square and drawn at [kSwarmAvatarPixels],+/// as a PNG: what any picture a person picks becomes before it leaves the+/// phone, as on the desktop (`superTabAvatarPng`). A file that is not a+/// picture is refused.+Future<Uint8List> swarmAvatarPng(Uint8List picked) async {+ final ui.Image source;+ try {+ final codec = await ui.instantiateImageCodec(picked);+ source = (await codec.getNextFrame()).image;+ codec.dispose();+ } catch (_) {+ throw const SuperTabFailure(+ 'AVATAR_TYPE',+ 'Use a PNG, JPEG or WebP picture.',+ );+ }+ final side = source.width < source.height ? source.width : source.height;+ final crop = ui.Rect.fromLTWH(+ (source.width - side) / 2,+ (source.height - side) / 2,+ side.toDouble(),+ side.toDouble(),+ );+ const pixels = kSwarmAvatarPixels;+ final recorder = ui.PictureRecorder();+ ui.Canvas(recorder).drawImageRect(+ source,+ crop,+ const ui.Rect.fromLTWH(0, 0, pixels * 1.0, pixels * 1.0),+ ui.Paint()..filterQuality = ui.FilterQuality.high,+ );+ final drawn = await recorder.endRecording().toImage(pixels, pixels);+ source.dispose();+ final bytes = await drawn.toByteData(format: ui.ImageByteFormat.png);+ drawn.dispose();+ return bytes!.buffer.asUint8List();+}diff --git a/mobile/lib/swarm/swarm_profile_sheet.dart b/mobile/lib/swarm/swarm_profile_sheet.dartnew file mode 100644index 000000000..0cb5d3adc--- /dev/null+++ b/mobile/lib/swarm/swarm_profile_sheet.dart@@ -0,0 +1,778 @@+import 'dart:async';+import 'dart:io';++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:image_picker/image_picker.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/shared/theme/app_icon_size.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'identity.dart';+import 'model.dart';+import 'swarm_face.dart';+import 'swarm_profile.dart';+import 'swarm_reader.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';++/// One photo from the person's library, or null when they back out. Asked+/// no larger than an avatar needs, so a 12-megapixel photo is never decoded+/// whole on the phone.+Future<Uint8List?> pickSwarmPhoto() async {+ final picked = await ImagePicker().pickImage(+ source: ImageSource.gallery,+ maxWidth: 1024,+ maxHeight: 1024,+ );+ return readPickedSwarmPhoto(picked);+}++/// The bytes of a [picked] photo, or null when they backed out. The picker's+/// copy of it in the app's temporary folder is deleted as soon as it is read,+/// so a private photo does not stay on the phone.+Future<Uint8List?> readPickedSwarmPhoto(XFile? picked) async {+ if (picked == null) return null;+ try {+ return await picked.readAsBytes();+ } finally {+ try {+ await File(picked.path).delete();+ } on FileSystemException {+ // Already gone: nothing is left to delete.+ }+ }+}++/// The person's own profile in the Swarm [swarmId], in a sheet over the+/// page: a built-in picture or a photo of theirs, and a status that clears+/// when they say — the desktop's profile (`profile_sheet.dart`) in the+/// phone's own way.+Future<void> showSwarmProfile(+ BuildContext context, {+ required String swarmId,+ Future<Uint8List?> Function() pickPhoto = pickSwarmPhoto,+}) => showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: AppGlass.rowFill,+ shape: AppControl.sheetShape,+ // On the page's own navigator, under the shell's [SwarmScope].+ builder: (_) => SwarmProfileSheet(swarmId: swarmId, pickPhoto: pickPhoto),+);++/// When a status clears itself.+enum _Clears {+ never('Never'),+ hour('1 hour'),+ four('4 hours'),+ today('Today');++ const _Clears(this.label);+ final String label;++ DateTime? from(DateTime now) => switch (this) {+ never => null,+ hour => now.add(const Duration(hours: 1)),+ four => now.add(const Duration(hours: 4)),+ today => () {+ final local = now.toLocal();+ return DateTime(local.year, local.month, local.day + 1);+ }(),+ };+}++/// What [showSwarmProfile] shows.+class SwarmProfileSheet extends StatefulWidget {+ const SwarmProfileSheet({+ super.key,+ required this.swarmId,+ this.pickPhoto = pickSwarmPhoto,+ });++ final String swarmId;+ final Future<Uint8List?> Function() pickPhoto;++ @override+ State<SwarmProfileSheet> createState() => _SwarmProfileSheetState();+}++class _SwarmProfileSheetState extends State<SwarmProfileSheet> {+ final _text = TextEditingController();+ String? _emoji;++ /// When the status clears; null keeps the end it has ([_keptUntil]).+ _Clears? _clears = _Clears.never;+ DateTime? _keptUntil;++ /// The editor took the person's status once, when it was first read.+ bool _seeded = false;+ bool _busy = false;+ String? _error;++ @override+ void dispose() {+ _text.dispose();+ super.dispose();+ }++ Future<void> _run(Future<String?> Function() action) async {+ setState(() {+ _busy = true;+ _error = null;+ });+ final error = await action();+ if (!mounted) return;+ setState(() {+ _busy = false;+ _error = error;+ });+ }++ Future<void> _photo(SwarmProfile profile) async {+ final Uint8List? picked;+ try {+ picked = await widget.pickPhoto();+ } on PlatformException {+ if (mounted) setState(() => _error = 'Could not open your photos.');+ return;+ }+ // Null is the person backing out, not a failure.+ if (picked == null || !mounted) return;+ await _run(() => profile.uploadAvatar(picked!));+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final inbox = SwarmScope.of(context)?.inbox;+ final upload = SwarmScope.uploadAvatarOf(context);+ return ConstrainedBox(+ constraints: BoxConstraints(+ maxHeight: MediaQuery.sizeOf(context).height * .9,+ ),+ child: SafeArea(+ top: false,+ child: Padding(+ // Above the keyboard while the status is typed.+ padding: EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.s,+ AppSpace.l,+ AppSpace.l + MediaQuery.viewInsetsOf(context).bottom,+ ),+ child: inbox == null+ ? const SizedBox.shrink()+ : ListenableBuilder(+ listenable: inbox,+ builder: (context, _) =>+ switch (inbox.reader(widget.swarmId)) {+ final reader? => ListenableBuilder(+ listenable: reader,+ builder: (context, _) =>+ _sheet(context, reader, upload),+ ),+ null => _sheet(context, null, null),+ },+ ),+ ),+ ),+ );+ }++ Widget _sheet(+ BuildContext context,+ SwarmReader? reader,+ SwarmAvatarUpload? upload,+ ) {+ final me = reader?.snapshot?.person(reader.accountId);+ final profile = reader == null+ ? null+ : SwarmProfile(reader: reader, upload: upload);+ final now = clock.now();+ final status = me?.statusAt(now);+ if (me != null && !_seeded) {+ _seeded = true;+ _text.text = status?.text ?? '';+ _emoji = status?.emoji;+ if (status?.until case final until?) {+ _keptUntil = until;+ _clears = null;+ }+ }+ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // The grabber: a capsule as wide as the two largest steps.+ Center(+ child: Container(+ width: AppSpace.xl + AppSpace.m,+ height: AppSpace.xs,+ margin: const EdgeInsets.only(bottom: AppSpace.s),+ decoration: ShapeDecoration(+ color: AppGlass.hair,+ shape: const StadiumBorder(),+ ),+ ),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ 0,+ AppSpace.xs,+ AppSpace.s,+ ),+ child: Row(+ children: [+ Expanded(+ child: Text(+ 'Your profile',+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ ),+ SwarmIconButton(+ key: const ValueKey('swarm-profile-close'),+ icon: LucideIcons.x300,+ label: 'Close',+ onPressed: () => Navigator.of(context).pop(),+ ),+ ],+ ),+ ),+ Flexible(+ child: me == null || profile == null+ // Not read yet: rows on their way.+ ? SwarmSkeletonRows(id: 'swarm-profile-loading', round: true)+ : SingleChildScrollView(child: _body(me, status, profile)),+ ),+ ],+ );+ }++ Widget _body(+ SuperTabPerson me,+ SuperTabPersonStatus? status,+ SwarmProfile profile,+ ) {+ final name = superTabPersonName(me.email);+ final edit = profile.canEdit && !_busy;+ final current = me.avatar;+ final text = _text.text.trim();+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ AppSpace.s,+ AppSpace.xs,+ AppSpace.xs,+ ),+ child: Row(+ children: [+ SwarmAvatar(+ key: const ValueKey('swarm-profile-face'),+ id: me.id,+ name: name,+ size: 64,+ picture: current,+ status: status,+ ),+ const SizedBox(width: 14),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ const SizedBox(height: 2),+ Text(+ status?.label ?? 'No status',+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ if (!profile.canEdit) _Note('You have read-only access to this Swarm.'),+ const SwarmCaption('Picture'),+ Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ for (final MapEntry(:key, :value) in superTabAvatarPresets.entries)+ _Picture(+ key: ValueKey('swarm-avatar-preset-$key'),+ glyph: value,+ label: key,+ selected: current is SuperTabPresetAvatar && current.key == key,+ onTap: edit+ ? () => _run(+ () => profile.setAvatar(SuperTabPresetAvatar(key)),+ )+ : null,+ ),+ ],+ ),+ const SizedBox(height: 12),+ Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ if (profile.canUpload)+ SwarmButton(+ key: const ValueKey('swarm-avatar-photo'),+ icon: LucideIcons.image300,+ label: 'Choose photo',+ busy: _busy,+ busyLabel: 'Saving…',+ onPressed: edit ? () => unawaited(_photo(profile)) : null,+ ),+ if (current != null)+ SwarmButton(+ key: const ValueKey('swarm-avatar-default'),+ label: 'Use initials',+ style: SwarmButtonStyle.link,+ onPressed: edit+ ? () => _run(() => profile.setAvatar(null))+ : null,+ ),+ ],+ ),+ if (!profile.canUpload)+ _Note('Photos can’t be sent from this phone yet. Pick a picture.'),+ const SwarmCaption('Status'),+ Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ for (final (emoji, words) in superTabStatusPresets)+ _Chip(+ key: ValueKey('swarm-status-$emoji'),+ label: '$emoji $words',+ selected: _emoji == emoji && text == words,+ onTap: edit+ ? () => setState(() {+ _emoji = emoji;+ _text.text = words;+ })+ : null,+ ),+ ],+ ),+ const SizedBox(height: 12),+ TextField(+ key: const ValueKey('swarm-status-text'),+ controller: _text,+ enabled: edit,+ maxLength: 80,+ textCapitalization: TextCapitalization.sentences,+ style: AppType.body(color: AppPalette.textPrimary),+ decoration: InputDecoration(+ hintText: 'What are you up to?',+ hintStyle: TextStyle(color: AppPalette.textFaint),+ filled: true,+ fillColor: AppPalette.swarmField,+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(AppControl.radius),+ borderSide: BorderSide.none,+ ),+ ),+ onChanged: (_) => setState(() {+ // An emoji goes with its own words only.+ if (!superTabStatusPresets.any(+ (p) => p.$1 == _emoji && p.$2 == _text.text.trim(),+ )) {+ _emoji = null;+ }+ }),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ AppSpace.xs,+ AppSpace.xs,+ AppSpace.s,+ ),+ child: Text(+ 'Clears',+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ),+ Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ if (_keptUntil case final until?)+ _Chip(+ key: const ValueKey('swarm-status-clears-kept'),+ label: 'At ${SwarmPersonSheet._time(context, until)}',+ selected: _clears == null,+ onTap: edit ? () => setState(() => _clears = null) : null,+ ),+ for (final clears in _Clears.values)+ _Chip(+ key: ValueKey('swarm-status-clears-${clears.name}'),+ label: clears.label,+ selected: _clears == clears,+ onTap: edit ? () => setState(() => _clears = clears) : null,+ ),+ ],+ ),+ const SizedBox(height: 16),+ SwarmButton(+ key: const ValueKey('swarm-status-save'),+ label: 'Save status',+ style: SwarmButtonStyle.fill,+ wide: true,+ onPressed: edit && text.isNotEmpty+ ? () => _run(+ () => profile.setStatus(+ SuperTabPersonStatus(+ text: text,+ emoji: _emoji,+ until: switch (_clears) {+ final clears? => clears.from(clock.now()),+ null => _keptUntil,+ },+ ),+ ),+ )+ : null,+ ),+ if (status != null) ...[+ const SizedBox(height: 4),+ Center(+ child: SwarmButton(+ key: const ValueKey('swarm-status-clear'),+ label: 'Clear status',+ style: SwarmButtonStyle.link,+ onPressed: edit+ ? () => _run(() async {+ final error = await profile.setStatus(null);+ if (error == null && mounted) {+ _text.clear();+ _emoji = null;+ _keptUntil = null;+ _clears = _Clears.never;+ }+ return error;+ })+ : null,+ ),+ ),+ ],+ if (_error case final error?)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ AppSpace.m,+ AppSpace.xs,+ 0,+ ),+ child: Text(+ error,+ key: const ValueKey('swarm-profile-error'),+ style: AppType.caption(color: AppColors.danger),+ ),+ ),+ ],+ );+ }+}++/// A quiet line under a section.+class _Note extends StatelessWidget {+ const _Note(this.text);+ final String text;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.fromLTRB(AppSpace.xs, AppSpace.m, AppSpace.xs, 0),+ child: Text(text, style: AppType.caption(color: AppPalette.textSecondary)),+ );+}++/// One built-in picture to wear: a 52-point round button, ringed when worn.+class _Picture extends StatelessWidget {+ const _Picture({+ super.key,+ required this.glyph,+ required this.label,+ required this.selected,+ required this.onTap,+ });++ final String glyph, label;+ final bool selected;+ final VoidCallback? onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ selected: selected,+ label: label,+ excludeSemantics: true,+ child: Material(+ color: AppPalette.swarmField,+ shape: CircleBorder(+ side: BorderSide(+ color: selected ? AppPalette.swarmAccent : AppGlass.hair,+ width: selected ? 2 : 1,+ ),+ ),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: onTap == null+ ? null+ : () {+ unawaited(HapticFeedback.selectionClick());+ onTap!();+ },+ child: SizedBox.square(+ dimension: 52,+ child: Center(+ child: Text(+ glyph,+ textScaler: TextScaler.noScaling,+ style: const TextStyle(+ fontSize: AppIconSize.standalone,+ height: 1,+ ),+ ),+ ),+ ),+ ),+ ),+ );+}++/// A choice in words, 44 points tall, filled when chosen.+class _Chip extends StatelessWidget {+ const _Chip({+ super.key,+ required this.label,+ required this.selected,+ required this.onTap,+ });++ final String label;+ final bool selected;+ final VoidCallback? onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ selected: selected,+ child: Material(+ color: selected+ ? AppPalette.swarmAccent.withValues(alpha: .18)+ : AppPalette.swarmField,+ shape: StadiumBorder(+ side: BorderSide(+ color: selected ? AppPalette.swarmAccent : AppGlass.hair,+ ),+ ),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 44),+ child: Padding(+ padding: AppControl.padding,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ label,+ style: AppType.caption(color: AppPalette.textPrimary),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+}++/// Who the member [personId] of the Swarm [swarmId] is, in a sheet over the+/// page: their face, name, email, role and status while it lasts. One's own+/// has Edit profile, which opens [showSwarmProfile].+Future<void> showSwarmPerson(+ BuildContext context, {+ required String swarmId,+ required String personId,+}) => showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: AppGlass.rowFill,+ shape: AppControl.sheetShape,+ builder: (sheet) => SwarmPersonSheet(+ swarmId: swarmId,+ personId: personId,+ onEdit: () {+ Navigator.of(sheet).pop();+ unawaited(showSwarmProfile(context, swarmId: swarmId));+ },+ ),+);++/// What [showSwarmPerson] shows.+class SwarmPersonSheet extends StatelessWidget {+ const SwarmPersonSheet({+ super.key,+ required this.swarmId,+ required this.personId,+ required this.onEdit,+ });++ final String swarmId, personId;+ final VoidCallback onEdit;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final reader = SwarmScope.of(context)?.inbox.reader(swarmId);+ return SafeArea(+ top: false,+ child: Padding(+ key: const ValueKey('swarm-person'),+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.s,+ AppSpace.l,+ AppSpace.xl,+ ),+ child: reader == null+ ? const SizedBox.shrink()+ : ListenableBuilder(+ listenable: reader,+ builder: (context, _) => _sheet(context, reader),+ ),+ ),+ );+ }++ Widget _sheet(BuildContext context, SwarmReader reader) {+ final person = reader.snapshot?.person(personId);+ final mine = personId == reader.accountId;+ final name = person == null ? 'Someone' : superTabPersonName(person.email);+ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // The grabber: a capsule as wide as the two largest steps.+ Center(+ child: Container(+ width: AppSpace.xl + AppSpace.m,+ height: AppSpace.xs,+ margin: const EdgeInsets.only(bottom: AppSpace.l),+ decoration: ShapeDecoration(+ color: AppGlass.hair,+ shape: const StadiumBorder(),+ ),+ ),+ ),+ if (person == null)+ _Note('They are no longer in this Swarm.')+ else+ SwarmUntil(+ until: person.status?.until,+ builder: (context) {+ final status = person.statusAt(clock.now());+ return Row(+ children: [+ SwarmAvatar(+ id: person.id,+ name: name,+ size: 64,+ picture: person.avatar,+ status: status,+ ),+ const SizedBox(width: 14),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ if (status != null) ...[+ const SizedBox(height: 2),+ Text(+ status.label,+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ if (status.until case final until?)+ Text(+ 'Clears at ${_time(context, until)}',+ style: AppType.caption(+ color: AppPalette.textFaint,+ ),+ ),+ ],+ const SizedBox(height: 4),+ Text(+ person.email,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ ),+ ),+ Text(+ _role(person.role),+ style: AppType.caption(color: AppPalette.textFaint),+ ),+ ],+ ),+ ),+ ],+ );+ },+ ),+ if (mine && person != null && person.canWrite) ...[+ const SizedBox(height: 18),+ SwarmButton(+ key: const ValueKey('swarm-person-edit'),+ label: 'Edit profile',+ style: SwarmButtonStyle.fill,+ wide: true,+ onPressed: onEdit,+ ),+ ],+ ],+ );+ }++ static String _role(String role) => switch (role) {+ 'owner' => 'Owner',+ 'collaborator' => 'Collaborator',+ 'viewer' => 'Viewer',+ _ => role,+ };++ static String _time(BuildContext context, DateTime at) =>+ MaterialLocalizations.of(context).formatTimeOfDay(+ TimeOfDay.fromDateTime(at.toLocal()),+ alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context),+ );+}diff --git a/mobile/lib/swarm/swarm_project_page.dart b/mobile/lib/swarm/swarm_project_page.dartnew file mode 100644index 000000000..ecba2f716--- /dev/null+++ b/mobile/lib/swarm/swarm_project_page.dart@@ -0,0 +1,1518 @@+import 'dart:async';++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/shared/theme/app_icon_size.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/shared/widgets/skeleton.dart';+import 'package:harness_mobile/shared/widgets/touch_target.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'model.dart';+import 'swarm_buddy.dart';+import 'swarm_buddy_chat.dart';+import 'swarm_conversation_page.dart';+import 'swarm_home_keeper.dart';+import 'swarm_inbox.dart';+import 'swarm_message_row.dart';+import 'swarm_pm_chat.dart';+import 'swarm_reader.dart';+import 'swarm_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';+import 'swarm_task_status.dart';+import 'team_glance.dart';++/// The conversations of one project the person may read, as its sheet lists+/// them: its work by latest activity, and the quiet or archived work behind+/// "Older". The project chat is the screen, so it is not here, and neither is+/// a Buddy chat ([buddies]), which has its own row. Nor is any other private+/// chat: Buddies replaced Chat with PM (#2090), so the old history an older+/// server still sends is hidden, as on the desktop (`hiddenByBuddies`).+({List<SuperTabConversation> active, List<SuperTabConversation> older})+swarmProjectWork(+ SuperTabSnapshot snapshot,+ SuperTabProject project, {+ SwarmBuddies buddies = SwarmBuddies.none,+}) {+ final work =+ snapshot.conversations+ .where(+ (g) =>+ g.projectId == project.id &&+ g.id != project.leadConversationId &&+ g.audience == null &&+ !buddies.chatOwners.containsKey(g.id),+ )+ .toList()+ ..sort(+ (a, b) => b.lastMessageSequence.compareTo(a.lastMessageSequence),+ );+ return (+ active: [+ for (final g in work)+ if (!g.closed) g,+ ],+ older: [+ for (final g in work)+ if (g.closed) g,+ ],+ );+}++/// The conversations of [swarmId] whose work waits on the person: those of+/// its Needs you ([SwarmInbox.needs]), so one rule says what waits.+Set<String> swarmWaitingOnYou(SwarmInbox inbox, String swarmId) => {+ for (final need in inbox.needs)+ if (need is SwarmWorkNeed && need.swarmId == swarmId) need.conversationId,+};++/// One project, as prototype B draws it (Tony, 2026-10-28): its project chat+/// (its Product Manager and everyone) is the screen, under the project's name+/// and who is in it, with nothing under the header; and at the header's end a+/// ⋮ menu (Tony, 2026-10-29) with Buddy chat and the team's status in words+/// ([SwarmProjectStatus]), which opens the project's work and team in a sheet+/// ([showSwarmProjectSheet]).+class SwarmProjectPage extends StatefulWidget {+ const SwarmProjectPage({+ super.key,+ required this.swarmId,+ required this.projectId,+ this.mention,+ });++ final String swarmId, projectId;++ /// An agent to @mention in the chat's draft as it opens+ /// ([SwarmConversationPage.mention]).+ final String? mention;++ @override+ State<SwarmProjectPage> createState() => _SwarmProjectPageState();+}++class _SwarmProjectPageState extends State<SwarmProjectPage> {+ SwarmSession? _session;++ /// The person's Buddy chat: being opened, and why the last one did not+ /// open. The menu's button and the line under the header listen; the chat+ /// is not built again for them.+ final _buddy = ValueNotifier<({bool opening, String? error})>((+ opening: false,+ error: null,+ ));++ /// What the page shows of the inbox ([_inboxChanged]): its Swarm's+ /// reader, whether there are several Swarms, why the list was not read.+ SwarmReader? _reader;+ bool _several = false;+ String? _listError;++ /// A read of the Swarm since the page opened has finished ([_readOnOpen]).+ /// Until then, a project the Swarm did not have may be one just made.+ bool _read = false;++ /// The project chat as last built, with what it was built from: a read+ /// that moved none of it builds none of it again ([_chatOf]).+ ({Object inputs, Widget chat})? _chat;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final session = SwarmScope.of(context);+ if (session == _session) return;+ _session?.inbox.removeListener(_inboxChanged);+ _session?.leave();+ _session = session?..enter();+ session?.inbox.addListener(_inboxChanged);+ _seeInbox();+ _readOnOpen();+ }++ @override+ void dispose() {+ _session?.inbox.removeListener(_inboxChanged);+ _session?.leave();+ _buddy.dispose();+ super.dispose();+ }++ /// The inbox tells of every change of every Swarm, and again when what+ /// waits on the person is read after one; the page is built again only+ /// when what it shows of the inbox moved. Its Swarm's own changes come+ /// from its reader.+ void _inboxChanged() {+ final inbox = _session?.inbox;+ if (inbox == null) return;+ final seen = (+ inbox.reader(widget.swarmId),+ inbox.swarms.length > 1,+ inbox.error,+ );+ if (seen != (_reader, _several, _listError)) setState(_seeInbox);+ }++ void _seeInbox() {+ final inbox = _session?.inbox;+ _reader = inbox?.reader(widget.swarmId);+ _several = (inbox?.swarms.length ?? 0) > 1;+ _listError = inbox?.error;+ }++ /// Reads the Swarm as the page opens: what Home read may be 15 seconds+ /// old, or from before the project was made. Not listed yet, the list is+ /// read with it.+ void _readOnOpen() {+ final session = _session;+ _read = false;+ if (session == null) return;+ final read = _reader?.refresh() ?? session.inbox.refresh();+ unawaited(+ read.whenComplete(() {+ if (mounted && _session == session) setState(() => _read = true);+ }),+ );+ }++ /// A pull: one read of the Swarm, joining one under way.+ Future<void> _pull() =>+ _reader?.refresh() ?? _session?.inbox.refresh() ?? Future.value();++ Future<void> _openBuddy() async {+ final reader = _reader;+ if (reader == null || _buddy.value.opening) return;+ _buddy.value = (opening: true, error: null);+ final error = await openSwarmBuddy(+ context,+ reader,+ widget.swarmId,+ widget.projectId,+ );+ if (!mounted) return;+ _buddy.value = (opening: false, error: error);+ }++ void _openSheet() => unawaited(+ showSwarmProjectSheet(+ context,+ swarmId: widget.swarmId,+ projectId: widget.projectId,+ ),+ );++ /// The header's menu ([showSwarmProjectMenu]), then what was picked in it.+ /// A viewer with no Buddy chat here has none to open, and starts none.+ Future<void> _openMenu() async {+ final reader = _reader;+ if (reader == null || _buddy.value.opening) return;+ final picked = await showSwarmProjectMenu(+ context,+ swarmId: widget.swarmId,+ projectId: widget.projectId,+ buddyChat:+ swarmBuddyChat(reader, widget.projectId) != null ||+ swarmCanWrite(reader),+ );+ if (!mounted) return;+ switch (picked) {+ case SwarmProjectMenuItem.buddyChat:+ await _openBuddy();+ case SwarmProjectMenuItem.status:+ _openSheet();+ case null:+ break;+ }+ }++ /// [project]'s chat as the screen: its name over who is in it — and, with+ /// several Swarms, which one — and its menu at the header's end.+ Widget _chatOf(SuperTabSnapshot snapshot, SuperTabProject project) {+ final who = switch (swarmPmName(snapshot, project)) {+ final name? => '$name and everyone',+ null => 'Everyone in the project',+ };+ final inputs = (+ project.leadConversationId,+ project.name,+ _several ? '$who · ${snapshot.name}' : who,+ );+ if (_chat case final kept? when kept.inputs == inputs) return kept.chat;+ final chat = SwarmConversationPage(+ key: ValueKey('swarm-project-chat-${project.leadConversationId}'),+ swarmId: widget.swarmId,+ conversationId: project.leadConversationId,+ title: inputs.$2,+ subtitle: inputs.$3,+ mention: widget.mention,+ action: ValueListenableBuilder(+ valueListenable: _buddy,+ builder: (context, buddy, _) => _MenuButton(+ opening: buddy.opening,+ onPressed: () => unawaited(_openMenu()),+ ),+ ),+ // Nothing else under the header (Tony, 2026-10-29): the team's status+ // is in the menu.+ below: ValueListenableBuilder(+ valueListenable: _buddy,+ builder: (context, buddy, _) => switch (buddy.error) {+ final error? => Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.screenInset,+ vertical: AppSpace.s,+ ),+ child: SwarmRow.line(+ error,+ key: const ValueKey('swarm-buddy-error'),+ lines: 3,+ color: AppColors.danger,+ ),+ ),+ null => const SizedBox.shrink(),+ },+ ),+ );+ _chat = (inputs: inputs, chat: chat);+ return chat;+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final session = _session;+ final reader = _reader;+ final back = SwarmBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ );+ if (session == null) {+ return _Frame(+ top: SwarmTopBar(leading: back, title: ''),+ );+ }+ return ListenableBuilder(+ // Not listed yet: the inbox tells when it is ([_inboxChanged]).+ listenable: reader ?? Listenable.merge(const []),+ builder: (context, _) {+ final snapshot = reader?.snapshot;+ final project = snapshot?.projects+ .where((p) => p.id == widget.projectId)+ .firstOrNull;+ if (snapshot != null && project != null) {+ return _chatOf(snapshot, project);+ }+ // Why there is no project to show: still reading, or a read that+ // failed or finished without it.+ final why = switch (reader) {+ null => _listError ?? (_read ? _gone : null),+ // Taken away: nothing of it stays, and none is read.+ SwarmReader(accessRevoked: true) => reader.error ?? _gone,+ SwarmReader(snapshot: null) => reader.error,+ _ => _read ? reader.error ?? _gone : null,+ };+ if (why == null) {+ return _Frame(+ top: _LoadingTopBar(leading: back),+ body: const _Loading(),+ );+ }+ return _Frame(+ top: SwarmTopBar(leading: back, title: ''),+ body: RefreshIndicator(+ onRefresh: _pull,+ child: ListView(+ physics: const AlwaysScrollableScrollPhysics(),+ padding: const EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.s,+ AppSpace.screenInset,+ 0,+ ),+ children: [SwarmRow.line(why, lines: 3)],+ ),+ ),+ );+ },+ );+ }++ static const _gone = 'This project is no longer in the Swarm.';+}++/// The page before its project chat is: its [top] bar, and [body] under it.+class _Frame extends StatelessWidget {+ const _Frame({required this.top, this.body});++ final Widget top;+ final Widget? body;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Scaffold(+ backgroundColor: AppPalette.windowBg,+ body: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ top,+ if (body case final body?) Expanded(child: body),+ ],+ ),+ ),+ );+ }+}++/// The header's ⋮: 44 points square, its glyph's end on the screen's side+/// margin, as the header's words are. While Buddy chat opens ([opening]), a+/// spinner in its place, and taps do nothing.+class _MenuButton extends StatelessWidget {+ const _MenuButton({required this.opening, required this.onPressed});++ final bool opening;+ final VoidCallback onPressed;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final ink = AppPalette.textPrimary;+ return Semantics(+ key: const ValueKey('swarm-project-menu'),+ button: true,+ enabled: !opening,+ label: opening ? 'Opening Buddy chat…' : 'Project menu',+ excludeSemantics: true,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: opening+ ? null+ : () {+ HapticFeedback.selectionClick();+ onPressed();+ },+ child: SizedBox.square(+ dimension: minTouchTarget,+ child: Align(+ alignment: AlignmentDirectional.centerEnd,+ child: opening+ ? SizedBox.square(+ dimension: 18,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ color: ink,+ backgroundColor: ink.withValues(alpha: .35),+ ),+ )+ : Icon(LucideIcons.ellipsisVertical300, size: 22, color: ink),+ ),+ ),+ ),+ );+ }+}++/// What the project's menu ([showSwarmProjectMenu]) was closed with.+enum SwarmProjectMenuItem { buddyChat, status }++/// The project's ⋮ menu, as Tony asked for it (2026-10-29): Buddy chat, where+/// Chat with PM was (#2090) — none for a viewer without one ([buddyChat]) —+/// then the team's status in words+/// ([SwarmProjectStatus]), which opens the project's work and team. Its rows+/// are a thumb's height at least, on the sheet the composer's + opens.+/// Answers the row picked, or null when the person closes it.+Future<SwarmProjectMenuItem?> showSwarmProjectMenu(+ BuildContext context, {+ required String swarmId,+ required String projectId,+ required bool buddyChat,+}) => showModalBottomSheet<SwarmProjectMenuItem>(+ context: context,+ backgroundColor: AppGlass.rowFill,+ shape: AppControl.sheetShape,+ builder: (_) => _ProjectMenu(+ swarmId: swarmId,+ projectId: projectId,+ buddyChat: buddyChat,+ ),+);++class _ProjectMenu extends StatelessWidget {+ const _ProjectMenu({+ required this.swarmId,+ required this.projectId,+ required this.buddyChat,+ });++ final String swarmId, projectId;+ final bool buddyChat;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ void pick(SwarmProjectMenuItem item) => Navigator.of(context).pop(item);+ return SafeArea(+ top: false,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.s,+ AppSpace.l,+ AppSpace.l,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // The grabber: a capsule as wide as the two largest steps.+ Center(+ child: Container(+ width: AppSpace.xl + AppSpace.m,+ height: AppSpace.xs,+ margin: const EdgeInsets.only(bottom: AppSpace.s),+ decoration: ShapeDecoration(+ color: AppGlass.hair,+ shape: const StadiumBorder(),+ ),+ ),+ ),+ if (buddyChat)+ _MenuRow(+ key: const ValueKey('swarm-project-menu-buddy-chat'),+ onTap: () => pick(SwarmProjectMenuItem.buddyChat),+ child: Text(+ 'Buddy chat',+ style: AppType.body(color: AppPalette.textPrimary),+ ),+ ),+ SwarmProjectStatus(+ swarmId: swarmId,+ projectId: projectId,+ onTap: () => pick(SwarmProjectMenuItem.status),+ ),+ ],+ ),+ ),+ );+ }+}++/// One row of the project's menu: its words, then maybe a mark at its end,+/// at least [minTouchTarget] tall.+class _MenuRow extends StatelessWidget {+ const _MenuRow({+ super.key,+ required this.onTap,+ required this.child,+ this.trailing,+ });++ final VoidCallback onTap;+ final Widget child;+ final Widget? trailing;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Semantics(+ button: true,+ child: InkWell(+ borderRadius: BorderRadius.circular(AppControl.radius),+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: minTouchTarget),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.m,+ vertical: AppSpace.s,+ ),+ child: Row(+ children: [+ Expanded(child: child),+ if (trailing case final trailing?) ...[+ const SizedBox(width: AppSpace.s),+ trailing,+ ],+ ],+ ),+ ),+ ),+ ),+ );+ }+}++/// The team of a project in its menu: its status in words+/// ([SwarmStatusText]) and a chevron, opening the project's work and team+/// ([onTap]). Counted from the Home kept, it reads "Updating…" until its+/// Swarm is read again ([swarmHomeKept]), and nothing waits yet.+///+/// It follows its Swarm and the inbox itself while the menu is open, and is+/// built again only when what it shows moved.+class SwarmProjectStatus extends StatefulWidget {+ const SwarmProjectStatus({+ super.key,+ required this.swarmId,+ required this.projectId,+ required this.onTap,+ });++ final String swarmId, projectId;+ final VoidCallback onTap;++ @override+ State<SwarmProjectStatus> createState() => _SwarmProjectStatusState();+}++/// What [SwarmProjectStatus] shows: its team, how much work waits on the+/// person, and whether it is counted from the Home kept.+typedef _Status = ({SwarmTeamGlance glance, int waiting, bool kept});++class _SwarmProjectStatusState extends State<SwarmProjectStatus> {+ SwarmSession? _session;+ SwarmReader? _reader;+ _Status? _status;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final session = SwarmScope.of(context);+ if (session == _session) return;+ _session?.inbox.removeListener(_changed);+ _session = session?..inbox.addListener(_changed);+ _follow();+ _status = _see();+ }++ @override+ void dispose() {+ _session?.inbox.removeListener(_changed);+ _reader?.removeListener(_changed);+ super.dispose();+ }++ /// Listens to the Swarm's reader the inbox has now.+ void _follow() {+ final reader = _session?.inbox.reader(widget.swarmId);+ if (reader == _reader) return;+ _reader?.removeListener(_changed);+ _reader = reader?..addListener(_changed);+ }++ void _changed() {+ _follow();+ final status = _see();+ if (status != _status) setState(() => _status = status);+ }++ _Status? _see() {+ final session = _session, reader = _reader;+ final snapshot = reader?.snapshot;+ final project = snapshot?.projects+ .where((p) => p.id == widget.projectId)+ .firstOrNull;+ if (session == null || snapshot == null || project == null) return null;+ final kept = swarmHomeKept(reader);+ final waits = swarmWaitingOnYou(session.inbox, widget.swarmId);+ final work = swarmProjectWork(snapshot, project, buddies: reader!.buddies);+ return (+ glance: swarmTeamGlance(snapshot, projectId: project.id),+ // What was kept is not now, what waits on the person least of all.+ waiting: kept ? 0 : work.active.where((g) => waits.contains(g.id)).length,+ kept: kept,+ );+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final status = _status;+ return _MenuRow(+ key: const ValueKey('swarm-project-menu-status'),+ onTap: widget.onTap,+ trailing: Icon(+ LucideIcons.chevronRight300,+ size: AppIconSize.besideText,+ color: AppPalette.textFaint,+ ),+ child: status == null+ ? Text(+ 'Updating…',+ style: AppType.body(color: AppPalette.textSecondary),+ )+ : SwarmStatusText(+ status.glance,+ waiting: status.waiting,+ kept: status.kept,+ ),+ );+ }+}++/// A project's team in words, as its menu says it (Tony, 2026-10-29): "17+/// working · 3 down", no faces — or, while work waits on the person+/// ([waiting]), how much does, in the warning colour, with only who is down+/// of the team. Who is down is red. Counted from the Home kept ([kept]), it+/// reads "Updating…".+class SwarmStatusText extends StatelessWidget {+ const SwarmStatusText(+ this.glance, {+ super.key,+ this.waiting = 0,+ this.kept = false,+ });++ final SwarmTeamGlance glance;+ final int waiting;+ final bool kept;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final down = swarmStateColor(SwarmAgentState.down);+ final List<({String text, Color? color})> parts = kept+ ? const []+ : waiting > 0+ ? [+ (text: '$waiting waiting on you', color: AppColors.warning),+ if (glance.down > 0) (text: '${glance.down} down', color: down),+ ]+ : [+ for (final part in glance.parts)+ (+ text: part.text,+ color: part.state == SwarmAgentState.down ? down : null,+ ),+ ];+ if (parts.isEmpty) {+ return Text(+ kept ? 'Updating…' : glance.line,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.body(+ color: kept ? AppPalette.textSecondary : AppPalette.textPrimary,+ ),+ );+ }+ return Text.rich(+ TextSpan(+ children: [+ for (final (i, part) in parts.indexed) ...[+ if (i > 0) const TextSpan(text: ' · '),+ TextSpan(+ text: part.text,+ style: part.color == null ? null : TextStyle(color: part.color),+ ),+ ],+ ],+ ),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppType.body(color: AppPalette.textPrimary),+ );+ }+}++/// The project's work and team in a sheet over its chat: its work — what+/// waits on the person, then what the team is working on, by latest activity,+/// and older work folded under "Older", read from the Swarm's closed work+/// when opened, as no first load has it ([SwarmReader.loadDormant]) — or its+/// team: each agent with its avatar, its name and its role in a tag (PM, Dev+/// or Rev), and its state in a word with the work it holds; the Product+/// Manager first, then who needs a person.+Future<void> showSwarmProjectSheet(+ BuildContext context, {+ required String swarmId,+ required String projectId,+}) => showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: AppGlass.rowFill,+ shape: AppControl.sheetShape,+ // On the page's own navigator, under the shell's [SwarmScope]: a chat+ // opened from it goes over it, and back comes back to it.+ builder: (_) => SwarmProjectSheet(swarmId: swarmId, projectId: projectId),+);++/// What [showSwarmProjectSheet] shows.+class SwarmProjectSheet extends StatefulWidget {+ const SwarmProjectSheet({+ super.key,+ required this.swarmId,+ required this.projectId,+ });++ final String swarmId, projectId;++ @override+ State<SwarmProjectSheet> createState() => _SwarmProjectSheetState();+}++class _SwarmProjectSheetState extends State<SwarmProjectSheet> {+ /// The team shows, not the work.+ bool _team = false;+ bool _older = false;+ String? _olderError;++ void _toggleOlder(SwarmReader reader) {+ setState(() => _older = !_older);+ if (_older) unawaited(_readOlder(reader));+ }++ /// The project's closed work: its first page, or [earlier] the next.+ Future<void> _readOlder(SwarmReader reader, {bool earlier = false}) async {+ setState(() => _olderError = null);+ try {+ await reader.loadDormant(widget.projectId, earlier: earlier);+ } catch (_) {+ if (mounted) {+ setState(() => _olderError = 'Could not load older work. Try again.');+ }+ }+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final session = SwarmScope.of(context);+ final inbox = session?.inbox;+ return SizedBox(+ // As tall whichever part shows, and its work built as it comes into+ // view: a sheet the size of its rows would build every row.+ height: MediaQuery.sizeOf(context).height * .82,+ child: SafeArea(+ top: false,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.s,+ AppSpace.l,+ 0,+ ),+ child: session == null || inbox == null+ ? const SizedBox.shrink()+ // Not listed yet, the inbox tells when it is; then the Swarm's+ // reader tells what changes.+ : ListenableBuilder(+ listenable: inbox,+ builder: (context, _) =>+ switch (inbox.reader(widget.swarmId)) {+ final reader? => ListenableBuilder(+ listenable: reader,+ builder: (context, _) =>+ _sheet(context, session, reader),+ ),+ null => _sheet(context, session, null),+ },+ ),+ ),+ ),+ );+ }++ Widget _sheet(+ BuildContext context,+ SwarmSession session,+ SwarmReader? reader,+ ) {+ final snapshot = reader?.snapshot;+ final project = snapshot?.projects+ .where((p) => p.id == widget.projectId)+ .firstOrNull;+ final glance = snapshot == null+ ? null+ : swarmTeamGlance(snapshot, projectId: widget.projectId);+ final pmId = snapshot == null || project == null+ ? null+ : swarmPmId(snapshot, project);+ final work = snapshot == null || project == null+ ? null+ : swarmProjectWork(snapshot, project, buddies: reader!.buddies);+ final waits = swarmWaitingOnYou(session.inbox, widget.swarmId);+ final waiting = [+ for (final g in work?.active ?? const <SuperTabConversation>[])+ if (waits.contains(g.id)) g,+ ];+ final Widget body;+ if (snapshot == null) {+ body = switch (reader?.error) {+ final error? => Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.xs,+ vertical: AppSpace.s,+ ),+ child: SwarmRow.line(error, lines: 3),+ ),+ null => _team ? const _MatesLoading() : const _WorkLoading(),+ };+ } else if (_team) {+ body = _mates(glance!, pmId);+ } else if (work == null) {+ body = const SizedBox.shrink();+ } else {+ body = RefreshIndicator(+ onRefresh: reader!.refresh,+ child: CustomScrollView(+ physics: const AlwaysScrollableScrollPhysics(),+ slivers: _work(snapshot, reader, work, waiting),+ ),+ );+ }+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // The grabber: a capsule as wide as the two largest steps.+ Center(+ child: Container(+ width: AppSpace.xl + AppSpace.m,+ height: AppSpace.xs,+ margin: const EdgeInsets.only(bottom: AppSpace.s),+ decoration: ShapeDecoration(+ color: AppGlass.hair,+ shape: const StadiumBorder(),+ ),+ ),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ 0,+ AppSpace.xs,+ AppSpace.s,+ ),+ child: Row(+ children: [+ Expanded(+ child: Text(+ project?.name ?? 'Team',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.heading(color: AppPalette.textPrimary),+ ),+ ),+ SwarmIconButton(+ key: const ValueKey('swarm-team-close'),+ icon: LucideIcons.x300,+ label: 'Close',+ onPressed: () => Navigator.of(context).pop(),+ ),+ ],+ ),+ ),+ _Parts(+ team: _team,+ work: switch ((work, waiting.length)) {+ (_, > 0 && final n) => (text: '$n waiting', waits: true),+ (final work?, _) => (text: '${work.active.length}', waits: false),+ (null, _) => null,+ },+ mates: glance == null ? null : '${glance.agents.length}',+ onTeam: (team) => setState(() => _team = team),+ ),+ const SizedBox(height: AppSpace.xs),+ Expanded(child: body),+ ],+ );+ }++ /// The work part's slivers: what waits on the person, then what the team+ /// works on, then "Older" — each card built row by row as it comes into+ /// view.+ List<Widget> _work(+ SuperTabSnapshot snapshot,+ SwarmReader reader,+ ({List<SuperTabConversation> active, List<SuperTabConversation> older})+ work,+ List<SuperTabConversation> waiting,+ ) {+ final working = [+ for (final g in work.active)+ if (!waiting.contains(g)) g,+ ];+ final projectId = widget.projectId;+ final olderRead = reader.dormantLoaded(projectId);+ final olderReading = reader.dormantLoading(projectId);+ final older = _older ? work.older : const <SuperTabConversation>[];+ final earlier = _older && reader.hasEarlierDormant(projectId);+ final personName = swarmTaskPersonName(snapshot);+ SwarmRow row(SuperTabConversation g) {+ final agentId = g.assignment?['agentId'] as String?;+ final agent = agentId == null ? null : snapshot.agentName(agentId);+ return SwarmRow(+ key: ValueKey('swarm-conversation-${g.id}'),+ // Nobody holds it: its number still lines up with the others'.+ leading: agentId == null+ ? const SizedBox(width: 24)+ : SwarmAvatar(+ id: agentId,+ name: snapshot.agentName(agentId),+ size: 24,+ picture: snapshot.agent(agentId)?.avatar,+ ),+ number: g.number == null ? null : '#${g.number}',+ title: g.title,+ // Its agent, then its task's line as the drawer's (#2125); work the+ // server gave no state keeps its words.+ detail: swarmTaskStatus(g, clock.now()) != null+ ? SwarmTaskLine(g, personName: personName, lead: agent)+ : switch (_statusOf(snapshot, g)) {+ final status? => SwarmRow.line(status),+ null => null,+ },+ onTap: () => openSwarmConversation(context, widget.swarmId, g.id),+ );+ }++ Widget box(Widget child) => SliverToBoxAdapter(child: child);+ // A card whose rows are built only as they come into view.+ Widget card(int count, Widget Function(int i) build) => SliverList.builder(+ itemCount: count,+ itemBuilder: (context, i) =>+ _CardRow(first: i == 0, last: i == count - 1, child: build(i)),+ );++ return [+ if (waiting.isNotEmpty) ...[+ box(const SwarmCaption('Waiting on you', first: true)),+ card(waiting.length, (i) => row(waiting[i])),+ ],+ box(SwarmCaption('Working on', first: waiting.isEmpty)),+ if (working.isEmpty)+ box(+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: SwarmRow.line('No work going on.'),+ ),+ )+ else+ card(working.length, (i) => row(working[i])),+ box(const SizedBox(height: 32)),+ card(1 + older.length + (earlier ? 1 : 0), (i) {+ if (i == 0) {+ return SwarmRow(+ key: const ValueKey('swarm-older'),+ title: _older+ ? 'Hide older'+ : olderRead+ ? 'Older (${work.older.length})'+ : 'Older',+ trailing: olderReading ? SwarmRow.line('Loading…') : null,+ chevron: _older+ ? LucideIcons.chevronDown300+ : LucideIcons.chevronRight300,+ onTap: () => _toggleOlder(reader),+ );+ }+ if (i <= older.length) return row(older[i - 1]);+ return SwarmRow(+ key: const ValueKey('swarm-older-earlier'),+ title: 'Show earlier',+ trailing: olderReading ? SwarmRow.line('Loading…') : null,+ onTap: olderReading+ ? null+ : () => unawaited(_readOlder(reader, earlier: true)),+ );+ }),+ if (_older && _olderError != null)+ box(+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.s),+ child: SwarmRow.line(+ _olderError!,+ lines: 2,+ color: AppColors.danger,+ ),+ ),+ )+ else if (_older && olderRead && work.older.isEmpty)+ box(+ Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ AppSpace.s,+ AppSpace.xs,+ 0,+ ),+ child: SwarmRow.line('No older work.'),+ ),+ ),+ SliverToBoxAdapter(+ child: SizedBox(height: MediaQuery.paddingOf(context).bottom + 28),+ ),+ ];+ }++ /// The team part: each agent, the Product Manager first.+ Widget _mates(SwarmTeamGlance glance, String? pmId) {+ if (glance.agents.isEmpty) {+ return Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.xs,+ vertical: AppSpace.s,+ ),+ child: Align(+ alignment: Alignment.topLeft,+ child: SwarmRow.line(glance.line),+ ),+ );+ }+ final agents = _pmFirst(glance, pmId);+ return ListView.separated(+ itemCount: agents.length,+ separatorBuilder: (_, _) =>+ Divider(height: 1, thickness: 1, color: AppGlass.hair),+ itemBuilder: (context, i) => _Mate(+ glance: agents[i],+ role: agents[i].agent.id == pmId+ ? 'PM'+ : agents[i].agent.isReviewer+ ? 'Rev'+ : 'Dev',+ ),+ );+ }++ /// "Nova · Needs you"-like, from the work it holds; null when nobody holds+ /// it.+ static String? _statusOf(SuperTabSnapshot snapshot, SuperTabConversation g) {+ final assignment = g.assignment;+ final status = assignment?['status'];+ if (assignment == null || status is! String) return null;+ final agent = snapshot.agentName(assignment['agentId'] as String? ?? '');+ final label = superTabWorkStatusLabel(status);+ return label.isEmpty+ ? agent+ : '$agent · ${label[0].toUpperCase()}${label.substring(1)}';+ }+}++/// The sheet's two parts, side by side: Work, with how much there is or how+/// much waits on the person ([work]), and Team, with how many ([mates]).+class _Parts extends StatelessWidget {+ const _Parts({+ required this.team,+ required this.work,+ required this.mates,+ required this.onTeam,+ });++ final bool team;+ final ({String text, bool waits})? work;+ final String? mates;+ final ValueChanged<bool> onTeam;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ Widget part(String label, ({String text, bool waits})? count, bool on) =>+ Expanded(+ child: Semantics(+ button: true,+ selected: on,+ child: Material(+ key: ValueKey('swarm-sheet-${label.toLowerCase()}'),+ color: on ? AppPalette.windowBg : Colors.transparent,+ borderRadius: BorderRadius.circular(AppControl.rowRadius),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () => onTeam(label == 'Team'),+ child: ConstrainedBox(+ constraints: const BoxConstraints(+ minHeight: AppControl.heightField,+ ),+ child: Center(+ child: Text.rich(+ TextSpan(+ children: [+ TextSpan(text: label),+ if (count case final count?)+ TextSpan(+ text: ' ${count.text}',+ style: tty.style(+ size: AppType.monoLabelSize,+ color: count.waits+ ? AppColors.warning+ : AppPalette.textFaint,+ ),+ ),+ ],+ ),+ maxLines: 1,+ style: swarmChatText(+ 15,+ color: on+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ weight: FontWeight.w500,+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ return DecoratedBox(+ decoration: BoxDecoration(+ color: AppPalette.swarmSearchSurface,+ borderRadius: BorderRadius.circular(AppControl.radius),+ ),+ child: Padding(+ padding: const EdgeInsets.all(AppSpace.xs / 2),+ child: Row(+ children: [+ part('Work', work, !team),+ part(+ 'Team',+ mates == null ? null : (text: mates!, waits: false),+ team,+ ),+ ],+ ),+ ),+ );+ }+}++/// One row of a card built row by row: a [SwarmGroup] drawn a row at a time,+/// its corners rounded at its [first] and [last] row and a hairline above+/// every row but the first.+class _CardRow extends StatelessWidget {+ const _CardRow({+ required this.first,+ required this.last,+ required this.child,+ });++ final bool first, last;+ final Widget child;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return ClipRRect(+ borderRadius: BorderRadius.vertical(+ top: Radius.circular(first ? 14 : 0),+ bottom: Radius.circular(last ? 14 : 0),+ ),+ child: ColoredBox(+ // A step from the sheet it is on.+ color: AppPalette.windowBg,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: [+ if (!first) Divider(height: 1, thickness: 1, color: AppGlass.hair),+ child,+ ],+ ),+ ),+ );+ }+}++/// The top bar while the project is read: its back, and its name on its way+/// in the title's place, the height of [SwarmTopBar].+class _LoadingTopBar extends StatelessWidget {+ const _LoadingTopBar({required this.leading});++ final Widget leading;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 52),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ AppSpace.xs,+ AppSpace.s,+ AppSpace.xs,+ ),+ child: Row(+ children: [+ leading,+ const SizedBox(width: 4),+ Expanded(+ child: Align(+ alignment: Alignment.centerLeft,+ child: SkeletonText(+ key: const ValueKey('swarm-project-title-loading'),+ style: Tty.of(context)+ .style(size: 17, weight: FontWeight.w600)+ .copyWith(height: 1.25),+ width: 120,+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }+}++/// The page on its way: nothing under its header, as nothing is there once+/// its chat is.+class _Loading extends StatelessWidget {+ const _Loading();++ @override+ Widget build(BuildContext context) =>+ const SizedBox.expand(key: ValueKey('swarm-project-loading'));+}++/// The sheet's work on its way: three rows, the shape of its cards'.+class _WorkLoading extends StatelessWidget {+ const _WorkLoading();++ @override+ Widget build(BuildContext context) => SkeletonBlock(+ key: const ValueKey('swarm-work-loading'),+ child: ListView(+ physics: const NeverScrollableScrollPhysics(),+ children: [+ const SwarmCaption('Working on', first: true),+ SwarmGroup(+ children: [+ for (var i = 0; i < 3; i++)+ Opacity(+ opacity: skeletonFade(i, 3, depth: .4),+ child: _SkeletonRow(width: i.isEven ? .45 : .6),+ ),+ ],+ ),+ ],+ ),+ );+}++/// A row on its way, the shape of a [SwarmRow] with a 24-point avatar and a+/// line under its title.+class _SkeletonRow extends StatelessWidget {+ const _SkeletonRow({this.width = .45});++ final double width;++ @override+ Widget build(BuildContext context) => ConstrainedBox(+ constraints: const BoxConstraints(minHeight: SwarmRow.height),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ vertical: AppSpace.m,+ ),+ child: Row(+ children: [+ const Skeleton(width: 24, height: 24, radius: 12),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ SkeletonText(+ style: AppType.label(height: 1.3),+ widthFactor: width,+ ),+ const SizedBox(height: 3),+ SkeletonText(+ style: AppType.caption(height: 1.35),+ widthFactor: width + .25,+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ );+}++/// The team with its Product Manager first, as the prototype lists it; the+/// rest as [swarmTeamGlance] orders them, who needs the person first.+List<SwarmAgentGlance> _pmFirst(SwarmTeamGlance glance, String? pmId) => [+ ...glance.agents.where((a) => a.agent.id == pmId),+ ...glance.agents.where((a) => a.agent.id != pmId),+];++/// The team part's agents on their way: three, the shape of [_Mate].+class _MatesLoading extends StatelessWidget {+ const _MatesLoading();++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return SkeletonBlock(+ key: const ValueKey('swarm-team-loading'),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (var i = 0; i < 3; i++) ...[+ if (i > 0) Divider(height: 1, thickness: 1, color: AppGlass.hair),+ Opacity(+ opacity: skeletonFade(i, 3, depth: .4),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.xs,+ vertical: AppSpace.m,+ ),+ child: Row(+ children: [+ const Skeleton(+ width: 32,+ height: 32,+ shape: BoxShape.circle,+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SkeletonText(+ style: AppType.label(),+ widthFactor: i.isEven ? .35 : .5,+ ),+ const SizedBox(height: 3),+ SkeletonText(+ style: AppType.caption(height: 1.4),+ widthFactor: .7,+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ ],+ ],+ ),+ );+ }+}++/// One agent of the team part.+class _Mate extends StatelessWidget {+ const _Mate({required this.glance, required this.role});++ final SwarmAgentGlance glance;++ /// Its role in a tag: PM, Dev (a Builder) or Rev (a Reviewer).+ final String role;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ final down = glance.state == SwarmAgentState.down;+ final shell = PhoneShellScope.maybeOf(context);+ return Padding(+ key: ValueKey('swarm-agent-${glance.agent.id}'),+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.xs,+ vertical: AppSpace.m,+ ),+ child: Row(+ children: [+ SwarmAvatar(+ id: glance.agent.id,+ name: glance.name,+ picture: glance.agent.avatar,+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Flexible(+ child: Text(+ glance.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.label(color: AppPalette.textPrimary),+ ),+ ),+ const SizedBox(width: 6),+ DecoratedBox(+ decoration: BoxDecoration(+ border: Border.all(color: AppGlass.hair),+ borderRadius: BorderRadius.circular(+ AppCard.insetRadius,+ ),+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.xs,+ ),+ child: Text(+ role,+ style: tty+ .style(+ size: 11,+ weight: FontWeight.w600,+ color: AppPalette.textSecondary,+ )+ .copyWith(height: 16 / 11),+ ),+ ),+ ),+ ],+ ),+ const SizedBox(height: 3),+ Text.rich(+ TextSpan(+ children: [+ TextSpan(+ text: '● ',+ style: TextStyle(color: swarmStateColor(glance.state)),+ ),+ TextSpan(+ text: glance.label,+ style: down+ ? TextStyle(color: swarmStateColor(glance.state))+ : null,+ ),+ if (glance.task case final task?)+ TextSpan(text: ' · ${task.label}'),+ ],+ ),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.4,+ ),+ ),+ if (shell != null && glance.agent.harnessId.isNotEmpty)+ Align(+ alignment: AlignmentDirectional.centerStart,+ child: SwarmButton(+ key: ValueKey('swarm-open-terminal-${glance.agent.id}'),+ label: 'Open terminal',+ style: SwarmButtonStyle.link,+ onPressed: () => shell.onOpenAgent(+ glance.agent.machineId,+ glance.agent.harnessId,+ ),+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_reactions.dart b/mobile/lib/swarm/swarm_reactions.dartnew file mode 100644index 000000000..15d194c64--- /dev/null+++ b/mobile/lib/swarm/swarm_reactions.dart@@ -0,0 +1,235 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/shared/theme/app_icon_size.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'model.dart';+import 'swarm_message_row.dart'+ show swarmChatCard, swarmChatHair, swarmChatText;++/// Who gave a reaction, as the chat names them: never by email.+typedef SwarmReactorName = String Function(String kind, String id);++/// The counts under a message, as Desktop draws them (`reactions.dart`): each+/// emoji and how many gave it, the reader's own marked. A tap takes theirs+/// back or adds it; holding one names who gave it. Without [onReact] (a+/// reader who cannot post) the counts only show.+class SwarmReactionBar extends StatelessWidget {+ const SwarmReactionBar({+ super.key,+ required this.messageId,+ required this.reactions,+ required this.readerId,+ required this.nameOf,+ this.onReact,+ });++ final String messageId;+ final List<SuperTabReactionCount> reactions;+ final String readerId;+ final SwarmReactorName nameOf;+ final ValueChanged<SuperTabReactionEmoji>? onReact;++ @override+ Widget build(BuildContext context) {+ if (reactions.isEmpty) return const SizedBox.shrink();+ return Padding(+ padding: const EdgeInsets.only(top: AppSpace.xs),+ child: Wrap(+ spacing: 6,+ children: [+ for (final reaction in reactions)+ _Count(+ key: ValueKey('swarm-reaction-$messageId-${reaction.emoji.key}'),+ reaction: reaction,+ mine: reaction.includes('person', readerId),+ names: _names(reaction),+ onTap: switch (onReact) {+ final react? => () => react(reaction.emoji),+ null => null,+ },+ ),+ ],+ ),+ );+ }++ String _names(SuperTabReactionCount reaction) {+ final names = [for (final who in reaction.by) nameOf(who.kind, who.id)];+ return names.length < 2+ ? names.join()+ : '${names.sublist(0, names.length - 1).join(', ')} and ${names.last}';+ }+}++/// One emoji's count: a finger's size to tap, though drawn smaller.+class _Count extends StatelessWidget {+ const _Count({+ super.key,+ required this.reaction,+ required this.mine,+ required this.names,+ required this.onTap,+ });++ final SuperTabReactionCount reaction;+ final bool mine;+ final String names;+ final VoidCallback? onTap;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ final accent = AppPalette.accentOnSurface;+ return Semantics(+ button: true,+ selected: mine,+ enabled: onTap != null,+ label: '${reaction.emoji.glyph} ${reaction.count}, $names',+ excludeSemantics: true,+ onTap: onTap,+ child: Tooltip(+ message: names,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minWidth: 44, minHeight: 44),+ child: Center(+ widthFactor: 1,+ child: Container(+ height: 30,+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),+ decoration: ShapeDecoration(+ color: mine+ ? accent.withValues(alpha: 0.14)+ : swarmChatCard(tty),+ shape: StadiumBorder(+ side: BorderSide(color: mine ? accent : swarmChatHair(tty)),+ ),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(reaction.emoji.glyph, style: swarmChatText(15)),+ const SizedBox(width: 5),+ Text(+ '${reaction.count}',+ style: swarmChatText(+ 13.5,+ color: mine ? accent : AppPalette.textSecondary,+ weight: FontWeight.w600,+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }+}++/// Opens the reactions a message can carry in a sheet, with a light tap of+/// the phone as a long-press gives: Desktop's six, the reader's own marked.+/// Answers the one picked, or null when the sheet closed without one.+Future<SuperTabReactionEmoji?> showSwarmReactionPicker(+ BuildContext context, {+ required List<SuperTabReactionCount> reactions,+ required String readerId,+}) {+ HapticFeedback.lightImpact();+ final mine = {+ for (final r in reactions)+ if (r.includes('person', readerId)) r.emoji,+ };+ return showModalBottomSheet<SuperTabReactionEmoji>(+ context: context,+ backgroundColor: AppGlass.rowFill,+ shape: AppControl.sheetShape,+ builder: (context) => _Picker(mine: mine),+ );+}++class _Picker extends StatelessWidget {+ const _Picker({required this.mine});++ final Set<SuperTabReactionEmoji> mine;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final accent = AppPalette.accentOnSurface;+ return SafeArea(+ top: false,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.s,+ AppSpace.l,+ AppSpace.l,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ // The grabber: a capsule as wide as the two largest steps.+ Container(+ width: AppSpace.xl + AppSpace.m,+ height: AppSpace.xs,+ margin: const EdgeInsets.only(bottom: AppSpace.m),+ decoration: ShapeDecoration(+ color: AppGlass.hair,+ shape: const StadiumBorder(),+ ),+ ),+ Row(+ mainAxisAlignment: MainAxisAlignment.spaceEvenly,+ children: [+ for (final emoji in SuperTabReactionEmoji.values)+ Semantics(+ button: true,+ selected: mine.contains(emoji),+ label:+ '${emoji.key.replaceAll('_', ' ')}'+ '${mine.contains(emoji) ? ', yours' : ''}',+ excludeSemantics: true,+ onTap: () => Navigator.of(context).pop(emoji),+ child: GestureDetector(+ key: ValueKey('swarm-react-${emoji.key}'),+ behavior: HitTestBehavior.opaque,+ onTap: () => Navigator.of(context).pop(emoji),+ child: Container(+ width: 50,+ height: 50,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: mine.contains(emoji)+ ? accent.withValues(alpha: 0.18)+ : null,+ border: mine.contains(emoji)+ ? Border.all(color: accent)+ : null,+ shape: BoxShape.circle,+ ),+ child: Text(+ emoji.glyph,+ style: const TextStyle(+ fontSize: AppIconSize.standalone,+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_read_marks.dart b/mobile/lib/swarm/swarm_read_marks.dartnew file mode 100644index 000000000..182cda538--- /dev/null+++ b/mobile/lib/swarm/swarm_read_marks.dart@@ -0,0 +1,251 @@+import 'dart:async';+import 'dart:convert';+import 'dart:math';++import 'package:flutter/foundation.dart';++import '../core/local_key_value_store.dart';+import 'model.dart';+import 'swarm_reader.dart';++/// Sends the reader's read marks to the server (backend `superTabs/readMarks.ts`, #2131), so a chat read on this phone+/// reads as read on every other device. The desktop's `SuperTabReadMarkSender`: one request per chat at a time; a+/// higher mark asked for while one is on its way goes after it, and a lower or equal one is never sent. A failed send+/// is forgotten, so the next mark asked for tries again; meanwhile this phone's own mark keeps the chat read here.+class SwarmReadMarkSender {+ SwarmReadMarkSender(this._send);++ /// Writes [sequence] as the mark of [conversationId]; completes once the server kept it, or throws.+ final Future<void> Function(String conversationId, int sequence) _send;++ /// The highest mark sent and kept, by chat.+ final _sent = <String, int>{};++ /// The mark waiting for the one on its way, by chat.+ final _next = <String, int>{};+ final _sending = <String>{};+ bool _disposed = false;++ /// Asks for [sequence] to be [conversationId]'s mark on the server, unless [kept] (what the server already holds)+ /// or a mark sent from here is as high.+ void mark(String conversationId, int sequence, {int kept = 0}) {+ if (_disposed || sequence <= kept) return;+ if (sequence <= (_sent[conversationId] ?? 0)) return;+ if (sequence <= (_next[conversationId] ?? 0)) return;+ _next[conversationId] = sequence;+ if (_sending.add(conversationId)) unawaited(_drain(conversationId));+ }++ Future<void> _drain(String conversationId) async {+ while (!_disposed) {+ final sequence = _next.remove(conversationId);+ if (sequence == null) break;+ try {+ await _send(conversationId, sequence);+ if (sequence > (_sent[conversationId] ?? 0)) {+ _sent[conversationId] = sequence;+ }+ } catch (_) {+ // Offline, or a server without read marks: this phone's mark stands,+ // and the next one asked for is sent afresh.+ }+ }+ _sending.remove(conversationId);+ }++ void dispose() => _disposed = true;+}++/// How far the person has read each chat of one Swarm ([reader]), as the+/// desktop keeps it (`SuperTabController.unread`): a chat is unread while its+/// newest message in the main stream ([SuperTabConversation.mainSequence]; a+/// reply only in a thread is not) is past the higher of the server's mark+/// ([SuperTabSnapshot.readMarks], #2131) and this phone's own. Unread is drawn+/// as the chat's name in bold (design system: Unread).+///+/// The phone's own marks are what a server without read marks has, and what+/// keeps a chat read here while a send is on its way or failed. They are kept+/// on the phone ([store]) under the account and the Swarm: no message, only+/// each chat's id and a number. The first read of a Swarm on this phone, with+/// no mark yet from the phone or the server, counts what is already there as+/// read (Tony, 2026-10-29), so a new phone does not start with every chat in+/// bold; the Home kept from before is no read. Nothing is unread until the+/// marks are read back. Access lost takes them off the phone too.+class SwarmReadMarks extends ChangeNotifier {+ SwarmReadMarks(+ this.reader, {+ required this.store,+ this.saveAfter = Duration.zero,+ }) {+ _sender = SwarmReadMarkSender(+ (id, sequence) => reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}'+ '/conversations/${Uri.encodeComponent(id)}/read',+ body: {'sequence': sequence},+ ),+ );+ reader.addListener(_swarmChanged);+ reader.reads.addListener(_swarmChanged);+ unawaited(_load());+ }++ /// The most chats whose marks the phone keeps per Swarm; the marks of chats+ /// the Swarm's read no longer has go first.+ static const kept = 1000;++ final SwarmReader reader;++ /// How long marks wait to be written: at once by default, after what moved+ /// them together (a first read's, a chat read on), which is written once.+ final Duration saveAfter;++ /// Where the phone keeps its marks; null keeps them in memory only.+ final LocalKeyValueStore? store;+ late final SwarmReadMarkSender _sender;++ /// The phone's own marks, by chat.+ final _marks = <String, int>{};++ /// The marks were read back from the phone (or there is no store).+ bool _loaded = false;++ /// The marks count: read back from the phone, or started by a first read.+ bool _started = false;+ Timer? _save;+ bool _disposed = false;++ String get _key => 'swarm_read_marks.${reader.accountId}.${reader.tabId}';++ /// Whether [group] has messages in its main stream past what the person+ /// has read.+ bool unread(SuperTabConversation group) {+ if (!_loaded || !_started) return false;+ final server = reader.snapshot?.readMarks[group.id] ?? 0;+ return group.mainSequence > max(server, _marks[group.id] ?? 0);+ }++ /// The person saw [conversationId] through [sequence]: sent to the server,+ /// and kept on the phone when it moves the phone's mark on.+ void markRead(String conversationId, int sequence) {+ if (_disposed || reader.accessRevoked) return;+ _sender.mark(+ conversationId,+ sequence,+ kept: reader.snapshot?.readMarks[conversationId] ?? 0,+ );+ if (sequence <= (_marks[conversationId] ?? 0)) return;+ _marks[conversationId] = sequence;+ _saveSoon();+ notifyListeners();+ }++ Future<void> _load() async {+ final held = <String, int>{};+ var found = false;+ try {+ if (await store?.read(_key) case final raw?) {+ if (jsonDecode(raw) case {'marks': final Map marks}) {+ for (final MapEntry(:key, :value) in marks.entries) {+ if (key is String && value is num) held[key] = value.toInt();+ }+ found = true;+ }+ }+ } catch (_) {+ // An unreadable value is no marks: the next first read starts afresh.+ }+ if (_disposed || reader.accessRevoked) return;+ final marked = _marks.isNotEmpty;+ for (final MapEntry(:key, :value) in held.entries) {+ if (value > (_marks[key] ?? 0)) _marks[key] = value;+ }+ _loaded = true;+ _started |= found;+ // A chat read before the marks were back is kept with them.+ if (marked) _saveSoon();+ _swarmChanged();+ notifyListeners();+ }++ /// The Swarm was read, changed or not: its first read on this phone starts+ /// the marks.+ void _swarmChanged() {+ if (_disposed) return;+ if (reader.accessRevoked) {+ _forget();+ return;+ }+ final snapshot = reader.snapshot;+ // The Home kept holds no first load ([SwarmReader.heldLoad]).+ if (!_loaded || _started || snapshot == null || reader.heldLoad == 0) {+ return;+ }+ _started = true;+ if (snapshot.readMarks.isEmpty) {+ for (final group in snapshot.conversations) {+ if (group.lastMessageSequence > (_marks[group.id] ?? 0)) {+ _marks[group.id] = group.lastMessageSequence;+ }+ }+ }+ _saveSoon();+ notifyListeners();+ }++ void _forget() {+ _save?.cancel();+ _save = null;+ final had = _marks.isNotEmpty || _started;+ _marks.clear();+ _started = false;+ unawaited(store?.delete(_key).catchError((Object _) {}));+ if (had) notifyListeners();+ }++ void _saveSoon() {+ if (!_loaded || store == null || _disposed) return;+ _save?.cancel();+ _save = Timer(saveAfter, _write);+ }++ void _write() {+ _save = null;+ _trim();+ final value = jsonEncode({'marks': _marks});+ unawaited(store?.write(_key, value).catchError((Object _) {}));+ }++ /// At most [kept] marks: those of chats the Swarm's read no longer has go+ /// first, then the oldest kept.+ void _trim() {+ if (_marks.length <= kept) return;+ final read = {+ for (final group in reader.snapshot?.conversations ?? const []) group.id,+ };+ for (final id in [+ for (final id in _marks.keys)+ if (!read.contains(id)) id,+ ]) {+ if (_marks.length <= kept) return;+ _marks.remove(id);+ }+ while (_marks.length > kept) {+ _marks.remove(_marks.keys.first);+ }+ }++ @override+ void dispose() {+ _disposed = true;+ // What waited to be written is written now.+ if (_save case final save?) {+ save.cancel();+ _write();+ }+ reader.removeListener(_swarmChanged);+ reader.reads.removeListener(_swarmChanged);+ _sender.dispose();+ super.dispose();+ }+}diff --git a/mobile/lib/swarm/swarm_reader.dart b/mobile/lib/swarm/swarm_reader.dartnew file mode 100644index 000000000..b01df5db8--- /dev/null+++ b/mobile/lib/swarm/swarm_reader.dart@@ -0,0 +1,438 @@+import 'dart:async';+import 'dart:isolate';++import 'package:flutter/foundation.dart';++import 'model.dart';+import 'parts.dart';+import 'swarm_buddy.dart';+import 'swarm_read_marks.dart';+import 'swarm_request.dart';+import 'waiting_work.dart';++/// A Swarm of this many groups and agents or more is made into what the+/// screens draw off the UI isolate: on the owner's iPhone 14 a 1.3 MB Swarm took 73 to 93 ms+/// there, several frames (Mira's Profile numbers, 2026-10-27). A small one+/// takes less than sending it away does.+const swarmParseOffThreadParts = 100;++/// What the screens draw of a Swarm, worked out from its parts.+typedef _View = ({+ SuperTabSnapshot snapshot,+ Map<String, String> partners,+ SwarmBuddies buddies,+});++/// [parts] as [accountId] reads them: whose Buddies are whose depends on who+/// reads.+_View _viewOf(SuperTabParts parts, String accountId) {+ final state = parts.state;+ return (+ snapshot: SuperTabSnapshot.fromJson(state),+ partners: swarmPartners(state),+ buddies: SwarmBuddies.read(state, accountId),+ );+}++/// Whether a Swarm whose first load is [answer] is big enough to be worked+/// out off the UI isolate: its groups and agents are nearly all of it.+bool _big(Map<String, dynamic> answer) =>+ ((answer['groups'] as List?)?.length ?? 0) ++ ((answer['agents'] as List?)?.length ?? 0) >=+ swarmParseOffThreadParts;++/// [work], off the UI isolate when [big]. Top-level, so its closures carry+/// only what they are handed, never a reader.+Future<T> _offThread<T>(bool big, T Function() work) =>+ big ? Isolate.run(work) : Future.sync(work);++Future<_View> _view(+ SuperTabParts parts,+ String accountId, {+ required bool big,+}) => _offThread(big, () => _viewOf(parts, accountId));++Future<({SuperTabParts parts, _View view})> _load(+ Map<String, dynamic> answer,+ String accountId,+) => _offThread(_big(answer), () {+ final parts = SuperTabParts.firstLoad(answer);+ return (parts: parts, view: _viewOf(parts, accountId));+});++/// One Swarm as this phone keeps it current: a first load, then only the parts+/// that changed since its cursor (docs/design/2026-10-26-swarm-state-parts.md,+/// section 4) — the desktop's `SuperTabController` read, without its panes,+/// drafts and launches.+///+/// It reads only while [shown]: a phone pays for every read in data and+/// battery, and a Swarm nobody is looking at needs none (the web build's+/// `SuperTabReading.pausesAway`). Shown again, it reads at once.+class SwarmReader extends ChangeNotifier {+ SwarmReader({+ required this.tabId,+ required this.accountId,+ required this.request,+ this.upload = refuseSwarmUpload,+ this.pollInterval = const Duration(seconds: 5),+ });++ final String tabId, accountId;+ final SwarmRequest request;++ /// Sends a chat's file to the backend ([SwarmConversation.send]).+ final SwarmUpload upload;+ final Duration pollInterval;++ /// The Swarm as last read; null before the first read and after access ends.+ SuperTabSnapshot? snapshot;++ /// Each conversation's partner, the person its work needs ([swarmPartners]).+ Map<String, String> partners = const {};++ /// The Buddy chats and Buddies held, the reader's own by project+ /// ([swarmBuddyChat], [swarmBuddy]).+ SwarmBuddies buddies = SwarmBuddies.none;++ /// How far the person has read each chat, which its inbox keeps with it;+ /// null where nobody keeps them, and nothing reads as unread.+ SwarmReadMarks? readMarks;++ /// What the last read could not do, as a sentence; null once one succeeds.+ String? error;++ /// The newest change of any part, as the last read said: what tells a list+ /// this Swarm changed. -1 before the first read. A move of it alone is no+ /// notify, only a [reads] count.+ int lastChangedAt = -1;++ /// The reader may no longer read this Swarm: it left, or was removed.+ bool accessRevoked = false;++ /// Moves each time what this reader holds is read again from nothing (a+ /// first load) or taken away: an answer asked for under an earlier one may+ /// carry what the reader can no longer see, and is not applied.+ int generation = 0;++ /// The backend needs a newer build: no read can succeed, so none is tried.+ bool updateRequired = false;++ /// True until the first read answers, either way.+ bool get loading => snapshot == null && error == null && !accessRevoked;++ /// Counts the reads that answered, changed or not: what tells a read that+ /// failed beside this one to try again, where the Swarm itself stays as it+ /// was and so tells nothing.+ ValueListenable<int> get reads => _reads;+ final _reads = ValueNotifier(0);++ /// Counts the first loads asked for, each told once its request is out:+ /// what is read alongside one answers no earlier than it does.+ ValueListenable<int> get firstLoads => _firstLoads;+ final _firstLoads = ValueNotifier(0);++ /// Which of [firstLoads] what this reader holds came from; 0 while it holds+ /// none.+ int get heldLoad => _heldLoad;+ int _heldLoad = 0;++ SuperTabParts? _parts;++ /// The first load held was big ([swarmParseOffThreadParts]): its changes+ /// are drawn off the UI isolate too.+ bool _bigParts = false;++ /// Counts what was drawn: one worked out off the UI isolate is not shown+ /// over one drawn meanwhile from the parts as they are now.+ int _views = 0;+ Future<void>? _refreshing;+ Timer? _poll;+ bool _shown = false, _disposed = false;++ String get _path => '/api/super-tabs/${Uri.encodeComponent(tabId)}';++ bool get shown => _shown;++ /// On screen: reads at once and every [pollInterval] after. Off screen:+ /// reads nothing.+ set shown(bool value) {+ if (_shown == value) return;+ _shown = value;+ _poll?.cancel();+ _poll = null;+ if (value) unawaited(_tick());+ }++ Future<void> _tick() async {+ await refresh();+ if (_disposed || !_shown || updateRequired || accessRevoked) return;+ _poll?.cancel();+ _poll = Timer(pollInterval, () => unawaited(_tick()));+ }++ /// One read now, joining one under way.+ Future<void> refresh() {+ if (_disposed || accessRevoked || updateRequired) return Future.value();+ return _refreshing ??= _read().whenComplete(() => _refreshing = null);+ }++ Future<Map<String, dynamic>> _get(String path) async =>+ superTabMap(await request('GET', path));++ Future<void> _read() async {+ var changed = false;+ final failedBefore = error;+ try {+ final read = await _readParts();+ if (_disposed || accessRevoked) return;+ final parts = _parts!;+ if (read.changed || snapshot == null) {+ final views = _views;+ final view = read.view ?? await _view(parts, accountId, big: _bigParts);+ if (_disposed || accessRevoked) return;+ if (view.snapshot.id != tabId) {+ _parts = null;+ throw const FormatException('A different Swarm was returned.');+ }+ if (views == _views && identical(parts, _parts)) {+ _show(view);+ changed = true;+ }+ }+ // Moved alone, it is a change this reader cannot see: nothing to draw+ // again. What waits on it hears of it through [reads].+ lastChangedAt = parts.lastChangedAt;+ error = null;+ _reads.value++;+ } on SuperTabFailure catch (failure) {+ if (_disposed || accessRevoked) return;+ if (failure.statusCode == 426 ||+ (failure.code == 'UPDATE_REQUIRED' && failure.statusCode != 400)) {+ updateRequired = true;+ error = 'Update Harness to keep using this Swarm.';+ _poll?.cancel();+ } else if (const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {+ // Refused a first load: nothing of a Swarm it left stays on screen.+ _forget();+ error = failure.message;+ } else {+ error = failure.message;+ }+ changed = true;+ } on FormatException catch (failure) {+ if (_disposed || accessRevoked) return;+ error = failure.message.isEmpty+ ? 'Could not read this Swarm.'+ : failure.message;+ changed = true;+ } catch (_) {+ if (_disposed || accessRevoked) return;+ error = 'Could not reach this Swarm. Try again.';+ changed = true;+ }+ if (changed || error != failedBefore) notifyListeners();+ }++ /// Changes since the cursor once a first load is held, else a first load. A+ /// reload answer, or a change read refused for access (the Swarm or the+ /// reader's access moved), loads in full at once.+ Future<({bool changed, _View? view})> _readParts() async {+ final held = _parts;+ if (held != null) {+ try {+ final answer = await _get(+ '$_path/changes?cursor=${Uri.encodeQueryComponent(held.cursor)}',+ );+ if (answer['reload'] != true) {+ final SuperTabPartsChange change;+ try {+ change = held.apply(answer);+ } catch (_) {+ // Half merged: the next read starts again from a first load.+ if (identical(_parts, held)) _parts = null;+ rethrow;+ }+ final stale = await _refreshStale(held);+ return (changed: change.changed || stale, view: null);+ }+ } on SuperTabFailure catch (failure) {+ if (!const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) rethrow;+ }+ _parts = null;+ }+ final asked = _get('$_path/parts');+ final number = ++_firstLoads.value;+ final answer = await asked;+ final load = await _load(answer, accountId);+ // Revoked meanwhile: what was read is not kept.+ if (_disposed || accessRevoked) return (changed: false, view: null);+ _parts = load.parts;+ _bigParts = _big(answer);+ _heldLoad = number;+ generation++;+ // A new store holds no closed conversations: they are read again.+ _dormantPages.clear();+ _dormantReads.clear();+ return (changed: true, view: load.view);+ }++ void _show(_View view) {+ snapshot = view.snapshot;+ partners = view.partners;+ buddies = view.buddies;+ swarmMarkBuddies(view.snapshot, view.buddies);+ _views++;+ }++ /// The reader may no longer read this Swarm — a first load was refused, or+ /// it left the account's list: nothing read of it stays, and it reads no+ /// more. Its listeners hear of it, so a screen holding it lets go too.+ void revoke() {+ if (_disposed || accessRevoked) return;+ _forget();+ error = null;+ notifyListeners();+ }++ void _forget() {+ accessRevoked = true;+ snapshot = null;+ partners = const {};+ buddies = SwarmBuddies.none;+ _parts = null;+ _heldLoad = 0;+ generation++;+ _dormantPages.clear();+ _dormantReads.clear();+ _poll?.cancel();+ }++ /// A dormant stub says a held group closed, not how: its data is read again+ /// by id. Best effort: a failure leaves it as it was until the next read.+ Future<bool> _refreshStale(SuperTabParts parts) async {+ var read = false;+ for (final id in parts.staleGroups) {+ try {+ if (await _readGroup(parts, id)) {+ read = true;+ } else {+ parts.forgetStale(id);+ }+ } on SuperTabFailure {+ // Tried again at the next read.+ }+ }+ return read;+ }++ /// Reads group [id] by id into [parts], active or closed (section 4.5).+ /// False when the reader cannot read it.+ Future<bool> _readGroup(SuperTabParts parts, String id) async {+ try {+ final answer = await _get('$_path/groups/${Uri.encodeComponent(id)}');+ if (!identical(parts, _parts)) return false;+ parts.addDormant([answer['group']]);+ return true;+ } on SuperTabFailure catch (failure) {+ if (const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) return false;+ rethrow;+ }+ }++ /// Makes conversation [id] part of [snapshot]: one a first load leaves out+ /// (closed, or quiet for a day) is read by id, as a decision or a tag can+ /// point at one. False when the reader cannot read it; a read that failed+ /// throws, as it says nothing of whether it could.+ Future<bool> loadConversation(String id) async {+ if (snapshot?.conversation(id) != null) return true;+ if (_parts == null) {+ await refresh();+ if (snapshot?.conversation(id) != null) return true;+ }+ if (_disposed || accessRevoked) return false;+ final parts = _parts;+ if (parts == null) {+ throw SuperTabFailure(+ 'UNAVAILABLE',+ error ?? 'Could not read this Swarm.',+ );+ }+ final bool readable;+ try {+ readable = await _readGroup(parts, id);+ } on SuperTabFailure catch (failure) {+ if (!_disposed) {+ error = failure.message;+ notifyListeners();+ }+ rethrow;+ }+ if (_disposed || accessRevoked) return false;+ // Read again from nothing meanwhile: that read is the one to ask.+ if (!identical(parts, _parts)) return loadConversation(id);+ if (!readable) return false;+ _show(_viewOf(parts, accountId));+ notifyListeners();+ return snapshot?.conversation(id) != null;+ }++ /// Each project's closed conversations as read: where the next earlier+ /// page starts, null when there is none. A project not here is not read.+ final _dormantPages = <String, String?>{};+ final _dormantReads = <String, Future<void>>{};++ /// Whether [projectId]'s closed conversations have been read.+ bool dormantLoaded(String projectId) => _dormantPages.containsKey(projectId);++ /// Whether a read of [projectId]'s closed conversations is under way.+ bool dormantLoading(String projectId) => _dormantReads.containsKey(projectId);++ /// Whether [projectId] has closed conversations older than those read.+ bool hasEarlierDormant(String projectId) => _dormantPages[projectId] != null;++ /// Reads [projectId]'s closed conversations (archived, or quiet for a day),+ /// which no first load has, newest first and a page at a time (section+ /// 4.5): the first page once, [earlier] the next. Joins a read under way;+ /// a read that failed throws, and asking again reads again — the desktop's+ /// `loadDormant`.+ Future<void> loadDormant(String projectId, {bool earlier = false}) {+ if (_disposed || accessRevoked || _parts == null) return Future.value();+ if (_dormantReads[projectId] case final reading?) return reading;+ if (earlier ? !hasEarlierDormant(projectId) : dormantLoaded(projectId)) {+ return Future.value();+ }+ late final Future<void> reading;+ reading = _readDormant(projectId, earlier).whenComplete(() {+ if (identical(_dormantReads[projectId], reading)) {+ _dormantReads.remove(projectId);+ }+ if (!_disposed) notifyListeners();+ });+ _dormantReads[projectId] = reading;+ notifyListeners();+ return reading;+ }++ Future<void> _readDormant(String projectId, bool earlier) async {+ final parts = _parts!;+ final before = earlier ? _dormantPages[projectId] : null;+ final answer = await _get(+ '$_path/groups?dormant=1&projectId=${Uri.encodeQueryComponent(projectId)}'+ '${before == null ? '' : '&before=${Uri.encodeQueryComponent(before)}'}',+ );+ // Read again from nothing meanwhile: this page is of the parts before.+ if (_disposed || accessRevoked || !identical(parts, _parts)) return;+ final change = parts.addDormant(answer['groups'] as List);+ _dormantPages[projectId] = answer['next'] as String?;+ if (change.changed) _show(_viewOf(parts, accountId));+ }++ @override+ void dispose() {+ _disposed = true;+ _poll?.cancel();+ _reads.dispose();+ _firstLoads.dispose();+ super.dispose();+ }+}diff --git a/mobile/lib/swarm/swarm_request.dart b/mobile/lib/swarm/swarm_request.dartnew file mode 100644index 000000000..302585197--- /dev/null+++ b/mobile/lib/swarm/swarm_request.dart@@ -0,0 +1,65 @@+import 'dart:math';+import 'dart:typed_data';++import 'package:dio/dio.dart' show CancelToken;++/// One Swarm backend call: what `AppNotifier.swarmRequest` does, and what the+/// readers here are handed so their tests need no machine.+typedef SwarmRequest = Future<Object?> Function(+ String method,+ String path, {+ Map<String, dynamic>? body,+});++/// A Swarm call that did not answer: the backend's refusal, the forwarding+/// machine's, or none to forward through. [code] is for the code to branch on;+/// [message] is the sentence to show.+///+/// The desktop's `SuperTabFailure` (`desktop/lib/super_tabs/controller.dart`),+/// so a refusal reads the same on both.+class SuperTabFailure implements Exception {+ const SuperTabFailure(this.code, this.message, {this.statusCode = 0});+ final String code, message;+ final int statusCode;+ @override+ String toString() => message;+}++/// A fresh receipt for one command: the backend runs a command once per+/// operation id, so a retry under the same id is the same command.+String superTabOperationId() {+ final random = Random.secure();+ return List.generate(+ 16,+ (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'),+ ).join();+}++/// Sends one file for a message in [conversationId] of Swarm [tabId] and+/// answers the backend's `{attachment: {...}}` — `ApiClient.uploadSwarmAttachment`,+/// and what the chats here are handed so their tests need no backend.+/// [onProgress] is told the part sent, from 0 to 1. A refusal throws a+/// [SuperTabFailure] carrying the backend's code.+typedef SwarmUpload =+ Future<Map<String, dynamic>> Function({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+ });++/// The upload of a phone that cannot reach the backend with a file.+Future<Map<String, dynamic>> refuseSwarmUpload({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+}) => Future.error(+ const SuperTabFailure('UPLOAD_UNAVAILABLE', 'Files can’t be sent from here.'),+);diff --git a/mobile/lib/swarm/swarm_row.dart b/mobile/lib/swarm/swarm_row.dartnew file mode 100644index 000000000..eb2ddd523--- /dev/null+++ b/mobile/lib/swarm/swarm_row.dart@@ -0,0 +1,145 @@+import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/tty.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 'swarm_style.dart';+import 'swarm_unread.dart';++/// One row of a Swarm card ([SwarmGroup]), as the approved prototype draws+/// it: maybe a mark at its left (an avatar, a project's tile, a need's+/// glyph), its title — after a work number in the terminal's face — and a+/// line under it, then at its right what it holds or a chevron. Never under+/// 56 points. Something new in it ([news]) sets its title in bold, with no+/// dot, and the tags waiting in it as `@N` before its right edge (desktop+/// design system: Unread, Mentions).+class SwarmRow extends StatelessWidget {+ const SwarmRow({+ super.key,+ this.leading,+ required this.title,+ this.number,+ this.detail,+ this.trailing,+ this.chevron = LucideIcons.chevronRight300,+ this.news = swarmNoNews,+ required this.onTap,+ });++ final Widget? leading;+ final String title;++ /// A work's number, "#4", before its title.+ final String? number;++ /// The line under the title: words ([line]) or a team line.+ final Widget? detail;++ /// What the row holds at its right, in place of the chevron.+ final Widget? trailing;++ /// The chevron of a row that opens something; null draws none.+ final IconData? chevron;++ /// What is new in it: unread or tagged ([swarmChatNews]).+ final SwarmRowNews news;+ final VoidCallback? onTap;++ /// Every row clears this, for a thumb.+ static const double height = 56;++ /// A row's line under its title, in the secondary ink.+ static Widget line(String text, {Key? key, int lines = 1, Color? color}) =>+ Text(+ text,+ key: key,+ maxLines: lines,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(+ color: color ?? AppPalette.textSecondary,+ height: 1.35,+ ),+ );++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ final end =+ trailing ??+ (onTap == null || chevron == null+ ? null+ : Icon(chevron, size: 18, color: AppPalette.textFaint));+ final row = ConstrainedBox(+ constraints: const BoxConstraints(minHeight: height),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ vertical: AppSpace.m,+ ),+ child: Row(+ children: [+ if (leading case final leading?) ...[+ leading,+ const SizedBox(width: 12),+ ],+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ // Unread is heard in words, as the bold is seen; tags+ // say their own.+ Semantics(+ label: news.bold && news.tags == 0+ ? 'Unread messages'+ : null,+ child: Text.rich(+ TextSpan(+ children: [+ if (number case final number?)+ TextSpan(+ text: '$number ',+ style: tty.style(+ size: 13.5,+ color: AppPalette.textSecondary,+ ),+ ),+ TextSpan(text: title),+ ],+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.label(+ color: AppPalette.textPrimary,+ height: 1.3,+ fontWeight: news.bold ? AppFont.semibold : null,+ ),+ ),+ ),+ if (detail case final detail?) ...[+ const SizedBox(height: 3),+ detail,+ ],+ ],+ ),+ ),+ if (news.tags > 0) ...[+ const SizedBox(width: 12),+ SwarmTags(news.tags),+ ],+ if (end != null) ...[const SizedBox(width: 12), end],+ ],+ ),+ ),+ );+ if (onTap == null) return row;+ return Material(+ color: Colors.transparent,+ child: InkWell(onTap: onTap, child: row),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_session.dart b/mobile/lib/swarm/swarm_session.dartnew file mode 100644index 000000000..db257b02b--- /dev/null+++ b/mobile/lib/swarm/swarm_session.dart@@ -0,0 +1,341 @@+import 'dart:async';++import 'package:flutter/widgets.dart';++import '../core/harness_file_store.dart';+import '../core/local_key_value_store.dart';+import '../notify/system_notices.dart';+import '../phone/voice_input_controller.dart';+import '../settings/experimental_features.dart';+import 'swarm_choices.dart';+import 'swarm_dictation.dart';+import 'swarm_face.dart';+import 'swarm_home_cache.dart';+import 'swarm_inbox.dart';+import 'swarm_notices.dart';+import 'swarm_profile.dart';+import 'swarm_request.dart';+import 'swarm_start.dart';++/// The account's Swarm on this phone: what its Swarms ask of the person+/// ([inbox]), the notices that tell them, and the answers held for Undo.+///+/// One per account and only while Swarm is on: [SwarmHost] makes it, and+/// drops it with everything it holds — notices on the lock screen included —+/// when the account leaves or Swarm is turned off.+class SwarmSession extends ChangeNotifier {+ SwarmSession({+ required this.accountId,+ required SwarmRequest request,+ SwarmUpload upload = refuseSwarmUpload,+ required SwarmNotices notices,+ Duration pollInterval = const Duration(seconds: 15),+ this.undoWindow = swarmUndoWindow,+ SwarmHomeCache? homeCache,+ LocalKeyValueStore? readMarks,+ }) : inbox = SwarmInbox(+ accountId: accountId,+ request: request,+ upload: upload,+ pollInterval: pollInterval,+ homeCache: homeCache,+ readMarks: readMarks,+ ) {+ _announcer = SwarmAnnouncer(+ notices,+ quiet: (_) => !swarmLocalNotices || _screens > 0,+ );+ inbox+ ..onArrived = announce+ ..addListener(_needsChanged);+ }++ final String accountId;+ final SwarmInbox inbox;++ /// How long a decision's answer is held before it is sent.+ final Duration undoWindow;++ late final SwarmAnnouncer _announcer;+ int _screens = 0;+ final _watching = <String, int>{};+ final _held = <String, ({int choice, Timer timer})>{};++ /// Needs whose held answer was dropped unsent: their card says so until+ /// another answer is held.+ final _dropped = <String>{};+ bool _foreground = false, _disposed = false;++ /// Harness is in front: the Swarms are read every poll, and those a screen+ /// watches every few seconds. Behind, nothing is.+ set foreground(bool value) {+ _foreground = value;+ inbox.shown = value;+ _show();+ }++ /// A Swarm screen is up: what arrives shows there, so no notice tells it.+ void enter() => _screens++;+ void leave() => _screens = _screens > 0 ? _screens - 1 : 0;++ /// Posts [need]'s notice, unless a Swarm screen is up.+ void announce(SwarmNeed need) => _announcer.announce(need);++ /// A screen shows Swarm [swarmId] closely (a conversation): it is read+ /// every few seconds while Harness is in front, until no screen does.+ void watch(String swarmId) {+ _watching[swarmId] = (_watching[swarmId] ?? 0) + 1;+ _show();+ }++ void unwatch(String swarmId) {+ final left = (_watching[swarmId] ?? 1) - 1;+ if (left > 0) {+ _watching[swarmId] = left;+ return;+ }+ _watching.remove(swarmId);+ inbox.reader(swarmId)?.shown = false;+ }++ /// Each watched Swarm's reader reads on its own only while Harness is in+ /// front; one listed again after it left is a new reader, shown here too.+ void _show() {+ for (final id in _watching.keys) {+ inbox.reader(id)?.shown = _foreground;+ }+ }++ /// The option held for [need], while its Undo window runs.+ int? held(SwarmDecisionNeed need) => _held[need.key]?.choice;++ /// [need]'s held answer was dropped before it was sent: it left the list+ /// meanwhile (the Swarm read again in full) and came back.+ bool dropped(SwarmDecisionNeed need) => _dropped.contains(need.key);++ /// Answers [need] with option [choice] once [undoWindow] has passed,+ /// unless [undo] takes it back first.+ void hold(SwarmDecisionNeed need, int choice) {+ if (_disposed) return;+ _held.remove(need.key)?.timer.cancel();+ _dropped.remove(need.key);+ if (undoWindow <= Duration.zero) {+ _send(need, choice);+ return;+ }+ _held[need.key] = (+ choice: choice,+ timer: Timer(undoWindow, () {+ if (_held.remove(need.key) case final held?) _send(need, held.choice);+ }),+ );+ notifyListeners();+ }++ void undo(SwarmDecisionNeed need) {+ if (_held.remove(need.key) case final held?) {+ held.timer.cancel();+ notifyListeners();+ }+ }++ void _send(SwarmDecisionNeed need, int choice) {+ if (_disposed) return;+ notifyListeners();+ unawaited(inbox.asks(need.swarmId)?.answer(need.decision, choice));+ }++ void _needsChanged() {+ _show();+ _announcer.settle(inbox.needs);+ // Answered somewhere else meanwhile, or out of the list while the Swarm+ // is read again: nothing is sent, and a card that comes back says so.+ final open = {for (final need in inbox.needs) need.key};+ final gone = [+ for (final key in _held.keys)+ if (!open.contains(key)) key,+ ];+ for (final key in gone) {+ _held.remove(key)!.timer.cancel();+ _dropped.add(key);+ }+ if (gone.isNotEmpty) notifyListeners();+ }++ @override+ void dispose() {+ _disposed = true;+ for (final held in _held.values) {+ held.timer.cancel();+ }+ _held.clear();+ inbox.removeListener(_needsChanged);+ _announcer.clear();+ inbox.dispose();+ super.dispose();+ }+}++/// Keeps one [SwarmSession] for the signed-in account while Settings ▸+/// Experimental ▸ Swarm is on, and none otherwise.+class SwarmHost extends ChangeNotifier {+ SwarmHost({+ required this.accountId,+ required this.account,+ required this.request,+ this.upload = refuseSwarmUpload,+ required this.notices,+ ExperimentalFeaturesStore? features,+ this.computers,+ SwarmHomeCache? homeCache,+ LocalKeyValueStore? readMarks,+ this.uploadAvatar,+ this.voice,+ this.dictation,+ }) : features = features ?? experimentalFeaturesStore,+ homeCache = homeCache ?? SwarmHomeCache.device(),+ readMarks = readMarks ?? HarnessFileStore.shared {+ account.addListener(_update);+ this.features.addListener(_update);+ computers?.addListener(_computersChanged);+ _update();+ }++ /// The signed-in account's id; null while nobody is.+ final String? Function() accountId;++ /// Tells when [accountId] may have changed.+ final Listenable account;+ final SwarmRequest request;++ /// Sends a chat's file to the backend, straight from the phone.+ final SwarmUpload upload;+ final SwarmNotices notices;+ final ExperimentalFeaturesStore features;++ /// The account's computers, for the start screens ([swarmStartView]); null+ /// where nobody handed them in, and no start screen shows.+ final SwarmComputers? computers;++ /// The last Home of the session's account, kept for a cold start; cleared+ /// when the account leaves or Swarm is turned off.+ final SwarmHomeCache homeCache;++ /// Where the session's read marks are kept on the phone: each chat's id+ /// and how far it was read, under the account and the Swarm.+ final LocalKeyValueStore readMarks;++ /// Sends an avatar photo with the phone's own sign-in; null where none can+ /// go, and only the built-in pictures are offered.+ final SwarmAvatarUpload? uploadAvatar;++ /// A new voice input for a chat's mic, which owns and disposes it — the+ /// terminal's speech-to-text; null where none can be heard, and the+ /// composer has no mic.+ final VoiceInputController Function()? voice;++ /// The phone's own speech recognizer, which shows a chat's words as they+ /// are said; null where there is none, and the mic records and has [voice]+ /// transcribe the take.+ final SwarmDictation? dictation;++ SwarmSession? session;+ bool _foreground = true;++ /// Whether Swarm was on at the last [_update]; null before the first.+ bool? _on;++ set foreground(bool value) {+ _foreground = value;+ session?.foreground = value;+ }++ /// A computer may have come up: a Swarm waiting for one reads at once.+ void _computersChanged() {+ session?.inbox.computerUp();+ notifyListeners();+ }++ void _update() {+ final on = features.isOn(PhoneExperiment.swarm);+ final wasOn = _on;+ _on = on;+ final id = on ? accountId() : null;+ if (id == session?.accountId) {+ // Swarm off with no session to end: its switch is read before the first+ // frame, so this is known, and what an earlier run kept goes. A missing+ // account is not: the signed-in shell is up before the account is read.+ if (!on && wasOn != false) unawaited(homeCache.clear());+ return;+ }+ // Signed out, another account, or Swarm turned off: nothing of it stays.+ if (session != null) {+ unawaited(homeCache.clear());+ swarmForgetAvatarImages();+ }+ session?.dispose();+ session = id == null+ ? null+ : (SwarmSession(+ accountId: id,+ request: request,+ upload: upload,+ notices: notices,+ homeCache: homeCache,+ readMarks: readMarks,+ )..foreground = _foreground);+ notifyListeners();+ }++ @override+ void dispose() {+ account.removeListener(_update);+ features.removeListener(_update);+ computers?.removeListener(_computersChanged);+ session?.dispose();+ session = null;+ super.dispose();+ }+}++/// The [SwarmHost] of the signed-in shell, for the screens under it.+class SwarmScope extends InheritedNotifier<SwarmHost> {+ const SwarmScope({+ super.key,+ required SwarmHost super.notifier,+ required super.child,+ });++ /// The account's session, or null while Swarm is off, nobody is signed in,+ /// or outside the shell.+ static SwarmSession? of(BuildContext context) => context+ .dependOnInheritedWidgetOfExactType<SwarmScope>()+ ?.notifier+ ?.session;++ /// How an avatar photo goes up ([SwarmHost.uploadAvatar]); null outside+ /// the shell or where none can.+ static SwarmAvatarUpload? uploadAvatarOf(BuildContext context) => context+ .dependOnInheritedWidgetOfExactType<SwarmScope>()+ ?.notifier+ ?.uploadAvatar;++ /// The account's computers ([SwarmHost.computers]); null outside the shell+ /// or where none were handed in.+ static SwarmComputers? computersOf(BuildContext context) => context+ .dependOnInheritedWidgetOfExactType<SwarmScope>()+ ?.notifier+ ?.computers;++ /// How a chat's mic makes its voice input ([SwarmHost.voice]); null+ /// outside the shell or where none can be heard.+ static VoiceInputController Function()? voiceOf(BuildContext context) =>+ context.dependOnInheritedWidgetOfExactType<SwarmScope>()?.notifier?.voice;++ /// The phone's own recognizer for a chat's mic ([SwarmHost.dictation]);+ /// null outside the shell or where there is none.+ static SwarmDictation? dictationOf(BuildContext context) => context+ .dependOnInheritedWidgetOfExactType<SwarmScope>()+ ?.notifier+ ?.dictation;+}diff --git a/mobile/lib/swarm/swarm_ship_row.dart b/mobile/lib/swarm/swarm_ship_row.dartnew file mode 100644index 000000000..191de1cab--- /dev/null+++ b/mobile/lib/swarm/swarm_ship_row.dart@@ -0,0 +1,452 @@+import 'dart:async';+import 'dart:math';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:url_launcher/url_launcher.dart';++import 'package:harness_mobile/shared/theme/app_icon_size.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/swarm_tokens_set_b.dart';++import 'identity.dart';+import 'model.dart';+import 'swarm_message_row.dart';+import 'swarm_session.dart';+import 'swarm_style.dart';++/// [message] is the project chat's ship line (backend superTabs/ship.ts+/// `SHIP_KIND`): linked work just became Done.+bool swarmShips(SuperTabMessage message) => message.source['kind'] == 'ship';++/// A GitHub pull request's address, and nothing else a ship line might carry+/// (the desktop's `superTabPullRequestLinks`).+final _pullRequest = RegExp(+ r'^https://github\.com/([A-Za-z0-9_-]+)/([A-Za-z0-9_.-]+)/pull/([1-9][0-9]*)$',+);++/// What a ship line says: what shipped, and who asked, built and reviewed+/// it, as ids the Swarm names; its pull requests, at most four.+class SwarmShip {+ SwarmShip.of(SuperTabMessage message)+ : title = message.source['title'] is String+ ? message.source['title'] as String+ : '',+ requesterId = message.source['requesterId'] is String+ ? message.source['requesterId'] as String+ : null,+ builderIds = _ids(message.source['builderIds']),+ reviewerIds = _ids(message.source['reviewerIds']),+ pullRequests = List.unmodifiable(+ _ids(message.source['pullRequests'])+ .where(_pullRequest.hasMatch)+ .map(Uri.parse)+ .take(4),+ );++ final String title;+ final String? requesterId;+ final List<String> builderIds, reviewerIds;+ final List<Uri> pullRequests;++ static List<String> _ids(Object? value) => List.unmodifiable([+ for (final id in value is List ? value : const [])+ ?id is String ? id : null,+ ]);+}++/// The avatars beside a ship's credits; their label's cell is as tall.+const _creditAvatar = 22.0;++/// How recent a ship still is: an older one in the history is still.+const swarmShipFresh = Duration(minutes: 2);++/// Whether [message] throws confetti as it first appears at [now]: only+/// while it is fresh, and only once per ship — [played] remembers which have+/// (the desktop's `SuperTabShipRow`).+bool swarmShipCelebrates(+ SuperTabMessage message,+ DateTime now,+ Set<String> played,+) {+ final at = message.createdAt;+ if (at == null || now.difference(at) > swarmShipFresh) return false;+ return played.add(message.id);+}++/// The project chat's line when linked work is Done, as a card in place of+/// a message (the desktop's `SuperTabShipRow`, laid out as the approved+/// mockup draws it): 🎉 and what shipped; who asked, built and reviewed it,+/// one to a line; then its pull requests. A fresh one throws confetti, once+/// per ship on this phone ([swarmShipCelebrates]).+///+/// Its people are named from the Swarm the chat belongs to; until that is+/// read, the title and links show alone.+class SwarmShipRow extends StatefulWidget {+ const SwarmShipRow({+ super.key,+ required this.message,+ this.now = DateTime.now,+ });++ final SuperTabMessage message;+ final DateTime Function() now;++ static final _played = <String>{};+ @visibleForTesting+ static void resetPlayed() => _played.clear();++ @override+ State<SwarmShipRow> createState() => _SwarmShipRowState();+}++class _SwarmShipRowState extends State<SwarmShipRow> {+ // Decided once, as the line first appears: a rebuild never cuts it short,+ // and the same line drawn again later throws none.+ late final bool _throws = swarmShipCelebrates(+ widget.message,+ widget.now(),+ SwarmShipRow._played,+ );+ late final SwarmShip _ship = SwarmShip.of(widget.message);++ /// The account's Swarms, read: the one whose chat this is names the people.+ SwarmSession? _session;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final session = SwarmScope.of(context);+ if (session == _session) return;+ _session?.inbox.removeListener(_changed);+ _session = session?..inbox.addListener(_changed);+ }++ void _changed() {+ if (mounted) setState(() {});+ }++ @override+ void dispose() {+ _session?.inbox.removeListener(_changed);+ super.dispose();+ }++ /// The Swarm read that holds this chat; null until one does.+ SuperTabSnapshot? get _snapshot {+ final inbox = _session?.inbox;+ if (inbox == null) return null;+ for (final swarm in inbox.swarms) {+ final snapshot = inbox.reader(swarm.id)?.snapshot;+ if (snapshot?.conversation(widget.message.conversationId) != null) {+ return snapshot;+ }+ }+ return null;+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final ship = _ship, snapshot = _snapshot, id = widget.message.id;+ final requester = snapshot?.people+ .where((p) => p.id == ship.requesterId)+ .firstOrNull;+ List<(String, String)> agents(List<String> ids) => [+ for (final id in ids)+ if (snapshot?.agent(id) != null) (id, snapshot!.agentName(id)),+ ];+ final credits = [+ if (requester != null)+ ('Requested by', [(requester.id, superTabPersonName(requester.email))]),+ ('Built by', agents(ship.builderIds)),+ ('Reviewed by', agents(ship.reviewerIds)),+ ].where((credit) => credit.$2.isNotEmpty).toList();+ final accent = AppPalette.accentOnSurface;+ final card = Container(+ key: ValueKey('swarm-ship-$id'),+ margin: const EdgeInsets.all(AppSpace.s),+ padding: const EdgeInsets.fromLTRB(+ AppSpace.l,+ AppSpace.m,+ AppSpace.l,+ AppSpace.l,+ ),+ decoration: BoxDecoration(+ color: accent.withValues(alpha: .10),+ borderRadius: BorderRadius.circular(AppCard.radius),+ border: Border.all(color: accent.withValues(alpha: .4)),+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const ExcludeSemantics(+ child: Text(+ '🎉',+ style: TextStyle(+ fontSize: AppIconSize.besideText,+ height: 1.2,+ ),+ ),+ ),+ const SizedBox(width: 10),+ Expanded(+ child: Text(+ 'Shipped: ${ship.title}',+ style: swarmChatText(+ 16,+ weight: FontWeight.w600,+ height: 1.4,+ ),+ ),+ ),+ ],+ ),+ if (credits.isNotEmpty) const SizedBox(height: 10),+ for (final (label, people) in credits)+ Padding(+ padding: const EdgeInsets.symmetric(vertical: AppSpace.xs),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ // As tall as an avatar and centred in it, so a label sits level+ // with the first name beside it at any text size.+ ConstrainedBox(+ constraints: const BoxConstraints(+ minWidth: 104,+ maxWidth: 104,+ minHeight: _creditAvatar,+ ),+ child: Align(+ alignment: Alignment.centerLeft,+ child: Text(+ label,+ style: swarmChatText(+ 14,+ color: AppPalette.textSecondary,+ ),+ ),+ ),+ ),+ Expanded(+ child: Wrap(+ spacing: 12,+ runSpacing: 6,+ children: [+ for (final (personId, name) in people)+ Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ SwarmAvatar(+ id: personId,+ name: name,+ size: _creditAvatar,+ ),+ const SizedBox(width: 6),+ Text(name, style: swarmChatText(15)),+ ],+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ if (ship.pullRequests.isNotEmpty) ...[+ const SizedBox(height: 10),+ Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ for (final (i, link) in ship.pullRequests.indexed)+ _PullRequestButton(+ key: ValueKey('swarm-ship-pr-$id-$i'),+ link: link,+ ),+ ],+ ),+ ],+ ],+ ),+ );+ if (!_throws) return card;+ return _Confetti(seed: id.hashCode, child: card);+ }+}++/// A pull request the ship links, as a button: its repository and number,+/// opened in the in-app browser.+class _PullRequestButton extends StatelessWidget {+ const _PullRequestButton({super.key, required this.link});++ final Uri link;++ @override+ Widget build(BuildContext context) {+ final label = '${link.pathSegments[1]} · PR #${link.pathSegments[3]}';+ return Semantics(+ button: true,+ link: true,+ label: 'Open $label',+ excludeSemantics: true,+ child: Material(+ color: AppPalette.windowBg,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(AppControl.radius),+ side: BorderSide(color: AppGlass.hair),+ ),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () {+ HapticFeedback.selectionClick();+ unawaited(launchUrl(link, mode: LaunchMode.inAppBrowserView));+ },+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 44),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.m),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(+ LucideIcons.gitPullRequest300,+ size: 16,+ color: AppPalette.textSecondary,+ ),+ const SizedBox(width: 8),+ Text(label, style: swarmChatText(14.5)),+ const SizedBox(width: 6),+ Icon(+ LucideIcons.externalLink300,+ size: 14,+ color: AppPalette.textFaint,+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}++/// A short burst of confetti over its child, once, then gone; with Reduce+/// Motion on, the child alone (the desktop's `SuperTabConfetti`).+class _Confetti extends StatefulWidget {+ const _Confetti({required this.seed, required this.child});++ final int seed;+ final Widget child;++ @override+ State<_Confetti> createState() => _ConfettiState();+}++class _ConfettiState extends State<_Confetti>+ with SingleTickerProviderStateMixin {+ late final _motion = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 2200),+ );+ late final _pieces = _Piece.burst(widget.seed);+ bool _done = false;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ if (_done || _motion.isAnimating) return;+ if (MediaQuery.disableAnimationsOf(context)) {+ _done = true;+ return;+ }+ _motion.forward().whenComplete(() {+ if (mounted) setState(() => _done = true);+ });+ }++ @override+ void dispose() {+ _motion.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => Stack(+ clipBehavior: Clip.none,+ children: [+ widget.child,+ if (!_done)+ Positioned.fill(+ child: IgnorePointer(+ child: ExcludeSemantics(+ child: CustomPaint(+ key: const ValueKey('swarm-ship-confetti'),+ painter: _ConfettiPainter(_pieces, _motion),+ ),+ ),+ ),+ ),+ ],+ );+}++class _Piece {+ const _Piece(this.x, this.drift, this.lift, this.spin, this.size, this.color);+ final double x, drift, lift, spin, size;+ final Color color;++ static List<_Piece> burst(int seed) {+ final random = Random(seed);+ return [+ for (var i = 0; i < 40; i++)+ _Piece(+ random.nextDouble(),+ (random.nextDouble() - .5) * .3,+ .4 + random.nextDouble() * .6,+ (random.nextDouble() - .5) * 12,+ 4 + random.nextDouble() * 4,+ SwarmConfetti.colors[i % SwarmConfetti.colors.length],+ ),+ ];+ }+}++class _ConfettiPainter extends CustomPainter {+ _ConfettiPainter(this.pieces, this.motion) : super(repaint: motion);+ final List<_Piece> pieces;+ final Animation<double> motion;++ @override+ void paint(Canvas canvas, Size size) {+ final t = motion.value;+ final paint = Paint();+ for (final piece in pieces) {+ // Thrown up from the card, then falling past it as it fades.+ final y = size.height * (1 - piece.lift * 4 * t * (1 - t) * 2 + t * .6);+ final x = size.width * (piece.x + piece.drift * t);+ paint.color = piece.color.withValues(alpha: (1 - t).clamp(0, 1));+ canvas+ ..save()+ ..translate(x, y)+ ..rotate(piece.spin * t)+ ..drawRect(+ Rect.fromCenter(+ center: Offset.zero,+ width: piece.size,+ height: piece.size * .5,+ ),+ paint,+ )+ ..restore();+ }+ }++ @override+ bool shouldRepaint(_ConfettiPainter old) => false;+}diff --git a/mobile/lib/swarm/swarm_start.dart b/mobile/lib/swarm/swarm_start.dartnew file mode 100644index 000000000..c0f658236--- /dev/null+++ b/mobile/lib/swarm/swarm_start.dart@@ -0,0 +1,489 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../phone/phone_sheet.dart';+import '../phone/tty.dart';+import '../phone/tty_controls.dart';+import '../settings/experimental_features.dart';+import '../shared/theme/app_space.dart';+import '../shared/theme/app_theme.dart';+import 'swarm_inbox.dart';+import 'swarm_session.dart';++/// One of the person's computers as Swarm's start screen lists it: its name,+/// and whether it is away for real (`phoneMachineAway`).+typedef SwarmComputer = ({String name, bool away});++/// What Swarm shows before there is a Swarm to show — one screen each, with+/// one button. Swarm turned off is not one of them: the app is as it was, and+/// Settings offers Swarm.+enum SwarmStart {+ /// The account has no computer at all: Connect a computer.+ noComputer,++ /// The Swarms were read, and there is none: Show me how.+ none,++ /// No Swarm, and an invitation to one waiting: Join.+ invited,++ /// No Swarm, and the invitations could not be read: Try again. Not "No+ /// Swarm yet", which would send the person to start one (#1802's review).+ invitesFailed,+}++/// Which start screen applies, from what the phone already knows: [computers]+/// as the account's list says (null until it has answered) and what [inbox]+/// read. Null when there is a Swarm to show, or nothing is known yet.+///+/// No computer answering shows no start screen: Home draws what it has —+/// what was read or kept, or rows on their way — with a card about the+/// computers (`SwarmConnectionNotice`), and the reads retry quietly+/// (`swarmRequest`). A screen in Home's place once flashed "Connect one of+/// your computers" for 10 to 25 seconds at a time with the computer connected+/// all along (owner's iPhone, 2026-10-27), and "No computer online" stayed+/// after a force-quit while the Mac was connecting (2026-10-28).+SwarmStart? swarmStart(SwarmInbox inbox, List<SwarmComputer>? computers) {+ if (computers == null) return null;+ if (computers.isEmpty) return SwarmStart.noComputer;+ if (!inbox.loaded || inbox.swarms.isNotEmpty) return null;+ if (inbox.invitations.isNotEmpty) return SwarmStart.invited;+ return inbox.invitationsFailed ? SwarmStart.invitesFailed : SwarmStart.none;+}++/// The person's computers as the start screens need them: the app's machine+/// list in the app (`AppSwarmComputers`), a stand-in in a test.+abstract interface class SwarmComputers implements Listenable {+ /// The account's computers; null until its list has answered.+ List<SwarmComputer>? get computers;++ /// A [recheck] is under way.+ bool get rechecking;++ /// Reads the list again and calls the computers that are away: Try again.+ Future<void> recheck();++ /// Opens the steps to connect a computer.+ void add(BuildContext context);+}++/// The start screen Swarm Home shows in place of its body, or null when it+/// shows its own — Home's one call. It follows the computers ([SwarmScope]);+/// the caller rebuilds it as [session]'s inbox changes.+SwarmStartView? swarmStartView(BuildContext context, SwarmSession session) {+ final computers = SwarmScope.computersOf(context);+ final start = swarmStart(session.inbox, computers?.computers);+ if (start == null || computers == null) return null;+ return SwarmStartView(start: start, session: session, computers: computers);+}++/// One start screen ([SwarmStart]), the whole of Home's body under its own+/// top bar: what is the matter in a title and a line, and one button. Shows+/// only what the phone already has: the computers' names, and an+/// invitation's Swarm by name with the role offered — nothing of the Swarm is+/// read before Join.+class SwarmStartView extends StatefulWidget {+ const SwarmStartView({+ super.key,+ required this.start,+ required this.session,+ required this.computers,+ });++ final SwarmStart start;+ final SwarmSession session;+ final SwarmComputers computers;++ @override+ State<SwarmStartView> createState() => _SwarmStartViewState();+}++class _SwarmStartViewState extends State<SwarmStartView> {+ /// Try again is looking: for the computers, then the Swarms through them.+ bool _looking = false;++ SwarmInbox get _inbox => widget.session.inbox;++ Future<void> _tryAgain() async {+ if (_looking) return;+ setState(() => _looking = true);+ try {+ await widget.computers.recheck();+ await _inbox.refresh();+ } catch (_) {+ // Nothing found: the screen stays, ready to try again.+ } finally {+ if (mounted) setState(() => _looking = false);+ }+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: Listenable.merge([_inbox, widget.computers]),+ builder: (context, _) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ return switch (widget.start) {+ SwarmStart.noComputer => _StartScreen(+ key: const ValueKey('swarm-start-no-computer'),+ mark: const _Mark(icon: LucideIcons.monitor300),+ title: 'No computer yet',+ line:+ 'Swarm reaches your team through your computers. Connect one '+ 'to start.',+ primary: TtyPrimaryButton(+ label: 'Connect a computer',+ onPressed: () => widget.computers.add(context),+ ),+ ),+ SwarmStart.none => _StartScreen(+ key: const ValueKey('swarm-start-none'),+ mark: const _Mark(icon: LucideIcons.network300),+ title: 'No Swarm yet',+ line:+ 'A Swarm is a team of agents that works on your projects. Start '+ 'one on your computer and it shows up here.',+ primary: TtyPrimaryButton(+ label: 'Show me how',+ onPressed: () => unawaited(_showHow(context)),+ ),+ // The invitations list is the account's email's: an invite to it+ // comes here by itself, and there is no link to open.+ quiet: Padding(+ padding: const EdgeInsets.only(top: AppSpace.m),+ child: Text(+ 'Invites to your email show up here.',+ textAlign: TextAlign.center,+ style: tty.style(color: tty.dim, size: TtySize.meta),+ ),+ ),+ ),+ SwarmStart.invited => _invited(tty),+ SwarmStart.invitesFailed => _StartScreen(+ key: const ValueKey('swarm-start-invites-failed'),+ mark: const _Mark(icon: LucideIcons.mailWarning300),+ title: "Couldn't check invitations",+ line:+ "Swarm couldn't read the invitations to your email just now. "+ 'You may have one waiting.',+ primary: TtyPrimaryButton(+ label: 'Try again',+ busy: _looking,+ busyLabel: 'Checking…',+ onPressed: () => unawaited(_tryAgain()),+ ),+ ),+ };+ },+ );++ Widget _invited(Tty tty) {+ // Put off since this screen was chosen: Home picks again at its next+ // build, so this one draws nothing meanwhile.+ if (_inbox.invitations.isEmpty) return const SizedBox.shrink();+ final invitation = _inbox.invitations.first;+ final name = invitation.name.trim();+ return _StartScreen(+ key: const ValueKey('swarm-start-invited'),+ mark: _Mark(letter: name.isEmpty ? '?' : name.characters.first),+ eyebrow: "You're invited to",+ title: name,+ line: switch (invitation.role) {+ 'collaborator' => 'You can collaborate',+ 'viewer' => 'You can view',+ _ => null,+ },+ more: [+ if (_inbox.joinError case final error?)+ Text(+ error,+ key: const ValueKey('swarm-join-error'),+ style: tty.style(color: tty.red, size: TtySize.meta),+ ),+ ],+ primary: TtyPrimaryButton(+ label: 'Join $name',+ busy: _inbox.joining.contains(invitation.inviteId),+ busyLabel: 'Joining…',+ onPressed: () => unawaited(_inbox.join(invitation)),+ ),+ quiet: TtyTextButton(+ label: 'Not now',+ onPressed: () => _inbox.notNow(invitation),+ ),+ );+ }+}++/// How to start a Swarm, in the three steps the desktop takes: a sheet over+/// No Swarm yet, closed with Got it.+Future<void> _showHow(BuildContext context) => Navigator.of(+ context,+ rootNavigator: true,+).push(phoneSheetRoute<void>(context, builder: (_) => const _HowSheet()));++class _HowSheet extends StatelessWidget {+ const _HowSheet();++ static const _steps = [+ 'Open Harness on your computer.',+ // The desktop's New Swarm (desktop/lib/shortcuts/app_shortcuts.dart).+ 'Press ⌘S.',+ 'Name it and add your first project.',+ ];++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return SafeArea(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.l,+ AppSpace.screenInset,+ AppSpace.m,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const TtyText(+ 'Start a Swarm',+ size: TtySize.title,+ weight: FontWeight.w600,+ ),+ const SizedBox(height: 18),+ for (final (index, step) in _steps.indexed)+ Padding(+ padding: const EdgeInsets.only(bottom: AppSpace.l),+ child: Row(+ children: [+ Container(+ width: 30,+ height: 30,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: ttyRaised(tty),+ shape: BoxShape.circle,+ ),+ child: TtyText(+ '${index + 1}',+ size: TtySize.meta,+ color: tty.dim,+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Text(step, style: tty.style(size: TtySize.row)),+ ),+ ],+ ),+ ),+ Text(+ "It shows up here when it's ready.",+ style: tty.style(color: tty.dim, size: TtySize.row),+ ),+ const SizedBox(height: 18),+ TtyPrimaryButton(+ label: 'Got it',+ onPressed: () => Navigator.of(context).pop(),+ ),+ ],+ ),+ ),+ );+ }+}++/// Swarm turned off: what it does, in three lines, and Turn on Swarm. The+/// one way to it is Settings ▸ Experimental, while Swarm is off.+class SwarmIntroPage extends StatelessWidget {+ const SwarmIntroPage({super.key, required this.features});++ final ExperimentalFeaturesStore features;++ static const _ticks = [+ 'See what needs you',+ 'Answer in one tap',+ 'Brainstorm with your Buddy',+ ];++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ void back() => unawaited(Navigator.of(context).maybePop());+ return Scaffold(+ backgroundColor: tty.ground,+ body: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Align(+ alignment: Alignment.centerLeft,+ child: TtyBackButton(onPressed: back),+ ),+ Expanded(+ child: _StartScreen(+ mark: const _Mark(icon: LucideIcons.network300),+ title: 'Your team of agents, on your phone',+ more: [+ for (final tick in _ticks)+ Padding(+ padding: const EdgeInsets.only(bottom: AppSpace.m),+ child: Row(+ children: [+ Icon(+ LucideIcons.check300,+ size: 20,+ color: tty.green,+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Text(+ tick,+ style: tty.style(size: TtySize.row),+ ),+ ),+ ],+ ),+ ),+ ],+ primary: TtyPrimaryButton(+ label: 'Turn on Swarm',+ onPressed: () {+ // On at once; only the memory for the next launch waits.+ unawaited(features.set(PhoneExperiment.swarm, true));+ back();+ },+ ),+ quiet: TtyTextButton(label: 'Not now', onPressed: back),+ ),+ ),+ ],+ ),+ ),+ );+ }+}++/// A start screen's layout: its mark, an eyebrow over the title, a line,+/// what [more] it shows, then its one button at the foot, with [quiet] under+/// it.+class _StartScreen extends StatelessWidget {+ const _StartScreen({+ super.key,+ required this.mark,+ required this.title,+ required this.primary,+ this.eyebrow,+ this.line,+ this.more = const [],+ this.quiet,+ });++ final Widget mark;+ final String title;+ final String? eyebrow, line;+ final List<Widget> more;+ final Widget primary;+ final Widget? quiet;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Expanded(+ child: SingleChildScrollView(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xl,+ AppSpace.xl,+ AppSpace.xl,+ AppSpace.l,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ mark,+ const SizedBox(height: 18),+ if (eyebrow case final eyebrow?) ...[+ Text(+ eyebrow,+ style: tty.style(color: tty.dim, size: TtySize.row),+ ),+ const SizedBox(height: 4),+ ],+ // Wrapped, not one line as a [TtyText]: an invitation's+ // name is as long as its owner made it.+ Text(+ title,+ style: tty.style(+ size: TtySize.display,+ weight: FontWeight.w600,+ ),+ ),+ if (line case final line?) ...[+ const SizedBox(height: 12),+ Text(+ line,+ style: tty.style(color: tty.dim, size: TtySize.row),+ ),+ ],+ if (more.isNotEmpty) const SizedBox(height: 20),+ ...more,+ ],+ ),+ ),+ ),+ Padding(+ padding: EdgeInsets.fromLTRB(+ AppSpace.screenInset,+ AppSpace.m,+ AppSpace.screenInset,+ AppSpace.m + MediaQuery.paddingOf(context).bottom,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [primary, ?quiet],+ ),+ ),+ ],+ );+ }+}++/// A start screen's mark: a glyph, or an invitation's first letter, on a+/// raised square.+class _Mark extends StatelessWidget {+ const _Mark({this.icon, this.letter});++ final IconData? icon;+ final String? letter;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Container(+ width: 64,+ height: 64,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: ttyRaised(tty),+ borderRadius: BorderRadius.circular(AppCard.radius),+ ),+ child: icon != null+ ? Icon(icon, size: 30, color: tty.text)+ : TtyText(+ letter ?? '',+ size: TtySize.display,+ weight: FontWeight.w600,+ ),+ );+ }+}diff --git a/mobile/lib/swarm/swarm_style.dart b/mobile/lib/swarm/swarm_style.dartnew file mode 100644index 000000000..6310e6edf--- /dev/null+++ b/mobile/lib/swarm/swarm_style.dart@@ -0,0 +1,618 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/tty.dart';+import 'package:harness_mobile/shared/theme/app_ink.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/shared/theme/swarm_tokens_set_b.dart';+import 'package:harness_mobile/shared/widgets/skeleton.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'profile_model.dart';+import 'swarm_face.dart';+import 'team_glance.dart';++/// The pieces Swarm's screens are drawn with, as the approved prototype v2+/// draws them: a top bar with its title beside the menu or back button,+/// captions in sentence case, cards of rows, round avatars, a project's+/// initial in a tile, filled counts, and buttons a thumb can find. Every+/// colour is one of the app's own tokens.++/// The colour of an agent's state: working green, waiting yellow, down red.+Color swarmStateColor(SwarmAgentState state) => switch (state) {+ SwarmAgentState.working => AppColors.success,+ SwarmAgentState.waiting || SwarmAgentState.stuck => AppColors.warning,+ SwarmAgentState.down => AppColors.danger,+ SwarmAgentState.limited || SwarmAgentState.idle => AppPalette.textFaint,+};++/// The colour [id]'s avatar takes, the same on every screen and every run.+Color swarmAvatarColor(String id) {+ // FNV-1a: String.hashCode is not promised to be stable across runs.+ var hash = 0x811c9dc5;+ for (final unit in id.codeUnits) {+ hash = ((hash ^ unit) * 0x01000193) & 0xffffffff;+ }+ return AppPalette.avatarPalette[hash % AppPalette.avatarPalette.length];+}++String _initial(String name) {+ final trimmed = name.trim();+ return trimmed.isEmpty ? '?' : trimmed.characters.first.toUpperCase();+}++/// A screen's top bar: the menu or back button ([leading], a 44-point+/// [SwarmIconButton]) 4 points in from the edge, the title 4 points beside it+/// in the terminal's face, and under it maybe one quiet line.+class SwarmTopBar extends StatelessWidget {+ const SwarmTopBar({+ super.key,+ required this.leading,+ required this.title,+ this.subtitle,+ });++ final Widget leading;+ final String title;+ final String? subtitle;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ return ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 52),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ AppSpace.xs,+ AppSpace.s,+ AppSpace.xs,+ ),+ child: Row(+ children: [+ leading,+ const SizedBox(width: 4),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ title,+ key: const ValueKey('swarm-title'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tty+ .style(size: 17, weight: FontWeight.w600)+ .copyWith(height: 1.25),+ ),+ if (subtitle case final subtitle?)+ Text(+ subtitle,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ );+ }+}++/// A caption over a card, in sentence case, with maybe a count at its right.+class SwarmCaption extends StatelessWidget {+ const SwarmCaption(this.text, {super.key, this.count, this.first = false});++ final String text;++ /// What waits on the person, in the warning colour; null shows none.+ final int? count;++ /// The first thing on the screen: less room above it.+ final bool first;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ return Padding(+ padding: EdgeInsets.fromLTRB(+ AppSpace.xs,+ first ? AppSpace.s : AppSpace.xl,+ AppSpace.xs,+ AppSpace.s,+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.baseline,+ textBaseline: TextBaseline.alphabetic,+ children: [+ Expanded(+ child: Text(+ text,+ style: AppType.caption(+ color: Color.lerp(+ AppPalette.textFaint,+ AppPalette.textSecondary,+ .5,+ ),+ ),+ ),+ ),+ if (count case final count? when count > 0)+ Text(+ '$count',+ key: const ValueKey('swarm-needs-count'),+ style: tty+ .style(size: 12.5, color: AppColors.warning)+ .copyWith(height: 1),+ ),+ ],+ ),+ );+ }+}++/// A card of rows, a hairline between them.+class SwarmGroup extends StatelessWidget {+ const SwarmGroup({super.key, required this.children});++ final List<Widget> children;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return ClipRRect(+ borderRadius: BorderRadius.circular(AppCard.radius),+ child: ColoredBox(+ color: AppGlass.rowFill,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final (i, child) in children.indexed) ...[+ if (i > 0) Divider(height: 1, thickness: 1, color: AppGlass.hair),+ child,+ ],+ ],+ ),+ ),+ );+ }+}++/// A row on its way, in the shape of the row it stands for: a mark at its+/// left, a bar for its title and a longer one for the line under it, each as+/// tall as the line it stands for ([SkeletonText]), so nothing moves when the+/// row arrives. It stands for a card's row (`SwarmRow`) with a line under its+/// title, or its title alone ([titleOnly]); the drawer draws its own.+class SwarmSkeletonRow extends StatelessWidget {+ const SwarmSkeletonRow({+ super.key,+ this.round = false,+ this.titleOnly = false,+ this.width = .45,+ });++ /// An avatar's round mark rather than a project's tile.+ final bool round;++ /// The row it stands for has no line under its title: a project's.+ final bool titleOnly;++ /// The title bar's share of the row's words.+ final double width;++ @override+ Widget build(BuildContext context) {+ // The real rows' metrics.+ final title = AppType.label(height: 1.3);+ final line = AppType.caption(height: 1.35);+ return ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 56),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ vertical: AppSpace.m,+ ),+ child: Row(+ children: [+ Skeleton(+ width: 32,+ height: 32,+ radius: 8,+ shape: round ? BoxShape.circle : BoxShape.rectangle,+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ SkeletonText(style: title, widthFactor: width),+ if (!titleOnly) ...[+ const SizedBox(height: 3),+ SkeletonText(+ style: line,+ widthFactor: (width + .25).clamp(0, 1),+ ),+ ],+ ],+ ),+ ),+ ],+ ),+ ),+ );+ }+}++/// [rows] rows on their way ([SwarmSkeletonRow]), in a card ([SwarmGroup]),+/// fading towards the last; one "Loading" to a screen reader. Keyed [id]; its+/// row `i`, `$id-$i`.+class SwarmSkeletonRows extends StatelessWidget {+ SwarmSkeletonRows({+ required this.id,+ this.rows = 2,+ this.round = false,+ this.titleOnly = false,+ }) : super(key: ValueKey(id));++ final String id;+ final int rows;++ /// Avatars' round marks rather than projects' tiles.+ final bool round;++ /// Rows with no line under their titles ([SwarmSkeletonRow.titleOnly]).+ final bool titleOnly;++ @override+ Widget build(BuildContext context) {+ final children = [+ for (var i = 0; i < rows; i++)+ Opacity(+ opacity: skeletonFade(i, rows, depth: .4),+ child: SwarmSkeletonRow(+ key: ValueKey('$id-$i'),+ round: round,+ titleOnly: titleOnly,+ width: i.isEven ? .45 : .6,+ ),+ ),+ ];+ return SkeletonBlock(child: SwarmGroup(children: children));+ }+}++/// A person's or an agent's round mark: their picture, or their initial on+/// their colour; a person's status emoji at its corner while it lasts.+class SwarmAvatar extends StatelessWidget {+ const SwarmAvatar({+ super.key,+ required this.id,+ required this.name,+ this.size = 32,+ this.ring,+ this.picture,+ this.status,+ });++ final String id, name;+ final double size;++ /// A ring of this colour around it, where avatars overlap.+ final Color? ring;++ /// What they chose to wear; null wears the initial.+ final SuperTabAvatarPicture? picture;++ /// A person's status; null for an agent.+ final SuperTabPersonStatus? status;++ @override+ Widget build(BuildContext context) {+ final color = swarmAvatarColor(id);+ final face = SwarmFace(+ picture: picture,+ size: size,+ tint: color,+ fallback: Container(+ width: size,+ height: size,+ alignment: Alignment.center,+ decoration: BoxDecoration(color: color, shape: BoxShape.circle),+ child: Text(+ _initial(name),+ style: TextStyle(+ color: AppInk.onFill,+ fontSize: size >= 32 ? 13.5 : 11,+ fontWeight: FontWeight.w600,+ height: 1,+ ),+ ),+ ),+ );+ return SwarmStatusFace(+ name: name,+ size: size,+ status: status,+ face: ring == null+ ? face+ : DecoratedBox(+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ border: Border.all(+ color: ring!,+ width: 2,+ strokeAlign: BorderSide.strokeAlignOutside,+ ),+ ),+ child: face,+ ),+ );+ }+}++/// A project's mark: its initial in a rounded tile.+class SwarmProjectTile extends StatelessWidget {+ const SwarmProjectTile(this.name, {super.key});++ final String name;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final tty = Tty.of(context);+ return Container(+ width: 32,+ height: 32,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: AppPalette.swarmSearchSurface,+ borderRadius: BorderRadius.circular(AppCard.insetRadius),+ ),+ child: Text(+ _initial(name).toLowerCase(),+ style: tty+ .style(+ size: 14,+ weight: FontWeight.w600,+ color: AppPalette.swarmAccent,+ )+ .copyWith(height: 1),+ ),+ );+ }+}++/// The Lead's tags still waiting on the person in a chat or a project, at+/// its row's trailing edge: "@2" in the warning ink, said in words (desktop+/// design system: Mentions).+class SwarmTags extends StatelessWidget {+ const SwarmTags(this.count, {super.key});++ final int count;++ @override+ Widget build(BuildContext context) => Semantics(+ label: count == 1 ? '1 mention' : '$count mentions',+ excludeSemantics: true,+ child: Text(+ '@$count',+ maxLines: 1,+ style: AppType.caption(+ color: AppColors.warning,+ fontWeight: AppFont.semibold,+ fontFeatures: const [FontFeature.tabularFigures()],+ ),+ ),+ );+}++/// A count in a filled circle: blue, or yellow for what waits on the person.+class SwarmBadge extends StatelessWidget {+ const SwarmBadge(this.count, {super.key, this.warn = false});++ final int count;+ final bool warn;++ @override+ Widget build(BuildContext context) => Container(+ constraints: const BoxConstraints(minWidth: 22, minHeight: 22),+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.s),+ alignment: Alignment.center,+ decoration: ShapeDecoration(+ color: warn ? AppColors.warning : AppPalette.accent,+ shape: const StadiumBorder(),+ ),+ child: Text(+ '$count',+ style: AppType.caption(+ color: warn ? SwarmInk.onWarning : AppInk.onFill,+ fontWeight: AppFont.semibold,+ height: 1,+ ),+ ),+ );+}++/// How a [SwarmButton] is drawn.+enum SwarmButtonStyle {+ /// A quiet button on a field, rimmed: a decision's option.+ plain,++ /// The screen's one main action, filled.+ fill,++ /// Words alone, in the accent: the second way out.+ link,+}++/// A button at least 44 points tall, in the app's sans face.+class SwarmButton extends StatelessWidget {+ const SwarmButton({+ super.key,+ required this.label,+ required this.onPressed,+ this.style = SwarmButtonStyle.plain,+ this.icon,+ this.wide = false,+ this.busy = false,+ this.busyLabel,+ });++ final String label;+ final VoidCallback? onPressed;+ final SwarmButtonStyle style;+ final IconData? icon;++ /// The whole width, taller and bolder: a screen's main action.+ final bool wide;++ /// Working: a spinner and [busyLabel], and taps do nothing.+ final bool busy;+ final String? busyLabel;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final (fill, ink, rim) = switch (style) {+ SwarmButtonStyle.plain => (+ AppPalette.swarmSearchSurface,+ AppPalette.textPrimary,+ AppGlass.hair,+ ),+ SwarmButtonStyle.fill => (AppPalette.accent, AppInk.onFill, null),+ SwarmButtonStyle.link => (null, AppPalette.swarmAccent, null),+ };+ final enabled = onPressed != null && !busy;+ final text = TextStyle(+ color: ink,+ fontSize: wide ? 16 : 15,+ fontWeight: wide ? FontWeight.w600 : FontWeight.w500,+ height: 1.25,+ );+ return Semantics(+ button: true,+ enabled: enabled,+ label: busy ? busyLabel ?? label : label,+ excludeSemantics: true,+ child: Material(+ color: fill ?? Colors.transparent,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(AppControl.radius),+ side: rim == null ? BorderSide.none : BorderSide(color: rim),+ ),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: enabled+ ? () {+ HapticFeedback.selectionClick();+ onPressed!();+ }+ : null,+ child: ConstrainedBox(+ constraints: BoxConstraints(minHeight: wide ? 52 : 44),+ child: Padding(+ padding: EdgeInsets.symmetric(+ horizontal: style == SwarmButtonStyle.link+ ? AppSpace.m+ : AppSpace.l,+ vertical: AppSpace.s,+ ),+ child: Row(+ mainAxisSize: wide ? MainAxisSize.max : MainAxisSize.min,+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ if (busy) ...[+ SizedBox.square(+ dimension: 18,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ color: ink,+ backgroundColor: ink.withValues(alpha: .35),+ ),+ ),+ const SizedBox(width: 8),+ ] else if (icon case final icon?) ...[+ Icon(icon, size: 20, color: ink),+ const SizedBox(width: 8),+ ],+ Flexible(+ child: Text(+ busy ? busyLabel ?? label : label,+ textAlign: TextAlign.center,+ style: text,+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}++/// A round 44-point button holding one glyph: the drawer's close, the top+/// bar's menu and back ([size] 24 there).+class SwarmIconButton extends StatelessWidget {+ const SwarmIconButton({+ super.key,+ required this.icon,+ required this.label,+ required this.onPressed,+ this.size = 22,+ });++ final IconData icon;+ final String label;+ final VoidCallback onPressed;+ final double size;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Semantics(+ button: true,+ label: label,+ excludeSemantics: true,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ HapticFeedback.selectionClick();+ onPressed();+ },+ child: SizedBox.square(+ dimension: 44,+ child: Icon(icon, size: size, color: AppPalette.textPrimary),+ ),+ ),+ );+ }+}++/// A Swarm page's back, in its top bar ([SwarmTopBar]); keyed as the app's+/// other back buttons are.+class SwarmBackButton extends StatelessWidget {+ const SwarmBackButton({super.key, required this.onPressed});++ final VoidCallback onPressed;++ @override+ Widget build(BuildContext context) => SwarmIconButton(+ key: const ValueKey('tty-back'),+ icon: LucideIcons.chevronLeft300,+ size: 24,+ label: 'Back',+ onPressed: onPressed,+ );+}diff --git a/mobile/lib/swarm/swarm_task_status.dart b/mobile/lib/swarm/swarm_task_status.dartnew file mode 100644index 000000000..1fef6ef21--- /dev/null+++ b/mobile/lib/swarm/swarm_task_status.dart@@ -0,0 +1,342 @@+import 'dart:async';+import 'dart:math' as math;++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import 'identity.dart';+import 'model.dart';++/// A person of [snapshot] as the Swarm names them, for a task's "Waiting on+/// …" ([swarmTaskStatus]); null for anyone the read does not hold, or holds+/// with no email (a Home kept for a cold start), so a task in one Swarm never+/// names a person from another.+String? Function(String personId) swarmTaskPersonName(+ SuperTabSnapshot snapshot,+) =>+ (personId) =>+ switch (snapshot.people.where((p) => p.id == personId).firstOrNull) {+ final person? when person.email.isNotEmpty => superTabPersonName(+ person.email,+ ),+ _ => null,+ };++/// A task's mark, named as the desktop's activity marks are+/// (`desktop/lib/super_tabs/task_status.dart`), drawn on the phone as a+/// dot in its colour ([swarmTaskMarkColor]).+enum SwarmTaskMark { working, needsInput, starting, failed, unknown }++/// The colour of a task's dot, from the phone's tokens: working green,+/// waiting or starting yellow, stuck red, queued faint — as an agent's state+/// is drawn ([swarmStateColor]).+Color swarmTaskMarkColor(SwarmTaskMark mark) => switch (mark) {+ SwarmTaskMark.working => AppColors.success,+ SwarmTaskMark.needsInput || SwarmTaskMark.starting => AppColors.warning,+ SwarmTaskMark.failed => AppColors.danger,+ SwarmTaskMark.unknown => AppPalette.textFaint,+};++/// A task's status: its mark, and its line in three parts, so a row too+/// narrow for all of it cuts the [reason] and never the [age]: ages are what+/// tell a stuck task from a new one. [pm] is what the PM did once the task+/// got here, and when. The desktop's `SuperTabTaskStatus`.+typedef SwarmTaskStatus = ({+ SwarmTaskMark mark,+ String reason,+ String age,+ String? pm,+ DateTime since,+ DateTime? pmAt,+});++/// The line as one string.+String swarmTaskStatusText(SwarmTaskStatus status) =>+ '${status.reason}${status.age}${status.pm == null ? '' : ' · ${status.pm}'}';++/// "12s", "4m", "3h", "2d", as the desktop's `superTabAgoShort`.+String _short(Duration age) {+ if (age.inSeconds < 60) return '${math.max(0, age.inSeconds)}s';+ if (age.inMinutes < 60) return '${age.inMinutes}m';+ if (age.inHours < 24) return '${age.inHours}h';+ return '${age.inDays}d';+}++String _span(Duration age) => age.inMinutes < 1 ? '<1m' : _short(age);++String _ago(Duration age) =>+ age.inMinutes < 1 ? 'just now' : '${_short(age)} ago';++DateTime _at(num ms) =>+ DateTime.fromMillisecondsSinceEpoch(ms.toInt(), isUtc: true);++/// Whether a task is moving, waiting on purpose and for what, or stuck, and+/// what the PM did about it: the desktop's `superTabTaskStatus`, word for+/// word (desktop parity in swarm_task_status_test). The server records the+/// state (backend liveness.ts); a working task has none, and its time is its+/// agent's last progress. Null for anything else: finished work, a group+/// without work, a wait an older backend sent no state for — and, where the+/// desktop would throw, a state whose time or kind is not what the server+/// sends: the phone draws nothing rather than a guess.+///+/// It reads [group] alone. A person waited on is named by [personName],+/// which looks only in the read [group] came with; anyone it does not name+/// is "a person".+SwarmTaskStatus? swarmTaskStatus(+ SuperTabConversation group,+ DateTime now, {+ String? Function(String personId)? personName,+}) {+ final assignment = group.assignment;+ final liveness = group.liveness;+ if (liveness == null) {+ final progress = assignment?['progressAt'];+ if (!const {'working', 'planned'}.contains(assignment?['status']) ||+ progress is! num) {+ return null;+ }+ final since = _at(progress);+ return (+ mark: SwarmTaskMark.working,+ reason: 'Working',+ age: ' · ${_ago(now.difference(since))}',+ pm: null,+ since: since,+ pmAt: null,+ );+ }+ final sinceMs = liveness['since'];+ if (sinceMs is! num) return null;+ final since = _at(sinceMs);+ final result = switch (assignment?['result']) {+ final String text when text.trim().isNotEmpty => text.trim(),+ _ => null,+ };+ // What the PM did once the task got here: earlier actions are not handling+ // it.+ final acted = group.leadAction;+ final pmAt = switch (acted?['at']) {+ final num at when at >= sinceMs => _at(at),+ _ => null,+ };+ final pmDid = pmAt == null+ ? null+ : switch (acted!['kind']) {+ 'assign' => 'PM reassigned it',+ 'route' || 'start' => 'PM retrying',+ 'post' => 'PM posted',+ _ => null,+ };+ final personId = switch (liveness['personId']) {+ final String id => id,+ _ => null,+ };+ final (mark, reason) = switch ((liveness['state'], liveness['why'])) {+ ('waiting', 'person') => (+ SwarmTaskMark.needsInput,+ [+ 'Waiting on ${(personId == null ? null : personName?.call(personId)) ?? 'a person'}',+ ?result,+ ].join(' · '),+ ),+ ('waiting', 'review') => (SwarmTaskMark.needsInput, 'Waiting for review'),+ ('waiting', 'revision') => (+ SwarmTaskMark.needsInput,+ 'Waiting for the new revision',+ ),+ ('waiting', 'blocked') => (+ SwarmTaskMark.needsInput,+ ['Blocked', ?result].join(' · '),+ ),+ ('waiting', 'queued') => (SwarmTaskMark.unknown, 'Queued: no free machine'),+ ('waiting', 'starting') => (SwarmTaskMark.starting, 'Starting its agent'),+ ('quiet', _) => (SwarmTaskMark.failed, 'Quiet'),+ ('orphaned', 'removed') => (+ SwarmTaskMark.failed,+ 'Stuck: its agent was removed',+ ),+ ('orphaned', 'lost') => (SwarmTaskMark.failed, 'Stuck: its agent stopped'),+ ('orphaned', 'start-failed') => (+ SwarmTaskMark.failed,+ 'Stuck: its agent could not start',+ ),+ ('orphaned', _) => (+ SwarmTaskMark.failed,+ 'Stuck: its agent has not started',+ ),+ _ => (null, ''),+ };+ if (mark == null) return null;+ final span = _span(now.difference(since));+ return (+ mark: mark,+ reason: reason,+ // As the mockup reads: "Quiet 34m", every other state "… · 12m".+ age: liveness['state'] == 'quiet' ? ' $span' : ' · $span',+ pm: pmDid == null ? null : '$pmDid ${_ago(now.difference(pmAt!))}',+ since: since,+ pmAt: pmDid == null ? null : pmAt,+ );+}++/// When an age [from] shows next reads differently: its next minute, hour or+/// day.+DateTime _nextChange(DateTime from, DateTime now) {+ final age = now.difference(from);+ final step = age.inHours < 1+ ? const Duration(minutes: 1)+ : age.inDays < 1+ ? const Duration(hours: 1)+ : const Duration(days: 1);+ return from.add(+ step * (math.max(0, age.inMicroseconds) ~/ step.inMicroseconds + 1),+ );+}++/// The line under a task's row: its dot, then its words — the reason cut+/// first, the age always whole, what the PM did in the room left — kept+/// current by one timer of its own, cancelled with the row, that wakes when+/// one of its ages would read differently. [lead] goes before the reason and+/// gives way with it, as a project's work row names its agent. Nothing when+/// the task has no status ([swarmTaskStatus]).+class SwarmTaskLine extends StatefulWidget {+ const SwarmTaskLine(this.group, {super.key, this.personName, this.lead});++ final SuperTabConversation group;+ final String? Function(String personId)? personName;+ final String? lead;++ @override+ State<SwarmTaskLine> createState() => _SwarmTaskLineState();+}++class _SwarmTaskLineState extends State<SwarmTaskLine> {+ Timer? _timer;++ @override+ void dispose() {+ _timer?.cancel();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final now = clock.now();+ final status = swarmTaskStatus(+ widget.group,+ now,+ personName: widget.personName,+ );+ _timer?.cancel();+ _timer = null;+ if (status == null) return const SizedBox.shrink();+ final next = [+ _nextChange(status.since, now),+ if (status.pmAt case final pmAt?) _nextChange(pmAt, now),+ ].reduce((a, b) => a.isBefore(b) ? a : b);+ _timer = Timer(next.difference(now) + const Duration(milliseconds: 1), () {+ if (mounted) setState(() {});+ });+ final style = AppType.caption(+ color: AppPalette.textSecondary,+ height: 1.35,+ );+ const dot = '● ';+ final reason = widget.lead == null+ ? status.reason+ : '${widget.lead} · ${status.reason}';+ final pm = status.pm == null ? null : ' · ${status.pm}';+ final id = widget.group.id;+ return LayoutBuilder(+ key: ValueKey('swarm-task-line-$id'),+ builder: (context, constraints) {+ final (reasonWidth, pmWidth) = _widths(+ context,+ style,+ room: constraints.maxWidth,+ whole: [dot, status.age],+ reason: reason,+ pm: pm,+ );+ Widget part(String text, double? width) => SizedBox(+ width: width,+ child: Text(+ text,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: style,+ ),+ );+ return Row(+ children: [+ // The words say what the dot shows: colour is never the only+ // signal.+ ExcludeSemantics(+ child: Text(+ dot,+ key: ValueKey('swarm-task-mark-$id'),+ style: style.copyWith(color: swarmTaskMarkColor(status.mark)),+ ),+ ),+ part(reason, reasonWidth),+ Text(status.age, maxLines: 1, softWrap: false, style: style),+ if (pm != null) part(pm, pmWidth),+ ],+ );+ },+ );+ }++ /// The widths [reason] and [pm] get of [room] once the [whole] parts have+ /// theirs: their own when the line fits. When it does not, they share+ /// what is left, and one that needs less than half leaves the rest to the+ /// other, so a short reason never cuts what the PM did, nor the other way+ /// round. Measured as their [Text]s lay them out.+ static (double, double) _widths(+ BuildContext context,+ TextStyle style, {+ required double room,+ required List<String> whole,+ required String reason,+ required String? pm,+ }) {+ var effective = DefaultTextStyle.of(context).style.merge(style);+ if (MediaQuery.boldTextOf(context)) {+ effective = effective.merge(const TextStyle(fontWeight: FontWeight.bold));+ }+ final scaler = MediaQuery.textScalerOf(context);+ final direction = Directionality.maybeOf(context) ?? TextDirection.ltr;+ double measure(String text) {+ final painter = TextPainter(+ text: TextSpan(text: text, style: effective),+ textDirection: direction,+ textScaler: scaler,+ maxLines: 1,+ )..layout();+ final width = painter.width.ceilToDouble();+ painter.dispose();+ return width;+ }++ final r = measure(reason);+ final p = pm == null ? 0.0 : measure(pm);+ if (!room.isFinite) return (r, p);+ final left = math.max(+ 0.0,+ room - whole.fold<double>(0, (sum, text) => sum + measure(text)),+ );+ if (r + p <= left) return (r, p);+ final half = left / 2;+ final reasonWidth = r <= half+ ? r+ : p <= half+ ? left - p+ : half;+ return (reasonWidth, math.min(p, left - reasonWidth));+ }+}diff --git a/mobile/lib/swarm/swarm_unread.dart b/mobile/lib/swarm/swarm_unread.dartnew file mode 100644index 000000000..0099a1bc6--- /dev/null+++ b/mobile/lib/swarm/swarm_unread.dart@@ -0,0 +1,64 @@+import 'model.dart';+import 'swarm_asks.dart';+import 'swarm_reader.dart';++/// What a row says is new in a chat or a project (desktop design system,+/// People and conversations in lists): unread, its name in bold, with no dot;+/// the Lead's tags still waiting on the person, bold too, with an `@N` count+/// of them at its trailing edge ([tags]).+typedef SwarmRowNews = ({bool bold, int tags});++/// Nothing new.+const SwarmRowNews swarmNoNews = (bold: false, tags: 0);++/// [group]'s row: bold while it is unread ([SwarmReader.readMarks]) or holds+/// tags still waiting ([asks]), with their count.+SwarmRowNews swarmChatNews(+ SwarmReader reader,+ SwarmAsks? asks,+ SuperTabConversation group,+) {+ var tags = 0;+ for (final mention in asks?.mentions ?? const <SuperTabMention>[]) {+ if (mention.conversationId == group.id) tags++;+ }+ final unread = reader.readMarks?.unread(group) ?? false;+ return (bold: unread || tags > 0, tags: tags);+}++/// Each project's row with something new, by project id: bold while its+/// project chat or any of its open work is unread, as the desktop's sidebar+/// reads a project — never for closed work, a private chat or the person's+/// Buddy chat, which has a row of its own — or while tags wait in it, with+/// the count of all of them. One pass over the Swarm's chats for every+/// project.+Map<String, SwarmRowNews> swarmProjectNews(+ SwarmReader reader,+ SwarmAsks? asks,+) {+ final snapshot = reader.snapshot, marks = reader.readMarks;+ if (snapshot == null) return const {};+ final unread = <String>{};+ if (marks != null) {+ for (final group in snapshot.conversations) {+ if (group.closed ||+ group.audience != null ||+ reader.buddies.chatOwners.containsKey(group.id) ||+ unread.contains(group.projectId)) {+ continue;+ }+ if (marks.unread(group)) unread.add(group.projectId);+ }+ }+ final tags = <String, int>{};+ for (final mention in asks?.mentions ?? const <SuperTabMention>[]) {+ final projectId = mention.projectId.isNotEmpty+ ? mention.projectId+ : snapshot.conversation(mention.conversationId)?.projectId;+ if (projectId != null) tags[projectId] = (tags[projectId] ?? 0) + 1;+ }+ return {+ for (final id in {...unread, ...tags.keys})+ id: (bold: true, tags: tags[id] ?? 0),+ };+}diff --git a/mobile/lib/swarm/swarm_voice.dart b/mobile/lib/swarm/swarm_voice.dartnew file mode 100644index 000000000..78e74049b--- /dev/null+++ b/mobile/lib/swarm/swarm_voice.dart@@ -0,0 +1,583 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/voice_input_controller.dart';+import 'package:harness_mobile/phone/voice_language_store.dart';+import 'package:harness_mobile/phone/voice_mic_face.dart';+import 'package:harness_mobile/phone/voice_notice.dart';+import 'package:harness_mobile/shared/theme/app_icon_size.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'swarm_dictation.dart';++/// Talking instead of typing in a chat, into the message box (Tony, 10-28:+/// "like the Claude app"). Tap to talk; tap again and what is in the box is+/// sent ([send]) — what the person typed or changed meanwhile included. Only+/// that tap ends a take (10-29: "until I tap"): no pause does — save [idle]+/// without a new word, which stops listening with the words left in the box.+/// A long press picks the language ([voiceLanguageStore]).+///+/// Two ways to hear, the first wherever it can:+///+/// - **The phone's own recognizer** ([dictation]), the one the keyboard's+/// dictation uses: the words show in the box as they are said. Asked for+/// once, with the microphone.+/// - **The terminal's voice input** ([VoiceInputController]): the take is+/// recorded and the backend transcribes it as it ends — at the tap, or at+/// [VoiceInputController.maxTake] with its words left in the box, unsent.+/// Where there is no recognizer (Android, sample mode), speech recognition+/// was refused, or the recognizer has no such language.+///+/// ⚠️ **Only while the chat is seen.** A take goes the moment the chat does —+/// covered by another screen ([hide]) or the app sent to the background — so+/// nothing is recorded, or sent to be transcribed, behind the person's back.+/// Behind a system prompt a recorded take is kept, but its time limit ends+/// it only once the app is back; a take that ended just before goes to be+/// transcribed only then, too.+class SwarmVoice extends ChangeNotifier {+ SwarmVoice({+ required this.create,+ this.dictation,+ required this.draft,+ required this.write,+ required this.send,+ });++ /// How long the recognizer listens without hearing a new word before it+ /// stops by itself: the microphone is released and the words stay in the+ /// box, for Send or the next take (Lead, review of #2056: a microphone open+ /// for nobody). A shorter pause never ends it.+ static const idle = Duration(minutes: 2);++ /// What the chat says, quietly, as the recognizer stops by itself after+ /// [idle], for [stoppedLinger] (Lead, 10-29: a mic that went still with no+ /// word said why).+ static const stoppedListening = 'Stopped listening';+ static const stoppedLinger = Duration(seconds: 3);++ /// How long the recognizer has to say it has stopped, after a tap asked it+ /// to, before its take is given up and what the box holds is sent.+ static const _endWait = Duration(seconds: 2);++ /// Makes the voice input, which this owns and disposes.+ final VoiceInputController Function() create;++ /// The phone's own recognizer; null where there is none.+ final SwarmDictation? dictation;++ /// The draft as it is now, and the draft written anew.+ final String Function() draft;+ final void Function(String text) write;++ /// Sends the draft: the second tap ended a take.+ final void Function() send;++ /// The recognizer's take: asking for it, listening, or waiting for it to+ /// say it has stopped — as only the second tap asks, to send the draft.+ _Live _live = _Live.off;++ /// Bumped by everything that ends a recognizer's take, so what an earlier+ /// one still says lands nowhere.+ int _liveTake = 0;++ /// Speech recognition was refused: the mic records from now on.+ bool _liveRefused = false;++ /// What the recognizer shows is spliced into the draft after [_liveFrom]:+ /// the draft as the take began, or as the person last left it. [_liveShown]+ /// is the draft as the recognizer last wrote it; a draft that is not, the+ /// person changed — their change stays, with [_liveHeard] as it was then in+ /// it ([_liveBase]).+ String _liveFrom = '', _liveShown = '';++ /// Every word the recognizer has heard in the take, as it last said them;+ /// and those of them already in [_liveFrom].+ List<String> _liveHeard = const [], _liveBase = const [];+ Timer? _liveEnd, _liveIdle, _liveNoticeTimer, _stoppedTimer;+ final ValueNotifier<double> _liveLevel = ValueNotifier(0);+ String? _liveNotice;++ VoiceInputController? _voice;+ bool _disposed = false;++ /// Hears the app go to the background, from the first tap.+ AppLifecycleListener? _lifecycle;++ /// The app is in front: not behind a system prompt or Control Center, nor+ /// gone. Only then does a take reach its limit and go to be transcribed.+ bool _inFront = true;++ /// The take reached [VoiceInputController.maxTake] while the app was not+ /// in front: it ends as the app comes back.+ bool _limitReached = false;++ /// A take whose microphone closed while the app was not in front, waiting+ /// for it to come back ([_mayTranscribe]).+ Completer<bool>? _held;++ /// The voice input, from the first tap: a recorder opens a platform+ /// channel, and a chat nobody talks to should not.+ VoiceInputController? get voice => _voice;++ /// What went wrong with the last take, as the terminal says it.+ String? get notice => _liveNotice ?? _voice?.notice;++ /// [stoppedListening] for a moment after the recognizer stopped by itself;+ /// null otherwise.+ String? get stopped => _stoppedTimer == null ? null : stoppedListening;++ /// The mic's face: null at rest.+ VoiceMicFace? get face => switch (_live) {+ _Live.asking => VoiceMicFace.starting,+ _Live.listening => VoiceMicFace.listening,+ _Live.ending => VoiceMicFace.busy,+ _Live.off => switch (_voice) {+ null => null,+ final voice when voice.isSending => VoiceMicFace.busy,+ final voice => switch (voice.status) {+ VoiceInputStatus.starting => VoiceMicFace.starting,+ VoiceInputStatus.listening => VoiceMicFace.listening,+ VoiceInputStatus.transcribing => VoiceMicFace.busy,+ VoiceInputStatus.idle || VoiceInputStatus.unavailable => null,+ },+ },+ };++ /// The microphone was refused: the mic is off.+ bool get off =>+ _live == _Live.off && _voice?.status == VoiceInputStatus.unavailable;++ /// How loud the microphone is, for the face's bars.+ ValueListenable<double>? get level =>+ _live == _Live.off ? _voice?.level : _liveLevel;++ /// Starts a take; ends it and sends the box, calls it off while the+ /// microphone opens or its permission is asked, or does nothing while its+ /// words are on their way.+ void tap() {+ if (_disposed) return;+ switch (_live) {+ case _Live.asking:+ _offLive();+ return;+ case _Live.listening:+ _endLive();+ return;+ case _Live.ending:+ return;+ case _Live.off:+ }+ _setLiveNotice(null);+ _stoppedTimer?.cancel();+ _stoppedTimer = null;+ final recorded = _voice;+ final underWay =+ recorded != null &&+ (recorded.isSending ||+ (recorded.status != VoiceInputStatus.idle &&+ recorded.status != VoiceInputStatus.unavailable));+ if (!underWay && dictation != null && !_liveRefused) {+ unawaited(_listen(dictation!));+ return;+ }+ _tapRecorded(recorded ?? _start());+ }++ /// [tap] on the terminal's voice input.+ void _tapRecorded(VoiceInputController voice) {+ if (voice.isSending) return;+ switch (voice.status) {+ case VoiceInputStatus.idle || VoiceInputStatus.unavailable:+ unawaited(voice.startListening());+ case VoiceInputStatus.starting:+ unawaited(voice.stopListening());+ case VoiceInputStatus.listening:+ _finish(voice, send: true);+ case VoiceInputStatus.transcribing:+ break;+ }+ }++ /// Throws away the take under way — opening, recording or being+ /// transcribed — with its words: the chat went out of sight. What it was+ /// waiting on lands nowhere ([VoiceInputController.clear]), and the next+ /// tap starts afresh.+ ///+ /// ⚠️ `clear`, never `stopListening` or a [_finish]: those transcribe the+ /// take, and a take nobody can see must not leave the phone.+ void hide() {+ _offLive();+ _release(false);+ final voice = _voice;+ if (voice == null || voice.isIdle) return;+ voice.clear();+ }++ VoiceInputController _start() {+ final voice = _voice = create();+ voice.addListener(_changed);+ voice.onTakeLimit = () async => _limit(voice);+ voice.mayTranscribe = _mayTranscribe;+ _watchApp();+ return voice;+ }++ /// Hears the app come and go, from the first tap.+ void _watchApp() {+ if (_lifecycle != null) return;+ final state = WidgetsBinding.instance.lifecycleState;+ _inFront = state == null || state == AppLifecycleState.resumed;+ _lifecycle = AppLifecycleListener(onStateChange: _lifecycleChanged);+ }++ /// A take with the phone's recognizer: asked for, then listening in the+ /// long-press language until the next tap, for as long as the chat is in+ /// front. Refused, or without the language, the tap records instead.+ Future<void> _listen(SwarmDictation dictation) async {+ final take = ++_liveTake;+ _watchApp();+ _live = _Live.asking;+ notifyListeners();+ final access = await dictation.access();+ if (_disposed || take != _liveTake) return;+ if (access != SwarmDictationAccess.allowed) {+ if (access == SwarmDictationAccess.denied) _liveRefused = true;+ _live = _Live.off;+ _tapRecorded(_voice ?? _start());+ notifyListeners();+ return;+ }+ _liveFrom = _liveShown = draft();+ _liveHeard = _liveBase = const [];+ final started = await dictation.start(+ swarmDictationLocale(voiceLanguageStore.value),+ onWords: (words) => _liveWords(take, words),+ onLevel: (level) {+ if (take == _liveTake) _liveLevel.value = level;+ },+ onEnd: (end) => _liveEnded(take, end),+ );+ if (_disposed || take != _liveTake) {+ if (started) unawaited(dictation.cancel());+ return;+ }+ if (!started) {+ _live = _Live.off;+ _tapRecorded(_voice ?? _start());+ notifyListeners();+ return;+ }+ _live = _Live.listening;+ _waitForWords(take);+ notifyListeners();+ }++ /// Starts [idle] over: a take that hears no new word in it is called off.+ void _waitForWords(int take) {+ _liveIdle?.cancel();+ _liveIdle = Timer(idle, () {+ if (take != _liveTake || _live != _Live.listening) return;+ _stoppedTimer = Timer(stoppedLinger, () {+ _stoppedTimer = null;+ if (!_disposed) notifyListeners();+ });+ _offLive();+ });+ }++ /// Every word the recognizer has heard so far, into the draft after+ /// [_liveFrom]: those not already in it, which — after an edit — are the+ /// ones past what the recognizer said then and says still, however it has+ /// revised it since. A spoken word may show twice; none is lost.+ void _liveWords(int take, String text) {+ if (take != _liveTake || _live == _Live.off) return;+ final words = text.split(RegExp(r'\s+')).where((w) => w.isNotEmpty);+ final now = draft();+ if (now != _liveShown) {+ _liveFrom = now;+ _liveBase = _liveHeard;+ }+ final heard = words.toList();+ final changed = heard.join(' ') != _liveHeard.join(' ');+ _liveHeard = heard;+ final kept = _sameStart(_liveBase, heard);+ _liveShown = _joined(_liveFrom, heard.skip(kept).join(' '));+ if (_liveShown != now) write(_liveShown);+ if (changed && _live == _Live.listening) _waitForWords(take);+ }++ /// How many words [a] and [b] begin with alike, case and punctuation aside.+ static int _sameStart(List<String> a, List<String> b) {+ String plain(String word) => word.toLowerCase().replaceAll(+ RegExp(r'[^\p{L}\p{N}]', unicode: true),+ '',+ );+ var same = 0;+ while (same < a.length &&+ same < b.length &&+ plain(a[same]) == plain(b[same])) {+ same++;+ }+ return same;+ }++ /// The second tap: asks the recognizer to stop — its last words, then its+ /// end ([_liveEnded]), which sends the draft.+ void _endLive() {+ final dictation = this.dictation;+ if (_live != _Live.listening || dictation == null) return;+ final take = _liveTake;+ _live = _Live.ending;+ _stopLiveTimers();+ _liveEnd = Timer(_endWait, () {+ if (take != _liveTake) return;+ unawaited(dictation.cancel());+ _liveEnded(take, SwarmDictationEnd.failed);+ });+ notifyListeners();+ unawaited(dictation.stop());+ }++ /// The recognizer has stopped: as the second tap asked — and then what the+ /// box holds is sent, however its last session ended (Tony, 10-29) — or+ /// because it cannot go on, its words left in the box. A notice only when+ /// nothing goes.+ void _liveEnded(int take, SwarmDictationEnd end) {+ if (take != _liveTake || _live == _Live.off) return;+ final send = _live == _Live.ending && draft().trim().isNotEmpty;+ _liveTake++;+ _live = _Live.off;+ _stopLiveTimers();+ _liveLevel.value = 0;+ _setLiveNotice(switch (end) {+ _ when send => null,+ SwarmDictationEnd.failed => VoiceNotice.notTranscribed,+ _ when _liveHeard.isEmpty => VoiceNotice.nothingHeard,+ _ => null,+ });+ notifyListeners();+ if (send && !_disposed) this.send();+ }++ /// Calls off the recognizer's take, whatever it is doing: the words already+ /// shown stay in the draft, and nothing is sent.+ void _offLive() {+ if (_live == _Live.off) return;+ final listened = _live != _Live.asking;+ _liveTake++;+ _live = _Live.off;+ _stopLiveTimers();+ _liveLevel.value = 0;+ if (listened) unawaited(dictation?.cancel());+ if (!_disposed) notifyListeners();+ }++ void _stopLiveTimers() {+ _liveEnd?.cancel();+ _liveIdle?.cancel();+ _liveEnd = _liveIdle = null;+ }++ /// A notice of the recognizer's, which goes by itself as the terminal's do.+ void _setLiveNotice(String? notice) {+ _liveNoticeTimer?.cancel();+ _liveNoticeTimer = null;+ _liveNotice = notice;+ if (notice == null) return;+ _liveNoticeTimer = Timer(VoiceInputController.noticeLinger, () {+ _liveNotice = null;+ if (!_disposed) notifyListeners();+ });+ }++ /// [words] after [draft], a space between them unless the draft ends in one.+ static String _joined(String draft, String words) {+ if (words.isEmpty) return draft;+ final spaced = draft.isEmpty || RegExp(r'\s$').hasMatch(draft);+ return '$draft${spaced ? '' : ' '}$words';+ }++ void _lifecycleChanged(AppLifecycleState state) {+ switch (state) {+ case AppLifecycleState.resumed:+ _inFront = true;+ _release(true);+ _back();+ // ⚠️ Kept, not thrown away: the microphone permission prompt itself+ // leaves the app inactive, and so do Control Center and a call's banner,+ // and the take asked for must survive them. Only its ending waits.+ //+ // The recognizer's take is not, once it listens: it has no prompt left+ // to survive, and what it hears goes to be recognized at once.+ case AppLifecycleState.inactive:+ _inFront = false;+ if (_live != _Live.asking) _offLive();+ case AppLifecycleState.hidden ||+ AppLifecycleState.paused ||+ AppLifecycleState.detached:+ _inFront = false;+ hide();+ }+ }++ /// The app is back in front: a take that reached its limit meanwhile ends+ /// now.+ void _back() {+ final voice = _voice;+ if (voice == null || voice.status != VoiceInputStatus.listening) return;+ if (!_limitReached) return;+ _limitReached = false;+ _finish(voice);+ }++ /// The take reached [VoiceInputController.maxTake]: it ends into the box,+ /// as a tap would — once the app is in front, never behind a prompt.+ void _limit(VoiceInputController voice) {+ if (_inFront) {+ _finish(voice);+ } else {+ _limitReached = true;+ }+ }++ /// Whether a take may go to be transcribed, asked once its microphone has+ /// closed: at once in front; behind a system prompt, once the app is back —+ /// and never if it goes away instead ([hide]).+ ///+ /// ⚠️ Asked again here, not only as the take ends: the microphone takes a+ /// moment to close, and Control Center can come down in it.+ Future<bool> _mayTranscribe() async {+ while (!_inFront) {+ if (!await (_held ??= Completer()).future) return false;+ }+ return true;+ }++ /// Lets a take held by [_mayTranscribe] go to be transcribed, or drops it.+ void _release(bool go) {+ final held = _held;+ _held = null;+ held?.complete(go);+ }++ /// Ends the take, its words into the draft, and with [send] sends the draft+ /// once they are there. A take that fails keeps the draft as it was, sends+ /// nothing and leaves its [notice].+ void _finish(VoiceInputController voice, {bool send = false}) {+ var heard = false;+ unawaited(+ voice+ .submit((words) async {+ write(_joined(draft(), words));+ heard = true;+ return true;+ })+ .then((_) {+ if (heard && send && !_disposed) this.send();+ }),+ );+ }++ void _changed() {+ if (_voice?.status != VoiceInputStatus.listening) _limitReached = false;+ notifyListeners();+ }++ /// Throws away a take still under way: the microphone closes with the chat.+ @override+ void dispose() {+ _disposed = true;+ _offLive();+ _liveNoticeTimer?.cancel();+ _stoppedTimer?.cancel();+ _liveLevel.dispose();+ _release(false);+ _lifecycle?.dispose();+ if (_voice case final voice?) {+ voice.removeListener(_changed);+ voice.dispose();+ }+ super.dispose();+ }+}++/// The composer's mic, a 44pt round like its other buttons: a plain mic at+/// rest, and the terminal's face ([VoiceMicCore]) while a take is under way —+/// opening, listening with its bars moving to the voice, transcribing. A long+/// press picks the language, from the terminal's list.+class SwarmVoiceMic extends StatelessWidget {+ const SwarmVoiceMic({super.key, required this.voice});++ final SwarmVoice voice;++ /// How wide the terminal's face is drawn here: inside the 44pt round, as+ /// the filled Send beside it is.+ static const double _face = 36;++ @override+ Widget build(BuildContext context) {+ final face = voice.face;+ final off = voice.off;+ void talk() {+ HapticFeedback.lightImpact();+ voice.tap();+ }++ void chooseLanguage() => unawaited(showVoiceLanguagePicker(context));+ // The actions on the node itself: the button's own are left out with its+ // icon, and VoiceOver's double-tap-and-hold is the only way to the list.+ return Semantics(+ button: true,+ enabled: true,+ onTap: talk,+ onLongPress: chooseLanguage,+ // One word while the mic is open: VoiceOver reads the label aloud, and+ // a sentence read into an open microphone lands in the take.+ label: switch (face) {+ VoiceMicFace.starting => 'Cancel',+ VoiceMicFace.listening => 'Done',+ null when off => 'Voice input is off',+ null => 'Talk',+ _ => 'Working',+ },+ onLongPressHint: 'Choose language',+ excludeSemantics: true,+ child: GestureDetector(+ key: const ValueKey('swarm-mic'),+ behavior: HitTestBehavior.opaque,+ onTap: talk,+ onLongPress: chooseLanguage,+ child: SizedBox.square(+ dimension: 44,+ child: Center(+ child: face == null+ ? Icon(+ off ? LucideIcons.micOff : LucideIcons.mic,+ size: AppIconSize.standalone,+ color: off+ ? AppPalette.textFaint+ : AppPalette.textSecondary,+ )+ : SizedBox.square(+ dimension: _face,+ child: FittedBox(+ child: VoiceMicCore(+ face: face,+ dead: false,+ level: voice.level,+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }+}++/// Where [SwarmVoice]'s take with the phone's recognizer is.+enum _Live { off, asking, listening, ending }diff --git a/mobile/lib/swarm/team_glance.dart b/mobile/lib/swarm/team_glance.dartnew file mode 100644index 000000000..73cea7121--- /dev/null+++ b/mobile/lib/swarm/team_glance.dart@@ -0,0 +1,188 @@+import 'model.dart';+import 'swarm_buddy.dart';++/// An agent's state on the phone. Read from the Swarm alone: the phone sees+/// no agent's computer, so the work an agent holds is the work it is doing+/// (the desktop's team glance, without its machine readings).+enum SwarmAgentState { working, waiting, stuck, down, limited, idle }++/// One agent in a word: "Working", "Stuck", "Limited until 09:05".+class SwarmAgentGlance {+ SwarmAgentGlance(this.agent, this.name, this.state, this.label, this.task);+ final SuperTabAgent agent;+ final String name;+ final SwarmAgentState state;+ final String label;++ /// The open work it holds, if any.+ final SuperTabConversation? task;+}++/// The team at a glance: [line] for the compact row, [agents] for each one,+/// who needs a person first.+class SwarmTeamGlance {+ SwarmTeamGlance._(this.agents);++ final List<SwarmAgentGlance> agents;++ int _count(Set<SwarmAgentState> states) =>+ agents.where((a) => states.contains(a.state)).length;++ late final int working = _count(const {SwarmAgentState.working});++ /// Waiting on a person: a question, or stuck.+ late final int waiting = _count(const {+ SwarmAgentState.waiting,+ SwarmAgentState.stuck,+ });+ late final int down = _count(const {SwarmAgentState.down});+ late final int limited = _count(const {SwarmAgentState.limited});++ /// What [line] counts, part by part, each with the state it counts: "2+ /// working", "1 down". Leaves out what is none.+ late final List<({String text, SwarmAgentState state})>+ parts = List.unmodifiable([+ if (working > 0) (text: '$working working', state: SwarmAgentState.working),+ if (waiting > 0) (text: '$waiting waiting', state: SwarmAgentState.waiting),+ if (down > 0) (text: '$down down', state: SwarmAgentState.down),+ if (limited > 0) (text: '$limited limited', state: SwarmAgentState.limited),+ ]);++ /// "2 working · 1 waiting · 1 down", leaving out what is none.+ late final String line = agents.isEmpty+ ? 'No agents yet'+ : parts.isEmpty+ ? 'All idle'+ : parts.map((part) => part.text).join(' · ');+}++const _finished = {'done', 'stopped', 'cancelled'};++/// The team of [snapshot], or of its project [projectId]: an agent is in the+/// project it records, else in the one whose work it is in (the desktop's+/// roster rule). A Buddy is no one's team ([swarmTeamAgents]).+///+/// Counted once per read and project: Home, the drawer and the project's page+/// share one glance until the read is replaced, or until [now] crosses an+/// agent's usage limit.+SwarmTeamGlance swarmTeamGlance(+ SuperTabSnapshot snapshot, {+ String? projectId,+ DateTime? now,+}) {+ final at = now ?? DateTime.now();+ final read = _reads[snapshot] ??= _ReadGlances(snapshot);+ final kept = read.glances[projectId];+ if (kept != null && kept.holdsAt(at)) return kept.glance;+ final counted = read.count(snapshot, projectId, at);+ read.glances[projectId] = counted;+ return counted.glance;+}++/// Each read's glances, kept with the read: a replaced read takes its own+/// with it, so nothing counted from an earlier read is shown.+final _reads = Expando<_ReadGlances>('swarm team glances');++/// What one read says of every agent, worked out once: the open work it holds+/// and the project of the first work it is in.+class _ReadGlances {+ _ReadGlances(SuperTabSnapshot snapshot) {+ for (final group in snapshot.conversations) {+ for (final id in [...group.agentIds, ?group.leadId]) {+ _projectOf.putIfAbsent(id, () => group.projectId);+ }+ final work = group.assignment;+ if (!group.closed && !_finished.contains(work?['status'])) {+ if (work?['agentId'] case final String id) {+ _taskOf.putIfAbsent(id, () => group);+ }+ }+ }+ }++ final _projectOf = <String, String>{};+ final _taskOf = <String, SuperTabConversation>{};+ final glances = <String?, _Kept>{};++ _Kept count(SuperTabSnapshot snapshot, String? projectId, DateTime at) {+ final agents =+ [+ for (final agent in swarmTeamAgents(snapshot))+ if (projectId == null || _projectOfAgent(agent) == projectId)+ _glance(snapshot, agent, _taskOf[agent.id], at),+ ]..sort((a, b) {+ final rank = _rank(a.state).compareTo(_rank(b.state));+ return rank != 0 ? rank : a.name.compareTo(b.name);+ });+ // The glance holds while no counted agent's limit starts or ends.+ DateTime? from, until;+ for (final glance in agents) {+ final limit = glance.agent.limitedUntil;+ if (limit == null) continue;+ if (limit.isAfter(at)) {+ if (until == null || limit.isBefore(until)) until = limit;+ } else if (from == null || limit.isAfter(from)) {+ from = limit;+ }+ }+ return _Kept(SwarmTeamGlance._(List.unmodifiable(agents)), from, until);+ }++ String? _projectOfAgent(SuperTabAgent agent) =>+ agent.hasProjectId ? agent.projectId : _projectOf[agent.id];+}++/// A glance and the time it holds for: from [from] (inclusive) to [until].+class _Kept {+ _Kept(this.glance, this.from, this.until);+ final SwarmTeamGlance glance;+ final DateTime? from, until;++ bool holdsAt(DateTime at) =>+ (from == null || !at.isBefore(from!)) &&+ (until == null || at.isBefore(until!));+}++int _rank(SwarmAgentState state) => switch (state) {+ SwarmAgentState.waiting || SwarmAgentState.stuck => 0,+ SwarmAgentState.down => 1,+ SwarmAgentState.limited => 2,+ SwarmAgentState.working => 3,+ SwarmAgentState.idle => 4,+};++SwarmAgentGlance _glance(+ SuperTabSnapshot snapshot,+ SuperTabAgent agent,+ SuperTabConversation? task,+ DateTime at,+) {+ final work = task?.assignment?['status'];+ final until = agent.limitedUntil?.toLocal();+ String two(int n) => n.toString().padLeft(2, '0');+ // The desktop's order, less what only the agent's computer can say.+ final (state, label) = switch (null) {+ _ when work == 'lost' => (SwarmAgentState.down, 'Lost'),+ _ when agent.downSince != null => (SwarmAgentState.down, 'Down'),+ _ when until != null && until.isAfter(at) => (+ SwarmAgentState.limited,+ 'Limited until ${two(until.hour)}:${two(until.minute)}',+ ),+ _ when work == 'blocked' => (SwarmAgentState.stuck, 'Stuck'),+ _ when work == 'needs_human' => (SwarmAgentState.waiting, 'Waiting'),+ _ when work == 'review' => (SwarmAgentState.working, 'In review'),+ _ when work == 'reconciling' => (SwarmAgentState.working, 'Checking'),+ _ when work == 'planned' || work == 'working' => (+ SwarmAgentState.working,+ 'Working',+ ),+ _ => (SwarmAgentState.idle, 'Idle'),+ };+ return SwarmAgentGlance(+ agent,+ snapshot.agentName(agent.id),+ state,+ label,+ task,+ );+}diff --git a/mobile/lib/swarm/waiting_work.dart b/mobile/lib/swarm/waiting_work.dartnew file mode 100644index 000000000..b6699f61f--- /dev/null+++ b/mobile/lib/swarm/waiting_work.dart@@ -0,0 +1,76 @@+import 'model.dart';++/// One piece of work waiting on the reader: its worker needs a person or is+/// stuck.+class SwarmWaitingWork {+ SwarmWaitingWork(this.conversation, this.project, this.snapshot);+ final SuperTabConversation conversation;+ final SuperTabProject project;+ final SuperTabSnapshot snapshot;++ /// `needs_human` or `blocked`.+ String get status => conversation.assignment!['status'] as String;++ /// The worker's name.+ String get agentName =>+ snapshot.agentName(conversation.assignment!['agentId'] as String? ?? '');++ /// What the worker wrote with the status: its question, or why it is stuck.+ String? get question => switch (conversation.assignment!['result']) {+ final String text when text.trim().isNotEmpty => text.trim(),+ _ => null,+ };+}++/// Each conversation's partner, the person its work needs (`partnerId`, named+/// by its Lead; backend v2 K), read from the raw state: the model the phone+/// shares with the desktop does not carry it yet.+Map<String, String> swarmPartners(Map<String, dynamic> state) => {+ for (final row in state['conversations'] as List? ?? const [])+ if (row case {'id': final String id, 'partnerId': final String partner})+ id: partner,+};++/// The work in [snapshot] waiting on [accountId]: a worker needs a person or+/// is stuck, and the reader is who it waits on — the conversation's partner+/// when it has one, else the project's owner (Lead's ruling, 2026-10-27). A+/// decision or tag asked of a person by name reaches them on its own+/// (`SwarmAsks`), so it is never counted here for anyone else.+///+/// The one place this rule lives: when people's areas reach the phone, the+/// owner gives way to whoever covers the area here.+///+/// Worked out once per read, reader and [partners]; the list is shared, so it+/// cannot be changed.+List<SwarmWaitingWork> swarmWaitingWork(+ SuperTabSnapshot snapshot,+ String accountId, {+ Map<String, String> partners = const {},+}) {+ final kept = _kept[snapshot];+ if (kept != null &&+ kept.accountId == accountId &&+ identical(kept.partners, partners)) {+ return kept.work;+ }+ final work = List<SwarmWaitingWork>.unmodifiable([+ for (final conversation in snapshot.conversations)+ if (superTabWorkWaits(conversation.assignment?['status']))+ if (snapshot.projectById(conversation.projectId) case final project?)+ if ((partners[conversation.id] ?? project.ownerId) == accountId)+ SwarmWaitingWork(conversation, project, snapshot),+ ]);+ _kept[snapshot] = (accountId: accountId, partners: partners, work: work);+ return work;+}++/// Each read's waiting work, kept with the read: a replaced read takes it+/// with it, and another reader or new partners work it out again.+final _kept =+ Expando<+ ({+ String accountId,+ Map<String, String> partners,+ List<SwarmWaitingWork> work,+ })+ >('swarm waiting work');diff --git a/mobile/pubspec.lock b/mobile/pubspec.lockindex 798521f08..de0683c76 100644--- a/mobile/pubspec.lock+++ b/mobile/pubspec.lock@@ -34,7 +34,7 @@ packages:source: hostedversion: "1.4.1"clock:- dependency: transitive+ dependency: "direct main"description:name: clocksha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e@@ -170,7 +170,7 @@ packages:source: hostedversion: "0.1.2"file:- dependency: transitive+ dependency: "direct dev"description:name: filesha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4@@ -254,6 +254,14 @@ packages:description: fluttersource: sdkversion: "0.0.0"+ flutter_cache_manager:+ dependency: "direct main"+ description:+ name: flutter_cache_manager+ sha256: f94fc6f5480977e3eb7b622ed488f671ba96c971bd0e274e6bd0f0ba9b044816+ url: "https://pub.dev"+ source: hosted+ version: "3.4.5"flutter_driver:dependency: "direct dev"description: flutter@@ -323,6 +331,54 @@ packages:url: "https://pub.dev"source: hostedversion: "2.6.1"+ flutter_secure_storage:+ dependency: "direct main"+ description:+ name: flutter_secure_storage+ sha256: fe638107c5f69119156ada2db5a57734385fac3f64430bd7252a00d3ead2ca4b+ url: "https://pub.dev"+ source: hosted+ version: "10.3.4"+ flutter_secure_storage_darwin:+ dependency: transitive+ description:+ name: flutter_secure_storage_darwin+ sha256: "82329fa5cdf343773b1b6897dea959105a29f092454259edff92f9f6637e8149"+ url: "https://pub.dev"+ source: hosted+ version: "0.3.2"+ flutter_secure_storage_linux:+ dependency: transitive+ description:+ name: flutter_secure_storage_linux+ sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea+ url: "https://pub.dev"+ source: hosted+ version: "3.0.3"+ flutter_secure_storage_platform_interface:+ dependency: transitive+ description:+ name: flutter_secure_storage_platform_interface+ sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.1"+ flutter_secure_storage_web:+ dependency: transitive+ description:+ name: flutter_secure_storage_web+ sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.1"+ flutter_secure_storage_windows:+ dependency: transitive+ description:+ name: flutter_secure_storage_windows+ sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1"+ url: "https://pub.dev"+ source: hosted+ version: "4.2.2"flutter_test:dependency: "direct dev"description: flutter@@ -608,7 +664,7 @@ packages:source: hostedversion: "1.9.1"path_provider:- dependency: transitive+ dependency: "direct main"description:name: path_providersha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825@@ -783,6 +839,14 @@ packages:url: "https://pub.dev"source: hostedversion: "2.6.1"+ rxdart:+ dependency: transitive+ description:+ name: rxdart+ sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962"+ url: "https://pub.dev"+ source: hosted+ version: "0.28.0"share_plus:dependency: "direct main"description:@@ -812,6 +876,46 @@ packages:url: "https://pub.dev"source: hostedversion: "1.10.2"+ sqflite:+ dependency: transitive+ description:+ name: sqflite+ sha256: "21a9750de2deb464946e9f41c7ddf176e25553618afdfc774868cd454990c06a"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.5"+ sqflite_android:+ dependency: transitive+ description:+ name: sqflite_android+ sha256: "3986f4cbdde19ca538aae877981c5a53400dcc4601499df18e7ed9e848a0bdd4"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.5"+ sqflite_common:+ dependency: transitive+ description:+ name: sqflite_common+ sha256: b80e94ff0d551d5f1f8c7d14348d29b576cca3ae30f6e195a7c380552c32b1e0+ url: "https://pub.dev"+ source: hosted+ version: "2.5.14"+ sqflite_darwin:+ dependency: transitive+ description:+ name: sqflite_darwin+ sha256: "8de68fc306040f992aaf378750c16f95e4298c4bb150dd45091d75e42b1f08ee"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.4+1"+ sqflite_platform_interface:+ dependency: transitive+ description:+ name: sqflite_platform_interface+ sha256: "5b611dbcb9bab33e7073594ecac111bf0a86ffc342652c2081160d7038a45fb6"+ url: "https://pub.dev"+ source: hosted+ version: "2.4.3"stack_trace:dependency: transitivedescription:diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yamlindex 89a6847ef..15865789c 100644--- a/mobile/pubspec.yaml+++ b/mobile/pubspec.yaml@@ -21,6 +21,9 @@ dependencies:sdk: flutter# `compareNatural` — the desktop's name order, so `harness 9` sorts before `harness 10` on both.collection: ^1.19.1+ # The time a Swarm status clears by (`swarm/swarm_face.dart`), which tests move+ # with the fake clock `testWidgets` runs under.+ clock: ^1.1.2cupertino_icons: ^1.0.8lucide_icons_flutter: ^3.1.15@@ -47,6 +50,9 @@ dependencies:# The running build's version, shown in Settings and sent with analytics.package_info_plus: ^10.2.1path: ^1.9.1+ # The app's temporary folder on Android, where a Swarm chat's pickers leave the copies it deletes+ # once read (`swarm/swarm_file_picker.dart`). Already in the app through flutter_cache_manager.+ path_provider: ^2.1.6# The phone's second wire to a machine: the `terminal-v1` data channel the# harness CLI opens with werift on the desktop's behalf (lib/p2p/). Data@@ -61,6 +67,11 @@ dependencies:# are re-encoded to PNG before they leave — see `terminal/image_transcode.dart`# for why the whole pipe past this point accepts nothing else.image_picker: ^1.2.3+ # Pictures in a Swarm chat shown in place (`swarm/swarm_attachment.dart`): each file kept in the+ # app's private temporary folder, one folder per account, for at most 7 days unopened and 200+ # files, and emptied on sign-out, Swarm off, account change and a Swarm's removal. Pinned+ # exactly: it decides where the account's files lie on the phone.+ flutter_cache_manager: 3.4.5# Sending any other file to an agent — a PDF, a log, a zip — from the same key: the system's own# document picker (Files on iOS, the Storage Access Framework on Android), which hands over one# file the person chose and asks for no storage permission. The bytes go out as the CLI's@@ -93,11 +104,19 @@ dependencies:# interactive demo. It also plays a video a terminal printed, downloaded from the agent's machine# (`phone/media_preview_page.dart`).video_player: ^2.14.0+ # The key the last Swarm Home is sealed under, in the iOS Keychain (Android: Keystore-backed), so a+ # cold start draws it at once (`swarm/swarm_home_cache.dart`); the sealed view sits beside the+ # state file. Pinned exactly: a native plugin, and 10.x is the line with a Swift package, which the+ # iOS build needs (no CocoaPods).+ flutter_secure_storage: 10.3.4dev_dependencies:flutter_test:sdk: flutterflutter_lints: ^6.0.0+ # The cache's own file abstraction, which `flutter_cache_manager` already brings in: tests keep+ # Swarm's image files in a temporary folder through it (`test/swarm/swarm_attachment_*`).+ file: 7.0.1# The p2p routing is all timers (retry, migration sweep, upgrade) — tests drive# them without waiting them out.fake_async: ^1.3.1diff --git a/mobile/test/api/api_client_test.dart b/mobile/test/api/api_client_test.dartindex 98774f7bb..3e339590c 100644--- a/mobile/test/api/api_client_test.dart+++ b/mobile/test/api/api_client_test.dart@@ -9,6 +9,7 @@ import 'package:harness_mobile/api/access_token_source.dart';import 'package:harness_mobile/api/api_client.dart';import 'package:harness_mobile/auth/auth_session.dart';import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/viewer/direct_auth.dart';import 'package:harness_mobile/viewer/direct_auth_api.dart';import 'package:harness_mobile/viewer/email_code_api.dart';@@ -356,6 +357,54 @@ void main() {},);+ test(+ "a Swarm avatar goes up as one PNG of its own and answers the upload's id",+ () async {+ backend.answer = (_, _) => (+ status: 200,+ body: ok({+ 'avatar': {'id': 'up-1'},+ }),+ );+ final png = Uint8List.fromList(List.generate(32, (i) => i));+ expect(+ await client(_Tokens(['t'])).uploadSwarmAvatar('tab/1', png),+ 'up-1',+ );+ final sent = backend.requests.single;+ expect(sent.path, '/api/super-tabs/tab%2F1/avatars');+ expect(sent.headers.contentType!.mimeType, 'multipart/form-data');+ final body = latin1.decode(sent.body);+ expect(body, contains('filename="avatar.png"'));+ expect(body, contains('Content-Type: image/png'));+ },+ );++ test('a Swarm avatar the server refuses says why', () async {+ backend.answer = (_, _) => (+ status: 503,+ body: {+ 'success': false,+ 'error': {+ 'code': 'AVATARS_UNAVAILABLE',+ 'message': 'Uploading pictures is not set up on this server yet.',+ },+ },+ );+ await expectLater(+ client(_Tokens(['t'])).uploadSwarmAvatar('tab-1', Uint8List(4)),+ throwsA(+ isA<ApiException>()+ .having((e) => e.status, 'status', 503)+ .having(+ (e) => e.message,+ 'message',+ 'Uploading pictures is not set up on this server yet.',+ ),+ ),+ );+ });+test('no transcript is an empty one', () async {backend.answer = (_, _) => (status: 200, body: ok(<String, Object?>{}));expect(@@ -365,6 +414,148 @@ void main() {});});+ group('a Swarm chat file', () {+ Future<Map<String, dynamic>> upload(+ ApiClient api, {+ String name = 'shot.jpg',+ String mime = 'image/jpeg',+ Uint8List? bytes,+ void Function(double sent)? onProgress,+ }) => api.uploadSwarmAttachment(+ tabId: 'tab-1',+ conversationId: 'conv-1',+ name: name,+ mime: mime,+ bytes: bytes ?? Uint8List.fromList([1, 2, 3]),+ cancel: CancelToken(),+ onProgress: onProgress ?? (_) {},+ );++ test(+ 'goes straight to the backend as the conversation, then one file',+ () async {+ final attachment = {+ 'id': 'att-1',+ 'name': 'shot.jpg',+ 'mime': 'image/jpeg',+ 'size': 3,+ 'url': 'https://cdn.harness.autonomous.ai/x/shot.jpg',+ };+ backend.answer = (_, _) =>+ (status: 200, body: ok({'attachment': attachment}));++ final answer = await upload(client(_Tokens(['t1'])));++ expect(answer, {'attachment': attachment});+ final sent = backend.requests.single;+ expect(sent.method, 'POST');+ expect(sent.path, '/api/super-tabs/tab-1/attachments');+ expect(sent.headers.value('authorization'), 'Bearer t1');+ expect(sent.headers.contentType!.mimeType, 'multipart/form-data');+ final boundary = sent.headers.contentType!.parameters['boundary']!;+ expect(+ sent.body,+ [+ ...utf8.encode(+ '--$boundary\r\n'+ 'Content-Disposition: form-data; name="conversationId"\r\n\r\n'+ 'conv-1\r\n'+ '--$boundary\r\n'+ 'Content-Disposition: form-data; name="file"; filename="shot.jpg"\r\n'+ 'Content-Type: image/jpeg\r\n\r\n',+ ),+ 1, 2, 3,+ ...utf8.encode('\r\n--$boundary--\r\n'),+ ],+ );+ },+ );++ test('a name cannot break out of its header', () async {+ backend.answer = (_, _) =>+ (status: 200, body: ok({'attachment': <String, Object?>{}}));++ await upload(client(_Tokens(['t'])), name: 'a"b\r\nc.jpg');++ expect(+ utf8.decode(backend.requests.single.body, allowMalformed: true),+ contains('filename="a%22b%0D%0Ac.jpg"'),+ );+ });++ test('says how much has gone up, up to all of it', () async {+ backend.answer = (_, _) =>+ (status: 200, body: ok({'attachment': <String, Object?>{}}));+ final told = <double>[];++ await upload(+ client(_Tokens(['t'])),+ bytes: Uint8List(200 * 1024),+ onProgress: told.add,+ );++ expect(told, isNotEmpty);+ expect(told.last, 1.0);+ });++ test('a refusal carries the backend\'s code and words', () async {+ backend.answer = (_, _) => (+ status: 403,+ body: {+ 'success': false,+ 'error': {'code': 'FORBIDDEN', 'message': 'Not a writer here.'},+ },+ );++ await expectLater(+ upload(client(_Tokens(['t']))),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'FORBIDDEN')+ .having((f) => f.message, 'message', 'Not a writer here.')+ .having((f) => f.statusCode, 'status', 403),+ ),+ );+ });++ test('a refusal without words says the desktop\'s', () async {+ backend.answer = (_, _) => (+ status: 413,+ body: {+ 'success': false,+ 'error': {'code': 'ATTACHMENT_TOO_LARGE'},+ },+ );++ await expectLater(+ upload(client(_Tokens(['t']))),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'ATTACHMENT_TOO_LARGE')+ .having((f) => f.message, 'message', 'That file is over 10 MB.'),+ ),+ );+ });++ test('an answer that is no envelope is a failed upload', () async {+ backend.answer = (_, _) => (status: 502, body: 'Bad Gateway');++ await expectLater(+ upload(client(_Tokens(['t']))),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'UPLOAD_FAILED')+ .having(+ (f) => f.message,+ 'message',+ 'Could not upload the file. Try again.',+ )+ .having((f) => f.statusCode, 'status', 502),+ ),+ );+ });+ });+group('describing a failure', () {DioException dio(DioExceptionType type, {int? status}) => DioException(requestOptions: RequestOptions(diff --git a/mobile/test/notify/local_system_notices_test.dart b/mobile/test/notify/local_system_notices_test.dartindex 44f46897f..f8a9eab02 100644--- a/mobile/test/notify/local_system_notices_test.dart+++ b/mobile/test/notify/local_system_notices_test.dart@@ -1,3 +1,4 @@+import 'package:flutter/foundation.dart';import 'package:flutter/services.dart';import 'package:flutter_local_notifications/flutter_local_notifications.dart';import 'package:flutter_test/flutter_test.dart';@@ -69,6 +70,87 @@ void main() {expect(notices.openedDevice.value, isNull);});+ group('a Swarm notice', () {+ const target = (swarmId: 'tab-1', conversationId: 'g9', messageId: null, decisionId: null);+ const swarm = (+ key: 'decision:d1',+ title: 'River asks you',+ subtitle: 'Mobile',+ body: 'Open Harness to answer.',+ target: target,+ );++ test('its own channel, where it is on the second line, replaced by its own key', () async {+ await notices.showSwarm(swarm);+ await notices.showSwarm(swarm);++ expect(plugin.shown.map((n) => n.id).toSet(), {swarmNoticeIdFor('decision:d1')});+ final shown = plugin.shown.first;+ expect(shown.title, 'River asks you');+ expect(shown.body, 'Open Harness to answer.');+ expect(shown.details!.android!.channelId, 'swarm-needs-you');+ expect(shown.details!.android!.subText, 'Mobile');+ expect(shown.details!.iOS!.subtitle, 'Mobile');+ expect(shown.details!.iOS!.threadIdentifier, 'swarm-needs-you');+ expect(decodeAgentPayload(shown.payload), isNull);+ });++ test('a locked phone that hides private content hides it', () async {+ await notices.showSwarm(swarm);+ final shown = plugin.shown.single;++ // Android: content hidden on a secure lock screen that hides it.+ expect(shown.details!.android!.visibility, NotificationVisibility.private);+ // iOS: when previews are hidden, who asks and where still show.+ expect(shown.details!.iOS!.categoryIdentifier, 'swarm-needs-you');+ final category = plugin.settings!.iOS!.notificationCategories.singleWhere(+ (c) => c.identifier == 'swarm-needs-you',+ );+ expect(category.options, {+ DarwinNotificationCategoryOption.hiddenPreviewShowTitle,+ DarwinNotificationCategoryOption.hiddenPreviewShowSubtitle,+ });+ });++ test('a tap opens that conversation, and no agent or device', () async {+ await notices.showSwarm(swarm);+ plugin.onResponse!(+ NotificationResponse(+ notificationResponseType: NotificationResponseType.selectedNotification,+ payload: plugin.shown.single.payload,+ ),+ );+ expect(notices.openedSwarm.value, target);+ expect(notices.opened.value, isNull);+ expect(notices.openedDevice.value, isNull);+ });++ test('the tap that launched the app from cold opens it too', () async {+ plugin.launch = NotificationAppLaunchDetails(+ true,+ notificationResponse: NotificationResponse(+ notificationResponseType: NotificationResponseType.selectedNotification,+ payload: encodeSwarmPayload(target),+ ),+ );+ await notices.requestPermission();+ expect(notices.openedSwarm.value, target);+ });++ test('taking it down cancels its own id', () async {+ await notices.cancelSwarm('decision:d1');+ expect(plugin.cancelled, [swarmNoticeIdFor('decision:d1')]);+ });++ test('a plugin that fails never throws into the Swarm', () async {+ plugin.failShow = true;+ plugin.failCancel = true;+ await notices.showSwarm(swarm);+ await notices.cancelSwarm('decision:d1');+ expect(plugin.shown, isEmpty);+ });+ });+test('nothing starts until a notice is first needed', () {expect(plugin.initialized, 0);// The app's own, over the real plugin: building it reaches no platform.@@ -126,9 +208,9 @@ void main() {expect(plugin.cancelled, [noticeIdFor(ref)]);});- test('asking permission asks both platforms for alerts and sound', () async {+ test('asking permission asks both platforms for alerts, sound and the icon count', () async {await notices.requestPermission();- expect(plugin.ios.asked, [(alert: true, sound: true)]);+ expect(plugin.ios.asked, [(alert: true, sound: true, badge: true)]);expect(plugin.android.asked, 1);});@@ -172,6 +254,48 @@ void main() {expect(notices.opened.value, isNull);});+ group("the app icon's count", () {+ const channel = MethodChannel('harness/app_badge');+ late List<MethodCall> calls;+ var fail = false;++ setUp(() {+ TestWidgetsFlutterBinding.ensureInitialized();+ calls = [];+ fail = false;+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(channel, (call) async {+ if (fail) throw PlatformException(code: 'badge');+ calls.add(call);+ return null;+ });+ });++ tearDown(() {+ debugDefaultTargetPlatformOverride = null;+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(channel, null);+ });++ test('is set on the icon on iOS', () async {+ debugDefaultTargetPlatformOverride = TargetPlatform.iOS;+ await notices.setSwarmBadge(3);+ await notices.setSwarmBadge(0);+ expect(calls.map((c) => (c.method, c.arguments)), [('set', 3), ('set', 0)]);+ });++ test('is left alone on Android, whose launchers show a dot from the notices', () async {+ debugDefaultTargetPlatformOverride = TargetPlatform.android;+ await notices.setSwarmBadge(3);+ expect(calls, isEmpty);+ });++ test('a platform that fails never throws into the Swarm', () async {+ debugDefaultTargetPlatformOverride = TargetPlatform.iOS;+ fail = true;+ await notices.setSwarmBadge(3);+ expect(calls, isEmpty);+ });+ });+group('a plugin that fails', () {test('never throws into the notifier', () async {plugin.failShow = true;@@ -290,7 +414,7 @@ class _FakePlugin implements FlutterLocalNotificationsPlugin {}class _FakeIos implements IOSFlutterLocalNotificationsPlugin {- final asked = <({bool alert, bool sound})>[];+ final asked = <({bool alert, bool sound, bool badge})>[];bool fail = false;@override@@ -304,7 +428,7 @@ class _FakeIos implements IOSFlutterLocalNotificationsPlugin {bool providesAppNotificationSettings = false,}) async {if (fail) throw PlatformException(code: 'permission');- asked.add((alert: alert, sound: sound));+ asked.add((alert: alert, sound: sound, badge: badge));return true;}diff --git a/mobile/test/phone/devices_fixture.dart b/mobile/test/phone/devices_fixture.dartindex 8eeb6d0d1..5aea49184 100644--- a/mobile/test/phone/devices_fixture.dart+++ b/mobile/test/phone/devices_fixture.dart@@ -81,7 +81,7 @@ DevLogHistoryRow historyRow(/// An app whose device list, last-seen times and removal are canned, so a page test is about what the/// page does with them.class DevicesApp extends AppNotifier {- DevicesApp({this.rows = const [], this.seen = const {}})+ DevicesApp({this.rows = const [], this.seen = const {}, super.systemNotices}): super(config: AppConfig.dev,authSession: AuthSession(),diff --git a/mobile/test/phone/out_of_sight_test.dart b/mobile/test/phone/out_of_sight_test.dartnew file mode 100644index 000000000..3e83c5f20--- /dev/null+++ b/mobile/test/phone/out_of_sight_test.dart@@ -0,0 +1,128 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/out_of_sight.dart';++/// A part of the screen kept built out of sight stops listening, and draws+/// what changed meanwhile once it is shown again.+void main() {+ late _Count count;+ late ValueNotifier<bool> hidden;+ late int built;++ setUp(() {+ count = _Count();+ hidden = ValueNotifier(false);+ built = 0;+ });+ tearDown(() {+ count.dispose();+ hidden.dispose();+ });++ Future<void> pump(WidgetTester tester) => tester.pumpWidget(+ MaterialApp(+ home: ValueListenableBuilder(+ valueListenable: hidden,+ builder: (context, isHidden, _) => OutOfSight(+ hidden: isHidden,+ child: ListenWhileInSight(+ listenable: count,+ builder: (context) {+ built++;+ return Text('${count.value}');+ },+ ),+ ),+ ),+ ),+ );++ testWidgets('in sight, it builds on every change', (tester) async {+ await pump(tester);+ count.value = 1;+ await tester.pump();+ count.value = 2;+ await tester.pump();++ expect(find.text('2'), findsOneWidget);+ expect(built, 3);+ });++ testWidgets('out of sight, it neither listens nor builds', (tester) async {+ await pump(tester);+ hidden.value = true;+ await tester.pump();+ final before = built;++ count.value = 1;+ await tester.pump();+ count.value = 2;+ await tester.pump();++ expect(built, before);+ expect(find.text('0'), findsOneWidget, reason: 'what it drew last');+ expect(count.listened, isFalse);+ });++ testWidgets('shown again, it builds once, with what is there now', (+ tester,+ ) async {+ await pump(tester);+ hidden.value = true;+ await tester.pump();+ count.value = 5;+ await tester.pump();+ final before = built;++ hidden.value = false;+ await tester.pump();++ expect(find.text('5'), findsOneWidget);+ expect(built, before + 1);+ count.value = 6;+ await tester.pump();+ expect(find.text('6'), findsOneWidget, reason: 'listening again');+ });++ testWidgets('hidden, a rebuild from above draws nothing new', (tester) async {+ await pump(tester);+ hidden.value = true;+ await tester.pump();+ final before = built;++ await pump(tester);++ expect(built, before);+ });++ testWidgets('with no OutOfSight above, it is in sight', (tester) async {+ await tester.pumpWidget(+ MaterialApp(+ home: ListenWhileInSight(+ listenable: count,+ builder: (context) => Text('${count.value}'),+ ),+ ),+ );+ count.value = 3;+ await tester.pump();++ expect(find.text('3'), findsOneWidget);+ });++ testWidgets('lets go of what it listens to when it goes', (tester) async {+ await pump(tester);+ expect(count.listened, isTrue);++ await tester.pumpWidget(const SizedBox());++ expect(count.listened, isFalse);+ });+}++/// A number that says whether anything listens to it.+class _Count extends ValueNotifier<int> {+ _Count() : super(0);++ bool get listened => hasListeners;+}diff --git a/mobile/test/phone/phone_shell_agent_notice_chat_test.dart b/mobile/test/phone/phone_shell_agent_notice_chat_test.dartnew file mode 100644index 000000000..998594b4c--- /dev/null+++ b/mobile/test/phone/phone_shell_agent_notice_chat_test.dart@@ -0,0 +1,308 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:flutter_local_notifications/flutter_local_notifications.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/notify/agent_notice.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/agent_home.dart';+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';++import '../swarm/swarm_fixture.dart';+import 'devices_fixture.dart';++class NoticeApp extends DevicesApp {+ NoticeApp({super.systemNotices});+ final fake = FakeSwarm();+ @override+ void handleAppResumed() {}+ @override+ Future<Object?> swarmRequest(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) => fake.request(method, path, body: body);+}++void main() {+ late NoticeApp app;+ setUp(() {+ app = NoticeApp()+ ..currentUser = const CurrentUserProfile(id: me, email: '[email protected]');+ app.fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm'},+ ],+ 'next': null,+ };+ });+ tearDown(() {+ experimentalFeaturesStore.value = const {};+ app.dispose();+ });++ for (final destination in ['terminal', 'home', 'page', 'back']) {+ testWidgets(+ 'explicit $destination navigation wins over a pending agent notice',+ (tester) async {+ final read = Completer<Object?>();+ app.fake.routes['/api/super-tabs/list'] = (_) => read.future;+ app.fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ groupData('g1', status: 'working', agentIds: ['agent-builder']),+ ],+ );+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await tester.pump();+ if (destination == 'back') {+ PhoneShellScope.maybeOf(tester.element(find.byType(SwarmPage)))!+ .onOpenAgent('mac-1', 'harness-agent-builder');+ await tester.pump();+ }+ app.agentNotices.system.opened.value = (+ machineId: 'mac-1',+ agentId: 'harness-agent-builder',+ );+ await tester.pump();+ final context = tester.element(+ find.byType(SwarmPage, skipOffstage: false),+ );+ final shell = PhoneShellScope.maybeOf(context)!;+ if (destination == 'terminal') {+ shell.onOpenAgent('mac-1', 'harness-agent-builder');+ } else if (destination == 'home') {+ shell.onShowSwarm!();+ } else if (destination == 'back') {+ await tester.binding.handlePopRoute();+ } else {+ unawaited(+ Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => const Text('Explicit page'),+ ),+ ),+ );+ }+ await tester.pump();+ read.complete({+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm'},+ ],+ 'next': null,+ });+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(find.byType(SwarmConversationPage), findsNothing);+ if (destination == 'terminal') {+ expect(find.byType(AgentHome), findsOneWidget);+ }+ if (destination == 'home' || destination == 'back') {+ expect(find.byType(SwarmPage), findsOneWidget);+ }+ if (destination == 'page') {+ expect(find.text('Explicit page'), findsOneWidget);+ }+ await tester.pumpWidget(const SizedBox());+ },+ );+ }++ testWidgets(+ 'cold start reads the OS tap without posting or asking permission',+ (tester) async {+ app.dispose();+ final plugin = LaunchPlugin();+ app = NoticeApp(systemNotices: LocalSystemNotices(plugin))+ ..currentUser = const CurrentUserProfile(+ id: me,+ email: '[email protected]',+ );+ app.fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm'},+ ],+ 'next': null,+ };+ app.fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(find.byType(SwarmConversationPage), findsOneWidget);+ expect(plugin.readLaunch, isTrue);+ await tester.pumpWidget(const SizedBox());+ },+ );++ for (final on in [true, false]) {+ for (final kind in NoticeKind.values) {+ testWidgets('OS ${kind.name} tap from background Swarm=$on', (+ tester,+ ) async {+ app.dispose();+ final plugin = LaunchPlugin()..launchPayload = null;+ final notices = LocalSystemNotices(plugin);+ app = NoticeApp(systemNotices: notices)+ ..currentUser = const CurrentUserProfile(+ id: me,+ email: '[email protected]',+ );+ app.fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm'},+ ],+ 'next': null,+ };+ app.fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ experimentalFeaturesStore.value = on ? {PhoneExperiment.swarm} : {};+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ for (var i = 0; i < 5; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ for (final state in [+ AppLifecycleState.inactive,+ AppLifecycleState.hidden,+ AppLifecycleState.paused,+ ]) {+ tester.binding.handleAppLifecycleStateChanged(state);+ }+ await notices.show((+ agent: (machineId: 'mac-1', agentId: 'harness-agent-builder'),+ kind: kind,+ title: 'Nova',+ machine: 'Mac',+ body: 'News',+ ));+ plugin.onResponse!(+ NotificationResponse(+ notificationResponseType:+ NotificationResponseType.selectedNotification,+ payload: plugin.shownPayload,+ ),+ );+ for (final state in [+ AppLifecycleState.hidden,+ AppLifecycleState.inactive,+ AppLifecycleState.resumed,+ ]) {+ tester.binding.handleAppLifecycleStateChanged(state);+ }+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(+ find.byType(SwarmConversationPage),+ on ? findsOneWidget : findsNothing,+ );+ expect(find.byType(AgentHome), on ? findsNothing : findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ });+ }+ }++ for (final on in [true, false]) {+ for (final cold in [true, false]) {+ for (final assigned in [true, false]) {+ testWidgets('agent notice Swarm=$on cold=$cold assigned=$assigned', (+ tester,+ ) async {+ experimentalFeaturesStore.value = on ? {PhoneExperiment.swarm} : {};+ app.fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ if (assigned)+ groupData(+ 'g1',+ status: 'working',+ workerId: 'agent-builder',+ agentIds: ['agent-builder'],+ ),+ ],+ );+ void tap() => app.agentNotices.system.opened.value = (+ machineId: 'mac-1',+ agentId: 'harness-agent-builder',+ );+ if (cold) tap();+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ if (!cold) {+ tap();+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }+ if (on) {+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect(page.conversationId, assigned ? 'g1' : leadChat);+ expect(find.byType(AgentHome), findsNothing);+ } else {+ expect(find.byType(AgentHome), findsOneWidget);+ expect(find.byType(SwarmConversationPage), findsNothing);+ }+ expect(app.agentNotices.system.opened.value, isNull);+ await tester.pumpWidget(const SizedBox());+ });+ }+ }+ }+}++class LaunchPlugin implements FlutterLocalNotificationsPlugin {+ bool readLaunch = false;+ String? launchPayload = 'swarm:tab-1/group-lead';+ String? shownPayload;+ DidReceiveNotificationResponseCallback? onResponse;+ @override+ Future<bool?> initialize({+ required InitializationSettings settings,+ DidReceiveNotificationResponseCallback? onDidReceiveNotificationResponse,+ DidReceiveBackgroundNotificationResponseCallback?+ onDidReceiveBackgroundNotificationResponse,+ }) async {+ onResponse = onDidReceiveNotificationResponse;+ return true;+ }++ @override+ Future<NotificationAppLaunchDetails?>+ getNotificationAppLaunchDetails() async {+ readLaunch = true;+ return NotificationAppLaunchDetails(+ launchPayload != null,+ notificationResponse: NotificationResponse(+ notificationResponseType: NotificationResponseType.selectedNotification,+ payload: launchPayload,+ ),+ );+ }++ @override+ Future<void> show({+ required int id,+ String? title,+ String? body,+ NotificationDetails? notificationDetails,+ String? payload,+ }) async {+ shownPayload = payload;+ }++ @override+ T? resolvePlatformSpecificImplementation<+ T extends FlutterLocalNotificationsPlatform+ >() => null;+ @override+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);+}diff --git a/mobile/test/phone/phone_shell_rebuilds_test.dart b/mobile/test/phone/phone_shell_rebuilds_test.dartnew file mode 100644index 000000000..8b2e9b57b--- /dev/null+++ b/mobile/test/phone/phone_shell_rebuilds_test.dart@@ -0,0 +1,149 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/agent_home.dart';+import 'package:harness_mobile/phone/phone_navigation.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_home_root.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';++import '../widget_rebuilds.dart';+import 'devices_fixture.dart';++/// The page stack is rebuilt from the shell only while a page that counts on+/// it is up. Swarm's pages listen for themselves, so with one of them pushed+/// an app update (an agent synced on any machine, a turn starting) rebuilds+/// nothing under it, and neither does the push itself.+void main() {+ late DevicesApp app;++ setUp(() {+ app = DevicesApp()+ ..currentUser = const CurrentUserProfile(+ id: 'person-me',+ email: '[email protected]',+ );+ // In memory only: the value, not the store's write, so nothing reaches the state file.+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ });+ tearDown(() {+ experimentalFeaturesStore.value = const {};+ app.dispose();+ });++ /// Frames enough for a page to slide in, and for the shell to hear that the+ /// stack moved. Not pumpAndSettle: Swarm keeps a poll running.+ Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 8; i++) {+ await tester.pump(const Duration(milliseconds: 150));+ }+ }++ Future<void> open(WidgetTester tester) async {+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await frames(tester);+ }++ BuildContext home(WidgetTester tester) =>+ tester.element(find.byType(SwarmPage));++ /// Three app updates, each with a frame after it.+ Future<void> ticks(WidgetTester tester) async {+ for (var i = 0; i < 3; i++) {+ app.notifyListeners();+ await tester.pump();+ }+ }++ testWidgets('with a Swarm chat pushed, app updates rebuild nothing of the '+ 'root under it', (tester) async {+ await open(tester);+ openSwarmConversation(home(tester), 'tab-b', 'g9');+ await frames(tester);+ expect(find.byType(SwarmConversationPage), findsOneWidget);++ final rebuilt = countRebuildsUnder<SwarmHomeRoot>();+ await ticks(tester);++ expect(rebuilt(), 0);+ });++ testWidgets('pushing a Swarm chat does not build Swarm Home again', (+ tester,+ ) async {+ await open(tester);++ final rebuilt = countRebuildsOf({SwarmHomeRoot, SwarmPage});+ openSwarmConversation(home(tester), 'tab-b', 'g9');+ await frames(tester);+ tester.state<NavigatorState>(find.byType(Navigator).last).pop();+ await frames(tester);++ expect(find.byType(SwarmConversationPage), findsNothing);+ expect(rebuilt(), 0, reason: 'its scroll and rows stay as they were');+ });++ group('Harness out of sight under Swarm Home', () {+ /// Harness explicitly opened, then back to Swarm Home: the terminal home+ /// is built, and kept out of sight.+ Future<void> hideHarness(WidgetTester tester) async {+ await open(tester);+ PhoneShellScope.maybeOf(tester.element(find.byType(SwarmPage)))!+ .onOpenAgent('mac-1', 'agent-1');+ await frames(tester);+ await tester.binding.handlePopRoute();+ await frames(tester);+ expect(find.byType(AgentHome), findsNothing);+ expect(find.byType(AgentHome, skipOffstage: false), findsOneWidget);+ }++ testWidgets('builds nothing on app updates', (tester) async {+ await hideHarness(tester);++ final rebuilt = countRebuildsUnder<AgentHome>();+ await ticks(tester);++ expect(rebuilt(), 0);+ });++ testWidgets('builds nothing on app updates with a page over Swarm Home '+ 'that is rebuilt on them', (tester) async {+ await hideHarness(tester);+ unawaited(+ Navigator.of(home(tester))+ .push(phoneRoute((_) => const Text('reads the app in build'))),+ );+ await frames(tester);++ final rebuilt = countRebuildsUnder<AgentHome>();+ await ticks(tester);++ expect(rebuilt(), 0);+ });+ });++ testWidgets('a page that does not listen for itself is rebuilt on every app '+ 'update, as before', (tester) async {+ await open(tester);+ var built = 0;+ unawaited(+ Navigator.of(home(tester)).push(+ phoneRoute((_) {+ built++;+ return const Text('reads the app in build');+ }),+ ),+ );+ await frames(tester);+ final before = built;++ await ticks(tester);++ expect(built - before, 3);+ });+}diff --git a/mobile/test/phone/phone_shell_swarm_files_test.dart b/mobile/test/phone/phone_shell_swarm_files_test.dartnew file mode 100644index 000000000..9bd465b96--- /dev/null+++ b/mobile/test/phone/phone_shell_swarm_files_test.dart@@ -0,0 +1,78 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/services.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/settings/experimental_features.dart';++import 'devices_fixture.dart';++/// The shell keeps Swarm's picture files to the signed-in account: at start+/// it empties what another account left, and signing out empties the rest.+void main() {+ late DevicesApp app;+ late Directory temporary;+ late Directory files;+ const pathProvider = MethodChannel('plugins.flutter.io/path_provider');++ setUp(() {+ temporary = Directory.systemTemp.createTempSync('phone-temporary-');+ files = Directory('${temporary.path}/swarm-attachments');+ // The app's private temporary folder, as the platform names it.+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(+ pathProvider,+ (call) async =>+ call.method == 'getTemporaryDirectory' ? temporary.path : null,+ );+ app = DevicesApp()+ ..currentUser = const CurrentUserProfile(+ id: 'person-me',+ email: '[email protected]',+ );+ // In memory only: the value, not the store's write, so nothing reaches the state file.+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ });+ tearDown(() {+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(pathProvider, null);+ experimentalFeaturesStore.value = const {};+ app.dispose();+ if (temporary.existsSync()) temporary.deleteSync(recursive: true);+ });++ /// Real time for the files to go, a frame after each step.+ Future<void> until(WidgetTester tester, bool Function() done) async {+ for (var i = 0; i < 100 && !done(); i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump();+ }+ expect(done(), isTrue);+ }++ File leftIn(String folder) =>+ File('${files.path}/$folder/left.png')+ ..createSync(recursive: true)+ ..writeAsBytesSync([1, 2, 3]);++ testWidgets("at start, what another account left is emptied; signing out "+ 'empties the rest', (tester) async {+ final other = leftIn('someone-else');++ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await until(tester, () => !other.existsSync());++ final mine = leftIn('anything-kept-now');+ app.currentUser = null;+ app.notifyListeners();+ await until(tester, () => !mine.existsSync());++ // The shell gone, and what its sign-out left running let run out.+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(minutes: 1));+ });+}diff --git a/mobile/test/phone/phone_shell_swarm_home_test.dart b/mobile/test/phone/phone_shell_swarm_home_test.dartnew file mode 100644index 000000000..cf6d53944--- /dev/null+++ b/mobile/test/phone/phone_shell_swarm_home_test.dart@@ -0,0 +1,248 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/phone/agent_home.dart';+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/phone/settings_page.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_computers.dart';+import 'package:harness_mobile/swarm/swarm_drawer.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import 'devices_fixture.dart';++/// With Swarm on, the app opens on Swarm Home, full screen, with Settings in+/// its drawer and no way to Harness there: Settings ▸ Swarm off is the way+/// back to it. With it off, the app opens on the terminal, as it always has.+void main() {+ late DevicesApp app;++ setUp(() {+ app = DevicesApp()+ ..currentUser = const CurrentUserProfile(+ id: 'person-me',+ email: '[email protected]',+ );+ // In memory only: the value, not the store's write, so nothing reaches the state file.+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ });+ tearDown(() {+ experimentalFeaturesStore.value = const {};+ app.dispose();+ });++ Finder key(String value) => find.byKey(ValueKey(value));++ /// Frames enough for a page to slide in or out, and for the shell to hear+ /// that the stack moved. Not pumpAndSettle: Swarm keeps a poll running.+ Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 8; i++) {+ await tester.pump(const Duration(milliseconds: 150));+ }+ }++ Future<void> open(WidgetTester tester) async {+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await frames(tester);+ }++ Future<void> drawerTo(WidgetTester tester, String row) async {+ await tester.tap(key('swarm-menu'));+ await frames(tester);+ await tester.tap(key(row));+ await frames(tester);+ }++ /// An agent explicitly opened through the shell: the terminal at the root, over Swarm+ /// Home.+ Future<void> toHarness(WidgetTester tester) async {+ PhoneShellScope.maybeOf(tester.element(find.byType(SwarmPage)))!+ .onOpenAgent('mac-1', 'agent-1');+ await frames(tester);+ }++ /// The Swarm switch in Settings ▸ Experimental, scrolled to and tapped.+ Future<void> tapSwarmSwitch(WidgetTester tester) async {+ final row = key('settings-experiment-swarm');+ await tester.scrollUntilVisible(+ row,+ 200,+ scrollable: find+ .descendant(+ of: find.byType(SettingsPage),+ matching: find.byType(Scrollable),+ )+ .first,+ );+ await tester.tap(row);+ await frames(tester);+ }++ testWidgets('with Swarm on, it opens on Swarm Home, and builds no terminal '+ 'until one is asked for', (tester) async {+ await open(tester);++ expect(find.byType(SwarmPage), findsOneWidget);+ expect(key('swarm-menu'), findsOneWidget);+ expect(key('tty-back'), findsNothing, reason: 'Home has nothing under it');+ expect(find.byType(AgentHome, skipOffstage: false), findsNothing);+ });++ testWidgets("the shell hands the app's computers to Swarm, for the start "+ 'screens, and lets go of them with itself', (tester) async {+ await open(tester);++ final computers = tester+ .widget<SwarmScope>(find.byType(SwarmScope))+ .notifier!+ .computers;+ expect(computers, isA<AppSwarmComputers>());++ await tester.pumpWidget(const SizedBox());+ expect(+ () => computers!.addListener(() {}),+ throwsFlutterError,+ reason: 'disposed with the shell',+ );+ });++ testWidgets('with Swarm off, it opens on the terminal, as it always has', (+ tester,+ ) async {+ experimentalFeaturesStore.value = const {};+ await open(tester);++ expect(find.byType(AgentHome), findsOneWidget);+ expect(find.byType(SwarmPage, skipOffstage: false), findsNothing);+ });++ testWidgets('with Swarm on, the drawer has no Harness: its models, then '+ 'Settings at its foot', (tester) async {+ await open(tester);+ await tester.tap(key('swarm-menu'));+ await frames(tester);++ final drawer = find.byType(SwarmDrawer);+ expect(key('swarm-drawer-models'), findsOneWidget);+ expect(key('swarm-drawer-settings'), findsOneWidget);+ expect(key('swarm-drawer-harness'), findsNothing);+ expect(+ find.descendant(of: drawer, matching: find.text('Harness')),+ findsNothing,+ reason: 'Settings ▸ Swarm off is the way back to Harness',+ );+ });++ testWidgets('an agent explicitly opened puts the terminal at the root; '+ 'back goes to Swarm Home; each keeps the other out of sight', (+ tester,+ ) async {+ await open(tester);++ await toHarness(tester);+ expect(find.byType(AgentHome), findsOneWidget);+ expect(find.byType(SwarmPage), findsNothing);+ expect(+ find.byType(SwarmPage, skipOffstage: false),+ findsOneWidget,+ reason: 'Home waits out of sight, as it was left',+ );++ await tester.binding.handlePopRoute();+ await frames(tester);+ expect(find.byType(SwarmPage), findsOneWidget);+ expect(find.byType(AgentHome), findsNothing);+ expect(+ find.byType(AgentHome, skipOffstage: false),+ findsOneWidget,+ reason: 'the terminal waits out of sight, as it was left',+ );+ });++ testWidgets('Settings in the drawer opens over Swarm Home', (tester) async {+ await open(tester);++ await drawerTo(tester, 'swarm-drawer-settings');+ expect(find.byType(SettingsPage), findsOneWidget);++ await tester.binding.handlePopRoute();+ await frames(tester);+ expect(find.byType(SettingsPage), findsNothing);+ expect(find.byType(SwarmPage), findsOneWidget);+ });++ testWidgets('Swarm turned off puts the terminal at the root; turned on '+ 'again, Swarm Home', (tester) async {+ await open(tester);+ await toHarness(tester);++ experimentalFeaturesStore.value = const {};+ await tester.pump();+ expect(find.byType(AgentHome), findsOneWidget);+ expect(find.byType(SwarmPage, skipOffstage: false), findsNothing);++ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ await frames(tester);+ expect(find.byType(SwarmPage), findsOneWidget);+ expect(find.byType(AgentHome), findsNothing);+ });++ testWidgets('Swarm asked for from the terminal (its mark, Find) closes '+ 'every page and puts Swarm Home at the root', (tester) async {+ await open(tester);+ await toHarness(tester);+ final terminal = tester.element(find.byType(AgentHome));+ unawaited(+ Navigator.of(terminal).push(+ MaterialPageRoute<void>(builder: (_) => const Text('a page over it')),+ ),+ );+ await frames(tester);+ expect(find.text('a page over it'), findsOneWidget);++ PhoneShellScope.maybeOf(terminal)!.onShowSwarm!();+ await frames(tester);++ expect(find.text('a page over it'), findsNothing);+ expect(find.byType(SwarmPage), findsOneWidget);+ expect(key('swarm-menu'), findsOneWidget, reason: 'the root, not pushed');+ expect(find.byType(AgentHome), findsNothing);+ expect(find.byType(AgentHome, skipOffstage: false), findsOneWidget);+ });++ testWidgets('Settings ▸ Swarm off, from the drawer, is the way to Harness: '+ 'back from Settings is the terminal; Swarm on again from its Settings is '+ 'Swarm Home', (tester) async {+ await open(tester);++ await drawerTo(tester, 'swarm-drawer-settings');+ await tapSwarmSwitch(tester);+ expect(experimentalFeaturesStore.isOn(PhoneExperiment.swarm), isFalse);+ expect(find.byType(SettingsPage), findsOneWidget, reason: 'still open');++ await tester.binding.handlePopRoute();+ await frames(tester);+ expect(find.byType(SettingsPage), findsNothing);+ expect(find.byType(AgentHome), findsOneWidget);+ expect(find.byType(SwarmPage, skipOffstage: false), findsNothing);++ // The terminal's Settings (its menu, Find), as the person reaches it.+ openPhoneSettings(tester.element(find.byType(AgentHome)), app);+ await frames(tester);+ await tapSwarmSwitch(tester);+ await tester.tap(find.text('Turn on Swarm'));+ await frames(tester);+ expect(experimentalFeaturesStore.isOn(PhoneExperiment.swarm), isTrue);+ expect(find.byType(SettingsPage), findsOneWidget, reason: 'back in it');++ await tester.binding.handlePopRoute();+ await frames(tester);+ expect(find.byType(SwarmPage), findsOneWidget);+ expect(key('swarm-menu'), findsOneWidget, reason: 'the root, not pushed');+ expect(find.byType(AgentHome), findsNothing);+ });+}diff --git a/mobile/test/phone/phone_shell_swarm_notice_test.dart b/mobile/test/phone/phone_shell_swarm_notice_test.dartnew file mode 100644index 000000000..5ae353b4f--- /dev/null+++ b/mobile/test/phone/phone_shell_swarm_notice_test.dart@@ -0,0 +1,142 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/agent_home.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';++import 'devices_fixture.dart';++/// A tapped Swarm notice opens the conversation it was about, over the Swarm+/// page — also when the tap is what launched the app.+void main() {+ late DevicesApp app;++ setUp(() {+ app = _NoticeApp()+ ..currentUser = const CurrentUserProfile(+ id: 'person-me',+ email: '[email protected]',+ );+ // In memory only: the value, not the store's write, so nothing reaches the state file.+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ });+ tearDown(() {+ experimentalFeaturesStore.value = const {};+ app.dispose();+ });++ SwarmNotices notices() => app.agentNotices.system as SwarmNotices;++ void expectOpened(WidgetTester tester) {+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), ('tab-b', 'g9'));+ expect(find.byType(SwarmPage, skipOffstage: false), findsOneWidget);+ expect(notices().openedSwarm.value, isNull, reason: 'the tap is spent');+ }++ for (final on in [true, false]) {+ for (final start in ['foreground', 'background', 'cold']) {+ for (final kind in ['project', 'pm', 'group', 'decision', 'work']) {+ testWidgets('$kind notice Swarm=$on $start', (tester) async {+ experimentalFeaturesStore.value = on ? {PhoneExperiment.swarm} : {};+ final target = (+ swarmId: 'tab-b',+ conversationId: kind == 'pm'+ ? 'private-pm'+ : kind == 'project'+ ? 'project-chat'+ : 'g9',+ messageId: const ['project', 'pm', 'group'].contains(kind)+ ? 'm7'+ : null,+ decisionId: kind == 'decision' ? 'd1' : null,+ );+ if (start == 'cold') notices().openedSwarm.value = target;+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await tester.pump();+ if (start == 'background') {+ for (final state in [+ AppLifecycleState.inactive,+ AppLifecycleState.hidden,+ AppLifecycleState.paused,+ ]) {+ tester.binding.handleAppLifecycleStateChanged(state);+ }+ }+ if (start != 'cold') notices().openedSwarm.value = target;+ if (start == 'background') {+ for (final state in [+ AppLifecycleState.hidden,+ AppLifecycleState.inactive,+ AppLifecycleState.resumed,+ ]) {+ tester.binding.handleAppLifecycleStateChanged(state);+ }+ }+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 400));+ if (on) {+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect(page.conversationId, target.conversationId);+ expect(page.messageId, target.messageId);+ expect(page.decisionId, target.decisionId);+ } else {+ expect(find.byType(SwarmConversationPage), findsNothing);+ expect(find.byType(AgentHome), findsOneWidget);+ }+ expect(notices().openedSwarm.value, isNull);+ await tester.pumpWidget(const SizedBox());+ tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ );+ });+ }+ }+ }++ testWidgets('a tap opens its conversation over the Swarm page', (+ tester,+ ) async {+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await tester.pump();++ notices().openedSwarm.value = (+ swarmId: 'tab-b',+ conversationId: 'g9',+ messageId: null,+ decisionId: null,+ );+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));++ expectOpened(tester);+ });++ testWidgets('a tap that launched the app opens it too', (tester) async {+ // Read before the shell exists, so no listener sees it change.+ notices().openedSwarm.value = (+ swarmId: 'tab-b',+ conversationId: 'g9',+ messageId: null,+ decisionId: null,+ );+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));++ expectOpened(tester);+ });+}++class _NoticeApp extends DevicesApp {+ @override+ void handleAppResumed() {}+}diff --git a/mobile/test/phone/phone_shell_swarm_voice_test.dart b/mobile/test/phone/phone_shell_swarm_voice_test.dartnew file mode 100644index 000000000..d5f88e3ec--- /dev/null+++ b/mobile/test/phone/phone_shell_swarm_voice_test.dart@@ -0,0 +1,73 @@+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/voice_input_controller.dart';+import 'package:harness_mobile/phone/voice_input_scope.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'devices_fixture.dart';++/// The shell hands its Swarm chats a mic: the terminal's speech-to-text, or+/// in sample mode the sample's own, which records nothing.+void main() {+ late DevicesApp app;++ setUp(() {+ app = _ShellApp()+ ..currentUser = const CurrentUserProfile(+ id: 'person-me',+ email: '[email protected]',+ );+ // In memory only: the value, not the store's write, so nothing reaches the state file.+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ });+ tearDown(() {+ experimentalFeaturesStore.value = const {};+ app.dispose();+ });++ SwarmHost host(WidgetTester tester) =>+ tester.widget<SwarmScope>(find.byType(SwarmScope)).notifier!;++ testWidgets('a Swarm chat in the shell can be talked to', (tester) async {+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await tester.pump();+ // The shell's first reads, on their timers, as a launch has them.+ await tester.pump(const Duration(seconds: 1));++ expect(host(tester).voice, isNotNull);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets('in sample mode a Swarm chat hears through the sample', (+ tester,+ ) async {+ final sample = VoiceInputController(+ transcriber: (_, _) async => '',+ recorder: FakeVoiceRecorder(),+ );+ addTearDown(sample.dispose);+ await tester.pumpWidget(+ MaterialApp(+ home: VoiceInputScope(+ create: () => sample,+ child: PhoneShell(notifier: app),+ ),+ ),+ );+ await tester.pump();+ // The shell's first reads, on their timers, as a launch has them.+ await tester.pump(const Duration(seconds: 1));++ expect(host(tester).voice!(), same(sample));+ await tester.pumpWidget(const SizedBox());+ });+}++class _ShellApp extends DevicesApp {+ @override+ void handleAppResumed() {}+}diff --git a/mobile/test/phone_edge/find_behavior_test.dart b/mobile/test/phone_edge/find_behavior_test.dartindex 47bdee98a..22e520f54 100644--- a/mobile/test/phone_edge/find_behavior_test.dart+++ b/mobile/test/phone_edge/find_behavior_test.dart@@ -57,7 +57,11 @@ void main() {FakeTranscriber stt,})>- openFind(WidgetTester tester, {bool handshaken = false}) async {+ openFind(+ WidgetTester tester, {+ bool handshaken = false,+ VoidCallback? onShowSwarm,+ }) async {setPhone(tester, largePhone);final app = edgeApp(conn: EdgeConn(const {}, machine)..handshaken = handshaken,@@ -93,6 +97,7 @@ void main() {PhoneShellScope(onMachineLinked: (_) {},onOpenAgent: (machineId, agentId) => opened.add((machineId, agentId)),+ onShowSwarm: onShowSwarm,child: phoneApp(Scaffold(body: TerminalSearchOverlay(@@ -288,7 +293,29 @@ void main() {await frames(tester, count: 6);expect(closes, isNotEmpty);expect(find.byType(SwarmPage), findsOneWidget);- expect(find.byKey(const ValueKey('swarm-building')), findsOneWidget);+ // Outside a signed-in shell there is no account's Swarm to read: the page says so.+ expect(find.byKey(const ValueKey('swarm-unavailable')), findsOneWidget);+ await close(tester, app);+ });++ testWidgets('in the shell, Swarm goes back to Swarm Home, the root', (+ tester,+ ) async {+ addTearDown(() => experimentalFeaturesStore.value = const {});+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ var shown = 0;+ final (:app, :closes, opened: _, voice: _, stt: _) = await openFind(+ tester,+ onShowSwarm: () => shown++,+ );+ await tester.enterText(find.byType(TextField), 'swar');+ await frames(tester);+ await tester.tap(find.text('Swarm', findRichText: true).last);+ await frames(tester, count: 6);++ expect(closes, isNotEmpty);+ expect(shown, 1);+ expect(find.byType(SwarmPage), findsNothing, reason: 'not a page over it');await close(tester, app);});diff --git a/mobile/test/phone_edge/settings_behavior_test.dart b/mobile/test/phone_edge/settings_behavior_test.dartindex 2d2fd7060..c8b98a31f 100644--- a/mobile/test/phone_edge/settings_behavior_test.dart+++ b/mobile/test/phone_edge/settings_behavior_test.dart@@ -235,7 +235,7 @@ void main() {});testWidgets(- 'Experimental: Swarm is off until switched, by the row or its switch',+ 'Experimental: Swarm is turned on from its page, and off at once',(tester) async {final storage = MemoryKeyValueStore();final experiments = ExperimentalFeaturesStore(storage: storage);@@ -251,14 +251,44 @@ void main() {find.descendant(of: row, matching: find.text('Swarm')),findsOneWidget,);+ expect(+ find.descendant(+ of: row,+ matching: find.text(+ 'Open your Swarms from Home or Find. Still taking shape.',+ ),+ ),+ findsOneWidget,+ reason: 'both ways in, as the app has them',+ );Switch toggle() => tester.widget<Switch>(find.descendant(of: row, matching: find.byType(Switch)),);expect(toggle().value, isFalse);- // Anywhere on the row turns it on, and the choice is written for the next launch.+ // Anywhere on the row opens what Swarm does, with Not now and Turn on Swarm.await tester.tap(find.descendant(of: row, matching: find.text('Swarm')));- await frames(tester);+ await frames(tester, count: 8);+ expect(find.text('Your team of agents, on your phone'), findsOneWidget);+ expect(find.text('See what needs you'), findsOneWidget);+ expect(find.text('Answer in one tap'), findsOneWidget);+ expect(find.text('Brainstorm with your Buddy'), findsOneWidget);+ expect(find.text('Chat with your PM'), findsNothing);+ await tester.tap(find.text('Not now'));+ // A page's slide out takes longer than [frames]' default.+ await frames(tester, count: 8);+ expect(find.text('Your team of agents, on your phone'), findsNothing);+ expect(toggle().value, isFalse);+ expect(experiments.isOn(PhoneExperiment.swarm), isFalse);++ // The switch opens it too; Turn on Swarm turns it on, back in Settings, and the choice is+ // written for the next launch.+ await tester.tap(find.descendant(of: row, matching: find.byType(Switch)));+ await frames(tester, count: 8);+ expect(find.text('Your team of agents, on your phone'), findsOneWidget);+ await tester.tap(find.text('Turn on Swarm'));+ await frames(tester, count: 8);+ expect(find.text('Your team of agents, on your phone'), findsNothing);expect(toggle().value, isTrue);expect(experiments.isOn(PhoneExperiment.swarm), isTrue);expect(storage.values['experimental_features'], '["swarm"]');diff --git a/mobile/test/render/swarm_attach_render_test.dart b/mobile/test/render/swarm_attach_render_test.dartnew file mode 100644index 000000000..490f75009--- /dev/null+++ b/mobile/test/render/swarm_attach_render_test.dart@@ -0,0 +1,322 @@+import 'dart:async';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_file_picker.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:image_picker/image_picker.dart' show XFile;++import '../voice_fakes.dart';+import '../swarm/swarm_fixture.dart';++/// Renders a phone Swarm chat attaching files — the composer with files, an upload under way,+/// the + sheet and the camera-off box — in light and dark, at iPhone 14 size in the system+/// fonts, to PNGs a reviewer can look at without a phone.+///+/// Skipped unless PHONE_RENDER_DIR names a directory to write into:+///+/// PHONE_RENDER_DIR=/tmp/renders flutter test test/render/swarm_attach_render_test.dart+///+/// macOS only: it loads SF Pro and SF Mono from /System/Library/Fonts.+final _outDir = Platform.environment['PHONE_RENDER_DIR'];++Future<void> _loadFonts() async {+ Future<void> load(String family, String file) async {+ final bytes = await File('/System/Library/Fonts/$file').readAsBytes();+ await (FontLoader(+ family,+ )..addFont(Future.value(ByteData.view(bytes.buffer)))).load();+ }++ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {+ await load(family, 'SFNS.ttf');+ }+ for (final family in ['.AppleSystemUIFontMonospaced', 'SF Mono']) {+ await load(family, 'SFNSMono.ttf');+ }+ // The icons, from the package in the pub cache.+ final lucide =+ '${Platform.environment['HOME']}/.pub-cache/hosted/pub.dev/lucide_icons_flutter-3.1.19/assets';+ Future<void> icons(String family, String file) async {+ final bytes = await File('$lucide/$file').readAsBytes();+ await (FontLoader(+ family,+ )..addFont(Future.value(ByteData.view(bytes.buffer)))).load();+ }++ await icons('packages/lucide_icons_flutter/Lucide', 'lucide.ttf');+ for (final weight in [100, 200, 300, 400, 500, 600]) {+ await icons(+ 'packages/lucide_icons_flutter/Lucide$weight',+ 'build_font/LucideVariable-w$weight.ttf',+ );+ }+}++/// A photo-like picture: a sky over a field, encoded as PNG.+Future<Uint8List> _photo(Color sky, Color ground) async {+ final recorder = ui.PictureRecorder();+ final canvas = Canvas(recorder);+ canvas.drawRect(const Rect.fromLTWH(0, 0, 120, 80), Paint()..color = sky);+ canvas.drawRect(const Rect.fromLTWH(0, 50, 120, 30), Paint()..color = ground);+ canvas.drawCircle(const Offset(90, 22), 10, Paint()..color = Colors.amber);+ final image = await recorder.endRecording().toImage(120, 80);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ return png!.buffer.asUint8List();+}++void main() {+ final skip = _outDir == null;+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';++ final original = (+ photos: pickSwarmPhotos,+ camera: takeSwarmPhoto,+ documents: pickSwarmFiles,+ copies: swarmPickerCopyFolders,+ );+ setUp(() => swarmPickerCopyFolders = () async => const []);+ tearDown(() {+ swarmPickerCopyFolders = original.copies;+ pickSwarmPhotos = original.photos;+ takeSwarmPhoto = original.camera;+ pickSwarmFiles = original.documents;+ });++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Login crash on iPhone',+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ lastMessageSequence: 2,+ ),+ ],+ ),+ '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>[],+ };+ Map<String, dynamic> message(+ String id,+ int sequence,+ String text,+ Map<String, dynamic> author, {+ List<Map<String, dynamic>> attachments = const [],+ }) => {+ 'id': id,+ 'conversationId': 'g1',+ 'text': text,+ 'sequence': sequence,+ 'author': author,+ 'attachments': attachments,+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 10, 28, 4, sequence).toIso8601String(),+ };+ fake.routes[messages] = (_) => {+ 'messages': [+ message(+ 'm2',+ 2,+ 'Here is the crash and the log.',+ {'kind': 'person', 'id': me, 'name': 'tony'},+ attachments: [+ {+ 'id': 'f1',+ 'name': 'crash.log',+ 'mime': 'text/plain',+ 'size': 12 * 1024,+ 'url': 'https://cdn.harness.autonomous.ai/f1/crash.log',+ },+ ],+ ),+ message('m1', 1, 'Can you send what you see on the phone?', {+ 'kind': 'agent',+ 'id': 'agent-lead',+ 'name': 'River',+ }),+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (_) =>+ Completer<Object?>().future;+ return fake;+ }++ /// Uploads held where they are, a fixed part of the way up.+ Future<Map<String, dynamic>> stuck({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required dynamic cancel,+ required void Function(double sent) onProgress,+ }) {+ onProgress(0.6);+ return Completer<Map<String, dynamic>>().future;+ }++ Future<void> shoot(WidgetTester tester, GlobalKey key, String name) async {+ await tester.runAsync(() async {+ final boundary =+ key.currentContext!.findRenderObject()! as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ final file = File('$_outDir/$name.png');+ await file.parent.create(recursive: true);+ await file.writeAsBytes(png!.buffer.asUint8List());+ });+ }++ for (final brightness in Brightness.values) {+ final look = brightness.name;++ Future<GlobalKey> chat(WidgetTester tester, {SwarmUpload? upload}) async {+ await tester.runAsync(_loadFonts);+ final photos = (await tester.runAsync(+ () async => [+ await _photo(const Color(0xFF7FB2E5), const Color(0xFF5E8C4A)),+ await _photo(const Color(0xFFE9A86B), const Color(0xFF3F5B73)),+ ],+ ))!;+ pickSwarmPhotos = (limit) async => [+ XFile.fromData(photos[0], path: '/copies/IMG_2041.jpg'),+ XFile.fromData(photos[1], path: '/copies/IMG_2050.jpg'),+ ];+ pickSwarmFiles = () async => [+ XFile.fromData(+ Uint8List(640 * 1024),+ path: '/copies/report.pdf',+ length: 640 * 1024,+ ),+ ];+ takeSwarmPhoto = () async =>+ throw PlatformException(code: 'camera_access_denied');++ // A palette carries its brightness: a light one is how the app goes light.+ final palette = HarnessPalette.values.firstWhere(+ (p) => p.brightness == brightness,+ );+ final previous = (+ grid.AppTheme.brightness.value,+ grid.AppTheme.palette.value,+ );+ grid.AppTheme.palette.value = palette;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() {+ grid.AppTheme.brightness.value = previous.$1;+ grid.AppTheme.palette.value = previous.$2;+ });+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);+ tester.view.viewPadding = const FakeViewPadding(+ top: 47 * 3,+ bottom: 34 * 3,+ );+ addTearDown(tester.view.reset);++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ upload: upload ?? stuck,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ final key = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: key,+ child: grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmConversationPage(+ swarmId: tab,+ conversationId: 'g1',+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return key;+ }++ Future<void> pick(WidgetTester tester, String row) async {+ await tester.tap(find.byKey(const ValueKey('swarm-attach')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(ValueKey(row)));+ await tester.pumpAndSettle();+ // Thumbnails decode on the real clock, not the test's.+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 300)),+ );+ await tester.pumpAndSettle();+ }++ testWidgets('composer with files ($look)', skip: skip, (tester) async {+ final key = await chat(tester);+ await pick(tester, 'swarm-attach-library');+ await pick(tester, 'swarm-attach-files');+ await tester.enterText(find.byType(TextField), 'Here are the shots');+ await tester.pumpAndSettle();+ await shoot(tester, key, 'swarm-attach-composer-$look');+ });++ testWidgets('upload under way ($look)', skip: skip, (tester) async {+ final key = await chat(tester);+ await pick(tester, 'swarm-attach-library');+ await tester.tap(find.byKey(const ValueKey('swarm-send')));+ await tester.pump();+ await tester.pump();+ await shoot(tester, key, 'swarm-attach-uploading-$look');+ });++ testWidgets('the + sheet ($look)', skip: skip, (tester) async {+ final key = await chat(tester);+ await tester.tap(find.byKey(const ValueKey('swarm-attach')));+ await tester.pumpAndSettle();+ await shoot(tester, key, 'swarm-attach-sheet-$look');+ });++ testWidgets('camera access off ($look)', skip: skip, (tester) async {+ final key = await chat(tester);+ await pick(tester, 'swarm-attach-camera');+ await shoot(tester, key, 'swarm-attach-camera-off-$look');+ });+ }+}diff --git a/mobile/test/render/swarm_project_render_test.dart b/mobile/test/render/swarm_project_render_test.dartnew file mode 100644index 000000000..daade2a60--- /dev/null+++ b/mobile/test/render/swarm_project_render_test.dart@@ -0,0 +1,299 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import '../swarm/swarm_fixture.dart';++/// Renders a phone Swarm project as prototype B draws it — its project chat+/// under the project's name with its ⋮ menu at the top right and nothing under+/// the header, the menu with nothing or something waiting on the person, and+/// the sheet its status opens on its Work and its Team — in light and dark, at+/// iPhone 14 size in the system fonts, to PNGs a reviewer can look at without+/// a phone.+///+/// Skipped unless PHONE_RENDER_DIR names a directory to write into:+///+/// PHONE_RENDER_DIR=/tmp/renders flutter test test/render/swarm_project_render_test.dart+///+/// macOS only: it loads SF Pro and SF Mono from /System/Library/Fonts.+final _outDir = Platform.environment['PHONE_RENDER_DIR'];++Future<void> _loadFonts() async {+ Future<void> load(String family, String file) async {+ final bytes = await File('/System/Library/Fonts/$file').readAsBytes();+ await (FontLoader(+ family,+ )..addFont(Future.value(ByteData.view(bytes.buffer)))).load();+ }++ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {+ await load(family, 'SFNS.ttf');+ }+ for (final family in ['.AppleSystemUIFontMonospaced', 'SF Mono']) {+ await load(family, 'SFNSMono.ttf');+ }+ // The icons, from the package in the pub cache.+ final lucide =+ '${Platform.environment['HOME']}/.pub-cache/hosted/pub.dev/lucide_icons_flutter-3.1.19/assets';+ Future<void> icons(String family, String file) async {+ final bytes = await File('$lucide/$file').readAsBytes();+ await (FontLoader(+ family,+ )..addFont(Future.value(ByteData.view(bytes.buffer)))).load();+ }++ await icons('packages/lucide_icons_flutter/Lucide', 'lucide.ttf');+ for (final weight in [100, 200, 300, 400, 500, 600]) {+ await icons(+ 'packages/lucide_icons_flutter/Lucide$weight',+ 'build_font/LucideVariable-w$weight.ttf',+ );+ }+}++void main() {+ final skip = _outDir == null;++ /// A project of four agents: its Product Manager idle, two at work, one+ /// down; and Fix login, waiting on the person when [waiting].+ FakeSwarm backend({required bool waiting}) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ final derived = {'decisionsWaiting': waiting ? 1 : 0};+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ derived: derived,+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ agent('agent-reviewer', name: 'Reviewer', displayName: 'Ken'),+ {+ ...agent('agent-tester', name: 'Tester', displayName: 'Pike'),+ 'downSince': '2026-10-28T03:00:00.000Z',+ },+ ],+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ number: 4,+ agentIds: ['agent-lead', 'agent-builder'],+ status: waiting ? 'needs_human' : 'working',+ workerId: 'agent-builder',+ lastMessageSequence: 12,+ ),+ groupData(+ 'g2',+ title: 'Skeleton rows on Home',+ number: 5,+ agentIds: ['agent-lead', 'agent-reviewer'],+ status: 'review',+ workerId: 'agent-reviewer',+ lastMessageSequence: 9,+ ),+ groupData(+ 'g3',+ title: 'Lazy project list',+ number: 6,+ agentIds: ['agent-lead', 'agent-tester'],+ status: 'working',+ workerId: 'agent-tester',+ lastMessageSequence: 7,+ ),+ ],+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/groups?dormant=1&projectId=$project'] = (+ _,+ ) => {'groups': <Object>[], 'next': null};+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ if (waiting)+ {+ 'id': 'd1',+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'askerName': 'Nova',+ 'question': 'Ship it behind a flag?',+ 'options': ['Yes', 'No'],+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ Map<String, dynamic> message(+ int sequence,+ String text,+ Map<String, dynamic> author,+ ) => {+ 'id': 'm$sequence',+ 'conversationId': leadChat,+ 'text': text,+ 'sequence': sequence,+ 'author': author,+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 10, 28, 4, sequence).toIso8601String(),+ };+ const river = {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'};+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =+ (_) => {+ 'messages': [+ message(+ 3,+ 'Nova is on Fix login, Ken reviews the skeleton rows. Pike is '+ 'down; I will hand Lazy project list on if it stays down.',+ river,+ ),+ message(2, 'Where are we on the login crash?', {+ 'kind': 'person',+ 'id': me,+ 'name': 'tony',+ }),+ message(1, 'Morning. Three things open in Mobile today.', river),+ ],+ 'next': null,+ };+ return fake;+ }++ Future<void> shoot(WidgetTester tester, GlobalKey key, String name) async {+ await tester.runAsync(() async {+ final boundary =+ key.currentContext!.findRenderObject()! as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ final file = File('$_outDir/$name.png');+ await file.parent.create(recursive: true);+ await file.writeAsBytes(png!.buffer.asUint8List());+ });+ }++ for (final brightness in Brightness.values) {+ final look = brightness.name;++ Future<GlobalKey> page(WidgetTester tester, {bool waiting = false}) async {+ await tester.runAsync(_loadFonts);+ // A palette carries its brightness: a light one is how the app goes light.+ final palette = HarnessPalette.values.firstWhere(+ (p) => p.brightness == brightness,+ );+ final previous = (+ grid.AppTheme.brightness.value,+ grid.AppTheme.palette.value,+ );+ grid.AppTheme.palette.value = palette;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() {+ grid.AppTheme.brightness.value = previous.$1;+ grid.AppTheme.palette.value = previous.$2;+ });+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);+ tester.view.viewPadding = const FakeViewPadding(+ top: 47 * 3,+ bottom: 34 * 3,+ );+ addTearDown(tester.view.reset);++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend(waiting: waiting).request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ final key = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: key,+ child: grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmProjectPage(swarmId: tab, projectId: project),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return key;+ }++ Future<void> openMenu(WidgetTester tester) async {+ await tester.tap(find.byKey(const ValueKey('swarm-project-menu')));+ await tester.pumpAndSettle();+ }++ Future<void> openSheet(WidgetTester tester) async {+ await openMenu(tester);+ await tester.tap(find.byKey(const ValueKey('swarm-project-menu-status')));+ await tester.pumpAndSettle();+ }++ testWidgets('project chat ($look)', skip: skip, (tester) async {+ final key = await page(tester);+ await shoot(tester, key, 'swarm-project-chat-$look');+ });++ testWidgets('project chat, work waiting ($look)', skip: skip, (+ tester,+ ) async {+ final key = await page(tester, waiting: true);+ await shoot(tester, key, 'swarm-project-waiting-$look');+ });++ testWidgets('its menu ($look)', skip: skip, (tester) async {+ final key = await page(tester);+ await openMenu(tester);+ await shoot(tester, key, 'swarm-project-menu-$look');+ });++ testWidgets('its menu, work waiting ($look)', skip: skip, (tester) async {+ final key = await page(tester, waiting: true);+ await openMenu(tester);+ await shoot(tester, key, 'swarm-project-menu-waiting-$look');+ });++ testWidgets('the sheet on Work ($look)', skip: skip, (tester) async {+ final key = await page(tester, waiting: true);+ await openSheet(tester);+ await shoot(tester, key, 'swarm-project-work-$look');+ });++ testWidgets('the sheet on Team ($look)', skip: skip, (tester) async {+ final key = await page(tester, waiting: true);+ await openSheet(tester);+ await tester.tap(find.byKey(const ValueKey('swarm-sheet-team')));+ await tester.pumpAndSettle();+ await shoot(tester, key, 'swarm-project-team-$look');+ });+ }+}diff --git a/mobile/test/render/swarm_voice_render_test.dart b/mobile/test/render/swarm_voice_render_test.dartnew file mode 100644index 000000000..c186411e2--- /dev/null+++ b/mobile/test/render/swarm_voice_render_test.dart@@ -0,0 +1,245 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/foundation.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/phone/voice_input_controller.dart';+import 'package:harness_mobile/phone/voice_recorder.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+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/swarm_fixture.dart';++/// Renders a phone Swarm chat's mic — at rest, listening, with what was heard+/// in the box, and refused — in light and dark, at iPhone 14 size in the+/// system fonts, to PNGs a reviewer can look at without a phone.+///+/// Skipped unless PHONE_RENDER_DIR names a directory to write into:+///+/// PHONE_RENDER_DIR=/tmp/renders flutter test test/render/swarm_voice_render_test.dart+///+/// macOS only: it loads SF Pro and SF Mono from /System/Library/Fonts.+final _outDir = Platform.environment['PHONE_RENDER_DIR'];++Future<void> _loadFonts() async {+ Future<void> load(String family, String file) async {+ final bytes = await File('/System/Library/Fonts/$file').readAsBytes();+ await (FontLoader(+ family,+ )..addFont(Future.value(ByteData.view(bytes.buffer)))).load();+ }++ for (final family in ['.AppleSystemUIFont', 'SF Pro Text', 'Roboto']) {+ await load(family, 'SFNS.ttf');+ }+ for (final family in ['.AppleSystemUIFontMonospaced', 'SF Mono']) {+ await load(family, 'SFNSMono.ttf');+ }+ // The icons, from the package in the pub cache.+ final lucide =+ '${Platform.environment['HOME']}/.pub-cache/hosted/pub.dev/lucide_icons_flutter-3.1.19/assets';+ Future<void> icons(String family, String file) async {+ final bytes = await File('$lucide/$file').readAsBytes();+ await (FontLoader(+ family,+ )..addFont(Future.value(ByteData.view(bytes.buffer)))).load();+ }++ await icons('packages/lucide_icons_flutter/Lucide', 'lucide.ttf');+ for (final weight in [100, 200, 300, 400, 500, 600]) {+ await icons(+ 'packages/lucide_icons_flutter/Lucide$weight',+ 'build_font/LucideVariable-w$weight.ttf',+ );+ }+}++void main() {+ final skip = _outDir == null;+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Login crash on iPhone',+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ lastMessageSequence: 1,+ ),+ ],+ );+ 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': 'm1',+ 'conversationId': 'g1',+ 'text': 'The fix is ready. Ship it to TestFlight today?',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 10, 28, 4, 1).toIso8601String(),+ },+ ],+ 'next': null,+ };+ return fake;+ }++ Future<void> shoot(WidgetTester tester, GlobalKey key, String name) async {+ await tester.runAsync(() async {+ final boundary =+ key.currentContext!.findRenderObject()! as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ final file = File('$_outDir/$name.png');+ await file.parent.create(recursive: true);+ await file.writeAsBytes(png!.buffer.asUint8List());+ });+ }++ for (final brightness in Brightness.values) {+ final look = brightness.name;++ Future<GlobalKey> chat(+ WidgetTester tester,+ _MeteredRecorder recorder,+ FakeTranscriber stt,+ ) async {+ await tester.runAsync(_loadFonts);+ // A palette carries its brightness: a light one is how the app goes light.+ final palette = HarnessPalette.values.firstWhere(+ (p) => p.brightness == brightness,+ );+ final previous = (+ grid.AppTheme.brightness.value,+ grid.AppTheme.palette.value,+ );+ grid.AppTheme.palette.value = palette;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() {+ grid.AppTheme.brightness.value = previous.$1;+ grid.AppTheme.palette.value = previous.$2;+ });+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);+ tester.view.viewPadding = const FakeViewPadding(+ top: 47 * 3,+ bottom: 34 * 3,+ );+ addTearDown(tester.view.reset);++ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ notices: SilentSystemNotices(),+ features: features,+ voice: () => VoiceInputController(+ transcriber: stt.call,+ recorder: recorder,+ language: ValueNotifier('en'),+ ),+ )..foreground = false;+ addTearDown(host.dispose);+ final key = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: key,+ child: grid.BrightnessScope(+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: const SwarmConversationPage(+ swarmId: tab,+ conversationId: 'g1',+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return key;+ }++ Future<void> tapMic(WidgetTester tester) async {+ await tester.tap(find.byKey(const ValueKey('swarm-mic')));+ for (var i = 0; i < 5; i++) {+ await tester.pump();+ }+ }++ testWidgets('mic at rest ($look)', skip: skip, (tester) async {+ final key = await chat(tester, _MeteredRecorder(), FakeTranscriber());+ await shoot(tester, key, 'swarm-voice-rest-$look');+ });++ testWidgets('listening ($look)', skip: skip, (tester) async {+ final recorder = _MeteredRecorder();+ final key = await chat(tester, recorder, FakeTranscriber());+ await tapMic(tester);+ recorder.meter.value = 0.7;+ await tester.pump(const Duration(milliseconds: 400));+ await shoot(tester, key, 'swarm-voice-listening-$look');+ });++ testWidgets('heard into the box ($look)', skip: skip, (tester) async {+ final stt = FakeTranscriber()+ ..replies.add('Yes, ship it today and tell me when it is up.');+ final key = await chat(tester, _MeteredRecorder(), stt);+ await tapMic(tester);+ await tapMic(tester);+ await tester.pumpAndSettle();+ await shoot(tester, key, 'swarm-voice-heard-$look');+ });++ testWidgets('mic refused ($look)', skip: skip, (tester) async {+ final key = await chat(+ tester,+ _MeteredRecorder()..permitted = false,+ FakeTranscriber(),+ );+ await tapMic(tester);+ await tester.pumpAndSettle();+ await shoot(tester, key, 'swarm-voice-refused-$look');+ });+ }+}++/// A microphone that also says how loud it is: what the bars follow.+class _MeteredRecorder extends FakeVoiceRecorder implements VoiceLevelMeter {+ final meter = ValueNotifier<double>(0);++ @override+ ValueListenable<double> get level => meter;+}diff --git a/mobile/test/swarm/desktop_parity_test.dart b/mobile/test/swarm/desktop_parity_test.dartnew file mode 100644index 000000000..12ea38799--- /dev/null+++ b/mobile/test/swarm/desktop_parity_test.dart@@ -0,0 +1,86 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_buddy.dart';++/// The Swarm models the phone carries as copies of the desktop's+/// (`../desktop/lib/super_tabs`): phone path → desktop path. The phone is a+/// standalone package (README), so it cannot import them.+///+/// ⚠️ A fix made to one side only fails nowhere else: a field the backend adds+/// would parse on a computer and be dropped on the phone. Here a drift fails+/// until the change is carried across — or, if the two are meant to differ now,+/// until the file leaves this list on purpose.+const _copies = {+ 'lib/swarm/parts.dart': 'lib/super_tabs/parts.dart',+ 'lib/swarm/profile_model.dart': 'lib/super_tabs/profile_model.dart',+};++/// The phone's model is ahead of main's desktop copy, so it is no exact copy+/// for now: it also keeps a read's lookups by id, cached once per read, and+/// each conversation's reaction counter (`reactionSeq`), which the phone's+/// chat needs and the desktop's model has not taken yet (the phone line,+/// merged into main without its desktop changes, 10-29). It still reads+/// every field the desktop's does, so nothing the backend adds is parsed on+/// a computer and dropped on the phone. Back in [_copies] once the desktop's+/// model carries them.+///+/// Chat threads (#2132), PM ruling 10-29: the phone has no thread view yet,+/// so a reply only in its thread stays in the chat, inline, and nothing is+/// lost; but unread and bold follow the desktop's main-stream rule+/// (`lastMainSequence`, [SuperTabConversation.mainSequence]), so a reply only+/// in its thread makes a chat unread on neither. The phone reads a message's+/// thread and the thread summaries as the desktop does, and shows none yet.+const _model = ('lib/swarm/model.dart', 'lib/super_tabs/model.dart');++void main() {+ test("${_model.$1} reads every field the desktop's ${_model.$2} reads", () {+ final reads = RegExp(+ r"(?:row|start|json)\['(\w+)'\]|_text\(row, '(\w+)'\)",+ );+ Set<String> fields(String path) => {+ for (final m in reads.allMatches(File(path).readAsStringSync()))+ (m.group(1) ?? m.group(2))!,+ };+ final desktop = fields('../desktop/${_model.$2}');+ expect(desktop, isNotEmpty);+ expect(desktop.difference(fields(_model.$1)), isEmpty);+ });++ test(+ 'a Buddy engine the server refuses is refused in the desktop\'s words',+ () {+ // The backend checks the desktop's words against its own refusal+ // (buddies.test.ts); the phone shows the same beside a turned-off engine.+ final desktop = File('../desktop/lib/super_tabs/buddies.dart')+ .readAsStringSync();+ final refusals = RegExp(+ r"kBuddyEngineRefusals = \{\s*((?:'\w+':\s*'[^']*',\s*)*)\}",+ ).firstMatch(desktop)!.group(1)!;+ expect(swarmBuddyEngineRefusals, {+ for (final m in RegExp(r"'(\w+)':\s*'([^']*)'").allMatches(refusals))+ m.group(1)!: m.group(2)!,+ });+ },+ );++ for (final MapEntry(key: phone, value: desktop) in _copies.entries) {+ test("$phone matches the desktop's $desktop", () {+ final source = File('../desktop/$desktop');+ if (!source.existsSync()) {+ throw StateError(+ '${source.path} missing — run from mobile/ in the monorepo',+ );+ }+ final copy = File(phone);+ expect(copy.existsSync(), isTrue, reason: '$phone is missing');+ expect(+ copy.readAsStringSync(),+ source.readAsStringSync(),+ reason:+ 'carry the change to both copies (or drop the pair from '+ 'test/swarm/desktop_parity_test.dart if they are meant to differ)',+ );+ });+ }+}diff --git a/mobile/test/swarm/swarm_asks_test.dart b/mobile/test/swarm/swarm_asks_test.dartnew file mode 100644index 000000000..373942642--- /dev/null+++ b/mobile/test/swarm/swarm_asks_test.dart@@ -0,0 +1,728 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_asks.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import 'swarm_fixture.dart';++/// What the Swarm asks of the reader: decisions to answer and the Lead's tags+/// (backend superTabs/decisions.ts and mentions.ts). Read only while the+/// Swarm's own counts say there is something, as the desktop does.+void main() {+ Map<String, dynamic> decisionRow(+ String id, {+ String question = 'Ship it?',+ List<String> options = const ['Yes', 'No'],+ int recommended = 0,+ }) => {+ 'id': id,+ 'batchId': 'batch-1',+ 'projectId': project,+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'askerName': 'River',+ 'question': question,+ 'options': options,+ 'recommended': recommended,+ 'unblocks': 'The release',+ 'createdAt': '2026-10-27T01:00:00.000Z',+ };++ Map<String, dynamic> mentionRow(String id, {String text = 'Look'}) => {+ 'id': id,+ 'projectId': project,+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'messageId': 'msg-$id',+ 'leadName': 'River',+ 'text': text,+ 'createdAt': '2026-10-27T01:00:00.000Z',+ };++ /// A Swarm whose reads say [decisions] and [mentions] are waiting.+ ({FakeSwarm swarm, SwarmReader reader, SwarmAsks asks}) rig({+ int decisions = 0,+ int mentions = 0,+ }) {+ final swarm = FakeSwarm();+ var derived = {'decisionsWaiting': decisions, 'mentionsWaiting': mentions};+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(derived: derived);+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ final asks = SwarmAsks(reader);+ addTearDown(() {+ asks.dispose();+ reader.dispose();+ });+ return (swarm: swarm, reader: reader, asks: asks);+ }++ test('a Swarm with nothing waiting reads its lists only with its first '+ 'load', () async {+ final r = rig();++ await r.reader.refresh();+ await settle();+ await r.reader.refresh();+ await settle();++ expect(r.swarm.paths, [+ '/api/super-tabs/$tab/parts',+ '/api/super-tabs/$tab/decisions?state=open',+ '/api/super-tabs/$tab/mentions?state=waiting',+ '/api/super-tabs/$tab/changes?cursor=c1',+ ]);+ expect(r.asks.decisions, isEmpty);+ expect(r.asks.mentions, isEmpty);+ });++ // Read after the first load, they waited a round trip through the+ // computer behind the whole 1.3 MB Swarm (Mira's iPhone 14 numbers).+ test('decisions and tags are read alongside the first load, once', () async {+ final r = rig(decisions: 1);+ final load = Completer<Object?>();+ r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) => load.future;+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [decisionRow('d1')],+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };++ final reading = r.reader.refresh();+ await settle();+ expect(+ r.swarm.paths,+ containsAll([+ '/api/super-tabs/$tab/decisions?state=open',+ '/api/super-tabs/$tab/mentions?state=waiting',+ ]),+ );+ expect(r.asks.decisions, isEmpty, reason: 'not before the Swarm is read');+ expect(r.asks.loading, isTrue);++ load.complete(+ firstLoad(derived: {'decisionsWaiting': 1, 'mentionsWaiting': 0}),+ );+ await reading;+ await settle();++ expect(r.asks.decisions.single.id, 'd1');+ expect(r.asks.loading, isFalse);+ expect(r.swarm.paths.where((p) => p.contains('decisions')), hasLength(1));+ });++ test(+ 'asks read alongside a first load that failed are never shown',+ () async {+ final r = rig(decisions: 1);+ var failing = true;+ var open = [decisionRow('d-old')];+ r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) => failing+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : firstLoad(derived: {'decisionsWaiting': 1, 'mentionsWaiting': 0});+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': open,+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ final shown = <String>[];+ r.asks.addListener(() => shown.addAll(r.asks.decisions.map((d) => d.id)));+ await r.reader.refresh();+ await settle();++ failing = false;+ open = [decisionRow('d-new')];+ await r.reader.refresh();+ await settle();++ expect(shown, isNot(contains('d-old')));+ expect(r.asks.decisions.single.id, 'd-new');+ },+ );++ test('asks read alongside the first load that disagree with its counts '+ 'are read again, not shown', () async {+ final r = rig();+ var open = [decisionRow('d1'), decisionRow('d2')];+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': open,+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ final load = Completer<Object?>();+ r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) => load.future;+ final shown = <String>[];+ r.asks.addListener(() => shown.addAll(r.asks.decisions.map((d) => d.id)));++ final reading = r.reader.refresh();+ await settle();+ // d1 answered elsewhere between the two answers: the Swarm counts one.+ open = [decisionRow('d2')];+ load.complete(+ firstLoad(derived: {'decisionsWaiting': 1, 'mentionsWaiting': 0}),+ );+ await reading;+ await settle();++ expect(shown, isNot(contains('d1')));+ expect(r.asks.decisions.single.id, 'd2');+ expect(r.swarm.paths.where((p) => p.contains('decisions')), hasLength(2));+ });++ group('loading', () {+ test('until decisions and tags are read, then not', () async {+ final r = rig(decisions: 1);+ final open = Completer<Object?>();+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) =>+ open.future;+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ expect(r.asks.loading, isTrue, reason: 'nothing is read yet');++ await r.reader.refresh();+ await settle();+ expect(r.reader.snapshot, isNotNull);+ expect(r.asks.loading, isTrue, reason: 'the Swarm is read, not its asks');++ var told = 0;+ r.asks.addListener(() => told++);+ open.complete({+ 'decisions': [decisionRow('d1')],+ });+ await settle();++ expect(r.asks.loading, isFalse);+ expect(told, 1);+ });++ test('ends with the first load when nothing waits', () async {+ final r = rig();+ var told = 0;+ r.asks.addListener(() => told++);++ await r.reader.refresh();+ await settle();++ expect(r.asks.loading, isFalse);+ expect(told, 1, reason: 'Home hears that loading ended');+ });++ test('ends when the read of the asks fails, with its error', () async {+ final r = rig(decisions: 1);+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };++ await r.reader.refresh();+ await settle();++ expect(r.asks.loading, isFalse);+ expect(r.asks.error, isNotNull);+ });++ test('ends when the Swarm itself could not be read', () async {+ final r = rig();+ r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');++ await r.reader.refresh();+ await settle();++ expect(r.reader.error, isNotNull);+ expect(r.asks.loading, isFalse);+ });++ test('starts again while a Swarm read again in full has its asks read '+ 'again', () async {+ final r = rig(decisions: 1);+ Object? open = {+ 'decisions': [decisionRow('d1')],+ };+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => open;+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ await r.reader.refresh();+ await settle();+ expect(r.asks.loading, isFalse);++ final again = Completer<Object?>();+ open = again.future;+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ await r.reader.refresh();+ await settle();+ expect(r.asks.decisions, isEmpty);+ expect(r.asks.loading, isTrue);++ again.complete({+ 'decisions': [decisionRow('d1')],+ });+ await settle();+ expect(r.asks.loading, isFalse);+ expect(r.asks.decisions.single.id, 'd1');+ });++ test('is not while the reader may no longer read the Swarm', () async {+ final r = rig();+ r.reader.revoke();++ expect(r.asks.loading, isFalse);+ });+ });++ test(+ 'open decisions and waiting tags are read when the counts say so',+ () async {+ final r = rig(decisions: 1, mentions: 1);+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ decisionRow(+ 'd1',+ options: ['Offline mode', 'Work offline'],+ recommended: 1,+ ),+ ],+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [mentionRow('m1', text: 'Can you check the copy?')],+ };++ await r.reader.refresh();+ await settle();++ final decision = r.asks.decisions.single;+ expect(decision.question, 'Ship it?');+ expect(decision.options, ['Offline mode', 'Work offline']);+ expect(decision.recommended, 1);+ expect(decision.askerName, 'River');+ expect(decision.conversationId, 'g1');+ expect(r.asks.mentions.single.text, 'Can you check the copy?');+ },+ );++ test('a backend from before decisions has none to show', () async {+ final r = rig(decisions: 1);+ r.swarm.routes['/api/super-tabs/$tab/decisions'] = (_) =>+ throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);++ await r.reader.refresh();+ await settle();++ expect(r.asks.decisions, isEmpty);+ expect(r.asks.error, isNull);+ });++ test('a failed read is tried again at the next read of the Swarm, '+ 'even one that changed nothing', () async {+ final r = rig(decisions: 1);+ var failing = true;+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => failing+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : {+ 'decisions': [decisionRow('d1')],+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ await r.reader.refresh();+ await settle();+ expect(r.asks.decisions, isEmpty);+ expect(r.asks.error, isNotNull);++ failing = false;+ await r.reader.refresh();+ await settle();++ expect(r.asks.decisions.single.id, 'd1');+ expect(r.asks.error, isNull);+ });++ test('while an ask waits, a read that moves only the last-change time '+ 'reads the asks again', () async {+ final r = rig(decisions: 1);+ var open = [decisionRow('d1')];+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': open,+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ await r.reader.refresh();+ await settle();+ expect(r.asks.decisions.single.id, 'd1');++ // d1 answered on the desktop and d2 asked: the count stays at one.+ open = [decisionRow('d2')];+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ derived: {'decisionsWaiting': 1, 'mentionsWaiting': 0},+ lastChangedAt: 300,+ );+ await r.reader.refresh();+ await settle();++ expect(r.asks.decisions.single.id, 'd2');+ });++ // Each such read notified, and the inbox rebuilt Home with it, several+ // times a poll (audit of 44d284f65, item 4; Jasper's item 5).+ test('asks read back as they were notify nothing, and stay the same '+ 'objects', () async {+ final r = rig(decisions: 1, mentions: 1);+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [decisionRow('d1')],+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [mentionRow('m1')],+ };+ await r.reader.refresh();+ await settle();+ final decisions = r.asks.decisions, mentions = r.asks.mentions;+ var notifies = 0;+ r.asks.addListener(() => notifies++);++ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ derived: {'decisionsWaiting': 1, 'mentionsWaiting': 1},+ lastChangedAt: 300,+ );+ await r.reader.refresh();+ await settle();+ await r.asks.load();++ expect(r.swarm.paths.where((p) => p.contains('decisions')), hasLength(3));+ expect(notifies, 0);+ expect(r.asks.decisions, same(decisions));+ expect(r.asks.mentions, same(mentions));+ });++ test('a changed ask is told, even with the same ids', () async {+ final r = rig(decisions: 1);+ var question = 'Ship it?';+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [decisionRow('d1', question: question)],+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ await r.reader.refresh();+ await settle();+ var notifies = 0;+ r.asks.addListener(() => notifies++);++ question = 'Ship it today?';+ await r.asks.load();++ expect(notifies, 1);+ expect(r.asks.decisions.single.question, 'Ship it today?');+ });++ test(+ 'a Swarm the reader may no longer read keeps none of its asks',+ () async {+ final r = rig(decisions: 1);+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [decisionRow('d1')],+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ await r.reader.refresh();+ await settle();+ expect(r.asks.decisions, hasLength(1));++ const refused = SuperTabFailure(+ 'FORBIDDEN',+ 'Not yours.',+ statusCode: 403,+ );+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => throw refused;+ r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) => throw refused;+ await r.reader.refresh();+ await settle();++ expect(r.reader.accessRevoked, isTrue);+ expect(r.asks.decisions, isEmpty);+ },+ );++ test(+ 'asks read before a full read of the Swarm are never shown after it',+ () async {+ final r = rig(decisions: 1);+ final before = Completer<Object?>();+ Object? open = before.future;+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => open;+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ await r.reader.refresh();+ await settle();+ final shown = <List<String>>[];+ r.asks.addListener(+ () => shown.add([for (final d in r.asks.decisions) d.id]),+ );++ // The person left the chat d1 was asked in; the Swarm is read again+ // in full, and still has one decision for them elsewhere.+ open = {+ 'decisions': [decisionRow('d2')],+ };+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ await r.reader.refresh();+ before.complete({+ 'decisions': [decisionRow('d1')],+ });+ await settle();++ expect(shown.expand((ids) => ids), isNot(contains('d1')));+ expect([for (final d in r.asks.decisions) d.id], ['d2']);+ },+ );++ test('answering sends the choice once, then reads again', () async {+ final r = rig(decisions: 1);+ var open = [decisionRow('d1')];+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': open,+ };+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) {+ open = [];+ return {'result': <String, dynamic>{}};+ };+ await r.reader.refresh();+ await settle();++ final answered = await r.asks.answer(r.asks.decisions.single, 1);++ expect(answered, isTrue);+ final sent = r.swarm.calls.singleWhere((c) => c.method == 'POST');+ expect(sent.body!['operationId'], isA<String>());+ expect(sent.body!['command'], {+ 'type': 'decision.answer',+ 'decisionId': 'd1',+ 'choice': 1,+ });+ expect(r.asks.decisions, isEmpty);+ expect(r.asks.answering, isEmpty);+ });++ test('a refused answer keeps the decision and says so', () async {+ final r = rig(decisions: 1);+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [decisionRow('d1')],+ };+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ await r.reader.refresh();+ await settle();++ final answered = await r.asks.answer(r.asks.decisions.single, 0);++ expect(answered, isFalse);+ expect(r.asks.decisions.single.id, 'd1');+ expect(r.asks.error, 'Could not send your answer. Try again.');+ });++ /// The backend's commands route as it treats answers: one answer per+ /// decision, and a receipt per operation that replays its reply.+ ({List<Map<String, dynamic>> sent, void Function() loseReplies}) answers(+ FakeSwarm swarm,+ List<Map<String, dynamic>> Function() open,+ void Function() answered,+ ) {+ final sent = <Map<String, dynamic>>[];+ final receipts = <String>{};+ var lose = false;+ swarm.routes['/api/super-tabs/$tab/commands'] = (body) {+ sent.add(body!);+ final operation = body['operationId'] as String;+ if (!receipts.contains(operation)) {+ if (open().isEmpty) {+ throw const SuperTabFailure(+ 'DECISION_ANSWERED',+ 'This decision is already answered.',+ statusCode: 409,+ );+ }+ receipts.add(operation);+ answered();+ }+ if (lose) {+ lose = false;+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ }+ return {'result': <String, dynamic>{}};+ };+ return (sent: sent, loseReplies: () => lose = true);+ }++ test('an answer taken whose reply was lost is sent again as the same answer, '+ 'and no other is offered meanwhile', () async {+ final r = rig(decisions: 1);+ var open = [decisionRow('d1')];+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': open,+ };+ final backend = answers(r.swarm, () => open, () => open = []);+ await r.reader.refresh();+ await settle();+ final decision = r.asks.decisions.single;++ backend.loseReplies();+ expect(await r.asks.answer(decision, 1), isFalse);+ expect(r.asks.unconfirmed(decision), 1);++ expect(await r.asks.answer(decision, 0), isTrue);++ expect(backend.sent, hasLength(2));+ expect(+ {for (final body in backend.sent) body['operationId']},+ hasLength(1),+ reason: 'the retry is the same command, so its receipt answers it',+ );+ expect(+ [for (final body in backend.sent) (body['command'] as Map)['choice']],+ [1, 1],+ );+ expect(r.asks.unconfirmed(decision), isNull);+ expect(r.asks.decisions, isEmpty);+ expect(r.asks.error, isNull);+ });++ test('an answer to a decision answered already reads it back', () async {+ final r = rig(decisions: 1);+ var open = [decisionRow('d1')];+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': open,+ };+ answers(r.swarm, () => open, () => open = []);+ await r.reader.refresh();+ await settle();+ final decision = r.asks.decisions.single;+ open = []; // Answered on another device meanwhile.++ await r.asks.answer(decision, 0);++ expect(r.asks.decisions, isEmpty);+ expect(r.asks.unconfirmed(decision), isNull);+ expect(r.asks.error, isNull);+ });++ test('done with a tag sends it once, then reads again', () async {+ final r = rig(mentions: 1);+ var waiting = [mentionRow('m1')];+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': waiting,+ };+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) {+ waiting = [];+ return {'result': <String, dynamic>{}};+ };+ await r.reader.refresh();+ await settle();++ expect(await r.asks.done(r.asks.mentions.single), isTrue);++ expect(r.swarm.commands.single, {+ 'type': 'mention.done',+ 'mentionId': 'm1',+ });+ expect(r.asks.mentions, isEmpty);+ });++ // Mira's run on the owner's iPhone, 2026-10-27: Done on a tag took 10+ // seconds to register, with no sign the tap counted.+ test('Done shows at once, and the tag goes the moment it is confirmed, '+ 'before the list is read again', () async {+ final r = rig(mentions: 1);+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [mentionRow('m1')],+ };+ await r.reader.refresh();+ await settle();+ final confirmed = Completer<Object?>();+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => confirmed.future;+ final tag = r.asks.mentions.single;++ final done = r.asks.done(tag);+ await settle();+ expect(r.asks.finishing(tag), isTrue);++ // The list the backend reads back still has it for a moment.+ confirmed.complete({'result': <String, dynamic>{}});+ expect(await done, isTrue);++ expect(r.asks.finishing(tag), isFalse);+ expect(r.asks.mentions, isEmpty);+ await r.asks.load();+ expect(r.asks.mentions, isEmpty);+ });++ test(+ 'a Done that fails says so on that tag alone, and the tag stays',+ () async {+ final r = rig(decisions: 1, mentions: 1);+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [decisionRow('d1')],+ };+ r.swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [mentionRow('m1')],+ };+ await r.reader.refresh();+ await settle();+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ final tag = r.asks.mentions.single;++ expect(await r.asks.done(tag), isFalse);++ expect(r.asks.finishing(tag), isFalse);+ expect(r.asks.notDone(tag), 'Not marked done. Try again.');+ expect(r.asks.mentions.single.id, 'm1');+ expect(r.asks.error, isNull, reason: 'the decision shows no error of it');+ },+ );++ test(+ 'a new ask that arrives later is news; the ones there at first are not',+ () async {+ final r = rig(decisions: 1);+ var open = [decisionRow('d1')];+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': open,+ };+ final news = <String>[];+ r.asks.onArrived = (item) => news.add(item.id);+ await r.reader.refresh();+ await settle();+ expect(news, isEmpty);++ open = [decisionRow('d1'), decisionRow('d2', question: 'Name?')];+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ derived: {'decisionsWaiting': 2, 'mentionsWaiting': 0},+ );+ await r.reader.refresh();+ await settle();++ expect(news, ['d2']);+ },+ );+}diff --git a/mobile/test/swarm/swarm_attachment_fakes.dart b/mobile/test/swarm/swarm_attachment_fakes.dartnew file mode 100644index 000000000..14bf42065--- /dev/null+++ b/mobile/test/swarm/swarm_attachment_fakes.dart@@ -0,0 +1,111 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io' as io;++import 'package:file/file.dart' hide FileSystem;+import 'package:file/local.dart';+import 'package:flutter_cache_manager/flutter_cache_manager.dart';+import 'package:harness_mobile/swarm/swarm_attachment_store.dart';++/// A one-pixel PNG, as Harness's file storage would serve a picture.+final pixelPng = base64Decode(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwAD'+ 'hgGAWjR9awAAAABJRU5ErkJggg==',+);++/// Harness's file storage as the phone reaches it: what was asked, with which+/// headers, and an answer the test can hold back or fail.+class FakeFileStorage implements FileService {+ @override+ int concurrentFetches = 10;++ final asked = <({String url, Map<String, String>? headers})>[];++ /// Set to hold every answer until it completes.+ Completer<void>? hold;++ /// The status every answer carries.+ int status = 200;++ /// What every answer carries.+ List<int> bytes = pixelPng;++ @override+ Future<FileServiceResponse> get(+ String url, {+ Map<String, String>? headers,+ }) async {+ asked.add((url: url, headers: headers));+ await hold?.future;+ return _Answer(status, bytes);+ }+}++class _Answer implements FileServiceResponse {+ _Answer(this.statusCode, this._bytes);++ final List<int> _bytes;++ @override+ final int statusCode;++ @override+ Stream<List<int>> get content => Stream.value(_bytes);++ @override+ int? get contentLength => _bytes.length;++ @override+ DateTime get validTill => DateTime.now().add(const Duration(days: 365));++ @override+ String? get eTag => null;++ @override+ String get fileExtension => '.png';+}++/// Files under [folder], where the app keeps them under its temporary folder.+class _Folder implements FileSystem {+ _Folder(this.folder);++ final io.Directory folder;++ @override+ Future<File> createFile(String name) async {+ final directory = const LocalFileSystem().directory(folder.path);+ await directory.create(recursive: true);+ return directory.childFile(name);+ }+}++/// A store over [root] and [storage], as the app's is over its temporary+/// folder and the network.+SwarmAttachmentStore storeIn(io.Directory root, FakeFileStorage storage) =>+ SwarmAttachmentStore(+ root: () async => root,+ fileService: storage,+ files: (folder) => _Folder(folder),+ );++/// The files kept under [root], by their path below it.+List<String> keptUnder(io.Directory root) => !root.existsSync()+ ? const []+ : [+ for (final entry in root.listSync(recursive: true))+ if (entry is io.File) entry.path.substring(root.path.length + 1),+ ];++/// The one account folder under [root] made read-only, so what is in it+/// cannot be deleted, as a phone can refuse; returns the undo, which the+/// caller also runs in its tear-down so the folder can be cleaned up.+void Function() denyDeletes(io.Directory root) {+ final folders = root.listSync().whereType<io.Directory>().toList();+ if (folders.length != 1) {+ throw StateError('Expected one account folder, found ${folders.length}.');+ }+ void mode(String bits) =>+ io.Process.runSync('chmod', [bits, folders.single.path]);+ mode('500');+ return () => mode('700');+}diff --git a/mobile/test/swarm/swarm_attachment_keeper_test.dart b/mobile/test/swarm/swarm_attachment_keeper_test.dartnew file mode 100644index 000000000..17d27b47d--- /dev/null+++ b/mobile/test/swarm/swarm_attachment_keeper_test.dart@@ -0,0 +1,206 @@+import 'dart:io';++import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/logging/app_log.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_attachment_store.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_attachment_fakes.dart';+import 'swarm_fixture.dart';++/// The files go with the account's Swarm: on sign-out, Swarm turned off,+/// another account, and a Swarm leaving the account's list.+void main() {+ late Directory root;+ late FakeFileStorage storage;+ late SwarmAttachmentStore store;+ late ValueNotifier<String?> account;+ late ExperimentalFeaturesStore features;+ late List<String> listed;+ late SwarmHost host;++ final picture = Uri.parse('https://cdn.example/swarm/a.png');++ setUp(() {+ root = Directory.systemTemp.createTempSync('swarm-attachments-');+ storage = FakeFileStorage();+ store = storeIn(root, storage);+ account = ValueNotifier(me);+ features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ listed = ['tab-a', 'tab-b'];+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ for (final id in listed) {'id': id, 'name': id, 'ownerId': me},+ ],+ 'next': null,+ };+ host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ });+ tearDown(() {+ host.dispose();+ if (root.existsSync()) root.deleteSync(recursive: true);+ });++ /// Waits, briefly, until [done] holds: the keeper empties files in the+ /// background.+ Future<void> until(bool Function() done) async {+ for (var i = 0; i < 100 && !done(); i++) {+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }+ expect(done(), isTrue);+ }++ /// A keeper over [host], the list read once, and a picture kept.+ Future<SwarmAttachmentKeeper> keeping() async {+ final keeper = SwarmAttachmentKeeper(host, store: store);+ addTearDown(keeper.dispose);+ await host.session!.inbox.refresh();+ await store.file(picture);+ expect(keptUnder(root), isNotEmpty);+ return keeper;+ }++ test('sign-out empties them', () async {+ await keeping();++ account.value = null;++ await until(() => keptUnder(root).isEmpty);+ });++ test('Swarm turned off empties them', () async {+ await keeping();++ features.value = const {};++ await until(() => keptUnder(root).isEmpty);+ });++ test("another account signing in empties the first one's", () async {+ await keeping();++ account.value = 'person-other';+ await store.file(picture);++ expect(storage.asked, hasLength(2), reason: 'fetched again, for them');+ expect(+ root.listSync().whereType<Directory>(),+ hasLength(1),+ reason: "the other account's folder only",+ );+ });++ test("a Swarm leaving the account's list empties them", () async {+ await keeping();++ listed = ['tab-a'];+ await host.session!.inbox.refresh();+ await store.file(picture);++ expect(storage.asked, hasLength(2), reason: 'emptied, so fetched again');+ });++ test(+ 'a Swarm joining, or the same list read again, empties nothing',+ () async {+ await keeping();++ listed = ['tab-a', 'tab-b', 'tab-c'];+ await host.session!.inbox.refresh();+ await host.session!.inbox.refresh();+ await store.file(picture);++ expect(storage.asked, hasLength(1));+ },+ );++ test('at start with nobody signed in, what was left is emptied', () async {+ File('${root.path}/stray.png').writeAsBytesSync(pixelPng);+ account.value = null;++ final keeper = SwarmAttachmentKeeper(host, store: store);+ addTearDown(keeper.dispose);++ await until(() => keptUnder(root).isEmpty);+ });++ test('files that cannot be emptied are logged, never thrown', () async {+ final log = _Log();+ final before = appLog;+ appLog = log;+ addTearDown(() => appLog = before);+ final broken = SwarmAttachmentStore(+ root: () async => throw const FileSystemException('no folder'),+ );++ final keeper = SwarmAttachmentKeeper(host, store: broken);+ addTearDown(keeper.dispose);++ await until(() => log.failures.isNotEmpty);+ expect(log.failures.single, contains('Swarm files'));+ });++ test('a sign-out whose files the phone refuses to delete is logged, and '+ 'tried again until they go', () async {+ final log = _Log();+ final before = appLog;+ appLog = log;+ addTearDown(() => appLog = before);+ final keeper = SwarmAttachmentKeeper(+ host,+ store: store,+ retry: const Duration(milliseconds: 20),+ );+ addTearDown(keeper.dispose);+ await host.session!.inbox.refresh();+ await store.file(picture);+ final allow = denyDeletes(root);+ addTearDown(allow);++ account.value = null;++ await until(() => log.failures.isNotEmpty);+ expect(log.failures.first, contains('Swarm files'));+ expect(keptUnder(root), isNotEmpty);+ allow();+ await until(() => keptUnder(root).isEmpty);+ });++ test('let go of, it hears nothing more', () async {+ final keeper = await keeping();+ keeper.dispose();++ listed = ['tab-a'];+ await host.session!.inbox.refresh();+ await store.file(picture);++ expect(storage.asked, hasLength(1));+ });+}++class _Log implements AppLog {+ final failures = <String>[];++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) {+ if (level == AppLogLevel.error) failures.add(message);+ }+}diff --git a/mobile/test/swarm/swarm_attachment_store_test.dart b/mobile/test/swarm/swarm_attachment_store_test.dartnew file mode 100644index 000000000..4c8ccf139--- /dev/null+++ b/mobile/test/swarm/swarm_attachment_store_test.dart@@ -0,0 +1,227 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_attachment_store.dart';++import 'swarm_attachment_fakes.dart';++/// The phone's copies of Swarm's files: fetched as the chip opens them, kept+/// for one account only, and gone with it.+void main() {+ late Directory root;+ late FakeFileStorage storage;+ late SwarmAttachmentStore store;++ final picture = Uri.parse('https://cdn.example/swarm/a.png');+ final other = Uri.parse('https://cdn.example/swarm/b.png');++ setUp(() {+ root = Directory.systemTemp.createTempSync('swarm-attachments-');+ storage = FakeFileStorage();+ store = storeIn(root, storage);+ });+ tearDown(() {+ if (root.existsSync()) root.deleteSync(recursive: true);+ });++ test('fetches a file once, with no credential of the app', () async {+ await store.keepOnly('person-a');++ final first = await store.file(picture);+ final again = await store.file(picture);++ expect(await first.readAsBytes(), pixelPng);+ expect(again.path, first.path);+ expect(storage.asked, hasLength(1));+ expect(storage.asked.single.url, picture.toString());+ expect(storage.asked.single.headers ?? const {}, isEmpty);+ });++ test('two asking for one file at once make one fetch', () async {+ await store.keepOnly('person-a');+ storage.hold = Completer();++ final both = Future.wait([store.file(picture), store.file(picture)]);+ await Future<void>.delayed(Duration.zero);+ storage.hold!.complete();+ await both;++ expect(storage.asked, hasLength(1));+ });++ test('with nobody to keep files for, fetches nothing', () async {+ await store.keepOnly(null);++ await expectLater(store.file(picture), throwsStateError);+ expect(storage.asked, isEmpty);+ });++ test('keeps one account only: another account empties the first', () async {+ await store.keepOnly('person-a');+ await store.file(picture);+ expect(keptUnder(root), isNotEmpty);++ await store.keepOnly('person-b');+ await store.file(other);++ final kept = keptUnder(root);+ expect(kept, isNotEmpty);+ expect(+ kept.map((path) => path.split(Platform.pathSeparator).first).toSet(),+ hasLength(1),+ reason: "only person-b's folder",+ );+ expect(await store.file(other), isA<File>());+ expect(storage.asked, hasLength(2), reason: "b's file is still kept");+ });++ test('nobody signed in (sign-out, Swarm off) empties everything', () async {+ await store.keepOnly('person-a');+ await store.file(picture);++ await store.keepOnly(null);++ expect(keptUnder(root), isEmpty);+ });++ test('at start, what another account left behind is emptied', () async {+ final left = Directory('${root.path}/someone-else')..createSync();+ File('${left.path}/old.png').writeAsBytesSync(pixelPng);++ await store.keepOnly('person-a');++ expect(left.existsSync(), isFalse);+ });++ test('at start with nobody signed in, everything is emptied', () async {+ File('${root.path}/stray.png').writeAsBytesSync(pixelPng);++ await store.keepOnly(null);++ expect(keptUnder(root), isEmpty);+ });++ test(+ "clear empties the account's files, and fetches them again after",+ () async {+ await store.keepOnly('person-a');+ await store.file(picture);++ await store.clear();+ expect(keptUnder(root), isEmpty);++ await store.file(picture);+ expect(storage.asked, hasLength(2));+ },+ );++ test('signed out during a fetch: the fetch ends first, then nothing is '+ 'left', () async {+ await store.keepOnly('person-a');+ storage.hold = Completer();+ final fetch = store.file(picture);+ await Future<void>.delayed(Duration.zero);++ final signedOut = store.keepOnly(null);+ storage.hold!.complete();+ await fetch;+ await signedOut;++ expect(keptUnder(root), isEmpty);+ await expectLater(store.file(picture), throwsStateError);+ });++ test(+ 'cleared during a fetch: the fetch ends first, then nothing is left',+ () async {+ await store.keepOnly('person-a');+ storage.hold = Completer();+ final fetch = store.file(picture);+ await Future<void>.delayed(Duration.zero);++ final cleared = store.clear();+ storage.hold!.complete();+ await fetch;+ await cleared;++ expect(keptUnder(root), isEmpty);+ },+ );++ test('asked while being emptied, a file waits and lands after', () async {+ await store.keepOnly('person-a');+ await store.file(picture);++ final cleared = store.clear();+ final again = store.file(picture);+ await cleared;+ await again;++ expect(storage.asked, hasLength(2), reason: 'fetched again, after');+ expect(keptUnder(root), isNotEmpty);+ });++ group('a delete the phone refuses', () {+ void Function() deny() {+ final allow = denyDeletes(root);+ addTearDown(allow);+ return allow;+ }++ test('on sign-out says so, and empties on the next try', () async {+ await store.keepOnly('person-a');+ await store.file(picture);+ final allow = deny();++ await expectLater(+ store.keepOnly(null),+ throwsA(isA<FileSystemException>()),+ );+ expect(keptUnder(root), isNotEmpty);++ allow();+ await store.keepOnly(null);++ expect(keptUnder(root), isEmpty);+ });++ test('on another account says so, and empties the first on the next '+ 'try', () async {+ await store.keepOnly('person-a');+ await store.file(picture);+ final allow = deny();++ await expectLater(+ store.keepOnly('person-b'),+ throwsA(isA<FileSystemException>()),+ );++ allow();+ await store.keepOnly('person-b');++ expect(keptUnder(root), isEmpty);+ });++ test('on clear says so, and the next keeping of the same account '+ 'empties it', () async {+ await store.keepOnly('person-a');+ await store.file(picture);+ final allow = deny();++ await expectLater(store.clear(), throwsA(isA<FileSystemException>()));++ allow();+ await store.keepOnly('person-a');++ expect(keptUnder(root), isEmpty);+ });+ });++ test('a refused fetch keeps nothing and says so', () async {+ await store.keepOnly('person-a');+ storage.status = 404;++ await expectLater(store.file(picture), throwsA(anything));+ });+}diff --git a/mobile/test/swarm/swarm_attachment_test.dart b/mobile/test/swarm/swarm_attachment_test.dartnew file mode 100644index 000000000..834097be7--- /dev/null+++ b/mobile/test/swarm/swarm_attachment_test.dart@@ -0,0 +1,441 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/shared/widgets/skeleton.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_attachment.dart';+import 'package:harness_mobile/swarm/swarm_attachment_store.dart';++import 'swarm_attachment_fakes.dart';++/// A picture in a chat shows in place: a skeleton in a fixed 4:3 box while it+/// loads, then the picture in the same box, decoded at the box's size, and a+/// tap opens it full screen. Every other file, and a picture that cannot be+/// shown, keeps the chip.+void main() {+ late Directory root;+ late FakeFileStorage storage;+ late SwarmAttachmentStore store;++ final link = Uri.parse('https://cdn.example/swarm/a.png');++ SuperTabAttachment attachment({String mime = 'image/png'}) =>+ SuperTabAttachment.fromJson({+ 'id': 'file-1',+ 'name': 'screen.png',+ 'mime': mime,+ 'size': 2048,+ 'url': link.toString(),+ });++ setUp(() {+ root = Directory.systemTemp.createTempSync('swarm-attachments-');+ storage = FakeFileStorage();+ store = storeIn(root, storage);+ });+ tearDown(() {+ if (root.existsSync()) root.deleteSync(recursive: true);+ });++ Finder key(String value) => find.byKey(ValueKey(value));+ final chip = key('chip');+ final preview = key('swarm-attachment-preview-file-1');++ /// [file] in a message [width] wide, on a phone at 2x.+ Future<void> pump(+ WidgetTester tester, {+ SuperTabAttachment? file,+ Uri? linked,+ bool noLink = false,+ double width = 320,+ String? signedIn = 'person-me',+ }) async {+ tester.view.devicePixelRatio = 2;+ addTearDown(tester.view.reset);+ // Real files: outside the test's fake clock.+ await tester.runAsync(() => store.keepOnly(signedIn));+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Align(+ alignment: Alignment.topLeft,+ child: SizedBox(+ width: width,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SwarmAttachment(+ file: file ?? attachment(),+ link: noLink ? null : linked ?? link,+ chip: const Text('chip', key: ValueKey('chip')),+ store: store,+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }++ /// Real time for the file to be written and the picture decoded, a frame+ /// after each step, until [done] holds.+ Future<void> until(WidgetTester tester, bool Function() done) async {+ for (var i = 0; i < 100 && !done(); i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump();+ }+ expect(done(), isTrue);+ }++ /// Ends a test that fetched: the chat closed, and the cache's own cleanup,+ /// which it runs every few seconds, let run.+ Future<void> closed(WidgetTester tester) async {+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(minutes: 1));+ }++ bool drawn(WidgetTester tester) => find+ .descendant(of: preview, matching: find.byType(RawImage))+ .evaluate()+ .any((e) => (e.widget as RawImage).image != null);++ testWidgets('a picture shows a skeleton in a 4:3 box while it loads, then '+ 'the picture in the same box', (tester) async {+ storage.hold = Completer();+ await pump(tester);+ await tester.pump();++ expect(preview, findsOneWidget);+ expect(tester.getSize(preview), const Size(240, 180));+ expect(+ find.descendant(of: preview, matching: find.byType(Skeleton)),+ findsOneWidget,+ );+ expect(chip, findsNothing);+ expect(find.byType(Text), findsNothing, reason: 'no words while loading');++ storage.hold!.complete();+ await until(tester, () => drawn(tester));++ expect(tester.getSize(preview), const Size(240, 180), reason: 'no jump');+ expect(+ find.descendant(of: preview, matching: find.byType(Skeleton)),+ findsNothing,+ );+ final image = tester.widget<Image>(+ find.descendant(of: preview, matching: find.byType(Image)),+ );+ expect(image.image, isA<ResizeImage>());+ expect((image.image as ResizeImage).width, 480, reason: '240 at 2x');++ await closed(tester);+ });++ testWidgets('a narrow message makes the box narrower, still 4:3', (+ tester,+ ) async {+ storage.hold = Completer();+ await pump(tester, width: 200);+ await tester.pump();++ expect(tester.getSize(preview), const Size(200, 150));+ storage.hold!.complete();++ await closed(tester);+ });++ testWidgets('the box sits 8 points under what is above it, and the skeleton '+ 'and the picture share the row corner of 10', (tester) async {+ storage.hold = Completer();+ await pump(tester);+ await tester.pump();++ expect(tester.getTopLeft(preview).dy, 8);+ expect(+ tester+ .widget<Skeleton>(+ find.descendant(of: preview, matching: find.byType(Skeleton)),+ )+ .radius,+ 10,+ );+ storage.hold!.complete();+ await until(tester, () => drawn(tester));++ expect(+ tester+ .widget<ClipRRect>(+ find.descendant(of: preview, matching: find.byType(ClipRRect)),+ )+ .borderRadius,+ BorderRadius.circular(10),+ );++ await closed(tester);+ });++ testWidgets('a file that is not a picture keeps the chip, and nothing is '+ 'fetched', (tester) async {+ await pump(tester, file: attachment(mime: 'application/pdf'));+ await tester.pump();++ expect(chip, findsOneWidget);+ expect(preview, findsNothing);+ expect(storage.asked, isEmpty);+ });++ testWidgets("a picture not on Harness's file storage keeps the chip", (+ tester,+ ) async {+ await pump(tester, noLink: true);+ await tester.pump();++ expect(chip, findsOneWidget);+ expect(storage.asked, isEmpty);+ });++ testWidgets('a picture that cannot be fetched shows the chip instead', (+ tester,+ ) async {+ storage.status = 404;+ await pump(tester);++ await until(tester, () => chip.evaluate().isNotEmpty);+ expect(preview, findsNothing);++ await closed(tester);+ });++ testWidgets('a file that is not a picture after all shows the chip instead', (+ tester,+ ) async {+ storage.bytes = 'not a picture'.codeUnits;+ await pump(tester);++ await until(tester, () => chip.evaluate().isNotEmpty);+ expect(preview, findsNothing);++ await closed(tester);+ });++ testWidgets('with no account to keep files for, the chip', (tester) async {+ await pump(tester, signedIn: null);++ await until(tester, () => chip.evaluate().isNotEmpty);+ expect(storage.asked, isEmpty);++ await closed(tester);+ });++ testWidgets('drawn again from above, it fetches nothing more', (+ tester,+ ) async {+ await pump(tester);+ await until(tester, () => drawn(tester));++ await pump(tester);+ await tester.pump();++ expect(storage.asked, hasLength(1));+ expect(drawn(tester), isTrue, reason: 'no skeleton again');++ await closed(tester);+ });++ testWidgets('a tap opens it full screen, to zoom; close goes back', (+ tester,+ ) async {+ await pump(tester);+ await until(tester, () => drawn(tester));++ await tester.tap(preview);+ await tester.pumpAndSettle();+ final viewer = key('swarm-attachment-viewer');+ expect(viewer, findsOneWidget);+ expect(+ find.descendant(of: viewer, matching: find.byType(InteractiveViewer)),+ findsOneWidget,+ );+ expect(find.text('screen.png'), findsOneWidget);+ final image = tester.widget<Image>(+ find.descendant(of: viewer, matching: find.byType(Image)),+ );+ expect(+ (image.image as ResizeImage).width,+ (tester.view.physicalSize.width * 2).round(),+ reason: 'the screen, twice over, for zoom',+ );++ await tester.tap(key('swarm-attachment-close'));+ await tester.pumpAndSettle();+ expect(viewer, findsNothing);+ expect(preview, findsOneWidget);++ await closed(tester);+ });++ group('open full screen, the picture goes with its account', () {+ final viewer = key('swarm-attachment-viewer');++ /// A second of frames: after a change the preview fetches again under a+ /// skeleton, which breathes, so the screen never settles.+ Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ /// The picture open full screen and decoded; the image cache's key for+ /// its decoded picture.+ Future<Object> opened(WidgetTester tester) async {+ await pump(tester);+ await until(tester, () => drawn(tester));+ await tester.tap(preview);+ await tester.pumpAndSettle();+ final picture = tester+ .widget<Image>(+ find.descendant(of: viewer, matching: find.byType(Image)),+ )+ .image;+ final key = (await tester.runAsync(+ () => picture.obtainKey(ImageConfiguration.empty),+ ))!;+ await until(+ tester,+ () => PaintingBinding.instance.imageCache.containsKey(key),+ );+ return key;+ }++ final changes = <String, Future<void> Function()>{+ 'another account': () => store.keepOnly('person-b'),+ 'sign-out or Swarm off': () => store.keepOnly(null),+ "a Swarm leaving the account's list": () => store.clear(),+ };+ for (final MapEntry(key: change, value: run) in changes.entries) {+ testWidgets('$change closes it at once, and lets the picture go', (+ tester,+ ) async {+ final picture = await opened(tester);++ // On the test's clock, as the keeper asks it: the cache it closes+ // was opened there.+ var changed = false;+ unawaited(run().whenComplete(() => changed = true));+ await tester.pump();++ expect(+ find.descendant(of: viewer, matching: find.byType(Image)),+ findsNothing,+ reason: 'blank from the first frame',+ );+ await frames(tester);+ expect(viewer, findsNothing);+ expect(+ PaintingBinding.instance.imageCache.containsKey(picture),+ isFalse,+ );++ await until(tester, () => changed);+ await closed(tester);+ });+ }++ testWidgets('another account between the tap and the next frame: it never '+ 'shows the old picture or its name', (tester) async {+ await pump(tester);+ await until(tester, () => drawn(tester));++ await tester.tap(preview);+ var changed = false;+ unawaited(store.keepOnly('person-b').whenComplete(() => changed = true));+ // Every frame of the opening, its first (offstage) one included.+ final opening = find.byKey(+ const ValueKey('swarm-attachment-viewer'),+ skipOffstage: false,+ );+ for (var frame = 0; frame < 8; frame++) {+ await tester.pump(const Duration(milliseconds: 50));+ expect(+ find.descendant(+ of: opening,+ matching: find.byType(Image, skipOffstage: false),+ ),+ findsNothing,+ reason: 'frame $frame',+ );+ expect(+ find.descendant(+ of: opening,+ matching: find.text('screen.png', skipOffstage: false),+ ),+ findsNothing,+ reason: 'frame $frame',+ );+ }+ await frames(tester);+ expect(opening, findsNothing);++ await until(tester, () => changed);+ await closed(tester);+ });++ testWidgets('another account while the preview fetches again: a skeleton, '+ 'never the old picture, and a tap opens nothing', (tester) async {+ await pump(tester);+ await until(tester, () => drawn(tester));+ storage.hold = Completer();++ var changed = false;+ unawaited(store.keepOnly('person-b').whenComplete(() => changed = true));+ await until(tester, () => storage.asked.length == 2);++ expect(drawn(tester), isFalse, reason: "the old account's picture");+ expect(+ find.descendant(of: preview, matching: find.byType(Skeleton)),+ findsOneWidget,+ );+ await tester.tap(preview);+ await frames(tester);+ expect(viewer, findsNothing);++ storage.hold!.complete();+ await until(tester, () => changed && drawn(tester));+ await closed(tester);+ });++ testWidgets('after another account, the preview fetches its picture '+ 'again, for that account', (tester) async {+ await pump(tester);+ await until(tester, () => drawn(tester));++ var changed = false;+ unawaited(store.keepOnly('person-b').whenComplete(() => changed = true));+ await until(+ tester,+ () => changed && storage.asked.length == 2 && drawn(tester),+ );++ await tester.tap(preview);+ await tester.pumpAndSettle();+ expect(viewer, findsOneWidget, reason: "the new account's picture opens");+ await closed(tester);+ });++ testWidgets('the same account kept again leaves it open', (tester) async {+ await opened(tester);++ await tester.runAsync(() => store.keepOnly('person-me'));+ await tester.pumpAndSettle();++ expect(viewer, findsOneWidget);+ await closed(tester);+ });+ });+}diff --git a/mobile/test/swarm/swarm_avatar_link_test.dart b/mobile/test/swarm/swarm_avatar_link_test.dartnew file mode 100644index 000000000..3f8df2c24--- /dev/null+++ b/mobile/test/swarm/swarm_avatar_link_test.dart@@ -0,0 +1,45 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/profile_model.dart';++/// Which uploaded-picture links the phone draws: a private avatar bucket's+/// signed link, or a picture kept with the chat files on their CDN (a server+/// without an avatar bucket, Ken 2026-10-28), but only in its avatars folder.+void main() {+ Uri? drawn(String url) =>+ switch (SuperTabAvatarPicture.fromJson({'kind': 'upload', 'url': url})) {+ final SuperTabUploadedAvatar upload => upload.url,+ _ => null,+ };++ test('a private bucket\'s signed link', () {+ const link =+ 'https://storage.googleapis.com/avatars/tab/0123/avatar?X-Goog-Signature=1';+ expect(drawn(link), Uri.parse(link));+ });++ test('a picture in the avatars folder on the chat files\' CDN', () {+ const link = 'https://cdn.harness.autonomous.ai/avatars/tab/0123/avatar';+ expect(drawn(link), Uri.parse(link));+ });++ test('nothing else on the CDN, and nothing that only looks like it', () {+ for (final link in [+ // A chat file.+ 'https://cdn.harness.autonomous.ai/super-tabs/tab/0123/photo.png',+ // Not https.+ 'http://cdn.harness.autonomous.ai/avatars/tab/0123/avatar',+ // A folder that only starts the same, or the folder itself.+ 'https://cdn.harness.autonomous.ai/avatars-old/tab/0123/avatar',+ 'https://cdn.harness.autonomous.ai/avatars',+ 'https://cdn.harness.autonomous.ai/avatars/',+ // Out of the folder again.+ 'https://cdn.harness.autonomous.ai/avatars/../super-tabs/tab/photo.png',+ 'https://cdn.harness.autonomous.ai/avatars/%2E%2E/super-tabs/photo.png',+ // Another host.+ 'https://cdn.harness.autonomous.ai.example/avatars/tab/0123/avatar',+ 'https://elsewhere.example/avatars/tab/0123/avatar',+ ]) {+ expect(drawn(link), isNull, reason: link);+ }+ });+}diff --git a/mobile/test/swarm/swarm_buddy_chat_test.dart b/mobile/test/swarm/swarm_buddy_chat_test.dartnew file mode 100644index 000000000..926c48f9d--- /dev/null+++ b/mobile/test/swarm/swarm_buddy_chat_test.dart@@ -0,0 +1,671 @@+import 'package:flutter/material.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' as grid;+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_message_row.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// The person's own Buddy chat on the phone (#2090; Desktop's Buddy chat,+/// `buddies.dart`): named after their Buddy, with what it runs on under the+/// header, the PM's private lines read as "River (PM) → you", every question+/// the PM asked them in the project, Start your Buddy while none runs, and+/// Remove Buddy in its ⋮.+void main() {+ const chat = 'buddy-me';+ const messages = '/api/super-tabs/$tab/conversations/$chat/messages';+ const commands = '/api/super-tabs/$tab/commands';+ const offline = '2026-10-29T01:00:00.000Z';++ Map<String, dynamic> message(+ String id,+ int sequence, {+ required String author,+ String text = 'hello',+ int minute = 0,+ }) => {+ 'id': id,+ 'conversationId': chat,+ 'text': text,+ 'sequence': sequence,+ 'author': author == me+ ? {'kind': 'person', 'id': me, 'name': 'tony'}+ : {+ 'kind': 'agent',+ 'id': author,+ 'name': author == 'agent-lead' ? 'River' : 'Wren',+ },+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 10, 29, 1, minute).toIso8601String(),+ };++ /// A question River asked the person in work chat g1 of the project.+ Map<String, dynamic> decision(String id, {int minute = 0}) => {+ 'id': id,+ 'projectId': project,+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'askerName': 'River',+ 'question': 'Ship #2090 tonight?',+ 'options': ['Yes', 'Tomorrow'],+ 'recommended': 0,+ 'createdAt': DateTime.utc(2026, 10, 29, 1, minute).toIso8601String(),+ };++ Map<String, dynamic> machine(String id, String name, {String owner = me}) => {+ 'machineId': id,+ 'name': name,+ 'contributorId': owner,+ 'engines': ['claude', 'codex'],+ };++ Map<String, dynamic> wren({String? downSince}) => {+ ...buddyData('agent-wren', displayName: 'Wren'),+ 'downSince': ?downSince,+ };++ /// One Swarm where the person has their Buddy chat in Mobile, reading+ /// [page]; [buddy] runs in it, or none. [after] is what the Swarm reads+ /// next, as a start or a removal changes it.+ FakeSwarm backend({+ List<Map<String, dynamic>> page = const [],+ Map<String, dynamic>? buddy,+ List<Map<String, dynamic>> machines = const [],+ List<Map<String, dynamic>> starts = const [],+ List<Map<String, dynamic>> decisions = const [],+ String role = 'owner',+ }) {+ final derived = {'decisionsWaiting': decisions.length};+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData('g1', title: 'Fix login', number: 7),+ buddyChatData(+ chat,+ agentIds: [if (buddy != null) 'agent-wren'],+ lastMessageSequence: page.length,+ ),+ ],+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ ?buddy,+ ],+ machines: machines,+ starts: starts,+ derived: derived,+ ),+ 'members': [part(me, 1, person(me, role: role))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': decisions,+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[messages] = (_) => {+ 'messages': page.reversed.toList(),+ 'next': null,+ };+ fake.routes[commands] = (_) => {'result': <String, dynamic>{}};+ return fake;+ }++ Future<void> pump(WidgetTester tester, FakeSwarm fake) async {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ upload: refuseSwarmUpload,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmConversationPage(swarmId: tab, conversationId: chat),+ ),+ );+ await tester.pumpAndSettle();+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ String hint(WidgetTester tester) =>+ tester.widget<TextField>(find.byType(TextField)).decoration!.hintText!;++ /// The Swarm's next read has [starts], as the backend keeps them once a+ /// start was asked for.+ void startsNext(FakeSwarm fake, List<Map<String, dynamic>> starts) =>+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c3'),+ 'starts': [for (final s in starts) part(s['id'] as String, 2, s)],+ };++ group('with its Buddy running', () {+ testWidgets('is named after the Buddy, under its project, and says what '+ 'it runs on and that only the person reads it', (tester) async {+ await pump(+ tester,+ backend(+ buddy: wren(),+ machines: [machine('mac-1', 'Tonys-MacBook-Pro.local')],+ ),+ );++ expect(+ tester.widget<Text>(key('swarm-title')).data,+ 'Wren',+ reason: 'never Chat with PM (#2090)',+ );+ expect(find.text('#Mobile'), findsOneWidget);+ expect(+ tester.widget<Text>(key('swarm-buddy-where')).data,+ 'Claude on Tonys-MacBook-Pro · only you can read this chat',+ );+ expect(hint(tester), 'Message Wren');+ expect(key('swarm-buddy-start'), findsNothing);+ });++ testWidgets("a Buddy on someone else's machine says they can see its "+ 'terminal', (tester) async {+ await pump(+ tester,+ backend(+ buddy: {...wren(), 'machineOwnerId': 'person-dee'},+ machines: [machine('mac-1', 'Dee Studio', owner: 'person-dee')],+ ),+ );++ expect(+ tester.widget<Text>(key('swarm-buddy-where')).data,+ 'Claude on Dee Studio · its owner can see its terminal',+ reason: 'a person the Swarm does not list goes unnamed',+ );+ });++ testWidgets("the PM's private lines read as lines to the person, with no "+ 'role beside them; the Buddy keeps its name', (tester) async {+ await pump(+ tester,+ backend(+ buddy: wren(),+ page: [+ message(+ 'm1',+ 1,+ author: 'agent-lead',+ text: 'The Desktop build is ready',+ ),+ message('m2', 2, author: 'agent-wren', minute: 1),+ ],+ ),+ );++ final pm = key('swarm-message-m1');+ expect(+ find.descendant(of: pm, matching: find.text('River (PM) → you')),+ findsOneWidget,+ );+ expect(find.descendant(of: pm, matching: find.text('PM')), findsNothing);+ expect(+ find.descendant(+ of: key('swarm-message-m2'),+ matching: find.text('Wren'),+ ),+ findsOneWidget,+ );+ });++ testWidgets('the Buddy wears no role beside its name: a Buddy is no Dev, '+ 'as on Desktop', (tester) async {+ await pump(+ tester,+ backend(+ buddy: wren(),+ page: [message('m1', 1, author: 'agent-wren')],+ ),+ );++ final line = key('swarm-message-m1');+ expect(+ find.descendant(of: line, matching: find.text('Wren')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: line, matching: find.text('Dev')),+ findsNothing,+ );+ expect(find.byType(SwarmRoleBadge), findsNothing);+ });++ testWidgets("the PM's line is answered in the project chat, with the PM "+ 'mentioned, where everyone reads it', (tester) async {+ final fake = backend(+ buddy: wren(),+ page: [+ message('m1', 1, author: 'agent-lead', text: 'Which flag name?'),+ message('m2', 2, author: 'agent-wren', minute: 1),+ ],+ );+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] = (+ _,+ ) => {'messages': <Object>[], 'next': null};+ await pump(tester, fake);++ expect(key('swarm-answer-in-m2'), findsNothing, reason: 'the Buddy');+ expect(+ find.descendant(+ of: key('swarm-answer-in-m1'),+ matching: find.text('Answer in #Mobile'),+ ),+ findsOneWidget,+ );+ expect(find.text('Everyone there reads it'), findsOneWidget);++ await tester.tap(find.text('Answer in #Mobile'));+ await tester.pumpAndSettle();++ expect(+ key('swarm-project-chat-$leadChat'),+ findsOneWidget,+ reason: 'the project chat',+ );+ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ '@River ',+ );+ await tester.enterText(find.byType(TextField), '@River Use swarm_buddy');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();+ final post = fake.commands.single;+ expect(post['conversationId'], leadChat);+ expect(post['recipientIds'], ['agent-lead']);+ });++ testWidgets('every open question the PM asked the person in the project '+ 'shows here and is answered in place', (tester) async {+ final fake = backend(+ buddy: wren(),+ page: [message('m1', 1, author: 'agent-wren')],+ decisions: [decision('d1', minute: 2)],+ );+ await pump(tester, fake);++ expect(key('swarm-ask-d1'), findsOneWidget);+ expect(find.text('Ship #2090 tonight?'), findsOneWidget);++ await tester.tap(key('swarm-option-d1-1'));+ await tester.pump();+ expect(find.text('Sending “Tomorrow”'), findsOneWidget);+ await tester.pump(const Duration(seconds: 10));+ await tester.pumpAndSettle();+ });++ testWidgets('offline, it says so, the chat stays, and Start again starts '+ 'it on the same machine and agent', (tester) async {+ final fake = backend(+ buddy: wren(downSince: offline),+ machines: [machine('mac-1', 'Tonys-MacBook-Pro')],+ );+ await pump(tester, fake);++ expect(find.text('Wren is offline. Your chat stays.'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-buddy-start-again'),+ matching: find.text('Start again'),+ ),+ findsOneWidget,+ );+ await tester.tap(key('swarm-buddy-start-again'));+ await tester.pumpAndSettle();++ expect(fake.commands, [+ {+ 'type': 'buddy.create',+ 'projectId': project,+ 'machineId': 'mac-1',+ 'engine': 'claude',+ },+ ]);+ });++ testWidgets('an offline Codex Buddy starts again with Claude Code, since '+ 'the server refuses a Codex Buddy for now', (tester) async {+ final fake = backend(+ buddy: {+ ...wren(downSince: offline),+ 'configuration': {'engine': 'codex'},+ },+ machines: [machine('mac-1', 'Tonys-MacBook-Pro')],+ );+ await pump(tester, fake);++ expect(+ find.descendant(+ of: key('swarm-buddy-start-again'),+ matching: find.text('Start with Claude Code'),+ ),+ findsOneWidget,+ );+ await tester.tap(key('swarm-buddy-start-again'));+ await tester.pumpAndSettle();++ expect(fake.commands, [+ {+ 'type': 'buddy.create',+ 'projectId': project,+ 'machineId': 'mac-1',+ 'engine': 'claude',+ },+ ]);+ });++ testWidgets('⋮ Remove Buddy asks first; Cancel removes nothing, Remove '+ 'stops it', (tester) async {+ final fake = backend(buddy: wren());+ await pump(tester, fake);++ await tester.tap(key('swarm-buddy-menu'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Remove Buddy'));+ await tester.pumpAndSettle();+ expect(find.text('Remove Buddy?'), findsOneWidget);+ expect(+ find.text(+ 'Its session stops. Your chat stays, and adding a Buddy here '+ 'again picks it up.',+ ),+ findsOneWidget,+ );+ await tester.tap(key('swarm-buddy-remove-cancel'));+ await tester.pumpAndSettle();+ expect(fake.commands, isEmpty);++ await tester.tap(key('swarm-buddy-menu'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Remove Buddy'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-buddy-remove-confirm'));+ await tester.pumpAndSettle();++ expect(fake.commands, [+ {'type': 'buddy.remove', 'projectId': project},+ ]);+ });++ testWidgets('a removal refused says why under the header', (tester) async {+ final fake = backend(buddy: wren());+ fake.routes[commands] = (_) => throw const SuperTabFailure(+ 'FORBIDDEN',+ 'Only its person removes a Buddy.',+ statusCode: 403,+ );+ await pump(tester, fake);++ await tester.tap(key('swarm-buddy-menu'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Remove Buddy'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-buddy-remove-confirm'));+ await tester.pumpAndSettle();++ expect(+ tester.widget<Text>(key('swarm-buddy-error')).data,+ 'Only its person removes a Buddy.',+ );+ });+ });++ group('with no Buddy', () {+ testWidgets('reads Buddy, and Start starts one on the first of the '+ "person's own machines with the agent picked, then says it is "+ 'starting', (tester) async {+ final fake = backend(+ machines: [+ machine('mac-2', 'Dee Studio', owner: 'person-dee'),+ machine('mac-1', 'Tonys-MacBook-Pro.local'),+ ],+ );+ await pump(tester, fake);++ expect(tester.widget<Text>(key('swarm-title')).data, 'Buddy');+ expect(hint(tester), 'Message');+ expect(find.text('Start your Buddy to brainstorm here'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-buddy-machine'),+ matching: find.text('Tonys-MacBook-Pro'),+ ),+ findsOneWidget,+ );+ expect(key('swarm-buddy-menu'), findsNothing, reason: 'none to remove');++ startsNext(fake, [+ buddyStartData('s1', chatId: chat, machineId: 'mac-1'),+ ]);+ await tester.tap(key('swarm-buddy-start-button'));+ await tester.pumpAndSettle();++ expect(fake.commands, [+ {+ 'type': 'buddy.create',+ 'projectId': project,+ 'machineId': 'mac-1',+ 'engine': 'claude',+ },+ ]);+ expect(+ tester.widget<Text>(key('swarm-buddy-starting')).data,+ 'Starting Claude on Tonys-MacBook-Pro…',+ );+ expect(key('swarm-buddy-start'), findsNothing);+ });++ testWidgets('the machine is picked from a sheet of the person\'s own', (+ tester,+ ) async {+ final fake = backend(+ machines: [+ machine('mac-1', 'Tonys-MacBook-Pro'),+ machine('mac-4', 'Mac Studio'),+ ],+ );+ await pump(tester, fake);++ await tester.tap(key('swarm-buddy-machine'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Mac Studio'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-buddy-start-button'));+ await tester.pumpAndSettle();++ expect(fake.commands, [+ {+ 'type': 'buddy.create',+ 'projectId': project,+ 'machineId': 'mac-4',+ 'engine': 'claude',+ },+ ]);+ });++ testWidgets('with no machine of the person\'s own, it says to add one and '+ 'offers no Start', (tester) async {+ await pump(+ tester,+ backend(+ machines: [machine('mac-2', 'Dee Studio', owner: 'person-dee')],+ ),+ );++ expect(key('swarm-buddy-no-machine'), findsOneWidget);+ expect(key('swarm-buddy-start-button'), findsNothing);+ });++ testWidgets('Codex is offered turned off, with the reason the server '+ 'refuses it beside it, as on Desktop; Claude stays picked', (+ tester,+ ) async {+ final fake = backend(machines: [machine('mac-1', 'Tonys-MacBook-Pro')]);+ await pump(tester, fake);++ expect(+ find.text(+ 'A Codex Buddy is not available yet: Codex would run some commands '+ 'outside its sandbox without asking. Choose Claude Code.',+ ),+ findsOneWidget,+ );+ await tester.tap(key('swarm-buddy-engine-codex'));+ await tester.pump();+ await tester.tap(key('swarm-buddy-start-button'));+ await tester.pumpAndSettle();++ expect(fake.commands.single['engine'], 'claude');+ });++ testWidgets('a start that failed says why, and Start again asks with the '+ 'same machine and agent', (tester) async {+ final fake = backend(+ machines: [machine('mac-1', 'Tonys-MacBook-Pro')],+ starts: [+ buddyStartData(+ 's1',+ chatId: chat,+ error: 'Claude Code is not signed in on Tonys-MacBook-Pro.',+ ),+ ],+ );+ await pump(tester, fake);++ expect(+ find.text(+ "Couldn't start: Claude Code is not signed in on Tonys-MacBook-Pro.",+ ),+ findsOneWidget,+ );+ await tester.tap(key('swarm-buddy-start-again'));+ await tester.pumpAndSettle();++ expect(fake.commands.single, {+ 'type': 'buddy.create',+ 'projectId': project,+ 'machineId': 'mac-1',+ 'engine': 'claude',+ });+ });++ testWidgets('a Codex start that failed is asked again with Claude Code', (+ tester,+ ) async {+ final fake = backend(+ machines: [machine('mac-1', 'Tonys-MacBook-Pro')],+ starts: [+ buddyStartData(+ 's1',+ chatId: chat,+ engine: 'codex',+ error: 'Codex is not signed in on Tonys-MacBook-Pro.',+ ),+ ],+ );+ await pump(tester, fake);++ expect(+ find.descendant(+ of: key('swarm-buddy-start-again'),+ matching: find.text('Start with Claude Code'),+ ),+ findsOneWidget,+ );+ await tester.tap(key('swarm-buddy-start-again'));+ await tester.pumpAndSettle();++ expect(fake.commands.single, {+ 'type': 'buddy.create',+ 'projectId': project,+ 'machineId': 'mac-1',+ 'engine': 'claude',+ });+ });++ testWidgets('a refused start says why under the bar', (tester) async {+ final fake = backend(machines: [machine('mac-1', 'Tonys-MacBook-Pro')]);+ fake.routes[commands] = (_) => throw const SuperTabFailure(+ 'MACHINE_OFFLINE',+ 'Tonys-MacBook-Pro is offline.',+ statusCode: 409,+ );+ await pump(tester, fake);++ await tester.tap(key('swarm-buddy-start-button'));+ await tester.pumpAndSettle();++ expect(+ tester.widget<Text>(key('swarm-buddy-error')).data,+ 'Tonys-MacBook-Pro is offline.',+ );+ expect(key('swarm-buddy-start'), findsOneWidget);+ });+ });++ testWidgets('a viewer reads the chat, but starts and removes no Buddy', (+ tester,+ ) async {+ await pump(+ tester,+ backend(+ role: 'viewer',+ machines: [machine('mac-1', 'Tonys-MacBook-Pro')],+ ),+ );+ expect(key('swarm-buddy-start'), findsNothing);+ expect(key('swarm-buddy-bar'), findsNothing);++ await pump(+ tester,+ backend(+ role: 'viewer',+ buddy: wren(downSince: offline),+ machines: [machine('mac-1', 'Tonys-MacBook-Pro')],+ ),+ );+ expect(find.text('Wren is offline. Your chat stays.'), findsOneWidget);+ expect(key('swarm-buddy-start-again'), findsNothing);+ expect(key('swarm-buddy-menu'), findsNothing);++ await pump(+ tester,+ backend(+ role: 'viewer',+ buddy: wren(),+ page: [message('m1', 1, author: 'agent-lead')],+ ),+ );+ expect(find.text('River (PM) → you'), findsOneWidget);+ expect(key('swarm-answer-in-m1'), findsNothing, reason: 'posts nothing');+ });+}diff --git a/mobile/test/swarm/swarm_buddy_test.dart b/mobile/test/swarm/swarm_buddy_test.dartnew file mode 100644index 000000000..0aab0f1bc--- /dev/null+++ b/mobile/test/swarm/swarm_buddy_test.dart@@ -0,0 +1,604 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_buddy.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import 'swarm_fixture.dart';++/// Buddies on the phone (spec: Buddies, 10-28; every Swarm since #2090): each+/// person's Buddy chat in each project, where the PM's private lines land,+/// and the Buddy that may run in it — Desktop's `buddies.dart` and+/// `SuperTabController.buddyChat`/`buddy`/`buddyStart`.+void main() {+ SwarmReader reader(FakeSwarm swarm) =>+ SwarmReader(tabId: tab, accountId: me, request: swarm.request);++ group('the reader', () {+ test("keeps the person's own Buddy chat and Buddy in each project, and "+ 'knows every Buddy chat it holds', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ groupData('g1', title: 'Fix login', number: 7),+ buddyChatData('buddy-dee', owner: 'person-dee'),+ buddyChatData('buddy-me', agentIds: ['agent-wren']),+ ],+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ buddyData('agent-ivy', owner: 'person-dee', displayName: 'Ivy'),+ buddyData('agent-wren', displayName: 'Wren'),+ ],+ );+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();++ expect(swarmBuddyChat(r, project)?.id, 'buddy-me');+ expect(swarmBuddy(r, project)?.id, 'agent-wren');+ expect(swarmIsBuddyChat(r, 'buddy-me'), isTrue);+ expect(+ swarmIsBuddyChat(r, 'buddy-dee'),+ isTrue,+ reason: "someone else's is a Buddy chat too, never a workgroup",+ );+ expect(swarmIsBuddyChat(r, 'g1'), isFalse);+ expect(swarmIsBuddyChat(r, leadChat), isFalse);+ });++ test('has no Buddy chat or Buddy in a project where the person has '+ 'none', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [buddyChatData('buddy-dee', owner: 'person-dee')],+ agents: [buddyData('agent-ivy', owner: 'person-dee')],+ );+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();++ expect(swarmBuddyChat(r, project), isNull);+ expect(swarmBuddy(r, project), isNull);+ expect(swarmBuddyChat(r, 'project-other'), isNull);+ });++ test('follows a Buddy added later, and forgets every Buddy once access '+ 'ends', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [buddyChatData('buddy-me')]);+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c2', lastChangedAt: 200),+ 'agents': [part('agent-wren', 1, buddyData('agent-wren'))],+ };+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();+ expect(swarmBuddy(r, project), isNull);++ await r.refresh();+ expect(swarmBuddy(r, project)?.id, 'agent-wren');++ r.revoke();+ expect(swarmBuddyChat(r, project), isNull);+ expect(swarmBuddy(r, project), isNull);+ expect(swarmIsBuddyChat(r, 'buddy-me'), isFalse);+ });++ test("the newest of the person's own Buddy starts in a project is the one "+ 'that counts', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ buddyChatData('buddy-me'),+ buddyChatData('buddy-dee', owner: 'person-dee'),+ ],+ starts: [+ buddyStartData('s1', chatId: 'buddy-me', error: 'Machine offline'),+ buddyStartData('s2', chatId: 'buddy-me', engine: 'codex'),+ buddyStartData('s3', chatId: 'buddy-dee', owner: 'person-dee'),+ ],+ );+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();++ final start = swarmBuddyStart(r, project)!;+ expect(start['id'], 's2');+ expect((start['request'] as Map)['engine'], 'codex');+ });++ test('a work start is no Buddy start', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [buddyChatData('buddy-me')],+ starts: [+ {+ 'id': 's1',+ 'request': {+ 'conversationId': 'buddy-me',+ 'machineId': 'mac-1',+ 'engine': 'claude',+ },+ 'harnessId': null,+ 'error': null,+ },+ ],+ );+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();++ expect(swarmBuddyStart(r, project), isNull);+ });+ });++ group('commands', () {+ const commands = '/api/super-tabs/$tab/commands';++ test(+ 'opening a Buddy chat the read holds asks the server nothing',+ () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [buddyChatData('buddy-me')]);+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ expect(await openSwarmBuddyChat(r, project), 'buddy-me');+ expect(swarm.commands, isEmpty);+ },+ );++ test('opening one the read lacks opens it on the server, one request per '+ 'person, membership and project, and answers its id', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ swarm.routes[commands] = (_) => {+ 'result': {'conversationId': 'buddy-new'},+ };+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ expect(await openSwarmBuddyChat(r, project), 'buddy-new');+ expect(await openSwarmBuddyChat(r, project), 'buddy-new');++ expect(swarm.commands, [+ {'type': 'buddy.chat', 'projectId': project},+ {'type': 'buddy.chat', 'projectId': project},+ ]);+ final operations = {+ for (final call in swarm.calls)+ if (call.path == commands) call.body!['operationId'],+ };+ expect(operations, {+ 'buddy-chat-$project-$me-gen-$me',+ }, reason: 'a second tap or another device gets the same chat back');+ });++ test('a refused open says why', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ swarm.routes[commands] = (_) => throw const SuperTabFailure(+ 'FORBIDDEN',+ 'You cannot read this project.',+ statusCode: 403,+ );+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ await expectLater(+ openSwarmBuddyChat(r, project),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.message,+ 'message',+ 'You cannot read this project.',+ ),+ ),+ );+ });++ test('starting a Buddy sends its project, machine and engine, then reads '+ 'the Swarm again so its start shows', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [buddyChatData('buddy-me')]);+ swarm.routes[commands] = (_) => {+ 'result': {'conversationId': 'buddy-me'},+ };+ var changesRead = 0;+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) {+ changesRead++;+ return {+ ...changes(cursor: 'c2', lastChangedAt: 200),+ 'starts': [part('s1', 1, buddyStartData('s1', chatId: 'buddy-me'))],+ };+ };+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ final id = await startSwarmBuddy(+ r,+ projectId: project,+ machineId: 'mac-1',+ engine: 'codex',+ );++ expect(id, 'buddy-me');+ expect(swarm.commands, [+ {+ 'type': 'buddy.create',+ 'projectId': project,+ 'machineId': 'mac-1',+ 'engine': 'codex',+ },+ ]);+ expect(changesRead, 1);+ expect(swarmBuddyStart(r, project)?['id'], 's1');+ });++ test(+ 'removing the Buddy sends its project, then reads the Swarm again',+ () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [buddyChatData('buddy-me')],+ agents: [buddyData('agent-wren')],+ );+ swarm.routes[commands] = (_) => {'result': <String, Object?>{}};+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c2', lastChangedAt: 200),+ 'agents': [+ {+ 'key': 'agent-wren',+ 'version': 2,+ 'changedAt': 200,+ 'deleted': true,+ },+ ],+ };+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ await removeSwarmBuddy(r, project);++ expect(swarm.commands, [+ {'type': 'buddy.remove', 'projectId': project},+ ]);+ expect(swarm.paths.last, startsWith('/api/super-tabs/$tab/changes'));+ expect(swarmBuddy(r, project), isNull);+ expect(+ swarmBuddyChat(r, project)?.id,+ 'buddy-me',+ reason: 'its chat stays',+ );+ },+ );+ });++ group('a Buddy as its rows show it', () {+ Future<SwarmReader> read({+ List<Map<String, dynamic>> agents = const [],+ List<Map<String, dynamic>> starts = const [],+ }) async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [buddyChatData('buddy-me')],+ agents: agents,+ starts: starts,+ );+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();+ return r;+ }++ test('is named after its Buddy, and reads Buddy while none runs', () async {+ expect(+ swarmBuddyName(+ await read(agents: [buddyData('agent-wren', displayName: 'Wren')]),+ project,+ ),+ 'Wren',+ );+ expect(swarmBuddyName(await read(), project), 'Buddy');+ });++ test(+ 'says not started, starting, or offline; nothing while it runs',+ () async {+ expect(swarmBuddyNote(await read(), project), 'not started');+ expect(+ swarmBuddyNote(+ await read(starts: [buddyStartData('s1', chatId: 'buddy-me')]),+ project,+ ),+ 'starting',+ );+ expect(+ swarmBuddyNote(+ await read(+ starts: [+ buddyStartData('s1', chatId: 'buddy-me', error: 'No machine'),+ ],+ ),+ project,+ ),+ 'not started',+ reason: 'a start that failed is no start',+ );+ expect(+ swarmBuddyNote(+ await read(+ agents: [+ {+ ...buddyData('agent-wren'),+ 'downSince': '2026-10-29T01:00:00.000Z',+ },+ ],+ ),+ project,+ ),+ 'offline',+ );+ expect(+ swarmBuddyNote(+ await read(agents: [buddyData('agent-wren')]),+ project,+ ),+ isNull,+ );+ },+ );+ });++ group("a project's work", () {+ test('lists no Buddy chat and no private chat: Chat with PM is closed '+ '(#2090), so its old history is hidden too', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ groupData('g1', title: 'Fix login', number: 7),+ buddyChatData('buddy-me'),+ groupData('pm-old', title: 'person-me', audience: [me]),+ groupData('g2', title: 'Ship it', number: 8),+ ],+ );+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();+ final snapshot = r.snapshot!;++ final work = swarmProjectWork(+ snapshot,+ snapshot.projects.single,+ buddies: r.buddies,+ );++ expect([for (final g in work.active) g.id], ['g1', 'g2']);+ expect(work.older, isEmpty);+ });+ });++ group('the machines a Buddy may start on', () {+ Map<String, dynamic> pool(+ String id,+ String name, {+ String owner = me,+ String? host,+ }) => {+ 'machineId': id,+ 'name': name,+ 'contributorId': owner,+ 'hostMachineId': ?host,+ 'engines': ['claude', 'codex'],+ };++ test("are the person's own, named without .local; never one shared with "+ 'them or another person\'s', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ machines: [+ pool('mac-1', 'Tonys-MacBook-Pro.local'),+ pool('mac-2', 'Dee Studio', owner: 'person-dee'),+ pool('mac-3', 'Shared Mini', host: 'mac-9'),+ pool('mac-4', 'Mac Studio'),+ ],+ );+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();++ expect(swarmBuddyMachines(r), [+ (id: 'mac-1', name: 'Tonys-MacBook-Pro'),+ (id: 'mac-4', name: 'Mac Studio'),+ ]);+ });++ test('are none before the Swarm is read', () {+ final r = reader(FakeSwarm());+ addTearDown(r.dispose);++ expect(swarmBuddyMachines(r), isEmpty);+ });+ });+ group("the PM's private lines", () {+ SuperTabMessage line(String chat, String author, {bool agent = true}) =>+ SuperTabMessage.fromJson({+ 'id': 'm-$chat-$author',+ 'conversationId': chat,+ 'text': 'hello',+ 'sequence': 1,+ 'author': {'kind': agent ? 'agent' : 'person', 'id': author},+ });++ test("are the project Lead's lines in the person's own Buddy chat, and "+ 'no one else\'s', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ groupData('g1', title: 'Fix login', number: 7),+ buddyChatData('buddy-me', agentIds: ['agent-wren']),+ buddyChatData('buddy-dee', owner: 'person-dee'),+ ],+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ buddyData('agent-wren', displayName: 'Wren'),+ ],+ );+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ expect(swarmIsPmLine(r, line('buddy-me', 'agent-lead')), isTrue);+ expect(+ swarmIsPmLine(r, line('buddy-me', 'agent-wren')),+ isFalse,+ reason: 'the Buddy itself',+ );+ expect(+ swarmIsPmLine(r, line('buddy-me', me, agent: false)),+ isFalse,+ reason: 'the person',+ );+ expect(+ swarmIsPmLine(r, line('buddy-dee', 'agent-lead')),+ isFalse,+ reason: "someone else's Buddy chat",+ );+ expect(swarmIsPmLine(r, line('g1', 'agent-lead')), isFalse);+ expect(swarmIsPmLine(r, line(leadChat, 'agent-lead')), isFalse);+ expect(swarmIsOwnBuddyChat(r, 'buddy-me'), isTrue);+ expect(swarmIsOwnBuddyChat(r, 'buddy-dee'), isFalse);+ });+ });++ group('names in a Buddy chat', () {+ test('a machine by its Swarm name without .local, another machine while '+ 'unnamed; a person by their address before the @', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ machines: [+ {'machineId': 'mac-1', 'name': 'Tonys-MacBook-Pro.local'},+ {'machineId': 'mac-2', 'name': ''},+ ],+ );+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ expect(swarmBuddyMachineName(r, 'mac-1'), 'Tonys-MacBook-Pro');+ expect(swarmBuddyMachineName(r, 'mac-2'), 'another machine');+ expect(swarmBuddyMachineName(r, 'mac-9'), 'another machine');+ expect(swarmBuddyPersonName(r, me), 'person-me');+ expect(swarmBuddyPersonName(r, 'person-gone'), 'its owner');+ });+ });++ group('what the person does to their Buddy', () {+ const commands = '/api/super-tabs/$tab/commands';++ Future<(FakeSwarm, SwarmReader)> read() async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [buddyChatData('buddy-me')]);+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();+ return (swarm, r);+ }++ test('runs one at a time: a second tap while one is under way sends '+ 'nothing', () async {+ final (swarm, r) = await read();+ final answer = Completer<Object?>();+ swarm.routes[commands] = (_) => answer.future;+ final actions = SwarmBuddyActions(r, project);+ addTearDown(actions.dispose);++ final first = actions.start(machineId: 'mac-1', engine: 'codex');+ expect(actions.busy, isTrue);+ await actions.start(machineId: 'mac-1', engine: 'claude');+ await actions.remove();+ answer.complete({'result': <String, dynamic>{}});+ await first;++ expect(swarm.commands, [+ {+ 'type': 'buddy.create',+ 'projectId': project,+ 'machineId': 'mac-1',+ 'engine': 'codex',+ },+ ]);+ expect(actions.busy, isFalse);+ expect(actions.error, isNull);+ });++ test('says why a start was refused, and forgets it once the next goes '+ 'through', () async {+ final (swarm, r) = await read();+ swarm.routes[commands] = (_) => throw const SuperTabFailure(+ 'MACHINE_OFFLINE',+ 'That machine is offline.',+ statusCode: 409,+ );+ final actions = SwarmBuddyActions(r, project);+ addTearDown(actions.dispose);++ await actions.start(machineId: 'mac-1', engine: 'claude');+ expect(actions.error, 'That machine is offline.');++ swarm.routes[commands] = (_) => {'result': <String, dynamic>{}};+ await actions.remove();+ expect(actions.error, isNull);+ expect(swarm.commands.last, {+ 'type': 'buddy.remove',+ 'projectId': project,+ });+ });++ test('a failure with no reason says what failed', () async {+ final (swarm, r) = await read();+ swarm.routes[commands] = (_) => throw StateError('offline');+ final actions = SwarmBuddyActions(r, project);+ addTearDown(actions.dispose);++ await actions.remove();++ expect(actions.error, "Couldn't remove your Buddy. Try again.");+ });++ test('closed while one is under way, it tells no one', () async {+ final (swarm, r) = await read();+ final answer = Completer<Object?>();+ swarm.routes[commands] = (_) => answer.future;+ final actions = SwarmBuddyActions(r, project);+ var told = 0;+ actions.addListener(() => told++);++ final running = actions.start(machineId: 'mac-1', engine: 'claude');+ expect(told, 1);+ actions.dispose();+ answer.complete({'result': <String, dynamic>{}});+ await running;++ expect(told, 1);+ });+ });+}diff --git a/mobile/test/swarm/swarm_chat_cache_test.dart b/mobile/test/swarm/swarm_chat_cache_test.dartnew file mode 100644index 000000000..6c07df073--- /dev/null+++ b/mobile/test/swarm/swarm_chat_cache_test.dart@@ -0,0 +1,170 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_chat_cache.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';++import 'swarm_fixture.dart';++/// The chats last read on the phone, kept in memory so one opened again+/// shows at once: the last ten, each only while its Swarm's read still has+/// it, and none once the reader's access ends.+void main() {+ /// Messages m[first] to m[first + count - 1] of [conversationId].+ List<SuperTabMessage> read(+ String conversationId, {+ int first = 1,+ int count = 1,+ }) => [+ for (var i = first; i < first + count; i++)+ SuperTabMessage.fromJson({+ 'id': 'm$i',+ 'conversationId': conversationId,+ 'text': 'hello',+ 'sequence': i,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'createdAt': '2026-10-27T01:00:00.000Z',+ }),+ ];++ /// A Swarm whose first load has chats g0 to g[count - 1].+ ({FakeSwarm swarm, SwarmReader reader}) rig({int count = 11}) {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [for (var i = 0; i < count; i++) groupData('g$i')]);+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ addTearDown(reader.dispose);+ addTearDown(SwarmChatCache.clear);+ return (swarm: swarm, reader: reader);+ }++ void keep(SwarmReader reader, String id) => SwarmChatCache.keep(+ reader,+ id,+ messages: read(id),+ before: const SuperTabPage(1, 'm1'),+ );++ test('gives back what was kept, with where earlier messages start', () async {+ final r = rig();+ await r.reader.refresh();++ keep(r.reader, 'g1');+ final kept = SwarmChatCache.take(r.reader, 'g1');++ expect(kept?.messages.single.id, 'm1');+ expect(kept?.before?.id, 'm1');+ expect(SwarmChatCache.take(r.reader, 'g2'), isNull);+ });++ test('keeps a chat\'s newest page, the rest read again as earlier '+ 'messages', () async {+ final r = rig();+ await r.reader.refresh();++ SwarmChatCache.keep(+ r.reader,+ 'g1',+ messages: read('g1', count: 250),+ before: null,+ );+ final kept = SwarmChatCache.take(r.reader, 'g1')!;++ expect(kept.messages, hasLength(100));+ expect(kept.messages.first.id, 'm151');+ expect(kept.messages.last.id, 'm250');+ expect((kept.before?.sequence, kept.before?.id), (151, 'm151'));+ });++ test('keeps the last ten chats', () async {+ final r = rig();+ await r.reader.refresh();++ for (var i = 0; i < 11; i++) {+ keep(r.reader, 'g$i');+ }++ expect(SwarmChatCache.length, 10);+ expect(SwarmChatCache.take(r.reader, 'g0'), isNull);+ expect(SwarmChatCache.take(r.reader, 'g10'), isNotNull);+ });++ test('a chat opened again is the newest kept', () async {+ final r = rig();+ await r.reader.refresh();+ for (var i = 0; i < 10; i++) {+ keep(r.reader, 'g$i');+ }++ keep(r.reader, 'g0');+ keep(r.reader, 'g10');++ expect(SwarmChatCache.take(r.reader, 'g0'), isNotNull);+ expect(SwarmChatCache.take(r.reader, 'g1'), isNull);+ });++ test('keeps nothing of a chat its Swarm\'s read does not have', () async {+ final r = rig();+ await r.reader.refresh();++ keep(r.reader, 'elsewhere');++ expect(SwarmChatCache.length, 0);+ });++ test('another reader of the same Swarm gets nothing', () async {+ final r = rig();+ final other = rig();+ await r.reader.refresh();+ await other.reader.refresh();++ keep(r.reader, 'g1');++ expect(SwarmChatCache.take(other.reader, 'g1'), isNull);+ });++ test('a Swarm read again from nothing forgets its chats', () async {+ final r = rig();+ await r.reader.refresh();+ keep(r.reader, 'g1');++ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ await r.reader.refresh();++ expect(SwarmChatCache.length, 0);+ expect(SwarmChatCache.take(r.reader, 'g1'), isNull);+ });++ test('a chat its Swarm\'s read no longer has is forgotten', () async {+ final r = rig(count: 2);+ await r.reader.refresh();+ keep(r.reader, 'g0');+ keep(r.reader, 'g1');++ r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [groupData('g0')]);+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ await r.reader.refresh();++ expect(SwarmChatCache.take(r.reader, 'g1'), isNull);+ });++ test(+ 'a reader whose access ended forgets its chats, and keeps no more',+ () async {+ final r = rig();+ await r.reader.refresh();+ keep(r.reader, 'g1');++ r.reader.revoke();++ expect(SwarmChatCache.length, 0);+ keep(r.reader, 'g1');+ expect(SwarmChatCache.length, 0);+ },+ );+}diff --git a/mobile/test/swarm/swarm_chat_dictation_test.dart b/mobile/test/swarm/swarm_chat_dictation_test.dartnew file mode 100644index 000000000..3fc6adc77--- /dev/null+++ b/mobile/test/swarm/swarm_chat_dictation_test.dart@@ -0,0 +1,820 @@+import 'dart:async';++import 'package:flutter/foundation.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/voice_input_controller.dart';+import 'package:harness_mobile/phone/voice_language_store.dart';+import 'package:harness_mobile/phone/voice_mic_face.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_dictation.dart';+import 'package:harness_mobile/swarm/swarm_file_picker.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:image_picker/image_picker.dart' show XFile;++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// A Swarm chat's mic on the phone's own speech recognizer (Tony, 10-28: the+/// one the keyboard's dictation uses): the words show in the message box as+/// they are said, and it listens on — through any pause — until a second tap+/// stops it and sends what is in the box (Tony, 10-29); only two minutes+/// without a new word stop it before that, the words left in the box (Lead,+/// review of #2056). Refused, or without the language, the mic records and the+/// backend transcribes.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const commands = '/api/super-tabs/$tab/commands';++ late FakeSwarm fake;+ late FakeDictation dictation;+ late FakeVoiceRecorder recorder;+ late FakeTranscriber stt;+ late List<String> uploads;+ late String language;++ setUp(() {+ dictation = FakeDictation();+ recorder = FakeVoiceRecorder();+ stt = FakeTranscriber();+ uploads = [];+ language = voiceLanguageStore.value;+ fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 1,+ ),+ ],+ );+ 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': <Object>[], 'next': null};+ fake.routes[commands] = (_) => {'result': <String, dynamic>{}};+ });++ tearDown(() => voiceLanguageStore.value = language);++ Future<void> pump(WidgetTester tester, {bool reduceMotion = false}) async {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ upload:+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required bytes,+ required cancel,+ required onProgress,+ }) {+ uploads.add(name);+ return Completer<Map<String, dynamic>>().future;+ },+ voice: () => VoiceInputController(+ transcriber: stt.call,+ recorder: recorder,+ language: ValueNotifier('vi'),+ ),+ dictation: dictation,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(disableAnimations: reduceMotion),+ child: SwarmScope(notifier: host, child: child!),+ ),+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ ),+ );+ await tester.pumpAndSettle();+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ /// A few frames, for the take's awaits to land. Never settling: the mic's+ /// bars move for as long as it listens.+ Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 5; i++) {+ await tester.pump();+ }+ }++ Future<void> tapMic(WidgetTester tester) async {+ await tester.tap(key('swarm-mic'));+ await frames(tester);+ }++ Future<void> say(WidgetTester tester, String words) async {+ dictation.say(words);+ await frames(tester);+ }++ String box(WidgetTester tester) =>+ tester.widget<TextField>(find.byType(TextField)).controller!.text;++ Future<void> lifecycle(+ WidgetTester tester,+ List<AppLifecycleState> states,+ ) async {+ for (final state in states) {+ tester.binding.handleAppLifecycleStateChanged(state);+ }+ await frames(tester);+ }++ testWidgets('words show in the box as they are said, revised as the '+ 'recognizer changes its mind', (tester) async {+ voiceLanguageStore.value = 'vi';+ await pump(tester);++ await tapMic(tester);+ expect(dictation.locales, ['vi-VN']);+ expect(recorder.starts, 0, reason: 'the recognizer has the microphone');+ expect(+ tester.widget<VoiceMicCore>(find.byType(VoiceMicCore)).face,+ VoiceMicFace.listening,+ );++ await say(tester, 'hôm');+ expect(box(tester), 'hôm');+ await say(tester, 'hôm nay mình làm');+ expect(box(tester), 'hôm nay mình làm');+ await say(tester, 'Hôm nay mình làm gì?');+ expect(box(tester), 'Hôm nay mình làm gì?');+ expect(dictation.listening, isTrue);+ expect(fake.commands, isEmpty);+ });++ testWidgets('the second tap stops listening and sends what is in the box, '+ 'its last words included', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'một hai ba');++ dictation.lastWords = 'một hai ba bốn';+ await tapMic(tester);+ await tester.pumpAndSettle();++ expect(dictation.stops, 1);+ expect(fake.commands.single['text'], 'một hai ba bốn');+ expect(box(tester), isEmpty);+ });++ testWidgets('what was typed stays in front, and an edit made while talking '+ 'is kept and sent', (tester) async {+ await pump(tester);+ await tester.enterText(find.byType(TextField), 'Nova:');+ await tester.pump();++ await tapMic(tester);+ await say(tester, 'ship it');+ expect(box(tester), 'Nova: ship it');++ await tester.enterText(find.byType(TextField), 'Nova: ship it now');+ await tester.pump();+ await say(tester, 'ship it today');+ expect(box(tester), 'Nova: ship it now today');++ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'Nova: ship it now today');+ });++ // Lead, review of #2056 at a43760af3: an edit, then the recognizer revising+ // what it heard into fewer words.+ testWidgets('an edit, then a shorter revision of what was said, drops no '+ 'spoken word', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'một hai');+ expect(box(tester), 'một hai');++ await tester.enterText(find.byType(TextField), 'một hai,');+ await tester.pump();+ await say(tester, '12');+ await say(tester, '123 bốn');+ expect(box(tester), 'một hai, 123 bốn');++ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'một hai, 123 bốn');+ });++ // Tony, 10-29: "listening continues until I tap".+ testWidgets('listening goes on through a silence of nearly two minutes '+ 'until the tap, which sends what was said', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'xong rồi');++ for (var i = 0; i < 11; i++) {+ await tester.pump(const Duration(seconds: 10));+ }+ await tester.pump(const Duration(seconds: 9));+ expect(dictation.stops, 0);+ expect(dictation.listening, isTrue);+ expect(+ tester.widget<VoiceMicCore>(find.byType(VoiceMicCore)).face,+ VoiceMicFace.listening,+ );+ expect(fake.commands, isEmpty, reason: 'only the tap sends');++ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'xong rồi');+ });++ testWidgets('talking with pauses under two minutes never stops it', (+ tester,+ ) async {+ await pump(tester);+ await tapMic(tester);++ var said = 'một';+ await say(tester, said);+ for (var i = 0; i < 5; i++) {+ await tester.pump(const Duration(seconds: 115));+ said = '$said hai';+ await say(tester, said);+ }+ expect(dictation.listening, isTrue, reason: 'ten minutes in');+ expect(dictation.stops + dictation.cancels, 0);++ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], said);+ });++ // Lead, review of #2056 at a43760af3 (privacy): the microphone is not held+ // open for nobody.+ testWidgets('two minutes without a new word stop listening and release the '+ 'mic; the words stay, for Send or another take', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'gần xong');+ await tester.pump(const Duration(seconds: 60));+ // The same words said again by the recognizer are not new ones.+ await say(tester, 'gần xong');++ await tester.pump(const Duration(seconds: 59));+ expect(dictation.listening, isTrue);+ await tester.pump(const Duration(seconds: 1));+ await frames(tester);+ expect(dictation.listening, isFalse);+ expect(dictation.cancels, 1, reason: 'the microphone released at once');+ expect(find.byType(VoiceMicCore), findsNothing, reason: 'the mic at rest');+ expect(box(tester), 'gần xong');+ expect(fake.commands, isEmpty);++ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'gần xong');++ await tapMic(tester);+ expect(dictation.listening, isTrue, reason: 'a new take');+ expect(dictation.locales, hasLength(2));+ });++ testWidgets('two minutes with nothing said at all stop listening too', (+ tester,+ ) async {+ await pump(tester);+ await tester.enterText(find.byType(TextField), 'Draft');+ await tester.pump();+ await tapMic(tester);++ await tester.pump(const Duration(minutes: 2));+ await frames(tester);+ expect(dictation.listening, isFalse);+ expect(dictation.cancels, 1);+ expect(box(tester), 'Draft');+ expect(fake.commands, isEmpty);+ });++ testWidgets('stopping by itself says so quietly for three seconds; the '+ 'words stay in the box', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'almost done');+ expect(find.text('Stopped listening'), findsNothing);++ await tester.pump(const Duration(minutes: 2));+ await frames(tester);+ expect(dictation.listening, isFalse);+ expect(+ tester.widget<Text>(key('swarm-voice-stopped')).data,+ 'Stopped listening',+ );+ expect(box(tester), 'almost done');+ expect(key('swarm-voice-note'), findsNothing, reason: 'nothing went wrong');++ await tester.pump(const Duration(milliseconds: 2900));+ expect(find.text('Stopped listening'), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 100));+ expect(find.text('Stopped listening'), findsNothing);+ expect(box(tester), 'almost done');+ expect(fake.commands, isEmpty);+ });++ testWidgets('a tap ends no take with Stopped listening, and a new take '+ 'takes it away', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'Ship it');+ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(find.text('Stopped listening'), findsNothing, reason: 'tapped');++ await tapMic(tester);+ await tester.pump(const Duration(minutes: 2));+ await frames(tester);+ expect(find.text('Stopped listening'), findsOneWidget);+ await tapMic(tester);+ expect(find.text('Stopped listening'), findsNothing);+ });++ testWidgets('a second tap with nothing said sends nothing', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await tapMic(tester);+ await tester.pumpAndSettle();++ expect(dictation.stops, 1);+ expect(box(tester), isEmpty);+ expect(fake.commands, isEmpty);+ });++ testWidgets('a second tap with nothing said sends what was typed', (+ tester,+ ) async {+ await pump(tester);+ await tester.enterText(find.byType(TextField), 'Draft');+ await tester.pump();++ await tapMic(tester);+ await tapMic(tester);+ await tester.pumpAndSettle();++ expect(fake.commands.single['text'], 'Draft');+ expect(box(tester), isEmpty);+ expect(find.text("Didn't catch that · tap the mic again"), findsNothing);+ });++ testWidgets('a second tap with nothing said and an empty box says so', (+ tester,+ ) async {+ await pump(tester);+ await tapMic(tester);+ await tapMic(tester);+ await tester.pumpAndSettle();++ expect(fake.commands, isEmpty);+ expect(find.text("Didn't catch that · tap the mic again"), findsOneWidget);+ });++ testWidgets('a recognizer that never says it stopped is given up after two '+ 'seconds, and what is in the box is sent', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'gửi đi');++ dictation.stopsSilently = true;+ await tapMic(tester);+ await tester.pump(const Duration(milliseconds: 1900));+ expect(+ tester.widget<VoiceMicCore>(find.byType(VoiceMicCore)).face,+ VoiceMicFace.busy,+ reason: 'still waiting for its last words',+ );++ await tester.pump(const Duration(milliseconds: 200));+ await frames(tester);+ expect(find.byType(VoiceMicCore), findsNothing);+ expect(dictation.cancels, 1);+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'gửi đi');+ expect(box(tester), isEmpty);+ });++ testWidgets('a second tap sends nothing once the box was emptied, though '+ 'files wait to go', (tester) async {+ final documents = pickSwarmFiles, copies = swarmPickerCopyFolders;+ addTearDown(() {+ pickSwarmFiles = documents;+ swarmPickerCopyFolders = copies;+ });+ swarmPickerCopyFolders = () async => const [];+ pickSwarmFiles = () async => [+ XFile.fromData(+ Uint8List(12),+ path: '/picker-copies/crash.log',+ length: 12,+ ),+ ];+ await pump(tester);+ await tester.tap(key('swarm-attach'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-attach-files'));+ await tester.pumpAndSettle();++ await tapMic(tester);+ await say(tester, 'nhầm rồi');+ await tester.enterText(find.byType(TextField), '');+ await tester.pump();+ dictation.lastWords = 'nhầm rồi';+ await tapMic(tester);+ await tester.pumpAndSettle();++ expect(box(tester), isEmpty);+ expect(uploads, isEmpty);+ expect(fake.commands, isEmpty);+ expect(key('swarm-outgoing-crash.log'), findsOneWidget);+ });++ testWidgets('listening that cannot go on stops, its words left unsent', (+ tester,+ ) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'một phút rồi');++ dictation.end(SwarmDictationEnd.done);+ await frames(tester);++ expect(box(tester), 'một phút rồi');+ expect(fake.commands, isEmpty);+ expect(find.byType(VoiceMicCore), findsNothing);+ });++ testWidgets('a recognizer that fails says so and keeps what it heard', (+ tester,+ ) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'một');++ dictation.end(SwarmDictationEnd.failed);+ await frames(tester);++ expect(box(tester), 'một');+ expect(+ find.text("Couldn't transcribe · tap the mic again"),+ findsOneWidget,+ );+ expect(fake.commands, isEmpty);+ });++ testWidgets('a second tap on a recognizer that fails as it stops still '+ 'sends what is in the box', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'gửi');++ dictation.stopEnd = SwarmDictationEnd.failed;+ await tapMic(tester);+ await tester.pumpAndSettle();++ expect(fake.commands.single['text'], 'gửi');+ });++ testWidgets('a second tap sends what was said though the last session heard '+ 'nothing', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'xin chào');++ dictation.stopEnd = SwarmDictationEnd.noSpeech;+ await tapMic(tester);+ await tester.pumpAndSettle();++ expect(fake.commands.single['text'], 'xin chào');+ expect(find.text("Didn't catch that · tap the mic again"), findsNothing);+ });++ testWidgets('nothing said before the recognizer gives up is said so', (+ tester,+ ) async {+ await pump(tester);+ await tapMic(tester);++ dictation.end(SwarmDictationEnd.noSpeech);+ await frames(tester);++ expect(find.text("Didn't catch that · tap the mic again"), findsOneWidget);+ });++ testWidgets('the mic is drawn as loud as the recognizer hears', (+ tester,+ ) async {+ await pump(tester);+ await tapMic(tester);++ dictation.loud(0.8);+ await tester.pump();++ expect(+ tester.widget<VoiceMicCore>(find.byType(VoiceMicCore)).level!.value,+ 0.8,+ );+ });++ /// How tall the mic's bars stand, all together: the face's 4pt-wide boxes.+ double bars(WidgetTester tester) => tester+ .widgetList<Container>(+ find.descendant(+ of: find.byType(VoiceMicCore),+ matching: find.byType(Container),+ ),+ )+ .map((box) => box.constraints)+ .where((size) => size?.maxWidth == 4)+ .fold(0, (sum, bar) => sum + bar!.maxHeight);++ /// Half a second of the bars' frames.+ Future<void> wave(WidgetTester tester) async {+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ }++ // Lead, 10-29: "a live wave animation driven by the mic level".+ testWidgets('the bars rise as the voice does', (tester) async {+ await pump(tester);+ await tapMic(tester);+ dictation.loud(0);+ await wave(tester);+ final quiet = bars(tester);++ dictation.loud(0.8);+ await wave(tester);+ expect(bars(tester), greaterThan(quiet + 20));+ });++ testWidgets('with Reduce Motion on, the bars still follow the voice', (+ tester,+ ) async {+ await pump(tester, reduceMotion: true);+ await tapMic(tester);+ dictation.loud(0);+ await tester.pump();+ final quiet = bars(tester);++ dictation.loud(0.8);+ await tester.pump();+ expect(bars(tester), greaterThan(quiet + 20));+ });++ testWidgets('the long-press language is the one listened in', (tester) async {+ voiceLanguageStore.value = 'ja';+ await pump(tester);++ await tapMic(tester);++ expect(dictation.locales, ['ja-JP']);+ });++ testWidgets('speech recognition refused: the mic records and transcribes, '+ 'and is not asked again', (tester) async {+ dictation.answer = SwarmDictationAccess.denied;+ await pump(tester);+ stt.replies.addAll(['ghi âm', 'lần nữa']);++ await tapMic(tester);+ expect(dictation.locales, isEmpty);+ expect(recorder.recording, isTrue);+ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'ghi âm');++ await tapMic(tester);+ expect(dictation.asks, 1);+ expect(recorder.recording, isTrue);+ });++ testWidgets('a language the recognizer lacks records and transcribes '+ 'instead', (tester) async {+ dictation.hasLocale = false;+ await pump(tester);++ await tapMic(tester);++ expect(dictation.locales, hasLength(1));+ expect(recorder.recording, isTrue);+ });++ testWidgets('a tap while the permission prompt is up calls the take off', (+ tester,+ ) async {+ dictation.pendingAccess = Completer();+ await pump(tester);++ await tapMic(tester);+ await tapMic(tester);+ dictation.pendingAccess!.complete(SwarmDictationAccess.allowed);+ await frames(tester);++ expect(dictation.locales, isEmpty);+ expect(recorder.starts, 0);+ expect(find.byType(VoiceMicCore), findsNothing, reason: 'back at rest');+ });++ testWidgets('the permission prompt over the app keeps the take it asks for', (+ tester,+ ) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ dictation.pendingAccess = Completer();+ await pump(tester);++ await tapMic(tester);+ await lifecycle(tester, [AppLifecycleState.inactive]);+ dictation.pendingAccess!.complete(SwarmDictationAccess.allowed);+ await lifecycle(tester, [AppLifecycleState.resumed]);++ expect(dictation.listening, isTrue);+ await say(tester, 'được');+ expect(box(tester), 'được');+ });++ testWidgets('Control Center or the app going away stops listening; the '+ 'words already shown stay', (tester) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'trước');++ await lifecycle(tester, [AppLifecycleState.inactive]);++ expect(dictation.cancels, 1);+ expect(dictation.listening, isFalse);+ await lifecycle(tester, [AppLifecycleState.resumed]);+ await tester.pump(const Duration(seconds: 5));+ expect(box(tester), 'trước');+ expect(fake.commands, isEmpty);+ });++ testWidgets('what a take called off still says lands nowhere, even in the '+ 'next take', (tester) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'trước');+ final first = dictation.heard.single;+ await lifecycle(tester, [+ AppLifecycleState.inactive,+ AppLifecycleState.resumed,+ ]);+ await tapMic(tester);+ await say(tester, 'sau');++ first('trước nữa');+ await frames(tester);++ expect(box(tester), 'trước sau');+ });++ testWidgets('covering the chat stops listening', (tester) async {+ await pump(tester);+ await tapMic(tester);+ await say(tester, 'đang nói');++ final context = tester.element(find.byType(SwarmConversationPage));+ unawaited(+ Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => const Scaffold(body: Text('Other screen')),+ ),+ ),+ );+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));++ expect(dictation.cancels, 1);+ expect(dictation.listening, isFalse);+ expect(fake.commands, isEmpty);+ });++ testWidgets('leaving the chat stops listening', (tester) async {+ await pump(tester);+ await tapMic(tester);++ await tester.pumpWidget(const SizedBox());++ expect(dictation.cancels, 1);+ });+}++/// The phone's own recognizer, spoken for by the test: [say] is what it+/// heard so far, [end] how it stopped by itself; [stop] delivers [lastWords]+/// and ends with [stopEnd] — or, [stopsSilently], never says it has.+class FakeDictation implements SwarmDictation {+ SwarmDictationAccess answer = SwarmDictationAccess.allowed;+ Completer<SwarmDictationAccess>? pendingAccess;+ bool hasLocale = true;+ String? lastWords;+ SwarmDictationEnd stopEnd = SwarmDictationEnd.done;+ bool stopsSilently = false;++ final List<String> locales = [];++ /// Each take's `onWords`, called off or not.+ final List<void Function(String)> heard = [];+ int asks = 0, stops = 0, cancels = 0;++ void Function(String)? _words;+ void Function(double)? _level;+ void Function(SwarmDictationEnd)? _end;++ bool get listening => _end != null;++ void say(String words) => _words?.call(words);++ void loud(double level) => _level?.call(level);++ void end(SwarmDictationEnd end) {+ final ended = _end;+ _forget();+ ended?.call(end);+ }++ @override+ Future<SwarmDictationAccess> access() {+ asks++;+ return pendingAccess?.future ?? Future.value(answer);+ }++ @override+ Future<bool> start(+ String locale, {+ required void Function(String words) onWords,+ required void Function(double level) onLevel,+ required void Function(SwarmDictationEnd end) onEnd,+ }) async {+ locales.add(locale);+ if (!hasLocale) return false;+ heard.add(onWords);+ _words = onWords;+ _level = onLevel;+ _end = onEnd;+ return true;+ }++ @override+ Future<void> stop() async {+ stops++;+ if (stopsSilently) return;+ if (lastWords case final words?) say(words);+ end(stopEnd);+ }++ @override+ Future<void> cancel() async {+ cancels++;+ _forget();+ }++ void _forget() {+ _words = null;+ _level = null;+ _end = null;+ }+}diff --git a/mobile/test/swarm/swarm_chat_pictures_test.dart b/mobile/test/swarm/swarm_chat_pictures_test.dartnew file mode 100644index 000000000..d3362f983--- /dev/null+++ b/mobile/test/swarm/swarm_chat_pictures_test.dart@@ -0,0 +1,147 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/material.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/widgets/skeleton.dart';+import 'package:harness_mobile/swarm/swarm_attachment_store.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_message_row.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// In a chat, a picture on Harness's file storage shows in place, and every+/// other file keeps its chip.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const pathProvider = MethodChannel('plugins.flutter.io/path_provider');+ late Directory temporary;++ setUp(() {+ temporary = Directory.systemTemp.createTempSync('phone-temporary-');+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(+ pathProvider,+ (call) async =>+ call.method == 'getTemporaryDirectory' ? temporary.path : null,+ );+ });+ tearDown(() {+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(pathProvider, null);+ if (temporary.existsSync()) temporary.deleteSync(recursive: true);+ });++ Map<String, dynamic> file(String id, String name, String mime) => {+ 'id': id,+ 'name': name,+ 'mime': mime,+ 'size': 2048,+ 'url': 'https://$swarmAttachmentHost/$id/$name',+ };++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-builder'],+ lastMessageSequence: 1,+ ),+ ],+ ),+ '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': 'm1',+ 'conversationId': 'g1',+ 'text': 'The sign-in sheet, and the plan',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'attachments': [+ file('f1', 'sheet.png', 'image/png'),+ file('f2', 'plan.pdf', 'application/pdf'),+ ],+ 'createdAt': DateTime.utc(2026, 10, 27, 1).toIso8601String(),+ },+ ],+ 'next': null,+ };+ return fake;+ }++ testWidgets('a picture shows in place; a PDF keeps its chip', (tester) async {+ // The app's store keeps this account's files, as the shell's keeper has+ // it do. Real folders: outside the test's fake clock.+ await tester.runAsync(() => swarmAttachments.keepOnly(me));+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ )..foreground = false;+ addTearDown(host.dispose);++ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ ),+ );+ final preview = find.byKey(const ValueKey('swarm-attachment-preview-f1'));+ // Frames until the message is read; not pumpAndSettle, as a skeleton+ // breathes for as long as it is up.+ for (var i = 0; i < 50 && preview.evaluate().isEmpty; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(preview, findsOneWidget);+ expect(+ find.descendant(of: preview, matching: find.byType(Skeleton)),+ findsOneWidget,+ reason: 'loading',+ );+ expect(find.textContaining('sheet.png'), findsNothing);+ expect(find.textContaining('plan.pdf'), findsOneWidget);++ // Signed out: emptying waits for the fetch under way, so real time and+ // frames until it is done.+ await tester.pumpWidget(const SizedBox());+ var emptied = false;+ unawaited(swarmAttachments.keepOnly(null).then((_) => emptied = true));+ for (var i = 0; i < 200 && !emptied; i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump();+ }+ expect(emptied, isTrue);+ // The cache's own cleanup, which it runs every few seconds, let run.+ await tester.pump(const Duration(minutes: 1));+ });+}diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dartnew file mode 100644index 000000000..3ea7e01dc--- /dev/null+++ b/mobile/test/swarm/swarm_chat_test.dart@@ -0,0 +1,2187 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:image_picker/image_picker.dart' show XFile;+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' as grid;+import 'package:harness_mobile/swarm/swarm_chat_cache.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_file_picker.dart';+import 'package:harness_mobile/swarm/swarm_message_row.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import '../theme/sheet_shape.dart';+import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// A Swarm chat on the phone, as Tony's prototype has it: who wrote each+/// message and in what role, follow-ups grouped, a reply's quote that brings+/// its original into view, Reply, the @ picker, files attached from the photo+/// library, the camera or Files, and a post that shows at once and says when it+/// is not confirmed.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const commands = '/api/super-tabs/$tab/commands';++ Map<String, dynamic> message(+ String id,+ int sequence, {+ String text = 'hello',+ String author = 'agent-builder',+ String? replyTo,+ int minute = 0,+ DateTime? at,+ List<Map<String, dynamic>> attachments = const [],+ Map<String, List<(String, String)>> reactions = const {},+ }) => {+ 'id': id,+ 'conversationId': 'g1',+ 'text': text,+ 'sequence': sequence,+ 'replyTo': ?replyTo,+ 'author': author == me+ ? {'kind': 'person', 'id': me, 'name': 'tony'}+ : {+ 'kind': 'agent',+ 'id': author,+ 'name': author == 'agent-lead' ? 'River' : 'Nova',+ },+ 'attachments': attachments,+ 'reactions': [+ for (final MapEntry(key: emoji, value: by) in reactions.entries)+ {+ 'emoji': emoji,+ 'count': by.length,+ 'by': [+ for (final (kind, who) in by) {'kind': kind, 'id': who},+ ],+ },+ ],+ 'createdAt': (at ?? DateTime.utc(2026, 10, 27, 1, minute))+ .toUtc()+ .toIso8601String(),+ };++ /// A decision River asked in chat g1, at [minute] past one.+ Map<String, dynamic> decision(String id, {int minute = 0}) => {+ 'id': id,+ 'projectId': project,+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'askerName': 'River',+ 'question': 'Ship it behind a flag?',+ 'options': ['Flag 1 week', 'Everyone'],+ 'recommended': 0,+ 'createdAt': DateTime.utc(2026, 10, 27, 1, minute).toIso8601String(),+ };++ /// One Swarm whose chat g1 has River (its project's Product Manager) and+ /// Nova (an engineer), reading [page] as its latest messages, with+ /// [decisions] open in it. With [audience], g1 is that person's own chat.+ FakeSwarm backend(+ List<Map<String, dynamic>> page, {+ Object? next,+ List<Map<String, dynamic>> decisions = const [],+ List<String>? audience,+ List<Map<String, dynamic>>? members,+ }) {+ // The Swarm's counts say a decision waits: what has its list read.+ final derived = {'decisionsWaiting': decisions.length};+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ audience: audience,+ lastMessageSequence: page.isEmpty+ ? 0+ : page+ .map((m) => m['sequence'] as int)+ .reduce((a, b) => a > b ? a : b),+ ),+ ],+ derived: derived,+ ),+ 'members': [+ for (final member in members ?? [person(me)])+ part(member['id'] as String, 1, member),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': decisions,+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[messages] = (_) => {+ 'messages': page.reversed.toList(),+ 'next': next,+ };+ fake.routes[commands] = (_) => {'result': <String, dynamic>{}};+ return fake;+ }++ /// Who is signed in, and Settings ▸ Experimental, of the last [pump].+ late ValueNotifier<String?> account;+ late ExperimentalFeaturesStore features;++ /// A few frames, for reads answered at once to land, never settling: a+ /// skeleton breathes for as long as it shows.+ Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 5; i++) {+ await tester.pump();+ }+ }++ /// Chat [conversation] of [host]'s Swarm on screen.+ Future<void> show(+ WidgetTester tester,+ SwarmHost host, {+ String conversation = 'g1',+ String? messageId,+ String? decisionId,+ bool settle = true,+ }) async {+ await tester.pumpWidget(+ // The app's own theme, as the shell sets it: its field defaults are+ // what the composer has to hold back.+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: SwarmConversationPage(+ swarmId: tab,+ conversationId: conversation,+ messageId: messageId,+ decisionId: decisionId,+ ),+ ),+ );+ if (settle) {+ await tester.pumpAndSettle();+ } else {+ await frames(tester);+ }+ }++ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ String conversation = 'g1',+ String? messageId,+ String? decisionId,+ bool settle = true,+ SwarmUpload upload = refuseSwarmUpload,+ }) async {+ features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ upload: upload,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await show(+ tester,+ host,+ conversation: conversation,+ settle: settle,+ messageId: messageId,+ decisionId: decisionId,+ );+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ /// The message rows built while [act] runs, by message id: a row drawn as+ /// it was is not built at all.+ Future<List<String>> rowsBuilt(Future<void> Function() act) async {+ final built = <String>[];+ final before = debugOnRebuildDirtyWidget;+ debugOnRebuildDirtyWidget = (element, _) {+ if (element.widget case SwarmMessageRow(:final message)) {+ built.add(message.id);+ }+ };+ try {+ await act();+ } finally {+ debugOnRebuildDirtyWidget = before;+ }+ return built;+ }++ String time(int minute) {+ final at = DateTime.utc(2026, 10, 27, 1, minute).toLocal();+ String two(int n) => n.toString().padLeft(2, '0');+ return '${two(at.hour)}:${two(at.minute)}';+ }++ /// [finder] is drawn inside the message list's view.+ bool inView(WidgetTester tester, Finder finder) {+ final list = tester.getRect(key('swarm-messages'));+ final rect = tester.getRect(finder);+ return rect.top >= list.top - 1 && rect.bottom <= list.bottom + 1;+ }++ /// Whether the composer holds the keyboard: its field focused, and the+ /// keyboard shown.+ ({bool focused, bool keyboard}) composer(WidgetTester tester) => (+ focused: tester+ .widget<TextField>(find.byType(TextField))+ .focusNode!+ .hasFocus,+ keyboard: tester.testTextInput.isVisible,+ );+ const up = (focused: true, keyboard: true);+ const down = (focused: false, keyboard: false);++ testWidgets('each message says who wrote it, in what role and when; '+ 'follow-ups are grouped under one name', (tester) async {+ await pump(+ tester,+ backend([+ message('m1', 1, author: 'agent-lead', text: 'Plan for today'),+ message(+ 'm2',+ 2,+ author: 'agent-lead',+ text: 'Then the build',+ minute: 1,+ ),+ message('m3', 3, text: 'On it', minute: 2),+ message('m4', 4, author: me, text: 'Thanks', minute: 3),+ ]),+ );++ expect(find.text('River'), findsOneWidget, reason: 'grouped once');+ expect(find.text('PM'), findsOneWidget);+ expect(find.text('Nova'), findsOneWidget);+ expect(find.text('Dev'), findsOneWidget);+ expect(find.text('tony'), findsOneWidget);+ expect(find.text(time(0)), findsOneWidget);+ expect(find.text(time(1)), findsNothing, reason: 'a follow-up has none');+ expect(find.text(time(2)), findsOneWidget);+ expect(find.text('Then the build'), findsOneWidget);+ });++ testWidgets('a file in a message opens', (tester) async {+ // Review of #1802 at bd73842: this test once passed with opening off.+ final opened = <Object?>[];+ const launcher = MethodChannel('plugins.flutter.io/url_launcher');+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(launcher, (call) async {+ opened.add((call.arguments as Map)['url']);+ return true;+ });+ addTearDown(() => messenger.setMockMethodCallHandler(launcher, null));+ await pump(+ tester,+ backend([+ message(+ 'm1',+ 1,+ text: 'Here is the plan',+ attachments: [+ {+ 'id': 'f1',+ 'name': 'plan.md',+ 'mime': 'text/markdown',+ 'size': 2048,+ 'url': 'https://cdn.harness.autonomous.ai/f1/plan.md',+ },+ ],+ ),+ ]),+ );++ expect(find.textContaining('plan.md'), findsOneWidget);++ await tester.tap(find.textContaining('plan.md'));+ await tester.pump();++ expect(opened, ['https://cdn.harness.autonomous.ai/f1/plan.md']);+ });++ testWidgets('a notification opens an earlier message and highlights it', (+ tester,+ ) async {+ await pump(+ tester,+ backend([+ for (var i = 1; i <= 40; i++)+ message('m$i', i, text: 'Message $i\nMore text', minute: i),+ ]),+ messageId: 'm1',+ );+ expect(key('swarm-lit-m1'), findsOneWidget);+ expect(inView(tester, find.text('Message 1\nMore text')), isTrue);+ });++ testWidgets('opened at an earlier message, the chat is read only once the '+ 'person goes down to its newest', (tester) async {+ final fake = backend([+ for (var i = 1; i <= 40; i++)+ message('m$i', i, text: 'Message $i\nMore text', minute: i),+ ]);+ List<Object?> marksSent() => [+ for (final call in fake.calls)+ if (call.method == 'POST' &&+ call.path == '/api/super-tabs/$tab/conversations/g1/read')+ call.body?['sequence'],+ ];+ await pump(tester, fake, messageId: 'm1');+ expect(inView(tester, find.text('Message 1\nMore text')), isTrue);++ expect(marksSent(), everyElement(lessThanOrEqualTo(1)));++ for (var i = 0; i < 10; i++) {+ await tester.drag(key('swarm-messages'), const Offset(0, -2000));+ await tester.pumpAndSettle();+ }++ expect(inView(tester, find.text('Message 40\nMore text')), isTrue);+ expect(marksSent().last, 40);+ });++ testWidgets(+ 'following a quote after a decision notification changes the target',+ (tester) async {+ await pump(+ tester,+ backend(+ [+ message('m1', 1, text: 'Original plan'),+ message('m2', 2, text: 'Follow up', replyTo: 'm1', minute: 1),+ ],+ decisions: [decision('d1')],+ ),+ decisionId: 'd1',+ );+ await tester.tap(key('swarm-quote-m2'));+ await tester.pumpAndSettle();+ expect(key('swarm-lit-m1'), findsOneWidget);+ },+ );++ testWidgets('a notification brings its decision card into view', (+ tester,+ ) async {+ await pump(+ tester,+ backend(+ [+ for (var i = 1; i <= 40; i++)+ message('m$i', i, text: 'Message $i\nMore text', minute: i),+ ],+ decisions: [decision('d1')],+ ),+ decisionId: 'd1',+ );+ expect(inView(tester, find.text('Ship it behind a flag?')), isTrue);+ });++ testWidgets('a reply quotes its original; tapping the quote brings the '+ 'original into view and lights it for a moment', (tester) async {+ await pump(+ tester,+ backend([+ message('m1', 1, author: 'agent-lead', text: 'The very first plan'),+ for (var i = 2; i < 40; i++)+ message('m$i', i, text: 'Line $i\nof the log', minute: i),+ message('m40', 40, author: me, text: 'Yes', replyTo: 'm1', minute: 50),+ ]),+ );+ final original = find.text('The very first plan');+ // Its quote is on screen; the message itself is far up.+ expect(original, findsOneWidget);+ expect(key('swarm-quote-m40'), findsOneWidget);++ await tester.tap(key('swarm-quote-m40'));+ await tester.pumpAndSettle();++ final row = find.descendant(+ of: key('swarm-message-m1'),+ matching: find.text('The very first plan'),+ );+ expect(inView(tester, row), isTrue);+ expect(key('swarm-lit-m1'), findsOneWidget);++ await tester.pump(const Duration(seconds: 3));+ await tester.pumpAndSettle();+ expect(key('swarm-lit-m1'), findsNothing);+ });++ testWidgets('an original further back is read in from earlier pages, then '+ 'shown', (tester) async {+ // A first page taller than the screen: nothing earlier is read until+ // the quote asks for it.+ final fake = backend(+ [+ for (var i = 10; i < 40; i++)+ message('m$i', i, text: 'Line $i\nof the log', minute: i),+ message('m40', 40, author: me, text: 'Yes', replyTo: 'm1', minute: 50),+ ],+ next: {'sequence': 10, 'id': 'm10'},+ );+ fake.routes['$messages?before=10&beforeId=m10'] = (_) => {+ 'messages': [+ for (var i = 9; i > 1; i--) message('m$i', i, minute: i),+ message('m1', 1, author: 'agent-lead', text: 'The very first plan'),+ ],+ 'next': null,+ };+ await pump(tester, fake);+ expect(find.text("The original message isn't loaded."), findsOneWidget);++ await tester.tap(key('swarm-quote-m40'));+ await tester.pumpAndSettle();++ expect(fake.paths, contains('$messages?before=10&beforeId=m10'));+ final row = find.descendant(+ of: key('swarm-message-m1'),+ matching: find.text('The very first plan'),+ );+ expect(inView(tester, row), isTrue);+ expect(key('swarm-lit-m1'), findsOneWidget);+ });++ testWidgets('an original no longer in the chat says so', (tester) async {+ await pump(+ tester,+ backend([message('m2', 2, author: me, text: 'Yes', replyTo: 'm-gone')]),+ );++ await tester.tap(key('swarm-quote-m2'));+ await tester.pumpAndSettle();++ expect(+ find.text('The original message is no longer in this chat.'),+ findsOneWidget,+ );+ });++ testWidgets('Reply: a tap on a message, Reply, a bar over the composer, and '+ 'the post answers that message', (tester) async {+ final fake = backend([message('m1', 1, text: 'Which name for the flag?')]);+ await pump(tester, fake);++ await tester.tap(find.text('Which name for the flag?'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-reply-m1'));+ await tester.pumpAndSettle();++ expect(key('swarm-reply-bar'), findsOneWidget);+ expect(find.textContaining('Reply to Nova'), findsOneWidget);++ await tester.enterText(find.byType(TextField), 'beta');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(fake.commands.single['replyTo'], 'm1');+ expect(key('swarm-reply-bar'), findsNothing);+ });++ testWidgets('a reply can be taken back before it is sent', (tester) async {+ final fake = backend([message('m1', 1, text: 'Which name for the flag?')]);+ await pump(tester, fake);+ await tester.tap(find.text('Which name for the flag?'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-reply-m1'));+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-reply-cancel'));+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), 'beta');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(key('swarm-reply-bar'), findsNothing);+ expect(fake.commands.single['replyTo'], isNull);+ });++ testWidgets('the composer has no @ button: an @ typed in the field opens '+ 'the picker', (tester) async {+ await pump(tester, backend([message('m1', 1)]));++ expect(key('swarm-attach'), findsOneWidget);+ expect(key('swarm-field'), findsOneWidget);+ expect(key('swarm-send'), findsOneWidget);+ expect(key('swarm-mention'), findsNothing);+ expect(find.byIcon(LucideIcons.atSign), findsNothing);++ await tester.enterText(find.byType(TextField), '@');+ await tester.pump();+ expect(key('swarm-mention-picker'), findsOneWidget);+ expect(key('swarm-pick-agent-lead'), findsOneWidget);+ expect(key('swarm-pick-agent-builder'), findsOneWidget);+ });++ testWidgets('the @ picker lists the chat\'s agents with role and state, '+ 'narrowed by what is typed', (tester) async {+ await pump(tester, backend([message('m1', 1)]));++ await tester.enterText(find.byType(TextField), '@');+ await tester.pump();+ expect(key('swarm-mention-picker'), findsOneWidget);+ expect(key('swarm-pick-agent-lead'), findsOneWidget);+ expect(key('swarm-pick-agent-builder'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-pick-agent-builder'),+ matching: find.text('Working'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: key('swarm-pick-agent-lead'),+ matching: find.text('PM'),+ ),+ findsOneWidget,+ );++ await tester.enterText(find.byType(TextField), 'ask @no');+ await tester.pump();+ expect(key('swarm-pick-agent-lead'), findsNothing);+ expect(key('swarm-pick-agent-builder'), findsOneWidget);++ await tester.enterText(find.byType(TextField), 'ask @zed');+ await tester.pump();+ expect(find.text('No agent by that name.'), findsOneWidget);++ await tester.enterText(find.byType(TextField), 'ask @N');+ await tester.pump();+ await tester.tap(key('swarm-pick-agent-builder'));+ await tester.pump();+ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ 'ask @Nova ',+ );+ expect(key('swarm-mention-picker'), findsNothing);+ });++ testWidgets('a post shows at once as Sending…, out of the field, and as '+ 'sent once read back', (tester) async {+ final fake = backend([message('m1', 1)]);+ final taken = Completer<Object?>();+ fake.routes[commands] = (_) => taken.future;+ await pump(tester, fake);++ await tester.enterText(find.byType(TextField), 'On it');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pump();++ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ isEmpty,+ );+ expect(key('swarm-pending'), findsOneWidget);+ expect(find.text('Sending…'), findsOneWidget);+ expect(find.text('On it'), findsOneWidget);++ fake.routes['$messages?after=1'] = (_) => {+ 'messages': [message('m2', 2, author: me, text: 'On it', minute: 5)],+ 'next': null,+ };+ taken.complete({'result': <String, dynamic>{}});+ await tester.pumpAndSettle();++ expect(key('swarm-pending'), findsNothing);+ expect(key('swarm-message-m2'), findsOneWidget);+ expect(find.text('On it'), findsOneWidget);+ });++ testWidgets('a post whose answer was lost says it is not confirmed, and '+ 'Send again sends the same post', (tester) async {+ final fake = backend([message('m1', 1)]);+ var lost = true;+ fake.routes[commands] = (_) => lost+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : {'result': <String, dynamic>{}};+ await pump(tester, fake);++ await tester.enterText(find.byType(TextField), 'On it');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(find.text('Not confirmed'), findsOneWidget);+ expect(key('swarm-resend-post'), findsOneWidget);++ lost = false;+ await tester.tap(key('swarm-resend-post'));+ await tester.pumpAndSettle();++ // The posts sent, not the chat's read marks.+ final receipts = {+ for (final call in fake.calls)+ if (call.method == 'POST' && call.path == commands)+ call.body!['operationId'],+ };+ expect(receipts, hasLength(1));+ expect(find.text('Not confirmed'), findsNothing);+ });++ testWidgets('a refused post says why and puts its text back in the field', (+ tester,+ ) async {+ final fake = backend([message('m1', 1)]);+ fake.routes[commands] = (_) => throw const SuperTabFailure(+ 'TOO_LONG',+ 'This message is too long.',+ statusCode: 400,+ );+ await pump(tester, fake);++ await tester.enterText(find.byType(TextField), 'On it');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(find.text('This message is too long.'), findsOneWidget);+ expect(key('swarm-pending'), findsNothing);+ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ 'On it',+ );+ });++ group('the keyboard', () {+ testWidgets('stays up while a post is on its way and goes down once it '+ 'is taken', (tester) async {+ final fake = backend([message('m1', 1)]);+ final taken = Completer<Object?>();+ fake.routes[commands] = (_) => taken.future;+ await pump(tester, fake);++ await tester.enterText(find.byType(TextField), 'On it');+ await tester.pump();+ expect(composer(tester), up);++ await tester.tap(key('swarm-send'));+ await tester.pump();+ expect(composer(tester), up);++ fake.routes['$messages?after=1'] = (_) => {+ 'messages': [message('m2', 2, author: me, text: 'On it', minute: 5)],+ 'next': null,+ };+ taken.complete({'result': <String, dynamic>{}});+ await tester.pumpAndSettle();++ expect(key('swarm-message-m2'), findsOneWidget);+ expect(composer(tester), down);+ });++ testWidgets('stays up for a refused post, to correct it and send again', (+ tester,+ ) async {+ final fake = backend([message('m1', 1)]);+ fake.routes[commands] = (_) => throw const SuperTabFailure(+ 'TOO_LONG',+ 'This message is too long.',+ statusCode: 400,+ );+ await pump(tester, fake);++ await tester.enterText(find.byType(TextField), 'On it');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(find.text('This message is too long.'), findsOneWidget);+ expect(composer(tester), up);+ });++ testWidgets('stays up for a post not confirmed, and goes down once Send '+ 'again is taken', (tester) async {+ final fake = backend([message('m1', 1)]);+ var lost = true;+ fake.routes[commands] = (_) => lost+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : {'result': <String, dynamic>{}};+ await pump(tester, fake);++ await tester.enterText(find.byType(TextField), 'On it');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(find.text('Not confirmed'), findsOneWidget);+ expect(composer(tester), up);++ lost = false;+ await tester.tap(key('swarm-resend-post'));+ await tester.pumpAndSettle();++ expect(find.text('Not confirmed'), findsNothing);+ expect(composer(tester), down);+ });++ testWidgets('stays up when the next message is typed before the post is '+ 'taken', (tester) async {+ final fake = backend([message('m1', 1)]);+ final taken = Completer<Object?>();+ fake.routes[commands] = (_) => taken.future;+ await pump(tester, fake);++ await tester.enterText(find.byType(TextField), 'On it');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pump();+ await tester.enterText(find.byType(TextField), 'And the');+ await tester.pump();++ taken.complete({'result': <String, dynamic>{}});+ await tester.pumpAndSettle();++ expect(composer(tester), up);+ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ 'And the',+ );+ });+ });++ testWidgets('the header names the chat, with its project under it; an old '+ 'private chat is no Chat with PM any more (#2090)', (tester) async {+ await pump(tester, backend([message('m1', 1)]));+ expect(find.text('Fix login'), findsOneWidget);+ expect(find.text('Mobile'), findsOneWidget);++ await pump(tester, backend([message('m1', 1)], audience: [me]));+ expect(find.text('Chat with PM'), findsNothing);+ expect(find.text('Fix login'), findsOneWidget);+ });++ testWidgets('a divider heads each day, Yesterday above Today', (+ tester,+ ) async {+ final now = DateTime.now();+ await pump(+ tester,+ backend([+ message(+ 'm1',+ 1,+ text: 'From yesterday',+ at: DateTime(now.year, now.month, now.day - 1, 12),+ ),+ message(+ 'm2',+ 2,+ text: 'From today',+ at: DateTime(now.year, now.month, now.day, 0, 30),+ ),+ ]),+ );++ final yesterday = tester.getTopLeft(find.text('Yesterday')).dy;+ final today = tester.getTopLeft(find.text('Today')).dy;+ expect(+ yesterday,+ lessThan(tester.getTopLeft(find.text('From yesterday')).dy),+ );+ expect(+ today,+ greaterThan(tester.getTopLeft(find.text('From yesterday')).dy),+ );+ expect(today, lessThan(tester.getTopLeft(find.text('From today')).dy));+ });++ testWidgets('a decision sits among the messages where it was asked: a card '+ 'with its question, the options side by side', (tester) async {+ await pump(+ tester,+ backend(+ [+ message('m1', 1, text: 'The build is green'),+ message('m2', 2, author: me, text: 'Flag it', minute: 2),+ ],+ decisions: [decision('d1', minute: 1)],+ ),+ );++ final card = tester.getRect(key('swarm-ask-d1'));+ expect(card.top, greaterThan(tester.getRect(key('swarm-message-m1')).top));+ expect(+ card.bottom,+ lessThanOrEqualTo(tester.getRect(key('swarm-message-m2')).top + 1),+ );+ expect(+ find.descendant(of: key('swarm-ask-d1'), matching: find.text('River')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: key('swarm-ask-d1'), matching: find.text('PM')),+ findsOneWidget,+ );+ final first = tester.getRect(key('swarm-option-d1-0'));+ final second = tester.getRect(key('swarm-option-d1-1'));+ expect(first.top, second.top, reason: 'side by side');+ expect(first.right, lessThan(second.left));++ await tester.tap(key('swarm-option-d1-1'));+ await tester.pump();+ expect(find.text('Sending “Everyone”'), findsOneWidget);+ await tester.pump(const Duration(seconds: 10));+ await tester.pumpAndSettle();+ });++ testWidgets('an open decision from before the messages read so far waits at '+ 'the foot, not behind Earlier messages', (tester) async {+ await pump(+ tester,+ backend(+ [+ for (var i = 10; i < 34; i++)+ message('m$i', i, text: 'Line $i\nof the log', minute: i),+ ],+ next: {'sequence': 10, 'id': 'm10'},+ decisions: [decision('d1')],+ ),+ );++ expect(+ tester.getRect(key('swarm-ask-d1')).top,+ greaterThan(tester.getRect(key('swarm-message-m33')).top),+ );+ });++ testWidgets('an @mention of one of the Swarm\'s agents is marked', (+ tester,+ ) async {+ await pump(+ tester,+ backend([message('m1', 1, author: me, text: '@Nova and @nobody, [email protected]')]),+ );++ final text = tester.widget<Text>(+ find.descendant(+ of: key('swarm-message-m1'),+ matching: find.text('@Nova and @nobody, [email protected]'),+ ),+ );+ final marked = <String>[];+ text.textSpan!.visitChildren((span) {+ if (span is TextSpan && span.style?.backgroundColor != null) {+ marked.add(span.text!);+ }+ return true;+ });+ expect(marked, ['@Nova']);+ });++ testWidgets('the field is one rounded line until more is typed; Send is a '+ 'round arrow that waits for text', (tester) async {+ final fake = backend([message('m1', 1)]);+ await pump(tester, fake);++ expect(find.text('Send'), findsNothing);+ expect(+ find.descendant(+ of: key('swarm-send'),+ matching: find.byIcon(LucideIcons.arrowUp),+ ),+ findsOneWidget,+ );+ final field = find.byType(TextField);+ final oneLine = tester.getSize(field).height;+ expect(oneLine, lessThan(30), reason: 'one line, not a box');++ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();+ expect(fake.commands, isEmpty, reason: 'nothing to send yet');++ await tester.enterText(field, 'one\ntwo\nthree');+ await tester.pump();+ expect(tester.getSize(field).height, greaterThan(oneLine * 2));+ });++ testWidgets('a decision asked just after its asker\'s own message is drawn '+ 'as part of it, under one name and time', (tester) async {+ await pump(+ tester,+ backend(+ [+ message(+ 'm1',+ 1,+ author: 'agent-lead',+ text: 'One question before the release:',+ ),+ ],+ decisions: [decision('d1', minute: 1)],+ ),+ );++ expect(find.text('River'), findsOneWidget);+ expect(find.text(time(1)), findsNothing);+ expect(+ tester.getRect(key('swarm-ask-d1')).top,+ greaterThanOrEqualTo(tester.getRect(key('swarm-message-m1')).bottom - 1),+ );+ });++ testWidgets(+ 'on an iPhone the field rests at the 44 of the buttons beside it',+ (tester) async {+ await pump(tester, backend([message('m1', 1)]));++ expect(tester.getSize(key('swarm-field')).height, 44);+ expect(tester.getSize(key('swarm-send')).height, 44);+ },+ variant: TargetPlatformVariant.only(TargetPlatform.iOS),+ );++ testWidgets('a post sent from far up the chat brings the chat back to its '+ 'foot, where the post shows', (tester) async {+ final fake = backend([+ message('m1', 1, author: 'agent-lead', text: 'The very first plan'),+ for (var i = 2; i < 40; i++)+ message('m$i', i, text: 'Line $i\nof the log', minute: i),+ message('m40', 40, author: me, text: 'Yes', replyTo: 'm1', minute: 50),+ ]);+ fake.routes[commands] = (_) => Completer<Object?>().future;+ await pump(tester, fake);+ await tester.tap(key('swarm-quote-m40'));+ await tester.pumpAndSettle();++ await tester.enterText(find.byType(TextField), 'On it');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(inView(tester, key('swarm-pending')), isTrue);+ });++ group('earlier messages', () {+ /// A first page of [count] two-line messages, m[first] onwards, with more+ /// before it.+ FakeSwarm long({int first = 10, int count = 30}) => backend(+ [+ for (var i = first; i < first + count; i++)+ message('m$i', i, text: 'Line $i\nof the log', minute: i % 60),+ ],+ next: {'sequence': first, 'id': 'm$first'},+ );+ final older = '$messages?before=10&beforeId=m10';+ List<Map<String, dynamic>> earlier() => [+ for (var i = 9; i > 0; i--)+ message('m$i', i, text: 'Earlier $i', minute: i),+ ];++ Future<void> nearTop(WidgetTester tester) async {+ // The list runs from the foot: a drag down goes up the chat, here to+ // its top.+ await tester.drag(key('swarm-messages'), const Offset(0, 4000));+ // Past the stretch at the edge, pumped as a settle would be but not+ // settled: the earlier messages being read breathe as skeletons+ // meanwhile.+ for (var i = 0; i < 20; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ testWidgets('are read behind skeleton bubbles, not a line of text', (+ tester,+ ) async {+ final fake = long();+ final page = Completer<Object?>();+ fake.routes[older] = (_) => page.future;+ await pump(tester, fake);++ await nearTop(tester);++ expect(+ find.descendant(+ of: key('swarm-older-loading'),+ matching: key('swarm-skeleton-bubble'),+ ),+ findsWidgets,+ );+ expect(find.text('Loading earlier messages…'), findsNothing);+ page.complete({'messages': earlier(), 'next': null});+ await tester.pumpAndSettle();+ expect(key('swarm-older-loading'), findsNothing);+ });++ testWidgets('are read on their own near the top, with no tap, and what '+ 'is read stays where it is', (tester) async {+ final fake = long();+ final page = Completer<Object?>();+ fake.routes[older] = (_) => page.future;+ await pump(tester, fake);+ expect(fake.paths, isNot(contains(older)), reason: 'not at the top yet');++ await nearTop(tester);+ expect(fake.paths, contains(older));+ expect(key('swarm-older-loading'), findsOneWidget);+ expect(key('swarm-older-messages'), findsNothing);+ final reading = find.text('Line 12\nof the log');+ final before = tester.getRect(reading).top;++ page.complete({'messages': earlier(), 'next': null});+ await tester.pumpAndSettle();++ expect(tester.getRect(reading).top, moreOrLessEquals(before, epsilon: 1));+ expect(key('swarm-message-m9'), findsOneWidget);+ expect(key('swarm-older-loading'), findsNothing);+ });++ testWidgets('that fail to load offer Earlier messages, which reads them '+ 'again', (tester) async {+ final fake = long();+ var down = true;+ fake.routes[older] = (_) => down+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : {'messages': earlier(), 'next': null};+ await pump(tester, fake);++ await nearTop(tester);+ await tester.pumpAndSettle();+ expect(key('swarm-older-messages'), findsOneWidget);+ final reads = fake.paths.where((p) => p == older).length;++ // Not read over and over on its own while it fails.+ await tester.drag(key('swarm-messages'), const Offset(0, -100));+ await nearTop(tester);+ await tester.pumpAndSettle();+ expect(fake.paths.where((p) => p == older), hasLength(reads));++ down = false;+ await tester.tap(key('swarm-older-messages'));+ await tester.pumpAndSettle();+ expect(key('swarm-message-m9'), findsOneWidget);+ expect(key('swarm-older-messages'), findsNothing);+ });++ testWidgets('a first page shorter than the screen reads the one before '+ 'it at once', (tester) async {+ final fake = long(count: 2);+ fake.routes[older] = (_) => {'messages': earlier(), 'next': null};+ await pump(tester, fake);++ expect(fake.paths, contains(older));+ expect(find.text('Earlier 9'), findsOneWidget);+ });++ testWidgets('a read that brings nothing new is not read again on its own', (+ tester,+ ) async {+ final fake = long(count: 2);+ fake.routes[older] = (_) => {+ 'messages': <Object>[],+ 'next': {'sequence': 10, 'id': 'm10'},+ };+ await pump(tester, fake);++ expect(fake.paths.where((p) => p == older), hasLength(1));+ expect(key('swarm-older-messages'), findsOneWidget);+ });+ });++ testWidgets('a Product Manager\'s avatar is the prototype\'s blue; another '+ 'agent\'s is not', (tester) async {+ await pump(+ tester,+ backend([+ message('m1', 1, author: 'agent-lead', text: 'Plan'),+ message('m2', 2, text: 'On it?', minute: 1),+ ]),+ );++ Color fill(String id) {+ final avatar = find.descendant(+ of: key('swarm-message-$id'),+ matching: find.byWidgetPredicate(+ (w) =>+ w is Container &&+ w.decoration is BoxDecoration &&+ (w.decoration! as BoxDecoration).shape == BoxShape.circle,+ ),+ );+ return ((tester.widget<Container>(avatar.first).decoration!+ as BoxDecoration)+ .color)!;+ }++ expect(fill('m1'), const Color(0xFF1D5BD6));+ expect(fill('m2'), isNot(const Color(0xFF1D5BD6)));+ });++ // Tony's iPhone 14, Profile, 44d284f65: the whole chat was built again on+ // each keystroke, and in 25 ms mid-scroll when the 5 s read answered.+ group('reactions', () {+ late List<String> haptics;++ setUp(() {+ haptics = [];+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method == 'HapticFeedback.vibrate') {+ haptics.add(call.arguments as String? ?? call.method);+ }+ return null;+ });+ });+ tearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, null),+ );++ testWidgets('a long-press on a message opens the six with a light tap; '+ 'the pick counts under it at once and goes to the backend', (+ tester,+ ) async {+ final fake = backend([message('m1', 1, text: 'Plan')]);+ final sent = Completer<Object?>();+ fake.routes[commands] = (_) => sent.future;+ fake.routes['$messages?before=2'] = (_) => {+ 'messages': [+ message(+ 'm1',+ 1,+ text: 'Plan',+ reactions: {+ 'tada': [('person', me)],+ },+ ),+ ],+ 'next': null,+ 'reactionSeq': 1,+ };+ await pump(tester, fake);++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();+ expect(haptics, ['HapticFeedbackType.lightImpact']);+ await tester.tap(key('swarm-react-tada'));+ await tester.pumpAndSettle();++ expect(fake.commands.single, {+ 'type': 'message.react',+ 'conversationId': 'g1',+ 'messageId': 'm1',+ 'emoji': 'tada',+ 'on': true,+ });+ expect(+ find.descendant(+ of: key('swarm-reaction-m1-tada'),+ matching: find.text('1'),+ ),+ findsOneWidget,+ reason: 'counted before the backend answers',+ );+ sent.complete({'result': <String, dynamic>{}});+ await tester.pumpAndSettle();+ expect(key('swarm-reaction-m1-tada'), findsOneWidget);+ });++ testWidgets('a tap on your own count takes it back', (tester) async {+ final fake = backend([+ message(+ 'm1',+ 1,+ reactions: {+ 'heart': [('person', me), ('agent', 'agent-lead')],+ },+ ),+ ]);+ fake.routes['$messages?before=2'] = (_) => {+ 'messages': [+ message(+ 'm1',+ 1,+ reactions: {+ 'heart': [('agent', 'agent-lead')],+ },+ ),+ ],+ 'next': null,+ 'reactionSeq': 2,+ };+ await pump(tester, fake);++ await tester.tap(key('swarm-reaction-m1-heart'));+ await tester.pumpAndSettle();++ expect(fake.commands.single['on'], isFalse);+ expect(+ find.descendant(+ of: key('swarm-reaction-m1-heart'),+ matching: find.text('1'),+ ),+ findsOneWidget,+ );+ });++ testWidgets('holding a count names who gave it, never by email', (+ tester,+ ) async {+ await pump(+ tester,+ backend(+ [+ message(+ 'm1',+ 1,+ reactions: {+ 'eyes': [+ ('agent', 'agent-lead'),+ ('person', 'person-ann'),+ ('person', me),+ ],+ },+ ),+ ],+ members: [+ person(me),+ person('person-ann', role: 'collaborator'),+ ],+ ),+ );++ await tester.longPress(key('swarm-reaction-m1-eyes'));+ await tester.pump();++ expect(find.text('River, person-ann and You'), findsOneWidget);+ expect(find.textContaining('@example.com'), findsNothing);+ expect(key('swarm-react-eyes'), findsNothing, reason: 'no picker');+ await tester.pumpAndSettle(const Duration(seconds: 3));+ });++ testWidgets('a person who cannot post sees the counts; neither a tap nor '+ 'a long-press reacts', (tester) async {+ final fake = backend(+ [+ message(+ 'm1',+ 1,+ text: 'Plan',+ reactions: {+ 'rocket': [('agent', 'agent-lead')],+ },+ ),+ ],+ members: [person(me, role: 'viewer')],+ );+ await pump(tester, fake);++ await tester.tap(key('swarm-reaction-m1-rocket'));+ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();++ expect(key('swarm-reaction-m1-rocket'), findsOneWidget);+ expect(key('swarm-react-rocket'), findsNothing);+ expect(fake.commands, isEmpty);+ });+ });++ group('drawn again', () {+ List<Map<String, dynamic>> page() => [+ message('m1', 1, author: 'agent-lead', text: 'The plan'),+ message('m2', 2, text: 'On it @River', minute: 1),+ message('m3', 3, author: me, text: 'Thanks', replyTo: 'm1', minute: 2),+ ];++ testWidgets('a keystroke: the composer, and no message', (tester) async {+ final fake = backend(page());+ fake.routes[commands] = (_) => Completer<Object?>().future;+ await pump(tester, fake);++ final built = await rowsBuilt(() async {+ await tester.enterText(find.byType(TextField), 'S');+ await tester.pump();+ await tester.enterText(find.byType(TextField), 'Sh');+ await tester.pump();+ });++ expect(built, isEmpty);+ // The composer did follow the typing: Send posts what was typed.+ await tester.tap(key('swarm-send'));+ await tester.pump();+ expect(+ find.descendant(of: key('swarm-pending'), matching: find.text('Sh')),+ findsOneWidget,+ );+ });++ testWidgets('a read of the Swarm that changes nothing in this chat: no '+ 'message', (tester) async {+ final fake = backend(page());+ final host = await pump(tester, fake);+ // The Lead's chat moved on: the Swarm, its asks and the inbox all+ // say so, and nothing this chat draws changed.+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ lastChangedAt: 200,+ derived: {'decisionsWaiting': 0},+ groups: [+ part(+ leadChat,+ 9,+ groupData(+ leadChat,+ title: 'Mobile',+ agentIds: ['agent-lead'],+ leadId: 'agent-lead',+ status: 'working',+ ),+ ),+ ],+ );++ final built = await rowsBuilt(() async {+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();+ });++ expect(built, isEmpty);+ expect(find.text('On it @River'), findsOneWidget);+ });++ /// The read marks sent for g1, in order.+ List<Object?> marksSent(FakeSwarm fake) => [+ for (final call in fake.calls)+ if (call.method == 'POST' &&+ call.path == '/api/super-tabs/$tab/conversations/g1/read')+ call.body?['sequence'],+ ];++ /// Whether g1 reads as unread on the phone.+ bool unread(SwarmHost host) {+ final reader = host.session!.inbox.reader(tab)!;+ return reader.readMarks!.unread(reader.snapshot!.conversation('g1')!);+ }++ /// g1 moved on to [sequence], as the Swarm's next read says.+ void movedOn(FakeSwarm fake, int sequence) =>+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ lastChangedAt: 200,+ derived: {'decisionsWaiting': 0},+ groups: [+ part(+ 'g1',+ 9,+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ lastMessageSequence: sequence,+ ),+ ),+ ],+ );++ testWidgets('a reaction: its own row alone', (tester) async {+ final fake = backend(page());+ fake.routes['$messages?before=4'] = (_) => {+ 'messages': [+ for (final row in page().reversed)+ if (row['id'] == 'm2')+ message(+ 'm2',+ 2,+ text: 'On it @River',+ minute: 1,+ reactions: {+ 'thumbs_up': [('person', me)],+ },+ )+ else+ row,+ ],+ 'next': null,+ 'reactionSeq': 1,+ };+ await pump(tester, fake);++ final reacted = await rowsBuilt(() async {+ await tester.longPress(find.text('On it @River'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-react-thumbs_up'));+ await tester.pumpAndSettle();+ });++ expect(reacted.toSet(), {'m2'});+ expect(key('swarm-reaction-m2-thumbs_up'), findsOneWidget);+ });++ testWidgets('a new message at the foot: its own row alone, at once', (+ tester,+ ) async {+ final fake = backend(page());+ final host = await pump(tester, fake);+ movedOn(fake, 4);+ fake.routes['$messages?after=3'] = (_) => {+ 'messages': [message('m4', 4, text: 'Fresh news', minute: 3)],+ 'next': null,+ };++ final built = await rowsBuilt(() async {+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();+ });++ expect(built, ['m4']);+ expect(inView(tester, find.text('Fresh news')), isTrue);+ expect(key('swarm-new-pill'), findsNothing);+ });++ testWidgets('only the row a quote leads to is lit, and fades', (+ tester,+ ) async {+ await pump(tester, backend(page()));+ final fading = find.descendant(+ of: key('swarm-messages'),+ matching: find.byType(AnimatedContainer),+ );+ expect(fading, findsNothing);++ await tester.tap(key('swarm-quote-m3'));+ await tester.pumpAndSettle();++ expect(key('swarm-lit-m1'), findsOneWidget);+ expect(fading, findsOneWidget);+ expect(+ find.descendant(of: key('swarm-message-m1'), matching: fading),+ findsNothing,+ reason: 'the lit row is the animated one itself',+ );+ expect(tester.widget(fading).key, const ValueKey('swarm-message-m1'));+ });++ testWidgets('a message arriving while the person reads back keeps what '+ 'they read in place, and says how many wait below; the pill goes '+ 'to them', (tester) async {+ final fake = backend([+ for (var i = 1; i < 40; i++)+ message('m$i', i, text: 'Line $i\nof the log', minute: i),+ ]);+ final host = await pump(tester, fake);+ await tester.drag(key('swarm-messages'), const Offset(0, 300));+ await tester.pumpAndSettle();+ final reading = [+ for (var i = 39; i > 0; i--) key('swarm-message-m$i'),+ ].firstWhere((row) => row.evaluate().isNotEmpty && inView(tester, row));+ final before = tester.getRect(reading).top;++ movedOn(fake, 40);+ fake.routes['$messages?after=39'] = (_) => {+ 'messages': [message('m40', 40, text: 'Fresh news', minute: 45)],+ 'next': null,+ };+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(tester.getRect(reading).top, moreOrLessEquals(before, epsilon: 1));+ expect(+ find.descendant(+ of: key('swarm-new-pill'),+ matching: find.text('1 new'),+ ),+ findsOneWidget,+ );++ // Waiting below, it is not read: no mark goes past what they saw.+ expect(marksSent(fake), everyElement(lessThan(40)));+ expect(unread(host), isTrue);++ await tester.tap(key('swarm-new-pill'));+ await tester.pumpAndSettle();++ expect(inView(tester, find.text('Fresh news')), isTrue);+ expect(key('swarm-new-pill'), findsNothing);+ expect(marksSent(fake).last, 40, reason: 'shown now, so read');+ expect(unread(host), isFalse);+ });++ testWidgets('a message left waiting below stays unread when the chat '+ 'opens again from what it kept, at an earlier message', (tester) async {+ final fake = backend([+ for (var i = 1; i < 40; i++)+ message('m$i', i, text: 'Line $i\nof the log', minute: i),+ ]);+ final host = await pump(tester, fake);+ await tester.drag(key('swarm-messages'), const Offset(0, 300));+ await tester.pumpAndSettle();+ movedOn(fake, 40);+ fake.routes['$messages?after=39'] = (_) => {+ 'messages': [message('m40', 40, text: 'Fresh news', minute: 45)],+ 'next': null,+ };+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();+ expect(marksSent(fake), everyElement(lessThan(40)));++ // Closed with 40 unseen; the chat keeps what it read.+ await tester.pumpWidget(const SizedBox());+ await tester.pumpAndSettle();+ expect(SwarmChatCache.length, greaterThan(0));+ // A notice opens it again at its first message.+ await show(tester, host, messageId: 'm1');++ expect(inView(tester, find.text('Line 1\nof the log')), isTrue);+ expect(marksSent(fake), everyElement(lessThan(40)));+ expect(unread(host), isTrue);+ });++ testWidgets('a message that arrives while Harness is behind is read only '+ 'once Harness is in front again', (tester) async {+ final fake = backend([message('m1', 1, text: 'The plan', minute: 1)]);+ final host = await pump(tester, fake);+ // The app's states, one step at a time, as the platform moves them.+ void go(List<AppLifecycleState> states) {+ for (final state in states) {+ tester.binding.handleAppLifecycleStateChanged(state);+ }+ }++ const behind = [+ AppLifecycleState.inactive,+ AppLifecycleState.hidden,+ AppLifecycleState.paused,+ ];+ const front = [+ AppLifecycleState.hidden,+ AppLifecycleState.inactive,+ AppLifecycleState.resumed,+ ];+ addTearDown(() {+ if (tester.binding.lifecycleState == AppLifecycleState.paused) {+ go(front);+ }+ });++ go(behind);+ movedOn(fake, 2);+ fake.routes['$messages?after=1'] = (_) => {+ 'messages': [message('m2', 2, text: 'Fresh news', minute: 2)],+ 'next': null,+ };+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ // Behind, no frame is drawn, but the chat reads the message all the+ // same: it is not seen.+ expect(marksSent(fake), everyElement(lessThan(2)));+ expect(unread(host), isTrue);++ go(front);+ await tester.pumpAndSettle();++ expect(marksSent(fake).last, 2);+ expect(unread(host), isFalse);+ });+ });++ group('while it loads', () {+ const parts = '/api/super-tabs/$tab/parts';+ const notOpen = 'This chat is not open to you.';++ /// Skeleton bubbles fill the chat: six to eight of them.+ void skeleton(WidgetTester tester) {+ expect(key('swarm-chat-skeleton'), findsOneWidget);+ expect(+ tester.widgetList(key('swarm-skeleton-bubble')).length,+ inInclusiveRange(6, 8),+ );+ }++ testWidgets('the first page shows skeleton bubbles, and nothing says the '+ 'chat is empty or not open', (tester) async {+ final fake = backend([message('m1', 1, text: 'The plan')]);+ final page = Completer<Object?>();+ fake.routes[messages] = (_) => page.future;++ await pump(tester, fake, settle: false);++ skeleton(tester);+ expect(find.text(notOpen), findsNothing);+ expect(find.text('No messages yet.'), findsNothing);++ page.complete({+ 'messages': [message('m1', 1, text: 'The plan')],+ 'next': null,+ });+ await tester.pumpAndSettle();+ expect(find.text('The plan'), findsOneWidget);+ expect(key('swarm-chat-skeleton'), findsNothing);+ });++ testWidgets('before the account\'s Swarms are read, the chat is a '+ 'skeleton under a placeholder header', (tester) async {+ final fake = backend([message('m1', 1)]);+ final list = Completer<Object?>();+ final listed = fake.routes['/api/super-tabs/list']!;+ fake.routes['/api/super-tabs/list'] = (_) => list.future;++ await pump(tester, fake, settle: false);++ skeleton(tester);+ expect(key('swarm-header-placeholder'), findsOneWidget);+ expect(find.text(notOpen), findsNothing);++ list.complete(listed(null));+ await tester.pumpAndSettle();+ expect(find.text('Fix login'), findsOneWidget);+ expect(key('swarm-header-placeholder'), findsNothing);+ });++ testWidgets('before its Swarm is read, the header is a placeholder of the '+ 'same height and nothing says the chat is not open', (tester) async {+ final fake = backend([message('m1', 1, text: 'The plan')]);+ final swarm = Completer<Object?>(), page = Completer<Object?>();+ final read = fake.routes[parts]!;+ fake.routes[parts] = (_) => swarm.future;+ fake.routes[messages] = (_) => page.future;++ await pump(tester, fake, settle: false);++ skeleton(tester);+ expect(key('swarm-header-placeholder'), findsOneWidget);+ expect(find.text(notOpen), findsNothing);+ expect(find.text('Chat'), findsNothing);+ final height = tester.getSize(key('swarm-chat-header')).height;++ swarm.complete(read(null));+ page.complete({+ 'messages': [message('m1', 1, text: 'The plan')],+ 'next': null,+ });+ await tester.pumpAndSettle();+ expect(find.text('Fix login'), findsOneWidget);+ expect(find.text('The plan'), findsOneWidget);+ expect(tester.getSize(key('swarm-chat-header')).height, height);+ });++ testWidgets('a chat looked for by id is a skeleton until the lookup '+ 'refuses it; only then is it not open', (tester) async {+ final fake = backend([]);+ final lookup = Completer<Object?>(), page = Completer<Object?>();+ fake.routes['/api/super-tabs/$tab/groups/g9'] = (_) => lookup.future;+ fake.routes['/api/super-tabs/$tab/conversations/g9/messages'] = (_) =>+ page.future;++ await pump(tester, fake, conversation: 'g9', settle: false);++ expect(fake.paths, contains('/api/super-tabs/$tab/groups/g9'));+ skeleton(tester);+ expect(find.text(notOpen), findsNothing);++ lookup.completeError(+ const SuperTabFailure('FORBIDDEN', 'Not yours.', statusCode: 403),+ );+ await frames(tester);+ expect(find.text(notOpen), findsOneWidget);+ expect(key('swarm-chat-skeleton'), findsNothing);+ expect(key('swarm-header-placeholder'), findsNothing);++ page.completeError(+ const SuperTabFailure('FORBIDDEN', 'Not yours.', statusCode: 403),+ );+ await tester.pumpAndSettle();+ expect(find.text(notOpen), findsOneWidget);+ });++ testWidgets('a chat with no message yet says so', (tester) async {+ await pump(tester, backend([]));++ expect(find.text('No messages yet.'), findsOneWidget);+ expect(key('swarm-chat-skeleton'), findsNothing);+ expect(find.text(notOpen), findsNothing);+ });+ });++ group('opened again', () {+ const parts = '/api/super-tabs/$tab/parts';++ FakeSwarm read() => backend([+ message('m1', 1, author: 'agent-lead', text: 'The plan'),+ message('m2', 2, text: 'On it'),+ ]);++ /// The chat closed, its Swarm still read.+ Future<void> close(WidgetTester tester) =>+ tester.pumpWidget(const SizedBox());++ testWidgets('shows at once what was read, then reads only what is newer', (+ tester,+ ) async {+ final fake = read();+ final host = await pump(tester, fake);+ await close(tester);+ final newer = Completer<Object?>();+ fake.routes['$messages?after=2'] = (_) => newer.future;++ await show(tester, host, settle: false);++ expect(find.text('The plan'), findsOneWidget);+ expect(find.text('On it'), findsOneWidget);+ expect(key('swarm-chat-skeleton'), findsNothing);+ expect(+ fake.paths.where((p) => p.startsWith(messages)).last,+ '$messages?after=2',+ );++ newer.complete({+ 'messages': [message('m3', 3, text: 'Done')],+ 'next': null,+ });+ await tester.pumpAndSettle();+ expect(find.text('Done'), findsOneWidget);+ });++ testWidgets('signing out forgets every chat kept', (tester) async {+ final fake = read();+ final host = await pump(tester, fake);+ await close(tester);+ expect(SwarmChatCache.length, 1);++ account.value = null;++ expect(SwarmChatCache.length, 0);+ account.value = me;+ fake.calls.clear();+ // Harness is behind in these tests: the new session's Swarms are read+ // here.+ await host.session!.inbox.refresh();+ await show(tester, host);+ expect(fake.paths, contains(messages));+ expect(+ fake.paths.where((p) => p.startsWith('$messages?after=')),+ isEmpty,+ reason: 'read from the start, as a first open',+ );+ });++ testWidgets('turning Swarm off forgets every chat kept', (tester) async {+ final host = await pump(tester, read());+ await close(tester);+ expect(SwarmChatCache.length, 1);++ features.value = {};++ expect(host.session, isNull);+ expect(SwarmChatCache.length, 0);+ });++ testWidgets('a chat the person can no longer read is forgotten, open or '+ 'closed', (tester) async {+ final fake = read();+ final host = await pump(tester, fake);+ await close(tester);+ expect(SwarmChatCache.length, 1);+ final reader = host.session!.inbox.reader(tab)!;++ // Closed: taken out of g1, the Swarm is read again without it.+ final full = fake.routes[parts]!(null)! as Map;+ void leaveOut() {+ fake.routes[parts] = (_) => {+ ...full,+ 'groups': [+ for (final g in full['groups'] as List)+ if ((g as Map)['key'] != 'g1') g,+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ }++ leaveOut();+ await reader.refresh();+ expect(SwarmChatCache.length, 0);++ await show(tester, host);+ expect(find.text('The plan'), findsNothing);+ expect(find.text('This chat is not open to you.'), findsOneWidget);+ await close(tester);+ expect(SwarmChatCache.length, 0);++ // Open: kept from before, then taken out while on screen.+ fake.routes[parts] = (_) => full;+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ await reader.refresh();+ await show(tester, host);+ await close(tester);+ expect(SwarmChatCache.length, 1);+ await show(tester, host);+ expect(find.text('The plan'), findsOneWidget);++ leaveOut();+ await reader.refresh();+ await tester.pumpAndSettle();++ expect(find.text('The plan'), findsNothing);+ expect(find.text('This chat is not open to you.'), findsOneWidget);+ expect(SwarmChatCache.length, 0);+ await close(tester);+ expect(SwarmChatCache.length, 0);+ });+ });++ group('a day divider says', () {+ final now = DateTime(2026, 10, 27, 9, 30);++ test('Today and Yesterday, whatever the hour', () {+ expect(swarmDayLabel(DateTime(2026, 10, 27, 0, 1), now), 'Today');+ expect(swarmDayLabel(DateTime(2026, 10, 27, 23, 59), now), 'Today');+ expect(swarmDayLabel(DateTime(2026, 10, 26, 23, 59), now), 'Yesterday');+ });++ test('the weekday within the week, then the date', () {+ expect(swarmDayLabel(DateTime(2026, 10, 25), now), 'Sunday');+ expect(swarmDayLabel(DateTime(2026, 10, 21), now), 'Wednesday');+ expect(swarmDayLabel(DateTime(2026, 10, 20), now), '20 Oct');+ expect(swarmDayLabel(DateTime(2025, 12, 31), now), '31 Dec 2025');+ });++ test('a day across a clock change is still one day', () {+ // 25 March 2029 is 23 hours long where the clocks go forward then.+ expect(+ swarmDayLabel(DateTime(2029, 3, 25, 12), DateTime(2029, 3, 26, 1)),+ 'Yesterday',+ );+ });++ test('a date ahead of the phone\'s clock is a date', () {+ expect(swarmDayLabel(DateTime(2026, 10, 28), now), '28 Oct');+ });+ });++ group('attaching files', () {+ final picker = (+ photos: pickSwarmPhotos,+ camera: takeSwarmPhoto,+ documents: pickSwarmFiles,+ settings: openSwarmSettings,+ copies: swarmPickerCopyFolders,+ );+ // No plugin answers in a widget test: the pickers' copies here are in memory.+ setUp(() => swarmPickerCopyFolders = () async => const []);+ tearDown(() {+ swarmPickerCopyFolders = picker.copies;+ pickSwarmPhotos = picker.photos;+ takeSwarmPhoto = picker.camera;+ pickSwarmFiles = picker.documents;+ openSwarmSettings = picker.settings;+ });++ /// A picker's file held in memory, named as on a phone: by its path.+ XFile picked(String name, int size) => XFile.fromData(+ Uint8List(size),+ path: '/picker-copies/$name',+ length: size,+ );++ /// Uploads the test answers: each held until [answer] completes it.+ final uploads =+ <+ ({+ String name,+ void Function(double) progress,+ Completer<Map<String, dynamic>> answer,+ })+ >[];+ setUp(uploads.clear);+ Future<Map<String, dynamic>> held({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required dynamic cancel,+ required void Function(double sent) onProgress,+ }) {+ final answer = Completer<Map<String, dynamic>>();+ uploads.add((name: name, progress: onProgress, answer: answer));+ return answer.future;+ }++ Map<String, dynamic> attachment(String id) => {+ 'attachment': {+ 'id': id,+ 'name': 'x',+ 'mime': 'image/jpeg',+ 'size': 1,+ 'url': 'https://cdn.harness.autonomous.ai/$id/x',+ },+ };++ Future<void> attach(WidgetTester tester, String row) async {+ await tester.tap(key('swarm-attach'));+ await tester.pumpAndSettle();+ await tester.tap(key(row));+ await tester.pumpAndSettle();+ }++ testWidgets('+ opens a sheet with Photo library, Camera and Files', (+ tester,+ ) async {+ await pump(tester, backend([message('m1', 1)]));++ await tester.tap(key('swarm-attach'));+ await tester.pumpAndSettle();++ expect(find.text('Photo library'), findsOneWidget);+ expect(find.text('Camera'), findsOneWidget);+ expect(find.text('Files'), findsOneWidget);+ for (final row in ['library', 'camera', 'files']) {+ expect(+ tester.getSize(key('swarm-attach-$row')).height,+ greaterThanOrEqualTo(44),+ );+ }+ });++ testWidgets('the sheet rounds at the theme\'s sheet radius', (+ tester,+ ) async {+ await pump(tester, backend([message('m1', 1)]));++ await tester.tap(key('swarm-attach'));+ await tester.pumpAndSettle();++ expect(sheetTopRadius(tester), grid.AppControl.sheetRadius);+ });++ testWidgets('photos picked show as chips with their size; ✕ takes one '+ 'off before sending', (tester) async {+ pickSwarmPhotos = (limit) async => [+ picked('a.jpg', 2 * 1024 * 1024),+ picked('b.jpg', 4 * 1024),+ ];+ await pump(tester, backend([message('m1', 1)]));++ await attach(tester, 'swarm-attach-library');++ expect(key('swarm-outgoing-photo.jpg'), findsOneWidget);+ expect(key('swarm-outgoing-photo-2.jpg'), findsOneWidget);+ expect(find.text('2.0 MB'), findsOneWidget);+ expect(find.text('4 KB'), findsOneWidget);++ await tester.tap(key('swarm-outgoing-remove-photo.jpg'));+ await tester.pump();++ expect(key('swarm-outgoing-photo.jpg'), findsNothing);+ expect(key('swarm-outgoing-photo-2.jpg'), findsOneWidget);+ });++ testWidgets('Send with files and no text uploads them, shows each one\'s '+ 'progress, then posts them', (tester) async {+ pickSwarmFiles = () async => [picked('crash.log', 12)];+ final fake = backend([message('m1', 1)]);+ await pump(tester, fake, upload: held);++ await attach(tester, 'swarm-attach-files');+ await tester.tap(key('swarm-send'));+ await tester.pump();++ expect(uploads.single.name, 'crash.log');+ uploads.single.progress(0.6);+ await tester.pump();+ expect(find.text('60%'), findsOneWidget);++ uploads.single.answer.complete(attachment('f1'));+ await tester.pumpAndSettle();++ expect(fake.commands.single['attachmentIds'], ['f1']);+ expect(key('swarm-outgoing-crash.log'), findsNothing);+ });++ testWidgets('the keyboard stays up while the files go up and goes down '+ 'once they are posted', (tester) async {+ pickSwarmFiles = () async => [picked('crash.log', 12)];+ final fake = backend([message('m1', 1)]);+ await pump(tester, fake, upload: held);++ await attach(tester, 'swarm-attach-files');+ await tester.enterText(find.byType(TextField), 'The log');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pump();++ expect(uploads.single.name, 'crash.log');+ expect(composer(tester), up);++ uploads.single.answer.complete(attachment('f1'));+ await tester.pumpAndSettle();++ expect(fake.commands.single['attachmentIds'], ['f1']);+ expect(composer(tester), down);+ });++ testWidgets('the keyboard stays up when the files could not go up', (+ tester,+ ) async {+ pickSwarmFiles = () async => [picked('crash.log', 12)];+ final fake = backend([message('m1', 1)]);+ await pump(tester, fake, upload: held);++ await attach(tester, 'swarm-attach-files');+ await tester.enterText(find.byType(TextField), 'The log');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pump();+ uploads.single.answer.completeError(+ const SuperTabFailure(+ 'UPLOAD_FAILED',+ 'Could not upload the file. Try again.',+ ),+ );+ await tester.pumpAndSettle();++ expect(+ find.text('Could not upload the file. Try again.'),+ findsOneWidget,+ );+ expect(composer(tester), up);+ });++ testWidgets('a post of files alone shows them while it is sent', (+ tester,+ ) async {+ pickSwarmFiles = () async => [picked('crash.log', 12)];+ final fake = backend([message('m1', 1)]);+ fake.routes[commands] = (_) => Completer<Object?>().future;+ await pump(tester, fake, upload: held);++ await attach(tester, 'swarm-attach-files');+ await tester.tap(key('swarm-send'));+ await tester.pump();+ uploads.single.answer.complete(attachment('f1'));+ await tester.pump();+ await tester.pump();++ expect(+ find.descendant(+ of: key('swarm-pending'),+ matching: find.textContaining('crash.log'),+ ),+ findsOneWidget,+ );+ });++ testWidgets('a refused upload says why and keeps the files', (+ tester,+ ) async {+ pickSwarmFiles = () async => [picked('crash.log', 12)];+ final fake = backend([message('m1', 1)]);+ await pump(tester, fake, upload: held);++ await attach(tester, 'swarm-attach-files');+ await tester.tap(key('swarm-send'));+ await tester.pump();+ uploads.single.answer.completeError(+ const SuperTabFailure(+ 'UPLOAD_FAILED',+ 'Could not upload the file. Try again.',+ ),+ );+ await tester.pumpAndSettle();++ expect(+ find.text('Could not upload the file. Try again.'),+ findsOneWidget,+ );+ expect(key('swarm-outgoing-crash.log'), findsOneWidget);+ expect(fake.commands, isEmpty);+ });++ testWidgets('a file over 10 MB is named under the files', (tester) async {+ pickSwarmFiles = () async => [+ picked('big.zip', 10 * 1024 * 1024 + 1),+ picked('ok.txt', 3),+ ];+ await pump(tester, backend([message('m1', 1)]));++ await attach(tester, 'swarm-attach-files');++ expect(find.text('big.zip is over 10 MB.'), findsOneWidget);+ expect(key('swarm-outgoing-ok.txt'), findsOneWidget);+ });++ testWidgets('camera access turned off offers Settings', (tester) async {+ takeSwarmPhoto = () async =>+ throw PlatformException(code: 'camera_access_denied');+ var opened = 0;+ openSwarmSettings = () async {+ opened++;+ return true;+ };+ await pump(tester, backend([message('m1', 1)]));++ await attach(tester, 'swarm-attach-camera');++ expect(find.text('Camera access is off'), findsOneWidget);+ await tester.tap(find.text('Open Settings'));+ await tester.pumpAndSettle();++ expect(opened, 1);+ expect(find.text('Camera access is off'), findsNothing);+ });++ testWidgets('Not now closes the camera box without Settings', (+ tester,+ ) async {+ takeSwarmPhoto = () async =>+ throw PlatformException(code: 'camera_access_denied');+ var opened = 0;+ openSwarmSettings = () async {+ opened++;+ return true;+ };+ await pump(tester, backend([message('m1', 1)]));++ await attach(tester, 'swarm-attach-camera');+ await tester.tap(find.text('Not now'));+ await tester.pumpAndSettle();++ expect(opened, 0);+ expect(find.text('Camera access is off'), findsNothing);+ });++ testWidgets('a person who cannot post has no attach button', (+ tester,+ ) async {+ await pump(+ tester,+ backend([message('m1', 1)], members: [person(me, role: 'viewer')]),+ );++ expect(key('swarm-read-only'), findsOneWidget);+ expect(key('swarm-attach'), findsNothing);+ });+ });+}diff --git a/mobile/test/swarm/swarm_chat_voice_test.dart b/mobile/test/swarm/swarm_chat_voice_test.dartnew file mode 100644index 000000000..64c8ec0f6--- /dev/null+++ b/mobile/test/swarm/swarm_chat_voice_test.dart@@ -0,0 +1,704 @@+import 'dart:async';++import 'package:flutter/foundation.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/voice_input_controller.dart';+import 'package:harness_mobile/phone/voice_mic_face.dart';+import 'package:harness_mobile/phone/voice_recorder.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+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';++/// Talking instead of typing in a Swarm chat (Tony, 10-28), where the phone+/// has no speech recognizer of its own to use: the terminal's mic in the+/// composer records, and what the backend hears lands in the message box as+/// the take ends; a second tap on the mic stops and sends what is in the box,+/// and nothing but its 5-minute limit ends a take before that (Tony, 10-29). A+/// long press on the mic picks the language. With the phone's recognizer:+/// `swarm_chat_dictation_test`.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const commands = '/api/super-tabs/$tab/commands';++ late FakeSwarm fake;+ late _MeteredRecorder recorder;+ late FakeTranscriber stt;++ setUp(() {+ recorder = _MeteredRecorder();+ stt = FakeTranscriber();+ fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 1,+ ),+ ],+ );+ 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': 'm1',+ 'conversationId': 'g1',+ 'text': 'Which build should I ship?',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 10, 28, 1).toIso8601String(),+ },+ ],+ 'next': null,+ };+ fake.routes[commands] = (_) => {'result': <String, dynamic>{}};+ });++ /// Chat g1 on screen, its composer's mic heard through [recorder] and+ /// [stt] — or with no voice input at all.+ Future<void> pump(WidgetTester tester, {bool voice = true}) async {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ voice: voice+ ? () => VoiceInputController(+ transcriber: stt.call,+ recorder: recorder,+ language: ValueNotifier('en'),+ )+ : null,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ ),+ );+ await tester.pumpAndSettle();+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ /// A few frames, for the take's awaits to land. Never settling: the mic's+ /// bars move for as long as it listens.+ Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 5; i++) {+ await tester.pump();+ }+ }++ Future<void> tapMic(WidgetTester tester) async {+ await tester.tap(key('swarm-mic'));+ await frames(tester);+ }++ String box(WidgetTester tester) =>+ tester.widget<TextField>(find.byType(TextField)).controller!.text;++ testWidgets('a second tap stops the take and sends what it heard', (+ tester,+ ) async {+ await pump(tester);+ stt.replies.add('ship the fix today');++ await tapMic(tester);+ expect(recorder.recording, isTrue);+ expect(+ tester.widget<VoiceMicCore>(find.byType(VoiceMicCore)).face,+ VoiceMicFace.listening,+ reason: 'the terminal\'s listening face, its bars moving with the voice',+ );++ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(recorder.recording, isFalse);+ expect(fake.commands.single['text'], 'ship the fix today');+ expect(box(tester), isEmpty);+ });++ testWidgets('what was typed goes with what is said, on the second tap', (+ tester,+ ) async {+ await pump(tester);+ await tester.enterText(find.byType(TextField), 'Nova:');+ await tester.pump();+ stt.replies.add('ship the fix');++ await tapMic(tester);+ await tapMic(tester);+ await tester.pumpAndSettle();++ expect(fake.commands.single['text'], 'Nova: ship the fix');+ expect(box(tester), isEmpty);+ });++ testWidgets('a second tap with nothing in the box sends nothing', (+ tester,+ ) async {+ await pump(tester);++ await tapMic(tester);+ await tapMic(tester);+ await tester.pumpAndSettle();++ expect(recorder.recording, isFalse);+ expect(box(tester), isEmpty);+ expect(fake.commands, isEmpty);+ expect(find.text("Didn't catch that · tap the mic again"), findsOneWidget);+ });++ // Tony, 10-29: "listening continues until I tap".+ testWidgets('a pause after speaking does not end the take: it records until '+ 'the tap, which sends', (tester) async {+ await pump(tester);+ stt.replies.add('looks good');++ await tapMic(tester);+ recorder.meter.value = 0.8;+ await tester.pump(const Duration(milliseconds: 500));+ recorder.meter.value = 0.02;+ await tester.pump(const Duration(seconds: 30));+ expect(recorder.recording, isTrue);+ expect(fake.commands, isEmpty);++ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'looks good');+ });++ testWidgets('the take runs on through quiet before anything is said, and '+ 'through a short pause', (tester) async {+ await pump(tester);++ await tapMic(tester);+ recorder.meter.value = 0.02;+ await tester.pump(const Duration(seconds: 10));+ expect(recorder.recording, isTrue, reason: 'nothing said yet');++ recorder.meter.value = 0.8;+ await tester.pump(const Duration(milliseconds: 500));+ recorder.meter.value = 0.02;+ await tester.pump(const Duration(seconds: 2));+ recorder.meter.value = 0.8;+ await tester.pump(const Duration(milliseconds: 500));+ recorder.meter.value = 0.02;+ await tester.pump(const Duration(seconds: 2));+ expect(recorder.recording, isTrue, reason: 'talking again restarts it');+ });++ testWidgets('a tap while the microphone is opening calls the take off', (+ tester,+ ) async {+ recorder.pendingPermission = Completer();+ await pump(tester);++ await tapMic(tester);+ await tapMic(tester);+ recorder.pendingPermission!.complete(true);+ await frames(tester);++ expect(recorder.starts, 0);+ expect(find.byType(VoiceMicCore), findsNothing, reason: 'back at rest');+ });++ testWidgets('a refused microphone says so, and records nothing', (+ tester,+ ) async {+ recorder.permitted = false;+ await pump(tester);++ await tapMic(tester);++ expect(recorder.starts, 0);+ expect(find.text('No mic access · allow it in Settings'), findsOneWidget);+ });++ testWidgets('a take that is not heard says so, and leaves the box as it '+ 'was', (tester) async {+ await pump(tester);+ await tester.enterText(find.byType(TextField), 'Draft');+ await tester.pump();+ stt.fails = true;++ await tapMic(tester);+ await tapMic(tester);++ expect(box(tester), 'Draft');+ expect(+ find.text("Couldn't transcribe · tap the mic again"),+ findsOneWidget,+ );+ expect(fake.commands, isEmpty);+ });++ testWidgets('a long press on the mic opens the voice language list', (+ tester,+ ) async {+ await pump(tester);++ await tester.longPress(key('swarm-mic'));+ await tester.pumpAndSettle();++ expect(find.text('Voice input language'), findsOneWidget);+ expect(find.text('Tiếng Việt'), findsOneWidget);+ expect(recorder.starts, 0, reason: 'a long press records nothing');+ // Put away without choosing: a choice writes the real preferences file.+ });++ testWidgets('VoiceOver can talk, finish and choose the language', (+ tester,+ ) async {+ final semantics = tester.ensureSemantics();+ await pump(tester);+ stt.replies.add('on my way');++ expect(+ tester.getSemantics(key('swarm-mic')),+ matchesSemantics(+ label: 'Talk',+ isButton: true,+ hasEnabledState: true,+ isEnabled: true,+ hasTapAction: true,+ hasLongPressAction: true,+ onLongPressHint: 'Choose language',+ ),+ );++ tester.semantics.tap(find.semantics.byLabel('Talk'));+ await frames(tester);+ expect(recorder.recording, isTrue);+ expect(find.semantics.byLabel('Done'), findsOne);++ tester.semantics.tap(find.semantics.byLabel('Done'));+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'on my way');++ tester.semantics.longPress(find.semantics.byLabel('Talk'));+ await tester.pumpAndSettle();+ expect(find.text('Voice input language'), findsOneWidget);+ semantics.dispose();+ });++ testWidgets('leaving the chat mid-take closes the microphone', (+ tester,+ ) async {+ await pump(tester);+ await tapMic(tester);+ expect(recorder.recording, isTrue);++ await tester.pumpWidget(const SizedBox());++ expect(recorder.cancels, 1);+ expect(recorder.recording, isFalse);+ });++ /// Another screen over the chat, its push done.+ Future<void> cover(WidgetTester tester) async {+ final context = tester.element(find.byType(SwarmConversationPage));+ unawaited(+ Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => const Scaffold(body: Text('Other screen')),+ ),+ ),+ );+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ }++ Future<void> uncover(WidgetTester tester) async {+ final context = tester.element(find.text('Other screen'));+ Navigator.of(context).pop();+ await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ }++ Future<void> lifecycle(+ WidgetTester tester,+ List<AppLifecycleState> states,+ ) async {+ for (final state in states) {+ tester.binding.handleAppLifecycleStateChanged(state);+ }+ await frames(tester);+ }++ // Review of #2014 at ad9dee05d: the reviewer's probe, as it was.+ testWidgets('covering a chat cancels its recording', (tester) async {+ await pump(tester);+ await tapMic(tester);+ expect(recorder.recording, isTrue);++ await cover(tester);++ expect(+ recorder.recording,+ isFalse,+ reason: 'A covered chat must not keep recording speech',+ );+ });++ testWidgets('a take covered after speaking is thrown away, not '+ 'transcribed', (tester) async {+ await pump(tester);+ stt.replies.add('said behind another screen');+ await tapMic(tester);+ recorder.meter.value = 0.8;+ await tester.pump(const Duration(milliseconds: 500));+ recorder.meter.value = 0.02;++ await cover(tester);+ await tester.pump(const Duration(seconds: 5));++ expect(recorder.cancels, 1);+ expect(recorder.stops, 0, reason: 'a take is only stopped to be sent');+ expect(stt.calls, isEmpty);+ await uncover(tester);+ expect(box(tester), isEmpty);+ });++ testWidgets('the app going to the background mid-take throws the take '+ 'away; a system prompt over it does not', (tester) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pump(tester);+ await tapMic(tester);++ // The microphone permission prompt and Control Center leave the app+ // inactive, still in front.+ await lifecycle(tester, [AppLifecycleState.inactive]);+ expect(recorder.recording, isTrue);++ await lifecycle(tester, [+ AppLifecycleState.hidden,+ AppLifecycleState.paused,+ ]);+ expect(recorder.recording, isFalse);+ expect(recorder.cancels, 1);++ await lifecycle(tester, [+ AppLifecycleState.hidden,+ AppLifecycleState.inactive,+ AppLifecycleState.resumed,+ ]);+ await tester.pump(const Duration(seconds: 5));+ expect(stt.calls, isEmpty);+ expect(box(tester), isEmpty);+ expect(find.byType(VoiceMicCore), findsNothing, reason: 'back at rest');+ });++ // Review of #2014 at 42c8eac9c: the reviewer's probe, in its order.+ testWidgets('quiet under a system prompt ends nothing; the take goes on '+ 'once the app is back, until the tap', (tester) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pump(tester);+ stt.replies.add('said before Control Center');+ await tapMic(tester);+ recorder.meter.value = 0.8;+ await tester.pump(const Duration(milliseconds: 500));++ await lifecycle(tester, [AppLifecycleState.inactive]);+ recorder.meter.value = 0.02;+ await tester.pump(const Duration(seconds: 4));+ expect(stt.calls, isEmpty, reason: 'Control Center over the chat');+ expect(recorder.recording, isTrue, reason: 'the take is kept');++ await lifecycle(tester, [AppLifecycleState.resumed]);+ await tester.pump(const Duration(seconds: 10));+ expect(recorder.recording, isTrue);+ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'said before Control Center');+ });++ testWidgets('a take kept under a system prompt goes if the app then goes '+ 'away', (tester) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pump(tester);+ await tapMic(tester);+ recorder.meter.value = 0.8;+ await tester.pump(const Duration(milliseconds: 500));+ recorder.meter.value = 0.02;+ await tester.pump(const Duration(seconds: 2));++ await lifecycle(tester, [AppLifecycleState.inactive]);+ await tester.pump(const Duration(seconds: 4));+ expect(stt.calls, isEmpty);+ expect(recorder.recording, isTrue);++ await lifecycle(tester, [+ AppLifecycleState.hidden,+ AppLifecycleState.paused,+ ]);+ await lifecycle(tester, [+ AppLifecycleState.hidden,+ AppLifecycleState.inactive,+ AppLifecycleState.resumed,+ ]);+ await tester.pump(const Duration(seconds: 5));+ expect(recorder.cancels, 1);+ expect(stt.calls, isEmpty);+ expect(box(tester), isEmpty);+ });++ testWidgets('a take that reaches its limit puts its words in the box', (+ tester,+ ) async {+ await pump(tester);+ stt.replies.add('five minutes of it');+ await tapMic(tester);++ await tester.pump(const Duration(minutes: 5));+ await frames(tester);++ expect(recorder.recording, isFalse);+ expect(box(tester), 'five minutes of it');+ expect(fake.commands, isEmpty);+ });++ testWidgets('a take that reaches its limit under a system prompt is held '+ 'until the app is back', (tester) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pump(tester);+ stt.replies.add('held over the limit');+ await tapMic(tester);++ await lifecycle(tester, [AppLifecycleState.inactive]);+ await tester.pump(const Duration(minutes: 5, seconds: 10));+ expect(stt.calls, isEmpty);+ expect(recorder.recording, isTrue);++ await lifecycle(tester, [AppLifecycleState.resumed]);+ await frames(tester);+ expect(recorder.recording, isFalse);+ expect(box(tester), 'held over the limit');+ });++ // Review of #2014 at 61a2bce93: the reviewer's probe, with the tap that+ // ends a take now (Tony, 10-29) — a system prompt comes up while the+ // microphone is still closing.+ testWidgets('a take whose microphone closes under a system prompt is sent '+ 'to be transcribed only once the app is back', (tester) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pump(tester);+ stt.replies.add('said just before Control Center');+ recorder.heldStop = Completer();+ await tapMic(tester);+ recorder.meter.value = 0.8;+ await tester.pump(const Duration(milliseconds: 500));+ await tapMic(tester);+ expect(recorder.stops, 1);+ expect(stt.calls, isEmpty);++ await lifecycle(tester, [AppLifecycleState.inactive]);+ recorder.heldStop!.complete(recorder.captured);+ await frames(tester);+ await tester.pump(const Duration(seconds: 10));+ expect(+ stt.calls,+ isEmpty,+ reason: 'checked again once the microphone has closed',+ );+ expect(fake.commands, isEmpty);++ await lifecycle(tester, [AppLifecycleState.resumed]);+ await tester.pumpAndSettle();+ expect(stt.calls, hasLength(1));+ expect(fake.commands.single['text'], 'said just before Control Center');+ });++ testWidgets('a take that reaches its limit as a system prompt comes up '+ 'waits for the app too', (tester) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pump(tester);+ stt.replies.add('five minutes, then Control Center');+ recorder.heldStop = Completer();+ await tapMic(tester);+ await tester.pump(const Duration(minutes: 5));+ await frames(tester);+ expect(recorder.stops, 1);++ await lifecycle(tester, [AppLifecycleState.inactive]);+ recorder.heldStop!.complete(recorder.captured);+ await frames(tester);+ expect(stt.calls, isEmpty);++ await lifecycle(tester, [AppLifecycleState.resumed]);+ expect(box(tester), 'five minutes, then Control Center');+ });++ testWidgets('a take held under a system prompt is thrown away if the app '+ 'goes away', (tester) async {+ addTearDown(+ () => tester.binding.handleAppLifecycleStateChanged(+ AppLifecycleState.resumed,+ ),+ );+ await pump(tester);+ stt.replies.add('never heard');+ recorder.heldStop = Completer();+ await tapMic(tester);+ await tapMic(tester);+ expect(recorder.stops, 1);++ await lifecycle(tester, [AppLifecycleState.inactive]);+ recorder.heldStop!.complete(recorder.captured);+ await frames(tester);+ await lifecycle(tester, [+ AppLifecycleState.hidden,+ AppLifecycleState.paused,+ ]);+ await lifecycle(tester, [+ AppLifecycleState.hidden,+ AppLifecycleState.inactive,+ AppLifecycleState.resumed,+ ]);+ await tester.pump(const Duration(seconds: 5));++ expect(stt.calls, isEmpty);+ expect(box(tester), isEmpty);+ expect(find.byType(VoiceMicCore), findsNothing, reason: 'back at rest');+ });++ testWidgets('a take whose microphone closes after the chat was covered is '+ 'not transcribed', (tester) async {+ await pump(tester);+ stt.replies.add('said behind another screen');+ recorder.heldStop = Completer();+ await tapMic(tester);+ await tapMic(tester);++ await cover(tester);+ recorder.heldStop!.complete(recorder.captured);+ await frames(tester);+ await uncover(tester);++ expect(stt.calls, isEmpty);+ expect(box(tester), isEmpty);+ });++ testWidgets('back on the chat, the mic starts a fresh take', (tester) async {+ await pump(tester);+ stt.replies.add('second try');+ await tapMic(tester);+ await cover(tester);+ await uncover(tester);++ await tapMic(tester);+ expect(recorder.starts, 2);+ expect(recorder.recording, isTrue);+ await tapMic(tester);+ await tester.pumpAndSettle();+ expect(fake.commands.single['text'], 'second try');+ });++ testWidgets('a microphone allowed after the chat was covered never opens', (+ tester,+ ) async {+ recorder.pendingPermission = Completer();+ await pump(tester);+ await tapMic(tester);++ await cover(tester);+ recorder.pendingPermission!.complete(true);+ await frames(tester);++ expect(recorder.starts, 0);+ });++ testWidgets('words transcribed after the chat was covered are dropped', (+ tester,+ ) async {+ await pump(tester);+ stt.pending = Completer();+ await tapMic(tester);+ await tapMic(tester);+ expect(stt.calls, hasLength(1), reason: 'sent while the chat was seen');++ await cover(tester);+ stt.pending!.complete('late words');+ await frames(tester);+ await uncover(tester);++ expect(box(tester), isEmpty);+ expect(fake.commands, isEmpty);+ });++ testWidgets('with no voice input the composer has no mic', (tester) async {+ await pump(tester, voice: false);++ expect(key('swarm-mic'), findsNothing);+ expect(key('swarm-send'), findsOneWidget);+ });+}++/// A microphone that also says how loud it is, for the mic's bars.+class _MeteredRecorder extends FakeVoiceRecorder implements VoiceLevelMeter {+ final meter = ValueNotifier<double>(0);++ /// Holds [stop] open until the test completes it: a microphone that takes+ /// its time to close, as a real one does.+ Completer<VoiceTake?>? heldStop;++ @override+ ValueListenable<double> get level => meter;++ @override+ Future<VoiceTake?> stop() async {+ final take = await super.stop();+ return heldStop?.future ?? take;+ }+}diff --git a/mobile/test/swarm/swarm_computers_fake.dart b/mobile/test/swarm/swarm_computers_fake.dartnew file mode 100644index 000000000..73a5e28fa--- /dev/null+++ b/mobile/test/swarm/swarm_computers_fake.dart@@ -0,0 +1,42 @@+import 'dart:async';++import 'package:flutter/widgets.dart';+import 'package:harness_mobile/swarm/swarm_start.dart';++/// The person's computers as a test scripts them.+class FakeComputers extends ChangeNotifier implements SwarmComputers {+ FakeComputers(this.computers);++ @override+ List<SwarmComputer>? computers;++ @override+ bool rechecking = false;++ int rechecks = 0, adds = 0;++ /// Holds a recheck until completed.+ Completer<void>? held;++ /// What a recheck finds.+ List<SwarmComputer>? found;++ void set(List<SwarmComputer>? next) {+ computers = next;+ notifyListeners();+ }++ @override+ Future<void> recheck() async {+ rechecks++;+ rechecking = true;+ notifyListeners();+ await held?.future;+ rechecking = false;+ if (found case final next?) computers = next;+ notifyListeners();+ }++ @override+ void add(BuildContext context) => adds++;+}diff --git a/mobile/test/swarm/swarm_computers_test.dart b/mobile/test/swarm/swarm_computers_test.dartnew file mode 100644index 000000000..3082b9dc7--- /dev/null+++ b/mobile/test/swarm/swarm_computers_test.dart@@ -0,0 +1,95 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/swarm/swarm_computers.dart';++import '../viewer_app_fixture.dart';++/// The account's computers as Swarm's start screens see them, from the app's+/// own machine list.+void main() {+ test('each computer by name, away only when the socket and the list agree, '+ 'and nothing until the list has answered', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ final computers = AppSwarmComputers(rig.app);+ addTearDown(computers.dispose);+ expect(computers.computers, isNull, reason: 'not answered yet');++ rig.api.onMachines = () async => [+ remoteMachine('a', name: 'Studio Mac'),+ remoteMachine('b', name: 'Mac mini', status: 'offline'),+ ];+ await rig.app.bootstrap();+ await settle();+ rig.app.connectionStatusForTest('a', ConnectionStatus.connected);+ rig.app.connectionStatusForTest('b', ConnectionStatus.disconnected);+ await settle();++ expect(computers.computers, [+ (name: 'Studio Mac', away: false),+ (name: 'Mac mini', away: true),+ ]);+ });++ test('tells only when the computers change, not at every change of the '+ 'app', () async {+ final rig = await signedInWith({'a': []});+ addTearDown(rig.app.dispose);+ final computers = AppSwarmComputers(rig.app);+ addTearDown(computers.dispose);+ var told = 0;+ computers.addListener(() => told++);++ rig.app.connectionStatusForTest('a', ConnectionStatus.connected);+ await settle();+ expect(told, 0);++ rig.api.onMachines = () async => [remoteMachine('a', status: 'offline')];+ await rig.app.refreshMachines();+ rig.app.connectionStatusForTest('a', ConnectionStatus.disconnected);+ await settle();++ expect(computers.computers, [(name: 'Machine a', away: true)]);+ expect(told, 1);+ });++ // At a cold start the socket comes up after the list, away all along: a+ // Swarm read that failed for want of a computer waited 2 to 8 s for its+ // next try (audit of 44d284f65, item 6).+ test('tells when a computer comes up, and not when it goes', () async {+ final rig = await signedInWith({'a': []});+ addTearDown(rig.app.dispose);+ rig.app.connectionStatusForTest('a', ConnectionStatus.connecting);+ await settle();+ final computers = AppSwarmComputers(rig.app);+ addTearDown(computers.dispose);+ var told = 0;+ computers.addListener(() => told++);++ rig.app.connectionStatusForTest('a', ConnectionStatus.connected);+ await settle();+ expect(told, 1);+ expect(computers.computers, [(name: 'Machine a', away: false)]);++ rig.app.connectionStatusForTest('a', ConnectionStatus.reconnecting);+ await settle();+ expect(told, 1, reason: 'still listed as up: nothing to tell');+ });++ test('Try again reads the list again', () async {+ final rig = await signedInWith({'a': []});+ addTearDown(rig.app.dispose);+ final computers = AppSwarmComputers(rig.app);+ addTearDown(computers.dispose);+ var listed = 0;+ rig.api.onMachines = () async {+ listed++;+ return [remoteMachine('a')];+ };++ await computers.recheck();++ expect(listed, 1);+ expect(computers.rechecking, isFalse);+ });+}diff --git a/mobile/test/swarm/swarm_conversation_files_test.dart b/mobile/test/swarm/swarm_conversation_files_test.dartnew file mode 100644index 000000000..29e3e902a--- /dev/null+++ b/mobile/test/swarm/swarm_conversation_files_test.dart@@ -0,0 +1,444 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:dio/dio.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import 'swarm_fixture.dart';++/// One upload the chat asked for: what it sent, and how to answer it.+class _Upload {+ _Upload(this.name, this.mime, this.bytes, this.conversationId, this.tabId,+ this.cancel, this.onProgress);+ final String name, mime, conversationId, tabId;+ final Uint8List bytes;+ final CancelToken cancel;+ final void Function(double sent) onProgress;+ final answer = Completer<Map<String, dynamic>>();+}++/// The backend's attachment upload, answered by the test.+class _Uploads {+ final asked = <_Upload>[];++ /// Answers each upload at once with an id made from its name, unless off.+ bool answersAtOnce = true;++ /// Refuses uploads of these names.+ final refuse = <String, SuperTabFailure>{};++ List<String> get names => [for (final u in asked) u.name];++ SwarmUpload get upload =>+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required bytes,+ required cancel,+ required onProgress,+ }) {+ final u = _Upload(+ name,+ mime,+ bytes,+ conversationId,+ tabId,+ cancel,+ onProgress,+ );+ asked.add(u);+ if (refuse[name] case final failure?) {+ u.answer.completeError(failure);+ } else if (answersAtOnce) {+ u.answer.complete(attachment('id-$name'));+ }+ return u.answer.future;+ };++ static Map<String, dynamic> attachment(String id) => {+ 'attachment': {+ 'id': id,+ 'name': 'x',+ 'mime': 'image/jpeg',+ 'size': 1,+ 'url': 'https://cdn.harness.autonomous.ai/x',+ },+ };+}++void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const commands = '/api/super-tabs/$tab/commands';++ SwarmOutgoingFile file(String name, [int size = 3]) =>+ SwarmOutgoingFile(name, Uint8List.fromList(List.filled(size, 7)));++ ({FakeSwarm swarm, SwarmReader reader, _Uploads uploads}) rig({+ String role = 'owner',+ bool uploads = true,+ }) {+ final swarm = FakeSwarm();+ final fake = _Uploads();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: const ['agent-lead', 'agent-builder'],+ lastMessageSequence: 0,+ ),+ ],+ ),+ 'members': [part(me, 1, person(me, role: role))],+ };+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ swarm.routes[commands] = (_) => {'result': <String, dynamic>{}};+ final reader = uploads+ ? SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ upload: fake.upload,+ )+ : SwarmReader(tabId: tab, accountId: me, request: swarm.request);+ addTearDown(reader.dispose);+ return (swarm: swarm, reader: reader, uploads: fake);+ }++ Future<SwarmConversation> open(+ SwarmReader reader, {+ Duration uploadTimeout = const Duration(minutes: 2),+ }) async {+ await reader.refresh();+ final c = SwarmConversation(reader, 'g1', uploadTimeout: uploadTimeout);+ addTearDown(c.dispose);+ await c.load();+ return c;+ }++ test('each file goes up once, in order, then the post names them', () async {+ final r = rig();+ final c = await open(r.reader);+ c.draft = 'Here are the shots';+ c.files.add([file('a.jpg'), file('b.pdf', 5)]);++ expect(await c.send(), isTrue);++ expect(r.uploads.names, ['a.jpg', 'b.pdf']);+ final first = r.uploads.asked.first;+ expect(first.tabId, tab);+ expect(first.conversationId, 'g1');+ expect(first.mime, 'image/jpeg');+ expect(first.bytes, [7, 7, 7]);+ expect(r.uploads.asked.last.mime, 'application/pdf');+ expect(r.swarm.commands.single, {+ 'type': 'message.send',+ 'conversationId': 'g1',+ 'text': 'Here are the shots',+ 'replyTo': null,+ 'recipientIds': <String>[],+ 'attachmentIds': ['id-a.jpg', 'id-b.pdf'],+ });+ });++ test('a post may be files alone', () async {+ final r = rig();+ final c = await open(r.reader);+ c.files.add([file('a.jpg')]);++ expect(c.canSend, isTrue);+ expect(await c.send(), isTrue);++ expect(r.swarm.commands.single['text'], '');+ expect(r.swarm.commands.single['attachmentIds'], ['id-a.jpg']);+ });++ test('a post without files names none', () async {+ final r = rig();+ final c = await open(r.reader);+ c.draft = 'hi';++ expect(await c.send(), isTrue);++ expect(r.uploads.asked, isEmpty);+ expect(r.swarm.commands.single.containsKey('attachmentIds'), isFalse);+ });++ test('nothing to send without text or files', () async {+ final r = rig();+ final c = await open(r.reader);++ expect(c.canSend, isFalse);+ expect(await c.send(), isFalse);++ expect(r.swarm.commands, isEmpty);+ });++ test('sent files leave the composer, and show with the post until it is '+ 'read back', () async {+ final r = rig();+ final taken = Completer<Object?>();+ r.swarm.routes[commands] = (_) => taken.future;+ final c = await open(r.reader);+ c.files.add([file('a.jpg')]);++ final sending = c.send();+ await settle();++ expect(c.files.files, isEmpty);+ expect([for (final f in c.pending!.files) f.name], ['a.jpg']);+ taken.complete({'result': <String, dynamic>{}});+ expect(await sending, isTrue);+ expect(c.pending, isNull);+ });++ test('a failed upload keeps the draft and the files, sends nothing, and '+ 'says why', () async {+ final r = rig();+ r.uploads.refuse['b.jpg'] = const SuperTabFailure(+ 'ATTACHMENT_TOO_LARGE',+ 'That file is over 10 MB.',+ statusCode: 413,+ );+ final c = await open(r.reader);+ c.draft = 'look';+ c.files.add([file('a.jpg'), file('b.jpg')]);++ expect(await c.send(), isFalse);++ expect(c.error, 'That file is over 10 MB.');+ expect(c.draft, 'look');+ expect([for (final f in c.files.files) f.name], ['a.jpg', 'b.jpg']);+ expect(r.swarm.commands, isEmpty);+ expect(c.uploading, isFalse);+ expect(c.pending, isNull);+ });++ test('an upload that fails for any other reason says so plainly', () async {+ final r = rig();+ r.uploads.answersAtOnce = false;+ final c = await open(r.reader);+ c.files.add([file('a.jpg'), file('b.jpg')]);++ final sending = c.send();+ await settle();+ r.uploads.asked.single.answer.completeError(StateError('socket closed'));++ expect(await sending, isFalse);+ expect(c.error, 'Could not upload the files. Try again.');+ });++ test('sending again does not upload a file that already went up', () async {+ final r = rig();+ r.uploads.refuse['b.jpg'] = const SuperTabFailure('UPLOAD_FAILED', 'No.');+ final c = await open(r.reader);+ c.files.add([file('a.jpg'), file('b.jpg')]);+ expect(await c.send(), isFalse);++ r.uploads.refuse.clear();+ expect(await c.send(), isTrue);++ expect(r.uploads.names, ['a.jpg', 'b.jpg', 'b.jpg']);+ expect(r.swarm.commands.single['attachmentIds'], ['id-a.jpg', 'id-b.jpg']);+ });++ test('each file says how much has gone up while it goes', () async {+ final r = rig();+ r.uploads.answersAtOnce = false;+ final c = await open(r.reader);+ c.files.add([file('a.jpg'), file('b.jpg')]);+ final [a, b] = c.files.files;++ final sending = c.send();+ await settle();+ expect(c.uploading, isTrue);+ expect(c.isUploading(a), isTrue);+ r.uploads.asked.single.onProgress(0.5);+ expect(c.uploadProgress(a), 0.5);+ expect(c.uploadProgress(b), isNull);++ r.uploads.asked.single.answer.complete(_Uploads.attachment('id-a'));+ await settle();+ expect(c.isUploading(a), isFalse, reason: 'it is up');+ expect(c.isUploading(b), isTrue);+ r.uploads.asked.last.answer.complete(_Uploads.attachment('id-b'));++ expect(await sending, isTrue);+ expect(c.uploading, isFalse);+ expect(c.uploadProgress(b), isNull);+ });++ test('taking a file off while it goes up gives the upload up and frees '+ 'the composer, with the draft and the other files kept', () async {+ final r = rig();+ r.uploads.answersAtOnce = false;+ final c = await open(r.reader);+ c.draft = 'look';+ c.files.add([file('a.jpg'), file('b.jpg')]);++ final sending = c.send();+ await settle();+ final going = r.uploads.asked.single;+ c.files.remove(c.files.files.first);++ expect(await sending, isFalse);+ expect(going.cancel.isCancelled, isTrue);+ expect(c.uploading, isFalse);+ expect(c.error, isNull, reason: 'the person did it');+ expect(c.draft, 'look');+ expect([for (final f in c.files.files) f.name], ['b.jpg']);+ expect(r.swarm.commands, isEmpty);+ });++ test('an upload that stops moving gives up and says so', () async {+ final r = rig();+ r.uploads.answersAtOnce = false;+ final c = await open(+ r.reader,+ uploadTimeout: const Duration(milliseconds: 20),+ );+ c.files.add([file('a.jpg')]);++ final sending = c.send();+ await settle();+ final going = r.uploads.asked.single;+ // A transport that honours its token ends when it is cancelled.+ unawaited(+ going.cancel.whenCancel.then(+ (e) => going.answer.isCompleted ? null : going.answer.completeError(e),+ ),+ );++ expect(await sending, isFalse);+ expect(going.cancel.isCancelled, isTrue);+ expect(c.error, 'The upload stopped moving. Try again.');+ expect([for (final f in c.files.files) f.name], ['a.jpg']);+ });++ test('a post refused for its files puts them back, to go up again', () async {+ final r = rig();+ var refuse = true;+ r.swarm.routes[commands] = (_) => refuse+ ? throw const SuperTabFailure(+ 'ATTACHMENT_NOT_FOUND',+ 'A file of this message is gone. Attach it again.',+ statusCode: 400,+ )+ : {'result': <String, dynamic>{}};+ final c = await open(r.reader);+ c.draft = 'look';+ c.files.add([file('a.jpg')]);++ expect(await c.send(), isFalse);+ expect(c.error, 'A file of this message is gone. Attach it again.');+ expect(c.draft, 'look');+ expect([for (final f in c.files.files) f.name], ['a.jpg']);++ refuse = false;+ expect(await c.send(), isTrue);+ expect(r.uploads.names, ['a.jpg', 'a.jpg']);+ });++ test('a post refused for something else keeps its files up', () async {+ final r = rig();+ var refuse = true;+ r.swarm.routes[commands] = (_) => refuse+ ? throw const SuperTabFailure(+ 'INVALID_RECIPIENT',+ 'Choose an agent in this conversation.',+ statusCode: 400,+ )+ : {'result': <String, dynamic>{}};+ final c = await open(r.reader);+ c.files.add([file('a.jpg')]);++ expect(await c.send(), isFalse);+ expect([for (final f in c.files.files) f.name], ['a.jpg']);++ refuse = false;+ expect(await c.send(), isTrue);+ expect(r.uploads.names, ['a.jpg']);+ expect(r.swarm.commands.last['attachmentIds'], ['id-a.jpg']);+ });++ test('a post whose answer was lost is sent again with the same files',+ () async {+ final r = rig();+ var lost = true;+ r.swarm.routes[commands] = (_) => lost+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : {'result': <String, dynamic>{}};+ final c = await open(r.reader);+ c.files.add([file('a.jpg')]);++ expect(await c.send(), isFalse);+ expect(c.unconfirmed, isTrue);+ lost = false;+ expect(await c.send(), isTrue);++ expect(r.uploads.names, ['a.jpg']);+ expect([for (final s in r.swarm.commands) s['attachmentIds']], [+ ['id-a.jpg'],+ ['id-a.jpg'],+ ]);+ });++ test('files added while a post goes stay for the next one', () async {+ final r = rig();+ final taken = Completer<Object?>();+ r.swarm.routes[commands] = (_) => taken.future;+ final c = await open(r.reader);+ c.files.add([file('a.jpg')]);++ final sending = c.send();+ await settle();+ c.files.add([file('later.jpg')]);+ taken.complete({'result': <String, dynamic>{}});+ await sending;++ expect([for (final f in c.files.files) f.name], ['later.jpg']);+ });++ test('a phone that cannot upload says files cannot be sent', () async {+ final r = rig(uploads: false);+ final c = await open(r.reader);+ c.files.add([file('a.jpg')]);++ expect(await c.send(), isFalse);++ expect(c.error, 'Files can’t be sent from here.');+ expect(r.swarm.commands, isEmpty);+ });++ test('a viewer uploads nothing', () async {+ final r = rig(role: 'viewer');+ final c = await open(r.reader);+ c.files.add([file('a.jpg')]);++ expect(c.canSend, isFalse);+ expect(await c.send(), isFalse);++ expect(r.uploads.asked, isEmpty);+ });++ test('closing the chat lets its files go', () async {+ final r = rig();+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g1');+ await c.load();+ c.files.add([file('a.jpg')]);+ final files = c.files;++ c.dispose();++ expect(files.files, isEmpty);+ });+}diff --git a/mobile/test/swarm/swarm_conversation_test.dart b/mobile/test/swarm/swarm_conversation_test.dartnew file mode 100644index 000000000..87e998432--- /dev/null+++ b/mobile/test/swarm/swarm_conversation_test.dart@@ -0,0 +1,1241 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_read_marks.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_unread.dart';++import 'swarm_fixture.dart';++/// One conversation on the phone: its messages (latest page first, older on+/// demand, new ones as the Swarm says they arrived), and what the person+/// posts to it (backend message.send, section 4.6 of the parts design).+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';++ Map<String, dynamic> message(+ String id,+ int sequence, {+ String text = 'hello',+ String authorId = 'agent-builder',+ bool fromAgent = true,+ String conversationId = 'g1',+ }) => {+ 'id': id,+ 'conversationId': conversationId,+ 'text': text,+ 'sequence': sequence,+ 'author': {+ 'kind': fromAgent ? 'agent' : 'person',+ 'id': authorId,+ 'name': fromAgent ? 'Builder' : 'me',+ },+ 'createdAt': '2026-10-27T01:00:00.000Z',+ };++ /// A Swarm with conversation g1 at [sequence], and [rest] of its groups.+ ({FakeSwarm swarm, SwarmReader reader}) rig({+ int sequence = 2,+ List<String> agentIds = const ['agent-lead', 'agent-builder'],+ String role = 'owner',+ bool archived = false,+ }) {+ final swarm = FakeSwarm();+ Map<String, dynamic> g1(int seq) => {+ ...groupData(+ 'g1',+ title: 'Fix login',+ agentIds: agentIds,+ lastMessageSequence: seq,+ ),+ 'archived': archived,+ };+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(groups: [g1(sequence)]),+ 'members': [part(me, 1, person(me, role: role))],+ };+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ 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 conversation = SwarmConversation(reader, 'g1');+ addTearDown(conversation.dispose);+ await conversation.load();+ return conversation;+ }++ test('opening reads the latest page, oldest first', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': {'sequence': 1, 'id': 'm1'},+ };++ final c = await open(r.reader);++ expect([for (final m in c.messages) m.id], ['m1', 'm2']);+ expect(c.hasOlder, isTrue);+ expect(r.swarm.paths.last, messages);+ });++ // The chat page redraws on what its conversation says: a read that brings+ // nothing, or a letter typed, is not news for its messages.+ test('a read that brings nothing new tells no one', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': {'sequence': 1, 'id': 'm1'},+ };+ final c = await open(r.reader);+ final shown = c.messages;+ var told = 0;+ c.addListener(() => told++);++ await c.load();++ expect(told, 0);+ expect(c.messages, same(shown));+ expect(c.hasOlder, isTrue);+ });++ test('a draft typed is told to the composer, not to the messages', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m1', 1)],+ 'next': null,+ };+ final c = await open(r.reader);+ var told = 0;+ c.addListener(() => told++);++ c.draft = 'Hel';+ c.draft = 'Hello';++ expect(told, 0);+ expect(c.draft, 'Hello');+ });++ test(+ 'older messages are read before the oldest shown, until there are none',+ () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m5', 5)],+ 'next': {'sequence': 5, 'id': 'm5'},+ };+ r.swarm.routes['$messages?before=5&beforeId=m5'] = (_) => {+ 'messages': [message('m3', 3), message('m4', 4)],+ 'next': null,+ };+ final c = await open(r.reader);++ await c.loadOlder();++ expect([for (final m in c.messages) m.id], ['m3', 'm4', 'm5']);+ expect(c.hasOlder, isFalse);+ },+ );++ test(+ 'new messages are read when the Swarm says the conversation moved',+ () async {+ final r = rig(sequence: 2);+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2)],+ 'next': null,+ };+ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': [message('m3', 3, text: 'done')],+ 'next': null,+ };+ final c = await open(r.reader);++ // A change that leaves the conversation where it was reads no messages.+ await r.reader.refresh();+ await settle();+ expect(r.swarm.paths.where((p) => p.contains('after=')), isEmpty);++ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part(+ 'g1',+ 30,+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 3,+ ),+ ),+ ],+ );+ await r.reader.refresh();+ await settle();++ expect([for (final m in c.messages) m.text], ['hello', 'done']);+ },+ );++ // The phone has no thread view yet: a reply only in its thread is read+ // and shown in the chat, though it leaves the chat's main stream where it+ // was (PM, 10-29; desktop_parity_test).+ test('a reply only in its thread is read and shown in the chat, so nothing '+ 'is lost', () async {+ final r = rig(sequence: 2);+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2)],+ 'next': null,+ };+ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': [+ {...message('m3', 3, text: 'in the thread'), 'thread': 'm2'},+ ],+ 'next': null,+ };+ final c = await open(r.reader);++ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part('g1', 30, {+ ...groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 3,+ ),+ 'lastMainSequence': 2,+ }),+ ],+ );+ await r.reader.refresh();+ await settle();++ expect([for (final m in c.messages) m.text], ['hello', 'in the thread']);+ expect(c.messages.last.threadReply, isTrue);+ expect(r.reader.snapshot!.conversation('g1')!.mainSequence, 2);+ });++ test(+ 'a post goes to the agents mentioned in it, and clears the draft',+ () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => {+ 'result': {'messageId': 'm9'},+ };+ final c = await open(r.reader);++ c.draft = 'Please check ';+ c.mention('agent-builder');+ expect(c.draft, 'Please check @Nova ');+ c.draft = '${c.draft}the build';+ expect(await c.send(), isTrue);++ final sent = r.swarm.calls.singleWhere((call) => call.method == 'POST');+ expect(sent.body!['operationId'], isA<String>());+ expect(sent.body!['command'], {+ 'type': 'message.send',+ 'conversationId': 'g1',+ 'text': 'Please check @Nova the build',+ 'replyTo': null,+ 'recipientIds': ['agent-builder'],+ });+ expect(c.draft, isEmpty);+ },+ );++ test('a mention taken out of the text addresses nobody', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => {+ 'result': <String, dynamic>{},+ };+ final c = await open(r.reader);++ c.mention('agent-builder');+ c.draft = 'never mind';+ await c.send();++ expect(r.swarm.commands.single['recipientIds'], isEmpty);+ });++ test('a refused post keeps the draft and says why', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw const SuperTabFailure(+ 'READ_ONLY',+ 'This conversation is read only.',+ statusCode: 403,+ );+ final c = await open(r.reader);++ c.draft = 'hi';+ expect(await c.send(), isFalse);++ expect(c.draft, 'hi');+ expect(c.error, 'This conversation is read only.');+ expect(c.unconfirmed, isFalse, reason: 'refused means nothing was done');+ });++ test('a post whose answer was lost is retried as the same post', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ var lost = true;+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => lost+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : {'result': <String, dynamic>{}};+ final c = await open(r.reader);++ c.draft = 'hi';+ expect(await c.send(), isFalse);+ expect(c.unconfirmed, isTrue);++ lost = false;+ expect(await c.send(), isTrue);++ final posts = [+ for (final call in r.swarm.calls)+ if (call.method == 'POST') call.body!['operationId'],+ ];+ expect(posts, hasLength(2));+ expect(posts.toSet(), hasLength(1), reason: 'the backend runs it once');+ });++ test('a reply carries the message it answers, and the reply goes once it '+ 'is sent', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m1', 1, text: 'Ship it?')],+ 'next': null,+ };+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => {+ 'result': <String, dynamic>{},+ };+ final c = await open(r.reader);++ c.replyingTo = c.messages.single;+ c.draft = 'Yes';+ expect(await c.send(), isTrue);++ expect(r.swarm.commands.single['replyTo'], 'm1');+ expect(c.replyingTo, isNull);+ });++ test('a post shows at once as sending, out of the draft, until it is read '+ 'back', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ final taken = Completer<Object?>();+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => taken.future;+ final c = await open(r.reader);++ c.draft = 'On my way';+ final sent = c.send();+ await settle();++ expect(c.draft, isEmpty, reason: 'the field is free at once');+ expect(c.pending?.text, 'On my way');+ expect(c.sending, isTrue);++ r.swarm.routes[messages] = (_) => {+ 'messages': [+ message('m9', 3, text: 'On my way', authorId: me, fromAgent: false),+ ],+ 'next': null,+ };+ taken.complete({'result': <String, dynamic>{}});+ expect(await sent, isTrue);++ expect(c.pending, isNull);+ expect([for (final m in c.messages) m.text], ['On my way']);+ });++ test('a post whose answer was lost stays at the foot, not confirmed, and '+ 'out of the draft', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ final c = await open(r.reader);++ c.draft = 'hi';+ expect(await c.send(), isFalse);++ expect(c.pending?.text, 'hi');+ expect(c.sending, isFalse);+ expect(c.unconfirmed, isTrue);+ expect(c.draft, isEmpty);+ });++ test('a refused post puts its text back in the draft, with its mention and '+ 'its reply', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m1', 1, text: 'Ship it?')],+ 'next': null,+ };+ var refuse = true;+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => refuse+ ? throw const SuperTabFailure(+ 'TOO_LONG',+ 'This message is too long.',+ statusCode: 400,+ )+ : {'result': <String, dynamic>{}};+ final c = await open(r.reader);+ c.replyingTo = c.messages.single;+ c.mention('agent-builder');+ c.draft = '${c.draft}please';++ expect(await c.send(), isFalse);++ expect(c.pending, isNull);+ expect(c.draft, '@Nova please');+ expect(c.replyingTo?.id, 'm1');+ expect(c.error, 'This message is too long.');++ refuse = false;+ expect(await c.send(), isTrue);+ expect(r.swarm.commands.last['recipientIds'], ['agent-builder']);+ expect(r.swarm.commands.last['replyTo'], 'm1');+ });++ test(+ 'the mention picker reads the name typed after an @ at the end',+ () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ final c = await open(r.reader);++ c.draft = 'hey';+ expect(c.mentionQuery, isNull);+ c.draft = 'hey @';+ expect(c.mentionQuery, '');+ c.draft = '@No';+ expect(c.mentionQuery, 'No');+ c.draft = 'mail me@home';+ expect(c.mentionQuery, isNull, reason: 'an @ inside a word is not one');+ c.draft = 'hey @No then';+ expect(c.mentionQuery, isNull);+ },+ );++ test('a name picked for the @ being typed takes its place, and the post '+ 'goes to that agent', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => {+ 'result': <String, dynamic>{},+ };+ final c = await open(r.reader);++ c.draft = 'Can you check @No';+ c.completeMention('agent-builder');+ expect(c.draft, 'Can you check @Nova ');+ expect(c.mentionQuery, isNull);++ c.draft = '${c.draft}this';+ await c.send();+ expect(r.swarm.commands.single['recipientIds'], ['agent-builder']);+ });++ test('a viewer, or an archived conversation, cannot post', () async {+ final viewer = rig(role: 'viewer');+ viewer.swarm.routes[messages] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };+ final c = await open(viewer.reader);+ c.draft = 'hi';+ expect(c.canPost, isFalse);+ expect(await c.send(), isFalse);++ final archived = rig(archived: true);+ archived.swarm.routes[messages] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };+ final a = await open(archived.reader);+ expect(a.canPost, isFalse);+ });++ test(+ 'messages of a conversation the person can no longer read are dropped',+ () async {+ final r = rig();+ var allowed = true;+ r.swarm.routes[messages] = (_) => allowed+ ? {+ 'messages': [message('m1', 1)],+ 'next': null,+ }+ : throw const SuperTabFailure(+ 'FORBIDDEN',+ 'Not yours.',+ statusCode: 403,+ );+ final c = await open(r.reader);+ expect(c.messages, hasLength(1));++ allowed = false;+ await c.load();++ expect(c.messages, isEmpty);+ },+ );++ group('a chat a full read leaves out', () {+ /// g1 as the first load lists it while [listed]; a change read answers+ /// with a reload, as when the person's access moved.+ ({FakeSwarm swarm, SwarmReader reader, void Function() leaveOut})+ reloadRig() {+ final r = rig();+ var listed = true;+ r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ if (listed)+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ audience: [me, 'person-other'],+ lastMessageSequence: 1,+ ),+ ],+ ),+ 'members': [part(me, 1, person(me))],+ };+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m1', 1, text: 'private plan')],+ 'next': null,+ };+ return (+ swarm: r.swarm,+ reader: r.reader,+ leaveOut: () {+ listed = false;+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {+ 'reload': true,+ };+ },+ );+ }++ test('and the person can no longer read loses its messages, draft and '+ 'unconfirmed post, and a late answer brings none back', () async {+ final r = reloadRig();+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ final c = await open(r.reader);+ expect(c.messages.single.text, 'private plan');+ c.draft = 'my reply';+ await c.send();+ expect(c.unconfirmed, isTrue);+ final late = Completer<Object?>();+ r.swarm.routes['$messages?after=1'] = (_) => late.future;+ final reading = c.load();++ r.leaveOut();+ await r.reader.refresh();+ await settle();++ expect(c.conversation, isNull);+ expect(+ r.swarm.paths,+ contains('/api/super-tabs/$tab/groups/g1'),+ reason: 'a closed chat is left out too, so it is asked by id',+ );+ expect(c.messages, isEmpty);+ expect(c.draft, isEmpty);+ expect(c.unconfirmed, isFalse);++ late.complete({+ 'messages': [message('m2', 2, text: 'more of the plan')],+ 'next': null,+ });+ await reading;+ await settle();+ expect(c.messages, isEmpty);+ });++ test(+ 'but can still read, as a closed one, keeps its draft and messages',+ () async {+ final r = reloadRig();+ r.swarm.routes['/api/super-tabs/$tab/groups/g1'] = (_) => {+ 'group': part(+ 'g1',+ 9,+ groupData(+ 'g1',+ title: 'Fix login',+ audience: [me, 'person-other'],+ lastMessageSequence: 1,+ dormant: true,+ ),+ ),+ };+ final c = await open(r.reader);+ c.draft = 'my reply';++ r.leaveOut();+ await r.reader.refresh();+ await settle();++ expect(c.conversation?.closed, isTrue);+ expect(c.messages.single.text, 'private plan');+ expect(c.draft, 'my reply');+ },+ );+ });++ group('where it stands', () {+ const lookup = '/api/super-tabs/$tab/groups/g-old';+ const old = '/api/super-tabs/$tab/conversations/g-old/messages';++ test('loading, then loaded', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m1', 1)],+ 'next': null,+ };+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g1');+ addTearDown(c.dispose);+ expect(c.state, SwarmChatState.loading);++ await c.load();++ expect(c.state, SwarmChatState.loaded);+ });++ test('a chat no full read has is looked for, its messages read '+ 'meanwhile', () async {+ final r = rig();+ final found = Completer<Object?>(), page = Completer<Object?>();+ r.swarm.routes[lookup] = (_) => found.future;+ r.swarm.routes[old] = (_) => page.future;+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g-old');+ addTearDown(c.dispose);++ final loading = c.load();+ await settle();++ expect(c.state, SwarmChatState.locating);+ expect(r.swarm.paths, containsAll([lookup, old]));++ page.complete({+ 'messages': [+ message('m1', 1, text: 'old plan', conversationId: 'g-old'),+ ],+ 'next': null,+ });+ found.complete({+ 'group': part(+ 'g-old',+ 9,+ groupData(+ 'g-old',+ title: 'Old work',+ lastMessageSequence: 1,+ dormant: true,+ ),+ ),+ });+ await loading;+ await settle();++ expect(c.conversation?.closed, isTrue);+ expect(c.messages.single.text, 'old plan');+ expect(c.state, SwarmChatState.loaded);+ });++ test('not open to the person only once the lookup refuses it', () async {+ final r = rig();+ final found = Completer<Object?>();+ r.swarm.routes[lookup] = (_) => found.future;+ r.swarm.routes[old] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g-old');+ addTearDown(c.dispose);+ var told = 0;+ c.addListener(() => told++);++ final loading = c.load();+ await settle();+ expect(c.state, isNot(SwarmChatState.lost));++ found.completeError(+ const SuperTabFailure('FORBIDDEN', 'Not yours.', statusCode: 403),+ );+ await loading;+ await settle();++ expect(c.state, SwarmChatState.lost);+ expect(told, greaterThan(0), reason: 'the page is told');+ });+ });++ test('reading back to a quoted message tells the chat once, not at each '+ 'page', () async {+ final r = rig(sequence: 30);+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m30', 30)],+ 'next': {'sequence': 30, 'id': 'm30'},+ };+ for (var top = 30; top > 26; top--) {+ r.swarm.routes['$messages?before=$top&beforeId=m$top'] = (_) => {+ 'messages': [message('m${top - 1}', top - 1)],+ 'next': {'sequence': top - 1, 'id': 'm${top - 1}'},+ };+ }+ final c = await open(r.reader);+ var told = 0;+ c.addListener(() => told++);++ expect(await c.readBackTo('m27'), isTrue);++ expect(told, 1);+ expect([for (final m in c.messages) m.id], ['m27', 'm28', 'm29', 'm30']);+ expect(r.swarm.paths.where((p) => p.contains('?before=')), hasLength(3));++ told = 0;+ expect(await c.readBackTo('m1', pages: 1), isFalse);+ expect(told, 1);+ expect(c.hasOlder, isTrue);+ });++ group('opened again', () {+ /// g1 read once and closed.+ Future<void> readAndClose(SwarmReader reader) async {+ await reader.refresh();+ final first = SwarmConversation(reader, 'g1');+ await first.load();+ first.dispose();+ }++ test(+ 'shows at once what was read, and reads only what came after',+ () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': {'sequence': 1, 'id': 'm1'},+ };+ await readAndClose(r.reader);++ final c = SwarmConversation(r.reader, 'g1');+ addTearDown(c.dispose);++ expect([for (final m in c.messages) m.id], ['m1', 'm2']);+ expect(c.hasOlder, isTrue);+ expect(c.state, SwarmChatState.loaded);+ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': [message('m3', 3)],+ 'next': null,+ };+ await c.load();+ expect(r.swarm.paths.last, '$messages?after=2');+ expect([for (final m in c.messages) m.id], ['m1', 'm2', 'm3']);+ },+ );++ test('more than a page newer reads the latest page instead', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': null,+ };+ await readAndClose(r.reader);+ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': [for (var i = 3; i < 103; i++) message('m$i', i)],+ 'next': {'sequence': 102, 'id': 'm102'},+ };+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m300', 300), message('m299', 299)],+ 'next': {'sequence': 299, 'id': 'm299'},+ };++ final c = SwarmConversation(r.reader, 'g1');+ addTearDown(c.dispose);+ await c.load();++ expect(r.swarm.paths.last, messages);+ expect([for (final m in c.messages) m.id], ['m299', 'm300']);+ expect(c.hasOlder, isTrue);+ });+ });++ // Desktop's reactions (backend reactions.ts): the person's own emoji counts+ // at once, the backend confirms it, and a change made anywhere reads the+ // page shown again so the counts match Desktop.+ group('reactions', () {+ const commands = '/api/super-tabs/$tab/commands';++ Map<String, dynamic> reacted(+ Map<String, dynamic> row,+ Map<String, List<(String, String)>> by,+ ) => {+ ...row,+ 'reactions': [+ for (final MapEntry(key: emoji, value: who) in by.entries)+ {+ 'emoji': emoji,+ 'count': who.length,+ 'by': [+ for (final (kind, id) in who) {'kind': kind, 'id': id},+ ],+ },+ ],+ };++ /// g1 at [sequence] with its reaction counter at [reactionSeq], as a+ /// change read brings it.+ Map<String, dynamic> moved(int version, int reactionSeq) => changes(+ cursor: 'c$version',+ groups: [+ part('g1', version, {+ ...groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: 2,+ ),+ 'reactionSeq': reactionSeq,+ }),+ ],+ );++ String counts(SwarmConversation c, String id) => [+ for (final r in c.reactionsOf(c.messages.firstWhere((m) => m.id == id)))+ '${r.emoji.key}:${[for (final who in r.by) who.id].join('+')}',+ ].join(' ');++ test('reacting counts the emoji at once, sends it, and reads the page '+ 'shown back', () async {+ final r = rig();+ var page = [message('m2', 2), message('m1', 1)];+ r.swarm.routes[messages] = (_) => {+ 'messages': page,+ 'next': null,+ 'reactionSeq': 0,+ };+ final sent = Completer<Object?>();+ r.swarm.routes[commands] = (_) => sent.future;+ final c = await open(r.reader);++ final reacting = c.react(c.messages.first, SuperTabReactionEmoji.tada);++ expect(counts(c, 'm1'), 'tada:$me');+ expect(r.swarm.commands.single, {+ 'type': 'message.react',+ 'conversationId': 'g1',+ 'messageId': 'm1',+ 'emoji': 'tada',+ 'on': true,+ });+ page = [+ message('m2', 2),+ reacted(message('m1', 1), {+ 'tada': [('agent', 'agent-lead'), ('person', me)],+ }),+ ];+ r.swarm.routes['$messages?before=3'] = (_) => {+ 'messages': page,+ 'next': null,+ 'reactionSeq': 2,+ };+ sent.complete({'result': <String, dynamic>{}});++ expect(await reacting, isTrue);+ expect(counts(c, 'm1'), 'tada:agent-lead+$me');+ expect(c.messages.first.reactions.single.count, 2);+ });++ test('reacting with your own emoji again takes it back', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [+ reacted(message('m1', 1), {+ 'heart': [('person', me), ('agent', 'agent-lead')],+ }),+ ],+ 'next': null,+ 'reactionSeq': 4,+ };+ final sent = Completer<Object?>();+ r.swarm.routes[commands] = (_) => sent.future;+ final c = await open(r.reader);++ final reacting = c.react(c.messages.single, SuperTabReactionEmoji.heart);++ expect(counts(c, 'm1'), 'heart:agent-lead');+ expect(r.swarm.commands.single['on'], isFalse);+ sent.complete({'result': <String, dynamic>{}});+ await reacting;+ });++ test('a refused reaction goes back and says why', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m1', 1)],+ 'next': null,+ 'reactionSeq': 0,+ };+ r.swarm.routes[commands] = (_) => throw SuperTabFailure(+ 'NOT_FOUND',+ 'This message is unavailable.',+ statusCode: 404,+ );+ final c = await open(r.reader);+ var told = 0;+ c.addListener(() => told++);++ expect(+ await c.react(c.messages.single, SuperTabReactionEmoji.eyes),+ isFalse,+ );++ expect(counts(c, 'm1'), '');+ expect(c.error, 'This message is unavailable.');+ expect(told, greaterThan(0));+ });++ test('a person who cannot post cannot react', () async {+ final r = rig(role: 'viewer');+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m1', 1)],+ 'next': null,+ };+ final c = await open(r.reader);++ expect(+ await c.react(c.messages.single, SuperTabReactionEmoji.eyes),+ isFalse,+ );+ expect(r.swarm.commands, isEmpty);+ });++ test('a reaction made elsewhere reads the page shown again; a Swarm read '+ 'that moved no counter reads nothing', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': null,+ 'reactionSeq': 0,+ };+ final c = await open(r.reader);+ await r.reader.refresh();+ await settle();+ expect(r.swarm.paths.where((p) => p.contains('before=')), isEmpty);++ r.swarm.routes['$messages?before=3'] = (_) => {+ 'messages': [+ message('m2', 2),+ reacted(message('m1', 1), {+ 'rocket': [('person', 'person-ann')],+ }),+ ],+ 'next': null,+ 'reactionSeq': 1,+ };+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => moved(30, 1);+ await r.reader.refresh();+ await settle();++ expect(counts(c, 'm1'), 'rocket:person-ann');+ await r.reader.refresh();+ await settle();+ expect(+ r.swarm.paths.where((p) => p.contains('before=')),+ hasLength(1),+ reason: 'the counter it read is the one the Swarm says',+ );+ });++ test('new messages that come with a moved counter read the page shown '+ 'again too', () async {+ final r = rig(sequence: 2);+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': null,+ 'reactionSeq': 0,+ };+ final c = await open(r.reader);+ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': [message('m3', 3)],+ 'next': null,+ 'reactionSeq': 1,+ };+ r.swarm.routes['$messages?before=4'] = (_) => {+ 'messages': [+ message('m3', 3),+ reacted(message('m2', 2), {+ 'laugh': [('agent', 'agent-lead')],+ }),+ message('m1', 1),+ ],+ 'next': null,+ 'reactionSeq': 1,+ };++ await c.load();++ expect([for (final m in c.messages) m.id], ['m1', 'm2', 'm3']);+ expect(counts(c, 'm2'), 'laugh:agent-lead');+ });++ test('a chat opened again reads its page again only when a reaction '+ 'changed while it was closed', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': null,+ 'reactionSeq': 3,+ };+ await r.reader.refresh();+ var c = SwarmConversation(r.reader, 'g1');+ await c.load();+ c.dispose();++ // Opened again with nothing changed: what was kept, and new messages+ // only.+ c = SwarmConversation(r.reader, 'g1');+ await c.load();+ await settle();+ expect(r.swarm.paths.where((p) => p.contains('before=')), isEmpty);+ c.dispose();++ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ 'reactionSeq': 5,+ };+ r.swarm.routes['$messages?before=3'] = (_) => {+ 'messages': [+ message('m2', 2),+ reacted(message('m1', 1), {+ 'thumbs_up': [('person', 'person-ann')],+ }),+ ],+ 'next': null,+ 'reactionSeq': 5,+ };+ c = SwarmConversation(r.reader, 'g1');+ addTearDown(c.dispose);+ await c.load();+ await settle();++ expect(counts(c, 'm1'), 'thumbs_up:person-ann');+ });+ });++ group('read marks', () {+ const read = '/api/super-tabs/$tab/conversations/g1/read';++ /// [r]'s Swarm with read marks the inbox would give it, and the marks it+ /// sends.+ ({SwarmReadMarks marks, List<Object?> sent}) marked(+ ({FakeSwarm swarm, SwarmReader reader}) r,+ ) {+ final marks = SwarmReadMarks(r.reader, store: null);+ r.reader.readMarks = marks;+ addTearDown(marks.dispose);+ final sent = <Object?>[];+ r.swarm.routes[read] = (body) {+ sent.add(body!['sequence']);+ return {'sequence': body['sequence']};+ };+ return (marks: marks, sent: sent);+ }++ /// A change read in which g1 moved on to [sequence].+ void moveOn(FakeSwarm swarm, int sequence) =>+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part(+ 'g1',+ 9 + sequence,+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: const ['agent-lead', 'agent-builder'],+ lastMessageSequence: sequence,+ ),+ ),+ ],+ );++ test('an open chat is read through its newest message, and again as '+ 'new ones come', () async {+ final r = rig();+ final m = marked(r);+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': null,+ };++ await open(r.reader);+ await settle();+ expect(m.sent, [2]);++ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': [message('m3', 3)],+ 'next': null,+ };+ moveOn(r.swarm, 3);+ await r.reader.refresh();+ await settle();++ expect(m.sent, [2, 3]);+ expect(m.marks.unread(r.reader.snapshot!.conversation('g1')!), isFalse);+ });++ test('a covered chat is not read until it shows again', () async {+ final r = rig();+ final m = marked(r);+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': null,+ };+ final c = await open(r.reader);+ await settle();++ c.shown = false;+ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': [message('m3', 3)],+ 'next': null,+ };+ moveOn(r.swarm, 3);+ await r.reader.refresh();+ await settle();+ expect(c.messages.last.id, 'm3');+ expect(m.sent, [2]);+ expect(m.marks.unread(r.reader.snapshot!.conversation('g1')!), isTrue);++ c.shown = true;+ await settle();++ expect(m.sent, [2, 3]);+ expect(m.marks.unread(r.reader.snapshot!.conversation('g1')!), isFalse);+ });++ test('a chat read before, opened again covered or at an earlier '+ 'message, marks nothing past what is seen of what it kept', () async {+ final r = rig();+ final m = marked(r);+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2), message('m1', 1)],+ 'next': null,+ };+ await r.reader.refresh();+ // Read while covered: kept, and not read.+ var c = SwarmConversation(r.reader, 'g1', shown: false);+ await c.load();+ c.dispose();+ await settle();+ expect(m.sent, isEmpty);++ c = SwarmConversation(r.reader, 'g1', shown: false);+ c.dispose();+ await settle();+ expect(m.sent, isEmpty, reason: 'covered from the start');++ c = SwarmConversation(r.reader, 'g1', heldAt: 'm1');+ addTearDown(c.dispose);+ await settle();+ expect(m.sent, [1], reason: 'only through the message it opened at');+ });++ test('a loaded chat whose newest message is a reply only in a thread is '+ 'not bold; a message in the main stream bolds it', () async {+ final r = rig();+ final m = marked(r);+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m2', 2)],+ 'next': null,+ };+ await r.reader.refresh();+ await settle();+ // Loaded while another screen covers it, so it marks nothing itself.+ final c = SwarmConversation(r.reader, 'g1', shown: false);+ addTearDown(c.dispose);+ await c.load();+ SuperTabConversation g1() => r.reader.snapshot!.conversation('g1')!;+ bool bold() => swarmChatNews(r.reader, null, g1()).bold;++ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': [+ {...message('m3', 3, text: 'in the thread'), 'thread': 'm2'},+ ],+ 'next': null,+ };+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part('g1', 30, {+ ...groupData('g1', title: 'Fix login', lastMessageSequence: 3),+ 'lastMainSequence': 2,+ }),+ ],+ );+ await r.reader.refresh();+ await settle();++ expect(c.messages.last.threadReply, isTrue, reason: 'loaded, last');+ expect(m.marks.unread(g1()), isFalse);+ expect(bold(), isFalse);++ r.swarm.routes['$messages?after=3'] = (_) => {+ 'messages': [message('m4', 4, text: 'in the chat')],+ 'next': null,+ };+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c4',+ groups: [+ part('g1', 31, {+ ...groupData('g1', title: 'Fix login', lastMessageSequence: 4),+ 'lastMainSequence': 4,+ }),+ ],+ );+ await r.reader.refresh();+ await settle();++ expect(c.messages.last.id, 'm4');+ expect(bold(), isTrue);+ expect(m.sent, isEmpty, reason: 'covered: it marked nothing');+ });++ test('a Swarm without read marks marks nothing', () async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {+ 'messages': [message('m1', 1)],+ 'next': null,+ };++ await open(r.reader);+ await settle();++ expect(r.swarm.paths.where((p) => p.endsWith('/read')), isEmpty);+ });+ });+}diff --git a/mobile/test/swarm/swarm_dictation_test.dart b/mobile/test/swarm/swarm_dictation_test.dartnew file mode 100644index 000000000..b89df4963--- /dev/null+++ b/mobile/test/swarm/swarm_dictation_test.dart@@ -0,0 +1,537 @@+import 'dart:math' as math;++import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_dictation.dart';++/// The phone's own recognizer as the chat reaches it: `harness/dictation`,+/// its native side answered here, and what it says routed to the take that+/// is listening — never to one already ended.+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ const channel = MethodChannel('harness/dictation');+ const codec = StandardMethodCodec();+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;++ /// What the native side was asked, and how it answers each method.+ late List<MethodCall> calls;+ late Map<String, Object? Function(MethodCall)> answers;++ setUp(() {+ calls = [];+ answers = {+ 'start': (_) => true,+ 'resume': (_) => true,+ 'access': (_) => 'allowed',+ };+ messenger.setMockMethodCallHandler(channel, (call) async {+ calls.add(call);+ return answers[call.method]?.call(call);+ });+ });+ tearDown(() => messenger.setMockMethodCallHandler(channel, null));++ /// The native side saying [method] about [take].+ Future<void> native(String method, int take, [Map<String, Object?>? more]) =>+ messenger.handlePlatformMessage(+ channel.name,+ codec.encodeMethodCall(MethodCall(method, {'take': take, ...?more})),+ (_) {},+ );++ /// What a take heard, in order.+ late List<Object> heard;++ Future<bool> start(SwarmChannelDictation dictation, [String? locale]) =>+ dictation.start(+ locale ?? 'vi-VN',+ onWords: (words) => heard.add(words),+ onLevel: (level) => heard.add(level),+ onEnd: (end) => heard.add(end),+ );++ setUp(() => heard = []);++ int take(MethodCall call) => (call.arguments as Map)['take'] as int;++ group('access', () {+ test('says what the person allowed', () async {+ final dictation = SwarmChannelDictation();+ for (final (answer, access) in [+ ('allowed', SwarmDictationAccess.allowed),+ ('noMic', SwarmDictationAccess.noMic),+ ('denied', SwarmDictationAccess.denied),+ ('restricted', SwarmDictationAccess.denied),+ ]) {+ answers['access'] = (_) => answer;+ expect(await dictation.access(), access, reason: answer);+ }+ });++ test('a native side that fails, or is not there, is a refusal', () async {+ final dictation = SwarmChannelDictation();+ answers['access'] = (_) => throw PlatformException(code: 'boom');+ expect(await dictation.access(), SwarmDictationAccess.denied);++ messenger.setMockMethodCallHandler(channel, null);+ expect(await dictation.access(), SwarmDictationAccess.denied);+ });+ });++ group('a take', () {+ test('listens in its locale, and hears its words, level and end', () async {+ final dictation = SwarmChannelDictation();+ expect(await start(dictation, 'ja-JP'), isTrue);+ final started = calls.single;+ expect(started.method, 'start');+ expect((started.arguments as Map)['locale'], 'ja-JP');+ final id = take(started);++ await native('words', id, {'text': 'こんにちは'});+ await native('level', id, {'rms': 0.1});+ await native('end', id, {'end': 'done'});+ await native('words', id, {'text': 'after the end'});++ expect(heard, ['こんにちは', isA<double>(), SwarmDictationEnd.done]);+ });++ test(+ 'ends as the native side says, and anything unknown is a failure',+ () async {+ final dictation = SwarmChannelDictation();+ for (final (end, expected) in [+ ('noSpeech', SwarmDictationEnd.noSpeech),+ ('failed', SwarmDictationEnd.failed),+ ('whatever', SwarmDictationEnd.failed),+ ]) {+ heard.clear();+ calls.clear();+ await start(dictation);+ await native('end', take(calls.single), {'end': end});+ expect(heard, [expected], reason: end);+ }+ },+ );++ test('stop asks for this take, whose end then comes once', () async {+ final dictation = SwarmChannelDictation();+ await start(dictation);+ final id = take(calls.single);++ await dictation.stop();+ expect(calls.last.method, 'stop');+ expect(take(calls.last), id);+ await native('end', id, {'end': 'done'});+ await native('end', id, {'end': 'failed'});++ expect(heard, [SwarmDictationEnd.done]);+ });++ test('a stop that fails ends the take as failed', () async {+ final dictation = SwarmChannelDictation();+ answers['stop'] = (_) => throw PlatformException(code: 'boom');+ await start(dictation);++ await dictation.stop();++ expect(heard, [SwarmDictationEnd.failed]);+ });++ test('cancel asks for this take, and nothing of it comes after', () async {+ final dictation = SwarmChannelDictation();+ await start(dictation);+ final id = take(calls.single);++ await dictation.cancel();+ expect(calls.last.method, 'cancel');+ expect(take(calls.last), id);+ await native('words', id, {'text': 'late'});+ await native('end', id, {'end': 'done'});++ expect(heard, isEmpty);+ });++ test('a cancel that fails is still a cancel', () async {+ final dictation = SwarmChannelDictation();+ answers['cancel'] = (_) => throw PlatformException(code: 'boom');+ await start(dictation);+ final id = take(calls.single);++ await dictation.cancel();+ await native('words', id, {'text': 'late'});++ expect(heard, isEmpty);+ });++ test('an earlier take\'s words land nowhere in the next one', () async {+ final dictation = SwarmChannelDictation();+ await start(dictation);+ final first = take(calls.single);+ await dictation.cancel();+ await start(dictation);+ final second = take(calls.last);+ expect(second, isNot(first));++ await native('words', first, {'text': 'old'});+ await native('words', second, {'text': 'new'});++ expect(heard, ['new']);+ });++ test(+ 'without the locale, or failing to start, it does not listen',+ () async {+ final dictation = SwarmChannelDictation();+ answers['start'] = (_) => false;+ expect(await start(dictation), isFalse);+ await native('words', take(calls.last), {'text': 'nothing'});++ answers['start'] = (_) => throw PlatformException(code: 'boom');+ expect(await start(dictation), isFalse);+ await native('words', take(calls.last), {'text': 'nothing'});++ expect(heard, isEmpty);+ },+ );++ test('what it says without a take, or malformed, is ignored', () async {+ final dictation = SwarmChannelDictation();+ await start(dictation);+ final id = take(calls.single);++ await messenger.handlePlatformMessage(+ channel.name,+ codec.encodeMethodCall(const MethodCall('words', 'text')),+ (_) {},+ );+ await native('words', id, {'text': 42});+ await native('level', id, {'rms': 'loud'});++ expect(heard, isEmpty);+ });+ });++ group('the words of a take', () {+ /// What [start] heard last: every word so far.+ String said() => heard.whereType<String>().last;++ late SwarmChannelDictation dictation;+ late int id;++ setUp(() async {+ dictation = SwarmChannelDictation();+ await start(dictation);+ id = take(calls.single);+ });++ /// The recognizer's latest best guess at what is being said: [from] and+ /// [to] where its words begin and end in the take's audio (0 where it+ /// does not say), [finished] when it says that guess is done.+ Future<void> guess(+ String text, {+ double from = 0,+ double to = 0,+ bool finished = false,+ }) => native('words', id, {+ 'text': text,+ 'final': finished,+ 'from': from,+ 'to': to,+ });++ // Tony, 10-29: 'một hai ba bốn năm' came out as 'Một 2 12345'.+ test('each guess replaces the last, however it is rewritten', () async {+ await guess('1', from: 0.4, to: 0.8);+ await guess('Một 2', from: 0.4, to: 1.2);+ await guess('123', from: 0.4, to: 1.6);+ await guess('1234', from: 0.4, to: 2.0);+ await guess('12345', from: 0.4, to: 2.4);+ expect(said(), '12345');+ });++ test('each guess replaces the last where it says no times', () async {+ await guess('1');+ await guess('Một 2');+ await guess('Một hai ba');+ expect(said(), 'Một hai ba');+ await guess('123');+ expect(said(), '123');+ });++ test('a guess with times after one without replaces it, unless that one '+ 'was finished', () async {+ await guess('1');+ await guess('Một 2', from: 0.4, to: 1.2);+ expect(said(), 'Một 2');++ await guess('Một hai.', finished: true);+ await guess('Ba', from: 3.0, to: 3.3);+ expect(said(), 'Một hai. Ba');+ });++ test('a finished sentence, then new words after a pause, keeps the '+ 'sentence exactly once', () async {+ await guess('Hôm nay mình làm gì', from: 0.3, to: 2.0);+ await guess('Hôm nay mình làm gì.', from: 0.3, to: 2.1, finished: true);+ await guess('Ngày', from: 3.6, to: 3.9);+ expect(said(), 'Hôm nay mình làm gì. Ngày');+ await guess('Ngày mai', from: 3.6, to: 4.3);+ expect(said(), 'Hôm nay mình làm gì. Ngày mai');+ });++ test(+ 'a finished sentence, then new words, where it says no times',+ () async {+ await guess('Hôm nay mình làm gì.', finished: true);+ await guess('Ngày');+ await guess('Ngày mai');+ expect(said(), 'Hôm nay mình làm gì. Ngày mai');+ },+ );++ test('words that start after the last ended are new, though nothing '+ 'said the last was finished', () async {+ await guess('hôm nay mình làm', from: 0.3, to: 2.0);+ await guess('gì', from: 3.4, to: 3.6);+ expect(said(), 'hôm nay mình làm gì');+ await guess('gì nữa', from: 3.4, to: 4.0);+ expect(said(), 'hôm nay mình làm gì nữa');+ });++ test('a guess said to be finished and then revised is replaced, not '+ 'repeated', () async {+ await guess('1', from: 0.4, to: 0.8, finished: true);+ await guess('Một 2', from: 0.4, to: 1.2);+ expect(said(), 'Một 2');+ });++ test('a recognizer that says everything again after a finished sentence '+ 'is not doubled', () async {+ await guess('Hôm nay', from: 0.3, to: 1.0, finished: true);+ await guess('Hôm nay mình', from: 0.3, to: 1.5);+ expect(said(), 'Hôm nay mình');++ await guess('Hôm nay mình.', finished: true);+ await guess('Hôm nay mình làm');+ expect(said(), 'Hôm nay mình làm', reason: 'where it says no times');+ });++ test('the last words, as the take stops, come once', () async {+ await guess('một hai', from: 0.3, to: 1.0);+ await guess('Một hai.', from: 0.3, to: 1.0, finished: true);+ expect(said(), 'Một hai.');+ });++ test('keeps nothing from one take for the next', () async {+ await guess('Một hai ba.', from: 0.3, to: 1.5, finished: true);+ await guess('bốn', from: 2.5, to: 2.8);+ await dictation.cancel();++ await start(dictation);+ id = take(calls.last);+ await guess('năm', from: 0.3, to: 0.6);++ expect(said(), 'năm');+ });+ });++ test('the long-press language as the recognizer\'s locale', () {+ expect(swarmDictationLocale('vi'), 'vi-VN');+ expect(swarmDictationLocale('en'), 'en-US');+ expect(swarmDictationLocale('es'), 'es-ES');+ expect(swarmDictationLocale('fr'), 'fr-FR');+ expect(swarmDictationLocale('ja'), 'ja-JP');+ expect(swarmDictationLocale('it'), 'it-IT');+ expect(+ swarmDictationLocale('xx'),+ 'vi-VN',+ reason: 'Vietnamese by default',+ );+ });++ group('a take listens until it is stopped (Tony, 10-29)', () {+ /// What [start] heard last: every word so far.+ String said() => heard.whereType<String>().last;++ var now = DateTime(2026, 10, 29, 9);+ late SwarmChannelDictation dictation;+ late int id;++ setUp(() async {+ now = DateTime(2026, 10, 29, 9);+ dictation = SwarmChannelDictation(clock: () => now);+ await start(dictation);+ id = take(calls.single);+ });++ Future<void> guess(+ String text, {+ double from = 0,+ double to = 0,+ bool finished = false,+ }) => native('words', id, {+ 'text': text,+ 'final': finished,+ 'from': from,+ 'to': to,+ });++ /// The recognizer ending its session by itself, the microphone still on.+ Future<void> paused([String end = 'done']) =>+ native('paused', id, {'end': end});++ List<MethodCall> resumes() =>+ calls.where((call) => call.method == 'resume').toList();++ test('a session the recognizer ends by itself is resumed at once, its '+ 'words kept', () async {+ await guess('Hôm nay mình làm gì.', from: 0.3, to: 2.1, finished: true);+ await paused();+ expect(resumes().single.arguments, {'take': id});++ // A new session's times start again from nothing.+ await guess('Ngày', from: 0.2, to: 0.5);+ await guess('Ngày mai', from: 0.2, to: 0.9);+ expect(said(), 'Hôm nay mình làm gì. Ngày mai');+ expect(heard.whereType<SwarmDictationEnd>(), isEmpty);+ });++ test('a session that ends on a guess it never finished keeps it', () async {+ await guess('hôm nay mình', from: 0.3, to: 1.2);+ await paused('noSpeech');+ await guess('làm gì', from: 0.1, to: 0.6);+ expect(said(), 'hôm nay mình làm gì');+ });++ test('a long silence, session after session, keeps listening', () async {+ await guess('một', from: 0.3, to: 0.6);+ for (var i = 0; i < 6; i++) {+ now = now.add(const Duration(seconds: 20));+ await paused('noSpeech');+ }+ expect(resumes(), hasLength(6));+ expect(heard.whereType<SwarmDictationEnd>(), isEmpty);+ await guess('hai', from: 0.2, to: 0.5);+ expect(said(), 'một hai');+ });++ test('sessions that keep ending at once, hearing nothing, are given up: '+ 'the take ends as failed, its words kept', () async {+ await guess('một', from: 0.3, to: 0.6);+ await paused();+ await paused('failed');+ now = now.add(const Duration(milliseconds: 900));+ await paused('failed');++ expect(heard.whereType<SwarmDictationEnd>(), [SwarmDictationEnd.failed]);+ expect(resumes(), hasLength(2));+ expect(calls.last.method, 'cancel');+ expect(said(), 'một');+ await paused();+ expect(resumes(), hasLength(2), reason: 'given up for good');+ });++ test('words between sessions that end quickly keep it going', () async {+ for (final word in ['một', 'hai', 'ba', 'bốn']) {+ await guess(word, from: 0.1, to: 0.3);+ await paused();+ }+ expect(heard.whereType<SwarmDictationEnd>(), isEmpty);+ expect(said(), 'một hai ba bốn');+ });++ test('a resume the phone refuses ends the take as failed', () async {+ answers['resume'] = (_) => false;+ await guess('một', from: 0.3, to: 0.6);+ await paused();++ expect(heard.whereType<SwarmDictationEnd>(), [SwarmDictationEnd.failed]);+ expect(calls.last.method, 'cancel');+ });++ test('a resume that fails ends the take as failed', () async {+ answers['resume'] = (_) => throw PlatformException(code: 'boom');+ await paused();++ expect(heard.whereType<SwarmDictationEnd>(), [SwarmDictationEnd.failed]);+ });++ test('a session ending as the take stops is not resumed', () async {+ await guess('một hai', from: 0.3, to: 0.9);+ await dictation.stop();+ await paused();+ await native('end', id, {'end': 'done'});++ expect(resumes(), isEmpty);+ expect(heard.whereType<SwarmDictationEnd>(), [SwarmDictationEnd.done]);+ expect(said(), 'một hai');+ });++ test('an earlier take\'s session ending is not resumed', () async {+ await dictation.cancel();+ await start(dictation);+ await paused();++ expect(resumes(), isEmpty);+ });+ });++ group('the level the wave follows (Tony, 10-29: "a live wave")', () {+ late SwarmChannelDictation dictation;+ late int id;++ setUp(() async {+ dictation = SwarmChannelDictation();+ await start(dictation);+ id = take(calls.single);+ });++ /// The microphone at [db] dBFS, [times] buffers of a tenth of a second.+ Future<void> sound(double db, [int times = 1]) async {+ for (var i = 0; i < times; i++) {+ await native('level', id, {'rms': math.pow(10, db / 20)});+ }+ }++ double last() => heard.whereType<double>().last;++ test('a voice above the room fills the wave and the room alone leaves it '+ 'low, however loud the microphone takes them', () async {+ for (final (room, voice) in [(-70.0, -45.0), (-40.0, -15.0)]) {+ await dictation.cancel();+ await start(dictation);+ id = take(calls.last);+ await sound(room, 30);+ expect(last(), lessThan(0.05), reason: 'the room at $room dB');+ await sound(voice);+ expect(last(), greaterThan(0.6), reason: 'a voice at $voice dB');+ await sound(room + 2);+ expect(last(), lessThan(0.05), reason: 'the room again');+ }+ });++ test(+ 'the click the microphone opens on is forgotten within seconds',+ () async {+ await sound(-95);+ await sound(-50, 35);+ expect(last(), lessThan(0.05));+ },+ );++ test('a room that grows louder is followed', () async {+ await sound(-60, 30);+ await sound(-45, 35);+ expect(last(), lessThan(0.05));+ });++ test('near-digital silence never moves the wave', () async {+ await sound(-100, 30);+ await sound(-80);+ expect(last(), 0);+ await native('level', id, {'rms': 0});+ expect(last(), 0);+ });+ });+}diff --git a/mobile/test/swarm/swarm_face_test.dart b/mobile/test/swarm/swarm_face_test.dartnew file mode 100644index 000000000..236d8949d--- /dev/null+++ b/mobile/test/swarm/swarm_face_test.dart@@ -0,0 +1,245 @@+import 'dart:convert';+import 'dart:typed_data';++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_face.dart';+import 'package:harness_mobile/swarm/swarm_message_row.dart';+import 'package:harness_mobile/swarm/swarm_style.dart';++/// A 1×1 PNG: what a picture that loads decodes to.+final pixel = base64Decode(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',+);++/// Links the face asked a picture for.+final asked = <Uri>[];++Future<void> show(WidgetTester tester, Widget child, {List<int>? bytes}) {+ asked.clear();+ final images = <Uri, ImageProvider>{};+ return tester.pumpWidget(+ MaterialApp(+ home: SwarmAvatarImages(+ image: (url) {+ if (!asked.contains(url)) asked.add(url);+ // One picture per link, as a network image is; bytes that are no+ // picture fail to decode, as a dead link fails.+ return images[url] ??= MemoryImage(+ Uint8List.fromList(bytes ?? [1, 2, 3]),+ );+ },+ child: Scaffold(body: Center(child: child)),+ ),+ ),+ );+}++/// Lets the picture decode, which happens outside the test's fake time:+/// until [done] holds, or for [rounds] turns when nothing is to appear.+Future<void> decode(+ WidgetTester tester, {+ bool Function()? done,+ int rounds = 100,+}) async {+ for (var i = 0; i < rounds && !(done?.call() ?? false); i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump();+ }+ if (done != null) expect(done(), isTrue, reason: 'the picture never showed');+}++final photo = SuperTabUploadedAvatar.of(+ 'https://storage.googleapis.com/avatars/me.png?sig=1',+)!;++/// The one face a person or an agent wears on the phone: their picture, the+/// built-in one they picked, or their initial when they have neither — and a+/// person's status emoji while it lasts.+void main() {+ testWidgets('a built-in picture shows instead of the initial', (+ tester,+ ) async {+ await show(+ tester,+ const SwarmAvatar(+ id: 'agent-1',+ name: 'Nova',+ picture: SuperTabPresetAvatar('fox'),+ ),+ );+ expect(find.text('🦊'), findsOneWidget);+ expect(find.text('N'), findsNothing);+ });++ testWidgets('no picture shows the initial', (tester) async {+ await show(tester, const SwarmAvatar(id: 'agent-1', name: 'Nova'));+ expect(find.text('N'), findsOneWidget);+ });++ testWidgets('an uploaded picture loads from its signed link', (tester) async {+ await tester.runAsync(+ () => show(+ tester,+ SwarmAvatar(id: 'person-1', name: 'tony', picture: photo),+ bytes: pixel,+ ),+ );+ await decode(+ tester,+ done: () => find.byType(RawImage).evaluate().isNotEmpty,+ );+ expect(asked, [+ Uri.parse('https://storage.googleapis.com/avatars/me.png?sig=1'),+ ]);+ expect(find.text('T'), findsNothing);+ });++ testWidgets('an uploaded picture that cannot load shows the initial', (+ tester,+ ) async {+ await tester.runAsync(+ () => show(+ tester,+ SwarmAvatar(id: 'person-1', name: 'tony', picture: photo),+ ),+ );+ // Shown as the initial while it loads, and after it fails.+ expect(find.text('T'), findsOneWidget);+ await decode(tester, rounds: 20);+ expect(find.text('T'), findsOneWidget);+ });++ testWidgets('a chat avatar shows the built-in picture too', (tester) async {+ await show(+ tester,+ const SwarmChatAvatar(+ name: 'tony',+ id: 'person-1',+ agent: false,+ picture: SuperTabPresetAvatar('rocket'),+ ),+ );+ expect(find.text('🚀'), findsOneWidget);+ expect(find.text('T'), findsNothing);+ });++ testWidgets('a chat avatar keeps the colour it always had, in both themes', (+ tester,+ ) async {+ // The chat's colours before they came from the member palette: the PM's+ // blue, then the six an agent takes by its id; a person's one fill.+ const agents = [+ Color(0xFF1D5BD6),+ Color(0xFF0F766E),+ Color(0xFF6D28D9),+ Color(0xFFA65A08),+ Color(0xFFBE123C),+ Color(0xFF15803D),+ Color(0xFF4E5D78),+ ];+ const person = Color(0xFF4B5F9B);+ Color? fill() =>+ (tester+ .widget<Container>(+ find.descendant(+ of: find.byType(SwarmChatAvatar),+ matching: find.byWidgetPredicate(+ (w) =>+ w is Container &&+ (w.decoration as BoxDecoration?)?.shape ==+ BoxShape.circle,+ ),+ ),+ )+ .decoration+ as BoxDecoration)+ .color;+ final previous = AppTheme.brightness.value;+ addTearDown(() => AppTheme.brightness.value = previous);+ for (final brightness in Brightness.values) {+ AppTheme.brightness.value = brightness;+ // 'a' to 'f' land on each of the six agent colours once.+ for (final id in ['a', 'b', 'c', 'd', 'e', 'f', 'agent-lead']) {+ await show(tester, SwarmChatAvatar(name: 'River', id: id, agent: true));+ final sum = id.codeUnits.fold(0, (a, b) => a + b);+ expect(fill(), agents[1 + sum % 6], reason: '$id, $brightness');+ }+ await show(+ tester,+ const SwarmChatAvatar(name: 'River', id: 'a', agent: true, pm: true),+ );+ expect(fill(), agents.first, reason: 'the PM, $brightness');+ await show(+ tester,+ const SwarmChatAvatar(name: 'Tony', id: 'person-1', agent: false),+ );+ expect(fill(), person, reason: 'a person, $brightness');+ }+ });++ testWidgets('a status shows its emoji and is read with the name', (+ tester,+ ) async {+ final handle = tester.ensureSemantics();+ await show(+ tester,+ SwarmAvatar(+ id: 'person-1',+ name: 'tony',+ status: SuperTabPersonStatus(+ text: 'Focusing',+ emoji: '🎯',+ until: clock.now().add(const Duration(hours: 1)),+ ),+ ),+ );+ expect(find.text('🎯'), findsOneWidget);+ expect(find.bySemanticsLabel('tony, 🎯 Focusing'), findsOneWidget);+ handle.dispose();+ });++ testWidgets('a status disappears by itself when its time passes', (+ tester,+ ) async {+ await show(+ tester,+ SwarmChatAvatar(+ name: 'tony',+ id: 'person-1',+ agent: false,+ status: SuperTabPersonStatus(+ text: 'At lunch',+ emoji: '🍽️',+ until: clock.now().add(const Duration(minutes: 30)),+ ),+ ),+ );+ expect(find.text('🍽️'), findsOneWidget);+ await tester.pump(const Duration(minutes: 29));+ expect(find.text('🍽️'), findsOneWidget);+ await tester.pump(const Duration(minutes: 1, seconds: 1));+ expect(find.text('🍽️'), findsNothing);+ });++ testWidgets('a status that has already ended shows nothing', (tester) async {+ await show(+ tester,+ SwarmAvatar(+ id: 'person-1',+ name: 'tony',+ status: SuperTabPersonStatus(+ text: 'Away',+ emoji: '🚶',+ until: clock.now().subtract(const Duration(minutes: 1)),+ ),+ ),+ );+ expect(find.text('🚶'), findsNothing);+ });+}diff --git a/mobile/test/swarm/swarm_faces_screens_test.dart b/mobile/test/swarm/swarm_faces_screens_test.dartnew file mode 100644index 000000000..ff30992de--- /dev/null+++ b/mobile/test/swarm/swarm_faces_screens_test.dart@@ -0,0 +1,206 @@+import 'dart:typed_data';++import 'package:flutter/material.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/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_face.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_style.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++const leadPhoto = 'https://storage.googleapis.com/avatars/river.png?sig=1';+const buddyPhoto = 'https://storage.googleapis.com/avatars/wren.png?sig=1';++/// The faces people and agents chose, on the screens that showed only+/// initials: Home's Buddies, the project page's work and team, and the+/// chat's messages — with a person's status emoji beside their own.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';++ /// With [buddy], the person's Buddy Wren wears an uploaded photo in its+ /// chat.+ FakeSwarm backend({bool buddy = false}) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ final derived = {+ 'avatars': {+ 'agent:agent-lead': leadPhoto,+ if (buddy) 'agent:agent-wren': buddyPhoto,+ },+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ derived: derived,+ agents: [+ {+ ...agent('agent-lead', name: 'Lead', displayName: 'River'),+ 'avatar': {'kind': 'upload'},+ },+ {+ ...agent('agent-builder', displayName: 'Nova'),+ 'avatar': {'kind': 'preset', 'key': 'owl'},+ },+ agent('agent-plain', displayName: 'Pike'),+ if (buddy)+ {+ ...buddyData('agent-wren', displayName: 'Wren'),+ 'avatar': {'kind': 'upload'},+ },+ ],+ groups: [+ if (buddy) buddyChatData('buddy-me', agentIds: ['agent-wren']),+ groupData(+ 'g1',+ title: 'Fix login',+ number: 4,+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ ),+ groupData(+ 'g2',+ title: 'Sync',+ number: 5,+ agentIds: ['agent-plain'],+ status: 'working',+ workerId: 'agent-plain',+ ),+ ],+ ),+ 'members': [+ part(me, 1, {+ ...person(me),+ 'avatar': {'kind': 'preset', 'key': 'fox'},+ 'status': {'text': 'Focusing', 'emoji': '🎯', 'until': null},+ }),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/groups'] = (_) => {+ 'groups': <Object>[],+ 'next': null,+ };+ fake.routes[messages] = (_) => {+ 'messages': [+ {+ 'id': 'msg-1',+ 'conversationId': 'g1',+ 'text': 'Which name should the flag have?',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'createdAt': '2026-10-27T01:00:00.000Z',+ },+ {+ 'id': 'msg-2',+ 'conversationId': 'g1',+ 'text': 'Call it beta.',+ 'sequence': 2,+ 'author': {'kind': 'person', 'id': me, 'name': '[email protected]'},+ 'createdAt': '2026-10-27T01:01:00.000Z',+ },+ ],+ 'next': null,+ };+ return fake;+ }++ /// Links an uploaded picture was asked from.+ final asked = <Uri>[];++ Future<void> pump(+ WidgetTester tester,+ Widget home, {+ bool buddy = false,+ }) async {+ asked.clear();+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend(buddy: buddy).request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ )..foreground = false;+ addTearDown(host.dispose);+ final images = <Uri, ImageProvider>{};+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(+ notifier: host,+ child: SwarmAvatarImages(+ image: (url) {+ if (!asked.contains(url)) asked.add(url);+ return images[url] ??= MemoryImage(Uint8List(0));+ },+ child: child!,+ ),+ ),+ home: home,+ ),+ );+ // A skeleton breathes while it shows: frames until the page is read.+ for (var i = 0; i < 20; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ }++ Finder within(String key, Finder finder) =>+ find.descendant(of: find.byKey(ValueKey(key)), matching: finder);++ testWidgets("Home's Buddies show the Buddy's uploaded picture", (+ tester,+ ) async {+ tester.view.physicalSize = const Size(1170, 2532);+ addTearDown(tester.view.reset);+ await pump(tester, const SwarmPage(), buddy: true);+ expect(+ within('swarm-home-buddy-$tab-$project', find.byType(SwarmAvatar)),+ findsOneWidget,+ );+ expect(asked, [Uri.parse(buddyPhoto)]);+ });++ testWidgets("the project's work shows each worker's chosen face", (+ tester,+ ) async {+ tester.view.physicalSize = const Size(1170, 2532);+ addTearDown(tester.view.reset);+ await pump(+ tester,+ const SwarmProjectPage(swarmId: tab, projectId: project),+ );+ await tester.tap(find.byKey(const ValueKey('swarm-project-menu')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('swarm-project-menu-status')));+ await tester.pumpAndSettle();+ expect(within('swarm-conversation-g1', find.text('🦉')), findsOneWidget);+ // Nobody chose one: the initial, as before.+ expect(within('swarm-conversation-g2', find.text('P')), findsOneWidget);+ expect(within('swarm-conversation-g2', find.text('🦉')), findsNothing);+ });++ testWidgets("a chat shows each author's face and a person's status", (+ tester,+ ) async {+ await pump(+ tester,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ expect(within('swarm-message-msg-1', find.text('🦉')), findsOneWidget);+ expect(within('swarm-message-msg-2', find.text('🦊')), findsOneWidget);+ expect(within('swarm-message-msg-2', find.text('🎯')), findsOneWidget);+ expect(within('swarm-message-msg-1', find.text('🎯')), findsNothing);+ });+}diff --git a/mobile/test/swarm/swarm_file_picker_test.dart b/mobile/test/swarm/swarm_file_picker_test.dartnew file mode 100644index 000000000..a2827615e--- /dev/null+++ b/mobile/test/swarm/swarm_file_picker_test.dart@@ -0,0 +1,373 @@+import 'dart:io';++import 'package:image_picker/image_picker.dart' show XFile;+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_file_picker.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';++/// What the phone Swarm chat's attach sheet picks: the photo library (several at once), the camera+/// and the system's file picker, read into the chat's [SwarmOutgoingFiles] by Desktop's limits,+/// with each picker's own copy of the file deleted once read.+void main() {+ late Directory folder;+ late SwarmOutgoingFiles files;+ late Directory elsewhere;+ final original = (+ photos: pickSwarmPhotos,+ camera: takeSwarmPhoto,+ documents: pickSwarmFiles,+ copies: swarmPickerCopyFolders,+ );++ setUp(() {+ folder = Directory.systemTemp.createTempSync('swarm-picker-test');+ elsewhere = Directory.systemTemp.createTempSync('swarm-picker-original');+ files = SwarmOutgoingFiles();+ // The app's own temporary folder, where the pickers leave their copies.+ swarmPickerCopyFolders = () async => [folder.path];+ });+ tearDown(() {+ files.dispose();+ for (final dir in [folder, elsewhere]) {+ if (dir.existsSync()) dir.deleteSync(recursive: true);+ }+ pickSwarmPhotos = original.photos;+ takeSwarmPhoto = original.camera;+ pickSwarmFiles = original.documents;+ swarmPickerCopyFolders = original.copies;+ });++ /// A picker's copy of a file, on disk as the pickers leave it.+ XFile copy(String name, int size) {+ final file = File('${folder.path}/$name')+ ..writeAsBytesSync(Uint8List(size)..fillRange(0, size, 7));+ return XFile(file.path, name: name);+ }++ /// A copy past the limit, made without writing ten megabytes.+ XFile bigCopy(String name) {+ final file = File('${folder.path}/$name')..createSync();+ file.openSync(mode: FileMode.write)+ ..setPositionSync(0)+ ..truncateSync(swarmAttachmentMaxBytes + 1)+ ..closeSync();+ return XFile(file.path, name: name);+ }++ List<String> names() => [for (final f in files.files) f.name];++ group('photo library', () {+ test('adds every photo picked, named photo.jpg, photo-2.jpg…', () async {+ pickSwarmPhotos = (limit) async => [+ copy('image_picker_A1B2.jpg', 3),+ copy('image_picker_C3D4.jpg', 4),+ ];++ final outcome = await addSwarmPicked(files, SwarmPickSource.library);++ expect(outcome, isA<SwarmPicked>());+ expect((outcome as SwarmPicked).note, isNull);+ expect(names(), ['photo.jpg', 'photo-2.jpg']);+ expect([for (final f in files.files) f.bytes.length], [3, 4]);+ });++ test('keeps a photo’s own kind in its name', () async {+ pickSwarmPhotos = (limit) async => [copy('scaled_1.png', 2)];++ await addSwarmPicked(files, SwarmPickSource.library);++ expect(names(), ['photo.png']);+ });++ test('numbers a photo beside one already attached', () async {+ files.add([SwarmOutgoingFile('photo.jpg', Uint8List(1))]);+ pickSwarmPhotos = (limit) async => [copy('x.jpg', 2)];++ await addSwarmPicked(files, SwarmPickSource.library);++ expect(names(), ['photo.jpg', 'photo-2.jpg']);+ });++ test('asks for no more photos than there is room for', () async {+ files.add([+ for (var i = 0; i < 7; i++) SwarmOutgoingFile('f$i.txt', Uint8List(1)),+ ]);+ int? asked;+ pickSwarmPhotos = (limit) async {+ asked = limit;+ return [];+ };++ await addSwarmPicked(files, SwarmPickSource.library);++ expect(asked, 3);+ });++ test('deletes the picker’s copies once they are read', () async {+ final picked = [copy('a.jpg', 3), copy('b.jpg', 3)];+ pickSwarmPhotos = (limit) async => picked;++ await addSwarmPicked(files, SwarmPickSource.library);++ expect(+ [for (final x in picked) File(x.path).existsSync()],+ [false, false],+ );+ });++ test('backing out of the picker adds nothing and says nothing', () async {+ pickSwarmPhotos = (limit) async => [];++ final outcome = await addSwarmPicked(files, SwarmPickSource.library);++ expect((outcome as SwarmPicked).note, isNull);+ expect(files.files, isEmpty);+ });++ test('refused access to photos asks for Settings', () async {+ pickSwarmPhotos = (limit) async =>+ throw PlatformException(code: 'photo_access_denied');++ final outcome = await addSwarmPicked(files, SwarmPickSource.library);++ expect(outcome, isA<SwarmPickDenied>());+ expect((outcome as SwarmPickDenied).source, SwarmPickSource.library);+ });++ test('a photo over 10 MB is named and left out', () async {+ final big = bigCopy('big.jpg');+ pickSwarmPhotos = (limit) async => [big, copy('ok.jpg', 2)];++ final outcome = await addSwarmPicked(files, SwarmPickSource.library);++ expect((outcome as SwarmPicked).note, 'photo.jpg is over 10 MB.');+ expect(names(), ['photo-2.jpg']);+ expect(File(big.path).existsSync(), isFalse);+ });+ });++ group('camera', () {+ test('adds the photo taken', () async {+ takeSwarmPhoto = () async => copy('image_picker_E5.jpg', 5);++ final outcome = await addSwarmPicked(files, SwarmPickSource.camera);++ expect((outcome as SwarmPicked).note, isNull);+ expect(names(), ['photo.jpg']);+ });++ test('refused camera access asks for Settings and adds nothing', () async {+ takeSwarmPhoto = () async =>+ throw PlatformException(code: 'camera_access_denied');++ final outcome = await addSwarmPicked(files, SwarmPickSource.camera);++ expect((outcome as SwarmPickDenied).source, SwarmPickSource.camera);+ expect(files.files, isEmpty);+ });++ test('a camera that cannot open says so', () async {+ takeSwarmPhoto = () async => throw PlatformException(code: 'no_camera');++ final outcome = await addSwarmPicked(files, SwarmPickSource.camera);++ expect(+ (outcome as SwarmPickFailed).message,+ 'Could not open the camera.',+ );+ });++ test('cancelling the camera says nothing', () async {+ takeSwarmPhoto = () async => null;++ final outcome = await addSwarmPicked(files, SwarmPickSource.camera);++ expect((outcome as SwarmPicked).note, isNull);+ expect(files.files, isEmpty);+ });+ });++ group('files', () {+ test('adds the files picked under their own names', () async {+ final picked = [copy('crash.log', 12), copy('report.pdf', 20)];+ pickSwarmFiles = () async => picked;++ final outcome = await addSwarmPicked(files, SwarmPickSource.files);++ expect((outcome as SwarmPicked).note, isNull);+ expect(names(), ['crash.log', 'report.pdf']);+ expect(+ [for (final x in picked) File(x.path).existsSync()],+ [false, false],+ );+ });++ test('a file over 10 MB is refused before it is read', () async {+ final big = bigCopy('big.zip');+ pickSwarmFiles = () async => [big, copy('ok.txt', 2)];++ final outcome = await addSwarmPicked(files, SwarmPickSource.files);++ expect((outcome as SwarmPicked).note, 'big.zip is over 10 MB.');+ expect(names(), ['ok.txt']);+ expect(File(big.path).existsSync(), isFalse);+ });++ test('files past the tenth are left out and counted', () async {+ files.add([+ for (var i = 0; i < 9; i++) SwarmOutgoingFile('f$i.txt', Uint8List(1)),+ ]);+ pickSwarmFiles = () async => [copy('a.txt', 1), copy('b.txt', 1)];++ final outcome = await addSwarmPicked(files, SwarmPickSource.files);++ expect((outcome as SwarmPicked).note, 'Attach at most 10 files.');+ expect(files.files, hasLength(10));+ });++ test('a file that cannot be read is named', () async {+ pickSwarmFiles = () async => [+ XFile('${folder.path}/gone.txt', name: 'gone.txt'),+ ];++ final outcome = await addSwarmPicked(files, SwarmPickSource.files);++ expect((outcome as SwarmPicked).note, 'Could not read gone.txt.');+ expect(files.files, isEmpty);+ });++ test('a picker that cannot open says so', () async {+ pickSwarmFiles = () async => throw PlatformException(code: 'error');++ final outcome = await addSwarmPicked(files, SwarmPickSource.files);++ expect(+ (outcome as SwarmPickFailed).message,+ 'Could not open the picker.',+ );+ });+ });++ test('with ten files attached no picker opens', () async {+ files.add([+ for (var i = 0; i < 10; i++) SwarmOutgoingFile('f$i.txt', Uint8List(1)),+ ]);+ var opened = false;+ pickSwarmFiles = () async {+ opened = true;+ return [];+ };++ final outcome = await addSwarmPicked(files, SwarmPickSource.files);++ expect((outcome as SwarmPickFailed).message, 'Attach at most 10 files.');+ expect(opened, isFalse);+ });++ test('a chat closed while the picker was up takes nothing, and the copies '+ 'are deleted', () async {+ final picked = [copy('a.jpg', 3)];+ pickSwarmPhotos = (limit) async => picked;++ final outcome = await addSwarmPicked(+ files,+ SwarmPickSource.library,+ stillWanted: () => false,+ );++ expect((outcome as SwarmPicked).note, isNull);+ expect(files.files, isEmpty);+ expect(File(picked.single.path).existsSync(), isFalse);+ });++ group('only the pickers\' own copies are deleted', () {+ test(+ 'a file outside the app\'s temporary folder is read and kept',+ () async {+ final file = File('${elsewhere.path}/original.pdf')+ ..writeAsBytesSync([1, 2, 3]);+ pickSwarmFiles = () async => [XFile(file.path)];++ await addSwarmPicked(files, SwarmPickSource.files);++ expect(names(), ['original.pdf']);+ expect(file.existsSync(), isTrue);+ },+ );++ test('a path that only starts like the temporary folder is kept', () async {+ final sibling = Directory('${folder.path}-sibling')..createSync();+ addTearDown(() => sibling.deleteSync(recursive: true));+ final file = File('${sibling.path}/a.jpg')..writeAsBytesSync([1]);+ pickSwarmPhotos = (limit) async => [XFile(file.path)];++ await addSwarmPicked(files, SwarmPickSource.library);++ expect(file.existsSync(), isTrue);+ });++ test('with no temporary folder known, nothing is deleted', () async {+ swarmPickerCopyFolders = () async => throw MissingPluginException();+ final picked = copy('a.jpg', 3);+ pickSwarmPhotos = (limit) async => [picked];++ await addSwarmPicked(files, SwarmPickSource.library);++ expect(names(), ['photo.jpg']);+ expect(File(picked.path).existsSync(), isTrue);+ });+ });++ group('reading', () {+ test('stops when there is no room: the 11th file is never read', () async {+ final picked = [+ for (var i = 0; i < 11; i++) _Counted(copy('f$i.txt', 2).path),+ ];+ pickSwarmFiles = () async => picked;++ final outcome = await addSwarmPicked(files, SwarmPickSource.files);++ expect((outcome as SwarmPicked).note, 'Attach at most 10 files.');+ expect(files.files, hasLength(10));+ expect([for (final f in picked) f.reads], [...List.filled(10, 1), 0]);+ expect(File(picked.last.path).existsSync(), isFalse);+ });++ test('with room for two, only two are read', () async {+ files.add([+ for (var i = 0; i < 8; i++) SwarmOutgoingFile('k$i.txt', Uint8List(1)),+ ]);+ final picked = [+ for (var i = 0; i < 4; i++) _Counted(copy('f$i.txt', 2).path),+ ];+ pickSwarmFiles = () async => picked;++ await addSwarmPicked(files, SwarmPickSource.files);++ expect([for (final f in picked) f.reads], [1, 1, 0, 0]);+ });++ test('an empty file is named, not dropped silently', () async {+ pickSwarmFiles = () async => [copy('empty.txt', 0), copy('ok.txt', 2)];++ final outcome = await addSwarmPicked(files, SwarmPickSource.files);++ expect((outcome as SwarmPicked).note, 'empty.txt is empty.');+ expect(names(), ['ok.txt']);+ });+ });+}++/// A picker's file that counts how often its bytes are read.+class _Counted extends XFile {+ _Counted(super.path);++ int reads = 0;++ @override+ Future<Uint8List> readAsBytes() {+ reads++;+ return super.readAsBytes();+ }+}diff --git a/mobile/test/swarm/swarm_fixture.dart b/mobile/test/swarm/swarm_fixture.dartnew file mode 100644index 000000000..9c6e3f046--- /dev/null+++ b/mobile/test/swarm/swarm_fixture.dart@@ -0,0 +1,381 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/swarm/swarm_home_cache.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++/// Swarm answers as the backend sends them (docs/design/2026-10-26-swarm-state-parts.md, section 4), built by hand so a+/// test reads like the wire. Nothing here reaches a machine or the backend.++const me = 'person-me';+const tab = 'tab-1';+const project = 'project-1';+const leadChat = 'group-lead';++/// One part as a read carries it.+Map<String, dynamic> part(String key, int version, Map<String, dynamic> data) =>+ {'key': key, 'version': version, 'changedAt': version, 'data': data};++Map<String, dynamic> headData({+ String id = tab,+ String name = 'Phone Swarm',+ String ownerId = me,+ List<Map<String, dynamic>>? projects,+}) => {+ 'version': 1,+ 'id': id,+ 'name': name,+ 'ownerId': ownerId,+ 'paused': false,+ 'projects':+ projects ??+ [+ {+ 'id': project,+ 'name': 'Mobile',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ 'rules': <Object>[],+ 'invitations': <Object>[],+};++Map<String, dynamic> person(String id, {String role = 'owner'}) => {+ 'id': id,+ 'email': '[email protected]',+ 'role': role,+ 'generation': 'gen-$id',+};++Map<String, dynamic> agent(+ String id, {+ String name = 'Builder',+ String? displayName,+ String machineId = 'mac-1',+}) => {+ 'id': id,+ 'projectId': project,+ 'machineId': machineId,+ 'harnessId': 'harness-$id',+ 'contributorId': me,+ 'name': name,+ 'displayName': ?displayName,+ 'configuration': {'engine': 'claude', 'model': 'opus', 'effort': 'high'},+};++Map<String, dynamic> groupData(+ String id, {+ String title = 'Work',+ int? number,+ List<String> agentIds = const [],+ String? leadId,+ String? status,+ String? workerId,+ List<String>? audience,+ int lastMessageSequence = 0,+ bool dormant = false,+}) => {+ 'id': id,+ 'projectId': project,+ 'number': ?number,+ 'title': title,+ 'leadId': ?leadId,+ 'agentIds': agentIds,+ 'archived': false,+ 'dormant': ?(dormant ? true : null),+ 'brief': '',+ 'checks': <Object>[],+ if (audience != null)+ 'audience': {+ 'people': [+ for (final id in audience) {'id': id, 'generation': 'gen-$id'},+ ],+ },+ if (status != null)+ 'assignment': {+ 'id': 'attempt-$id',+ 'agentId': workerId ?? 'agent-builder',+ 'status': status,+ 'result': null,+ },+ 'lastMessageSequence': lastMessageSequence,+ 'pullRequestUrls': <String>[],+};++/// [owner]'s Buddy chat in [project] as the backend sends it (backend read/views.ts `groupView`): its owner named+/// instead of an audience.+Map<String, dynamic> buddyChatData(+ String id, {+ String owner = me,+ List<String> agentIds = const [],+ int lastMessageSequence = 0,+}) => {+ ...groupData(+ id,+ title: "$owner's Buddy",+ agentIds: agentIds,+ lastMessageSequence: lastMessageSequence,+ ),+ 'kind': 'buddy',+ 'buddyOwnerId': owner,+};++/// [owner]'s Buddy in [project]: an agent with no role, only its person.+Map<String, dynamic> buddyData(+ String id, {+ String owner = me,+ String? displayName,+ String machineId = 'mac-1',+ String engine = 'claude',+}) => {+ ...agent(+ id,+ name: "$owner's Buddy",+ displayName: displayName,+ machineId: machineId,+ ),+ 'configuration': {'engine': engine, 'model': 'opus', 'effort': 'high'},+ 'buddyOf': {'personId': owner, 'generation': 'gen-$owner'},+};++/// A Buddy's start for [chatId] as the backend keeps it: under way with neither a harness nor an [error].+Map<String, dynamic> buddyStartData(+ String id, {+ required String chatId,+ String owner = me,+ String machineId = 'mac-1',+ String engine = 'claude',+ String? harnessId,+ String? error,+}) => {+ 'id': id,+ 'request': {+ 'conversationId': chatId,+ 'machineId': machineId,+ 'engine': engine,+ 'name': "$owner's Buddy",+ 'buddyOf': {'personId': owner, 'generation': 'gen-$owner'},+ },+ 'harnessId': harnessId,+ 'error': error,+};++/// A first load of a Swarm with one project, its Lead's conversation and [groups] besides.+Map<String, dynamic> firstLoad({+ String tabId = tab,+ String cursor = 'c1',+ Map<String, dynamic>? head,+ List<Map<String, dynamic>> groups = const [],+ List<Map<String, dynamic>>? agents,+ List<Map<String, dynamic>> machines = const [],+ List<Map<String, dynamic>> starts = const [],+ Map<String, dynamic> derived = const {},+ int lastChangedAt = 100,+}) => {+ 'format': 2,+ 'tabId': tabId,+ 'cursor': cursor,+ 'epoch': 1,+ 'lastChangedAt': lastChangedAt,+ 'githubApp': false,+ 'head': part('head', 1, head ?? headData(id: tabId)),+ 'members': [part(me, 1, person(me))],+ 'agents': [+ for (final a+ in agents ??+ [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ ])+ part(a['id'] as String, 1, a),+ ],+ 'groups': [+ part(+ leadChat,+ 1,+ groupData(+ leadChat,+ title: 'Mobile',+ agentIds: ['agent-lead'],+ leadId: 'agent-lead',+ ),+ ),+ for (final (i, g) in groups.indexed) part(g['id'] as String, 2 + i, g),+ ],+ 'machines': [for (final m in machines) part(m['machineId'] as String, 1, m)],+ 'starts': [for (final s in starts) part(s['id'] as String, 1, s)],+ 'progress': <Object>[],+ 'derived': derived,+};++/// A change read: what changed since the cursor it was asked with.+Map<String, dynamic> changes({+ required String cursor,+ List<Map<String, dynamic>> groups = const [],+ Map<String, dynamic> derived = const {},+ int lastChangedAt = 100,+}) => {+ 'format': 2,+ 'reload': false,+ 'cursor': cursor,+ 'epoch': 1,+ 'lastChangedAt': lastChangedAt,+ 'head': null,+ 'members': <Object>[],+ 'agents': <Object>[],+ 'groups': groups,+ 'machines': <Object>[],+ 'starts': <Object>[],+ 'progress': <Object>[],+ 'derived': derived,+};++/// The backend as a test scripts it: each path answers from [routes] (the longest prefix that matches, query+/// included), and every call is remembered.+class FakeSwarm {+ final routes =+ <String, FutureOr<Object?> Function(Map<String, dynamic>? body)>{};+ final calls = <({String method, String path, Map<String, dynamic>? body})>[];++ List<String> get paths => [for (final call in calls) call.path];++ /// The bodies of every command sent, in order.+ List<Map<String, dynamic>> get commands => [+ for (final call in calls)+ if (call.method == 'POST' && call.path.endsWith('/commands'))+ call.body!['command'] as Map<String, dynamic>,+ ];++ SwarmRequest get request => (method, path, {body}) async {+ calls.add((method: method, path: path, body: body));+ String? best;+ for (final route in routes.keys) {+ if (path.startsWith(route) &&+ (best == null || route.length > best.length)) {+ best = route;+ }+ }+ if (best == null) {+ throw SuperTabFailure('NOT_FOUND', 'No route for $path', statusCode: 404);+ }+ return routes[best]!(body);+ };+}++/// Lets queued microtasks and zero timers run.+Future<void> settle() async {+ for (var i = 0; i < 20; i++) {+ await Future<void>.delayed(Duration.zero);+ }+}++/// The Keychain item the kept Home is sealed under, held in memory; [refuses]+/// as a locked or broken Keychain does.+class MemorySwarmHomeKey implements SwarmHomeKey {+ String? value;+ bool refuses = false;++ @override+ Future<String?> read() async => refuses ? throw StateError('locked') : value;++ @override+ Future<void> write(String next) async {+ if (refuses) throw StateError('locked');+ value = next;+ }++ @override+ Future<void> delete() async {+ if (refuses) throw StateError('locked');+ value = null;+ }+}++/// A kept Home in a folder of its own, gone after the test.+SwarmHomeCache memoryHomeCache() {+ final dir = Directory.systemTemp.createTempSync('swarm-home');+ addTearDown(() => dir.deleteSync(recursive: true));+ return SwarmHomeCache(+ key: MemorySwarmHomeKey(),+ file: File('${dir.path}/home.bin'),+ );+}++/// Waits, in real time, until [done] holds: at most a few seconds.+Future<void> until(bool Function() done) async {+ for (var i = 0; i < 500 && !done(); i++) {+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }+ if (!done()) throw StateError('never happened');+}++/// A leaderboard read's answer as the backend sends it+/// (`backend/src/superTabs/leaderboard/contract.ts`), built by hand.+Map<String, dynamic> scoreData(+ String personId, {+ required int points,+ required int rank,+ String? medal,+ int shipped = 0,+ int? medianAskToShipMs,+ int unblocked = 0,+ int unblockedMs = 0,+ int? medianAnswerMs,+ int lentMachines = 0,+ int lentMs = 0,+ int streakDays = 0,+}) => {+ 'personId': personId,+ 'points': points,+ 'rank': rank,+ 'medal': medal,+ 'shipped': {'count': shipped, 'medianAskToShipMs': medianAskToShipMs},+ 'unblocked': {+ 'count': unblocked,+ 'agentMs': unblockedMs,+ 'medianAnswerMs': medianAnswerMs,+ },+ 'lent': {'machines': lentMachines, 'agentMs': lentMs},+ 'streakDays': streakDays,+};++Map<String, dynamic> leaderboardData({+ int week = 1792454400000,+ int shipped = 19,+ List<Map<String, dynamic>>? people,+}) => {+ 'projectId': 'project-1',+ 'week': week,+ 'goal': {+ 'openRequests': 4,+ 'thisWeek': {'shipped': shipped, 'points': 76, 'medianAskToShipMs': null},+ 'lastWeek': {'shipped': 11, 'points': 40, 'medianAskToShipMs': null},+ },+ 'people':+ people ??+ [+ scoreData(+ 'diego',+ points: 28,+ rank: 1,+ medal: 'gold',+ shipped: 8,+ medianAskToShipMs: 3 * 3600000,+ unblocked: 1,+ unblockedMs: 6 * 60000,+ medianAnswerMs: 4 * 60000,+ lentMachines: 2,+ lentMs: 40 * 3600000,+ streakDays: 3,+ ),+ scoreData('ken', points: 21, rank: 2, medal: 'silver', shipped: 3),+ scoreData('dee', points: 0, rank: 4),+ ],+ 'waiting': {'total': 0, 'people': <Object>[]},+};diff --git a/mobile/test/swarm/swarm_home_cache_test.dart b/mobile/test/swarm/swarm_home_cache_test.dartnew file mode 100644index 000000000..6e3b666aa--- /dev/null+++ b/mobile/test/swarm/swarm_home_cache_test.dart@@ -0,0 +1,302 @@+import 'dart:convert';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_buddy.dart';+import 'package:harness_mobile/swarm/swarm_home_cache.dart';+import 'package:harness_mobile/swarm/swarm_pm_chat.dart';+import 'package:harness_mobile/swarm/team_glance.dart';+import 'package:harness_mobile/swarm/waiting_work.dart';++import 'swarm_fixture.dart';++/// The last Home kept on the phone, so a cold start draws it at once: only+/// what Home draws, encrypted under a key in the Keychain, and gone with the+/// account, the Swarm switch, or the person's access.+void main() {+ /// A Swarm whose work g1 waits on the person, with everything Home does+ /// not draw filled in: a brief, checks, a question, emails.+ ({SuperTabSnapshot snapshot, Map<String, String> partners}) read() {+ final load = firstLoad(+ groups: [+ {+ ...groupData(+ 'g1',+ title: 'Rotate the keys',+ number: 4,+ agentIds: ['agent-builder'],+ ),+ 'brief': 'The secret plan',+ 'checks': [+ {'id': 'c1', 'description': 'Keys rotated in prod'},+ ],+ 'assignment': {+ 'id': 'attempt-g1',+ 'agentId': 'agent-builder',+ 'status': 'needs_human',+ 'result': 'Which vault holds the old key?',+ },+ 'partnerId': me,+ 'lastMessageSequence': 12,+ },+ ],+ );+ final state = SuperTabParts.firstLoad(load).state;+ return (+ snapshot: SuperTabSnapshot.fromJson(state),+ partners: swarmPartners(state),+ );+ }++ group('the view kept', () {+ test('draws Home as the Swarm did', () {+ final (:snapshot, :partners) = read();++ final kept = swarmHomeSwarm(snapshot, partners);+ final back = SuperTabSnapshot.fromJson(kept.state);++ expect(back.name, snapshot.name);+ expect([for (final p in back.projects) p.name], ['Mobile']);+ final project = back.projects.single;+ expect(swarmPmName(back, project), 'River');+ expect(+ swarmTeamGlance(back, projectId: project.id).line,+ swarmTeamGlance(snapshot, projectId: project.id).line,+ );+ final waiting = swarmWaitingWork(back, me, partners: kept.partners);+ expect(+ [for (final w in waiting) w.conversation.label],+ ['#4 Rotate the keys'],+ );+ expect(waiting.single.status, 'needs_human');+ expect(waiting.single.agentName, 'Nova');+ });++ test('keeps nothing Home does not draw', () {+ final (:snapshot, :partners) = read();++ final text = jsonEncode(swarmHomeSwarm(snapshot, partners).state);++ expect(text, isNot(contains('The secret plan')));+ expect(text, isNot(contains('Keys rotated')));+ expect(text, isNot(contains('Which vault')));+ expect(text, isNot(contains('@example.com')));+ final back = SuperTabSnapshot.fromJson(+ swarmHomeSwarm(snapshot, partners).state,+ );+ expect(back.decisionsWaiting, 0);+ expect(back.mentionsWaiting, 0);+ expect(back.conversation('g1')!.lastMessageSequence, 0);+ });+ });++ group('Buddies kept', () {+ test("keep which chats are Buddy chats and whose Buddy an agent is, so a "+ 'cold start lists no Buddy chat as work', () {+ final state = SuperTabParts.firstLoad(+ firstLoad(+ groups: [+ buddyChatData('buddy-me', agentIds: ['agent-wren']),+ groupData('g1', title: 'Fix login'),+ ],+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ buddyData('agent-wren', displayName: 'Wren'),+ ],+ ),+ ).state;+ final buddies = SwarmBuddies.read(state, me);++ final kept = swarmHomeSwarm(+ SuperTabSnapshot.fromJson(state),+ swarmPartners(state),+ buddies: buddies,+ ).state;+ final back = SwarmBuddies.read(kept, me);++ expect(back.ownChats, {project: 'buddy-me'});+ expect(back.ownBuddies, {project: 'agent-wren'});+ expect(back.chatOwners, {'buddy-me': me});+ expect(+ SuperTabSnapshot.fromJson(kept).agent('agent-wren')!.displayName,+ 'Wren',+ );+ });++ test('keep none where there are none', () {+ final state = SuperTabParts.firstLoad(firstLoad()).state;++ final kept = swarmHomeSwarm(+ SuperTabSnapshot.fromJson(state),+ swarmPartners(state),+ ).state;++ expect(SwarmBuddies.read(kept, me).chatOwners, isEmpty);+ expect(SwarmBuddies.read(kept, me).ownBuddies, isEmpty);+ });+ });++ group('faces kept', () {+ /// A Swarm where River wears an uploaded photo, Nova the owl, and the+ /// person the fox and a status.+ SuperTabSnapshot faces() {+ final load = firstLoad(+ agents: [+ {+ ...agent('agent-lead', name: 'Lead', displayName: 'River'),+ 'avatar': {'kind': 'upload'},+ },+ {+ ...agent('agent-builder', displayName: 'Nova'),+ 'avatar': {'kind': 'preset', 'key': 'owl'},+ },+ ],+ derived: {+ 'avatars': {+ 'agent:agent-lead':+ 'https://storage.googleapis.com/avatars/river.png?sig=secret',+ },+ },+ );+ load['members'] = [+ part(me, 1, {+ ...person(me),+ 'avatar': {'kind': 'preset', 'key': 'fox'},+ 'status': {'text': 'At the dentist', 'emoji': null, 'until': null},+ }),+ ];+ return SuperTabSnapshot.fromJson(SuperTabParts.firstLoad(load).state);+ }++ test('a built-in picture is kept by its name', () {+ final back = SuperTabSnapshot.fromJson(+ swarmHomeSwarm(faces(), const {}).state,+ );+ expect(+ (back.agent('agent-builder')!.avatar! as SuperTabPresetAvatar).key,+ 'owl',+ );+ expect((back.people.single.avatar! as SuperTabPresetAvatar).key, 'fox');+ });++ test('a photo, its link and a status are never kept', () {+ final snapshot = faces();+ expect(+ snapshot.agent('agent-lead')!.avatar,+ isA<SuperTabUploadedAvatar>(),+ );+ final kept = swarmHomeSwarm(snapshot, const {}).state;+ final text = jsonEncode(kept);+ expect(text, isNot(contains('storage.googleapis.com')));+ expect(text, isNot(contains('sig=secret')));+ expect(text, isNot(contains('upload')));+ expect(text, isNot(contains('At the dentist')));+ final back = SuperTabSnapshot.fromJson(kept);+ expect(back.agent('agent-lead')!.avatar, isNull);+ expect(back.people.single.status, isNull);+ });+ });++ group('kept on the phone', () {+ late Directory dir;+ late MemorySwarmHomeKey key;+ late SwarmHomeCache cache;++ setUp(() {+ dir = Directory.systemTemp.createTempSync('swarm-home');+ addTearDown(() => dir.deleteSync(recursive: true));+ key = MemorySwarmHomeKey();+ cache = SwarmHomeCache(key: key, file: File('${dir.path}/home.bin'));+ });++ List<SwarmHomeEntry> home() {+ final (:snapshot, :partners) = read();+ return [+ (+ id: tab,+ name: 'Phone Swarm',+ view: swarmHomeSwarm(snapshot, partners),+ ),+ ];+ }++ test('reads back for its account', () async {+ await cache.write(me, home());++ final back = await cache.read(me);++ expect([for (final s in back!) s.name], ['Phone Swarm']);+ final snapshot = SuperTabSnapshot.fromJson(back.single.view.state);+ expect(snapshot.projects.single.name, 'Mobile');+ expect(back.single.view.partners, {'g1': me});+ });++ test('is sealed on disk under a key kept in the Keychain', () async {+ await cache.write(me, home());++ final bytes = File('${dir.path}/home.bin').readAsBytesSync();+ final text = utf8.decode(bytes, allowMalformed: true);+ expect(text, isNot(contains('Mobile')));+ expect(text, isNot(contains('Rotate the keys')));+ expect(text, isNot(contains(me)));+ expect(key.value, isNotNull);+ });++ test('another account reads nothing, and the view goes', () async {+ await cache.write(me, home());++ expect(await cache.read('person-other'), isNull);+ expect(await cache.read(me), isNull);+ });++ test(+ 'without its key it reads nothing, and the sealed file goes',+ () async {+ await cache.write(me, home());+ key.value = null;++ expect(await cache.read(me), isNull);+ expect(File('${dir.path}/home.bin').existsSync(), isFalse);+ },+ );++ test('a file that does not open reads nothing, never an error', () async {+ await cache.write(me, home());+ final file = File('${dir.path}/home.bin');+ final bytes = file.readAsBytesSync();+ bytes[bytes.length ~/ 2] ^= 0xff;+ file.writeAsBytesSync(bytes);++ expect(await cache.read(me), isNull);+ expect(file.existsSync(), isFalse);+ });++ test(+ 'a Keychain that refuses reads and keeps nothing, never throws',+ () async {+ key.refuses = true;++ await cache.write(me, home());++ expect(await cache.read(me), isNull);+ expect(File('${dir.path}/home.bin').existsSync(), isFalse);+ },+ );++ test('clear leaves neither the view nor its key', () async {+ await cache.write(me, home());++ await cache.clear();++ expect(File('${dir.path}/home.bin').existsSync(), isFalse);+ expect(key.value, isNull);+ expect(await cache.read(me), isNull);+ });++ test('nothing read before any was kept', () async {+ expect(await cache.read(me), isNull);+ });+ });+}diff --git a/mobile/test/swarm/swarm_home_choice_test.dart b/mobile/test/swarm/swarm_home_choice_test.dartnew file mode 100644index 000000000..280eae545--- /dev/null+++ b/mobile/test/swarm/swarm_home_choice_test.dart@@ -0,0 +1,65 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_home_root.dart';++import '../voice_fakes.dart';++/// What the root of the phone's stack shows: Swarm Home while Swarm is on,+/// until the person goes to Harness; the terminal while it is off.+void main() {+ ExperimentalFeaturesStore features({bool on = true}) =>+ ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {if (on) PhoneExperiment.swarm};++ test('Swarm on: Swarm Home, until Harness is asked for', () {+ final choice = SwarmHomeChoice(features());+ addTearDown(choice.dispose);+ expect(choice.swarm, isTrue);+ expect(choice.harnessOverSwarm, isFalse);++ var told = 0;+ choice.addListener(() => told++);+ choice.showHarness();+ expect(choice.swarm, isFalse);+ expect(choice.harnessOverSwarm, isTrue);+ choice.showHarness();+ expect(told, 1, reason: 'asked twice, changed once');++ choice.showSwarm();+ expect(choice.swarm, isTrue);+ expect(told, 2);+ });++ test('Swarm off: the terminal, whatever was asked for', () {+ final choice = SwarmHomeChoice(features(on: false));+ addTearDown(choice.dispose);+ expect(choice.swarm, isFalse);+ expect(choice.harnessOverSwarm, isFalse);++ choice.showSwarm();+ expect(choice.swarm, isFalse);+ });++ test('turned off, the terminal; turned on again, Swarm Home', () {+ final store = features();+ final choice = SwarmHomeChoice(store);+ addTearDown(choice.dispose);+ choice.showHarness();+ var told = 0;+ choice.addListener(() => told++);++ store.value = const {};+ expect(choice.swarm, isFalse);+ expect(choice.harnessOverSwarm, isFalse);+ store.value = {PhoneExperiment.swarm};+ expect(choice.swarm, isTrue, reason: 'Swarm Home is Home again');+ expect(told, 2);+ });++ test('stops listening to the switch once disposed', () {+ final store = features();+ SwarmHomeChoice(store).dispose();+ // ignore: invalid_use_of_protected_member+ expect(store.hasListeners, isFalse);+ });+}diff --git a/mobile/test/swarm/swarm_home_inbox_test.dart b/mobile/test/swarm/swarm_home_inbox_test.dartnew file mode 100644index 000000000..956fd2bd0--- /dev/null+++ b/mobile/test/swarm/swarm_home_inbox_test.dart@@ -0,0 +1,331 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_buddy.dart';+import 'package:harness_mobile/swarm/team_glance.dart';+import 'package:harness_mobile/swarm/swarm_home_cache.dart';+import 'package:harness_mobile/swarm/swarm_inbox.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/waiting_work.dart';++import 'swarm_fixture.dart';++/// The last Home kept on the phone: drawn at once on a cold start, replaced+/// by the first read, and rid of a Swarm the moment a read says the person+/// lost it (owner, 2026-10-27).+void main() {+ /// Swarm `a`'s Home with [title] work waiting on the person, as kept.+ SwarmHomeEntry kept({String title = 'Kept work', String project = 'Mobile'}) {+ final state = SuperTabParts.firstLoad(+ firstLoad(+ tabId: 'a',+ head: headData(+ id: 'a',+ projects: [+ {+ 'id': 'project-1',+ 'name': project,+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ groups: [+ {+ ...groupData('g1', title: title, status: 'needs_human'),+ 'partnerId': me,+ },+ ],+ ),+ ).state;+ return (+ id: 'a',+ name: 'Swarm a',+ view: swarmHomeSwarm(+ SuperTabSnapshot.fromJson(state),+ swarmPartners(state),+ ),+ );+ }++ /// The backend of Swarm `a`, whose list waits on [listed] when given.+ FakeSwarm backend({+ Completer<Object?>? listed,+ List<Map<String, dynamic>> groups = const [],+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) =>+ listed?.future ??+ {+ 'tabs': [+ {'id': 'a', 'name': 'Swarm a', 'ownerId': me, 'lastChangedAt': 100},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/a/parts'] = (_) =>+ firstLoad(tabId: 'a', groups: groups);+ fake.routes['/api/super-tabs/a/changes'] = (_) =>+ changes(cursor: 'c2', groups: const []);+ return fake;+ }++ SwarmInbox inbox(+ FakeSwarm fake,+ SwarmHomeCache cache, {+ String account = me,+ Duration homeWait = const Duration(hours: 1),+ }) {+ final i = SwarmInbox(+ accountId: account,+ request: fake.request,+ homeCache: cache,+ homeWait: homeWait,+ );+ addTearDown(i.dispose);+ return i;+ }++ Future<List<String>> keptTitles(SwarmHomeCache cache) async => [+ for (final s in await cache.read(me) ?? const <SwarmHomeEntry>[])+ for (final c in SuperTabSnapshot.fromJson(s.view.state).conversations)+ c.title,+ ];++ test(+ 'a cold start draws the Home kept before the first read answers',+ () async {+ final cache = memoryHomeCache();+ await cache.write(me, [kept()]);+ final i = inbox(backend(listed: Completer()), cache)..shown = true;++ await until(() => i.swarms.isNotEmpty);++ expect([for (final s in i.swarms) s.name], ['Swarm a']);+ expect(i.reader('a')!.snapshot!.projects.single.name, 'Mobile');+ expect(+ i.needs.whereType<SwarmWorkNeed>().single.work.conversation.title,+ 'Kept work',+ );+ expect(i.loaded, isFalse);+ expect(i.asks('a')!.loading, isTrue, reason: 'its asks are not kept');+ },+ );++ test(+ "a cold start draws the person's Buddy chat from the Home kept",+ () async {+ final state = SuperTabParts.firstLoad(+ firstLoad(+ tabId: 'a',+ head: headData(id: 'a'),+ groups: [buddyChatData('buddy-me')],+ agents: [buddyData('agent-wren', displayName: 'Wren')],+ ),+ ).state;+ final cache = memoryHomeCache();+ await cache.write(me, [+ (+ id: 'a',+ name: 'Swarm a',+ view: swarmHomeSwarm(+ SuperTabSnapshot.fromJson(state),+ swarmPartners(state),+ buddies: SwarmBuddies.read(state, me),+ ),+ ),+ ]);+ final i = inbox(backend(listed: Completer()), cache)..shown = true;++ await until(() => i.swarms.isNotEmpty);++ final reader = i.reader('a')!;+ expect(swarmBuddyChat(reader, project)?.id, 'buddy-me');+ expect(swarmBuddy(reader, project)?.id, 'agent-wren');+ expect(+ swarmTeamGlance(reader.snapshot!).agents,+ isEmpty,+ reason: 'a Buddy is no one\'s team, from the Home kept too',+ );+ },+ );++ test('the first read replaces the Home kept, and is kept in turn', () async {+ final cache = memoryHomeCache();+ await cache.write(me, [kept()]);+ final i = inbox(+ backend(groups: [groupData('g2', title: 'Fresh work')]),+ cache,+ );++ await i.refresh();+ await settle();++ final titles = [+ for (final c in i.reader('a')!.snapshot!.conversations) c.title,+ ];+ expect(titles, contains('Fresh work'));+ expect(titles, isNot(contains('Kept work')));+ expect(await keptTitles(cache), contains('Fresh work'));+ expect(await keptTitles(cache), isNot(contains('Kept work')));+ });++ test('work in the Home kept is never news', () async {+ final cache = memoryHomeCache();+ await cache.write(me, [kept(title: 'Login')]);+ final listed = Completer<Object?>();+ final i = inbox(+ backend(+ listed: listed,+ groups: [+ {+ ...groupData('g1', title: 'Login', status: 'needs_human'),+ 'partnerId': me,+ },+ // Waiting already at the first read, not since: no news either.+ {+ ...groupData('g2', title: 'Billing', status: 'blocked'),+ 'partnerId': me,+ },+ ],+ ),+ cache,+ );+ final news = <SwarmNeed>[];+ i.onArrived = news.add;+ await until(() => i.swarms.isNotEmpty);++ listed.complete({+ 'tabs': [+ {'id': 'a', 'name': 'Swarm a', 'ownerId': me, 'lastChangedAt': 100},+ ],+ 'next': null,+ });+ await i.refresh();+ await settle();++ expect(i.needs.whereType<SwarmWorkNeed>(), hasLength(2));+ expect(news, isEmpty);+ });++ test('a Swarm off the list leaves the Home kept at once', () async {+ final cache = memoryHomeCache();+ final fake = backend(groups: [groupData('g2', title: 'Fresh work')]);+ final i = inbox(fake, cache);+ await i.refresh();+ await settle();+ expect(await keptTitles(cache), contains('Fresh work'));++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': <Object>[],+ 'next': null,+ };+ await i.refresh();+ await settle();++ expect(await keptTitles(cache), isEmpty);+ });++ test('a Swarm a read refuses leaves the Home kept at once', () async {+ final cache = memoryHomeCache();+ await cache.write(me, [kept()]);+ final fake = backend();+ fake.routes['/api/super-tabs/a/parts'] = (_) => throw const SuperTabFailure(+ 'FORBIDDEN',+ 'You left this Swarm.',+ statusCode: 403,+ );+ final i = inbox(fake, cache);++ await i.refresh();+ await settle();++ expect(i.reader('a')!.snapshot, isNull);+ expect(await keptTitles(cache), isEmpty);+ });++ test('a Swarm read again in full takes what it no longer has out of the '+ 'Home kept at once', () async {+ final cache = memoryHomeCache();+ final fake = backend(+ groups: [+ groupData('g-private', title: 'Pay review', audience: [me]),+ ],+ );+ final i = inbox(fake, cache);+ await i.refresh();+ await settle();+ expect(await keptTitles(cache), contains('Pay review'));++ // Taken out of the private chat: the Swarm is read again without it.+ fake.routes['/api/super-tabs/a/parts'] = (_) => firstLoad(tabId: 'a');+ fake.routes['/api/super-tabs/a/changes'] = (_) => {'reload': true};+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': 'a', 'name': 'Swarm a', 'ownerId': me, 'lastChangedAt': 200},+ ],+ 'next': null,+ };+ await i.refresh();+ await settle();++ expect(await keptTitles(cache), isNot(contains('Pay review')));+ });++ group('any other change', () {+ /// Swarm `a` read once, then renamed by its next change read.+ Future<SwarmInbox> renamed(SwarmHomeCache cache, Duration wait) async {+ final fake = backend(groups: [groupData('g2', title: 'Fresh work')]);+ final i = inbox(fake, cache, homeWait: wait)..shown = true;+ await until(() => i.reader('a')?.generation == 1);+ await settle();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': 'a', 'name': 'Swarm a', 'ownerId': me, 'lastChangedAt': 200},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/a/changes'] = (_) => changes(+ cursor: 'c2',+ groups: [part('g2', 9, groupData('g2', title: 'Renamed work'))],+ lastChangedAt: 200,+ );+ await i.refresh();+ await settle();+ return i;+ }++ test('is kept when Harness goes behind', () async {+ final cache = memoryHomeCache();+ final i = await renamed(cache, const Duration(hours: 1));+ expect(await keptTitles(cache), isNot(contains('Renamed work')));++ i.shown = false;++ expect(await keptTitles(cache), contains('Renamed work'));+ });++ test('is kept at once once a while has passed since the last', () async {+ final cache = memoryHomeCache();++ await renamed(cache, Duration.zero);++ expect(await keptTitles(cache), contains('Renamed work'));+ });+ });++ test("another account's Home is never drawn", () async {+ final cache = memoryHomeCache();+ await cache.write('person-other', [kept()]);+ final i = inbox(backend(listed: Completer()), cache);++ await Future<void>.delayed(const Duration(milliseconds: 100));++ expect(i.swarms, isEmpty);+ expect(i.error, isNull);+ });+}diff --git a/mobile/test/swarm/swarm_home_instant_test.dart b/mobile/test/swarm/swarm_home_instant_test.dartnew file mode 100644index 000000000..a1ee1fce5--- /dev/null+++ b/mobile/test/swarm/swarm_home_instant_test.dart@@ -0,0 +1,465 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_home_cache.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_style.dart';+import 'package:harness_mobile/swarm/waiting_work.dart';++import '../voice_fakes.dart';+import 'swarm_computers_fake.dart';+import 'swarm_fixture.dart';++/// A cold start draws the last Home at once, before any computer answers+/// (owner, 2026-10-27: 4 to 5 seconds of "Reading your Swarms…" on the+/// iPhone 14), then reads.+void main() {+ /// The Home kept: project Mobile, its Product Manager River, Nova waiting+ /// on the person in Fix login.+ SwarmHomeEntry kept() {+ final state = SuperTabParts.firstLoad({+ ...firstLoad(+ groups: [+ {+ ...groupData(+ 'g1',+ title: 'Fix login',+ number: 4,+ agentIds: ['agent-builder'],+ status: 'needs_human',+ ),+ 'partnerId': me,+ },+ ],+ ),+ 'members': [+ part(me, 1, {+ ...person(me),+ 'avatar': {'kind': 'preset', 'key': 'fox'},+ }),+ ],+ }).state;+ return (+ id: tab,+ name: 'Phone Swarm',+ view: swarmHomeSwarm(+ SuperTabSnapshot.fromJson(state),+ swarmPartners(state),+ ),+ );+ }++ /// A cold start over the Home kept (none when [keep] is false), with the+ /// account's [computers]. Unless [list] answers it, no computer answers:+ /// the list never comes back. Pumped until the kept view is read off disk.+ Future<({SwarmHost host, FakeSwarm fake})> coldStart(+ WidgetTester tester, {+ bool keep = true,+ FakeComputers? computers,+ FutureOr<Object?> Function(Map<String, dynamic>? body)? list,+ }) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ final cache = memoryHomeCache();+ if (keep) await tester.runAsync(() => cache.write(me, [kept()]));+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] =+ list ?? (_) => Completer<Object?>().future;+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ computers: computers,+ homeCache: cache,+ );+ addTearDown(host.dispose);++ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmPage(),+ ),+ );+ // The kept view is read off disk: real time, then a frame, until it is.+ for (+ var i = 0;+ i < 100 && keep && host.session!.inbox.swarms.isEmpty;+ i+++ ) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump();+ }++ await tester.pump();+ return (host: host, fake: fake);+ }++ testWidgets(+ 'a cold start draws the Home kept before the first read answers',+ (tester) async {+ final (:host, :fake) = await coldStart(tester);++ expect(key('swarm-projects-loading-$tab'), findsNothing);+ expect(+ find.byKey(const ValueKey('swarm-project-$tab-$project')),+ findsOneWidget,+ );+ expect(find.text('Mobile'), findsWidgets);+ expect(+ find.byKey(const ValueKey('swarm-home-buddy-$tab-$project')),+ findsOneWidget,+ reason: 'its Buddies',+ );+ expect(find.textContaining('Fix login'), findsOneWidget);+ expect(host.session!.inbox.loaded, isFalse, reason: 'nothing read yet');+ expect(fake.paths, ['/api/super-tabs/list']);+ },+ );++ testWidgets(+ 'a cold start lists the projects kept in the drawer, with none on their '+ 'way',+ (tester) async {+ await coldStart(tester);++ await tester.tap(key('swarm-menu'));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 500));++ expect(key('swarm-drawer-project-$tab-$project'), findsOneWidget);+ expect(key('swarm-drawer-loading'), findsNothing);+ },+ );++ testWidgets('a cold start draws you first in the menu, in your picture', (+ tester,+ ) async {+ await coldStart(tester);+ await tester.tap(key('swarm-menu'));+ for (var i = 0; i < 5; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ final you = key('swarm-drawer-you-$tab');+ expect(find.descendant(of: you, matching: find.text('🦊')), findsOneWidget);+ // The kept view holds no email: no name to give, so You.+ expect(+ find.descendant(of: you, matching: find.text('You')),+ findsOneWidget,+ );+ });++ group('no computer answering', () {+ const mac = (name: 'MacBook Pro', away: false);+ const macAway = (name: 'MacBook Pro', away: true);++ Object? unavailable(Map<String, dynamic>? _) => throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ );++ testWidgets(+ 'every computer offline: the Home kept stays, with a line that says '+ 'so, never a screen in its place',+ (tester) async {+ final (:host, fake: _) = await coldStart(+ tester,+ computers: FakeComputers([macAway]),+ list: unavailable,+ );++ expect(find.text('No computer online'), findsNothing);+ expect(+ find.byKey(const ValueKey('swarm-project-$tab-$project')),+ findsOneWidget,+ );+ final notice = key('swarm-connection');+ expect(+ find.descendant(+ of: notice,+ matching: find.text('Your computers are offline.'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: notice,+ matching: find.text('Showing your last update.'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(of: notice, matching: find.text('Try again')),+ findsOneWidget,+ );+ expect(+ find.text('Connect one of your computers to open Swarm.'),+ findsNothing,+ reason: 'the notice says it, not a red line besides',+ );+ stopReads(host);+ },+ );++ testWidgets(+ 'a computer still connecting: the Home kept stays, and the line says '+ 'it is connecting',+ (tester) async {+ final (:host, fake: _) = await coldStart(+ tester,+ computers: FakeComputers([mac]),+ list: unavailable,+ );++ expect(find.text('No computer online'), findsNothing);+ expect(+ find.byKey(const ValueKey('swarm-project-$tab-$project')),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: key('swarm-connection'),+ matching: find.text('Connecting to your computers…'),+ ),+ findsOneWidget,+ );+ stopReads(host);+ },+ );++ testWidgets(+ 'nothing kept and every computer offline: Home on its way, with the '+ 'line, never a screen in its place',+ (tester) async {+ final (:host, fake: _) = await coldStart(+ tester,+ keep: false,+ computers: FakeComputers([macAway]),+ list: unavailable,+ );++ expect(find.text('No computer online'), findsNothing);+ expect(key('swarm-projects-loading'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-connection'),+ matching: find.text('Your computers are offline.'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: key('swarm-connection'),+ matching: find.text('Turn one on and open Harness.'),+ ),+ findsOneWidget,+ );+ stopReads(host);+ },+ );++ testWidgets(+ 'Try again looks for the computers, says so, then reads the Swarms; '+ 'once they answer the line goes',+ (tester) async {+ var away = true;+ final computers = FakeComputers([macAway])+ ..held = Completer<void>()+ ..found = [mac];+ final (:host, fake: _) = await coldStart(+ tester,+ computers: computers,+ list: (_) => away+ ? unavailable(null)+ : {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ },+ );++ await tester.tap(+ find.descendant(+ of: key('swarm-connection'),+ matching: find.text('Try again'),+ ),+ );+ await tester.pump();+ expect(computers.rechecks, 1);+ expect(find.text('Looking…'), findsOneWidget);++ away = false;+ computers.held!.complete();+ await tester.pump();+ await tester.pump();+ await tester.pump();++ expect(key('swarm-connection'), findsNothing);+ expect(+ find.byKey(const ValueKey('swarm-project-$tab-$project')),+ findsOneWidget,+ );+ stopReads(host);+ },+ );++ testWidgets('a Try again that finds nothing keeps the line, ready to try '+ 'again', (tester) async {+ final computers = FakeComputers([macAway]);+ final (:host, fake: _) = await coldStart(+ tester,+ computers: computers,+ list: unavailable,+ );++ await tester.tap(+ find.descendant(+ of: key('swarm-connection'),+ matching: find.text('Try again'),+ ),+ );+ await tester.pump();+ await tester.pump();++ expect(computers.rechecks, 1);+ expect(+ find.descendant(+ of: key('swarm-connection'),+ matching: find.text('Try again'),+ ),+ findsOneWidget,+ );+ expect(+ find.byKey(const ValueKey('swarm-project-$tab-$project')),+ findsOneWidget,+ );+ stopReads(host);+ });+ });++ testWidgets(+ 'the Home kept says it is updating until its Swarm is read again',+ (tester) async {+ final answer = Completer<Object?>();+ final (:host, fake: _) = await coldStart(+ tester,+ list: (_) => answer.future,+ );++ expect(updating(), findsOneWidget, reason: 'under the title, quiet');+ expect(key('swarm-connection'), findsNothing);++ answer.complete({+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ });+ await tester.pump();+ await tester.pump();+ await tester.pump();++ expect(updating(), findsNothing);+ stopReads(host);+ },+ );+ testWidgets("a project opened from the Home kept: its menu's status reads "+ 'Updating… until its Swarm is read again', (tester) async {+ final (:host, :fake) = await coldStart(tester);+ final read = Completer<void>();+ fake.routes['/api/super-tabs/$tab/parts'] = (_) async {+ await read.future;+ return firstLoad();+ };+ await tester.tap(key('swarm-project-$tab-$project'));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 500));+ await tester.tap(key('swarm-project-menu'));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 500));++ final line = key('swarm-project-menu-status');+ Finder inLine(Finder matching) =>+ find.descendant(of: line, matching: matching);+ // Kept: Nova waiting on the person in Fix login.+ expect(inLine(find.text('Updating…')), findsOneWidget);+ expect(+ inLine(find.textContaining('waiting')),+ findsNothing,+ reason: 'neither the team nor what waits on the person is now',+ );++ read.complete();+ await tester.pump();+ await tester.pump();+ await tester.pump();++ // Read again: nobody holds work.+ expect(inLine(find.text('Updating…')), findsNothing);+ expect(inLine(find.text('All idle')), findsOneWidget);+ stopReads(host);+ });++ testWidgets(+ 'a first read of the Swarm that fails keeps Home Updating… until a read '+ 'gets through',+ (tester) async {+ final answer = Completer<Object?>();+ final (:host, :fake) = await coldStart(+ tester,+ list: (_) => answer.future,+ );+ fake.routes['/api/super-tabs/$tab/parts'] = (_) =>+ throw const SuperTabFailure('TIMEOUT', 'The Swarm did not answer.');+ answer.complete({+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ });+ await tester.pump();+ await tester.pump();+ await tester.pump();+ final inbox = host.session!.inbox;+ expect(inbox.loaded, isTrue);+ expect(inbox.reader(tab)!.error, isNotNull, reason: 'the read failed');++ expect(updating(), findsOneWidget);++ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ await inbox.refresh();+ await tester.pump();+ await tester.pump();++ expect(updating(), findsNothing);+ stopReads(host);+ },+ );+}++Finder key(String value) => find.byKey(ValueKey(value));++/// Harness behind: [host]'s polls, and its quick retries while no computer+/// answers, stop.+void stopReads(SwarmHost host) => host.foreground = false;++/// Home's quiet "Updating…" under its title.+Finder updating() => find.descendant(+ of: find.byType(SwarmTopBar),+ matching: find.text('Updating…'),+);diff --git a/mobile/test/swarm/swarm_home_root_test.dart b/mobile/test/swarm/swarm_home_root_test.dartnew file mode 100644index 000000000..68efe50f4--- /dev/null+++ b/mobile/test/swarm/swarm_home_root_test.dart@@ -0,0 +1,201 @@+import 'package:flutter/material.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/swarm/swarm_home_root.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import '../widget_rebuilds.dart';+import 'swarm_fixture.dart';++/// Swarm Home and Harness side by side at the root: going to Harness and back+/// finds Home as it was left, and Home out of sight costs nothing and mutes+/// no notice.+void main() {+ /// One Swarm with more projects than fit on the screen, and one decision+ /// waiting on the person.+ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ const derived = {'decisionsWaiting': 1, 'mentionsWaiting': 0};+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ derived: derived,+ head: headData(+ projects: [+ for (var i = 0; i < 10; i++)+ {+ 'id': 'project-$i',+ 'name': 'Project $i',+ 'ownerId': me,+ 'leadConversationId': 'lead-$i',+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ agents: [agent('agent-lead', name: 'Lead', displayName: 'River')],+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'conversationId': 'g9',+ 'askerName': 'River',+ 'question': 'Ship it?',+ 'options': ['Yes', 'No'],+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ return fake;+ }++ late FakeSwarm fake;+ late _Notices notices;+ late SwarmHost host;+ late SwarmHomeChoice choice;++ Future<void> pump(WidgetTester tester) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ fake = backend();+ notices = _Notices();+ host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: notices,+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ choice = SwarmHomeChoice(features);+ addTearDown(choice.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: SwarmHomeRoot(+ choice: choice,+ harness: const Text('the terminal'),+ swarm: (_) => const SwarmPage(),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ Future<void> toHarnessAndBack(WidgetTester tester) async {+ choice.showHarness();+ await tester.pumpAndSettle();+ expect(find.byType(SwarmPage), findsNothing);+ choice.showSwarm();+ await tester.pumpAndSettle();+ }++ Finder homeList() => find.descendant(+ of: find.byType(SwarmPage),+ matching: find.byType(Scrollable),+ );++ double offset(WidgetTester tester) =>+ tester.state<ScrollableState>(homeList()).position.pixels;++ testWidgets('Home keeps its scroll position after Harness and back', (+ tester,+ ) async {+ await pump(tester);+ await tester.drag(homeList(), const Offset(0, -600));+ await tester.pumpAndSettle();+ final scrolled = offset(tester);+ expect(scrolled, greaterThan(0));++ await toHarnessAndBack(tester);++ expect(offset(tester), scrolled);+ });++ testWidgets('Home out of sight mutes no notice', (tester) async {+ await pump(tester);+ final need = host.session!.inbox.needs.single;+ choice.showHarness();+ await tester.pumpAndSettle();++ host.session!.announce(need);++ expect(notices.shown.single.title, 'River asks you');+ });++ testWidgets('Home dropped while out of sight (Swarm turned off) leaves '+ 'another Swarm screen muting them', (tester) async {+ await pump(tester);+ final session = host.session!;+ final need = session.inbox.needs.single;+ choice.showHarness();+ await tester.pumpAndSettle();+ // Another Swarm screen up meanwhile (a chat).+ session.enter();++ choice.features.value = const {};+ await tester.pumpAndSettle();+ expect(find.byType(SwarmPage, skipOffstage: false), findsNothing);+ session.announce(need);++ expect(notices.shown, isEmpty, reason: 'Home left once, when hidden');+ });++ testWidgets('Home in sight mutes them, as before', (tester) async {+ await pump(tester);++ host.session!.announce(host.session!.inbox.needs.single);++ expect(notices.shown, isEmpty);+ });++ testWidgets('Home out of sight builds nothing when its Swarms change', (+ tester,+ ) async {+ await pump(tester);+ choice.showHarness();+ await tester.pumpAndSettle();++ final rebuilt = countRebuildsUnder<SwarmPage>();+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();++ expect(rebuilt(), 0);+ });++ testWidgets('Home shown again reads its Swarms again', (tester) async {+ await pump(tester);+ int lists() =>+ fake.paths.where((path) => path == '/api/super-tabs/list').length;+ final before = lists();++ await toHarnessAndBack(tester);++ expect(lists(), before + 1);+ });+}++class _Notices extends SilentSystemNotices {+ final shown = <SwarmNoticeMessage>[];++ @override+ Future<void> showSwarm(SwarmNoticeMessage message) async =>+ shown.add(message);+}diff --git a/mobile/test/swarm/swarm_home_signed_out_test.dart b/mobile/test/swarm/swarm_home_signed_out_test.dartnew file mode 100644index 000000000..27eb12a34--- /dev/null+++ b/mobile/test/swarm/swarm_home_signed_out_test.dart@@ -0,0 +1,46 @@+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/welcome/phone_welcome.dart';+import 'package:harness_mobile/swarm/parts.dart';++import '../phone_edge/edge_fixture.dart';+import 'swarm_fixture.dart';++/// A phone that starts signed out (its session ended while the app was not+/// running) keeps nothing of the last Swarm Home: the signed-out screen lets+/// it go, view and key, before anyone signs in again.+void main() {+ testWidgets('the signed-out screen lets the Home kept go', (tester) async {+ final home = memoryHomeCache();+ await tester.runAsync(+ () => home.write('person-me', [+ (+ id: 'a',+ name: 'Swarm a',+ view: (+ state: SuperTabParts.firstLoad(firstLoad(tabId: 'a')).state,+ partners: const <String, String>{},+ ),+ ),+ ]),+ );+ setPhone(tester, largePhone);+ final app = edgeApp(noMachines: true);++ // On the real clock: the clear the screen starts is real file work.+ await tester.runAsync(() async {+ await tester.pumpWidget(+ phoneApp(PhoneWelcome(notifier: app, swarmHome: home)),+ );+ await home.read('person-me');+ });++ expect(home.file.existsSync(), isFalse);+ expect((home.key as MemorySwarmHomeKey).value, isNull);++ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 3));+ app.dispose();+ await tester.pump(const Duration(seconds: 30));+ });+}diff --git a/mobile/test/swarm/swarm_home_test.dart b/mobile/test/swarm/swarm_home_test.dartnew file mode 100644index 000000000..327e1c1b2--- /dev/null+++ b/mobile/test/swarm/swarm_home_test.dart@@ -0,0 +1,1971 @@+import 'dart:async';+import 'dart:collection';++import 'package:flutter/cupertino.dart' show CupertinoPageRoute;+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' show AppFont;+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_drawer.dart';+import 'package:harness_mobile/swarm/swarm_leaderboard.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_start.dart';+import 'package:harness_mobile/swarm/swarm_style.dart';+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// The person's computers as a test sets them.+class _Computers extends ChangeNotifier implements SwarmComputers {+ _Computers(this.computers);++ @override+ List<SwarmComputer>? computers;++ @override+ bool get rechecking => false;++ void set(List<SwarmComputer>? next) {+ computers = next;+ notifyListeners();+ }++ @override+ Future<void> recheck() async {}++ @override+ void add(BuildContext context) {}+}++/// A list that counts how often what it holds is read, in turn or one by one;+/// its length is not a read.+class _Reads<E> extends ListBase<E> {+ _Reads(this._items);++ final List<E> _items;+ var reads = 0;++ @override+ int get length => _items.length;++ @override+ set length(int value) => throw UnsupportedError('Read only');++ @override+ E operator [](int index) {+ reads++;+ return _items[index];+ }++ @override+ void operator []=(int index, E value) => throw UnsupportedError('Read only');++ @override+ Iterator<E> get iterator {+ reads++;+ return _items.iterator;+ }+}++/// Half a second of frames, for a screen that cannot settle.+Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 5; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+}++/// Swarm Home and its drawer, over a scripted backend: one Swarm with two+/// projects. Mobile has River as its Product Manager, Nova waiting on the+/// person in g1, Atlas down, and the person's old Chat with PM, which a+/// server before #2090 still sends; Web has Cleo as its Product Manager.+/// With [buddy], Mobile has the person's Buddy chat and their Buddy Wren+/// running in it; Web has no Buddy chat yet, and opening one opens+/// `buddy-web`.+void main() {+ const web = 'project-2';+ const webLead = 'group-lead-web';++ FakeSwarm backend({bool buddy = false}) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ const derived = {'decisionsWaiting': 1, 'mentionsWaiting': 1};+ Map<String, dynamic> inWeb(Map<String, dynamic> row) => {+ ...row,+ 'projectId': web,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ derived: derived,+ head: headData(+ projects: [+ {+ 'id': project,+ 'name': 'Mobile',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ {+ 'id': web,+ 'name': 'Web',+ 'ownerId': me,+ 'leadConversationId': webLead,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ {+ ...agent('agent-atlas', displayName: 'Atlas'),+ 'downSince': '2026-10-27T01:00:00.000Z',+ },+ inWeb(agent('agent-cleo', name: 'Lead', displayName: 'Cleo')),+ if (buddy) buddyData('agent-wren', displayName: 'Wren'),+ ],+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ number: 4,+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'needs_human',+ lastMessageSequence: 9,+ ),+ groupData(+ 'g-atlas',+ title: 'Search page',+ number: 5,+ agentIds: ['agent-atlas'],+ status: 'lost',+ workerId: 'agent-atlas',+ lastMessageSequence: 3,+ ),+ groupData('g-busy', title: 'Sync', lastMessageSequence: 20),+ groupData(+ 'g-private',+ title: 'Their chat',+ audience: ['person-other', 'person-third'],+ ),+ groupData('g-pm', title: 'me', audience: [me]),+ if (buddy) buddyChatData('buddy-me', agentIds: ['agent-wren']),+ inWeb(+ groupData(+ webLead,+ title: 'Web',+ agentIds: ['agent-cleo'],+ leadId: 'agent-cleo',+ ),+ ),+ ],+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'askerName': 'River',+ 'question': 'Ship it behind a flag?',+ 'options': ['Yes', 'No'],+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [+ {+ 'id': 'm1',+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'messageId': 'msg-1',+ 'leadName': 'River',+ 'text': 'Can you check the copy?',+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (body) => {+ 'result': switch (body?['command']) {+ {'type': 'buddy.chat', 'projectId': web} => {+ 'conversationId': 'buddy-web',+ },+ _ => <String, dynamic>{},+ },+ };+ fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };+ return fake;+ }++ /// Swarm Home as the root of its own stack, Swarm on, on an iPhone's+ /// screen. Its route is the shell's kind, the kind of every page pushed+ /// over it: a push or pop builds nothing of Home again, as on the phone.+ /// [overPage] opens it over another page instead ([openSwarmHome]).+ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ void Function(BuildContext context)? onSettings,+ SwarmComputers? computers,+ bool settle = true,+ bool overPage = false,+ }) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ computers: computers,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ onGenerateRoute: (_) => CupertinoPageRoute<void>(+ builder: (_) => overPage+ ? const SizedBox(key: ValueKey('page-under'))+ : SwarmPage(onSettings: onSettings),+ ),+ ),+ );+ if (overPage) {+ openSwarmHome(tester.element(find.byKey(const ValueKey('page-under'))));+ }+ // A skeleton breathes for as long as it shows: nothing settles under it.+ settle ? await tester.pumpAndSettle() : await frames(tester);+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));+ double y(WidgetTester tester, String k) => tester.getTopLeft(key(k)).dy;+ Finder inside(String k, Finder matching) =>+ find.descendant(of: key(k), matching: matching);+ double middle(WidgetTester tester, Finder finder) =>+ tester.getCenter(finder).dy;++ Future<void> openDrawer(WidgetTester tester) async {+ await tester.tap(key('swarm-menu'));+ await tester.pumpAndSettle();+ }++ /// The weight of the words in row [k] that hold [words].+ FontWeight? weightOf(WidgetTester tester, String k, String words) => tester+ .widget<Text>(inside(k, find.textContaining(words)))+ .style+ ?.fontWeight;++ /// A change read in which [groups] moved, by id.+ void moveOn(FakeSwarm fake, Map<String, Map<String, dynamic>> groups) =>+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ derived: const {'decisionsWaiting': 1, 'mentionsWaiting': 1},+ groups: [+ for (final MapEntry(:key, :value) in groups.entries)+ part(key, 30, value),+ ],+ );++ group('the drawer', () {+ testWidgets('its title and close, Swarm Home with a count, the projects, '+ 'then Settings at its foot', (tester) async {+ var settings = 0;+ await pump(tester, backend(), onSettings: (_) => settings++);+ await openDrawer(tester);++ expect(+ tester.getSize(find.byType(Drawer)).width,+ closeTo(390 * .86, .5),+ reason: "most of the screen, as the prototype's",+ );+ expect(+ inside('swarm-drawer-home', find.byType(SwarmBadge)),+ findsOneWidget,+ reason: 'what waits on the person, in a filled count',+ );+ expect(inside('swarm-drawer-home', find.text('3')), findsOneWidget);+ expect(+ y(tester, 'swarm-drawer-home'),+ lessThan(y(tester, 'swarm-drawer-project-$tab-$project')),+ );+ expect(+ y(tester, 'swarm-drawer-project-$tab-$project'),+ lessThan(y(tester, 'swarm-drawer-project-$tab-$web')),+ );+ expect(+ y(tester, 'swarm-drawer-project-$tab-$web'),+ lessThan(y(tester, 'swarm-drawer-settings')),+ );+ expect(+ inside('swarm-drawer-settings', find.byIcon(LucideIcons.settings2300)),+ findsOneWidget,+ reason: "the prototype's two sliders",+ );+ final drawer = find.byType(SwarmDrawer);+ expect(+ find.descendant(of: drawer, matching: find.text('Projects')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: drawer, matching: find.text('Chat with PM')),+ findsNothing,+ reason: 'Buddies replaced Chat with PM (#2090)',+ );+ for (final matching in [+ find.text('Mobile'),+ find.byType(SwarmProjectTile),+ ]) {+ expect(+ inside('swarm-drawer-project-$tab-$project', matching),+ findsOneWidget,+ reason: 'a project: its initial and its name',+ );+ }++ expect(key('swarm-drawer-harness'), findsNothing);+ await tester.tap(key('swarm-drawer-settings'));+ await tester.pumpAndSettle();+ expect(settings, 1);+ });++ testWidgets('its close button closes it', (tester) async {+ await pump(tester, backend());+ await openDrawer(tester);+ expect(+ middle(tester, key('swarm-drawer-close')),+ closeTo(middle(tester, find.text('Swarm').last), 2),+ reason: 'beside its title',+ );++ await tester.tap(key('swarm-drawer-close'));+ await tester.pumpAndSettle();++ expect(key('swarm-drawer-home'), findsNothing);+ });++ testWidgets("a project's name opens its page", (tester) async {+ await pump(tester, backend());+ await openDrawer(tester);++ await tester.tap(key('swarm-drawer-project-$tab-$web'));+ await tester.pumpAndSettle();++ final page = tester.widget<SwarmProjectPage>(+ find.byType(SwarmProjectPage),+ );+ expect((page.swarmId, page.projectId), (tab, web));+ });++ testWidgets("a project's arrow lists its chats, and a chat opens", (+ tester,+ ) async {+ await pump(tester, backend());+ await openDrawer(tester);+ expect(key('swarm-drawer-chat-g1'), findsNothing);++ await tester.tap(key('swarm-drawer-chats-$tab-$project'));+ await tester.pumpAndSettle();++ expect(+ y(tester, 'swarm-drawer-buddy-chat-$tab-$project'),+ lessThan(y(tester, 'swarm-drawer-chat-$leadChat')),+ reason: 'Buddy chat first, where Chat with PM was',+ );+ expect(+ inside(+ 'swarm-drawer-buddy-chat-$tab-$project',+ find.text('Buddy chat'),+ ),+ findsOneWidget,+ );+ expect(+ y(tester, 'swarm-drawer-chat-$leadChat'),+ lessThan(y(tester, 'swarm-drawer-chat-g1')),+ reason: 'then the project chat',+ );+ expect(+ y(tester, 'swarm-drawer-chat-g1'),+ lessThan(y(tester, 'swarm-drawer-chat-g-busy')),+ reason: 'then work: what waits on the person, then the latest',+ );+ expect(+ inside('swarm-drawer-chat-$leadChat', find.text('Project chat')),+ findsOneWidget,+ );+ expect(+ key('swarm-drawer-chat-g-private'),+ findsNothing,+ reason: 'a private chat is for its people only',+ );+ expect(+ key('swarm-drawer-chat-g-pm'),+ findsNothing,+ reason: 'an old Chat with PM is hidden (#2090)',+ );+ expect(find.text('Chat with PM'), findsNothing);+ expect(+ key('swarm-drawer-buddy-chat-$tab-$web'),+ findsNothing,+ reason: 'closed',+ );+ expect(key('swarm-drawer-chat-$webLead'), findsNothing);++ await tester.tap(key('swarm-drawer-chat-g1'));+ await tester.pumpAndSettle();+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), (tab, 'g1'));+ });++ testWidgets('a chat the Lead tagged the person in is bold with @N, and '+ 'so is its project; the rest are not, and no project has a team line '+ '(Team at a glance is gone, as on the desktop)', (tester) async {+ final semantics = tester.ensureSemantics();+ await pump(tester, backend());+ await openDrawer(tester);++ const mobileRow = 'swarm-drawer-project-$tab-$project';+ const webRow = 'swarm-drawer-project-$tab-$web';+ expect(weightOf(tester, mobileRow, 'Mobile'), AppFont.semibold);+ expect(inside(mobileRow, find.text('@1')), findsOneWidget);+ expect(weightOf(tester, webRow, 'Web'), isNot(AppFont.semibold));+ expect(inside(webRow, find.textContaining('@')), findsNothing);+ for (final words in ['working', 'waiting', 'down', 'idle']) {+ expect(+ find.descendant(+ of: find.byType(SwarmDrawer),+ matching: find.textContaining(words),+ ),+ findsNothing,+ reason: 'no team line',+ );+ }++ await tester.tap(key('swarm-drawer-chats-$tab-$project'));+ await tester.pumpAndSettle();++ expect(+ weightOf(tester, 'swarm-drawer-chat-g1', 'Fix login'),+ AppFont.semibold,+ );+ expect(inside('swarm-drawer-chat-g1', find.text('@1')), findsOneWidget);+ expect(+ find.descendant(+ of: find.byType(SwarmDrawer),+ matching: find.bySemanticsLabel(RegExp('1 mention')),+ ),+ findsNWidgets(2),+ );+ for (final (row, words) in [+ ('swarm-drawer-chat-$leadChat', 'Project chat'),+ ('swarm-drawer-chat-g-busy', 'Sync'),+ ('swarm-drawer-leaderboard-$tab-$project', 'Leaderboard'),+ ('swarm-drawer-buddy-chat-$tab-$project', 'Buddy chat'),+ ]) {+ expect(weightOf(tester, row, words), isNot(AppFont.semibold));+ expect(inside(row, find.textContaining('@')), findsNothing);+ }+ semantics.dispose();+ });++ testWidgets('a chat with messages since it was read is bold with no count, '+ 'and so are its project and a Buddy chat with new lines', (+ tester,+ ) async {+ final fake = backend(buddy: true);+ final host = await pump(tester, fake);+ moveOn(fake, {+ 'g-busy': groupData('g-busy', title: 'Sync', lastMessageSequence: 21),+ webLead: {+ ...groupData(+ webLead,+ title: 'Web',+ agentIds: ['agent-cleo'],+ leadId: 'agent-cleo',+ lastMessageSequence: 1,+ ),+ 'projectId': web,+ },+ 'buddy-me': buddyChatData(+ 'buddy-me',+ agentIds: ['agent-wren'],+ lastMessageSequence: 1,+ ),+ });+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();+ await openDrawer(tester);++ const webRow = 'swarm-drawer-project-$tab-$web';+ expect(weightOf(tester, webRow, 'Web'), AppFont.semibold);+ expect(inside(webRow, find.textContaining('@')), findsNothing);+ expect(+ weightOf(tester, 'swarm-drawer-buddy-$tab-$project', 'Wren'),+ AppFont.semibold,+ );++ await tester.tap(key('swarm-drawer-chats-$tab-$project'));+ await tester.pumpAndSettle();++ expect(+ weightOf(tester, 'swarm-drawer-chat-g-busy', 'Sync'),+ AppFont.semibold,+ );+ expect(+ inside('swarm-drawer-chat-g-busy', find.textContaining('@')),+ findsNothing,+ );+ expect(+ weightOf(tester, 'swarm-drawer-buddy-chat-$tab-$project', 'Buddy chat'),+ AppFont.semibold,+ );+ });++ testWidgets("a project's leaderboard opens from its chats", (tester) async {+ await pump(tester, backend());+ await openDrawer(tester);+ expect(key('swarm-drawer-leaderboard-$tab-$project'), findsNothing);+ await tester.tap(key('swarm-drawer-chats-$tab-$project'));+ await tester.pumpAndSettle();++ expect(+ inside(+ 'swarm-drawer-leaderboard-$tab-$project',+ find.text('Leaderboard'),+ ),+ findsOneWidget,+ );+ expect(+ y(tester, 'swarm-drawer-chat-$leadChat'),+ lessThan(y(tester, 'swarm-drawer-leaderboard-$tab-$project')),+ reason: 'after Buddy chat and the project chat',+ );+ expect(+ y(tester, 'swarm-drawer-leaderboard-$tab-$project'),+ lessThan(y(tester, 'swarm-drawer-chat-g1')),+ reason: 'before the work',+ );++ await tester.tap(key('swarm-drawer-leaderboard-$tab-$project'));+ await tester.pumpAndSettle();++ final page = tester.widget<SwarmLeaderboardPage>(+ find.byType(SwarmLeaderboardPage),+ );+ expect((page.swarmId, page.projectId), (tab, project));+ expect(key('swarm-drawer-home'), findsNothing, reason: 'it closed');+ });++ testWidgets("a project's Buddy chat opens the person's own Buddy chat "+ 'there, asking the server nothing', (tester) async {+ final fake = backend(buddy: true);+ await pump(tester, fake);+ await openDrawer(tester);+ await tester.tap(key('swarm-drawer-chats-$tab-$project'));+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-drawer-buddy-chat-$tab-$project'));+ await tester.pumpAndSettle();++ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), (tab, 'buddy-me'));+ expect(fake.commands.where((c) => c['type'] == 'buddy.chat'), isEmpty);+ });++ testWidgets("Buddies, above the projects: the person's Buddy chat in each "+ "project, by its Buddy's name or Buddy while none runs, the project "+ 'in brackets, and how it stands', (tester) async {+ await pump(tester, backend(buddy: true));+ await openDrawer(tester);++ final drawer = find.byType(SwarmDrawer);+ expect(+ find.descendant(of: drawer, matching: find.text('Buddies')),+ findsOneWidget,+ );+ expect(+ y(tester, 'swarm-drawer-home'),+ lessThan(y(tester, 'swarm-drawer-buddy-$tab-$project')),+ );+ expect(+ y(tester, 'swarm-drawer-buddy-$tab-$project'),+ lessThan(y(tester, 'swarm-drawer-buddy-$tab-$web')),+ );+ expect(+ y(tester, 'swarm-drawer-buddy-$tab-$web'),+ lessThan(y(tester, 'swarm-drawer-project-$tab-$project')),+ reason: 'above the projects',+ );+ for (final words in ['Wren', '(Mobile)']) {+ expect(+ inside('swarm-drawer-buddy-$tab-$project', find.text(words)),+ findsOneWidget,+ );+ }+ expect(+ inside('swarm-drawer-buddy-$tab-$project', find.byType(SwarmAvatar)),+ findsOneWidget,+ reason: "its Buddy's face",+ );+ expect(+ inside('swarm-drawer-buddy-$tab-$project', find.text('not started')),+ findsNothing,+ reason: 'Wren runs',+ );+ for (final words in ['Buddy', '(Web)', 'not started']) {+ expect(+ inside('swarm-drawer-buddy-$tab-$web', find.text(words)),+ findsOneWidget,+ );+ }+ });++ testWidgets('a Buddy row opens the Buddy chat; one not opened yet is '+ 'opened on the server first', (tester) async {+ final fake = backend(buddy: true);+ await pump(tester, fake);+ await openDrawer(tester);++ await tester.tap(key('swarm-drawer-buddy-$tab-$project'));+ await tester.pumpAndSettle();+ expect(+ tester+ .widget<SwarmConversationPage>(find.byType(SwarmConversationPage))+ .conversationId,+ 'buddy-me',+ );+ expect(fake.commands.where((c) => c['type'] == 'buddy.chat'), isEmpty);++ await tester.tap(key('tty-back'));+ await tester.pumpAndSettle();+ await openDrawer(tester);+ await tester.tap(key('swarm-drawer-buddy-$tab-$web'));+ await tester.pumpAndSettle();++ expect(fake.commands.where((c) => c['type'] == 'buddy.chat'), [+ {'type': 'buddy.chat', 'projectId': web},+ ]);+ expect(+ tester+ .widget<SwarmConversationPage>(find.byType(SwarmConversationPage))+ .conversationId,+ 'buddy-web',+ );+ });+ });++ group('Swarm Home', () {+ testWidgets('Needs you first, then Buddies, then the projects', (+ tester,+ ) async {+ await pump(tester, backend(buddy: true));++ expect(key('swarm-menu'), findsOneWidget);+ expect(key('tty-back'), findsNothing);+ expect(+ y(tester, 'swarm-need-decision:d1'),+ lessThan(y(tester, 'swarm-home-buddy-$tab-$project')),+ );+ expect(+ y(tester, 'swarm-home-buddy-$tab-$project'),+ lessThan(y(tester, 'swarm-home-buddy-$tab-$web')),+ );+ expect(+ y(tester, 'swarm-home-buddy-$tab-$web'),+ lessThan(y(tester, 'swarm-project-$tab-$project')),+ );+ for (final words in ['Wren', 'Mobile · Claude']) {+ expect(+ inside('swarm-home-buddy-$tab-$project', find.text(words)),+ findsOneWidget,+ reason: 'its Buddy, then its project and what it runs on',+ );+ }+ for (final words in ['Buddy', 'Web · not started']) {+ expect(+ inside('swarm-home-buddy-$tab-$web', find.text(words)),+ findsOneWidget,+ );+ }+ expect(find.text('Chat with PM'), findsNothing);+ });++ testWidgets('a project the Lead tagged the person in is bold with @N; '+ 'the rest are not, and no project has a team line (Team at a glance '+ 'is gone, as on the desktop)', (tester) async {+ final semantics = tester.ensureSemantics();+ await pump(tester, backend());++ const mobileRow = 'swarm-project-$tab-$project';+ const webRow = 'swarm-project-$tab-$web';+ expect(weightOf(tester, mobileRow, 'Mobile'), AppFont.semibold);+ expect(inside(mobileRow, find.text('@1')), findsOneWidget);+ expect(find.bySemanticsLabel(RegExp('1 mention')), findsOneWidget);+ expect(weightOf(tester, webRow, 'Web'), isNot(AppFont.semibold));+ expect(inside(webRow, find.textContaining('@')), findsNothing);+ for (final row in [mobileRow, webRow]) {+ for (final words in ['working', 'waiting', 'down', 'idle']) {+ expect(+ inside(row, find.textContaining(words)),+ findsNothing,+ reason: 'no team line',+ );+ }+ }+ semantics.dispose();+ });++ testWidgets('a project with a chat read since is bold with no count, and '+ 'so is a Buddy whose chat has new lines', (tester) async {+ final fake = backend(buddy: true);+ final host = await pump(tester, fake);+ moveOn(fake, {+ webLead: {+ ...groupData(+ webLead,+ title: 'Web',+ agentIds: ['agent-cleo'],+ leadId: 'agent-cleo',+ lastMessageSequence: 1,+ ),+ 'projectId': web,+ },+ 'buddy-me': buddyChatData(+ 'buddy-me',+ agentIds: ['agent-wren'],+ lastMessageSequence: 1,+ ),+ });+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();++ const webRow = 'swarm-project-$tab-$web';+ expect(weightOf(tester, webRow, 'Web'), AppFont.semibold);+ expect(inside(webRow, find.textContaining('@')), findsNothing);+ expect(+ weightOf(tester, 'swarm-home-buddy-$tab-$project', 'Wren'),+ AppFont.semibold,+ );+ expect(+ weightOf(tester, 'swarm-home-buddy-$tab-$web', 'Buddy'),+ isNot(AppFont.semibold),+ reason: 'not started: no chat to read',+ );+ });++ testWidgets("the prototype's top bar, captions, avatars and tiles", (+ tester,+ ) async {+ await pump(tester, backend());++ expect(+ middle(tester, key('swarm-title')),+ closeTo(middle(tester, key('swarm-menu')), 2),+ reason: 'the title beside the menu, in one bar',+ );+ expect(+ tester.getRect(key('swarm-menu')),+ const Rect.fromLTWH(+ 4,+ 0,+ 44,+ 44,+ ).shift(Offset(0, tester.getTopLeft(key('swarm-menu')).dy)),+ reason: "the prototype's 44-point menu, 4 points in",+ );+ expect(+ tester.getTopLeft(key('swarm-title')).dx,+ 4 + 44 + 4,+ reason: 'the title 4 points beside it',+ );+ expect(find.text('Swarm'), findsOneWidget);+ for (final caption in ['Needs you', 'Buddies', 'Projects']) {+ expect(find.text(caption), findsOneWidget, reason: 'sentence case');+ }+ expect(+ tester.widget<Text>(key('swarm-needs-count')).data,+ '3',+ reason: 'how many need the person, beside Needs you',+ );+ expect(+ tester.widget<Text>(key('swarm-needs-count')).style?.color,+ AppColors.warning,+ );+ expect(+ inside('swarm-home-buddy-$tab-$project', find.byType(SwarmAvatar)),+ findsOneWidget,+ reason: 'its Buddy, in a round mark',+ );+ expect(+ inside('swarm-home-buddy-$tab-$project', find.text('B')),+ findsOneWidget,+ reason: 'Buddy while none runs',+ );+ expect(+ inside('swarm-project-$tab-$project', find.byType(SwarmProjectTile)),+ findsOneWidget,+ reason: "a project's initial in a tile",+ );+ expect(inside('swarm-project-$tab-$project', find.text('m')), findsOne);+ });++ testWidgets(+ 'an open decision: its glyph, who asks and where, the question, '+ 'its options side by side; who asks opens the chat',+ (tester) async {+ await pump(tester, backend());++ const card = 'swarm-need-decision:d1';+ expect(+ inside(card, find.byIcon(LucideIcons.circleQuestionMark300)),+ findsOneWidget,+ );+ expect(+ inside(+ card,+ find.text('River asks you · Mobile', findRichText: true),+ ),+ findsOneWidget,+ );+ expect(+ inside(card, find.text('Ship it behind a flag?')),+ findsOneWidget,+ );+ expect(+ middle(tester, key('swarm-option-d1-0')),+ middle(tester, key('swarm-option-d1-1')),+ reason: 'two options share a line',+ );+ expect(+ tester.getSize(key('swarm-option-d1-0')).height,+ greaterThanOrEqualTo(44),+ );+ expect(inside(card, find.text('Open chat')), findsNothing);++ await tester.tap(key('swarm-need-open-decision:d1'));+ await tester.pumpAndSettle();+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), (tab, 'g1'));+ },+ );++ testWidgets('a need card is set on the type roles: 17-point words, '+ '16 points in, its glyph level with the first line', (tester) async {+ await pump(tester, backend());++ const card = 'swarm-need-decision:d1';+ final title = find.descendant(+ of: key(card),+ matching: find.text('River asks you · Mobile', findRichText: true),+ );+ expect(+ tester.renderObject<RenderParagraph>(title).text.style?.fontSize,+ 17,+ reason: 'the label role',+ );+ expect(+ tester+ .widget<Text>(inside(card, find.text('Ship it behind a flag?')))+ .style+ ?.fontSize,+ 17,+ reason: 'the body role',+ );+ final glyph = inside(+ card,+ find.byIcon(LucideIcons.circleQuestionMark300),+ );+ expect(tester.getTopLeft(glyph).dx - tester.getTopLeft(key(card)).dx, 16);+ expect(+ tester.getCenter(glyph).dy,+ closeTo(tester.getTopLeft(title).dy + 17 * 1.3 / 2, .1),+ reason: "centred on the title's first line (17 points at 1.3)",+ );+ });++ testWidgets('an open tag has Done, filled, and Open chat; open work has '+ 'Open chat', (tester) async {+ await pump(tester, backend());+ await tester.tap(key('swarm-need-row-mention:m1'));+ await tester.pumpAndSettle();++ expect(+ tester.widget<SwarmButton>(key('swarm-done-m1')).style,+ SwarmButtonStyle.fill,+ );+ expect(+ middle(tester, key('swarm-done-m1')),+ middle(tester, key('swarm-need-chat-mention:m1')),+ );+ expect(+ inside('swarm-need-mention:m1', find.byIcon(LucideIcons.atSign300)),+ findsOneWidget,+ );+ expect(+ inside(+ 'swarm-need-row-decision:d1',+ find.byIcon(LucideIcons.circleQuestionMark300),+ ),+ findsOneWidget,+ reason: 'a closed need keeps its glyph',+ );++ const work = 'work:$tab:g1:attempt-g1:needs_human';+ await tester.tap(key('swarm-need-row-$work'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-need-chat-$work'));+ await tester.pumpAndSettle();+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), (tab, 'g1'));+ });++ testWidgets('Needs you opens one thing at a time; a line opens the next', (+ tester,+ ) async {+ await pump(tester, backend());++ expect(key('swarm-option-d1-0'), findsOneWidget);+ expect(key('swarm-done-m1'), findsNothing);+ expect(key('swarm-need-row-mention:m1'), findsOneWidget);+ expect(+ key('swarm-need-row-work:$tab:g1:attempt-g1:needs_human'),+ findsOneWidget,+ );+ expect(find.text('River tagged you'), findsOneWidget);+ expect(find.text('Nova needs you'), findsOneWidget);++ await tester.tap(key('swarm-need-row-mention:m1'));+ await tester.pumpAndSettle();++ expect(key('swarm-done-m1'), findsOneWidget);+ expect(key('swarm-option-d1-0'), findsNothing);+ expect(key('swarm-need-row-decision:d1'), findsOneWidget);+ expect(find.text('River asks you'), findsOneWidget);+ });++ testWidgets('one tap answers, held for Undo; then the next need opens', (+ tester,+ ) async {+ final fake = backend();+ var answered = false;+ fake.routes['/api/super-tabs/$tab/commands'] = (body) {+ if (body?['command']?['type'] == 'decision.answer') answered = true;+ return {'result': <String, dynamic>{}};+ };+ final open = fake.routes['/api/super-tabs/$tab/decisions?state=open']!;+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (body) =>+ answered ? {'decisions': <Object>[]} : open(body);+ await pump(tester, fake);++ await tester.tap(key('swarm-option-d1-0'));+ await tester.pump();+ expect(find.text('Sending “Yes”'), findsOneWidget);+ expect(key('swarm-undo-d1'), findsOneWidget);+ double bar() => tester+ .widget<FractionallySizedBox>(+ inside('swarm-need-decision:d1', find.byType(FractionallySizedBox)),+ )+ .widthFactor!;+ expect(bar(), 1, reason: 'the Undo window, full');+ await tester.pump(const Duration(seconds: 2));+ expect(fake.commands, isEmpty, reason: 'still in its Undo window');+ expect(bar(), lessThan(.5), reason: 'draining');++ await tester.pump(const Duration(seconds: 2));+ await tester.pumpAndSettle();+ expect(fake.commands.single, {+ 'type': 'decision.answer',+ 'decisionId': 'd1',+ 'choice': 0,+ });+ expect(key('swarm-need-decision:d1'), findsNothing);+ expect(key('swarm-done-m1'), findsOneWidget, reason: 'the tag is next');+ });++ testWidgets('Done marks a tag done', (tester) async {+ final fake = backend();+ await pump(tester, fake);+ await tester.tap(key('swarm-need-row-mention:m1'));+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-done-m1'));+ await tester.pumpAndSettle();++ expect(fake.commands.single, {'type': 'mention.done', 'mentionId': 'm1'});+ });++ testWidgets('nothing waiting says so, and the rest of Home stays', (+ tester,+ ) async {+ final fake = backend();+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ await pump(tester, fake);++ expect(find.text('Nothing needs you.'), findsOneWidget);+ expect(key('swarm-home-buddy-$tab-$project'), findsOneWidget);+ expect(key('swarm-project-$tab-$project'), findsOneWidget);+ });++ testWidgets('a Buddy row opens the Buddy chat; one the server will not '+ 'open says why', (tester) async {+ final fake = backend(buddy: true);+ fake.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw const SuperTabFailure(+ 'FORBIDDEN',+ 'You cannot read this project.',+ statusCode: 403,+ );+ await pump(tester, fake);++ await tester.tap(key('swarm-home-buddy-$tab-$web'));+ await tester.pumpAndSettle();+ expect(fake.commands.single, {'type': 'buddy.chat', 'projectId': web});+ expect(find.byType(SwarmConversationPage), findsNothing);+ expect(+ tester.widget<Text>(key('swarm-buddy-error')).data,+ 'You cannot read this project.',+ );++ await tester.tap(key('swarm-home-buddy-$tab-$project'));+ await tester.pumpAndSettle();+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), (tab, 'buddy-me'));+ expect(fake.commands, hasLength(1), reason: 'that one was held');+ });++ testWidgets('back from a Buddy chat, Home still has its menu, and it '+ 'opens the drawer', (tester) async {+ await pump(tester, backend(buddy: true));++ await tester.tap(key('swarm-home-buddy-$tab-$project'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmConversationPage), findsOneWidget);++ await tester.tap(key('tty-back'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmConversationPage), findsNothing);+ expect(key('swarm-menu'), findsOneWidget);+ expect(key('tty-back'), findsNothing, reason: 'Home is the root');++ await openDrawer(tester);+ expect(find.byType(SwarmDrawer), findsOneWidget);+ });++ testWidgets('opened over another page, it has back instead of the menu, '+ 'and back goes to that page', (tester) async {+ await pump(tester, backend(), overPage: true);+ expect(find.byType(SwarmPage), findsOneWidget);+ expect(key('swarm-menu'), findsNothing);++ await tester.tap(key('tty-back'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmPage), findsNothing);+ expect(key('page-under'), findsOneWidget);+ });++ testWidgets("back from the drawer's Buddy chat, Home still has its menu", (+ tester,+ ) async {+ await pump(tester, backend(buddy: true));+ await openDrawer(tester);+ await tester.tap(key('swarm-drawer-chats-$tab-$project'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-drawer-buddy-chat-$tab-$project'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmConversationPage), findsOneWidget);++ await tester.tap(key('tty-back'));+ await tester.pumpAndSettle();+ expect(key('swarm-menu'), findsOneWidget);+ expect(key('tty-back'), findsNothing, reason: 'Home is the root');+ });++ testWidgets('a project opens its page', (tester) async {+ await pump(tester, backend());++ await tester.tap(key('swarm-project-$tab-$web'));+ await tester.pumpAndSettle();++ final page = tester.widget<SwarmProjectPage>(+ find.byType(SwarmProjectPage),+ );+ expect((page.swarmId, page.projectId), (tab, web));+ });+ });++ group('a project', () {+ Future<void> openProject(WidgetTester tester, String id) async {+ await tester.tap(key('swarm-project-$tab-$id'));+ await tester.pumpAndSettle();+ }++ /// The project's ⋮ menu, open.+ Future<void> openMenu(WidgetTester tester) async {+ await tester.tap(key('swarm-project-menu'));+ await tester.pumpAndSettle();+ }++ /// The project's work and team, from its menu's status row.+ Future<void> openSheet(WidgetTester tester) async {+ await openMenu(tester);+ await tester.tap(key('swarm-project-menu-status'));+ await tester.pumpAndSettle();+ }++ /// The words of the menu's status row.+ TextSpan statusWords(WidgetTester tester) =>+ tester+ .widget<RichText>(+ find.descendant(+ of: inside(+ 'swarm-project-menu-status',+ find.byType(SwarmStatusText),+ ),+ matching: find.byType(RichText),+ ),+ )+ .text+ as TextSpan;+ String status(WidgetTester tester) => statusWords(tester).toPlainText();+ Color? colorOf(WidgetTester tester, String words) {+ Color? found;+ statusWords(tester).visitChildren((span) {+ if (span is TextSpan && span.text == words) found = span.style?.color;+ return true;+ });+ return found;+ }++ testWidgets('opens on its project chat, its name over who is in it, its '+ 'menu at the top right, and nothing under the header', (tester) async {+ await pump(tester, backend());+ await openProject(tester, project);++ final chat = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((chat.swarmId, chat.conversationId), (tab, leadChat));+ expect(tester.widget<Text>(key('swarm-title')).data, 'Mobile');+ expect(find.text('River and everyone'), findsOneWidget);+ expect(key('swarm-field'), findsOneWidget, reason: 'its composer');+ expect(key('swarm-lead-chat'), findsNothing, reason: 'no row to open');+ expect(find.text('Working on'), findsNothing, reason: 'in the sheet');++ expect(+ key('swarm-team-line'),+ findsNothing,+ reason: 'no team strip under the header (Tony, 2026-10-29)',+ );+ expect(find.byType(SwarmAvatar), findsNothing, reason: 'no faces');+ expect(+ find.textContaining('waiting on you'),+ findsNothing,+ reason: 'the status is in the menu',+ );+ expect(+ key('swarm-project-menu-buddy-chat'),+ findsNothing,+ reason: 'in the menu',+ );+ expect(find.text('Chat with PM'), findsNothing);++ final menu = key('swarm-project-menu');+ expect(tester.getSize(menu), const Size(44, 44), reason: 'a thumb');+ final glyph = find.descendant(+ of: menu,+ matching: find.byIcon(LucideIcons.ellipsisVertical300),+ );+ expect(glyph, findsOneWidget);+ expect(+ tester.getTopLeft(menu).dx,+ greaterThan(tester.getTopRight(key('swarm-title')).dx),+ reason: 'at the end of the header',+ );+ expect(+ middle(tester, menu),+ closeTo(middle(tester, key('tty-back')), 2),+ reason: 'in the one bar with back',+ );+ expect(+ tester.getTopRight(glyph).dx,+ tester.getSize(find.byType(SwarmConversationPage)).width -+ AppSpace.screenInset,+ reason: "on the screen's side margin, not its edge",+ );+ });++ testWidgets('its menu has Buddy chat, then the team in words, each a '+ 'row a thumb can press', (tester) async {+ await pump(tester, backend());+ await openProject(tester, project);+ await openMenu(tester);++ expect(+ inside('swarm-project-menu-buddy-chat', find.text('Buddy chat')),+ findsOneWidget,+ );+ expect(find.text('Chat with PM'), findsNothing, reason: 'closed (#2090)');+ expect(+ status(tester),+ '1 waiting on you · 1 down',+ reason: 'Fix login waits on the person; of the team, Atlas is down',+ );+ expect(colorOf(tester, '1 waiting on you'), AppColors.warning);+ expect(colorOf(tester, '1 down'), AppColors.danger);+ expect(+ find.descendant(+ of: find.byType(BottomSheet),+ matching: find.byType(SwarmAvatar),+ ),+ findsNothing,+ reason: 'words only, no faces',+ );+ expect(+ inside(+ 'swarm-project-menu-status',+ find.byIcon(LucideIcons.chevronRight300),+ ),+ findsOneWidget,+ reason: 'it opens more',+ );+ expect(+ y(tester, 'swarm-project-menu-buddy-chat'),+ lessThan(y(tester, 'swarm-project-menu-status')),+ reason: 'Buddy chat first, where Chat with PM was',+ );+ for (final row in [+ 'swarm-project-menu-buddy-chat',+ 'swarm-project-menu-status',+ ]) {+ expect(+ tester.getSize(key(row)).height,+ greaterThanOrEqualTo(44),+ reason: row,+ );+ }+ });++ testWidgets('with nothing waiting on the person, the menu says the team '+ 'in one line', (tester) async {+ final fake = backend();+ final parts = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) {+ final load = parts(body)! as Map<String, dynamic>;+ return {+ ...load,+ 'groups': [+ for (final row in load['groups'] as List)+ if ((row as Map)['key'] == 'g1')+ {+ ...row,+ 'data': {+ ...row['data'] as Map,+ 'assignment': {+ ...(row['data'] as Map)['assignment'] as Map,+ 'status': 'working',+ },+ },+ }+ else+ row,+ ],+ };+ };+ await pump(tester, fake);+ await openProject(tester, project);+ await openMenu(tester);++ expect(status(tester), '1 working · 1 down', reason: 'Nova and Atlas');+ expect(colorOf(tester, '1 down'), AppColors.danger);+ expect(find.textContaining('waiting on you'), findsNothing);+ });++ testWidgets("the menu's counts follow the Swarm while it is open", (+ tester,+ ) async {+ final fake = backend();+ final host = await pump(tester, fake);+ await openProject(tester, project);+ await openMenu(tester);+ expect(status(tester), '1 waiting on you · 1 down');++ // Nova goes down too.+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(+ cursor: 'c3',+ lastChangedAt: 200,+ derived: const {'decisionsWaiting': 1, 'mentionsWaiting': 1},+ ),+ 'agents': [+ part('agent-builder', 2, {+ ...agent('agent-builder', displayName: 'Nova'),+ 'downSince': '2026-10-29T01:00:00.000Z',+ }),+ ],+ };+ unawaited(host.session!.inbox.reader(tab)!.refresh());+ await tester.pumpAndSettle();++ expect(status(tester), '1 waiting on you · 2 down', reason: 'Nova too');+ expect(+ key('swarm-project-menu-buddy-chat'),+ findsOneWidget,+ reason: 'open',+ );+ });++ testWidgets("a viewer with no Buddy chat in the project has the menu's "+ 'team alone: they start no Buddy', (tester) async {+ final fake = backend();+ final parts = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) => {+ ...parts(body)! as Map<String, dynamic>,+ 'members': [part(me, 1, person(me, role: 'viewer'))],+ };+ await pump(tester, fake);+ await openProject(tester, project);+ await openMenu(tester);++ expect(key('swarm-project-menu-buddy-chat'), findsNothing);+ expect(status(tester), '1 waiting on you · 1 down');+ });++ testWidgets("the menu's status opens the project's work: waiting on you, "+ 'then working on', (tester) async {+ await pump(tester, backend());+ await openProject(tester, project);+ await openSheet(tester);++ expect(find.byType(SwarmProjectSheet), findsOneWidget);+ expect(+ key('swarm-project-menu-status'),+ findsNothing,+ reason: 'the menu closed for it',+ );+ expect(find.byType(SwarmProjectPage), findsOneWidget, reason: 'under it');+ expect(+ tester.getTopLeft(find.text('Waiting on you')).dy,+ lessThan(y(tester, 'swarm-conversation-g1')),+ );+ expect(+ y(tester, 'swarm-conversation-g1'),+ lessThan(tester.getTopLeft(find.text('Working on')).dy),+ reason: 'Nova waits on the person, though Sync is newer',+ );+ expect(+ tester.getTopLeft(find.text('Working on')).dy,+ lessThan(y(tester, 'swarm-conversation-g-busy')),+ );+ expect(+ inside(+ 'swarm-conversation-g1',+ find.text('#4 Fix login', findRichText: true),+ ),+ findsOneWidget,+ );+ expect(+ inside('swarm-conversation-g1', find.text('Nova · Needs human')),+ findsOneWidget,+ );+ expect(+ inside('swarm-conversation-g1', find.byType(SwarmAvatar)),+ findsOneWidget,+ reason: 'who holds it',+ );+ expect(+ tester+ .getTopLeft(inside('swarm-conversation-g-busy', find.text('Sync')))+ .dx,+ tester+ .getTopLeft(+ inside(+ 'swarm-conversation-g1',+ find.text('#4 Fix login', findRichText: true),+ ),+ )+ .dx,+ reason: 'work nobody holds lines up with work an agent holds',+ );+ expect(+ key('swarm-conversation-$leadChat'),+ findsNothing,+ reason: 'the project chat is the screen, not a row',+ );+ });++ testWidgets("the menu's Buddy chat opens the person's Buddy chat, and back "+ 'comes back to the project chat', (tester) async {+ await pump(tester, backend(buddy: true));+ await openProject(tester, project);+ await openMenu(tester);++ await tester.tap(key('swarm-project-menu-buddy-chat'));+ await tester.pumpAndSettle();+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), (tab, 'buddy-me'));++ await tester.tap(key('tty-back'));+ await tester.pumpAndSettle();+ expect(key('swarm-project-menu'), findsOneWidget, reason: 'back on it');+ expect(+ key('swarm-project-menu-buddy-chat'),+ findsNothing,+ reason: 'the menu closed as the chat opened',+ );+ await tester.tap(key('tty-back'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmProjectPage), findsNothing);+ expect(key('swarm-menu'), findsOneWidget, reason: 'back on Home');+ });++ testWidgets("the sheet's Team lists each agent in a word", (tester) async {+ final fake = backend();+ final parts = fake.routes['/api/super-tabs/$tab/parts']!;+ fake.routes['/api/super-tabs/$tab/parts'] = (body) {+ final load = parts(body)! as Map<String, dynamic>;+ return {+ ...load,+ 'agents': [+ for (final row in load['agents'] as List)+ if ((row as Map)['key'] == 'agent-atlas')+ {+ ...row,+ 'data': {...row['data'] as Map, 'role': 'reviewer'},+ }+ else+ row,+ ],+ };+ };+ await pump(tester, fake);+ await openProject(tester, project);++ await openSheet(tester);+ expect(key('swarm-agent-agent-lead'), findsNothing, reason: 'Work first');+ await tester.tap(key('swarm-sheet-team'));+ await tester.pumpAndSettle();++ expect(key('swarm-conversation-g1'), findsNothing);+ for (final id in ['agent-lead', 'agent-builder', 'agent-atlas']) {+ expect(key('swarm-agent-$id'), findsOneWidget);+ }+ expect(+ inside('swarm-agent-agent-lead', find.text('PM')),+ findsOneWidget,+ reason: 'the Product Manager is marked',+ );+ expect(+ inside('swarm-agent-agent-builder', find.text('Dev')),+ findsOneWidget,+ reason: "each agent's role in a tag, as the prototype",+ );+ expect(inside('swarm-agent-agent-atlas', find.text('Rev')), findsOne);+ expect(+ y(tester, 'swarm-agent-agent-lead'),+ lessThan(y(tester, 'swarm-agent-agent-builder')),+ reason: 'the Product Manager first, then who needs the person',+ );+ expect(+ y(tester, 'swarm-agent-agent-builder'),+ lessThan(y(tester, 'swarm-agent-agent-atlas')),+ );+ expect(+ inside(+ 'swarm-agent-agent-atlas',+ find.textContaining('Lost', findRichText: true),+ ),+ findsOneWidget,+ reason: 'its state in a word',+ );++ await tester.tap(key('swarm-sheet-work'));+ await tester.pumpAndSettle();+ expect(key('swarm-conversation-g1'), findsOneWidget);++ await tester.tap(key('swarm-team-close'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmProjectSheet), findsNothing);+ expect(+ key('swarm-project-menu'),+ findsOneWidget,+ reason: 'back on the chat',+ );+ });++ testWidgets('Buddy chat shows it is opening in place of the menu, and '+ 'says why it did not open', (tester) async {+ final semantics = tester.ensureSemantics();+ final fake = backend();+ final answer = Completer<Object?>();+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => answer.future;+ await pump(tester, fake);+ await openProject(tester, web);++ await openMenu(tester);+ await tester.tap(key('swarm-project-menu-buddy-chat'));+ // A spinner turns until the answer: nothing settles.+ await frames(tester);+ expect(+ key('swarm-project-menu-buddy-chat'),+ findsNothing,+ reason: 'the menu closed',+ );+ expect(+ inside('swarm-project-menu', find.byType(CircularProgressIndicator)),+ findsOneWidget,+ );+ expect(find.bySemanticsLabel('Opening Buddy chat…'), findsOneWidget);+ await tester.tap(key('swarm-project-menu'));+ await frames(tester);+ expect(+ key('swarm-project-menu-status'),+ findsNothing,+ reason: 'no menu while it opens',+ );+ expect(fake.commands, [+ {'type': 'buddy.chat', 'projectId': web},+ ], reason: 'one tap, one chat');++ answer.complete({'result': <String, dynamic>{}});+ await tester.pumpAndSettle();+ expect(+ tester+ .widget<SwarmConversationPage>(find.byType(SwarmConversationPage))+ .conversationId,+ webLead,+ reason: 'no Buddy chat over the project chat',+ );+ expect(+ find.descendant(+ of: key('swarm-buddy-error'),+ matching: find.text('Your Buddy chat is not ready yet. Try again.'),+ matchRoot: true,+ ),+ findsOneWidget,+ );+ expect(+ inside(+ 'swarm-project-menu',+ find.byIcon(LucideIcons.ellipsisVertical300),+ ),+ findsOneWidget,+ reason: 'the menu is back',+ );+ semantics.dispose();+ });++ testWidgets('a task in the sheet opens over it, and back returns to the '+ 'sheet', (tester) async {+ await pump(tester, backend());+ await openProject(tester, project);+ await openSheet(tester);++ await tester.tap(key('swarm-conversation-g-busy'));+ await tester.pumpAndSettle();+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId), (tab, 'g-busy'));++ await tester.tap(key('tty-back'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmProjectSheet), findsOneWidget);+ expect(key('swarm-conversation-g-busy'), findsOneWidget);+ });+ });++ group('while Home reads', () {+ /// [path] answers only once the returned gate is opened.+ Completer<void> hold(FakeSwarm fake, String path) {+ final gate = Completer<void>();+ final answer = fake.routes[path]!;+ fake.routes[path] = (body) async {+ await gate.future;+ return answer(body);+ };+ return gate;+ }++ double height(WidgetTester tester, String k) =>+ tester.getSize(key(k)).height;++ const decision = {+ 'id': 'd1',+ 'projectName': 'Mobile',+ 'conversationId': leadChat,+ 'conversationTitle': 'Mobile',+ 'askerName': 'River',+ 'question': 'Ship it behind a flag?',+ 'options': ['Yes', 'No'],+ };++ /// One Swarm whose counts say a decision waits, with no work waiting:+ /// what waits on the person is the decision alone.+ FakeSwarm deciding() {+ final fake = backend();+ fake.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(derived: const {'decisionsWaiting': 1});+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ return fake;+ }++ testWidgets('before the list answers, Needs you, Buddies and the '+ 'projects are skeleton rows, and nothing says it is reading', (+ tester,+ ) async {+ final fake = backend();+ final listed = hold(fake, '/api/super-tabs/list');+ await pump(tester, fake, settle: false);++ for (final k in [+ 'swarm-needs-loading',+ 'swarm-buddy-loading',+ 'swarm-projects-loading',+ ]) {+ expect(key(k), findsOneWidget, reason: k);+ }+ expect(+ y(tester, 'swarm-needs-loading'),+ lessThan(y(tester, 'swarm-buddy-loading')),+ );+ expect(+ y(tester, 'swarm-buddy-loading'),+ lessThan(y(tester, 'swarm-projects-loading')),+ );+ expect(find.text('Buddies'), findsOneWidget);+ expect(find.text('Projects'), findsOneWidget);+ expect(find.text('Nothing needs you.'), findsNothing);+ expect(find.textContaining('Reading'), findsNothing);++ listed.complete();+ await tester.pumpAndSettle();++ expect(key('swarm-needs-loading'), findsNothing);+ expect(key('swarm-projects-loading'), findsNothing);+ expect(key('swarm-project-$tab-$project'), findsOneWidget);+ });++ for (final scale in [1.0, 1.3]) {+ testWidgets('skeleton rows are as tall as the rows that replace them '+ '(text at $scale)', (tester) async {+ tester.platformDispatcher.textScaleFactorTestValue = scale;+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);+ final fake = backend();+ final listed = hold(fake, '/api/super-tabs/list');+ await pump(tester, fake, settle: false);+ final buddy = height(tester, 'swarm-buddy-loading-0');+ final row = height(tester, 'swarm-projects-loading-0');++ listed.complete();+ await tester.pumpAndSettle();++ expect(+ height(tester, 'swarm-home-buddy-$tab-$project'),+ closeTo(buddy, .01),+ );+ expect(+ height(tester, 'swarm-project-$tab-$web'),+ closeTo(row, .01),+ reason: 'its title alone, as the skeleton draws it',+ );+ });+ }++ testWidgets('of two Swarms, the one still to be read has its rows on '+ 'their way under its name, on Home and in the drawer', (tester) async {+ const second = 'tab-2';+ final fake = backend();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ {'id': second, 'name': 'Second Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$second/parts'] = (_) => firstLoad(+ tabId: second,+ head: headData(id: second, name: 'Second Swarm'),+ );+ final read = hold(fake, '/api/super-tabs/$tab/parts');+ await pump(tester, fake, settle: false);++ expect(key('swarm-project-$second-$project'), findsOneWidget);+ expect(key('swarm-home-buddy-$second-$project'), findsOneWidget);+ expect(key('swarm-buddy-loading-$tab'), findsOneWidget);+ expect(key('swarm-projects-loading-$tab'), findsOneWidget);+ expect(+ y(tester, 'swarm-projects-loading-$tab'),+ greaterThan(tester.getTopLeft(find.text('Phone Swarm').first).dy),+ reason: 'under its own name',+ );+ expect(key('swarm-needs-loading'), findsOneWidget);+ expect(find.text('Nothing needs you.'), findsNothing);+ await tester.tap(key('swarm-menu'));+ await frames(tester);+ expect(key('swarm-drawer-loading-$tab'), findsOneWidget);+ expect(key('swarm-drawer-project-$second-$project'), findsOneWidget);++ read.complete();+ await tester.pumpAndSettle();++ expect(key('swarm-drawer-loading-$tab'), findsNothing);+ expect(key('swarm-drawer-project-$tab-$project'), findsOneWidget);+ expect(key('swarm-projects-loading-$tab'), findsNothing);+ expect(key('swarm-project-$tab-$project'), findsOneWidget);+ });++ testWidgets('what waits is read before Home says nothing needs you', (+ tester,+ ) async {+ final fake = deciding()+ ..routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [decision],+ };+ final asked = hold(fake, '/api/super-tabs/$tab/decisions?state=open');+ await pump(tester, fake, settle: false);++ expect(key('swarm-project-$tab-$project'), findsOneWidget);+ expect(key('swarm-needs-loading'), findsOneWidget);+ expect(find.text('Nothing needs you.'), findsNothing);++ asked.complete();+ await tester.pumpAndSettle();++ expect(key('swarm-needs-loading'), findsNothing);+ expect(key('swarm-need-decision:d1'), findsOneWidget);+ });++ testWidgets('read again in full, what waits is read again before Home '+ 'says nothing needs you; a failure ends the skeleton', (tester) async {+ final fake = deciding()+ ..routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [decision],+ };+ final host = await pump(tester, fake);+ expect(key('swarm-need-decision:d1'), findsOneWidget);++ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) =>+ throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);+ final asked = hold(fake, '/api/super-tabs/$tab/decisions?state=open');+ unawaited(host.session!.inbox.refresh());+ await frames(tester);++ expect(key('swarm-need-decision:d1'), findsNothing);+ expect(key('swarm-needs-loading'), findsOneWidget);+ expect(find.text('Nothing needs you.'), findsNothing);++ asked.complete();+ await tester.pumpAndSettle();++ expect(key('swarm-needs-loading'), findsNothing);+ expect(find.text('Nothing needs you.'), findsNothing);+ expect(key('swarm-needs-unread'), findsOneWidget);+ });++ testWidgets('a tag marked done leaves "Nothing needs you", with no '+ 'skeleton between', (tester) async {+ final fake = deciding();+ fake.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(derived: const {'mentionsWaiting': 1});+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ var waiting = true;+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [+ if (waiting)+ {+ 'id': 'm1',+ 'projectName': 'Mobile',+ 'conversationId': leadChat,+ 'conversationTitle': 'Mobile',+ 'messageId': 'msg-1',+ 'leadName': 'River',+ 'text': 'Can you check the copy?',+ },+ ],+ };+ final read = hold(fake, '/api/super-tabs/$tab/changes');+ fake.routes['/api/super-tabs/$tab/commands'] = (_) {+ waiting = false;+ return {'result': <String, dynamic>{}};+ };+ await pump(tester, fake);++ await tester.tap(key('swarm-done-m1'));+ await frames(tester);++ expect(+ key('swarm-needs-loading'),+ findsNothing,+ reason: 'what waits was read; only the Swarm count is behind',+ );+ expect(find.text('Nothing needs you.'), findsOneWidget);+ read.complete();+ await tester.pumpAndSettle();+ });++ testWidgets('what waits that could not be read says so, not that '+ 'nothing needs you', (tester) async {+ final fake = deciding()+ ..routes['/api/super-tabs/$tab/decisions?state=open'] = (_) =>+ throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);+ await pump(tester, fake);++ expect(key('swarm-needs-loading'), findsNothing);+ expect(find.text('Nothing needs you.'), findsNothing);+ expect(+ tester.widget<Text>(key('swarm-needs-unread')).data,+ 'Could not load what is waiting for you. Try again.',+ );+ });++ testWidgets('a Swarm that could not be read says so, with no skeleton '+ 'left and no "Nothing needs you"', (tester) async {+ final fake = backend()+ ..routes['/api/super-tabs/$tab/parts'] = (_) =>+ throw SuperTabFailure('INTERNAL', 'Broken', statusCode: 500);+ await pump(tester, fake);++ expect(key('swarm-needs-loading'), findsNothing);+ expect(key('swarm-projects-loading-$tab'), findsNothing);+ expect(find.text('Nothing needs you.'), findsNothing);+ expect(key('swarm-needs-unread'), findsOneWidget);+ expect(find.text('Pull down to try again.'), findsOneWidget);+ });++ testWidgets('the drawer has skeleton project rows before the list, as '+ 'tall as the rows that replace them', (tester) async {+ final fake = backend();+ final listed = hold(fake, '/api/super-tabs/list');+ await pump(tester, fake, settle: false);+ await tester.tap(key('swarm-menu'));+ await frames(tester);++ expect(+ find.descendant(+ of: find.byType(SwarmDrawer),+ matching: find.text('Projects'),+ ),+ findsOneWidget,+ );+ final row = height(tester, 'swarm-drawer-loading-0');+ listed.complete();+ await tester.pumpAndSettle();++ expect(key('swarm-drawer-loading'), findsNothing);+ expect(+ height(tester, 'swarm-drawer-project-$tab-$web'),+ closeTo(row, .01),+ );+ });++ testWidgets("a closed project in the drawer works out none of its chats", (+ tester,+ ) async {+ final host = await pump(tester, backend());+ final inbox = host.session!.inbox;+ final needs = _Reads(inbox.needs);+ inbox.needs = needs;++ await openDrawer(tester);+ expect(needs.reads, 0, reason: 'both projects are closed');++ await tester.tap(key('swarm-drawer-chats-$tab-$project'));+ await tester.pumpAndSettle();+ expect(+ needs.reads,+ greaterThan(0),+ reason: 'the open one lists what waits on the person first',+ );+ expect(+ y(tester, 'swarm-drawer-chat-g1'),+ lessThan(y(tester, 'swarm-drawer-chat-g-busy')),+ );+ });+ });++ group('the start screens', () {+ const mac = (name: 'MacBook Pro', away: false);++ testWidgets('with no computer, Home draws its start screen in place of '+ 'its body, under its own top bar', (tester) async {+ await pump(tester, backend(), computers: _Computers(const []));++ expect(find.byType(SwarmStartView), findsOneWidget);+ expect(key('swarm-menu'), findsOneWidget, reason: 'the drawer stays');+ expect(tester.widget<Text>(key('swarm-title')).data, 'Swarm');+ expect(find.text('Needs you'), findsNothing);+ });++ testWidgets('a computer coming back brings Home back', (tester) async {+ final computers = _Computers(const []);+ await pump(tester, backend(), computers: computers);+ expect(find.byType(SwarmStartView), findsOneWidget);++ computers.set(const [mac]);+ await tester.pumpAndSettle();++ expect(find.byType(SwarmStartView), findsNothing);+ expect(find.text('Needs you'), findsOneWidget);+ });++ testWidgets('with a computer and a Swarm, Home is as it was', (+ tester,+ ) async {+ await pump(tester, backend(), computers: _Computers(const [mac]));++ expect(find.byType(SwarmStartView), findsNothing);+ expect(find.text('Needs you'), findsOneWidget);+ });+ });+}diff --git a/mobile/test/swarm/swarm_inbox_test.dart b/mobile/test/swarm/swarm_inbox_test.dartnew file mode 100644index 000000000..45099bae5--- /dev/null+++ b/mobile/test/swarm/swarm_inbox_test.dart@@ -0,0 +1,925 @@+import 'dart:async';+import 'dart:convert';++import 'package:fake_async/fake_async.dart';+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_inbox.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import '../voice_fakes.dart' show MemoryKeyValueStore;++import 'swarm_fixture.dart';++/// The account's Swarms on the phone, and everything they ask of the person in+/// one list: open decisions, Lead tags and work waiting on them.+void main() {+ Map<String, dynamic> listing(String id, String name) => {+ 'id': id,+ 'name': name,+ 'ownerId': me,+ 'paused': false,+ 'lastChangedAt': 100,+ };++ /// [swarms] answer a first load each, with [groups] of their own.+ FakeSwarm backend(+ Map<String, List<Map<String, dynamic>>> swarms, {+ Map<String, Map<String, dynamic>> derived = const {},+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [for (final id in swarms.keys) listing(id, 'Swarm $id')],+ 'next': null,+ };+ for (final MapEntry(key: id, value: groups) in swarms.entries) {+ fake.routes['/api/super-tabs/$id/parts'] = (_) => firstLoad(+ tabId: id,+ groups: groups,+ derived: derived[id] ?? const {},+ );+ fake.routes['/api/super-tabs/$id/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived[id] ?? const {});+ }+ return fake;+ }++ SwarmInbox inbox(FakeSwarm fake) {+ final inbox = SwarmInbox(accountId: me, request: fake.request);+ addTearDown(inbox.dispose);+ return inbox;+ }++ test("lists the account's Swarms, every page of them", () async {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list?after=p2'] = (_) => {+ 'tabs': [listing('b', 'Beta')],+ 'next': null,+ };+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [listing('a', 'Alpha')],+ 'next': 'p2',+ };+ fake.routes['/api/super-tabs/a/parts'] = (_) => firstLoad(tabId: 'a');+ fake.routes['/api/super-tabs/b/parts'] = (_) => firstLoad(tabId: 'b');+ final i = inbox(fake);++ await i.refresh();++ expect([for (final s in i.swarms) s.name], ['Alpha', 'Beta']);+ expect(i.error, isNull);+ });++ test(+ 'a list that repeats its cursor is refused, and the last list stays',+ () async {+ final fake = backend({'a': []});+ final i = inbox(fake);+ await i.refresh();++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [listing('z', 'Zed')],+ 'next': 'loop',+ };+ fake.routes['/api/super-tabs/list?after=loop'] = (_) => {+ 'tabs': <Object>[],+ 'next': 'loop',+ };+ await i.refresh();++ expect([for (final s in i.swarms) s.id], ['a']);+ expect(i.error, isNotNull);+ },+ );++ test('what each Swarm asks of the person is one list', () async {+ final fake = backend(+ {+ 'a': [groupData('g1', title: 'Login', status: 'needs_human')],+ 'b': [],+ },+ derived: {+ 'b': {'decisionsWaiting': 1, 'mentionsWaiting': 0},+ },+ );+ fake.routes['/api/super-tabs/b/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'conversationId': 'g9',+ 'question': 'Ship it?',+ 'options': ['Yes', 'No'],+ 'createdAt': '2026-10-27T01:00:00.000Z',+ },+ ],+ };+ fake.routes['/api/super-tabs/b/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ final i = inbox(fake);++ await i.refresh();+ await settle();++ expect(i.needs, hasLength(2));+ expect(+ i.needs.whereType<SwarmDecisionNeed>().single.decision.question,+ 'Ship it?',+ );+ expect(i.needs.whereType<SwarmDecisionNeed>().single.swarmId, 'b');+ final work = i.needs.whereType<SwarmWorkNeed>().single;+ expect(work.work.conversation.title, 'Login');+ expect(work.swarmId, 'a');+ });++ test('a Swarm the person left is dropped, with all it held', () async {+ final fake = backend({+ 'a': [groupData('g1', status: 'needs_human')],+ 'b': [],+ });+ final i = inbox(fake);+ await i.refresh();+ expect(i.reader('a'), isNotNull);++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [listing('b', 'Swarm b')],+ 'next': null,+ };+ await i.refresh();++ expect([for (final s in i.swarms) s.id], ['b']);+ expect(i.reader('a'), isNull);+ expect(i.needs, isEmpty);+ });++ test(+ 'a Swarm the person left takes its chat off a screen still holding it',+ () async {+ final fake = backend({+ 'a': [groupData('g1', title: 'Login', lastMessageSequence: 1)],+ });+ fake.routes['/api/super-tabs/a/conversations/g1/messages'] = (_) => {+ 'messages': [+ {+ 'id': 'm1',+ 'conversationId': 'g1',+ 'text': 'private plan',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ },+ ],+ 'next': null,+ };+ final i = inbox(fake);+ await i.refresh();+ final held = i.reader('a')!;+ final chat = SwarmConversation(held, 'g1');+ addTearDown(chat.dispose);+ await chat.load();+ chat.draft = 'my reply';+ expect(chat.messages, hasLength(1));++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': <Object>[],+ 'next': null,+ };+ await i.refresh();++ expect(held.snapshot, isNull);+ expect(chat.messages, isEmpty);+ expect(chat.draft, isEmpty);+ },+ );++ test(+ 'a private question is out of the list from the moment the Swarm is '+ 'read again in full, even when the new read of what waits fails',+ () async {+ const derived = {'decisionsWaiting': 1, 'mentionsWaiting': 0};+ final fake = backend(+ {+ 'a': [+ groupData(+ 'g-private',+ title: 'Pair',+ audience: [me, 'person-other'],+ ),+ ],+ },+ derived: {'a': derived},+ );+ Object? open = {+ 'decisions': [+ {+ 'id': 'd1',+ 'conversationId': 'g-private',+ 'question': 'Rotate the keys?',+ 'options': ['Yes', 'No'],+ },+ ],+ };+ fake.routes['/api/super-tabs/a/decisions?state=open'] = (_) => open;+ fake.routes['/api/super-tabs/a/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ final i = inbox(fake);+ await i.refresh();+ await settle();+ expect(i.needs.whereType<SwarmDecisionNeed>(), hasLength(1));++ // Taken out of the private chat: the Swarm is read again without it,+ // and the read of what waits for the person stalls.+ fake.routes['/api/super-tabs/a/parts'] = (_) =>+ firstLoad(tabId: 'a', derived: derived);+ fake.routes['/api/super-tabs/a/changes'] = (_) => {'reload': true};+ final stalled = Completer<Object?>();+ open = stalled.future;+ await i.refresh();+ await settle();++ expect(i.needs.whereType<SwarmDecisionNeed>(), isEmpty);++ stalled.completeError(+ const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.'),+ );+ await settle();++ expect(i.needs.whereType<SwarmDecisionNeed>(), isEmpty);+ },+ );++ test('work that starts waiting after the first read is news', () async {+ var status = 'working';+ var changedAt = 100;+ final fake = backend({'a': []});+ // The status is a part: its change moves the Swarm's last change.+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {...listing('a', 'Swarm a'), 'lastChangedAt': changedAt},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/a/parts'] = (_) => firstLoad(+ tabId: 'a',+ groups: [groupData('g1', title: 'Login', status: status)],+ );+ fake.routes['/api/super-tabs/a/changes'] = (_) => changes(+ cursor: 'c2',+ groups: [part('g1', 50, groupData('g1', title: 'Login', status: status))],+ lastChangedAt: changedAt,+ );+ final i = inbox(fake);+ final news = <SwarmNeed>[];+ i.onArrived = news.add;+ await i.refresh();+ expect(news, isEmpty);++ status = 'needs_human';+ changedAt = 200;+ await i.refresh();++ expect(news.single, isA<SwarmWorkNeed>());+ await i.refresh();+ expect(news, hasLength(1), reason: 'still waiting is not news again');+ });++ group('a poll reads a Swarm again', () {+ /// Swarms `a` and `b`, listed as last changed at [changedAt].+ FakeSwarm two(+ Map<String, int> changedAt, {+ Map<String, Map<String, dynamic>> derived = const {},+ }) {+ final fake = backend({'a': [], 'b': []}, derived: derived);+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ for (final id in ['a', 'b'])+ {...listing(id, 'Swarm $id'), 'lastChangedAt': changedAt[id]},+ ],+ 'next': null,+ };+ return fake;+ }++ int changeReads(FakeSwarm fake, String id) => fake.paths+ .where((p) => p.startsWith('/api/super-tabs/$id/changes'))+ .length;++ // Every Swarm was read every 15 seconds whether it had changed or not+ // (audit of 44d284f65, swarm_inbox.dart:280).+ test('only when its listed last change moved', () async {+ final changedAt = {'a': 100, 'b': 100};+ final fake = two(changedAt);+ fake.routes['/api/super-tabs/a/changes'] = (_) =>+ changes(cursor: 'c2', lastChangedAt: 200);+ final i = inbox(fake);+ await i.refresh();+ await settle();++ changedAt['a'] = 200;+ await i.refresh();+ await settle();+ await i.refresh();+ await settle();++ expect(changeReads(fake, 'a'), 1);+ expect(changeReads(fake, 'b'), 0);+ });++ test(+ 'a Swarm never changed is listed with no time, and read once',+ () async {+ final fake = two({});+ fake.routes['/api/super-tabs/a/parts'] = (_) =>+ firstLoad(tabId: 'a', lastChangedAt: 0);+ fake.routes['/api/super-tabs/a/changes'] = (_) =>+ changes(cursor: 'c2', lastChangedAt: 0);+ final i = inbox(fake);+ await i.refresh();+ await settle();++ await i.refresh();+ await settle();++ expect(changeReads(fake, 'a'), 0);+ },+ );++ // Decisions and tags are not parts: one answered or done on another+ // device moves no last-change time.+ test('every poll while something waits in it', () async {+ final fake = two(+ {'a': 100, 'b': 100},+ derived: {+ 'a': {'decisionsWaiting': 1, 'mentionsWaiting': 0},+ },+ );+ fake.routes['/api/super-tabs/a/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'conversationId': 'g1',+ 'question': 'Ship it?',+ 'options': ['Yes'],+ },+ ],+ };+ final i = inbox(fake);+ await i.refresh();+ await settle();++ await i.refresh();+ await settle();+ await i.refresh();+ await settle();++ expect(changeReads(fake, 'a'), 2);+ expect(changeReads(fake, 'b'), 0);+ });++ test('at the next poll when its last read failed', () async {+ final fake = two({'a': 100, 'b': 100});+ var failing = true;+ final load = fake.routes['/api/super-tabs/b/parts']!;+ fake.routes['/api/super-tabs/b/parts'] = (body) => failing+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : load(body);+ final i = inbox(fake);+ await i.refresh();+ await settle();+ expect(i.reader('b')!.snapshot, isNull);++ failing = false;+ await i.refresh();+ await settle();++ expect(i.reader('b')!.snapshot, isNotNull);+ });++ test('at the next poll when its asks could not be read', () async {+ final fake = two(+ {'a': 100, 'b': 100},+ derived: {+ 'a': {'decisionsWaiting': 0, 'mentionsWaiting': 1},+ },+ );+ var failing = true;+ fake.routes['/api/super-tabs/a/mentions?state=waiting'] = (_) => failing+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : {+ 'mentions': [+ {+ 'id': 'm1',+ 'conversationId': 'g1',+ 'messageId': 'msg-1',+ 'text': 'Look',+ },+ ],+ };+ final i = inbox(fake);+ await i.refresh();+ await settle();+ expect(i.asks('a')!.error, isNotNull);++ failing = false;+ await i.refresh();+ await settle();++ expect(i.needs.whereType<SwarmMentionNeed>(), hasLength(1));+ });+ });++ group('notifies only when what it shows changed', () {+ /// Swarm `a` with work waiting on the person and one open decision;+ /// [groups] answers each change read.+ FakeSwarm waiting({List<Map<String, dynamic>> Function()? groups}) {+ const derived = {'decisionsWaiting': 1, 'mentionsWaiting': 0};+ final fake = backend(+ {+ 'a': [groupData('g1', title: 'Login', status: 'needs_human')],+ },+ derived: {'a': derived},+ );+ fake.routes['/api/super-tabs/a/changes'] = (_) => changes(+ cursor: 'c2',+ groups: groups?.call() ?? const [],+ derived: derived,+ );+ fake.routes['/api/super-tabs/a/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'conversationId': 'g1',+ 'question': 'Ship it?',+ 'options': ['Yes', 'No'],+ },+ ],+ };+ fake.routes['/api/super-tabs/a/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ return fake;+ }++ // Every 15-second poll rebuilt Home, the drawer and Project, twice or+ // more, with nothing new (audit of 44d284f65, items 4 and 5).+ test('a poll that finds everything as it was notifies nothing', () async {+ final i = inbox(waiting());+ await i.refresh();+ await settle();+ expect(i.needs, hasLength(2));+ final needs = i.needs;+ var notifies = 0;+ i.addListener(() => notifies++);++ await i.refresh();+ await settle();+ await i.refresh();+ await settle();++ expect(notifies, 0);+ expect(i.needs, same(needs));+ });++ test('a poll that changes a Swarm notifies once', () async {+ var title = 'Login';+ final i = inbox(+ waiting(+ groups: () => [+ part('g1', 9, groupData('g1', title: title, status: 'needs_human')),+ ],+ ),+ );+ await i.refresh();+ await settle();+ var notifies = 0;+ i.addListener(() => notifies++);++ title = 'Login on the phone';+ await i.refresh();+ await settle();++ expect(notifies, 1);+ expect(+ i.needs.whereType<SwarmWorkNeed>().single.work.conversation.title,+ 'Login on the phone',+ );+ });++ test('still no computer is told once', () async {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ );+ final i = inbox(fake);+ var notifies = 0;+ i.addListener(() => notifies++);++ await i.refresh();+ await i.refresh();+ await i.refresh();++ expect(i.noComputer, isTrue);+ expect(notifies, 1);+ });++ test('a computer back after none is told', () async {+ final fake = backend({'a': []});+ final listed = fake.routes['/api/super-tabs/list']!;+ var away = true;+ fake.routes['/api/super-tabs/list'] = (q) => away+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : listed(q);+ final i = inbox(fake);+ await i.refresh();+ var notifies = 0;+ i.addListener(() => notifies++);++ away = false;+ await i.refresh();+ await settle();++ expect(i.noComputer, isFalse);+ expect(i.loaded, isTrue);+ expect(notifies, greaterThan(0));+ });++ test("a Swarm's asks ending their loading are told", () async {+ final fake = waiting();+ final open = Completer<Object?>();+ fake.routes['/api/super-tabs/a/decisions?state=open'] = (_) =>+ open.future;+ final i = inbox(fake);+ await i.refresh();+ await settle();+ expect(i.asks('a')!.loading, isTrue);+ var notifies = 0;+ i.addListener(() => notifies++);++ open.complete({'decisions': <Object>[]});+ await settle();++ expect(i.asks('a')!.loading, isFalse);+ expect(notifies, 1);+ });++ // A Done or an answer waited for the poll's slowest Swarm read before+ // Home showed it: on the owner's iPhone a read takes seconds.+ test('a slow poll holds back no Done and no answer', () async {+ const derived = {'decisionsWaiting': 1, 'mentionsWaiting': 1};+ final fake = backend({'a': []}, derived: {'a': derived});+ var answered = false, done = false;+ fake.routes['/api/super-tabs/a/decisions?state=open'] = (_) => {+ 'decisions': [+ if (!answered)+ {+ 'id': 'd1',+ 'conversationId': 'g1',+ 'question': 'Ship it?',+ 'options': ['Yes', 'No'],+ },+ ],+ };+ fake.routes['/api/super-tabs/a/mentions?state=waiting'] = (_) => {+ 'mentions': [+ if (!done)+ {+ 'id': 'm1',+ 'conversationId': 'g1',+ 'messageId': 'msg-1',+ 'text': 'Can you check the copy?',+ },+ ],+ };+ final sent = Completer<void>();+ fake.routes['/api/super-tabs/a/commands'] = (body) async {+ final command = body!['command'] as Map;+ if (command['type'] == 'decision.answer') {+ await sent.future;+ answered = true;+ } else {+ done = true;+ }+ return {'result': <String, dynamic>{}};+ };+ final i = inbox(fake);+ await i.refresh();+ await settle();+ final asks = i.asks('a')!;+ expect(i.needs.whereType<SwarmMentionNeed>(), hasLength(1));+ final decision = i.needs.whereType<SwarmDecisionNeed>().single.decision;+ final read = Completer<void>();+ final changed = fake.routes['/api/super-tabs/a/changes']!;+ fake.routes['/api/super-tabs/a/changes'] = (q) async {+ await read.future;+ return changed(q);+ };+ unawaited(i.refresh());+ await settle();+ var notifies = 0;+ i.addListener(() => notifies++);++ unawaited(asks.done(asks.mentions.single));+ await settle();++ expect(i.needs.whereType<SwarmMentionNeed>(), isEmpty);++ notifies = 0;+ unawaited(asks.answer(decision, 0));+ await settle();++ expect(notifies, greaterThan(0), reason: 'its buttons wait at once');+ expect(asks.answering, contains('d1'));++ sent.complete();+ await settle();++ expect(i.needs.whereType<SwarmDecisionNeed>(), isEmpty);+ read.complete();+ await settle();+ });++ testWidgets('a screen over it builds once per change, not once per poll', (+ tester,+ ) async {+ final i = inbox(waiting());+ var builds = 0;+ await tester.pumpWidget(+ ListenableBuilder(+ listenable: i,+ builder: (_, _) {+ builds++;+ return Text('${i.needs.length}', textDirection: TextDirection.ltr);+ },+ ),+ );+ Future<void> poll() async {+ unawaited(i.refresh());+ for (var n = 0; n < 20; n++) {+ await tester.pump();+ }+ }++ await poll();+ final afterFirst = builds;+ expect(find.text('2'), findsOneWidget);++ await poll();+ await poll();+ await poll();++ expect(builds, afterFirst);+ });+ });++ test('without a computer to ask, it says so', () async {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ );+ final i = inbox(fake);++ await i.refresh();++ expect(i.error, 'Connect one of your computers to open Swarm.');+ expect(i.loaded, isFalse);+ });++ // Production before Swarm v1 (2026-10-27, on the owner's iPhone): no list+ // route, so the old one-Swarm route read "list" as a Swarm's id and said+ // "This Super Tab is unavailable."+ test(+ 'a server without the list says it has no Swarm on the phone yet',+ () async {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => throw const SuperTabFailure(+ 'NOT_FOUND',+ 'This Super Tab is unavailable.',+ statusCode: 404,+ );+ final i = inbox(fake);++ await i.refresh();++ expect(i.error, swarmServerTooOld);+ expect(i.loaded, isFalse);+ },+ );++ test('any other refusal of the list keeps its own words', () async {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => throw const SuperTabFailure(+ 'SWARM_MIGRATING',+ 'This Swarm is being moved. Try again in a moment.',+ statusCode: 503,+ );+ final i = inbox(fake);++ await i.refresh();++ expect(i.error, 'This Swarm is being moved. Try again in a moment.');+ });++ test('without a computer it asks again within seconds, on a backoff, '+ 'not at the next poll', () {+ fakeAsync((async) {+ final fake = backend({'a': []});+ final listed = fake.routes['/api/super-tabs/list']!;+ var away = true;+ fake.routes['/api/super-tabs/list'] = (q) => away+ ? throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ )+ : listed(q);+ final i = SwarmInbox(+ accountId: me,+ request: fake.request,+ pollInterval: const Duration(seconds: 15),+ );+ int lists() => fake.paths.where((p) => p.endsWith('/list')).length;++ i.shown = true;+ async.flushMicrotasks();+ expect(i.error, 'Connect one of your computers to open Swarm.');++ // Asked again after 2, 4 and 8 seconds.+ async.elapse(const Duration(milliseconds: 14500));+ expect(lists(), 4);++ away = false;+ async.elapse(const Duration(seconds: 16));+ expect(i.loaded, isTrue);+ expect(i.error, isNull);++ // Read, it is back on the poll.+ final read = lists();+ async.elapse(const Duration(seconds: 13));+ expect(lists(), read);++ // Back in front after a while away: asked at once.+ i.shown = false;+ async.elapse(const Duration(minutes: 5));+ i.shown = true;+ async.flushMicrotasks();+ expect(lists(), read + 1);+ i.dispose();+ });+ });++ test(+ 'a computer up while it has none reads at once, not at the next try',+ () {+ fakeAsync((async) {+ final fake = backend({'a': []});+ final listed = fake.routes['/api/super-tabs/list']!;+ var away = true;+ fake.routes['/api/super-tabs/list'] = (q) => away+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : listed(q);+ final i = SwarmInbox(accountId: me, request: fake.request);+ int lists() => fake.paths.where((p) => p.endsWith('/list')).length;+ i.shown = true;+ async.flushMicrotasks();+ expect(i.noComputer, isTrue);++ away = false;+ async.elapse(const Duration(milliseconds: 500));+ i.computerUp();+ async.flushMicrotasks();++ expect(lists(), 2);+ expect(i.loaded, isTrue);+ expect(i.noComputer, isFalse);++ // Back on the poll: no quick try left behind.+ async.elapse(const Duration(seconds: 14));+ expect(lists(), 2);+ i.dispose();+ });+ },+ );++ test('a computer up reads nothing while it has one, or is hidden', () {+ fakeAsync((async) {+ final fake = backend({'a': []});+ final i = SwarmInbox(accountId: me, request: fake.request);+ int lists() => fake.paths.where((p) => p.endsWith('/list')).length;++ i.computerUp();+ async.flushMicrotasks();+ expect(lists(), 0, reason: 'hidden');++ i.shown = true;+ async.flushMicrotasks();+ i.computerUp();+ async.flushMicrotasks();+ expect(lists(), 1, reason: 'it had one: the poll reads');+ i.dispose();+ });+ });++ test('while shown it reads every poll; hidden, it reads nothing', () {+ fakeAsync((async) {+ final fake = backend({'a': []});+ final i = SwarmInbox(+ accountId: me,+ request: fake.request,+ pollInterval: const Duration(seconds: 15),+ );+ int lists() => fake.paths.where((p) => p.endsWith('/list')).length;++ i.shown = true;+ async.flushMicrotasks();+ expect(lists(), 1);++ async.elapse(const Duration(seconds: 31));+ expect(lists(), 3);++ i.shown = false;+ async.elapse(const Duration(minutes: 2));+ expect(lists(), 3);+ i.dispose();+ });+ });++ test("each Swarm's reader has its read marks, kept on the phone; a move of "+ 'them is told, and a Swarm off the list takes them', () async {+ final fake = backend({+ 'a': [groupData('g1', lastMessageSequence: 3)],+ });+ final store = MemoryKeyValueStore();+ final i = SwarmInbox(+ accountId: me,+ request: fake.request,+ readMarks: store,+ );+ addTearDown(i.dispose);+ await i.refresh();+ await settle();+ final marks = i.reader('a')!.readMarks!;+ // The first read's marks are written a moment after it.+ await until(() => store.values['swarm_read_marks.$me.a'] != null);+ var told = 0;+ i.addListener(() => told++);++ marks.markRead('g1', 5);+ await settle();+ expect(told, greaterThan(0));++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': <Object>[],+ 'next': null,+ };+ await i.refresh();+ await settle();++ expect(i.reader('a'), isNull);+ expect(store.values['swarm_read_marks.$me.a'], isNull);+ });++ test('an inbox closing keeps its read marks: the next one, for the same '+ 'account, reads what came since as unread', () async {+ const key = 'swarm_read_marks.$me.a';+ final store = MemoryKeyValueStore();+ final first = SwarmInbox(+ accountId: me,+ request: backend({+ 'a': [groupData('g1', lastMessageSequence: 3)],+ }).request,+ readMarks: store,+ );+ await first.refresh();+ await settle();+ await until(() => store.values[key] != null);++ first.dispose();+ await settle();++ expect(store.values[key], isNotNull, reason: 'kept, not forgotten');+ expect(jsonDecode(store.values[key]!), {+ 'marks': {'g1': 3},+ });+ final next = SwarmInbox(+ accountId: me,+ request: backend({+ 'a': [groupData('g1', lastMessageSequence: 6)],+ }).request,+ readMarks: store,+ );+ addTearDown(next.dispose);+ await next.refresh();+ await settle();+ final reader = next.reader('a')!;+ await until(+ () => reader.readMarks!.unread(reader.snapshot!.conversation('g1')!),+ );++ expect(+ reader.readMarks!.unread(reader.snapshot!.conversation(leadChat)!),+ isFalse,+ );+ });+}diff --git a/mobile/test/swarm/swarm_leaderboard_page_test.dart b/mobile/test/swarm/swarm_leaderboard_page_test.dartnew file mode 100644index 000000000..75efae989--- /dev/null+++ b/mobile/test/swarm/swarm_leaderboard_page_test.dart@@ -0,0 +1,582 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/shared/widgets/touch_target.dart';+import 'package:harness_mobile/swarm/swarm_leaderboard.dart';+import 'package:harness_mobile/swarm/swarm_leaderboard_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../theme/sheet_shape.dart';+import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// The leaderboard page over a scripted backend, built to the design system's+/// Numbers and rankings at phone sizes: skeleton rows while it reads, the+/// team's total as quiet text with the week picker, then each person as a row+/// of rank, avatar, name over their non-zero numbers, change against last+/// week and points; a week picker and a person's week in bottom sheets.+void main() {+ const path = '/api/super-tabs/$tab/leaderboard?projectId=$project';+ // Wednesday 28 October 2026; this week's Monday is the 26th.+ final now = DateTime.utc(2026, 10, 28, 2);+ final monday = DateTime.utc(2026, 10, 26).millisecondsSinceEpoch;+ final lastWeek = monday - swarmWeekMs;++ /// This week's board: diego up from 20, ken down from 25, the viewer level,+ /// and dee, who has left, on 0.+ Map<String, dynamic> board() {+ final data = leaderboardData(week: monday);+ final people = (data['people'] as List).cast<Map<String, dynamic>>();+ people[0]['prevWeekPoints'] = 20;+ people[1]['prevWeekPoints'] = 25;+ people.insert(+ 2,+ scoreData(me, points: 5, rank: 3, medal: 'bronze', unblocked: 2)+ ..['prevWeekPoints'] = 5,+ );+ people.last['rank'] = 4;+ return data;+ }++ /// One Swarm whose members are the viewer, diego and ken; dee scores on+ /// the board but has left.+ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(),+ 'members': [+ part(me, 1, person(me)),+ part('diego', 1, {+ ...person('diego', role: 'collaborator'),+ 'avatar': {'kind': 'preset', 'key': 'owl'},+ }),+ part('ken', 1, person('ken', role: 'collaborator')),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes[path] = (_) => board();+ fake.routes['$path&week=$lastWeek'] = (_) => leaderboardData(+ week: lastWeek,+ shipped: 11,+ people: [scoreData('ken', points: 9, rank: 1, medal: 'gold', shipped: 2)],+ );+ return fake;+ }++ /// The page under a signed-in shell's Swarm whose list has been read.+ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ bool still = false,+ ValueNotifier<String?>? signedIn,+ }) async {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = signedIn ?? ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await host.session!.inbox.refresh();+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context).copyWith(disableAnimations: still),+ child: SwarmScope(notifier: host, child: child!),+ ),+ home: SwarmLeaderboardPage(+ swarmId: tab,+ projectId: project,+ now: () => now,+ ),+ ),+ );+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));+ Finder inside(String value, Finder matching) =>+ find.descendant(of: key(value), matching: matching);+ double y(WidgetTester tester, String value) =>+ tester.getTopLeft(key(value)).dy;++ testWidgets('skeleton rows while it reads, then each person in place', (+ tester,+ ) async {+ final fake = backend();+ final gate = Completer<void>();+ fake.routes[path] = (_) async {+ await gate.future;+ return board();+ };+ await pump(tester, fake);+ await tester.pump();++ expect(key('swarm-leaderboard-loading'), findsOneWidget);+ expect(find.textContaining('pts'), findsNothing);++ gate.complete();+ await tester.pumpAndSettle();++ expect(key('swarm-leaderboard-loading'), findsNothing);+ expect(find.text('Leaderboard'), findsOneWidget);+ // The team's total leads, as quiet text, with the week picker beside it.+ const team = 'swarm-leaderboard-team';+ final total = inside(+ team,+ find.text('19 shipped this week · 11 last week'),+ );+ expect(total, findsOneWidget);+ expect(tester.widget<Text>(total).style!.fontSize, AppType.captionSize);+ expect(tester.widget<Text>(total).style!.color, AppPalette.textSecondary);+ expect(+ inside(team, inside('swarm-leaderboard-week', find.text('This week'))),+ findsOneWidget,+ );+ expect(+ y(tester, team),+ lessThan(y(tester, 'swarm-leaderboard-person-diego')),+ );++ const diego = 'swarm-leaderboard-person-diego';+ expect(inside(diego, find.text('diego')), findsOneWidget);+ // The face diego chose, not the initial.+ expect(inside(diego, find.text('🦉')), findsOneWidget);+ expect(inside(diego, find.text('D')), findsNothing);+ expect(+ tester.getSemantics(key(diego)),+ isSemantics(+ label:+ 'diego, place 1, 28 points, 8 shipped, 1 unblocked, '+ '40 hours lent, up 8 from last week',+ isButton: true,+ ),+ );+ // The label says what the row shows: a number at zero is left out.+ expect(+ tester.getSemantics(key('swarm-leaderboard-person-ken')),+ isSemantics(+ label: 'ken, place 2, 21 points, 3 shipped, down 4 from last week',+ isButton: true,+ ),+ );+ expect(+ tester.getSemantics(key('swarm-leaderboard-person-dee')),+ isSemantics(label: 'Former member, place 4, 0 points', isButton: true),+ );+ expect(+ tester.getSize(key(diego)).height,+ greaterThanOrEqualTo(minTouchTarget),+ reason: 'a thumb',+ );+ expect(+ y(tester, diego),+ lessThan(y(tester, 'swarm-leaderboard-person-ken')),+ );+ const dee = 'swarm-leaderboard-person-dee';+ expect(inside(dee, find.text('Former member')), findsOneWidget);+ expect(y(tester, 'swarm-leaderboard-person-ken'), lessThan(y(tester, dee)));+ expect(fake.paths.where((p) => p.contains('/leaderboard')), [path]);+ });++ testWidgets('a display name from the board wins over the email name', (+ tester,+ ) async {+ final fake = backend();+ fake.routes[path] = (_) {+ final data = board();+ (data['people'] as List<Map<String, dynamic>>)[1]['displayName'] =+ 'Ken Nguyen';+ return data;+ };+ await pump(tester, fake);+ await tester.pumpAndSettle();+ const ken = 'swarm-leaderboard-person-ken';+ expect(inside(ken, find.text('Ken Nguyen')), findsOneWidget);+ expect(find.text('ken'), findsNothing);+ expect(+ tester.getSemantics(key(ken)).label,+ startsWith('Ken Nguyen, place 2'),+ );+ // Its sheet is titled the same.+ await tester.tap(key(ken));+ await tester.pumpAndSettle();+ expect(+ inside('swarm-leaderboard-sheet', find.text('Ken Nguyen')),+ findsOneWidget,+ );+ });++ testWidgets('a bold rank in its own column and the points as the one '+ 'emphasized number, each right-aligned', (tester) async {+ await pump(tester, backend());+ await tester.pumpAndSettle();+ final ids = ['diego', 'ken', me, 'dee'];+ for (final (i, id) in ids.indexed) {+ expect(+ inside('swarm-leaderboard-rank-$id', find.text('${i + 1}')),+ findsOneWidget,+ reason: id,+ );+ }+ double right(String value) => tester.getTopRight(key(value)).dx;+ for (final id in ids) {+ expect(+ right('swarm-leaderboard-rank-$id'),+ right('swarm-leaderboard-rank-diego'),+ );+ expect(+ right('swarm-leaderboard-points-$id'),+ right('swarm-leaderboard-points-diego'),+ );+ }+ TextStyle style(String value, String text) =>+ tester.widget<Text>(inside(value, find.text(text))).style!;+ final rank = style('swarm-leaderboard-rank-diego', '1');+ expect(rank.fontWeight, FontWeight.w700);+ expect(rank.color, AppPalette.textSecondary);+ expect(rank.fontFeatures, const [FontFeature.tabularFigures()]);+ final points = style('swarm-leaderboard-points-diego', '28');+ expect(points.fontWeight, FontWeight.w600);+ expect(points.color, AppPalette.textPrimary);+ expect(points.fontFeatures, const [FontFeature.tabularFigures()]);+ expect(find.textContaining('pts'), findsNothing);+ // No points yet: the 0 holds the column in the points style, one rule+ // for every value.+ expect(style('swarm-leaderboard-points-dee', '0'), points);+ });++ testWidgets('the numbers in words under the name: zeros left out, whole '+ 'items only', (tester) async {+ await pump(tester, backend());+ await tester.pumpAndSettle();+ String? shown(String id) {+ final line = key('swarm-leaderboard-meta-$id');+ if (line.evaluate().isEmpty) return null;+ return tester+ .widget<Text>(find.descendant(of: line, matching: find.byType(Text)))+ .data;+ }++ const diego = '8 shipped · 1 unblocked · 40 hours lent';+ final text = shown('diego')!;+ expect(diego.startsWith(text), isTrue, reason: text);+ expect(+ text == diego || diego.substring(text.length).startsWith(' · '),+ isTrue,+ reason: text,+ );+ expect(shown('ken'), '3 shipped');+ expect(shown(me), '2 unblocked');+ expect(shown('dee'), isNull, reason: 'nothing to say, no line');+ final style = tester+ .widget<Text>(+ find.descendant(+ of: key('swarm-leaderboard-meta-ken'),+ matching: find.byType(Text),+ ),+ )+ .style!;+ expect(style.fontSize, AppType.captionSize);+ expect(style.color, AppPalette.textSecondary);+ });++ testWidgets('an arrow against last week, by shape and colour, and none '+ 'when level', (tester) async {+ await pump(tester, backend());+ await tester.pumpAndSettle();+ Icon arrow(String id) => tester.widget<Icon>(+ inside('swarm-leaderboard-trend-$id', find.byType(Icon)),+ );+ expect(+ inside('swarm-leaderboard-trend-diego', find.text('8')),+ findsOneWidget,+ );+ expect(arrow('diego').color, AppPalette.online);+ expect(+ inside('swarm-leaderboard-trend-ken', find.text('4')),+ findsOneWidget,+ );+ expect(arrow('ken').icon, isNot(arrow('diego').icon));+ final context = tester.element(key('swarm-leaderboard-trend-ken'));+ expect(arrow('ken').color, Theme.of(context).colorScheme.error);+ expect(key('swarm-leaderboard-trend-$me'), findsNothing);+ expect(key('swarm-leaderboard-trend-dee'), findsNothing);+ });++ testWidgets("the viewer's own row has the selected fill, no other", (+ tester,+ ) async {+ await pump(tester, backend());+ await tester.pumpAndSettle();+ Color? fill(String id) => tester+ .widget<Material>(+ find+ .ancestor(+ of: key('swarm-leaderboard-person-$id'),+ matching: find.byType(Material),+ )+ .first,+ )+ .color;+ expect(fill(me), AppSurface.selectedFill);+ expect(fill('diego'), Colors.transparent);+ });++ testWidgets("a hardware keyboard's focus shows over the viewer's own fill", (+ tester,+ ) async {+ await pump(tester, backend());+ await tester.pumpAndSettle();+ final row = key('swarm-leaderboard-person-$me');+ final ink = Material.of(tester.element(row)) as RenderObject;+ final focus = Theme.of(tester.element(row)).focusColor;+ expect(ink, isNot(paints..rrect(color: focus)));+ FocusManager.instance.highlightStrategy =+ FocusHighlightStrategy.alwaysTraditional;+ addTearDown(+ () => FocusManager.instance.highlightStrategy =+ FocusHighlightStrategy.automatic,+ );+ Focus.of(+ tester.element(+ find.descendant(of: row, matching: find.byType(Padding)).first,+ ),+ ).requestFocus();+ await tester.pumpAndSettle();+ expect(ink, paints..rrect(color: focus));+ });++ testWidgets('no cups, medals, sparkles or emoji of its own', (tester) async {+ await pump(tester, backend());+ await tester.pump();+ await tester.pump();+ for (final mark in ['🥇', '🥈', '🥉', '🚀', '✨']) {+ expect(find.textContaining(mark), findsNothing, reason: mark);+ }+ expect(key('swarm-leaderboard-sparkle'), findsNothing);+ await tester.pumpAndSettle();+ });++ testWidgets('the week picker shows another week', (tester) async {+ final fake = backend();+ await pump(tester, fake);+ await tester.pumpAndSettle();+ expect(+ tester.getSize(key('swarm-leaderboard-week')).height,+ greaterThanOrEqualTo(44),+ );++ await tester.tap(key('swarm-leaderboard-week'));+ await tester.pumpAndSettle();+ expect(sheetTopRadius(tester), 12);+ for (final name in ['Last week', '2 weeks ago', '3 weeks ago']) {+ expect(find.text(name), findsOneWidget);+ }++ await tester.tap(find.text('Last week'));+ await tester.pumpAndSettle();++ expect(fake.paths.last, '$path&week=$lastWeek');+ expect(+ inside('swarm-leaderboard-week', find.text('Last week')),+ findsOneWidget,+ );+ const team = 'swarm-leaderboard-team';+ expect(+ inside(team, find.text('11 shipped last week · 11 the week before')),+ findsOneWidget,+ );+ expect(key('swarm-leaderboard-person-diego'), findsNothing);+ expect(+ inside('swarm-leaderboard-points-ken', find.text('9')),+ findsOneWidget,+ );++ await tester.tap(key('swarm-leaderboard-week'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('This week').last);+ await tester.pumpAndSettle();+ expect(fake.paths.last, path);+ });++ testWidgets("tapping a person opens their week", (tester) async {+ await pump(tester, backend());+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-leaderboard-person-diego'));+ await tester.pumpAndSettle();++ const sheet = 'swarm-leaderboard-sheet';+ expect(sheetTopRadius(tester), 12);+ expect(inside(sheet, find.text('diego')), findsOneWidget);+ for (final line in [+ '28 this week · place 1',+ '8 asks landed · median 3 h to ship',+ '1 answered · median 4 min · 6 min of agent time freed',+ '2 machines · 40 agent-hours',+ '3 days shipping',+ ]) {+ expect(inside(sheet, find.text(line)), findsOneWidget, reason: line);+ }++ await tester.tap(key('swarm-leaderboard-sheet-close'));+ await tester.pumpAndSettle();+ expect(key(sheet), findsNothing);++ await tester.tap(key('swarm-leaderboard-person-dee'));+ await tester.pumpAndSettle();+ for (final line in [+ '0 this week',+ 'Nothing landed yet',+ 'Nothing answered yet',+ 'Nothing lent yet',+ 'No streak yet',+ ]) {+ expect(inside(sheet, find.text(line)), findsOneWidget, reason: line);+ }+ });++ testWidgets('a read that fails with nothing shown offers Try again', (+ tester,+ ) async {+ final fake = backend();+ var fail = true;+ fake.routes[path] = (_) => fail+ ? throw const SuperTabFailure('OFFLINE', 'No computer answered.')+ : leaderboardData(week: monday);+ await pump(tester, fake);+ await tester.pumpAndSettle();++ expect(find.text('No computer answered.'), findsOneWidget);+ expect(key('swarm-leaderboard-person-diego'), findsNothing);++ fail = false;+ await tester.tap(find.text('Try again'));+ await tester.pumpAndSettle();+ expect(key('swarm-leaderboard-person-diego'), findsOneWidget);+ expect(find.text('No computer answered.'), findsNothing);+ });++ testWidgets('a server without a leaderboard says it has none', (+ tester,+ ) async {+ final fake = backend()..routes.remove(path);+ await pump(tester, fake);+ await tester.pumpAndSettle();++ expect(+ find.text("This Swarm's server has no leaderboard yet."),+ findsOneWidget,+ );+ expect(key('swarm-leaderboard-loading'), findsNothing);+ });++ testWidgets('a pull reads the board again', (tester) async {+ final fake = backend();+ await pump(tester, fake);+ await tester.pumpAndSettle();++ await tester.fling(+ key('swarm-leaderboard-person-diego'),+ const Offset(0, 400),+ 1000,+ );+ await tester.pumpAndSettle();++ expect(fake.paths.where((p) => p == path), hasLength(2));+ });++ group("another account's board never stays", () {+ /// The backend as each account reads it: the old account's board has+ /// diego first; the next account's has only ken.+ FakeSwarm twoAccounts(ValueNotifier<String?> account) {+ final fake = backend();+ fake.routes[path] = (_) => account.value == me+ ? leaderboardData(week: monday)+ : leaderboardData(+ week: monday,+ shipped: 2,+ people: [scoreData('ken', points: 9, rank: 1, medal: 'gold')],+ );+ return fake;+ }++ testWidgets('an account switch shows only the new account\'s board', (+ tester,+ ) async {+ final account = ValueNotifier<String?>(me);+ final fake = twoAccounts(account);+ await pump(tester, fake, signedIn: account);+ await tester.pumpAndSettle();+ expect(key('swarm-leaderboard-person-diego'), findsOneWidget);+ final before = fake.paths.where((p) => p.startsWith(path)).length;++ account.value = 'person-other';+ await tester.pump();++ expect(+ key('swarm-leaderboard-person-diego'),+ findsNothing,+ reason: 'the old account\'s board is gone at once',+ );+ expect(find.textContaining('shipped this week'), findsNothing);++ await tester.pumpAndSettle();+ expect(key('swarm-leaderboard-person-diego'), findsNothing);+ expect(+ inside('swarm-leaderboard-points-ken', find.text('9')),+ findsOneWidget,+ );+ expect(+ inside(+ 'swarm-leaderboard-team',+ find.text('2 shipped this week · 11 last week'),+ ),+ findsOneWidget,+ );+ expect(+ fake.paths.where((p) => p.startsWith(path)).length,+ before + 1,+ reason: 'read once for the new account',+ );+ });++ testWidgets('a sign-out clears the board and reads no more', (+ tester,+ ) async {+ final account = ValueNotifier<String?>(me);+ final fake = twoAccounts(account);+ await pump(tester, fake, signedIn: account);+ await tester.pumpAndSettle();+ expect(key('swarm-leaderboard-person-diego'), findsOneWidget);+ final reads = fake.paths.length;++ account.value = null;+ await tester.pumpAndSettle();++ expect(key('swarm-leaderboard-person-diego'), findsNothing);+ expect(key('swarm-leaderboard-team'), findsNothing);+ expect(key('swarm-leaderboard-loading'), findsNothing);++ await tester.pump(const Duration(minutes: 11));+ expect(fake.paths.length, reads, reason: 'nothing read once signed out');+ });+ });+}diff --git a/mobile/test/swarm/swarm_leaderboard_shots_test.dart b/mobile/test/swarm/swarm_leaderboard_shots_test.dartnew file mode 100644index 000000000..2350c5b8c--- /dev/null+++ b/mobile/test/swarm/swarm_leaderboard_shots_test.dart@@ -0,0 +1,151 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_leaderboard.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Set to a folder to write the phone leaderboard's screenshots there, light+/// and dark, over a scripted backend: never a real Swarm.+final shots = Platform.environment['SWARM_LEADERBOARD_SHOTS'];++void main() {+ const path = '/api/super-tabs/$tab/leaderboard?projectId=$project';+ final now = DateTime.utc(2026, 10, 28, 2);+ final monday = DateTime.utc(2026, 10, 26).millisecondsSinceEpoch;++ 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 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();+ }+ });++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(),+ 'members': [+ part(me, 1, person(me)),+ part('diego', 1, person('diego', role: 'collaborator')),+ part('ken', 1, person('ken', role: 'collaborator')),+ part('tony', 1, person('tony', role: 'collaborator')),+ part('maximilian', 1, person('maximilian', role: 'collaborator')),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes[path] = (_) => leaderboardData(+ week: monday,+ people: [+ {+ ...scoreData(+ 'diego',+ points: 28,+ rank: 1,+ shipped: 8,+ unblocked: 1,+ lentMs: 40 * 3600000,+ ),+ 'displayName': 'Diego',+ 'prevWeekPoints': 20,+ },+ {+ ...scoreData('ken', points: 21, rank: 2, shipped: 3, unblocked: 4),+ 'displayName': 'Ken',+ 'prevWeekPoints': 25,+ },+ {+ ...scoreData(me, points: 6, rank: 3, unblocked: 2),+ 'displayName': 'Dee',+ 'prevWeekPoints': 6,+ },+ scoreData('tony', points: 2, rank: 4, shipped: 1),+ scoreData('maximilian', points: 0, rank: 5),+ ],+ );+ return fake;+ }++ testWidgets('screenshots for review', (tester) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ // A palette carries its brightness: the shell's default dark one, and+ // the neutral light one.+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ await host.session!.inbox.refresh();+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ SwarmScope(notifier: host, child: child!),+ home: SwarmLeaderboardPage(+ swarmId: tab,+ projectId: project,+ now: () => now,+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$shots/phone-leaderboard-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ });+ await tester.pumpWidget(const SizedBox());+ host.dispose();+ }+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_leaderboard_test.dart b/mobile/test/swarm/swarm_leaderboard_test.dartnew file mode 100644index 000000000..e6f0dbfd5--- /dev/null+++ b/mobile/test/swarm/swarm_leaderboard_test.dart@@ -0,0 +1,287 @@+import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/swarm/swarm_leaderboard_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import 'swarm_fixture.dart';++void main() {+ group('the board as read', () {+ test('keeps the order, places, cups and counts the backend sends', () {+ final read = SwarmLeaderboard.fromJson(leaderboardData());++ expect(read.week, 1792454400000);+ expect(read.shipped, 19);+ expect(read.shippedBefore, 11);+ expect(+ [for (final p in read.people) p.personId],+ ['diego', 'ken', 'dee'],+ );+ final diego = read.people.first;+ expect(diego.points, 28);+ expect(diego.rank, 1);+ expect(diego.medal, SwarmMedal.gold);+ expect(diego.shipped, 8);+ expect(diego.medianAskToShipMs, 3 * 3600000);+ expect(diego.unblocked, 1);+ expect(diego.unblockedMs, 6 * 60000);+ expect(diego.medianAnswerMs, 4 * 60000);+ expect(diego.lentMachines, 2);+ expect(diego.lentMs, 40 * 3600000);+ expect(diego.streakDays, 3);+ expect(read.people[1].medal, SwarmMedal.silver);+ expect(read.people[2].medal, isNull);+ expect(read.people[2].rank, 4);+ });++ test('a field missing or of another type reads as nothing', () {+ final read = SwarmLeaderboard.fromJson({+ 'week': 1792454400000,+ 'people': [+ {'personId': 'kim', 'points': 'many', 'medal': 'platinum'},+ ],+ });++ expect(read.shipped, 0);+ expect(read.shippedBefore, 0);+ final kim = read.people.single;+ expect(kim.points, 0);+ expect(kim.medal, isNull);+ expect(kim.shipped, 0);+ expect(kim.lentMs, 0);+ expect(kim.medianAskToShipMs, isNull);+ expect(kim.medianAnswerMs, isNull);+ expect(kim.streakDays, 0);+ });+ });++ group('how the board writes', () {+ test('the numbers in words, each that would read zero left out', () {+ SwarmScore score(Map<String, dynamic> json) => SwarmScore.fromJson(json);+ expect(+ swarmNumbers(+ score(+ scoreData(+ 'a',+ points: 9,+ rank: 1,+ shipped: 8,+ unblocked: 1,+ lentMs: 40 * 3600000,+ ),+ ),+ ),+ ['8 shipped', '1 unblocked', '40 hours lent'],+ );+ expect(+ swarmNumbers(score(scoreData('b', points: 2, rank: 2, unblocked: 2))),+ ['2 unblocked'],+ );+ expect(+ swarmNumbers(+ score(scoreData('d', points: 1, rank: 4, lentMs: 3600000)),+ ),+ ['1 hour lent'],+ );+ // Under half an hour lent reads 0 hours, so it is left out.+ expect(+ swarmNumbers(score(scoreData('c', points: 0, rank: 3, lentMs: 60000))),+ isEmpty,+ );+ });++ test('the profile name when the board has one', () {+ expect(+ SwarmScore.fromJson({+ ...scoreData('a', points: 1, rank: 1),+ 'displayName': 'Diego M',+ }).displayName,+ 'Diego M',+ );+ expect(+ SwarmScore.fromJson({+ ...scoreData('a', points: 1, rank: 1),+ 'displayName': '',+ }).displayName,+ isNull,+ );+ });++ test('the change against last week, none when level or unknown', () {+ SwarmScore score(int points, int? before) => SwarmScore.fromJson({+ ...scoreData('a', points: points, rank: 1),+ 'prevWeekPoints': ?before,+ });+ expect(swarmTrend(score(28, 20)), 'up 8 from last week');+ expect(swarmTrend(score(21, 25)), 'down 4 from last week');+ expect(swarmTrend(score(5, 5)), isNull);+ expect(swarmTrend(score(5, null)), isNull);+ });++ test('a duration in minutes under an hour, then in hours', () {+ expect(swarmDuration(6 * 60000), '6 min');+ expect(swarmDuration(3 * 3600000), '3 h');+ expect(swarmDuration(3 * 3600000 + 6 * 60000), '3.1 h');+ });++ test('lent time in whole agent-hours', () {+ expect(swarmHours(0), 0);+ expect(swarmHours(40 * 3600000), 40);+ expect(swarmHours(123 * 3600000 + 29 * 60000), 123);+ expect(swarmHours(30 * 60000), 1);+ });++ test("a week is named from this week's Monday", () {+ // Wednesday 28 October 2026, 02:00 in Hanoi: still Tuesday in UTC.+ final now = DateTime.utc(2026, 10, 27, 19);+ final monday = DateTime.utc(2026, 10, 26).millisecondsSinceEpoch;+ expect(swarmWeekOf(now), monday);+ expect(swarmWeekOf(DateTime.utc(2026, 10, 26)), monday);+ expect(swarmWeekOf(DateTime.utc(2026, 11, 1, 23, 59)), monday);++ expect(swarmWeekName(null, monday), 'This week');+ expect(swarmWeekName(monday, monday), 'This week');+ expect(swarmWeekName(monday - swarmWeekMs, monday), 'Last week');+ expect(swarmWeekName(monday - 3 * swarmWeekMs, monday), '3 weeks ago');+ });+ });++ group('the reader', () {+ const path = '/api/super-tabs/$tab/leaderboard?projectId=$project';+ const lastWeek = 1792454400000 - swarmWeekMs;++ SwarmLeaderboardReader reader(FakeSwarm fake, {bool inFront = true}) {+ final read = SwarmLeaderboardReader(+ tabId: tab,+ projectId: project,+ request: fake.request,+ inFront: () => inFront,+ );+ addTearDown(read.dispose);+ return read;+ }++ test("reads this week's board of the project", () async {+ final fake = FakeSwarm()..routes[path] = (_) => leaderboardData();+ final read = reader(fake);+ expect(read.loading, isTrue);++ await read.refresh();++ expect(fake.paths, [path]);+ expect(read.loading, isFalse);+ expect(read.board!.people.first.personId, 'diego');+ expect(read.week, isNull);+ });++ test('another week clears the board until its own read lands', () async {+ final fake = FakeSwarm()+ ..routes[path] = ((_) => leaderboardData())+ ..routes['$path&week=$lastWeek'] = (_) =>+ leaderboardData(week: lastWeek, shipped: 11);+ final read = reader(fake);+ await read.refresh();+ final told = <SwarmLeaderboard?>[];+ read.addListener(() => told.add(read.board));++ final shown = read.showWeek(lastWeek);+ expect(read.board, isNull, reason: "this week's numbers under its name");+ expect(read.week, lastWeek);+ await shown;++ expect(fake.paths.last, '$path&week=$lastWeek');+ expect(read.board!.shipped, 11);+ expect(told.first, isNull);+ });++ test('an answer for the week left behind is not shown', () async {+ final slow = Completer<Object?>();+ final fake = FakeSwarm()+ ..routes[path] = ((_) => slow.future)+ ..routes['$path&week=$lastWeek'] = (_) =>+ leaderboardData(week: lastWeek, shipped: 11);+ final read = reader(fake);+ final first = read.refresh();++ await read.showWeek(lastWeek);+ slow.complete(leaderboardData(shipped: 19));+ await first;++ expect(read.board!.shipped, 11);+ });++ test('a failed refresh keeps the board and says why', () async {+ var fail = false;+ final fake = FakeSwarm()+ ..routes[path] = (_) => fail+ ? throw const SuperTabFailure('OFFLINE', 'No computer answered.')+ : leaderboardData();+ final read = reader(fake);+ await read.refresh();++ fail = true;+ await read.refresh();+ expect(read.board!.shipped, 19);+ expect(read.error, 'No computer answered.');++ fail = false;+ await read.refresh();+ expect(read.error, isNull);+ });++ test('an answer it cannot read says so', () async {+ final fake = FakeSwarm()..routes[path] = (_) => 'not a board';+ final read = reader(fake);++ await read.refresh();++ expect(read.board, isNull);+ expect(read.error, "Couldn't read the leaderboard.");+ expect(read.loading, isFalse);+ });++ test('a server without a leaderboard says it has none', () async {+ // FakeSwarm answers 404 for a path it has no route for.+ final read = reader(FakeSwarm());++ await read.refresh();++ expect(read.unavailable, isTrue);+ expect(read.board, isNull);+ expect(read.error, isNull);+ expect(read.loading, isFalse);+ });++ test('reads again every five minutes, only while the app is in '+ 'front', () {+ fakeAsync((async) {+ var inFront = true;+ final fake = FakeSwarm()..routes[path] = (_) => leaderboardData();+ final read = SwarmLeaderboardReader(+ tabId: tab,+ projectId: project,+ request: fake.request,+ inFront: () => inFront,+ );+ read.start();+ async.flushMicrotasks();+ expect(fake.paths, hasLength(1), reason: 'read at once');++ async.elapse(const Duration(minutes: 5));+ expect(fake.paths, hasLength(2));++ inFront = false;+ async.elapse(const Duration(minutes: 10));+ expect(fake.paths, hasLength(2));++ read.dispose();+ inFront = true;+ async.elapse(const Duration(minutes: 10));+ expect(fake.paths, hasLength(2), reason: 'none after it is gone');+ });+ });+ });+}diff --git a/mobile/test/swarm/swarm_machines_shots_test.dart b/mobile/test/swarm/swarm_machines_shots_test.dartnew file mode 100644index 000000000..5535eb6b7--- /dev/null+++ b/mobile/test/swarm/swarm_machines_shots_test.dart@@ -0,0 +1,148 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_machines.dart';++import 'swarm_machines_test.dart' show machinePool;++import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++final shots = Platform.environment['SWARM_MACHINE_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('machine drawer and sheet in both phone themes', (tester) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'OpenHarness', 'ownerId': me},+ ],+ 'next': null,+ };+ final rows = [+ machinePool('mac-1', 'MacBook-Pro-19'),+ machinePool('mac-2', 'MAC-Mac-Studio', deviceType: 'Mac Studio'),+ machinePool('mac-3', 'MacBookPro2021', receivedAt: 1),+ ];+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ head: headData(+ name: 'OpenHarness',+ projects: [+ {+ 'id': project,+ 'name': 'openharness',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ ),+ 'machines': [+ for (final m in rows) part(m['machineId'] as String, 1, m),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2');+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => me,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ await host.session!.inbox.refresh();+ 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 SwarmPage(),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('swarm-menu')));+ await tester.pumpAndSettle();+ Future<void> capture(String name) => tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$shots/machines-$name-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ await capture('drawer');+ await tester.tap(find.byKey(const ValueKey('swarm-machine-$tab-mac-1')));+ await tester.pumpAndSettle();+ await capture('hardware');+ await tester.drag(+ find.descendant(+ of: find.byType(SwarmMachineSheet),+ matching: find.byType(SingleChildScrollView),+ ),+ const Offset(0, -550),+ );+ await tester.pumpAndSettle();+ await capture('allowances-agents');+ await tester.pumpWidget(const SizedBox());+ host.dispose();+ account.dispose();+ }+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_machines_test.dart b/mobile/test/swarm/swarm_machines_test.dartnew file mode 100644index 000000000..0874b7305--- /dev/null+++ b/mobile/test/swarm/swarm_machines_test.dart@@ -0,0 +1,380 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_machines.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';++Map<String, dynamic> machinePool(+ String id,+ String name, {+ String? host,+ String owner = me,+ int? receivedAt,+ num cpu = 25,+ String deviceType = 'MacBook Pro',+}) => {+ 'machineId': id,+ 'name': name,+ 'contributorId': owner,+ 'hostMachineId': ?host,+ 'engines': ['claude', 'codex'],+ 'observation': {+ 'receivedAt': receivedAt ?? DateTime.now().millisecondsSinceEpoch,+ 'resources': {+ 'cpuPercent': cpu,+ 'gpuPercent': 40,+ 'memoryTotalBytes': 16 * 1073741824,+ 'memoryUsedBytes': 4 * 1073741824,+ 'diskTotalBytes': 512 * 1073741824,+ 'diskFreeBytes': 128 * 1073741824,+ 'chip': 'Apple M2',+ 'deviceType': deviceType,+ 'os': 'macOS',+ },+ 'quotas': [+ {+ 'engine': 'claude',+ 'known': true,+ 'windows': [+ {+ 'name': 'Session',+ 'usedPercent': 20,+ 'resetsAt': DateTime.now()+ .add(const Duration(hours: 2))+ .millisecondsSinceEpoch,+ },+ ],+ },+ ],+ },+};++void main() {+ late SwarmHost host;+ late FakeSwarm fake;+ Future<void> open(+ WidgetTester tester, {+ List<Map<String, dynamic>>? machines,+ List<Map<String, dynamic>>? agents,+ }) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ final rows = machines ?? [machinePool('mac-1', 'Tony’s Mac')];+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(agents: agents),+ 'machines': [for (final m in rows) part(m['machineId'] as String, 1, m)],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ host = SwarmHost(+ accountId: () => me,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await host.session!.inbox.refresh();+ await tester.pumpWidget(+ MaterialApp(+ builder: (_, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmPage(),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('swarm-menu')));+ await tester.pumpAndSettle();+ }++ Finder key(String s) => find.byKey(ValueKey(s));++ testWidgets(+ 'contributed Machines under Projects collapse without hiding projects',+ (tester) async {+ await open(tester);+ expect(key('swarm-machine-$tab-mac-1'), findsOneWidget);+ expect(+ tester.getTopLeft(key('swarm-machines-$tab')).dy,+ greaterThan(+ tester.getTopLeft(key('swarm-drawer-project-$tab-$project')).dy,+ ),+ );+ await tester.tap(key('swarm-machines-$tab'));+ await tester.pumpAndSettle();+ expect(key('swarm-machine-$tab-mac-1'), findsNothing);+ expect(key('swarm-drawer-project-$tab-$project'), findsOneWidget);+ await tester.tap(key('swarm-machines-$tab'));+ await tester.pumpAndSettle();+ expect(find.text('Tony’s Mac'), findsOneWidget);+ },+ );++ testWidgets(+ 'tap shows capacity, allowance reset and running agents, without management',+ (tester) async {+ await open(tester);+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ expect(find.text('CPU'), findsOneWidget);+ expect(find.text('25% in use'), findsOneWidget);+ expect(find.text('40% in use'), findsOneWidget);+ expect(find.text('12 GB free of 16 GB'), findsOneWidget);+ expect(find.text('128 GB free of 512 GB'), findsOneWidget);+ expect(find.textContaining('80% left'), findsWidgets);+ expect(find.textContaining('Resets'), findsWidgets);+ expect(+ find.descendant(+ of: find.byType(SwarmMachineSheet),+ matching: find.text('River'),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: find.byType(SwarmMachineSheet),+ matching: find.text('Nova'),+ ),+ findsOneWidget,+ );+ for (final text in ['Remove', 'Configure', 'Pause']) {+ expect(find.text(text), findsNothing);+ }+ },+ );++ testWidgets("a machine's agents leave Buddies out (Ken, 10-29)", (+ tester,+ ) async {+ await open(+ tester,+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ buddyData('agent-wren', displayName: 'Wren'),+ buddyData('agent-ivy', owner: 'person-dee', displayName: 'Ivy'),+ buddyData('agent-oak', owner: 'person-kai', displayName: 'Oak'),+ ],+ );+ expect(find.text('1 agent'), findsOneWidget);++ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ for (final name in ['Wren', 'Ivy', 'Oak']) {+ expect(+ find.descendant(+ of: find.byType(SwarmMachineSheet),+ matching: find.text(name),+ ),+ findsNothing,+ );+ }+ expect(+ find.descendant(+ of: find.byType(SwarmMachineSheet),+ matching: find.text('River'),+ ),+ findsOneWidget,+ );+ });++ testWidgets('Team account folds into Mac; its readings shown to teammates', (+ tester,+ ) async {+ await open(+ tester,+ machines: [+ machinePool('mac-1', 'Shared Mac', owner: 'other', cpu: 99),+ machinePool(+ 'team-1',+ 'Team account',+ owner: 'other',+ host: 'mac-1',+ cpu: 12,+ ),+ ],+ agents: [agent('dev', displayName: 'Robin', machineId: 'team-1')],+ );+ expect(key('swarm-machine-$tab-team-1'), findsNothing);+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ expect(find.text('12% in use'), findsOneWidget);+ expect(find.text('99% in use'), findsNothing);+ expect(find.text('Robin'), findsOneWidget);+ });++ testWidgets(+ 'offline machine keeps identity and hides stale capacity and quotas',+ (tester) async {+ await open(+ tester,+ machines: [+ machinePool(+ 'mac-1',+ 'Away Mac',+ receivedAt: DateTime.now()+ .subtract(const Duration(minutes: 2))+ .millisecondsSinceEpoch,+ ),+ ],+ );+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ expect(find.text('Offline'), findsWidgets);+ expect(find.text('25% in use'), findsNothing);+ expect(find.textContaining('80% left'), findsNothing);+ expect(find.textContaining('unavailable'), findsWidgets);+ },+ );+ testWidgets(+ 'an open sheet clears private readings when Swarm is turned off',+ (tester) async {+ await open(tester);+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ host.features.value = const {};+ await tester.pumpAndSettle();+ expect(find.text('25% in use'), findsNothing);+ expect(find.text('Access ended'), findsOneWidget);+ },+ );++ testWidgets(+ 'a failed read hides current numbers instead of reporting offline',+ (tester) async {+ await open(tester);+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ throw const SuperTabFailure('UNAVAILABLE', 'Unavailable');+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();+ expect(find.text("Can't reach Harness"), findsWidgets);+ expect(find.text('25% in use'), findsNothing);+ expect(find.text('Offline'), findsNothing);+ },+ );++ testWidgets('the owner reads their Mac rather than its Team account', (+ tester,+ ) async {+ await open(+ tester,+ machines: [+ machinePool('mac-1', 'My Mac', cpu: 31),+ machinePool('team-1', 'Team', host: 'mac-1', cpu: 98),+ ],+ );+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ expect(find.text('31% in use'), findsOneWidget);+ expect(find.text('98% in use'), findsNothing);+ });++ testWidgets(+ 'expired allowances are unavailable and down agents are omitted',+ (tester) async {+ final pool = machinePool('mac-1', 'Mac');+ final observation = pool['observation'] as Map<String, dynamic>;+ observation['quotas'] = [+ {+ 'engine': 'claude',+ 'known': true,+ 'windows': [+ {+ 'name': 'Session',+ 'usedPercent': 20,+ 'resetsAt': DateTime.now()+ .subtract(const Duration(minutes: 1))+ .millisecondsSinceEpoch,+ },+ ],+ },+ ];+ await open(+ tester,+ machines: [pool],+ agents: [+ {+ ...agent('gone', displayName: 'Gone'),+ 'downSince': '2026-01-01T00:00:00Z',+ },+ ],+ );+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ expect(find.textContaining('80% left'), findsNothing);+ expect(find.text('Allowance unavailable'), findsWidgets);+ expect(find.text('Gone'), findsNothing);+ expect(find.text('No agents running'), findsOneWidget);+ },+ );+ testWidgets('an agent-only machine with no observation still opens safely', (+ tester,+ ) async {+ await open(tester, machines: []);+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ expect(find.text('Current readings unavailable'), findsOneWidget);+ expect(tester.takeException(), isNull);+ });+ testWidgets(+ 'hardware labels and values share a row, label left and value right',+ (tester) async {+ await open(tester);+ await tester.tap(key('swarm-machine-$tab-mac-1'));+ await tester.pumpAndSettle();+ final label = find.text('CPU');+ final value = find.text('25% in use');+ expect(+ tester.getTopLeft(label).dy,+ closeTo(tester.getTopLeft(value).dy, 1),+ );+ expect(+ tester.getTopRight(label).dx,+ lessThan(tester.getTopLeft(value).dx),+ );+ },+ );++ testWidgets('Mac Studio has a desktop icon and MacBook has a laptop icon', (+ tester,+ ) async {+ await open(+ tester,+ machines: [+ machinePool('mac-1', 'MacBook Pro'),+ machinePool('studio', 'MAC-Mac-Studio', deviceType: 'Mac Studio'),+ ],+ );+ expect(+ find.descendant(+ of: key('swarm-machine-$tab-studio'),+ matching: find.byIcon(LucideIcons.monitor300),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: key('swarm-machine-$tab-mac-1'),+ matching: find.byIcon(LucideIcons.laptop300),+ ),+ findsOneWidget,+ );+ });+}diff --git a/mobile/test/swarm/swarm_model_lookups_test.dart b/mobile/test/swarm/swarm_model_lookups_test.dartnew file mode 100644index 000000000..f65b41453--- /dev/null+++ b/mobile/test/swarm/swarm_model_lookups_test.dart@@ -0,0 +1,94 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';++import 'swarm_fixture.dart';++/// A Swarm read finds its chats, agents, projects and Product Managers by id,+/// and says so when one is not there.+void main() {+ const web = 'project-2';+ const webLead = 'group-lead-web';++ final snapshot = SuperTabSnapshot.fromJson(+ SuperTabParts.firstLoad(+ firstLoad(+ head: headData(+ projects: [+ {+ 'id': project,+ 'name': 'Mobile',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ },+ {+ 'id': web,+ 'name': 'Web',+ 'ownerId': me,+ 'leadConversationId': webLead,+ 'visibility': 'public',+ 'members': <Object>[],+ },+ ],+ ),+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', name: 'Builder'),+ {+ ...agent('agent-cleo', name: 'Lead', displayName: 'Cleo'),+ 'projectId': web,+ },+ ],+ groups: [+ groupData('g1', title: 'Fix login', agentIds: ['agent-builder']),+ {+ ...groupData(+ webLead,+ title: 'Web',+ agentIds: ['agent-cleo'],+ leadId: 'agent-cleo',+ ),+ 'projectId': web,+ },+ ],+ ),+ ).state,+ );++ test('a chat and an agent by id; none for an unknown id', () {+ expect(snapshot.conversation('g1')?.title, 'Fix login');+ expect(snapshot.conversation('nope'), isNull);+ expect(snapshot.agent('agent-builder')?.name, 'Builder');+ expect(snapshot.agent('nope'), isNull);+ });++ test(+ "an agent's name: its display name, else its name, else the fallback",+ () {+ expect(snapshot.agentName('agent-lead'), 'River');+ expect(snapshot.agentName('agent-builder'), 'Builder');+ expect(snapshot.agentName('nope'), 'Agent');+ expect(snapshot.agentName('nope', fallback: 'Gone'), 'Gone');+ },+ );++ test("a chat's project; none for an unknown chat", () {+ expect(snapshot.projectFor('g1')?.name, 'Mobile');+ expect(snapshot.projectFor(webLead)?.name, 'Web');+ expect(snapshot.projectFor('nope'), isNull);+ });++ test("each project's Product Manager, and no project for anyone else", () {+ expect(snapshot.leadProjectForAgent('agent-lead')?.id, project);+ expect(snapshot.leadProjectForAgent('agent-cleo')?.id, web);+ expect(snapshot.leadProjectForAgent('agent-builder'), isNull);+ expect(snapshot.isLead('agent-cleo'), isTrue);+ expect(snapshot.isLead('agent-builder'), isFalse);+ expect(+ snapshot.leadProtectionReason('agent-cleo'),+ 'Cleo is the Product Manager of project Web. Delete the project first.',+ );+ });+}diff --git a/mobile/test/swarm/swarm_models_devices_test.dart b/mobile/test/swarm/swarm_models_devices_test.dartnew file mode 100644index 000000000..faf714cb2--- /dev/null+++ b/mobile/test/swarm/swarm_models_devices_test.dart@@ -0,0 +1,547 @@+import 'dart:async';++import 'package:flutter/cupertino.dart' show CupertinoPageRoute;+import 'package:flutter/material.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/swarm/swarm_devices_page.dart';+import 'package:harness_mobile/swarm/swarm_drawer.dart';+import 'package:harness_mobile/swarm/swarm_models_page.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_start.dart';+import 'package:harness_mobile/swarm/swarm_style.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// The drawer's Your models and Your devices, under the projects, and the two+/// read-only pages they open: the models a Swarm can use now, and the+/// person's computers — each with rows on their way while it is read, and+/// words for when there is nothing to list.+void main() {+ /// One Swarm whose models are on, [models] served by its machine Studio+ /// (read just now); its read waits for [held] when given.+ FakeSwarm backend({+ List<Map<String, dynamic>> models = const [],+ bool modelsOn = true,+ Completer<void>? held,+ List<({String id, String name})> swarms = const [+ (id: tab, name: 'Phone Swarm'),+ ],+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ for (final s in swarms) {'id': s.id, 'name': s.name, 'ownerId': me},+ ],+ 'next': null,+ };+ for (final s in swarms) {+ fake.routes['/api/super-tabs/${s.id}/parts'] = (_) async {+ await held?.future;+ final data = firstLoad(tabId: s.id);+ (data['head'] as Map)['data'] = {+ ...headData(id: s.id, name: s.name),+ if (modelsOn)+ 'localModels': {'grid': 'grid-${s.id}', 'enabled': true},+ };+ data['machines'] = [+ part('mac-1', 1, {+ 'machineId': 'mac-1',+ 'name': 'Studio',+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'localModels': [+ for (final m in models) {'grid': 'grid-${s.id}', ...m},+ ],+ },+ }),+ ];+ return data;+ };+ fake.routes['/api/super-tabs/${s.id}/changes'] = (_) =>+ changes(cursor: 'c2');+ fake.routes['/api/super-tabs/${s.id}/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/${s.id}/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ }+ return fake;+ }++ /// [home] under a Swarm that is on, on an iPhone's screen.+ Future<void> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ Widget home = const SwarmPage(),+ SwarmComputers? computers,+ bool settle = true,+ }) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ computers: computers,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ onGenerateRoute: (_) => CupertinoPageRoute<void>(builder: (_) => home),+ ),+ );+ unawaited(host.session!.inbox.refresh());+ // A skeleton breathes for as long as it shows: nothing settles under it.+ if (settle) {+ await tester.pumpAndSettle();+ } else {+ for (var i = 0; i < 5; i++) {+ await tester.pump(const Duration(milliseconds: 16));+ }+ }+ }++ Finder key(String value) => find.byKey(ValueKey(value));+ Finder inside(String k, Finder matching) =>+ find.descendant(of: key(k), matching: matching);+ double y(WidgetTester tester, String k) => tester.getTopLeft(key(k)).dy;++ group('the drawer', () {+ testWidgets('lists Your models and Your devices under the projects', (+ tester,+ ) async {+ await pump(+ tester,+ backend(),+ computers: _Computers(const [(name: 'Studio Mac', away: false)]),+ );+ await tester.tap(key('swarm-menu'));+ await tester.pumpAndSettle();++ expect(+ inside('swarm-drawer-models', find.text('Your models')),+ findsOneWidget,+ );+ expect(+ inside('swarm-drawer-devices', find.text('Your devices')),+ findsOneWidget,+ );+ expect(+ y(tester, 'swarm-drawer-project-$tab-$project'),+ lessThan(y(tester, 'swarm-drawer-models')),+ );+ expect(+ y(tester, 'swarm-drawer-models'),+ lessThan(y(tester, 'swarm-drawer-devices')),+ );+ expect(+ tester.getSize(key('swarm-drawer-models')).height,+ greaterThanOrEqualTo(44),+ reason: "a thumb's tap",+ );+ });++ testWidgets('Your devices shows only where the computers are known', (+ tester,+ ) async {+ await pump(tester, backend());+ await tester.tap(key('swarm-menu'));+ await tester.pumpAndSettle();++ expect(key('swarm-drawer-models'), findsOneWidget);+ expect(key('swarm-drawer-devices'), findsNothing);+ });++ testWidgets('Your models closes the drawer and opens its page', (+ tester,+ ) async {+ await pump(+ tester,+ backend(+ models: [+ {'model': 'qwen3-coder', 'name': 'Qwen3 Coder', 'kind': 'local'},+ ],+ ),+ );+ await tester.tap(key('swarm-menu'));+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-drawer-models'));+ await tester.pumpAndSettle();++ expect(key('swarm-drawer-models'), findsNothing, reason: 'it closed');+ expect(find.byType(SwarmModelsPage), findsOneWidget);+ expect(find.text('Qwen3 Coder'), findsOneWidget);+ });++ testWidgets('Your devices closes the drawer and opens its page', (+ tester,+ ) async {+ await pump(+ tester,+ backend(),+ computers: _Computers(const [(name: 'Studio Mac', away: false)]),+ );+ await tester.tap(key('swarm-menu'));+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-drawer-devices'));+ await tester.pumpAndSettle();++ expect(key('swarm-drawer-devices'), findsNothing, reason: 'it closed');+ expect(find.byType(SwarmDevicesPage), findsOneWidget);+ expect(find.text('Studio Mac'), findsOneWidget);+ });++ testWidgets('a drawer too short for its rows scrolls Your devices out '+ 'from under Settings', (tester) async {+ await pump(+ tester,+ backend(),+ home: SwarmPage(onSettings: (_) {}),+ computers: _Computers(const [(name: 'Studio Mac', away: false)]),+ );+ // A phone shorter than the drawer's rows.+ tester.view.physicalSize = const Size(1179, 1500);+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-menu'));+ await tester.pumpAndSettle();+ final settings = tester.getRect(key('swarm-drawer-settings'));+ final devices = key('swarm-drawer-devices');+ // Below the list's end it is not even built yet.+ expect(+ devices.evaluate().isEmpty ||+ tester.getRect(devices).bottom > settings.top,+ isTrue,+ reason: 'under the pinned Settings row at first',+ );++ await tester.scrollUntilVisible(+ devices,+ 100,+ scrollable: find+ .descendant(+ of: find.byType(SwarmDrawer),+ matching: find.byType(Scrollable),+ )+ .first,+ );+ await tester.pumpAndSettle();++ expect(tester.getRect(devices).bottom, lessThanOrEqualTo(settings.top));+ await tester.tap(devices);+ await tester.pumpAndSettle();+ expect(find.byType(SwarmDevicesPage), findsOneWidget);+ });+ });++ group('Your models', () {+ testWidgets('rows on their way while the Swarm is read', (tester) async {+ final held = Completer<void>();+ await pump(+ tester,+ backend(held: held),+ home: const SwarmModelsPage(),+ settle: false,+ );++ expect(key('swarm-models-loading-$tab'), findsOneWidget);++ held.complete();+ await tester.pumpAndSettle();+ expect(key('swarm-models-loading-$tab'), findsNothing);+ });++ testWidgets('APIs, local models and one-computer models, under headings', (+ tester,+ ) async {+ await pump(+ tester,+ backend(+ models: [+ {+ 'model': 'moonshotai/kimi-k3',+ 'name': 'moonshotai/kimi-k3 · OpenRouter',+ 'kind': 'api',+ },+ {'model': 'qwen3-coder', 'name': 'Qwen3 Coder', 'kind': 'local'},+ {'model': 'llama-4', 'name': 'Llama 4', 'kind': 'shared'},+ ],+ ),+ home: const SwarmModelsPage(),+ );++ expect(find.text('API models'), findsOneWidget);+ expect(find.text('Local models'), findsOneWidget);+ expect(find.text('On one computer only'), findsOneWidget);+ expect(find.text('kimi-k3'), findsOneWidget);+ expect(find.text('OpenRouter'), findsOneWidget);+ expect(find.text('Qwen3 Coder'), findsOneWidget);+ expect(find.text('Llama 4'), findsOneWidget);+ expect(find.textContaining('Studio'), findsWidgets);+ expect(+ tester.getTopLeft(find.text('kimi-k3')).dy,+ lessThan(tester.getTopLeft(find.text('Qwen3 Coder')).dy),+ );+ expect(+ tester.getTopLeft(find.text('Qwen3 Coder')).dy,+ lessThan(tester.getTopLeft(find.text('Llama 4')).dy),+ );+ });++ testWidgets('a Swarm with nothing running says so', (tester) async {+ await pump(tester, backend(), home: const SwarmModelsPage());++ expect(key('swarm-models-none-$tab'), findsOneWidget);+ expect(+ find.text('No models are running for this Swarm right now.'),+ findsOneWidget,+ );+ });++ testWidgets('nothing to list is a line under the caption, as on Home', (+ tester,+ ) async {+ await pump(tester, backend(), home: const SwarmModelsPage());++ expect(+ find.ancestor(+ of: key('swarm-models-none-$tab'),+ matching: find.byType(SwarmGroup),+ matchRoot: true,+ ),+ findsNothing,+ reason: "Home's empty states are words, not a card",+ );+ });++ testWidgets('its lines sit 12 in from the edge, the words 4 more', (+ tester,+ ) async {+ await pump(tester, backend(), home: const SwarmModelsPage());++ expect(tester.getTopLeft(key('swarm-models-none-$tab')).dx, 12);+ expect(+ tester+ .getTopLeft(+ find.text('No models are running for this Swarm right now.'),+ )+ .dx,+ 12 + 4,+ );+ });++ testWidgets('pulling down reads the Swarms again, as on Home', (+ tester,+ ) async {+ final fake = backend();+ await pump(tester, fake, home: const SwarmModelsPage());+ int lists() => fake.paths.where((p) => p.endsWith('/list')).length;+ final before = lists();++ await tester.fling(+ find.byType(Scrollable).first,+ const Offset(0, 400),+ 1000,+ );+ await tester.pumpAndSettle();++ expect(lists(), greaterThan(before));+ });++ testWidgets('a Swarm whose models are not set up says who sets them up', (+ tester,+ ) async {+ await pump(+ tester,+ backend(modelsOn: false),+ home: const SwarmModelsPage(),+ );++ expect(key('swarm-models-off-$tab'), findsOneWidget);+ expect(+ find.text(+ "Models aren't set up for this Swarm yet. "+ 'Its owner sets them up on a computer.',+ ),+ findsOneWidget,+ );+ });++ testWidgets('several Swarms: one block each, under its name', (+ tester,+ ) async {+ await pump(+ tester,+ backend(+ swarms: const [+ (id: 'tab-a', name: 'Alpha'),+ (id: 'tab-b', name: 'Beta'),+ ],+ ),+ home: const SwarmModelsPage(),+ );++ expect(find.text('Alpha'), findsOneWidget);+ expect(find.text('Beta'), findsOneWidget);+ expect(key('swarm-models-none-tab-a'), findsOneWidget);+ expect(key('swarm-models-none-tab-b'), findsOneWidget);+ });+ });++ group('Your devices', () {+ testWidgets('rows on their way until the computers are known', (+ tester,+ ) async {+ final computers = _Computers(null);+ await pump(+ tester,+ backend(),+ home: const SwarmDevicesPage(),+ computers: computers,+ settle: false,+ );++ expect(key('swarm-devices-loading'), findsOneWidget);++ computers.set(const [(name: 'Studio Mac', away: false)]);+ await tester.pumpAndSettle();+ expect(key('swarm-devices-loading'), findsNothing);+ expect(find.text('Studio Mac'), findsOneWidget);+ });++ testWidgets('each computer, online or offline, with nothing to tap', (+ tester,+ ) async {+ await pump(+ tester,+ backend(),+ home: const SwarmDevicesPage(),+ computers: _Computers(const [+ (name: 'Studio Mac', away: false),+ (name: 'Office iMac', away: true),+ ]),+ );++ expect(inside('swarm-device-0', find.text('Studio Mac')), findsOneWidget);+ expect(inside('swarm-device-0', find.text('Online')), findsOneWidget);+ expect(+ inside('swarm-device-1', find.text('Office iMac')),+ findsOneWidget,+ );+ expect(inside('swarm-device-1', find.text('Offline')), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-device-0'),+ matching: find.byType(InkWell),+ ),+ findsNothing,+ reason: 'read only',+ );+ });++ testWidgets('pulling down reads the computers again', (tester) async {+ final computers = _Computers(const [(name: 'Studio Mac', away: false)]);+ await pump(+ tester,+ backend(),+ home: const SwarmDevicesPage(),+ computers: computers,+ );++ await tester.fling(+ find.byType(Scrollable).first,+ const Offset(0, 400),+ 1000,+ );+ await tester.pumpAndSettle();++ expect(computers.rechecks, 1);+ });++ testWidgets('no computer yet is a line under the caption, as on Home', (+ tester,+ ) async {+ await pump(+ tester,+ backend(),+ home: const SwarmDevicesPage(),+ computers: _Computers(const []),+ );++ expect(+ find.ancestor(+ of: key('swarm-devices-none'),+ matching: find.byType(SwarmGroup),+ matchRoot: true,+ ),+ findsNothing,+ );+ });++ testWidgets('its lines sit 12 in from the edge, the words 4 more', (+ tester,+ ) async {+ await pump(+ tester,+ backend(),+ home: const SwarmDevicesPage(),+ computers: _Computers(const []),+ );++ expect(tester.getTopLeft(key('swarm-devices-none')).dx, 12);+ expect(+ tester.getTopLeft(find.text('No computers on your account yet.')).dx,+ 12 + 4,+ );+ });++ testWidgets('no computer yet says so', (tester) async {+ await pump(+ tester,+ backend(),+ home: const SwarmDevicesPage(),+ computers: _Computers(const []),+ );++ expect(key('swarm-devices-none'), findsOneWidget);+ expect(find.text('No computers on your account yet.'), findsOneWidget);+ });+ });+}++/// The person's computers as a test sets them.+class _Computers extends ChangeNotifier implements SwarmComputers {+ _Computers(this.computers);++ @override+ List<SwarmComputer>? computers;++ @override+ bool get rechecking => false;++ void set(List<SwarmComputer>? next) {+ computers = next;+ notifyListeners();+ }++ var rechecks = 0;++ @override+ Future<void> recheck() async => rechecks++;++ @override+ void add(BuildContext context) {}+}diff --git a/mobile/test/swarm/swarm_models_test.dart b/mobile/test/swarm/swarm_models_test.dartnew file mode 100644index 000000000..d92e5d7d8--- /dev/null+++ b/mobile/test/swarm/swarm_models_test.dart@@ -0,0 +1,149 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_models_page.dart';++import 'swarm_fixture.dart';++/// What Your models lists for a Swarm: the models its machines' fresh+/// readings say it can use now, as Desktop's machine details read them — an+/// API a member shares, a member's model on the Swarm's grid, or a model+/// shared with one machine's owner, usable on that machine alone.+void main() {+ final now = DateTime.utc(2026, 10, 28, 4);+ final fresh = now.subtract(const Duration(seconds: 10));+ final stale = now.subtract(const Duration(minutes: 2));++ Map<String, dynamic> machine(+ String id,+ String name,+ List<Map<String, dynamic>> models, {+ DateTime? at,+ }) => {+ 'machineId': id,+ 'name': name,+ 'observation': {+ 'receivedAt': (at ?? fresh).millisecondsSinceEpoch,+ 'localModels': models,+ },+ };++ SuperTabSnapshot snapshot({+ Map<String, dynamic>? localModels = const {+ 'grid': 'swarm-grid',+ 'enabled': true,+ 'ready': true,+ },+ List<Map<String, dynamic>> machines = const [],+ }) {+ final data = firstLoad();+ (data['head'] as Map)['data'] = {+ ...headData(),+ 'localModels': ?localModels,+ };+ data['machines'] = [+ for (final (i, m) in machines.indexed)+ part(m['machineId'] as String, 1 + i, m),+ ];+ return SuperTabSnapshot.fromJson(SuperTabParts.firstLoad(data).state);+ }++ test('a Swarm whose models were never turned on lists none', () {+ expect(swarmModelList(snapshot(localModels: null), now: now), isNull);+ expect(+ swarmModelList(+ snapshot(localModels: {'grid': 'swarm-grid', 'enabled': false}),+ now: now,+ ),+ isNull,+ );+ });++ test('APIs, local models and one-computer models, each where it runs', () {+ final list = swarmModelList(+ snapshot(+ machines: [+ machine('mac-1', 'MacbookPro.local', [+ {+ 'grid': 'swarm-grid',+ 'model': 'moonshotai/kimi-k3',+ 'name': 'moonshotai/kimi-k3 · OpenRouter',+ 'kind': 'api',+ },+ {+ 'grid': 'swarm-grid',+ 'model': 'qwen3-coder-30b',+ 'name': 'Qwen3 Coder 30B',+ 'kind': 'local',+ },+ ]),+ machine('mac-2', "Diego's Mac", [+ {+ 'grid': 'diego-grid',+ 'model': 'llama-4-scout',+ 'name': 'Llama 4 Scout',+ 'kind': 'shared',+ },+ ]),+ ],+ ),+ now: now,+ )!;++ expect(list.apis, [+ (name: 'kimi-k3', provider: 'OpenRouter', machine: 'MacbookPro.local'),+ ]);+ expect(list.local, [+ (name: 'Qwen3 Coder 30B', provider: null, machine: 'MacbookPro.local'),+ ]);+ expect(list.oneComputer, [+ (name: 'Llama 4 Scout', provider: null, machine: "Diego's Mac"),+ ]);+ expect(list.isEmpty, isFalse);+ });++ test('an old reading, or a model still starting, is not usable now', () {+ final list = swarmModelList(+ snapshot(+ machines: [+ machine('mac-1', 'Studio', [+ {'grid': 'swarm-grid', 'model': 'old', 'kind': 'local'},+ ], at: stale),+ machine('mac-2', 'Mini', [+ {+ 'grid': 'swarm-grid',+ 'model': 'warming',+ 'kind': 'local',+ 'starting': true,+ },+ ]),+ ],+ ),+ now: now,+ )!;++ expect(list.isEmpty, isTrue);+ });++ test('a model two machines offer is listed once', () {+ final model = {+ 'grid': 'swarm-grid',+ 'model': 'deepseek/deepseek-v4.1-flash',+ 'name': 'deepseek/deepseek-v4.1-flash · OpenRouter',+ 'kind': 'api',+ };+ final list = swarmModelList(+ snapshot(+ machines: [+ machine('mac-1', 'Studio', [model]),+ machine('mac-2', 'Mini', [model]),+ ],+ ),+ now: now,+ )!;++ expect(list.apis, [+ (name: 'deepseek-v4.1-flash', provider: 'OpenRouter', machine: 'Studio'),+ ]);+ });+}diff --git a/mobile/test/swarm/swarm_news_shots_test.dart b/mobile/test/swarm/swarm_news_shots_test.dartnew file mode 100644index 000000000..00aed6198--- /dev/null+++ b/mobile/test/swarm/swarm_news_shots_test.dart@@ -0,0 +1,224 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Review screenshots of Swarm Home and its drawer with a chat unread and a+/// tag waiting, in both phone themes, from made-up Swarm data only.+final shots = Platform.environment['SWARM_NEWS_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('Home and the drawer, unread and tagged, in both phone themes', (+ tester,+ ) async {+ const web = 'project-web';+ const webLead = 'group-web-lead';+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'OpenHarness', 'ownerId': me},+ ],+ 'next': null,+ };+ Map<String, dynamic> inWeb(Map<String, dynamic> row) => {+ ...row,+ 'projectId': web,+ };+ Map<String, dynamic> work(String id, String title, int number, int at) =>+ groupData(+ id,+ title: title,+ number: number,+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ workerId: 'agent-builder',+ lastMessageSequence: at,+ );+ const derived = {'mentionsWaiting': 1};+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ derived: derived,+ head: headData(+ name: 'OpenHarness',+ projects: [+ {+ 'id': project,+ 'name': 'openharness',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ {+ 'id': web,+ 'name': 'web-2',+ 'ownerId': me,+ 'leadConversationId': webLead,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ buddyData('agent-wren', displayName: 'Wren'),+ inWeb(agent('agent-cleo', name: 'Lead', displayName: 'Cleo')),+ ],+ groups: [+ work('g-bold', 'Mobile: bold names and @N', 12, 3),+ work('g-agents', 'Desktop: agents list', 13, 2),+ buddyChatData(+ 'buddy-me',+ agentIds: ['agent-wren'],+ lastMessageSequence: 1,+ ),+ inWeb(+ groupData(+ webLead,+ title: 'web-2',+ agentIds: ['agent-cleo'],+ leadId: 'agent-cleo',+ lastMessageSequence: 1,+ ),+ ),+ ],+ );+ // Read once: what was there is read; then the work chat and the Buddy+ // chat move on.+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [+ {+ 'id': 'm1',+ 'projectId': project,+ 'projectName': 'openharness',+ 'conversationId': leadChat,+ 'conversationTitle': 'openharness',+ 'messageId': 'msg-1',+ 'leadName': 'River',+ 'text': 'Can you check the mockups?',+ 'createdAt': '2026-10-29T01:00:00.000Z',+ },+ ],+ };+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => me,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (_, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmPage(),+ ),+ ),+ );+ await tester.pumpAndSettle();+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ derived: derived,+ groups: [+ part(+ 'g-bold',+ 30,+ work('g-bold', 'Mobile: bold names and @N', 12, 5),+ ),+ part(+ 'buddy-me',+ 31,+ buddyChatData(+ 'buddy-me',+ agentIds: ['agent-wren'],+ lastMessageSequence: 2,+ ),+ ),+ ],+ );+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();+ Future<void> capture(String name) => tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File('$shots/news-$name-${brightness.name}.png')+ .writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ await capture('home');+ await tester.tap(find.byKey(const ValueKey('swarm-menu')));+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('swarm-drawer-chats-$tab-$project')),+ );+ await tester.pumpAndSettle();+ await capture('drawer');+ await tester.pumpWidget(const SizedBox());+ host.dispose();+ account.dispose();+ }+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_notices_test.dart b/mobile/test/swarm/swarm_notices_test.dartnew file mode 100644index 000000000..a2733098c--- /dev/null+++ b/mobile/test/swarm/swarm_notices_test.dart@@ -0,0 +1,311 @@+import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_asks.dart';+import 'package:harness_mobile/swarm/swarm_inbox.dart';+import 'package:harness_mobile/swarm/swarm_notices.dart';+import 'package:harness_mobile/swarm/waiting_work.dart';++import 'swarm_fixture.dart';++/// What the phone's notices say about the Swarm: a decision asked of the+/// person, a Lead's tag, work waiting on them — and where a tap leads.+///+/// A notice can be read on a locked phone, so it says only who asks and in+/// which project; what they ask is read in the app (Lead, 2026-10-27).+void main() {+ SwarmDecisionNeed decision() => SwarmDecisionNeed(+ 'tab-b',+ SuperTabDecision.fromJson({+ 'id': 'd1',+ 'projectName': 'Mobile',+ 'conversationId': 'g9',+ 'conversationTitle': 'Fix login',+ 'askerName': 'River',+ 'question': 'Ship it behind a flag?',+ 'options': ['Yes', 'No'],+ }),+ );++ SwarmMentionNeed mention() => SwarmMentionNeed(+ 'tab-b',+ SuperTabMention.fromJson({+ 'id': 'm1',+ 'projectName': 'Mobile',+ 'conversationId': 'g9',+ 'conversationTitle': 'Fix login',+ 'messageId': 'msg-1',+ 'leadName': 'River',+ 'text': 'Can you check the copy?',+ }),+ );++ SwarmWorkNeed work(String status, {String? result}) {+ final snapshot = SuperTabSnapshot.fromJson(+ SuperTabParts.firstLoad(+ firstLoad(+ groups: [+ {+ ...groupData('g1', title: 'Sync', number: 4, status: status),+ 'assignment': {+ 'id': 'attempt-g1',+ 'agentId': 'agent-builder',+ 'status': status,+ 'result': result,+ },+ },+ ],+ ),+ ).state,+ );+ return SwarmWorkNeed(tab, swarmWaitingWork(snapshot, me).single);+ }++ /// Nothing the notice shows: what was asked, or where.+ void keepsItsContent(SwarmNoticeMessage notice, List<String> private) {+ for (final text in private) {+ for (final line in [notice.title, notice.subtitle, notice.body]) {+ expect(line, isNot(contains(text)), reason: '"$text" in "$line"');+ }+ }+ }++ test('a decision says who asks and in which project, not the question', () {+ final notice = swarmNotice(decision());++ expect(notice.title, 'River asks you');+ expect(notice.subtitle, 'Mobile');+ expect(notice.body, 'Open Harness to answer.');+ expect(notice.target, (+ swarmId: 'tab-b',+ conversationId: 'g9',+ messageId: null,+ decisionId: 'd1',+ ));+ keepsItsContent(notice, ['Ship it', 'Yes', 'Fix login']);+ });++ test("a tag says who tagged, not the Lead's words", () {+ final notice = swarmNotice(mention());++ expect(notice.title, 'River tagged you');+ expect(notice.subtitle, 'Mobile');+ expect(notice.body, 'Open Harness to read it.');+ keepsItsContent(notice, ['check the copy', 'Fix login']);+ });++ test("waiting work says who waits, not the worker's words", () {+ final needs = swarmNotice(work('needs_human', result: 'Which name?'));+ expect(needs.title, 'Nova needs you');+ expect(needs.subtitle, 'Mobile');+ expect(needs.body, 'Open Harness to answer.');+ keepsItsContent(needs, ['Which name', 'Sync']);++ final stuck = swarmNotice(work('blocked', result: 'No access to the repo'));+ expect(stuck.title, 'Nova is stuck');+ expect(stuck.body, 'Open Harness to see why.');+ keepsItsContent(stuck, ['No access', 'Sync']);+ });++ test('each need is its own notice, and the same need replaces itself', () {+ expect(swarmNotice(decision()).key, swarmNotice(decision()).key);+ expect(swarmNotice(decision()).key, isNot(swarmNotice(mention()).key));+ });++ test('nothing is posted while the Swarm is on screen', () {+ final notices = _Recording();+ var onScreen = true;+ final announcer = SwarmAnnouncer(notices, quiet: (_) => onScreen);++ announcer.announce(decision());+ expect(notices.shown, isEmpty);++ onScreen = false;+ announcer.announce(decision());+ expect(notices.shown.single.title, 'River asks you');+ });++ test('a notice is taken down once its need is gone, and only then', () {+ final notices = _Recording();+ final announcer = SwarmAnnouncer(notices, quiet: (_) => false);+ announcer.announce(decision());+ announcer.announce(mention());++ announcer.settle([decision(), mention()]);+ expect(notices.cancelled, isEmpty);++ // Answered on the desktop: the lock screen must stop asking.+ announcer.settle([mention()]);+ expect(notices.cancelled, [decision().key]);++ // Signed out: nothing of the account stays on the lock screen.+ announcer.clear();+ expect(notices.cancelled, [decision().key, mention().key]);+ });++ test('a need never shown is never taken down', () {+ final notices = _Recording();+ final announcer = SwarmAnnouncer(notices, quiet: (_) => true);+ announcer.announce(decision());++ announcer.settle(const []);++ expect(notices.cancelled, isEmpty);+ });++ group("the app icon's count", () {+ test('is the number of needs each read, as the drawer counts them', () {+ final notices = _Recording();+ final announcer = SwarmAnnouncer(notices, quiet: (_) => false);++ announcer.settle([decision(), mention(), work('needs_human')]);+ expect(notices.badges, [3]);++ // Answered on the desktop.+ announcer.settle([mention(), work('needs_human')]);+ expect(notices.badges, [3, 2]);+ });++ test('is set on the first read even with nothing waiting', () {+ // What an earlier run left on the icon goes.+ final notices = _Recording();+ SwarmAnnouncer(notices, quiet: (_) => false).settle(const []);+ expect(notices.badges, [0]);+ });++ test('is not set again while it stays the same', () {+ final notices = _Recording();+ final announcer = SwarmAnnouncer(notices, quiet: (_) => false);++ announcer.settle([decision()]);+ announcer.settle([mention()]);++ expect(notices.badges, [1]);+ });++ test('counts while a Swarm screen is up, where no notice is posted', () {+ final notices = _Recording();+ final announcer = SwarmAnnouncer(notices, quiet: (_) => true);++ announcer.settle([decision(), mention()]);++ expect(notices.badges, [2]);+ });++ test('clears when the account signs out', () {+ final notices = _Recording();+ final announcer = SwarmAnnouncer(notices, quiet: (_) => false);+ announcer.settle([decision()]);++ announcer.clear();++ expect(notices.badges, [1, 0]);+ });+ });++ group("the app icon's count while nobody is signed in", () {+ test('goes as the app finds itself signed out, once each time', () {+ final notices = _Recording();+ final app = ValueNotifier('booting');+ swarmBadgeOffWhileSignedOut(+ app,+ signedOut: () => app.value == 'signed out',+ notices: notices,+ );+ expect(notices.badges, isEmpty, reason: 'not known yet');++ // A launch that starts signed out never makes a Swarm session, whose+ // end would have taken the last account's count off.+ app.value = 'signed out';+ expect(notices.badges, [0]);+ app.notifyListeners();+ expect(notices.badges, [0], reason: 'still signed out: once');++ app.value = 'signed in';+ expect(notices.badges, [0], reason: 'the session counts from here');++ app.value = 'signed out';+ expect(notices.badges, [0, 0]);+ });++ test('a launch already known to be signed out takes it off at once', () {+ final notices = _Recording();+ swarmBadgeOffWhileSignedOut(+ ValueNotifier(0),+ signedOut: () => true,+ notices: notices,+ );+ expect(notices.badges, [0]);+ });+ });++ group('the tap', () {+ test('a message tap retains its exact message through the OS payload', () {+ expect(decodeSwarmPayload('swarm:tab-b/g9/message/m%2F7'), (+ swarmId: 'tab-b',+ conversationId: 'g9',+ messageId: 'm/7',+ decisionId: null,+ ));+ });+ test('a decision tap retains its card through the OS payload', () {+ expect(decodeSwarmPayload('swarm:tab-b/g9/decision/d1'), (+ swarmId: 'tab-b',+ conversationId: 'g9',+ messageId: null,+ decisionId: 'd1',+ ));+ });++ test('leads to the Swarm and conversation, never read as an agent', () {+ const target = (+ swarmId: 'tab-b',+ conversationId: 'g9',+ messageId: null,+ decisionId: null,+ );+ final payload = encodeSwarmPayload(target);++ expect(decodeSwarmPayload(payload), target);+ expect(decodeAgentPayload(payload), isNull);+ expect(+ decodeSwarmPayload(encodeAgentPayload((machineId: 'm', agentId: 'a'))),+ isNull,+ );+ });++ test('a damaged payload opens nothing', () {+ expect(decodeSwarmPayload('swarm:%E0%A4%A/g9'), isNull);+ expect(decodeSwarmPayload('swarm:tab-b'), isNull);+ expect(decodeSwarmPayload('swarm:/g9'), isNull);+ expect(decodeSwarmPayload('device:tab-b/g9'), isNull);+ });++ test('a notice id is stable and never an agent notice id', () {+ expect(swarmNoticeIdFor('decision:d1'), swarmNoticeIdFor('decision:d1'));+ expect(+ swarmNoticeIdFor('decision:d1'),+ isNot(swarmNoticeIdFor('decision:d2')),+ );+ expect(swarmNoticeIdFor('decision:d1'), greaterThan(0));+ });+ });+}++class _Recording extends SilentSystemNotices {+ final shown = <SwarmNoticeMessage>[];+ final cancelled = <String>[];+ final badges = <int>[];++ @override+ Future<void> showSwarm(SwarmNoticeMessage message) async =>+ shown.add(message);++ @override+ Future<void> cancelSwarm(String key) async => cancelled.add(key);++ @override+ Future<void> setSwarmBadge(int count) async => badges.add(count);+}diff --git a/mobile/test/swarm/swarm_outgoing_files_test.dart b/mobile/test/swarm/swarm_outgoing_files_test.dartnew file mode 100644index 000000000..eb957f6bc--- /dev/null+++ b/mobile/test/swarm/swarm_outgoing_files_test.dart@@ -0,0 +1,154 @@+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';++/// The files waiting to go with the next message in a phone Swarm chat: the+/// desktop's rules (`desktop/lib/state/harness_attachments.dart` with the+/// limits of `desktop/lib/super_tabs/attachment_upload.dart`).+void main() {+ SwarmOutgoingFile file(String name, int size) =>+ SwarmOutgoingFile(name, Uint8List(size));++ test('takes files in the order picked', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);++ expect(files.add([file('a.jpg', 3), file('b.pdf', 5)]), isNull);++ expect([for (final f in files.files) f.name], ['a.jpg', 'b.pdf']);+ });++ test('a file over 10 MB is left out and named', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);++ final said = files.add([+ file('big.jpg', 10 * 1024 * 1024 + 1),+ file('ok.jpg', 10 * 1024 * 1024),+ ]);++ expect(said, 'big.jpg is over 10 MB.');+ expect([for (final f in files.files) f.name], ['ok.jpg']);+ });++ test('several files over 10 MB are counted', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);++ final said = files.add([+ file('a.jpg', 11 * 1024 * 1024),+ file('b.jpg', 12 * 1024 * 1024),+ ]);++ expect(said, '2 files are over 10 MB.');+ expect(files.files, isEmpty);+ });++ test('an eleventh file is refused', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);+ files.add([for (var i = 0; i < 10; i++) file('$i.jpg', 1)]);++ final said = files.add([file('extra.jpg', 1)]);++ expect(said, 'Attach at most 10 files.');+ expect(files.files, hasLength(10));+ expect(files.files.any((f) => f.name == 'extra.jpg'), isFalse);+ });++ test('a file of a name already there takes its place', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);+ files.add([file('a.jpg', 1), file('b.jpg', 1)]);++ files.add([file('a.jpg', 7)]);++ expect([for (final f in files.files) f.name], ['b.jpg', 'a.jpg']);+ expect(files.files.last.bytes, hasLength(7));+ });++ test('an empty file is skipped silently', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);++ expect(files.add([file('empty.txt', 0)]), isNull);++ expect(files.files, isEmpty);+ });++ test('room is what ten files leave', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);+ expect(files.room, 10);++ files.add([file('a.jpg', 1), file('b.jpg', 1), file('c.jpg', 1)]);++ expect(files.room, 7);+ });++ test('a camera photo never replaces another of the same name', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);+ files.add([file('photo.jpg', 1)]);++ files.addNumbered([file('photo.jpg', 2)]);+ files.addNumbered([file('photo.jpg', 3)]);++ expect([for (final f in files.files) f.name], [+ 'photo.jpg',+ 'photo-2.jpg',+ 'photo-3.jpg',+ ]);+ });++ test('remove and clear tell their listeners', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);+ files.add([file('a.jpg', 1), file('b.jpg', 1)]);+ var told = 0;+ files.addListener(() => told++);++ files.remove(files.files.first);+ expect([for (final f in files.files) f.name], ['b.jpg']);+ files.clear();++ expect(files.files, isEmpty);+ expect(told, 2);+ });++ group('swarmMimeForName', () {+ test('names the kinds the desktop names', () {+ expect(swarmMimeForName('a.PNG'), 'image/png');+ expect(swarmMimeForName('a.jpg'), 'image/jpeg');+ expect(swarmMimeForName('a.jpeg'), 'image/jpeg');+ expect(swarmMimeForName('a.gif'), 'image/gif');+ expect(swarmMimeForName('a.webp'), 'image/webp');+ expect(swarmMimeForName('a.pdf'), 'application/pdf');+ expect(swarmMimeForName('a.json'), 'application/json');+ expect(swarmMimeForName('a.zip'), 'application/zip');+ expect(swarmMimeForName('a.txt'), 'text/plain');+ expect(swarmMimeForName('a.log'), 'text/plain');+ expect(swarmMimeForName('a.md'), 'text/markdown');+ expect(swarmMimeForName('a.csv'), 'text/csv');+ });++ test('anything else goes as bytes', () {+ expect(swarmMimeForName('a.heic'), 'application/octet-stream');+ expect(swarmMimeForName('Makefile'), 'application/octet-stream');+ });+ });++ test('files over both the count and the size say both', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);++ final said = files.add([+ for (var i = 0; i < 11; i++) file('f$i.txt', 1),+ file('big.jpg', 10 * 1024 * 1024 + 1),+ ]);++ expect(said, 'Attach at most 10 files. big.jpg is over 10 MB.');+ expect(files.files, hasLength(10));+ });+}diff --git a/mobile/test/swarm/swarm_profile_sheet_test.dart b/mobile/test/swarm/swarm_profile_sheet_test.dartnew file mode 100644index 000000000..46e9ba3ba--- /dev/null+++ b/mobile/test/swarm/swarm_profile_sheet_test.dart@@ -0,0 +1,502 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:image_picker/image_picker.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_profile_sheet.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../theme/sheet_shape.dart';+import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// The person's own profile in a Swarm, in a sheet from the foot of the+/// screen: a built-in picture or a photo of theirs, and a status that clears+/// when they say.+void main() {+ late FakeSwarm swarm;+ late Map<String, dynamic> mine;+ late List<Uint8List> uploads;++ Future<Uint8List> photo() async {+ final recorder = ui.PictureRecorder();+ ui.Canvas(recorder).drawRect(+ const ui.Rect.fromLTWH(0, 0, 40, 30),+ ui.Paint()..color = const ui.Color(0xFF22AA66),+ );+ final image = await recorder.endRecording().toImage(40, 30);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ return bytes!.buffer.asUint8List();+ }++ /// The sheet open over a page, for a member with [role]; [canUpload] off+ /// is a phone that cannot send a picture.+ Future<void> open(+ WidgetTester tester, {+ String role = 'owner',+ Map<String, dynamic> extra = const {},+ bool canUpload = true,+ Future<String> Function()? answer,+ Uint8List? picked,+ Future<Uint8List?> Function()? pick,+ }) async {+ swarm = FakeSwarm();+ mine = {...person(me, role: role), ...extra};+ var version = 1;+ swarm.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(),+ 'members': [part(me, version, mine)],+ };+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c${++version}'),+ 'members': [part(me, version, mine)],+ };+ swarm.routes['/api/super-tabs/$tab/commands'] = (body) {+ final command = body!['command'] as Map<String, dynamic>;+ switch (command['type']) {+ case 'member.avatar':+ final avatar = command['avatar'] as Map<String, dynamic>?;+ mine = {+ ...mine..remove('avatar'),+ if (avatar != null)+ 'avatar': avatar['kind'] == 'upload'+ ? {'kind': 'upload'}+ : avatar,+ };+ case 'member.status':+ mine = {...mine..remove('status'), 'status': ?command['status']};+ }+ return {'ok': true};+ };+ uploads = [];+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: swarm.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ uploadAvatar: canUpload+ ? ({required tabId, required png}) async {+ uploads.add(png);+ return answer == null ? 'upload-1' : await answer();+ }+ : null,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: Builder(+ builder: (context) => Scaffold(+ body: Center(+ child: TextButton(+ onPressed: () => showSwarmProfile(+ context,+ swarmId: tab,+ pickPhoto: pick ?? () async => picked,+ ),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ ),+ );+ // The Swarm read first, as the shell would have.+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ expect(sheetTopRadius(tester), 12);+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ /// Taps [finder], then lets the command and the read after it answer.+ Future<void> tap(WidgetTester tester, Finder finder) async {+ await tester.ensureVisible(finder);+ await tester.pumpAndSettle();+ await tester.tap(finder);+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ }++ testWidgets('it shows their face and the eight pictures, each a thumb '+ 'wide', (tester) async {+ await open(+ tester,+ extra: {+ 'avatar': {'kind': 'preset', 'key': 'fox'},+ },+ );+ expect(find.text('Your profile'), findsOneWidget);+ expect(+ find.descendant(of: key('swarm-profile-face'), matching: find.text('🦊')),+ findsOneWidget,+ );+ for (final name in [+ 'fox',+ 'owl',+ 'cat',+ 'panda',+ 'octopus',+ 'cactus',+ 'rocket',+ 'sun',+ ]) {+ final size = tester.getSize(key('swarm-avatar-preset-$name'));+ expect(size.width, greaterThanOrEqualTo(44), reason: name);+ expect(size.height, greaterThanOrEqualTo(44), reason: name);+ }+ });++ testWidgets('a picture tapped is theirs at once', (tester) async {+ await open(tester);+ await tap(tester, key('swarm-avatar-preset-owl'));+ expect(swarm.commands, [+ {+ 'type': 'member.avatar',+ 'avatar': {'kind': 'preset', 'key': 'owl'},+ },+ ]);+ expect(+ find.descendant(of: key('swarm-profile-face'), matching: find.text('🦉')),+ findsOneWidget,+ );+ });++ testWidgets('back to the initial, offered only when they wear something', (+ tester,+ ) async {+ await open(tester);+ expect(key('swarm-avatar-default'), findsNothing);+ await tap(tester, key('swarm-avatar-preset-cat'));+ await tap(tester, key('swarm-avatar-default'));+ expect(swarm.commands.last, {'type': 'member.avatar', 'avatar': null});+ expect(key('swarm-avatar-default'), findsNothing);+ });++ testWidgets('a photo from the library goes up and becomes theirs', (+ tester,+ ) async {+ final picked = await tester.runAsync(photo);+ await open(tester, picked: picked);+ await tester.ensureVisible(key('swarm-avatar-photo'));+ await tester.tap(key('swarm-avatar-photo'));+ // Resized outside the test's fake time.+ for (var i = 0; i < 100 && swarm.commands.isEmpty; i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump();+ }+ expect(uploads, hasLength(1));+ expect(swarm.commands, [+ {+ 'type': 'member.avatar',+ 'avatar': {'kind': 'upload', 'id': 'upload-1'},+ },+ ]);+ });++ testWidgets('a photo the server refuses says why, and nothing changes', (+ tester,+ ) async {+ final picked = await tester.runAsync(photo);+ await open(+ tester,+ picked: picked,+ answer: () => throw const SuperTabFailure(+ 'AVATARS_UNAVAILABLE',+ 'Uploading pictures is not set up on this server yet. Pick one of '+ 'the pictures instead.',+ statusCode: 503,+ ),+ );+ await tester.ensureVisible(key('swarm-avatar-photo'));+ await tester.tap(key('swarm-avatar-photo'));+ final error = key('swarm-profile-error');+ for (var i = 0; i < 100 && error.evaluate().isEmpty; i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 10)),+ );+ await tester.pump();+ }+ expect(+ tester.widget<Text>(error).data,+ 'Uploading pictures is not set up on this server yet. Pick one of '+ 'the pictures instead.',+ );+ expect(swarm.commands, isEmpty);+ });++ testWidgets('a phone that cannot send photos offers the pictures and '+ 'says so', (tester) async {+ await open(tester, canUpload: false);+ expect(key('swarm-avatar-photo'), findsNothing);+ expect(+ find.text('Photos can’t be sent from this phone yet. Pick a picture.'),+ findsOneWidget,+ );+ expect(key('swarm-avatar-preset-fox'), findsOneWidget);+ });++ testWidgets('a status from the presets, clearing in an hour', (tester) async {+ await open(tester);+ await tap(tester, key('swarm-status-☕'));+ expect(+ tester.widget<TextField>(key('swarm-status-text')).controller!.text,+ 'Coffee break',+ );+ await tap(tester, key('swarm-status-clears-hour'));+ final sent = clock.now();+ await tap(tester, key('swarm-status-save'));+ final command = swarm.commands.single;+ expect(command['type'], 'member.status');+ final status = command['status'] as Map<String, dynamic>;+ expect(status['text'], 'Coffee break');+ expect(status['emoji'], '☕');+ expect(+ DateTime.parse(status['until'] as String).difference(sent).inMinutes,+ 60,+ );+ });++ testWidgets('a status in their own words, then cleared', (tester) async {+ await open(tester);+ await tester.ensureVisible(key('swarm-status-text'));+ await tester.enterText(key('swarm-status-text'), 'On a train');+ await tap(tester, key('swarm-status-save'));+ expect(swarm.commands.single, {+ 'type': 'member.status',+ 'status': {'text': 'On a train'},+ });+ await tap(tester, key('swarm-status-clear'));+ expect(swarm.commands.last, {'type': 'member.status', 'status': null});+ });++ testWidgets('no words, no status to save', (tester) async {+ await open(tester);+ await tap(tester, key('swarm-status-save'));+ expect(swarm.commands, isEmpty);+ });++ testWidgets('their status shows in the editor while it lasts', (+ tester,+ ) async {+ await open(+ tester,+ extra: {+ 'status': {'text': 'At lunch', 'emoji': '🍽️', 'until': null},+ },+ );+ expect(+ tester.widget<TextField>(key('swarm-status-text')).controller!.text,+ 'At lunch',+ );+ expect(key('swarm-status-clear'), findsOneWidget);+ });++ testWidgets('a viewer sees their profile and changes nothing', (+ tester,+ ) async {+ await open(tester, role: 'viewer');+ expect(+ find.text('You have read-only access to this Swarm.'),+ findsOneWidget,+ );+ await tap(tester, key('swarm-avatar-preset-owl'));+ expect(swarm.commands, isEmpty);+ });++ testWidgets('a status that ends keeps its end when saved again', (+ tester,+ ) async {+ final until = clock.now().toUtc().add(const Duration(hours: 2));+ await open(+ tester,+ extra: {+ 'status': {+ 'text': 'Focusing',+ 'emoji': '🎯',+ 'until': until.toIso8601String(),+ },+ },+ );+ expect(key('swarm-status-clears-kept'), findsOneWidget);+ await tester.ensureVisible(key('swarm-status-text'));+ await tester.enterText(key('swarm-status-text'), 'Deep focus');+ await tap(tester, key('swarm-status-save'));+ final status = swarm.commands.single['status'] as Map<String, dynamic>;+ expect(DateTime.parse(status['until'] as String), until);+ });++ /// The text style of the one [text] on screen.+ TextStyle styleOf(WidgetTester tester, String text) =>+ tester.widget<Text>(find.text(text)).style!;++ /// The padding nearest around [finder].+ EdgeInsetsGeometry paddingAround(WidgetTester tester, Finder finder) => tester+ .widget<Padding>(+ find.ancestor(of: finder, matching: find.byType(Padding)).first,+ )+ .padding;++ group('on the design system', () {+ testWidgets('the sheet is dimmed as every sheet is, inset 16 across and '+ '16 below, with a grabber 36 by 4', (tester) async {+ await open(tester);++ expect(+ ModalRoute.of(tester.element(find.text('Your profile')))!.barrierColor,+ Colors.black54,+ );+ expect(+ tester+ .widget<Padding>(+ find.byWidgetPredicate(+ (w) => w is Padding && w.child is ListenableBuilder,+ ),+ )+ .padding,+ const EdgeInsets.fromLTRB(16, 8, 16, 16),+ );+ final grabber = find.byWidgetPredicate(+ (w) => w is Container && w.constraints?.maxWidth == 36,+ );+ expect(+ tester.getSize(+ find.descendant(of: grabber, matching: find.byType(DecoratedBox)),+ ),+ const Size(36, 4),+ );+ expect(+ tester.widget<Container>(grabber).margin,+ const EdgeInsets.only(bottom: 8),+ );+ });++ testWidgets('the title and the name are headings of 17; the status under '+ 'the name is a caption of 13', (tester) async {+ await open(tester);++ for (final text in ['Your profile', 'person-me']) {+ expect(styleOf(tester, text).fontSize, 17, reason: text);+ expect(styleOf(tester, text).fontWeight, FontWeight.w600, reason: text);+ }+ expect(styleOf(tester, 'No status').fontSize, 13);+ expect(+ paddingAround(tester, find.text('Your profile')),+ const EdgeInsets.fromLTRB(4, 0, 4, 8),+ );+ expect(+ paddingAround(tester, key('swarm-profile-face')),+ const EdgeInsets.fromLTRB(4, 8, 4, 4),+ );+ });++ testWidgets('a picture is a glyph of 24, and a choice is a caption of 13 '+ 'in a capsule padded 14 across', (tester) async {+ await open(tester);++ expect(+ tester+ .widget<Text>(+ find.descendant(+ of: key('swarm-avatar-preset-fox'),+ matching: find.text('🦊'),+ ),+ )+ .style!+ .fontSize,+ 24,+ );+ await tester.ensureVisible(key('swarm-status-clears-never'));+ expect(styleOf(tester, 'Never').fontSize, 13);+ expect(+ paddingAround(tester, find.text('Never')),+ const EdgeInsets.symmetric(horizontal: 14),+ );+ });++ testWidgets('the status field reads at 17 on the field corner of 10, and '+ 'its Clears caption is 13', (tester) async {+ await open(tester);+ await tester.ensureVisible(key('swarm-status-text'));++ final field = tester.widget<TextField>(key('swarm-status-text'));+ expect(field.style!.fontSize, 17);+ expect(+ (field.decoration!.border! as OutlineInputBorder).borderRadius,+ BorderRadius.circular(10),+ );+ expect(styleOf(tester, 'Clears').fontSize, 13);+ expect(+ paddingAround(tester, find.text('Clears')),+ const EdgeInsets.fromLTRB(4, 4, 4, 8),+ );+ });++ testWidgets('a note under a section is a caption of 13, 12 below it', (+ tester,+ ) async {+ await open(tester, role: 'viewer');++ const note = 'You have read-only access to this Swarm.';+ expect(styleOf(tester, note).fontSize, 13);+ expect(+ paddingAround(tester, find.text(note)),+ const EdgeInsets.fromLTRB(4, 12, 4, 0),+ );+ });++ testWidgets('an error is a caption of 13 in the danger ink', (+ tester,+ ) async {+ await open(+ tester,+ pick: () async => throw PlatformException(code: 'denied'),+ );+ await tester.ensureVisible(key('swarm-avatar-photo'));+ await tester.tap(key('swarm-avatar-photo'));+ await tester.pumpAndSettle();++ final error = tester.widget<Text>(key('swarm-profile-error'));+ expect(error.data, 'Could not open your photos.');+ expect(error.style!.fontSize, 13);+ expect(+ paddingAround(tester, key('swarm-profile-error')),+ const EdgeInsets.fromLTRB(4, 12, 4, 0),+ );+ });+ });++ test('a picked photo is read, and its copy on the phone deleted', () async {+ final dir = await Directory.systemTemp.createTemp('swarm-photo');+ addTearDown(() => dir.delete(recursive: true));+ final copy = File('${dir.path}/image_picker_1.jpg');+ await copy.writeAsBytes([1, 2, 3]);++ final bytes = await readPickedSwarmPhoto(XFile(copy.path));++ expect(bytes, [1, 2, 3]);+ expect(copy.existsSync(), isFalse);+ expect(await readPickedSwarmPhoto(null), isNull);+ });+}diff --git a/mobile/test/swarm/swarm_profile_test.dart b/mobile/test/swarm/swarm_profile_test.dartnew file mode 100644index 000000000..c70864615--- /dev/null+++ b/mobile/test/swarm/swarm_profile_test.dart@@ -0,0 +1,248 @@+import 'dart:typed_data';+import 'dart:ui' as ui;++import 'package:dio/dio.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/api/api_client.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_profile.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import 'swarm_fixture.dart';++/// A [width]×[height] PNG, as a photo picked from the library would be.+Future<Uint8List> picture(int width, int height) async {+ final recorder = ui.PictureRecorder();+ ui.Canvas(recorder).drawRect(+ ui.Rect.fromLTWH(0, 0, width * 1.0, height * 1.0),+ ui.Paint()..color = const ui.Color(0xFF3366CC),+ );+ final image = await recorder.endRecording().toImage(width, height);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ return bytes!.buffer.asUint8List();+}++Future<({int width, int height})> sizeOf(Uint8List png) async {+ final codec = await ui.instantiateImageCodec(png);+ final image = (await codec.getNextFrame()).image;+ return (width: image.width, height: image.height);+}++/// The person's own avatar and status, as Desktop sets them+/// (`desktop/lib/super_tabs/profile_actions.dart`): each a command of its+/// own; an uploaded photo first goes up straight from the phone.+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ late FakeSwarm swarm;+ late SwarmReader reader;+ late List<({String tabId, Uint8List png})> uploads;++ Future<SwarmProfile> rig({+ String role = 'owner',+ bool canUpload = true,+ Future<String> Function()? answer,+ }) async {+ swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(),+ 'members': [part(me, 1, person(me, role: role))],+ };+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ swarm.routes['/api/super-tabs/$tab/commands'] = (_) => {'ok': true};+ reader = SwarmReader(tabId: tab, accountId: me, request: swarm.request);+ addTearDown(reader.dispose);+ await reader.refresh();+ uploads = [];+ return SwarmProfile(+ reader: reader,+ upload: canUpload+ ? ({required tabId, required png}) async {+ uploads.add((tabId: tabId, png: png));+ return answer == null ? 'upload-1' : await answer();+ }+ : null,+ );+ }++ int reads() => swarm.paths+ .where((path) => path.startsWith('/api/super-tabs/$tab/changes'))+ .length;++ test('a status goes as the person wrote it, and the Swarm is read', () async {+ final profile = await rig();+ final until = DateTime.utc(2026, 10, 28, 12);+ expect(+ await profile.setStatus(+ SuperTabPersonStatus(text: 'Focusing', emoji: '🎯', until: until),+ ),+ isNull,+ );+ expect(swarm.commands, [+ {+ 'type': 'member.status',+ 'status': {+ 'text': 'Focusing',+ 'emoji': '🎯',+ 'until': '2026-10-28T12:00:00.000Z',+ },+ },+ ]);+ expect(reads(), 1);+ });++ test('a status in their own words, that never clears', () async {+ final profile = await rig();+ await profile.setStatus(const SuperTabPersonStatus(text: 'On a train'));+ expect(swarm.commands, [+ {+ 'type': 'member.status',+ 'status': {'text': 'On a train'},+ },+ ]);+ });++ test('clearing the status sends none', () async {+ final profile = await rig();+ await profile.setStatus(null);+ expect(swarm.commands, [+ {'type': 'member.status', 'status': null},+ ]);+ });++ test('a built-in picture, and back to the initial', () async {+ final profile = await rig();+ await profile.setAvatar(const SuperTabPresetAvatar('fox'));+ await profile.setAvatar(null);+ expect(swarm.commands, [+ {+ 'type': 'member.avatar',+ 'avatar': {'kind': 'preset', 'key': 'fox'},+ },+ {'type': 'member.avatar', 'avatar': null},+ ]);+ });++ test('a photo goes up as its middle square at 256 pixels, then becomes the '+ 'avatar', () async {+ final profile = await rig();+ expect(await profile.uploadAvatar(await picture(600, 400)), isNull);+ expect(uploads.single.tabId, tab);+ expect(await sizeOf(uploads.single.png), (width: 256, height: 256));+ expect(swarm.commands, [+ {+ 'type': 'member.avatar',+ 'avatar': {'kind': 'upload', 'id': 'upload-1'},+ },+ ]);+ expect(reads(), 1);+ });++ test('a server with uploads off says so, and nothing is set', () async {+ final profile = await rig(+ answer: () => throw const SuperTabFailure(+ 'AVATARS_UNAVAILABLE',+ 'Uploading pictures is not set up on this server yet. Pick one of the '+ 'pictures instead.',+ statusCode: 503,+ ),+ );+ expect(+ await profile.uploadAvatar(await picture(10, 10)),+ 'Uploading pictures is not set up on this server yet. Pick one of the '+ 'pictures instead.',+ );+ expect(swarm.commands, isEmpty);+ });++ test('a file that is no picture is refused before it goes up', () async {+ final profile = await rig();+ expect(+ await profile.uploadAvatar(Uint8List.fromList([1, 2, 3])),+ 'Use a PNG, JPEG or WebP picture.',+ );+ expect(uploads, isEmpty);+ });++ test('a phone that cannot send pictures offers none', () async {+ final profile = await rig(canUpload: false);+ expect(profile.canUpload, isFalse);+ expect(+ await profile.uploadAvatar(await picture(10, 10)),+ 'Pictures can’t be sent from here. Pick one of the pictures instead.',+ );+ expect(swarm.commands, isEmpty);+ });++ test('a refused command comes back as its sentence', () async {+ final profile = await rig();+ swarm.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw const SuperTabFailure(+ 'STATUS_EXPIRED',+ 'Choose a time that has not passed yet.',+ statusCode: 400,+ );+ expect(+ await profile.setStatus(+ SuperTabPersonStatus(text: 'Away', until: DateTime.utc(2020)),+ ),+ 'Choose a time that has not passed yet.',+ );+ expect(reads(), 0);+ });++ test('a viewer changes nothing', () async {+ final profile = await rig(role: 'viewer');+ expect(profile.canEdit, isFalse);+ expect(+ await profile.setAvatar(const SuperTabPresetAvatar('owl')),+ 'You have read-only access to this Swarm.',+ );+ expect(swarm.commands, isEmpty);+ });++ group('the phone\'s upload', () {+ Future<Object?> refusal(Object error) async {+ final upload = swarmAvatarUploadVia((tabId, png) async => throw error);+ try {+ await upload(tabId: tab, png: Uint8List(4));+ } catch (caught) {+ return caught;+ }+ return null;+ }++ test('answers the id the backend gave', () async {+ final upload = swarmAvatarUploadVia((tabId, png) async => 'up-$tabId');+ expect(await upload(tabId: tab, png: Uint8List(4)), 'up-$tab');+ });++ test("tells the server's refusal in its words", () async {+ final failure = await refusal(ApiException('Not set up.', status: 503));+ expect(+ failure,+ isA<SuperTabFailure>()+ .having((f) => f.message, 'message', 'Not set up.')+ .having((f) => f.statusCode, 'statusCode', 503),+ );+ });++ test('tells a lost connection in words', () async {+ final failure = await refusal(+ DioException(+ requestOptions: RequestOptions(),+ type: DioExceptionType.connectionError,+ ),+ );+ expect(+ failure,+ isA<SuperTabFailure>().having(+ (f) => f.message,+ 'message',+ 'The picture was not sent: could not reach Harness. Check your '+ 'connection and try again.',+ ),+ );+ });+ });+}diff --git a/mobile/test/swarm/swarm_profile_ways_test.dart b/mobile/test/swarm/swarm_profile_ways_test.dartnew file mode 100644index 000000000..82f8f2c5b--- /dev/null+++ b/mobile/test/swarm/swarm_profile_ways_test.dart@@ -0,0 +1,196 @@+import 'package:flutter/material.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/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++const other = 'person-tony';++/// The ways to a profile: the "You" row at the top of the menu opens one's+/// own, and a person's face in a chat opens theirs — one's own with Edit.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(groups: [groupData('g1', title: 'Fix login', number: 4)]),+ 'members': [+ part(me, 1, {+ ...person(me),+ 'avatar': {'kind': 'preset', 'key': 'fox'},+ 'status': {'text': 'Focusing', 'emoji': '🎯', 'until': null},+ }),+ part(other, 1, {+ ...person(other, role: 'collaborator'),+ 'status': {'text': 'At lunch', 'emoji': '🍽️', 'until': null},+ }),+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/groups'] = (_) => {+ 'groups': <Object>[],+ 'next': null,+ };+ fake.routes[messages] = (_) => {+ 'messages': [+ {+ 'id': 'msg-1',+ 'conversationId': 'g1',+ 'text': 'Ship it today?',+ 'sequence': 1,+ 'author': {'kind': 'person', 'id': other, 'name': '[email protected]'},+ 'createdAt': '2026-10-27T01:00:00.000Z',+ },+ {+ 'id': 'msg-2',+ 'conversationId': 'g1',+ 'text': 'Yes.',+ 'sequence': 2,+ 'author': {'kind': 'person', 'id': me, 'name': '[email protected]'},+ 'createdAt': '2026-10-27T01:01:00.000Z',+ },+ ],+ 'next': null,+ };+ return fake;+ }++ Future<void> pump(WidgetTester tester, Widget home) async {+ tester.view.physicalSize = const Size(1170, 2532);+ addTearDown(tester.view.reset);+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: home,+ ),+ );+ await frames(tester);+ }++ Finder key(String value) => find.byKey(ValueKey(value));+ Finder inside(String value, Finder finder) =>+ find.descendant(of: key(value), matching: finder);++ testWidgets('the menu starts with you, and opens your profile', (+ tester,+ ) async {+ await pump(tester, const SwarmPage());+ await tester.tap(key('swarm-menu'));+ await frames(tester);+ expect(inside('swarm-drawer-you-$tab', find.text('🦊')), findsOneWidget);+ expect(+ inside('swarm-drawer-you-$tab', find.text('🎯 Focusing')),+ findsOneWidget,+ );+ expect(+ tester.getSize(key('swarm-drawer-you-$tab')).height,+ greaterThanOrEqualTo(44),+ );+ await tester.tap(key('swarm-drawer-you-$tab'));+ await frames(tester);+ expect(find.text('Your profile'), findsOneWidget);+ });++ testWidgets("a person's face in a chat opens who they are", (tester) async {+ await pump(+ tester,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ final face = key('swarm-author-msg-1');+ expect(tester.getSize(face).width, greaterThanOrEqualTo(44));+ expect(tester.getSize(face).height, greaterThanOrEqualTo(44));+ await tester.tap(face);+ await frames(tester);+ expect(inside('swarm-person', find.text('person-tony')), findsOneWidget);+ expect(inside('swarm-person', find.text('🍽️ At lunch')), findsOneWidget);+ expect(+ inside('swarm-person', find.text('[email protected]')),+ findsOneWidget,+ );+ expect(key('swarm-person-edit'), findsNothing);+ });++ testWidgets('who they are is dimmed as every sheet is and inset 16 across '+ 'and 24 below, with the name a heading of 17, its status a body of 17 '+ 'and its email and role captions of 13', (tester) async {+ await pump(+ tester,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ await tester.tap(key('swarm-author-msg-1'));+ await frames(tester);++ expect(+ ModalRoute.of(tester.element(key('swarm-person')))!.barrierColor,+ Colors.black54,+ );+ expect(+ tester.widget<Padding>(key('swarm-person')).padding,+ const EdgeInsets.fromLTRB(16, 8, 16, 24),+ );+ final grabber = find.byWidgetPredicate(+ (w) => w is Container && w.constraints?.maxWidth == 36,+ );+ expect(+ tester.getSize(+ find.descendant(of: grabber, matching: find.byType(DecoratedBox)),+ ),+ const Size(36, 4),+ );+ expect(+ tester.widget<Container>(grabber).margin,+ const EdgeInsets.only(bottom: 16),+ );+ TextStyle styleOf(String text) =>+ tester.widget<Text>(inside('swarm-person', find.text(text))).style!;+ expect(styleOf('person-tony').fontSize, 17);+ expect(styleOf('person-tony').fontWeight, FontWeight.w600);+ expect(styleOf('🍽️ At lunch').fontSize, 17);+ for (final line in ['[email protected]', 'Collaborator']) {+ expect(styleOf(line).fontSize, 13, reason: line);+ }+ });++ testWidgets('your own face opens yours, with Edit profile', (tester) async {+ await pump(+ tester,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ await tester.tap(key('swarm-author-msg-2'));+ await frames(tester);+ expect(inside('swarm-person', find.text('🎯 Focusing')), findsOneWidget);+ await tester.tap(key('swarm-person-edit'));+ await frames(tester);+ expect(find.text('Your profile'), findsOneWidget);+ expect(key('swarm-person'), findsNothing);+ });+}++/// A second of frames, for screens whose skeletons never settle.+Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+}diff --git a/mobile/test/swarm/swarm_reactions_test.dart b/mobile/test/swarm/swarm_reactions_test.dartnew file mode 100644index 000000000..0d9480865--- /dev/null+++ b/mobile/test/swarm/swarm_reactions_test.dart@@ -0,0 +1,355 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_reactions.dart';++import 'swarm_fixture.dart';+import '../theme/sheet_shape.dart';++/// Emoji reactions on a Swarm message, as Desktop draws them (backend+/// reactions.ts): the counts under it, the reader's own marked, and the six+/// a long-press offers.+void main() {+ group('the reaction counter', () {+ SuperTabConversation g1(Map<String, dynamic> extra) =>+ SuperTabSnapshot.fromJson(+ SuperTabParts.firstLoad(+ firstLoad(+ groups: [+ {...groupData('g1', title: 'Fix login'), ...extra},+ ],+ ),+ ).state,+ ).conversation('g1')!;++ test('a conversation carries the counter its read sends', () {+ expect(g1({'reactionSeq': 7}).reactionSeq, 7);+ });++ test('a conversation nobody reacted in counts none', () {+ expect(g1(const {}).reactionSeq, 0);+ });+ });++ List<SuperTabReactionCount> counts(Map<String, List<(String, String)>> by) =>+ SuperTabReactionCount.listFromJson([+ for (final MapEntry(key: emoji, value: who) in by.entries)+ {+ 'emoji': emoji,+ 'count': who.length,+ 'by': [+ for (final (kind, id) in who) {'kind': kind, 'id': id},+ ],+ },+ ]);++ Future<void> show(WidgetTester tester, Widget child) => tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(body: Center(child: child)),+ ),+ );++ String nameOf(String kind, String id) => switch (id) {+ me => 'You',+ 'agent-lead' => 'River',+ _ => 'Ann',+ };++ Finder chip(SuperTabReactionEmoji emoji) =>+ find.byKey(ValueKey('swarm-reaction-m1-${emoji.key}'));++ group('the reaction bar', () {+ testWidgets("shows each emoji with its count, the reader's own marked", (+ tester,+ ) async {+ final semantics = tester.ensureSemantics();+ await show(+ tester,+ SwarmReactionBar(+ messageId: 'm1',+ reactions: counts({+ 'tada': [('agent', 'agent-lead'), ('person', me)],+ 'eyes': [('person', 'person-ann')],+ }),+ readerId: me,+ nameOf: nameOf,+ onReact: (_) {},+ ),+ );++ expect(+ tester.getSemantics(chip(SuperTabReactionEmoji.tada)),+ isSemantics(+ label: '🎉 2, River and You',+ isButton: true,+ isEnabled: true,+ isSelected: true,+ hasTapAction: true,+ ),+ );+ expect(+ tester.getSemantics(chip(SuperTabReactionEmoji.eyes)),+ isSemantics(+ label: '👀 1, Ann',+ isButton: true,+ isEnabled: true,+ isSelected: false,+ hasTapAction: true,+ ),+ );+ semantics.dispose();+ });++ testWidgets('a tap on a count reacts with its emoji; each is a '+ "finger's size", (tester) async {+ final picked = <SuperTabReactionEmoji>[];+ await show(+ tester,+ SwarmReactionBar(+ messageId: 'm1',+ reactions: counts({+ 'rocket': [('person', 'person-ann')],+ }),+ readerId: me,+ nameOf: nameOf,+ onReact: picked.add,+ ),+ );++ await tester.tap(chip(SuperTabReactionEmoji.rocket));++ expect(picked, [SuperTabReactionEmoji.rocket]);+ final size = tester.getSize(chip(SuperTabReactionEmoji.rocket));+ expect(size.height, greaterThanOrEqualTo(44));+ expect(size.width, greaterThanOrEqualTo(44));+ });++ testWidgets('holding a count names who gave it', (tester) async {+ await show(+ tester,+ SwarmReactionBar(+ messageId: 'm1',+ reactions: counts({+ 'heart': [('agent', 'agent-lead'), ('person', 'person-ann')],+ }),+ readerId: me,+ nameOf: nameOf,+ onReact: (_) {},+ ),+ );++ await tester.longPress(chip(SuperTabReactionEmoji.heart));+ await tester.pump();++ expect(find.text('River and Ann'), findsOneWidget);+ await tester.pumpAndSettle(const Duration(seconds: 3));+ });++ testWidgets('the bar sits 4 points under its message, and a count is '+ 'padded 8 points across, on the spacing scale', (tester) async {+ await show(+ tester,+ SwarmReactionBar(+ messageId: 'm1',+ reactions: counts({+ 'rocket': [('person', 'person-ann')],+ }),+ readerId: me,+ nameOf: nameOf,+ onReact: (_) {},+ ),+ );++ expect(+ tester+ .widget<Padding>(+ find+ .descendant(+ of: find.byType(SwarmReactionBar),+ matching: find.byType(Padding),+ )+ .first,+ )+ .padding,+ const EdgeInsets.only(top: 4),+ );+ expect(+ tester+ .widget<Container>(+ find.descendant(+ of: chip(SuperTabReactionEmoji.rocket),+ matching: find.byType(Container),+ ),+ )+ .padding,+ const EdgeInsets.symmetric(horizontal: 8),+ );+ });++ testWidgets('a message with no reactions draws nothing', (tester) async {+ await show(+ tester,+ SwarmReactionBar(+ messageId: 'm1',+ reactions: const [],+ readerId: me,+ nameOf: nameOf,+ onReact: (_) {},+ ),+ );++ expect(tester.getSize(find.byType(SwarmReactionBar)), Size.zero);+ });+ });++ group('the reaction picker', () {+ late List<String> haptics;++ setUp(() {+ haptics = [];+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method == 'HapticFeedback.vibrate') {+ haptics.add(call.arguments as String? ?? call.method);+ }+ return null;+ });+ });+ tearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, null),+ );++ Future<Future<SuperTabReactionEmoji?>> open(+ WidgetTester tester,+ List<SuperTabReactionCount> reactions,+ ) async {+ late BuildContext context;+ await show(+ tester,+ Builder(+ builder: (c) {+ context = c;+ return const SizedBox();+ },+ ),+ );+ final picked = showSwarmReactionPicker(+ context,+ reactions: reactions,+ readerId: me,+ );+ await tester.pumpAndSettle();+ expect(sheetTopRadius(tester), 12);+ return picked;+ }++ testWidgets("offers Desktop's six emoji with a light tap of the phone, "+ "each a finger's size, and answers the one picked", (tester) async {+ final picked = await open(tester, const []);++ expect(haptics, ['HapticFeedbackType.lightImpact']);+ for (final emoji in SuperTabReactionEmoji.values) {+ final option = find.byKey(ValueKey('swarm-react-${emoji.key}'));+ expect(option, findsOneWidget);+ expect(tester.getSize(option).height, greaterThanOrEqualTo(44));+ expect(tester.getSize(option).width, greaterThanOrEqualTo(44));+ }+ await tester.tap(find.byKey(const ValueKey('swarm-react-rocket')));+ await tester.pumpAndSettle();++ expect(await picked, SuperTabReactionEmoji.rocket);+ expect(find.byKey(const ValueKey('swarm-react-rocket')), findsNothing);+ });++ testWidgets('dims the page as every sheet does, and draws each emoji at '+ "an icon's size, 24 points", (tester) async {+ final picked = await open(tester, const []);++ final route = ModalRoute.of(+ tester.element(find.byKey(const ValueKey('swarm-react-rocket'))),+ )!;+ expect(route.barrierColor, Colors.black54);+ expect(+ tester.widget<Text>(find.text('🚀')).style!.fontSize,+ 24,+ reason: 'a glyph alone in a control, like AppIconSize.standalone',+ );++ await tester.tapAt(const Offset(20, 20));+ await tester.pumpAndSettle();+ expect(await picked, isNull);+ });++ testWidgets('the sheet is inset 16 across and 16 below, 8 above, with a '+ 'grabber 36 by 4', (tester) async {+ final picked = await open(tester, const []);++ expect(+ tester+ .widget<Padding>(+ find.byWidgetPredicate((w) => w is Padding && w.child is Column),+ )+ .padding,+ const EdgeInsets.fromLTRB(16, 8, 16, 16),+ );+ final grabber = find.byWidgetPredicate(+ (w) => w is Container && w.constraints?.maxWidth == 36,+ );+ expect(+ tester.getSize(+ find.descendant(of: grabber, matching: find.byType(DecoratedBox)),+ ),+ const Size(36, 4),+ );+ expect(+ tester.widget<Container>(grabber).margin,+ const EdgeInsets.only(bottom: 12),+ );++ await tester.tapAt(const Offset(20, 20));+ await tester.pumpAndSettle();+ expect(await picked, isNull);+ });++ testWidgets("marks the reader's own, and closes with none picked", (+ tester,+ ) async {+ final semantics = tester.ensureSemantics();+ final picked = await open(+ tester,+ counts({+ 'heart': [('person', me)],+ 'eyes': [('person', 'person-ann')],+ }),+ );++ expect(+ tester.getSemantics(find.byKey(const ValueKey('swarm-react-heart'))),+ isSemantics(+ label: 'heart, yours',+ isButton: true,+ isSelected: true,+ hasTapAction: true,+ ),+ );+ expect(+ tester.getSemantics(find.byKey(const ValueKey('swarm-react-eyes'))),+ isSemantics(+ label: 'eyes',+ isButton: true,+ isSelected: false,+ hasTapAction: true,+ ),+ );+ await tester.tapAt(const Offset(20, 20));+ await tester.pumpAndSettle();+ expect(await picked, isNull);+ semantics.dispose();+ });+ });+}diff --git a/mobile/test/swarm/swarm_read_marks_test.dart b/mobile/test/swarm/swarm_read_marks_test.dartnew file mode 100644index 000000000..8bf149ca0--- /dev/null+++ b/mobile/test/swarm/swarm_read_marks_test.dart@@ -0,0 +1,372 @@+import 'dart:async';+import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_read_marks.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';++import '../voice_fakes.dart' show MemoryKeyValueStore;+import 'swarm_fixture.dart';++/// How far the person has read each chat on this phone, as each Desktop+/// computer keeps it, and as the server keeps it once it can (#2131): a chat+/// is unread while its newest message is past the higher of the two marks.+/// Unread is drawn as the chat's name in bold (design system: Unread).+void main() {+ const work = 'group-work';+ const key = 'swarm_read_marks.$me.$tab';++ /// A Swarm whose first read holds the Lead's chat and a work chat at+ /// [workAt], and whose change reads answer [next] when set.+ ({+ FakeSwarm swarm,+ SwarmReader reader,+ SwarmReadMarks marks,+ MemoryKeyValueStore store,+ })+ rig({int workAt = 4, int leadAt = 2, MemoryKeyValueStore? store}) {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [groupData(work, title: 'Work', lastMessageSequence: workAt)],+ )..['groups'][0]['data']['lastMessageSequence'] = leadAt;+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ swarm.routes['/api/super-tabs/$tab/conversations/'] = (body) => {+ 'sequence': body!['sequence'],+ };+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ store ??= MemoryKeyValueStore();+ final marks = SwarmReadMarks(+ reader,+ store: store,+ saveAfter: Duration.zero,+ );+ addTearDown(() {+ marks.dispose();+ reader.dispose();+ });+ return (swarm: swarm, reader: reader, marks: marks, store: store);+ }++ SuperTabConversation chat(SwarmReader reader, String id) =>+ reader.snapshot!.conversation(id)!;++ /// A change read in which [id] moved on to [sequence].+ void moveOn(FakeSwarm swarm, String id, int sequence, {int version = 9}) =>+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part(+ id,+ version,+ groupData(id, title: 'Work', lastMessageSequence: sequence),+ ),+ ],+ );++ List<({String path, Object? sequence})> markWrites(FakeSwarm swarm) => [+ for (final call in swarm.calls)+ if (call.method == 'POST' && call.path.endsWith('/read'))+ (path: call.path, sequence: call.body?['sequence']),+ ];++ test('the first read on a phone counts what is already there as read, '+ 'and a later message makes the chat unread', () async {+ final r = rig();+ await r.reader.refresh();+ await settle();++ expect(r.marks.unread(chat(r.reader, work)), isFalse);+ expect(r.marks.unread(chat(r.reader, leadChat)), isFalse);++ moveOn(r.swarm, work, 6);+ await r.reader.refresh();+ await settle();++ expect(r.marks.unread(chat(r.reader, work)), isTrue);+ expect(r.marks.unread(chat(r.reader, leadChat)), isFalse);+ });++ test('a chat read through its newest message is read again, and the '+ 'mark goes to the server', () async {+ final r = rig();+ await r.reader.refresh();+ await settle();+ moveOn(r.swarm, work, 6);+ await r.reader.refresh();+ await settle();+ var told = 0;+ r.marks.addListener(() => told++);++ r.marks.markRead(work, 6);+ await settle();++ expect(r.marks.unread(chat(r.reader, work)), isFalse);+ expect(told, greaterThan(0));+ expect(markWrites(r.swarm), [+ (path: '/api/super-tabs/$tab/conversations/$work/read', sequence: 6),+ ]);+ });++ test('a mark no higher than the one held is neither kept nor sent', () async {+ final r = rig();+ await r.reader.refresh();+ await settle();+ r.marks.markRead(work, 6);+ await settle();+ var told = 0;+ r.marks.addListener(() => told++);++ r.marks+ ..markRead(work, 6)+ ..markRead(work, 5);+ await settle();++ expect(told, 0);+ expect(markWrites(r.swarm).map((w) => w.sequence), [6]);+ });++ test('a server without read marks refuses the send; the phone\'s own mark '+ 'still keeps the chat read, and the next mark is tried again', () async {+ final r = rig();+ r.swarm.routes.remove('/api/super-tabs/$tab/conversations/');+ await r.reader.refresh();+ await settle();+ moveOn(r.swarm, work, 6);+ await r.reader.refresh();+ await settle();++ r.marks.markRead(work, 6);+ await settle();+ expect(r.marks.unread(chat(r.reader, work)), isFalse);++ moveOn(r.swarm, work, 8, version: 10);+ await r.reader.refresh();+ await settle();+ expect(r.marks.unread(chat(r.reader, work)), isTrue);+ r.marks.markRead(work, 8);+ await settle();++ expect(r.marks.unread(chat(r.reader, work)), isFalse);+ expect(markWrites(r.swarm).map((w) => w.sequence), [6, 8]);+ });++ test("the server's mark (#2131) counts: the higher of the server's and "+ "the phone's", () async {+ final r = rig();+ await r.reader.refresh();+ await settle();+ moveOn(r.swarm, work, 9);+ await r.reader.refresh();+ await settle();+ expect(r.marks.unread(chat(r.reader, work)), isTrue);++ // Read to 9 on a Desktop computer: the server's marks say so.+ r.reader.snapshot = SuperTabSnapshot.fromJson({+ ...headData(),+ 'people': [person(me)],+ 'agents': <Object>[],+ 'conversations': [+ groupData(leadChat, lastMessageSequence: 2),+ groupData(work, lastMessageSequence: 9),+ ],+ 'readMarks': {work: 9},+ });++ expect(r.reader.snapshot!.readMarks, {work: 9});+ expect(r.marks.unread(chat(r.reader, work)), isFalse);+ });++ test("the server's marks come with the Swarm's reads, as on Desktop "+ '(#2131): a read that moves only a mark still counts', () async {+ final r = rig();+ r.swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [groupData(work, title: 'Work', lastMessageSequence: 4)],+ derived: {+ 'readMarks': {work: 4},+ },+ );+ await r.reader.refresh();+ await settle();+ expect(r.reader.snapshot!.readMarks, {work: 4});++ moveOn(r.swarm, work, 9);+ await r.reader.refresh();+ await settle();+ expect(r.marks.unread(chat(r.reader, work)), isTrue);++ // Read to 9 on a Desktop computer: the next read moves only that mark.+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c4',+ derived: {+ 'readMarks': {work: 9},+ },+ );+ await r.reader.refresh();+ await settle();+ expect(r.reader.snapshot!.readMarks, {work: 9});+ expect(r.marks.unread(chat(r.reader, work)), isFalse);+ });++ test('marks outlive the app: read back from the phone, and the first-read '+ 'rule does not apply again', () async {+ final first = rig();+ await first.reader.refresh();+ await settle();+ first.marks.markRead(work, 4);+ await settle();+ expect(jsonDecode(first.store.values[key]!), {+ 'marks': {work: 4, leadChat: 2},+ });++ // Started again later, after a message came.+ final again = rig(workAt: 7, store: first.store);+ await again.reader.refresh();+ await settle();++ expect(again.marks.unread(chat(again.reader, work)), isTrue);+ expect(again.marks.unread(chat(again.reader, leadChat)), isFalse);+ });++ test('nothing is unread until the phone has read its marks back', () async {+ final store = _SlowStore();+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [groupData(work, lastMessageSequence: 7)]);+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ final marks = SwarmReadMarks(+ reader,+ store: store,+ saveAfter: Duration.zero,+ );+ addTearDown(() {+ marks.dispose();+ reader.dispose();+ });+ await reader.refresh();+ await settle();++ expect(marks.unread(chat(reader, work)), isFalse);++ store.answer(+ jsonEncode({+ 'marks': {work: 3},+ }),+ );+ await settle();++ expect(marks.unread(chat(reader, work)), isTrue);+ });++ test('the Home kept from before is no first read: it starts no marks and '+ 'draws nothing unread', () async {+ final store = MemoryKeyValueStore();+ final swarm = FakeSwarm();+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ final marks = SwarmReadMarks(+ reader,+ store: store,+ saveAfter: Duration.zero,+ );+ addTearDown(() {+ marks.dispose();+ reader.dispose();+ });+ // The inbox draws the Home kept before any read ([SwarmInbox]).+ final kept = SwarmReader(tabId: tab, accountId: me, request: swarm.request);+ addTearDown(kept.dispose);+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [groupData(work, lastMessageSequence: 5)]);+ await kept.refresh();+ reader.snapshot = kept.snapshot;+ await settle();++ expect(store.values[key], isNull);+ expect(marks.unread(chat(reader, work)), isFalse);+ });++ test('losing access forgets the marks on the phone too', () async {+ final r = rig();+ await r.reader.refresh();+ await settle();+ r.marks.markRead(work, 4);+ await settle();+ expect(r.store.values[key], isNotNull);++ r.reader.revoke();+ await settle();++ expect(r.store.values[key], isNull);+ });++ test('marks are kept for at most a bound of chats, those the Swarm no '+ 'longer reads going first', () async {+ final store = MemoryKeyValueStore()+ ..values[key] = jsonEncode({+ 'marks': {+ for (var i = 0; i < SwarmReadMarks.kept + 5; i++) 'gone-$i': 1,+ },+ });+ final r = rig(store: store);+ await r.reader.refresh();+ await settle();+ r.marks.markRead(work, 4);+ await settle();++ final kept = (jsonDecode(store.values[key]!)['marks'] as Map).keys;+ expect(kept, hasLength(SwarmReadMarks.kept));+ expect(kept, contains(work));+ });++ test(+ "a snapshot reads the server's marks, and none from an older server",+ () {+ final state = {+ ...headData(),+ 'people': [person(me)],+ 'agents': <Object>[],+ 'conversations': [groupData(work, lastMessageSequence: 4)],+ };+ expect(+ SuperTabSnapshot.fromJson({+ ...state,+ 'readMarks': {work: 4, 'bad': 'x'},+ }).readMarks,+ {work: 4},+ );+ expect(SuperTabSnapshot.fromJson(state).readMarks, isEmpty);+ },+ );+}++/// A store whose read answers only when told.+class _SlowStore extends MemoryKeyValueStore {+ final _pending = <void Function(String?)>[];++ @override+ Future<String?> read(String key) {+ final answer = Completer<String?>();+ _pending.add(answer.complete);+ return answer.future;+ }++ void answer(String? value) {+ for (final pending in _pending) {+ pending(value);+ }+ _pending.clear();+ }+}diff --git a/mobile/test/swarm/swarm_reader_test.dart b/mobile/test/swarm/swarm_reader_test.dartnew file mode 100644index 000000000..51a48812f--- /dev/null+++ b/mobile/test/swarm/swarm_reader_test.dart@@ -0,0 +1,413 @@+import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import 'swarm_fixture.dart';++/// One Swarm as the phone keeps it current: a first load, then only what+/// changed since (docs/design/2026-10-26-swarm-state-parts.md, section 4).+void main() {+ SwarmReader reader(FakeSwarm swarm) =>+ SwarmReader(tabId: tab, accountId: me, request: swarm.request);++ test('the first read is a first load, and draws the Swarm', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [groupData('g1', title: 'Fix login', number: 7)]);+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();++ expect(r.snapshot!.name, 'Phone Swarm');+ expect(r.snapshot!.projects.single.name, 'Mobile');+ expect(r.snapshot!.conversation('g1')!.label, '#7 Fix login');+ expect(r.error, isNull);+ });++ test("each conversation's partner is kept beside the Swarm", () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ {...groupData('g1'), 'partnerId': 'person-dee'},+ groupData('g2'),+ ],+ );+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();++ expect(r.partners, {'g1': 'person-dee'});+ });++ test('later reads ask only what changed since the cursor', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(cursor: 'c1');+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c2',+ groups: [part('g2', 9, groupData('g2', title: 'New work'))],+ lastChangedAt: 200,+ );+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();+ await r.refresh();++ expect(swarm.paths, [+ '/api/super-tabs/$tab/parts',+ '/api/super-tabs/$tab/changes?cursor=c1',+ ]);+ expect(r.snapshot!.conversation('g2')!.title, 'New work');+ expect(r.lastChangedAt, 200);++ await r.refresh();+ expect(swarm.paths.last, '/api/super-tabs/$tab/changes?cursor=c2');+ });++ test('a reload answer starts again from a first load', () async {+ var loads = 0;+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) {+ loads++;+ return firstLoad(head: headData(name: loads == 1 ? 'Before' : 'After'));+ };+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();+ await r.refresh();++ expect(loads, 2);+ expect(r.snapshot!.name, 'After');+ });++ test('a change read refused for access tries a first load', () async {+ var forbidden = false;+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => forbidden+ ? throw const SuperTabFailure(+ 'FORBIDDEN',+ 'Not yours.',+ statusCode: 403,+ )+ : firstLoad();+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) =>+ throw const SuperTabFailure('FORBIDDEN', 'Not yours.', statusCode: 403);+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ forbidden = true;+ await r.refresh();++ expect(swarm.paths.last, '/api/super-tabs/$tab/parts');+ expect(r.accessRevoked, isTrue, reason: 'the first load was refused too');+ expect(+ r.snapshot,+ isNull,+ reason: 'nothing of a Swarm it left stays shown',+ );+ });++ test('a failed read keeps what was shown and says so', () async {+ var down = false;+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => down+ ? throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ )+ : changes(cursor: 'c2');+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ down = true;+ await r.refresh();++ expect(r.snapshot!.name, 'Phone Swarm');+ expect(r.error, 'Connect one of your computers to open Swarm.');+ expect(r.accessRevoked, isFalse);++ down = false;+ await r.refresh();+ expect(r.error, isNull);+ });++ test(+ 'a backend this build cannot read asks for an update and stops',+ () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ throw const SuperTabFailure(+ 'UPDATE_REQUIRED',+ 'Update Harness.',+ statusCode: 426,+ );+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();+ await r.refresh();++ expect(r.updateRequired, isTrue);+ expect(swarm.calls, hasLength(1), reason: 'no read can succeed now');+ },+ );++ test('another Swarm in the answer is never shown as this one', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(),+ 'head': part('head', 1, {...headData(), 'id': 'tab-other'}),+ };+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();++ expect(r.snapshot, isNull);+ expect(r.error, isNotNull);+ });++ test('a read that changes nothing redraws nothing', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();+ var redraws = 0;+ r.addListener(() => redraws++);++ await r.refresh();++ expect(redraws, 0);+ });++ // A change the reader cannot see (another person's private chat) moves+ // only the last-change time: Home, the drawer and Project drew the same+ // Swarm again on every such read (audit of 44d284f65, item 4).+ test('a read that moves only the last-change time redraws nothing, '+ 'and is still counted as a read', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', lastChangedAt: 250);+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();+ final shown = r.snapshot;+ var redraws = 0;+ r.addListener(() => redraws++);+ final reads = r.reads.value;++ await r.refresh();++ expect(redraws, 0);+ expect(r.lastChangedAt, 250);+ expect(r.reads.value, reads + 1);+ expect(r.snapshot, same(shown));+ });++ group('a big Swarm', () {+ /// [n] groups besides the Lead's, each with a partner.+ List<Map<String, dynamic>> work(int n, {String title = 'Work'}) => [+ for (var g = 0; g < n; g++)+ {+ ...groupData('g$g', title: '$title $g', number: g),+ 'partnerId': 'person-$g',+ },+ ];++ /// How many turns the UI's event loop took while [read] ran: none while+ /// a parse holds it.+ Future<int> turnsDuring(Future<void> Function() read) async {+ var turns = 0, counting = true;+ final counted = () async {+ while (counting) {+ await Future<void>.delayed(Duration.zero);+ if (counting) turns++;+ }+ }();+ await read();+ final during = turns;+ counting = false;+ await counted;+ return during;+ }++ // 73 to 93 ms on the owner's iPhone 14 for a 1.3 MB Swarm: several+ // frames dropped at every first load (Mira's Profile numbers).+ test('is parsed off the UI isolate at its first load', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: work(swarmParseOffThreadParts));+ final r = reader(swarm);+ addTearDown(r.dispose);+ expect(await turnsDuring(r.refresh), greaterThan(0));+ expect(+ r.snapshot!.conversations,+ hasLength(swarmParseOffThreadParts + 1),+ );+ expect(r.partners['g7'], 'person-7');+ expect(r.error, isNull);+ });++ test('is drawn again off the UI isolate when it changes', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: work(swarmParseOffThreadParts));+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c2',+ groups: [part('g3', 900, groupData('g3', title: 'Renamed'))],+ lastChangedAt: 300,+ );+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();+ var redraws = 0;+ r.addListener(() => redraws++);+ expect(await turnsDuring(r.refresh), greaterThan(0));+ expect(r.snapshot!.conversation('g3')!.title, 'Renamed');+ expect(redraws, 1);+ });++ test('of another format says so, as a small one does', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(groups: work(swarmParseOffThreadParts)),+ 'format': 3,+ };+ final r = reader(swarm);+ addTearDown(r.dispose);++ await r.refresh();++ expect(r.snapshot, isNull);+ expect(r.error, 'Update Harness to open this Swarm.');+ });++ test('a conversation read by id while it is drawn again is kept', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: work(swarmParseOffThreadParts));+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c2',+ groups: [part('g3', 900, groupData('g3', title: 'Renamed'))],+ lastChangedAt: 300,+ );+ swarm.routes['/api/super-tabs/$tab/groups/old'] = (_) => {+ 'group': part(+ 'old',+ 5,+ groupData('old', title: 'Closed', dormant: true),+ ),+ };+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ final changing = r.refresh();+ await Future<void>.delayed(Duration.zero);+ expect(await r.loadConversation('old'), isTrue);+ await changing;++ expect(r.snapshot!.conversation('old'), isNotNull);+ expect(r.snapshot!.conversation('g3')!.title, 'Renamed');+ });+ });++ test('a closed conversation is read by id when it is opened', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ swarm.routes['/api/super-tabs/$tab/groups/g-old'] = (_) => {+ 'group': part(+ 'g-old',+ 5,+ groupData('g-old', title: 'Shipped', dormant: true),+ ),+ };+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();++ expect(await r.loadConversation('g-old'), isTrue);+ expect(r.snapshot!.conversation('g-old')!.closed, isTrue);+ expect(await r.loadConversation('g-missing'), isFalse);+ });++ test("a project's closed conversations are read from the dormant list, "+ 'a page at a time', () async {+ const dormant = '/api/super-tabs/$tab/groups?dormant=1&projectId=$project';+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ swarm.routes[dormant] = (_) => {+ 'groups': [+ part('g-old', 5, groupData('g-old', title: 'Shipped', dormant: true)),+ ],+ 'next': 'page-2',+ };+ swarm.routes['$dormant&before=page-2'] = (_) => {+ 'groups': [+ part('g-older', 4, groupData('g-older', title: 'Spike', dormant: true)),+ ],+ 'next': null,+ };+ final r = reader(swarm);+ addTearDown(r.dispose);+ await r.refresh();+ expect(r.dormantLoaded(project), isFalse);++ await r.loadDormant(project);++ expect(swarm.paths.last, dormant);+ expect(r.snapshot!.conversation('g-old')!.closed, isTrue);+ expect(r.hasEarlierDormant(project), isTrue);++ await r.loadDormant(project);+ expect(swarm.paths.last, dormant, reason: 'the first page is read once');++ await r.loadDormant(project, earlier: true);++ expect(swarm.paths.last, '$dormant&before=page-2');+ expect(r.snapshot!.conversation('g-older')!.label, 'Spike');+ expect(r.hasEarlierDormant(project), isFalse);+ });++ test('while shown it reads every poll; hidden, it reads nothing', () {+ fakeAsync((async) {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2');+ final r = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ pollInterval: const Duration(seconds: 5),+ );++ r.shown = true;+ async.flushMicrotasks();+ expect(swarm.calls, hasLength(1), reason: 'shown reads at once');++ async.elapse(const Duration(seconds: 11));+ expect(swarm.calls, hasLength(3));++ r.shown = false;+ async.elapse(const Duration(minutes: 1));+ expect(swarm.calls, hasLength(3));++ r.shown = true;+ async.flushMicrotasks();+ expect(swarm.calls, hasLength(4), reason: 'shown again reads at once');+ r.dispose();+ });+ });+}diff --git a/mobile/test/swarm/swarm_request_test.dart b/mobile/test/swarm/swarm_request_test.dartnew file mode 100644index 000000000..f0e04d809--- /dev/null+++ b/mobile/test/swarm/swarm_request_test.dart@@ -0,0 +1,706 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:dio/dio.dart' show CancelToken;+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_inbox.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/ws/ws_conn.dart';++import '../viewer_app_fixture.dart';+import 'swarm_fixture.dart' show changes, firstLoad, groupData, me, tab;++/// How the phone reaches the Swarm: one of the account's own machines+/// forwards the call to the backend with its session (`super_tabs`,+/// `action: backend` in cli/src/superTabs/service.ts), as the web build does.+/// The phone holds no Swarm credential of its own.+void main() {+ Map<String, dynamic> forwarded(Object? value) => {'ok': true, 'value': value};++ test(+ 'a read goes through a connected machine and answers its value',+ () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ rig.conn('m').answers['super_tabs'] = (_) =>+ forwarded({'tabs': <Object>[], 'next': null});++ final value = await rig.app.swarmRequest('GET', '/api/super-tabs/list');++ expect(value, {'tabs': <Object>[], 'next': null});+ expect(rig.conn('m').payloadsOf('super_tabs').single, {+ 'action': 'backend',+ 'method': 'GET',+ 'path': '/api/super-tabs/list',+ });+ },+ );++ test('a command carries its body', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ rig.conn('m').answers['super_tabs'] = (_) => forwarded({'result': {}});++ await rig.app.swarmRequest(+ 'POST',+ '/api/super-tabs/t/commands',+ body: {+ 'operationId': 'op',+ 'command': {'type': 'mention.done', 'mentionId': 'x'},+ },+ );++ expect(rig.conn('m').payloadsOf('super_tabs').single['body'], {+ 'operationId': 'op',+ 'command': {'type': 'mention.done', 'mentionId': 'x'},+ });+ });++ test('a machine that is not connected is passed over', () async {+ final rig = await signedInWith({'a': [], 'b': []});+ addTearDown(rig.app.dispose);+ rig.app.connectionStatusForTest('a', ConnectionStatus.disconnected);+ await settle();+ rig.conn('b').answers['super_tabs'] = (_) => forwarded({'tabs': []});++ await rig.app.swarmRequest('GET', '/api/super-tabs/list');++ expect(rig.conn('a').payloadsOf('super_tabs'), isEmpty);+ expect(rig.conn('b').payloadsOf('super_tabs'), hasLength(1));+ });++ test('with no machine connected, it says to connect one', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ rig.app.connectionStatusForTest('m', ConnectionStatus.disconnected);+ await settle();++ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/list'),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.code,+ 'code',+ 'MACHINE_UNAVAILABLE',+ ),+ ),+ );+ expect(rig.conn('m').payloadsOf('super_tabs'), isEmpty);+ });++ test(+ "the backend's refusal arrives with its code, words and status",+ () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ rig.conn('m').answers['super_tabs'] = (_) => {+ 'error': 'NOT_FOUND',+ 'detail': 'This Swarm is unavailable.',+ 'status': 404,+ };++ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/t/parts'),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'NOT_FOUND')+ .having((f) => f.message, 'message', 'This Swarm is unavailable.')+ .having((f) => f.statusCode, 'statusCode', 404),+ ),+ );+ },+ );++ test("the machine's own refusal is a failure too, never a value", () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ rig.conn('m').answers['super_tabs'] = (_) =>+ throw refusal('OWNER_REQUIRED', detail: 'Only the owner.');++ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/list'),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'OWNER_REQUIRED')+ .having((f) => f.message, 'message', 'Only the owner.'),+ ),+ );+ });++ // Mira's run on the owner's iPhone, 2026-10-27: the phone read the+ // person's Swarm through a Team sign-in computer from 14:26:00 to 14:36:55+ // and the server refused every read, while the owner's Mac was connected+ // all along but for 14:27:24 to 14:29:06. The phone kept the Team computer+ // because it stayed connected, and moved only once that computer was+ // marked offline.+ test('a computer that refuses a read is passed over at once, and stays '+ 'passed over until it reconnects', () async {+ final rig = await signedInWith({'mac': [], 'team': []});+ addTearDown(rig.app.dispose);+ Map<String, dynamic> teamRefuses(_) => {+ 'error': 'TEAM_SESSION_LIMITED',+ 'detail': 'A team sign-in can only run Swarm agents on its own machine.',+ 'status': 403,+ };+ rig.conn('team').answers['super_tabs'] = teamRefuses;+ rig.conn('mac').answers['super_tabs'] = (_) => forwarded({'tabs': []});+ int reads(String id) => rig.conn(id).payloadsOf('super_tabs').length;++ // 14:27:24: the Mac is marked offline; the Team computer is the only one+ // up, and nothing tells whose refusal it is: no computer, for now.+ rig.app.connectionStatusForTest('mac', ConnectionStatus.disconnected);+ await settle();+ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/list'),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.code,+ 'code',+ 'MACHINE_UNAVAILABLE',+ ),+ ),+ );+ expect(reads('team'), 1);++ // 14:29:06: the Mac is back. The Team computer refuses the next read, and+ // the same read is answered through the Mac at once.+ rig.app.connectionStatusForTest('mac', ConnectionStatus.connected);+ await settle();+ expect(await rig.app.swarmRequest('GET', '/api/super-tabs/list'), {+ 'tabs': <Object>[],+ });+ expect(reads('team'), 2);+ expect(reads('mac'), 1);++ // Until 14:36:39 every read goes through the Mac alone.+ for (var i = 0; i < 3; i++) {+ await rig.app.swarmRequest('GET', '/api/super-tabs/list');+ }+ expect(reads('team'), 2);+ expect(reads('mac'), 4);++ // 14:36:39: the Team computer drops and comes back; with the Mac away it+ // is asked again.+ rig.app.connectionStatusForTest('team', ConnectionStatus.disconnected);+ rig.app.connectionStatusForTest('team', ConnectionStatus.connected);+ rig.app.connectionStatusForTest('mac', ConnectionStatus.disconnected);+ rig.conn('team').answers['super_tabs'] = (_) => forwarded({'tabs': []});+ await settle();+ await rig.app.swarmRequest('GET', '/api/super-tabs/list');+ expect(reads('team'), 3);+ });++ // Mira's run of ac7ce77 on the owner's iPhone, 2026-10-27: at 15:06:19 the+ // Mac was marked offline and the read went to the Team computer, whose+ // refusal Swarm showed from 15:06:23. The Mac was back at 15:06:27, but+ // Swarm stayed on the refusal until its normal read at 15:06:41: neither+ // the quick retry nor the computer list's re-read had started.+ test('a refusal from the only computer up, with the Mac away, is no '+ 'computer: the list is read again and Swarm retries soon', () async {+ final rig = await signedInWith({'mac': [], 'team': []});+ addTearDown(rig.app.dispose);+ var listed = 0;+ rig.api.onMachines = () async {+ listed++;+ return [remoteMachine('mac'), remoteMachine('team')];+ };+ rig.conn('team').answers['super_tabs'] = (_) => {+ 'error': 'TEAM_SESSION_LIMITED',+ 'detail': 'A team sign-in can only run Swarm agents on its own machine.',+ 'status': 403,+ };+ // The list, with no Swarm yet; then the invitations, with none.+ rig.conn('mac').answers['super_tabs'] = (payload) =>+ payload['path'] == '/api/super-tabs/list'+ ? forwarded({'tabs': <Object>[], 'next': null})+ : forwarded(<Object>[]);+ int reads(String id) => rig.conn(id).payloadsOf('super_tabs').length;+ final inbox = SwarmInbox(accountId: 'u', request: rig.app.swarmRequest);+ addTearDown(inbox.dispose);++ // 15:06:19: the Mac is marked offline; the read goes to the Team+ // computer, which refuses it.+ rig.app.connectionStatusForTest('mac', ConnectionStatus.disconnected);+ await settle();+ final before = listed;+ await inbox.refresh();+ await settle();++ expect(reads('team'), 1);+ expect(inbox.noComputer, isTrue, reason: 'the quick retry is on');+ expect(inbox.error, 'Connect one of your computers to open Swarm.');+ expect(listed, before + 1, reason: 'the computer list is read again');++ // 15:06:27: the Mac is back. The next read, the quick retry's, is+ // refused by the Team computer and answered through the Mac at once.+ rig.app.connectionStatusForTest('mac', ConnectionStatus.connected);+ await settle();+ await inbox.refresh();++ expect(inbox.loaded, isTrue);+ expect(inbox.error, isNull);+ expect(inbox.noComputer, isFalse);+ expect(reads('team'), 2);+ expect(reads('mac'), greaterThan(0));+ });++ test('a refusal from the only computer up waits for one on its way back, '+ 'and is answered through it', () async {+ final rig = await signedInWith({'mac': [], 'team': []});+ addTearDown(rig.app.dispose);+ rig.conn('team').answers['super_tabs'] = (_) => {+ 'error': 'TEAM_SESSION_LIMITED',+ 'detail': 'A team sign-in can only run Swarm agents on its own machine.',+ 'status': 403,+ };+ rig.conn('mac').answers['super_tabs'] = (_) => forwarded({'tabs': []});+ rig.app.connectionStatusForTest('mac', ConnectionStatus.reconnecting);+ await settle();++ Object? value;+ final read = rig.app+ .swarmRequest('GET', '/api/super-tabs/list')+ .then((v) => value = v);+ await settle();+ expect(rig.conn('team').payloadsOf('super_tabs'), hasLength(1));+ expect(value, isNull, reason: 'waiting for the Mac');++ rig.app.connectionStatusForTest('mac', ConnectionStatus.connected);+ await read;++ expect(value, {'tabs': <Object>[]});+ await rig.app.swarmRequest('GET', '/api/super-tabs/list');+ expect(+ rig.conn('team').payloadsOf('super_tabs'),+ hasLength(1),+ reason: 'the Team computer is passed over',+ );+ });++ test('a refusal that says the person lost the Swarm is never taken for no '+ 'computer: what was read of it must go', () async {+ final rig = await signedInWith({'mac': [], 'team': []});+ addTearDown(rig.app.dispose);+ rig.conn('team').answers['super_tabs'] = (_) => {+ 'error': 'NOT_FOUND',+ 'detail': 'This Swarm is unavailable.',+ 'status': 404,+ };+ rig.app.connectionStatusForTest('mac', ConnectionStatus.disconnected);+ await settle();++ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/t/parts'),+ throwsA(+ isA<SuperTabFailure>().having((f) => f.code, 'code', 'NOT_FOUND'),+ ),+ );+ });++ test("the only computer of the account refusing: its refusal is the read's "+ 'own, as it was', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ rig.conn('m').answers['super_tabs'] = (_) => {+ 'error': 'SWARM_PAUSED',+ 'detail': 'This Swarm is paused.',+ 'status': 409,+ };++ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/list'),+ throwsA(+ isA<SuperTabFailure>().having((f) => f.code, 'code', 'SWARM_PAUSED'),+ ),+ );+ });++ // Mira's clean repeat, 14:41:00 to 14:41:37: both computers connected the+ // whole time, the phone reading through the Team computer, and every read+ // refused until the kept computer was cleared by hand.+ test('a kept computer that refuses while it stays connected is left for '+ 'one that answers, in the same read', () async {+ // The Team computer sorts first, so it is the one kept from the start.+ final rig = await signedInWith({'a-team': [], 'b-mac': []});+ addTearDown(rig.app.dispose);+ rig.conn('a-team').answers['super_tabs'] = (_) => {+ 'error': 'TEAM_SESSION_LIMITED',+ 'detail': 'A team sign-in can only run Swarm agents on its own machine.',+ 'status': 403,+ };+ rig.conn('b-mac').answers['super_tabs'] = (_) => forwarded({'tabs': []});++ for (var i = 0; i < 3; i++) {+ expect(await rig.app.swarmRequest('GET', '/api/super-tabs/list'), {+ 'tabs': <Object>[],+ });+ }++ expect(rig.conn('a-team').payloadsOf('super_tabs'), hasLength(1));+ expect(rig.conn('b-mac').payloadsOf('super_tabs'), hasLength(3));+ });++ test(+ "a refusal every computer gives is the read's own, and passes over none",+ () async {+ final rig = await signedInWith({'a': [], 'b': []});+ addTearDown(rig.app.dispose);+ Map<String, dynamic> left(_) => {+ 'error': 'FORBIDDEN',+ 'detail': 'You are not in this Swarm.',+ 'status': 403,+ };+ rig.conn('a').answers['super_tabs'] = left;+ rig.conn('b').answers['super_tabs'] = left;++ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/t/parts'),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'FORBIDDEN')+ .having((f) => f.statusCode, 'statusCode', 403),+ ),+ );++ rig.conn('a').answers['super_tabs'] = (_) => forwarded({'tabs': []});+ await rig.app.swarmRequest('GET', '/api/super-tabs/list');+ expect(rig.conn('a').payloadsOf('super_tabs'), hasLength(2));+ },+ );++ // Mira's run on the owner's iPhone, 2026-10-27: Swarm said "Connect one of+ // your computers" for 10 to 25 seconds mid-session while the computer+ // stayed connected — its socket was redialling, and the read gave up at+ // once.+ test('a read while the only computer reconnects waits for it, and goes '+ 'through once it is back', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ rig.conn('m').answers['super_tabs'] = (_) => forwarded({'tabs': []});+ rig.app.connectionStatusForTest('m', ConnectionStatus.reconnecting);+ await settle();++ Object? value;+ final read = rig.app+ .swarmRequest('GET', '/api/super-tabs/list')+ .then((v) => value = v);+ await settle();+ expect(value, isNull);+ expect(rig.conn('m').payloadsOf('super_tabs'), isEmpty);++ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);+ await read;++ expect(value, {'tabs': <Object>[]});+ });++ test('a computer still away after the wait: no computer', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ rig.app.swarmReconnectWait = const Duration(milliseconds: 50);+ rig.app.connectionStatusForTest('m', ConnectionStatus.reconnecting);+ await settle();++ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/list'),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.code,+ 'code',+ 'MACHINE_UNAVAILABLE',+ ),+ ),+ );+ });++ test('a read lost on the way is asked again through another computer, '+ 'quietly', () async {+ final rig = await signedInWith({'a': [], 'b': []});+ addTearDown(rig.app.dispose);+ rig.conn('a').answers['super_tabs'] = (_) =>+ throw const WsRequestTimeout('super_tabs');+ rig.conn('b').answers['super_tabs'] = (_) => forwarded({'tabs': []});++ expect(await rig.app.swarmRequest('GET', '/api/super-tabs/list'), {+ 'tabs': <Object>[],+ });+ expect(rig.conn('a').payloadsOf('super_tabs'), hasLength(1));+ expect(rig.conn('b').payloadsOf('super_tabs'), hasLength(1));+ });++ // The owner's iPhone, 2026-10-27: after a restart Swarm said "Connect one+ // of your computers" for minutes with a computer online again, and every+ // read failed until the computer list was refreshed by hand.+ test('with no computer up, a read asks for the computer list again: '+ 'offline at launch, then online', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ var status = 'offline', listed = 0;+ rig.api.onMachines = () async {+ listed++;+ return [remoteMachine('m', status: status)];+ };+ await rig.app.refreshMachines();+ rig.app.connectionStatusForTest('m', ConnectionStatus.disconnected);+ await settle();+ rig.conn('m').answers['super_tabs'] = (_) => forwarded({'tabs': []});+ final before = listed;++ status = 'online';+ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/list'),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.code,+ 'code',+ 'MACHINE_UNAVAILABLE',+ ),+ ),+ );+ await settle();+ expect(listed, before + 1);++ // The list says it is up; its socket comes back, and Swarm reads.+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);+ await settle();+ expect(await rig.app.swarmRequest('GET', '/api/super-tabs/list'), {+ 'tabs': <Object>[],+ });+ });++ test('reads failing one after another ask for the list once in a while, '+ 'not each time', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ var listed = 0;+ rig.api.onMachines = () async {+ listed++;+ return [remoteMachine('m', status: 'offline')];+ };+ rig.app.connectionStatusForTest('m', ConnectionStatus.disconnected);+ await settle();++ for (var i = 0; i < 4; i++) {+ await rig.app+ .swarmRequest('GET', '/api/super-tabs/list')+ .catchError((Object _) => null);+ await settle();+ }++ expect(listed, 1);+ });++ Map<String, dynamic> teamRefuses(_) => {+ 'error': 'TEAM_SESSION_LIMITED',+ 'detail': 'A team sign-in can only run Swarm agents on its own machine.',+ 'status': 403,+ };+ Map<String, dynamic> left(_) => {+ 'error': 'FORBIDDEN',+ 'detail': 'You are not in this Swarm.',+ 'status': 403,+ };++ // Review of #1802 at bd73842: the person's Mac said they left the Swarm,+ // a Team computer refused for its own reason, and the Team computer's+ // refusal was what the screen got. The Mac was passed over for it, and+ // what was read of the Swarm stayed.+ test("a computer's word that the person lost the Swarm stands over another "+ "computer's refusal of its own, and passes neither over", () async {+ final rig = await signedInWith({'a-mac': [], 'b-team': []});+ addTearDown(rig.app.dispose);+ rig.conn('a-mac').answers['super_tabs'] = left;+ rig.conn('b-team').answers['super_tabs'] = teamRefuses;++ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/t/parts'),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'FORBIDDEN')+ .having((f) => f.statusCode, 'statusCode', 403),+ ),+ );++ rig.conn('a-mac').answers['super_tabs'] = (_) => forwarded({'tabs': []});+ await rig.app.swarmRequest('GET', '/api/super-tabs/list');+ expect(rig.conn('a-mac').payloadsOf('super_tabs'), hasLength(2));+ expect(rig.conn('b-team').payloadsOf('super_tabs'), hasLength(1));+ });++ test('what was read of a Swarm the person lost goes, though a Team '+ 'computer refuses for its own reason', () async {+ // The Mac sorts first: the Swarm is read through it.+ final rig = await signedInWith({'a-mac': [], 'b-team': []});+ addTearDown(rig.app.dispose);+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ var member = true;+ rig.conn('a-mac').answers['super_tabs'] = (payload) {+ if (!member) return left(payload);+ final path = payload['path'] as String;+ if (path.startsWith(messages)) {+ return forwarded({+ 'messages': [+ {+ 'id': 'm1',+ 'conversationId': 'g1',+ 'text': 'The private plan',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},+ 'createdAt': '2026-10-27T01:00:00.000Z',+ },+ ],+ 'next': null,+ });+ }+ if (path.contains('/changes')) return forwarded(changes(cursor: 'c2'));+ return forwarded(firstLoad(groups: [groupData('g1')]));+ };+ rig.conn('b-team').answers['super_tabs'] = teamRefuses;+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: rig.app.swarmRequest,+ );+ addTearDown(reader.dispose);+ await reader.refresh();+ final conversation = SwarmConversation(reader, 'g1');+ addTearDown(conversation.dispose);+ await conversation.load();+ expect(reader.snapshot, isNotNull);+ expect(conversation.messages.single.text, 'The private plan');++ member = false;+ await conversation.load();+ await reader.refresh();++ expect(conversation.messages, isEmpty);+ expect(reader.accessRevoked, isTrue);+ expect(reader.snapshot, isNull);+ });++ // Review of #1802 at bd73842: with computers A, B and C, A and B refusing+ // the same way, C was never asked — in this read or any after.+ test('two computers refusing the same way leave the third to answer, under '+ 'one receipt, and it is asked first after', () async {+ final rig = await signedInWith({'a': [], 'b': [], 'c': []});+ addTearDown(rig.app.dispose);+ rig.conn('a').answers['super_tabs'] = teamRefuses;+ rig.conn('b').answers['super_tabs'] = teamRefuses;+ rig.conn('c').answers['super_tabs'] = (_) => forwarded({'result': {}});++ final value = await rig.app.swarmRequest(+ 'POST',+ '/api/super-tabs/t/commands',+ body: {+ 'operationId': 'op',+ 'command': {'type': 'mention.done', 'mentionId': 'x'},+ },+ );++ expect(value, {'result': <String, dynamic>{}});+ for (final id in ['a', 'b', 'c']) {+ expect(+ rig.conn(id).payloadsOf('super_tabs').single['body']['operationId'],+ 'op',+ );+ }+ await rig.app.swarmRequest('GET', '/api/super-tabs/list');+ expect(rig.conn('a').payloadsOf('super_tabs'), hasLength(1));+ expect(rig.conn('b').payloadsOf('super_tabs'), hasLength(1));+ expect(rig.conn('c').payloadsOf('super_tabs'), hasLength(2));+ });++ test('a read asks at most five computers', () async {+ final ids = ['a', 'b', 'c', 'd', 'e', 'f'];+ final rig = await signedInWith({for (final id in ids) id: []});+ addTearDown(rig.app.dispose);+ for (final id in ids) {+ rig.conn(id).answers['super_tabs'] = teamRefuses;+ }++ await expectLater(+ rig.app.swarmRequest('GET', '/api/super-tabs/list'),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.code,+ 'code',+ 'TEAM_SESSION_LIMITED',+ ),+ ),+ );+ final asked = [+ for (final id in ids) rig.conn(id).payloadsOf('super_tabs').length,+ ];+ expect(asked, [1, 1, 1, 1, 1, 0]);+ });++ test('an answer that lands after sign-out is dropped', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ final answer = Completer<Map<String, dynamic>>();+ rig.conn('m').answers['super_tabs'] = (_) => answer.future;++ final read = rig.app.swarmRequest('GET', '/api/super-tabs/list');+ await settle();+ await rig.app.logout();+ answer.complete(forwarded({'tabs': []}));++ await expectLater(+ read,+ throwsA(+ isA<SuperTabFailure>().having((f) => f.code, 'code', 'ACCOUNT_CHANGED'),+ ),+ );+ });++ group('a chat file', () {+ Future<Map<String, dynamic>> upload(ViewerRig rig) => rig.app.swarmUpload(+ tabId: 't',+ conversationId: 'g1',+ name: 'shot.jpg',+ mime: 'image/jpeg',+ bytes: Uint8List(1),+ cancel: CancelToken(),+ onProgress: (_) {},+ );++ test('goes straight to the backend, through no machine', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);++ final answer = await upload(rig);++ expect(answer, {+ 'attachment': {'id': 'att'},+ });+ expect(rig.api.swarmUploads, ['t/g1/shot.jpg']);+ expect(rig.conn('m').payloadsOf('super_tabs'), isEmpty);+ });++ test('an answer that lands after sign-out is dropped', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ final answer = Completer<Map<String, dynamic>>();+ rig.api.onSwarmUpload = () => answer.future;++ final sending = upload(rig);+ await settle();+ await rig.app.logout();+ answer.complete({'attachment': <String, dynamic>{}});++ await expectLater(+ sending,+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.code,+ 'code',+ 'ACCOUNT_CHANGED',+ ),+ ),+ );+ });+ });+}diff --git a/mobile/test/swarm/swarm_row_test.dart b/mobile/test/swarm/swarm_row_test.dartnew file mode 100644index 000000000..43b086b36--- /dev/null+++ b/mobile/test/swarm/swarm_row_test.dart@@ -0,0 +1,77 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/shared/theme/app_space.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/shared/theme/app_type.dart';+import 'package:harness_mobile/swarm/swarm_row.dart';++/// A row of a Swarm card draws with the design system's roles and spacing, not+/// numbers of its own: the title is the control role, the line under it the+/// caption, and the row keeps a thumb's height.+void main() {+ Future<void> show(WidgetTester tester, Widget child) => tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(body: Center(child: child)),+ ),+ );++ /// The style the row's title is drawn in.+ TextStyle titleStyle(WidgetTester tester) {+ final title = tester.widget<RichText>(+ find.byWidgetPredicate(+ (w) => w is RichText && w.text.toPlainText().contains('Fix login'),+ ),+ );+ return (title.text as TextSpan).style!;+ }++ testWidgets('the title is the control role: 17 points, medium', (+ tester,+ ) async {+ await show(tester, SwarmRow(title: 'Fix login', onTap: () {}));++ final style = titleStyle(tester);+ expect(style.fontSize, AppType.bodySize);+ expect(style.fontWeight, FontWeight.w500);+ expect(style.height, 1.3);+ });++ testWidgets('the line under the title is the caption role', (tester) async {+ await show(+ tester,+ SwarmRow(+ title: 'Fix login',+ detail: SwarmRow.line('Nova is working'),+ onTap: () {},+ ),+ );++ final style = tester.widget<Text>(find.text('Nova is working')).style!;+ expect(style.fontSize, AppType.captionSize);+ expect(style.height, 1.35);+ });++ testWidgets('the row is padded 16 across and 12 down, on the spacing scale', (+ tester,+ ) async {+ await show(tester, SwarmRow(title: 'Fix login', onTap: () {}));++ final padding = tester.widget<Padding>(+ find.byWidgetPredicate((w) => w is Padding && w.child is Row),+ );+ expect(+ padding.padding,+ const EdgeInsets.symmetric(horizontal: AppSpace.l, vertical: AppSpace.m),+ );+ });++ testWidgets("a row never draws under a thumb's 56 points", (tester) async {+ await show(tester, SwarmRow(title: 'Fix login', onTap: () {}));++ expect(+ tester.getSize(find.byType(SwarmRow)).height,+ greaterThanOrEqualTo(SwarmRow.height),+ );+ });+}diff --git a/mobile/test/swarm/swarm_screens_test.dart b/mobile/test/swarm/swarm_screens_test.dartnew file mode 100644index 000000000..bc08247b3--- /dev/null+++ b/mobile/test/swarm/swarm_screens_test.dart@@ -0,0 +1,1108 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/widgets/skeleton.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_mark.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_project_page.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';+import '../theme/sheet_shape.dart';++/// Half a second of frames, for a screen that cannot settle.+Future<void> frames(WidgetTester tester) async {+ for (var i = 0; i < 5; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+}++/// The [SwarmHost] a test's app is under.+SwarmHost host(WidgetTester tester) =>+ tester.widget<SwarmScope>(find.byType(SwarmScope)).notifier!;++/// Swarm's screens on the phone, over a scripted backend: what needs the+/// person first, a decision answered with one tap and Undo, a project's+/// conversations in order, and a post with a mention.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const dormant = '/api/super-tabs/$tab/groups?dormant=1&projectId=$project';++ /// One Swarm, project Mobile: work g1 (Nova needs the person), someone+ /// else's private chat, and one open decision and tag. Its closed work,+ /// g-old and older g-spike, is in no first load: the dormant list has it.+ FakeSwarm backend({String role = 'owner'}) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ const derived = {'decisionsWaiting': 1, 'mentionsWaiting': 1};+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ derived: derived,+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ number: 4,+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'needs_human',+ lastMessageSequence: 9,+ ),+ groupData('g-busy', title: 'Sync', lastMessageSequence: 20),+ groupData(+ 'g-private',+ title: 'Their chat',+ audience: ['person-other', 'person-third'],+ ),+ groupData('g-pm', title: 'me', audience: [me]),+ ],+ ),+ 'members': [part(me, 1, person(me, role: role))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ final oldWork = part(+ 'g-old',+ 7,+ groupData('g-old', title: 'Old work', dormant: true),+ );+ fake.routes[dormant] = (_) => {+ 'groups': [oldWork],+ 'next': 'page-2',+ };+ fake.routes['$dormant&before=page-2'] = (_) => {+ 'groups': [+ part('g-spike', 6, groupData('g-spike', title: 'Spike', dormant: true)),+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/groups/g-old'] = (_) => {+ 'group': oldWork,+ };+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'askerName': 'River',+ 'question': 'Ship it behind a flag?',+ 'options': ['Yes', 'No'],+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [+ {+ 'id': 'm1',+ 'projectName': 'Mobile',+ 'conversationId': 'g1',+ 'conversationTitle': 'Fix login',+ 'messageId': 'msg-1',+ 'leadName': 'River',+ 'text': 'Can you check the copy?',+ },+ ],+ };+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => {+ 'result': <String, dynamic>{},+ };+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =+ (_) => {+ 'messages': [+ {+ 'id': 'msg-lead-1',+ 'conversationId': leadChat,+ 'text': 'Morning: Fix login waits on you.',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},+ 'createdAt': '2026-10-27T00:30:00.000Z',+ },+ ],+ 'next': null,+ };+ fake.routes[messages] = (_) => {+ 'messages': [+ {+ 'id': 'msg-1',+ 'conversationId': 'g1',+ 'text': 'Which name should the flag have?',+ 'sequence': 9,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ 'createdAt': '2026-10-27T01:00:00.000Z',+ },+ ],+ 'next': null,+ };+ return fake;+ }++ /// [home] under a signed-in shell's Swarm, with Swarm turned on.+ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake,+ Widget home, {+ void Function(String, String)? openAgent,+ bool on = true,+ bool settle = true,+ }) async {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {if (on) PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(+ notifier: host,+ child: openAgent == null+ ? child!+ : PhoneShellScope(+ onMachineLinked: (_) {},+ onOpenAgent: openAgent,+ child: child!,+ ),+ ),+ home: home,+ ),+ );+ // A skeleton breathes for as long as it shows: nothing settles under it.+ settle ? await tester.pumpAndSettle() : await frames(tester);+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ /// [path] answers only once the returned gate is opened.+ Completer<void> hold(FakeSwarm fake, String path) {+ final gate = Completer<void>();+ final answer = fake.routes[path]!;+ fake.routes[path] = (body) async {+ await gate.future;+ return answer(body);+ };+ return gate;+ }++ /// The change reads asked so far.+ int changeReads(FakeSwarm fake) => fake.paths+ .where((path) => path.startsWith('/api/super-tabs/$tab/changes'))+ .length;++ group('the Swarm page', () {+ testWidgets('what needs the person comes first, then its projects', (+ tester,+ ) async {+ // An iPhone's screen: all of Home at once.+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ await pump(tester, backend(), const SwarmPage());++ // The open decision says who asks and where in one line.+ final asks = find.textContaining('River asks you', findRichText: true);+ expect(asks, findsOneWidget);+ expect(find.text('River tagged you'), findsOneWidget);+ expect(find.text('Nova needs you'), findsOneWidget);+ expect(+ tester.getTopLeft(asks).dy,+ lessThan(tester.getTopLeft(key('swarm-project-$tab-$project')).dy),+ );+ expect(+ find.text('Projects'),+ findsOneWidget,+ reason: 'one Swarm: its projects, not its name',+ );++ await tester.tap(find.text('River tagged you'));+ await tester.pumpAndSettle();+ expect(+ find.text('Open chat'),+ findsOneWidget,+ reason: 'the Naming System: a Swarm chat, not a conversation',+ );+ final row = key('swarm-project-$tab-$project');+ expect(+ find.descendant(of: row, matching: find.text('@1')),+ findsOneWidget,+ reason: "River's tag, waiting in it",+ );+ expect(+ find.descendant(of: row, matching: find.textContaining('waiting')),+ findsNothing,+ reason: 'no team line (Team at a glance is gone, as on the desktop)',+ );+ });++ testWidgets('an answer is held for Undo, and undone is never sent', (+ tester,+ ) async {+ final fake = backend();+ await pump(tester, fake, const SwarmPage());++ await tester.tap(key('swarm-option-d1-0'));+ await tester.pump();+ expect(find.text('Sending “Yes”'), findsOneWidget);++ await tester.tap(key('swarm-undo-d1'));+ await tester.pump(const Duration(seconds: 5));+ expect(fake.commands, isEmpty);+ expect(key('swarm-option-d1-0'), findsOneWidget);+ });++ testWidgets(+ 'an answer dropped before it was sent says so, and offers the options '+ 'again',+ (tester) async {+ final fake = backend();+ final host = await pump(tester, fake, const SwarmPage());+ await tester.tap(key('swarm-option-d1-0'));+ await tester.pump();+ expect(find.text('Sending “Yes”'), findsOneWidget);++ // Read again in full within the Undo window: what waits for the+ // person is read again, and that read is slow to answer.+ const decisions = '/api/super-tabs/$tab/decisions?state=open';+ final open = fake.routes[decisions]!(null);+ final stalled = Completer<Object?>();+ fake.routes[decisions] = (_) => stalled.future;+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ await host.session!.inbox.refresh();+ await tester.pump();+ expect(find.text('Sending “Yes”'), findsNothing);++ stalled.complete(open);+ await tester.pump(const Duration(seconds: 5));+ await tester.pumpAndSettle();++ expect(fake.commands, isEmpty);+ expect(find.text('Not sent, choose again.'), findsOneWidget);+ expect(key('swarm-option-d1-0'), findsOneWidget);++ await tester.tap(key('swarm-option-d1-1'));+ await tester.pump();+ expect(find.text('Not sent, choose again.'), findsNothing);+ expect(find.text('Sending “No”'), findsOneWidget);+ await tester.tap(key('swarm-undo-d1'));+ await tester.pump();+ },+ );++ testWidgets('one tap answers once the Undo window has passed', (+ tester,+ ) async {+ final fake = backend();+ await pump(tester, fake, const SwarmPage());++ await tester.tap(key('swarm-option-d1-1'));+ await tester.pump(const Duration(seconds: 2));+ expect(fake.commands, isEmpty);+ await tester.pump(const Duration(seconds: 2));+ await tester.pumpAndSettle();++ expect(fake.commands.single, {+ 'type': 'decision.answer',+ 'decisionId': 'd1',+ 'choice': 1,+ });+ });++ testWidgets(+ 'an answer not confirmed offers only to send the same one again',+ (tester) async {+ final fake = backend();+ var lost = true;+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => lost+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : {'result': <String, dynamic>{}};+ await pump(tester, fake, const SwarmPage());++ await tester.tap(key('swarm-option-d1-1'));+ await tester.pump(const Duration(seconds: 4));+ await tester.pumpAndSettle();++ expect(key('swarm-option-d1-0'), findsNothing);+ expect(key('swarm-option-d1-1'), findsNothing);+ expect(find.text('“No” is not confirmed.'), findsOneWidget);++ lost = false;+ await tester.tap(key('swarm-resend-d1'));+ await tester.pumpAndSettle();++ expect([for (final c in fake.commands) c['choice']], [1, 1]);+ final operations = {+ for (final call in fake.calls)+ if (call.method == 'POST') call.body!['operationId'],+ };+ expect(operations, hasLength(1));+ },+ );++ testWidgets('a tag is marked done from its row', (tester) async {+ final fake = backend();+ await pump(tester, fake, const SwarmPage());+ await tester.tap(key('swarm-need-row-mention:m1'));+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-done-m1'));+ await tester.pumpAndSettle();++ expect(fake.commands.single, {'type': 'mention.done', 'mentionId': 'm1'});+ });++ testWidgets('Done says so at once, and the tag row goes once confirmed', (+ tester,+ ) async {+ final fake = backend();+ await pump(tester, fake, const SwarmPage());+ final confirmed = Completer<Object?>();+ fake.routes['/api/super-tabs/$tab/commands'] = (_) => confirmed.future;+ await tester.tap(key('swarm-need-row-mention:m1'));+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-done-m1'));+ await tester.pump();++ expect(find.text('Done…'), findsOneWidget);+ final tag = find.textContaining('River tagged you', findRichText: true);+ expect(tag, findsOneWidget);++ confirmed.complete({'result': <String, dynamic>{}});+ await tester.pumpAndSettle();++ expect(tag, findsNothing);+ });++ testWidgets('a Done that fails says so on its row', (tester) async {+ final fake = backend();+ await pump(tester, fake, const SwarmPage());+ fake.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');+ await tester.tap(key('swarm-need-row-mention:m1'));+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-done-m1'));+ await tester.pumpAndSettle();++ expect(+ find.textContaining('Not marked done. Try again.'),+ findsOneWidget,+ );+ expect(+ find.textContaining('River tagged you', findRichText: true),+ findsOneWidget,+ );+ expect(key('swarm-done-m1'), findsOneWidget);+ });++ testWidgets('a need opens the conversation it was asked in', (+ tester,+ ) async {+ await pump(tester, backend(), const SwarmPage());+ await tester.tap(find.text('Nova needs you'));+ await tester.pumpAndSettle();+ expect(+ find.byType(SwarmConversationPage),+ findsNothing,+ reason: 'the first tap opens it on Home, where another was open',+ );++ // Open, it says who asks and where in one line, and that opens it.+ await tester.tap(+ find.textContaining('Nova needs you', findRichText: true),+ );+ await tester.pumpAndSettle();++ expect(find.byType(SwarmConversationPage), findsOneWidget);+ expect(find.text('Which name should the flag have?'), findsOneWidget);+ });++ testWidgets('with Swarm off, says where to turn it on', (tester) async {+ await pump(tester, backend(), const SwarmPage(), on: false);++ expect(key('swarm-unavailable'), findsOneWidget);+ });+ });++ group('a project', () {+ const page = SwarmProjectPage(swarmId: tab, projectId: project);++ /// The scrollable of the project's sheet, not the chat's under it.+ Finder sheetList() => find+ .descendant(+ of: find.byType(SwarmProjectSheet),+ matching: find.byType(Scrollable),+ )+ .first;++ /// The project's work and team, from its menu's status row.+ Future<void> openSheet(WidgetTester tester) async {+ await tester.tap(key('swarm-project-menu'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-project-menu-status'));+ await tester.pumpAndSettle();+ }++ testWidgets(+ 'an agent offers Open terminal with its actual machine and harness',+ (tester) async {+ final opened = <(String, String)>[];+ await pump(+ tester,+ backend(),+ page,+ openAgent: (m, a) => opened.add((m, a)),+ );+ await openSheet(tester);+ await tester.tap(key('swarm-sheet-team'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-open-terminal-agent-builder'));+ expect(opened, [('mac-1', 'harness-agent-builder')]);+ },+ );++ testWidgets('opens on its project chat, under its header', (tester) async {+ await pump(tester, backend(), page);+ await tester.pumpAndSettle();++ const said = 'Morning: Fix login waits on you.';+ expect(find.text(said), findsOneWidget, reason: 'its project chat');+ expect(+ tester.getBottomLeft(key('swarm-chat-header')).dy,+ lessThanOrEqualTo(tester.getTopLeft(find.text(said)).dy),+ );+ expect(+ find.textContaining('Lead'),+ findsNothing,+ reason: 'the Naming System: Product Manager on screen, never Lead',+ );+ });++ testWidgets('its sheet has what waits on the person, then work by '+ 'latest, older folded', (tester) async {+ await pump(tester, backend(), page);+ await tester.pumpAndSettle();+ await openSheet(tester);++ double y(String k) => tester.getTopLeft(key(k)).dy;+ expect(+ y('swarm-conversation-g1'),+ lessThan(y('swarm-conversation-g-busy')),+ reason: 'what waits on the person first, then the latest activity',+ );+ expect(key('swarm-conversation-g-old'), findsNothing);+ expect(+ key('swarm-conversation-g-private'),+ findsNothing,+ reason: 'a private chat is for its people only',+ );+ expect(+ key('swarm-conversation-g-pm'),+ findsNothing,+ reason: 'an old Chat with PM is hidden (#2090)',+ );+ expect(+ key('swarm-conversation-$leadChat'),+ findsNothing,+ reason: 'the project chat is the screen',+ );+ expect(+ find.textContaining('Lead'),+ findsNothing,+ reason: 'the Naming System: Product Manager on screen, never Lead',+ );++ await tester.tap(key('swarm-older'));+ await tester.pumpAndSettle();+ expect(key('swarm-conversation-g-old'), findsOneWidget);+ expect(key('swarm-conversation-g-spike'), findsNothing);++ // Rows are 56 points tall: below the fold of the sheet, and built only+ // as they come into view.+ await tester.scrollUntilVisible(+ key('swarm-older-earlier'),+ 200,+ scrollable: sheetList(),+ );+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-older-earlier'));+ await tester.pumpAndSettle();+ expect(key('swarm-conversation-g-spike'), findsOneWidget);+ expect(key('swarm-older-earlier'), findsNothing);+ });++ testWidgets("its sheet's Team has each agent in a word", (tester) async {+ await pump(tester, backend(), page);+ await tester.pumpAndSettle();+ await openSheet(tester);++ await tester.tap(key('swarm-sheet-team'));+ await tester.pumpAndSettle();++ expect(find.byType(SwarmProjectSheet), findsOneWidget);+ expect(key('swarm-agent-agent-builder'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-agent-agent-builder'),+ matching: find.textContaining('Waiting', findRichText: true),+ ),+ findsOneWidget,+ );+ });++ testWidgets("a pull on its sheet's work reads its Swarm once", (+ tester,+ ) async {+ final fake = backend();+ await pump(tester, fake, page);+ await openSheet(tester);+ final before = changeReads(fake);++ await tester.fling(+ key('swarm-conversation-g1'),+ const Offset(0, 400),+ 1000,+ );+ await tester.pumpAndSettle();++ expect(changeReads(fake), before + 1);+ expect(find.byType(SwarmProjectSheet), findsOneWidget, reason: 'open');+ });++ testWidgets('of hundreds of older chats, only those in view are built', (+ tester,+ ) async {+ final fake = backend();+ fake.routes[dormant] = (_) => {+ 'groups': [+ for (var i = 0; i < 300; i++)+ part(+ 'old-$i',+ 100 + i,+ groupData(+ 'old-$i',+ title: 'Old work $i',+ lastMessageSequence: 1000 - i,+ dormant: true,+ ),+ ),+ ],+ 'next': null,+ };+ await pump(tester, fake, page);+ await openSheet(tester);+ final older = find.byWidgetPredicate(+ (widget) => switch (widget.key) {+ ValueKey(:final String value) => value.startsWith(+ 'swarm-conversation-old-',+ ),+ _ => false,+ },+ );++ await tester.tap(key('swarm-older'));+ await tester.pumpAndSettle();++ expect(key('swarm-conversation-old-0'), findsOneWidget);+ expect(older.evaluate().length, lessThan(40));+ await tester.scrollUntilVisible(+ key('swarm-conversation-old-299'),+ 600,+ scrollable: sheetList(),+ );+ expect(key('swarm-conversation-old-299'), findsOneWidget);+ expect(older.evaluate().length, lessThan(40));+ });+ });++ group('a project while it reads', () {+ const gone = 'This project is no longer in the Swarm.';+ const page = SwarmProjectPage(swarmId: tab, projectId: project);++ /// [projectId]'s page pushed over Home, as Home opens it.+ Future<void> openFromHome(WidgetTester tester, String projectId) async {+ unawaited(+ Navigator.of(tester.element(find.byType(SwarmPage))).push(+ MaterialPageRoute<void>(+ builder: (_) =>+ SwarmProjectPage(swarmId: tab, projectId: projectId),+ ),+ ),+ );+ await frames(tester);+ }++ testWidgets('draws its title on its way while its Swarm is read, with '+ 'nothing under it, then its chat', (tester) async {+ final fake = backend();+ final read = hold(fake, '/api/super-tabs/$tab/parts');+ await pump(tester, fake, page, settle: false);++ expect(key('swarm-project-title-loading'), findsOneWidget);+ expect(key('swarm-project-loading'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-project-loading'),+ matching: find.byType(Skeleton),+ ),+ findsNothing,+ reason: 'no team strip comes under the header',+ );+ expect(find.text(gone), findsNothing);+ expect(find.byType(SwarmConversationPage), findsNothing);++ read.complete();+ await tester.pumpAndSettle();++ expect(key('swarm-project-loading'), findsNothing);+ expect(key('swarm-project-title-loading'), findsNothing);+ expect(tester.widget<Text>(key('swarm-title')).data, 'Mobile');+ expect(key('swarm-project-menu'), findsOneWidget);+ expect(find.byType(SwarmConversationPage), findsOneWidget);+ });+ testWidgets('says it is no longer in the Swarm only once a read since it '+ 'opened has finished without it', (tester) async {+ final fake = backend();+ await pump(tester, fake, const SwarmPage());+ final read = hold(fake, '/api/super-tabs/$tab/changes');+ await openFromHome(tester, 'project-new');++ expect(find.text(gone), findsNothing);+ expect(key('swarm-project-loading'), findsOneWidget);++ read.complete();+ await tester.pumpAndSettle();++ expect(find.text(gone), findsOneWidget);+ expect(key('swarm-project-loading'), findsNothing);+ });++ testWidgets('a Swarm taken away says the project is gone, with nothing '+ 'of it left and no rows on their way', (tester) async {+ await pump(tester, backend(), page);++ host(tester).session!.inbox.reader(tab)!.revoke();+ await frames(tester);++ expect(find.text(gone), findsOneWidget);+ expect(key('swarm-project-loading'), findsNothing);+ expect(key('swarm-project-menu'), findsNothing);+ });++ testWidgets('opening it reads its Swarm once', (tester) async {+ final fake = backend();+ await pump(tester, fake, const SwarmPage());+ final before = changeReads(fake);++ await openFromHome(tester, project);+ await tester.pumpAndSettle();++ expect(changeReads(fake), before + 1);+ expect(key('swarm-project-menu'), findsOneWidget);+ });++ testWidgets('its sheet has rows on their way while the Swarm is read', (+ tester,+ ) async {+ final fake = backend();+ final read = hold(fake, '/api/super-tabs/$tab/parts');+ await pump(+ tester,+ fake,+ Builder(+ builder: (context) => TextButton(+ onPressed: () => showSwarmProjectSheet(+ context,+ swarmId: tab,+ projectId: project,+ ),+ child: const Text('Open'),+ ),+ ),+ settle: false,+ );++ await tester.tap(find.text('Open'));+ await frames(tester);+ expect(key('swarm-work-loading'), findsOneWidget);+ await tester.tap(key('swarm-sheet-team'));+ await frames(tester);+ expect(key('swarm-team-loading'), findsOneWidget);++ read.complete();+ await tester.pumpAndSettle();+ expect(key('swarm-team-loading'), findsNothing);+ expect(sheetTopRadius(tester), 12);+ expect(key('swarm-agent-agent-builder'), findsOneWidget);+ });++ testWidgets("a poll that changes its Swarm builds its menu's status "+ 'once, and not its chat', (tester) async {+ final fake = backend();+ await pump(tester, fake, page);+ await tester.tap(key('swarm-project-menu'));+ await tester.pumpAndSettle();+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ lastChangedAt: 200,+ derived: const {'decisionsWaiting': 1, 'mentionsWaiting': 1},+ groups: [+ part(+ 'g-busy',+ 30,+ groupData('g-busy', title: 'Sync again', lastMessageSequence: 21),+ ),+ ],+ );+ var lines = 0, chats = 0;+ debugOnRebuildDirtyWidget = (element, _) {+ if (element.widget is SwarmProjectStatus) lines++;+ if (element.widget is SwarmConversationPage) chats++;+ };+ addTearDown(() => debugOnRebuildDirtyWidget = null);++ // What waits is read again after the Swarm, a moment later, as it is+ // over a network.+ final asked = hold(fake, '/api/super-tabs/$tab/decisions?state=open');+ unawaited(host(tester).session!.inbox.reader(tab)!.refresh());+ await tester.pump();+ await tester.pump();+ asked.complete();+ await tester.pumpAndSettle();++ expect(+ lines,+ 1,+ reason:+ 'what waits on the person in its chats is read again, '+ 'which moved nothing the line shows',+ );+ expect(chats, 0, reason: 'the chat follows its own messages');+ debugOnRebuildDirtyWidget = null;+ await tester.tap(key('swarm-project-menu-status'));+ await tester.pumpAndSettle();+ expect(find.text('Sync again'), findsOneWidget);+ });++ testWidgets('a change in another Swarm does not build it', (tester) async {+ const other = 'tab-2';+ final fake = backend();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ {'id': other, 'name': 'Web Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$other/parts'] = (_) => firstLoad(+ tabId: other,+ head: headData(id: other, name: 'Web Swarm'),+ );+ fake.routes['/api/super-tabs/$other/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$other/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$other/changes'] = (_) => changes(+ cursor: 'c2',+ lastChangedAt: 200,+ groups: [+ part(+ 'g-web',+ 30,+ groupData('g-web', title: 'Web work', lastMessageSequence: 3),+ ),+ ],+ );+ await pump(tester, fake, page);+ // With two Swarms, the page names its own after who is in the chat.+ expect(find.text('River and everyone · Phone Swarm'), findsOneWidget);+ await tester.tap(key('swarm-project-menu'));+ await tester.pumpAndSettle();+ var builds = 0;+ debugOnRebuildDirtyWidget = (element, _) {+ if (element.widget is SwarmProjectStatus ||+ element.widget is SwarmConversationPage) {+ builds++;+ }+ };+ addTearDown(() => debugOnRebuildDirtyWidget = null);++ final web = host(tester).session!.inbox.reader(other)!;+ unawaited(web.refresh());+ await tester.pumpAndSettle();++ expect(web.snapshot!.conversation('g-web'), isNotNull);+ expect(builds, 0);+ });+ });++ group('a conversation', () {+ testWidgets('posts text to the agent it mentions', (tester) async {+ final fake = backend();+ await pump(+ tester,+ fake,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ await tester.pumpAndSettle();++ await tester.enterText(find.byType(TextField), '@');+ await tester.pumpAndSettle();+ await tester.tap(find.text('Nova').last);+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), '@Nova use beta');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(fake.commands.single, {+ 'type': 'message.send',+ 'conversationId': 'g1',+ 'text': '@Nova use beta',+ 'replyTo': null,+ 'recipientIds': ['agent-builder'],+ });+ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ isEmpty,+ );+ });++ testWidgets('a refused post says why, even before any message', (+ tester,+ ) async {+ final fake = backend();+ fake.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ fake.routes['/api/super-tabs/$tab/commands'] = (_) =>+ throw const SuperTabFailure(+ 'READ_ONLY',+ 'This conversation is read only.',+ statusCode: 403,+ );+ await pump(+ tester,+ fake,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ await tester.pumpAndSettle();++ await tester.enterText(find.byType(TextField), 'hello');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(key('swarm-post-error'), findsOneWidget);+ expect(find.text('This conversation is read only.'), findsOneWidget);+ });++ testWidgets('the decision asked in it is answered in it', (tester) async {+ await pump(+ tester,+ backend(),+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ await tester.pumpAndSettle();++ expect(find.text('Ship it behind a flag?'), findsOneWidget);+ expect(key('swarm-option-d1-0'), findsOneWidget);+ });++ testWidgets('a viewer reads it and cannot post', (tester) async {+ await pump(+ tester,+ backend(role: 'viewer'),+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ await tester.pumpAndSettle();++ expect(find.text('Which name should the flag have?'), findsOneWidget);+ expect(key('swarm-send'), findsNothing);+ expect(key('swarm-read-only'), findsOneWidget);+ expect(+ find.text('You can read this chat, not post in it.'),+ findsOneWidget,+ );+ });++ testWidgets('one the person can no longer read shows nothing of it, '+ 'its decision included', (tester) async {+ final fake = backend();+ final host = await pump(+ tester,+ fake,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), 'my reply');+ expect(find.text('Which name should the flag have?'), findsOneWidget);+ expect(find.text('Ship it behind a flag?'), findsOneWidget);++ // Taken out of g1: the Swarm is read again in full without it, and+ // the decision list has not caught up yet.+ final full = fake.routes['/api/super-tabs/$tab/parts']!(null)! as Map;+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...full,+ 'groups': [+ for (final g in full['groups'] as List)+ if ((g as Map)['key'] != 'g1') g,+ ],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {'reload': true};+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();++ expect(find.text('Which name should the flag have?'), findsNothing);+ expect(find.text('Ship it behind a flag?'), findsNothing);+ expect(find.text('my reply'), findsNothing);+ expect(find.text('This chat is not open to you.'), findsOneWidget);+ });++ testWidgets('its Swarm is read often only while the chat is on screen '+ 'and Harness is in front', (tester) async {+ final host = await pump(+ tester,+ backend(),+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ await tester.pumpAndSettle();+ final reader = host.session!.inbox.reader(tab)!;+ expect(reader.shown, isFalse, reason: 'Harness is behind');++ host.foreground = true;+ expect(reader.shown, isTrue);++ final navigator = tester.state<NavigatorState>(find.byType(Navigator));+ unawaited(+ navigator.push(+ MaterialPageRoute<void>(builder: (_) => const Scaffold()),+ ),+ );+ await tester.pumpAndSettle();+ expect(reader.shown, isFalse, reason: 'another screen covers it');++ navigator.pop();+ await tester.pumpAndSettle();+ expect(reader.shown, isTrue);++ host.foreground = false;+ expect(reader.shown, isFalse);+ });++ testWidgets('a closed one opened from a notice reads its name', (+ tester,+ ) async {+ final fake = backend();+ fake.routes['/api/super-tabs/$tab/conversations/g-old/messages'] = (_) =>+ {'messages': <Object>[], 'next': null};+ await pump(+ tester,+ fake,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g-old'),+ );+ await tester.pumpAndSettle();++ expect(fake.paths, contains('/api/super-tabs/$tab/groups/g-old'));+ expect(find.text('Old work'), findsOneWidget);+ expect(find.text('This chat is not open to you.'), findsNothing);+ });++ testWidgets('one in a Swarm the person left shows nothing of it', (+ tester,+ ) async {+ final fake = backend();+ final host = await pump(+ tester,+ fake,+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),+ );+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), 'my reply');++ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': <Object>[],+ 'next': null,+ };+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();++ expect(find.text('Which name should the flag have?'), findsNothing);+ expect(find.text('my reply'), findsNothing);+ expect(find.text('This chat is not open to you.'), findsOneWidget);+ });+ });++ group("Home's Swarm mark", () {+ testWidgets('counts what needs the person, and opens Swarm', (+ tester,+ ) async {+ final host = await pump(+ tester,+ backend(),+ const Scaffold(body: Center(child: SwarmMark())),+ );+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();++ expect(find.text('3'), findsOneWidget);++ await tester.tap(key('swarm-mark'));+ await tester.pumpAndSettle();+ expect(find.byType(SwarmPage), findsOneWidget);+ });++ testWidgets('in the shell, goes back to Swarm Home rather than over it', (+ tester,+ ) async {+ var shown = 0;+ final host = await pump(+ tester,+ backend(),+ PhoneShellScope(+ onMachineLinked: (_) {},+ onOpenAgent: (_, _) {},+ onShowSwarm: () => shown++,+ child: const Scaffold(body: Center(child: SwarmMark())),+ ),+ );+ await host.session!.inbox.refresh();+ await tester.pumpAndSettle();++ await tester.tap(key('swarm-mark'));+ await tester.pumpAndSettle();++ expect(shown, 1);+ expect(find.byType(SwarmPage), findsNothing);+ });++ testWidgets('is not there while Swarm is off', (tester) async {+ await pump(+ tester,+ backend(),+ const Scaffold(body: Center(child: SwarmMark())),+ on: false,+ );++ expect(key('swarm-mark'), findsNothing);+ });+ });+}diff --git a/mobile/test/swarm/swarm_session_test.dart b/mobile/test/swarm/swarm_session_test.dartnew file mode 100644index 000000000..848f18531--- /dev/null+++ b/mobile/test/swarm/swarm_session_test.dart@@ -0,0 +1,583 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:dio/dio.dart' show CancelToken;+import 'package:fake_async/fake_async.dart';+import 'package:flutter/widgets.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/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_face.dart';+import 'package:harness_mobile/swarm/swarm_home_cache.dart';+import 'package:harness_mobile/swarm/swarm_inbox.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_start.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// The account's Swarm on the phone: made while Swarm is turned on and someone+/// is signed in, read while Harness is in front, telling the person what+/// arrives unless they are looking at it, and holding a decision's answer+/// for Undo.+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ /// One Swarm `a` whose open decision is d1, asked in conversation g9.+ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': 'a', 'name': 'Swarm a', 'ownerId': me, 'lastChangedAt': 100},+ ],+ 'next': null,+ };+ const derived = {'decisionsWaiting': 1, 'mentionsWaiting': 0};+ fake.routes['/api/super-tabs/a/parts'] = (_) =>+ firstLoad(tabId: 'a', derived: derived);+ fake.routes['/api/super-tabs/a/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/a/decisions?state=open'] = (_) => {+ 'decisions': [+ {+ 'id': 'd1',+ 'conversationId': 'g9',+ 'askerName': 'River',+ 'question': 'Ship it?',+ 'options': ['Yes', 'No'],+ },+ ],+ };+ fake.routes['/api/super-tabs/a/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/a/commands'] = (_) => {+ 'result': <String, dynamic>{},+ };+ return fake;+ }++ SwarmSession session(FakeSwarm fake, {_Notices? notices}) {+ final s = SwarmSession(+ accountId: me,+ request: fake.request,+ notices: notices ?? _Notices(),+ );+ addTearDown(s.dispose);+ return s;+ }++ group('SwarmHost', () {+ late ExperimentalFeaturesStore features;+ late ValueNotifier<String?> account;+ late _Notices notices;+ late SwarmHomeCache home;++ SwarmHost host() {+ final h = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ notices: notices,+ features: features,+ homeCache: home,+ );+ addTearDown(h.dispose);+ return h;+ }++ setUp(() {+ features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore());+ account = ValueNotifier(me);+ notices = _Notices();+ home = memoryHomeCache();+ });++ /// The account's Home, kept as a Swarm it read.+ Future<void> keep(String account) => home.write(account, [+ (+ id: 'a',+ name: 'Swarm a',+ view: (+ state: SuperTabParts.firstLoad(firstLoad(tabId: 'a')).state,+ partners: const <String, String>{},+ ),+ ),+ ]);++ test('each Swarm sends its chats\' files with the upload handed in',+ () async {+ await features.set(PhoneExperiment.swarm, true);+ final sent = <String>[];+ final h = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ upload:+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required bytes,+ required cancel,+ required onProgress,+ }) async {+ sent.add('$tabId/$conversationId/$name');+ return {'attachment': <String, dynamic>{}};+ },+ notices: notices,+ features: features,+ homeCache: home,+ );+ addTearDown(h.dispose);+ final inbox = h.session!.inbox..shown = true;+ await until(() => inbox.reader('a') != null);++ final reader = inbox.reader('a')!;+ await reader.upload(+ tabId: reader.tabId,+ conversationId: 'g9',+ name: 'shot.jpg',+ mime: 'image/jpeg',+ bytes: Uint8List(1),+ cancel: CancelToken(),+ onProgress: (_) {},+ );++ expect(sent, ['a/g9/shot.jpg']);+ });++ group('the photos drawn', () {+ setUp(() => features.set(PhoneExperiment.swarm, true));++ /// A photo of the Swarm's as drawing holds it in memory.+ ImageProvider drawn(String url) {+ final image = swarmAvatarImage(Uri.parse(url));+ PaintingBinding.instance.imageCache.putIfAbsent(+ image,+ () => OneFrameImageStreamCompleter(Completer<ImageInfo>().future),+ );+ expect(PaintingBinding.instance.imageCache.containsKey(image), isTrue);+ return image;+ }++ test('go when the person signs out', () {+ host();+ final photo = drawn('https://storage.googleapis.com/a.png?sig=1');+ account.value = null;+ expect(PaintingBinding.instance.imageCache.containsKey(photo), isFalse);+ });++ test('go when another account signs in', () {+ host();+ final photo = drawn('https://storage.googleapis.com/b.png?sig=1');+ account.value = 'person-other';+ expect(PaintingBinding.instance.imageCache.containsKey(photo), isFalse);+ });++ test('stay while the same account is signed in', () {+ final h = host();+ final photo = drawn('https://storage.googleapis.com/c.png?sig=1');+ h.foreground = false;+ h.foreground = true;+ expect(PaintingBinding.instance.imageCache.containsKey(photo), isTrue);+ PaintingBinding.instance.imageCache.clear();+ });+ });++ group('the Home kept', () {+ setUp(() => features.set(PhoneExperiment.swarm, true));++ test('goes when the person signs out', () async {+ host();+ await keep(me);++ account.value = null;++ expect(await home.read(me), isNull);+ });++ test('goes when Swarm is turned off', () async {+ host();+ await keep(me);++ await features.set(PhoneExperiment.swarm, false);++ expect(await home.read(me), isNull);+ });++ test('goes when another account signs in', () async {+ host();+ await keep(me);++ account.value = 'person-other';++ expect(await home.read(me), isNull);+ });++ test(+ 'stays while the same account is signed in, in front or not',+ () async {+ final h = host();+ await keep(me);++ h.foreground = false;+ h.foreground = true;++ expect(await home.read(me), isNotNull);+ },+ );+ });++ group('the Home kept, at a cold start', () {+ /// Nothing of it on the phone: no view, and no key that opens one.+ Future<void> expectGone() async {+ expect(await home.read(me), isNull);+ expect(home.file.existsSync(), isFalse);+ expect((home.key as MemorySwarmHomeKey).value, isNull);+ }++ test('goes when Swarm is already off, with no session to end', () async {+ await keep(me);++ host();++ await expectGone();+ });++ test('stays while the account is still being read', () async {+ await features.set(PhoneExperiment.swarm, true);+ account.value = null;+ await keep(me);++ final h = host();+ account.value = me;++ expect(h.session?.accountId, me);+ expect(await home.read(me), isNotNull);+ });++ test(+ 'goes when Swarm is turned off before the account is read',+ () async {+ await features.set(PhoneExperiment.swarm, true);+ account.value = null;+ await keep(me);+ host();++ await features.set(PhoneExperiment.swarm, false);++ await expectGone();+ },+ );+ });++ test(+ 'has a session only while Swarm is on and someone is signed in',+ () async {+ final h = host();+ expect(h.session, isNull, reason: 'Swarm is off');++ await features.set(PhoneExperiment.swarm, true);+ expect(h.session?.accountId, me);++ account.value = null;+ expect(h.session, isNull, reason: 'signed out');++ account.value = 'person-other';+ expect(h.session?.accountId, 'person-other');++ await features.set(PhoneExperiment.swarm, false);+ expect(h.session, isNull);+ },+ );++ test('a session dropped takes its notices off the lock screen', () async {+ await features.set(PhoneExperiment.swarm, true);+ final h = host();+ final s = h.session!;+ s.foreground = false;+ await s.inbox.refresh();+ await settle();+ s.announce(s.inbox.needs.single);+ expect(notices.shown, hasLength(1));++ account.value = 'person-other';++ expect(notices.cancelled, [notices.shown.single.key]);+ });++ group("the app icon's count", () {+ /// Swarm on, and the session's Swarm read once: one decision waits.+ Future<SwarmSession> read() async {+ await features.set(PhoneExperiment.swarm, true);+ final s = host().session!;+ await s.inbox.refresh();+ await settle();+ return s;+ }++ test('is what the drawer counts after a read', () async {+ final s = await read();++ expect(s.inbox.needs, hasLength(1));+ expect(notices.badges.last, 1);+ });++ test('clears when the person signs out', () async {+ await read();++ account.value = null;++ expect(notices.badges.last, 0);+ });++ test('clears when another account signs in', () async {+ await read();++ account.value = 'person-other';++ expect(notices.badges.last, 0);+ });++ test('clears when Swarm is turned off', () async {+ await read();++ await features.set(PhoneExperiment.swarm, false);++ expect(notices.badges.last, 0);+ });+ });+ });++ test('a computer coming up while Swarm has none reads at once', () {+ fakeAsync((async) {+ final fake = backend();+ final listed = fake.routes['/api/super-tabs/list']!;+ var away = true;+ fake.routes['/api/super-tabs/list'] = (q) => away+ ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')+ : listed(q);+ final features = ExperimentalFeaturesStore(+ storage: MemoryKeyValueStore(),+ );+ features.set(PhoneExperiment.swarm, true);+ async.flushMicrotasks();+ final computers = _Computers();+ final host = SwarmHost(+ accountId: () => me,+ account: ValueNotifier(me),+ request: fake.request,+ notices: _Notices(),+ features: features,+ computers: computers,+ );+ async.flushMicrotasks();+ final inbox = host.session!.inbox;+ expect(inbox.noComputer, isTrue);++ away = false;+ async.elapse(const Duration(milliseconds: 300));+ computers.up();+ async.flushMicrotasks();++ expect(inbox.loaded, isTrue);+ host.dispose();+ });+ });++ test('reads only while Harness is in front', () {+ fakeAsync((async) {+ final fake = backend();+ final s = SwarmSession(+ accountId: me,+ request: fake.request,+ notices: _Notices(),+ );+ int lists() => fake.paths.where((p) => p.endsWith('/list')).length;++ s.foreground = true;+ async.flushMicrotasks();+ expect(lists(), 1);++ s.foreground = false;+ async.elapse(const Duration(minutes: 2));+ expect(lists(), 1);+ s.dispose();+ });+ });++ test('tells what arrives, unless a Swarm screen is up', () async {+ final notices = _Notices();+ final s = session(backend(), notices: notices);+ await s.inbox.refresh();+ await settle();+ final need = s.inbox.needs.single;++ s.enter();+ s.announce(need);+ expect(notices.shown, isEmpty);++ s.leave();+ s.announce(need);+ expect(notices.shown.single.title, 'River asks you');+ });++ group('an answer', () {+ test('is held for Undo, then sent once', () {+ fakeAsync((async) {+ final fake = backend();+ final s = SwarmSession(+ accountId: me,+ request: fake.request,+ notices: _Notices(),+ );+ s.inbox.refresh();+ async.flushMicrotasks();+ final need = s.inbox.needs.whereType<SwarmDecisionNeed>().single;++ s.hold(need, 0);+ expect(s.held(need), 0);+ async.elapse(const Duration(seconds: 2));+ expect(fake.commands, isEmpty, reason: 'still in its Undo window');++ async.elapse(const Duration(seconds: 2));+ expect(fake.commands.single, {+ 'type': 'decision.answer',+ 'decisionId': 'd1',+ 'choice': 0,+ });+ expect(s.held(need), isNull);+ s.dispose();+ });+ });++ test('undone in time is never sent', () {+ fakeAsync((async) {+ final fake = backend();+ final s = SwarmSession(+ accountId: me,+ request: fake.request,+ notices: _Notices(),+ );+ s.inbox.refresh();+ async.flushMicrotasks();+ final need = s.inbox.needs.whereType<SwarmDecisionNeed>().single;++ s.hold(need, 1);+ async.elapse(const Duration(seconds: 1));+ s.undo(need);+ async.elapse(const Duration(seconds: 10));++ expect(fake.commands, isEmpty);+ expect(s.held(need), isNull);+ s.dispose();+ });+ });++ test('held when the account leaves is dropped, not sent', () {+ fakeAsync((async) {+ final fake = backend();+ final s = SwarmSession(+ accountId: me,+ request: fake.request,+ notices: _Notices(),+ );+ s.inbox.refresh();+ async.flushMicrotasks();+ s.hold(s.inbox.needs.whereType<SwarmDecisionNeed>().single, 0);++ s.dispose();+ async.elapse(const Duration(seconds: 10));++ expect(fake.commands, isEmpty);+ });+ });+ });++ test(+ 'a Swarm watched by a screen is read often, until no screen watches it',+ () async {+ final s = session(backend())..foreground = true;+ await s.inbox.refresh();+ final reader = s.inbox.reader('a')!;++ s.watch('a');+ s.watch('a');+ expect(reader.shown, isTrue);++ s.unwatch('a');+ expect(reader.shown, isTrue, reason: 'one screen still watches it');++ s.unwatch('a');+ expect(reader.shown, isFalse);+ },+ );++ test('a watched Swarm reads nothing while Harness is behind, '+ 'and reads at once when it is in front again', () {+ fakeAsync((async) {+ final fake = backend();+ final s = SwarmSession(+ accountId: me,+ request: fake.request,+ notices: _Notices(),+ )..foreground = true;+ async.flushMicrotasks();+ int reads() => fake.paths+ .where((p) => p.startsWith('/api/super-tabs/a/changes'))+ .length;+ s.watch('a');+ async.elapse(const Duration(seconds: 6));+ final watched = reads();+ expect(watched, greaterThan(0));++ s.foreground = false;+ async.elapse(const Duration(minutes: 2));+ expect(reads(), watched, reason: 'behind, the watched Swarm too');++ s.foreground = true;+ async.flushMicrotasks();+ expect(reads(), greaterThan(watched));+ s.dispose();+ });+ });+}++/// The account's computers, told by hand.+class _Computers extends ChangeNotifier implements SwarmComputers {+ @override+ List<SwarmComputer>? computers = const [(name: 'Studio Mac', away: false)];++ @override+ bool get rechecking => false;++ @override+ Future<void> recheck() async {}++ @override+ void add(BuildContext context) {}++ /// A computer came up.+ void up() => notifyListeners();+}++class _Notices extends SilentSystemNotices {+ final shown = <SwarmNoticeMessage>[];+ final cancelled = <String>[];++ @override+ Future<void> showSwarm(SwarmNoticeMessage message) async =>+ shown.add(message);++ @override+ Future<void> cancelSwarm(String key) async => cancelled.add(key);++ final badges = <int>[];++ @override+ Future<void> setSwarmBadge(int count) async => badges.add(count);+}diff --git a/mobile/test/swarm/swarm_ship_row_test.dart b/mobile/test/swarm/swarm_ship_row_test.dartnew file mode 100644index 000000000..f3984e55e--- /dev/null+++ b/mobile/test/swarm/swarm_ship_row_test.dart@@ -0,0 +1,412 @@+import 'package:flutter/material.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/swarm_tokens_set_b.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_message_row.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_ship_row.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// A ship line as the backend posts it to the project chat+/// (`backend/src/superTabs/ship.ts` `shipNotice`), built by hand.+SuperTabMessage shipMessage({+ String id = 'ship-1',+ DateTime? at,+ Map<String, dynamic>? source,+}) => SuperTabMessage.fromJson({+ 'id': id,+ 'conversationId': leadChat,+ 'text':+ '🎉 Shipped: Fix login, requested by person-me, built by Nova, '+ 'reviewed by Rex. https://github.com/autonomous-ai/openharness/pull/12',+ 'sequence': 5,+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},+ 'createdAt': (at ?? DateTime.now()).toUtc().toIso8601String(),+ 'source':+ source ??+ {+ 'kind': 'ship',+ 'conversationId': 'g1',+ 'title': 'Fix login',+ 'pullRequests': [+ 'https://github.com/autonomous-ai/openharness/pull/12',+ ],+ 'requesterId': me,+ 'builderIds': ['agent-builder'],+ 'reviewerIds': ['agent-reviewer'],+ },+});++void main() {+ setUp(SwarmShipRow.resetPlayed);++ group('a ship line as read', () {+ test('is a ship by its source kind alone', () {+ expect(swarmShips(shipMessage()), isTrue);+ expect(swarmShips(shipMessage(source: {'kind': 'message'})), isFalse);+ expect(swarmShips(shipMessage(source: {})), isFalse);+ });++ test('reads what shipped and who asked, built and reviewed it', () {+ final ship = SwarmShip.of(shipMessage());++ expect(ship.title, 'Fix login');+ expect(ship.requesterId, me);+ expect(ship.builderIds, ['agent-builder']);+ expect(ship.reviewerIds, ['agent-reviewer']);+ expect(ship.pullRequests, [+ Uri.parse('https://github.com/autonomous-ai/openharness/pull/12'),+ ]);+ });++ test('keeps only GitHub pull requests, at most four', () {+ final ship = SwarmShip.of(+ shipMessage(+ source: {+ 'kind': 'ship',+ 'title': 7,+ 'builderIds': ['agent-builder', 3],+ 'pullRequests': [+ 'https://evil.example/autonomous-ai/openharness/pull/1',+ 'http://github.com/autonomous-ai/openharness/pull/2',+ 'https://github.com/autonomous-ai/openharness/issues/3',+ for (var n = 10; n < 16; n++)+ 'https://github.com/autonomous-ai/openharness/pull/$n',+ ],+ },+ ),+ );++ expect(ship.title, '');+ expect(ship.requesterId, isNull);+ expect(ship.builderIds, ['agent-builder']);+ expect(ship.reviewerIds, isEmpty);+ expect(+ [for (final link in ship.pullRequests) link.pathSegments[3]],+ ['10', '11', '12', '13'],+ );+ });+ });++ group('when a ship throws confetti', () {+ final now = DateTime.utc(2026, 10, 28, 3);++ test('a ship under two minutes old does, once per ship', () {+ final played = <String>{};+ final fresh = shipMessage(at: now.subtract(const Duration(seconds: 90)));++ expect(swarmShipCelebrates(fresh, now, played), isTrue);+ expect(swarmShipCelebrates(fresh, now, played), isFalse);+ expect(+ swarmShipCelebrates(shipMessage(id: 'ship-2', at: now), now, played),+ isTrue,+ );+ });++ test('an older ship, or one with no time, does not', () {+ final played = <String>{};+ expect(+ swarmShipCelebrates(+ shipMessage(at: now.subtract(const Duration(minutes: 2, seconds: 1))),+ now,+ played,+ ),+ isFalse,+ );+ final timeless = SuperTabMessage.fromJson({+ 'id': 'ship-3',+ 'conversationId': leadChat,+ 'text': '',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'agent-lead'},+ 'source': {'kind': 'ship'},+ });+ expect(swarmShipCelebrates(timeless, now, played), isFalse);+ expect(played, isEmpty, reason: 'nothing counted as played');+ });+ });++ group('the ship row', () {+ /// The project chat's Swarm, read: the viewer asked, Nova built and Rex+ /// reviewed.+ FakeSwarm backend() => FakeSwarm()+ ..routes['/api/super-tabs/list'] = ((_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ })+ ..routes['/api/super-tabs/$tab/parts'] = ((_) => firstLoad(+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ {...agent('agent-reviewer', displayName: 'Rex'), 'role': 'reviewer'},+ ],+ ))+ ..routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');++ Future<void> pump(+ WidgetTester tester,+ SuperTabMessage message, {+ FakeSwarm? fake,+ bool still = false,+ TextScaler? scale,+ }) async {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: (fake ?? backend()).request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await host.session!.inbox.refresh();+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(disableAnimations: still, textScaler: scale),+ child: SwarmScope(notifier: host, child: child!),+ ),+ home: Scaffold(+ body: ListView(+ children: [+ SwarmMessageRow(+ key: ValueKey(message.id),+ message: message,+ name: 'River',+ look: (picture: null, status: null),+ role: 'PM',+ mentions: SwarmMentions(const []),+ grouped: false,+ lit: false,+ quote: null,+ actions: false,+ onTap: () {},+ onReply: null,+ ),+ ],+ ),+ ),+ ),+ );+ }++ Finder key(String value) => find.byKey(ValueKey(value));+ Finder inside(Finder matching) =>+ find.descendant(of: key('swarm-ship-ship-1'), matching: matching);++ testWidgets('names what shipped and who asked, built and reviewed it', (+ tester,+ ) async {+ await pump(tester, shipMessage());+ await tester.pumpAndSettle();++ expect(inside(find.text('🎉')), findsOneWidget);+ expect(inside(find.text('Shipped: Fix login')), findsOneWidget);+ expect(inside(find.text('Requested by')), findsOneWidget);+ expect(inside(find.text('person-me')), findsOneWidget);+ expect(inside(find.text('Built by')), findsOneWidget);+ expect(inside(find.text('Nova')), findsOneWidget);+ expect(inside(find.text('Reviewed by')), findsOneWidget);+ expect(inside(find.text('Rex')), findsOneWidget);+ expect(inside(find.text('N')), findsOneWidget, reason: 'an initial');+ expect(inside(find.text('openharness · PR #12')), findsOneWidget);+ expect(+ tester.getSize(key('swarm-ship-pr-ship-1-0')).height,+ greaterThanOrEqualTo(44),+ reason: 'a thumb',+ );+ expect(+ find.text('River'),+ findsNothing,+ reason: 'a ship line is no message from its author',+ );+ expect(+ find.textContaining('requested by person-me'),+ findsNothing,+ reason: 'the card, not the plain text',+ );+ });++ testWidgets('until its Swarm is read, the title and links show alone', (+ tester,+ ) async {+ final fake = backend()..routes.remove('/api/super-tabs/$tab/parts');+ await pump(tester, shipMessage(), fake: fake);+ await tester.pumpAndSettle();++ expect(inside(find.text('Shipped: Fix login')), findsOneWidget);+ expect(inside(find.text('openharness · PR #12')), findsOneWidget);+ expect(inside(find.text('Built by')), findsNothing);+ expect(inside(find.text('Requested by')), findsNothing);+ });++ testWidgets('a fresh ship throws confetti once', (tester) async {+ await pump(tester, shipMessage());+ await tester.pump();++ expect(+ find.descendant(+ of: key('swarm-message-ship-1'),+ matching: key('swarm-ship-confetti'),+ ),+ findsOneWidget,+ reason: 'over this ship',+ );+ await tester.pumpAndSettle();+ expect(key('swarm-ship-confetti'), findsNothing, reason: 'it ends');++ // The same ship drawn again, as when the chat is opened again.+ await tester.pumpWidget(const SizedBox());+ await pump(tester, shipMessage());+ await tester.pump();+ expect(key('swarm-ship-confetti'), findsNothing);+ });++ testWidgets('a ship from earlier in the history throws none', (+ tester,+ ) async {+ await pump(+ tester,+ shipMessage(at: DateTime.now().subtract(const Duration(minutes: 3))),+ );+ await tester.pump();++ expect(inside(find.text('Shipped: Fix login')), findsOneWidget);+ expect(key('swarm-ship-confetti'), findsNothing);+ });++ testWidgets('with Reduce Motion on, a fresh ship throws none', (+ tester,+ ) async {+ await pump(tester, shipMessage(), still: true);+ await tester.pump();++ expect(inside(find.text('Shipped: Fix login')), findsOneWidget);+ expect(key('swarm-ship-confetti'), findsNothing);+ });++ testWidgets('any other message is drawn as before', (tester) async {+ await pump(tester, shipMessage(source: {'kind': 'message'}));+ await tester.pumpAndSettle();++ expect(key('swarm-ship-ship-1'), findsNothing);+ expect(find.text('River'), findsOneWidget);+ expect(find.textContaining('requested by person-me'), findsOneWidget);+ });++ group('drawn on the design tokens', () {+ // The card itself, inside the margin that is part of its Container.+ Finder card() => find+ .descendant(+ of: key('swarm-ship-ship-1'),+ matching: find.byType(DecoratedBox),+ )+ .first;++ // Half size, so that a label fits one line in the test's square font.+ Future<void> shown(WidgetTester tester) async {+ await pump(+ tester,+ shipMessage(at: DateTime(2020)),+ scale: const TextScaler.linear(.5),+ );+ await tester.pumpAndSettle();+ }++ testWidgets('the card sits 8 in from the edge, rounded at 12', (+ tester,+ ) async {+ await shown(tester);++ expect(tester.getTopLeft(card()).dx, 8);+ expect(+ (tester.widget<DecoratedBox>(card()).decoration as BoxDecoration)+ .borderRadius,+ BorderRadius.circular(12),+ );+ });++ testWidgets('its words start 16 inside the 1-point rim, the 🎉 at 20', (+ tester,+ ) async {+ await shown(tester);++ expect(+ tester.getTopLeft(find.text('🎉')).dx - tester.getTopLeft(card()).dx,+ 1 + 16,+ );+ expect(tester.widget<Text>(find.text('🎉')).style?.fontSize, 20);+ });++ testWidgets("each credit's label is centred on its first name", (+ tester,+ ) async {+ await shown(tester);++ for (final (label, name) in [+ ('Requested by', 'person-me'),+ ('Built by', 'Nova'),+ ('Reviewed by', 'Rex'),+ ]) {+ expect(+ tester.getCenter(find.text(label)).dy,+ closeTo(tester.getCenter(find.text(name)).dy, .01),+ reason: label,+ );+ }+ });++ testWidgets('each credit has 4 above and below its line', (tester) async {+ await shown(tester);++ const avatar = 22.0;+ expect(+ tester.getCenter(find.text('Reviewed by')).dy -+ tester.getCenter(find.text('Built by')).dy,+ avatar + 2 * 4,+ reason: 'one avatar tall, 4 points above and below',+ );+ });++ testWidgets('a pull request is a button rounded at 10, 44 tall', (+ tester,+ ) async {+ await shown(tester);++ final button = find.byKey(const ValueKey('swarm-ship-pr-ship-1-0'));+ final shape =+ tester+ .widget<Material>(+ find.descendant(+ of: button,+ matching: find.byType(Material),+ ),+ )+ .shape!+ as RoundedRectangleBorder;+ expect(shape.borderRadius, BorderRadius.circular(10));+ expect(tester.getSize(button).height, 44);+ });+ });++ test('the confetti keeps its six colours', () {+ expect(SwarmConfetti.colors, const [+ Color(0xffff6b6b),+ Color(0xffffc145),+ Color(0xff4ecdc4),+ Color(0xff5b8def),+ Color(0xffb084f5),+ Color(0xff6ad08a),+ ]);+ });+ });+}diff --git a/mobile/test/swarm/swarm_snapshot_glance_test.dart b/mobile/test/swarm/swarm_snapshot_glance_test.dartnew file mode 100644index 000000000..c5927fb48--- /dev/null+++ b/mobile/test/swarm/swarm_snapshot_glance_test.dart@@ -0,0 +1,100 @@+import 'package:flutter/material.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/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/team_glance.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// A project's team line is counted once per Swarm read: the project's page+/// draws the one glance of the read it shows.+void main() {+ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-builder'],+ status: 'needs_human',+ ),+ ],+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/decisions'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };+ return fake;+ }++ Future<SwarmHost> pump(WidgetTester tester) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: backend().request,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmPage(),+ ),+ );+ await tester.pumpAndSettle();+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ testWidgets("the project's menu draws the read's one glance", (tester) async {+ final host = await pump(tester);+ final reader = host.session!.inbox.reader(tab)!;+ final read = reader.snapshot!;+ final glance = swarmTeamGlance(read, projectId: project);+ expect(glance.line, '1 waiting');++ await tester.tap(key('swarm-menu'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-drawer-project-$tab-$project'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-project-menu'));+ await tester.pumpAndSettle();+ final page = tester+ .widget<SwarmStatusText>(+ find.descendant(+ of: key('swarm-project-menu-status'),+ matching: find.byType(SwarmStatusText),+ ),+ )+ .glance;++ expect(reader.snapshot, same(read), reason: 'still the same read');+ expect(page, same(glance));+ });+}diff --git a/mobile/test/swarm/swarm_start_test.dart b/mobile/test/swarm/swarm_start_test.dartnew file mode 100644index 000000000..175e84fba--- /dev/null+++ b/mobile/test/swarm/swarm_start_test.dart@@ -0,0 +1,276 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_inbox.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_start.dart';++import 'swarm_fixture.dart';++/// What Swarm shows before there is a Swarm to show, from what the phone+/// already knows: its computers, and what the Swarm list said.+void main() {+ const mac = (name: 'MacBook Pro', away: false);+ const macAway = (name: 'MacBook Pro', away: true);++ /// The account's Swarm list answers [tabs]; its invitations, [invites].+ FakeSwarm backend({+ List<String> tabs = const [],+ List<Map<String, dynamic>> invites = const [],+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ for (final id in tabs) {'id': id, 'name': 'Swarm $id', 'ownerId': me},+ ],+ 'next': null,+ };+ for (final id in tabs) {+ fake.routes['/api/super-tabs/$id/parts'] = (_) => firstLoad(tabId: id);+ }+ fake.routes['/api/super-tabs/invitations'] = (_) => invites;+ return fake;+ }++ Map<String, dynamic> invite(String tabId, String name) => {+ 'tabId': tabId,+ 'name': name,+ 'inviteId': 'invite-$tabId',+ 'role': 'collaborator',+ 'expiresAt': 1893456000000,+ };++ SwarmInbox inbox(FakeSwarm fake) {+ final inbox = SwarmInbox(accountId: me, request: fake.request);+ addTearDown(inbox.dispose);+ return inbox;+ }++ test('an account with no computer at all is asked to connect one', () async {+ final i = inbox(backend());++ expect(swarmStart(i, const []), SwarmStart.noComputer);+ });++ test('a computer list not answered yet says nothing', () async {+ final i = inbox(backend());++ expect(swarmStart(i, null), isNull);+ });++ // "No computer online" never takes Home's place: Home draws what it has,+ // and says so in a line (owner's iPhone, 2026-10-28).+ test('every computer away, before any Swarm was read: no start screen', () {+ final i = inbox(backend());++ expect(swarmStart(i, const [macAway]), isNull);+ });++ test('a list that failed for want of a computer: no start screen', () async {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ );+ final i = inbox(fake);++ await i.refresh();++ expect(i.noComputer, isTrue);+ expect(swarmStart(i, const [mac]), isNull);+ });++ test('a list that failed otherwise is not "no computer"', () async {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => throw const SuperTabFailure(+ 'SWARM_MIGRATING',+ 'This Swarm is being moved. Try again in a moment.',+ statusCode: 503,+ );+ final i = inbox(fake);++ await i.refresh();++ expect(swarmStart(i, const [mac]), isNull);+ });++ test('read once, a computer going away mid-session keeps what was shown, '+ 'and says no start screen', () async {+ final i = inbox(backend(tabs: ['a']));+ await i.refresh();++ expect(swarmStart(i, const [macAway]), isNull);+ });++ test('read, with no Swarm and no invitation: no Swarm yet', () async {+ final i = inbox(backend());++ await i.refresh();++ expect(swarmStart(i, const [mac]), SwarmStart.none);+ });++ test('read, with no Swarm but an invitation: invited, to it', () async {+ final i = inbox(backend(invites: [invite('t-lab', 'Design Lab')]));++ await i.refresh();++ expect(swarmStart(i, const [mac]), SwarmStart.invited);+ expect(i.invitations.single.name, 'Design Lab');+ });++ test(+ 'a Swarm to show: no start screen, and invitations are not read',+ () async {+ final fake = backend(+ tabs: ['a'],+ invites: [invite('t-lab', 'Design Lab')],+ );+ final i = inbox(fake);++ await i.refresh();++ expect(swarmStart(i, const [mac]), isNull);+ expect(fake.paths, isNot(contains('/api/super-tabs/invitations')));+ },+ );++ test('a server without invitations: no Swarm yet', () async {+ final fake = backend();+ fake.routes.remove('/api/super-tabs/invitations');+ final i = inbox(fake);++ await i.refresh();++ expect(swarmStart(i, const [mac]), SwarmStart.none);+ expect(i.error, isNull);+ });++ // Review of #1802 at bd73842: after an empty Swarm list, an invitations+ // read that failed was taken for "no invitation", and the person was told+ // to start a Swarm rather than that Join could not be loaded.+ group('invitations that cannot be read', () {+ final failures = <String, Object? Function(Map<String, dynamic>?)>{+ 'refused': (_) => throw const SuperTabFailure(+ 'INTERNAL',+ 'Something went wrong.',+ statusCode: 500,+ ),+ 'lost on the way': (_) => throw Exception('socket closed'),+ 'not a list': (_) => {'invitations': <Object>[]},+ 'a row without its Swarm': (_) => [+ {'name': 'Design Lab', 'inviteId': 'invite-t-lab', 'role': 'viewer'},+ ],+ };+ for (final MapEntry(key: how, value: fails) in failures.entries) {+ test('on the first read ($how): not "No Swarm yet", but invitations '+ 'not checked', () async {+ final fake = backend();+ fake.routes['/api/super-tabs/invitations'] = fails;+ final i = inbox(fake);++ await i.refresh();++ expect(i.loaded, isTrue);+ expect(i.invitations, isEmpty);+ expect(i.invitationsFailed, isTrue);+ expect(swarmStart(i, const [mac]), SwarmStart.invitesFailed);+ });+ }++ test('on a later read: the invitation already shown stays', () async {+ final fake = backend(invites: [invite('t-lab', 'Design Lab')]);+ final i = inbox(fake);+ await i.refresh();+ expect(swarmStart(i, const [mac]), SwarmStart.invited);++ fake.routes['/api/super-tabs/invitations'] = failures['refused']!;+ await i.refresh();++ expect(i.invitations.single.name, 'Design Lab');+ expect(i.invitationsFailed, isTrue);+ expect(swarmStart(i, const [mac]), SwarmStart.invited);+ });++ test('for want of a computer: read again soon', () async {+ final fake = backend();+ fake.routes['/api/super-tabs/invitations'] = (_) =>+ throw const SuperTabFailure(+ 'MACHINE_UNAVAILABLE',+ 'Connect one of your computers to open Swarm.',+ );+ final i = inbox(fake);++ await i.refresh();++ expect(i.noComputer, isTrue, reason: 'the quick retry is on');+ expect(swarmStart(i, const [mac]), SwarmStart.invitesFailed);+ });++ test('read again: what they say, and the failure is gone', () async {+ final fake = backend(invites: [invite('t-lab', 'Design Lab')]);+ final read = fake.routes['/api/super-tabs/invitations']!;+ fake.routes['/api/super-tabs/invitations'] = failures['refused']!;+ final i = inbox(fake);+ await i.refresh();++ fake.routes['/api/super-tabs/invitations'] = read;+ await i.refresh();++ expect(i.invitationsFailed, isFalse);+ expect(swarmStart(i, const [mac]), SwarmStart.invited);+ });+ });++ test('Join accepts the invitation once, under one receipt, then the Swarm '+ 'is read', () async {+ var joined = false;+ final fake = backend(invites: [invite('t-lab', 'Design Lab')]);+ fake.routes['/api/super-tabs/t-lab/commands'] = (_) {+ joined = true;+ return {'result': <String, dynamic>{}};+ };+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ if (joined)+ {'id': 't-lab', 'name': 'Design Lab', 'ownerId': 'person-o'},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/t-lab/parts'] = (_) =>+ firstLoad(tabId: 't-lab');+ final i = inbox(fake);+ await i.refresh();++ expect(await i.join(i.invitations.single), isTrue);++ expect(fake.commands.single, {+ 'type': 'invite.accept',+ 'inviteId': 'invite-t-lab',+ });+ expect([for (final s in i.swarms) s.name], ['Design Lab']);+ expect(swarmStart(i, const [mac]), isNull);+ });++ test('a Join whose answer is lost is sent again under the same receipt, '+ 'and says why it failed meanwhile', () async {+ final fake = backend(invites: [invite('t-lab', 'Design Lab')]);+ var lost = true;+ fake.routes['/api/super-tabs/t-lab/commands'] = (_) => lost+ ? throw Exception('socket closed')+ : {'result': <String, dynamic>{}};+ final i = inbox(fake);+ await i.refresh();+ final invitation = i.invitations.single;++ expect(await i.join(invitation), isFalse);+ expect(i.joinError, 'Could not join. Try again.');++ lost = false;+ expect(await i.join(invitation), isTrue);+ final receipts = {+ for (final call in fake.calls)+ if (call.method == 'POST') call.body!['operationId'],+ };+ expect(receipts, hasLength(1));+ expect(i.joinError, isNull);+ });+}diff --git a/mobile/test/swarm/swarm_start_view_test.dart b/mobile/test/swarm/swarm_start_view_test.dartnew file mode 100644index 000000000..603964619--- /dev/null+++ b/mobile/test/swarm/swarm_start_view_test.dart@@ -0,0 +1,338 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/phone/tty_controls.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_start.dart';++import '../voice_fakes.dart';+import 'swarm_computers_fake.dart';+import 'swarm_fixture.dart';++/// Swarm Home's body before there is a Swarm to show: one screen per start+/// state, each with one button, over a scripted backend.+void main() {+ const mac = (name: 'MacBook Pro', away: false);++ /// The account's Swarm list answers [tabs]; its invitations, [invites].+ FakeSwarm backend({+ List<String> tabs = const [],+ List<Map<String, dynamic>> invites = const [],+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ for (final id in tabs) {'id': id, 'name': 'Swarm $id', 'ownerId': me},+ ],+ 'next': null,+ };+ for (final id in tabs) {+ fake.routes['/api/super-tabs/$id/parts'] = (_) => firstLoad(tabId: id);+ }+ fake.routes['/api/super-tabs/invitations'] = (_) => invites;+ return fake;+ }++ Map<String, dynamic> invite(+ String tabId,+ String name, {+ String role = 'collaborator',+ }) => {+ 'tabId': tabId,+ 'name': name,+ 'inviteId': 'invite-$tabId',+ 'role': role,+ 'expiresAt': 1893456000000,+ };++ /// Swarm Home as Home build A draws it: the start screen in place of its+ /// body while one applies, its own body otherwise.+ Future<({SwarmHost host, SwarmSession session})> pump(+ WidgetTester tester,+ FakeSwarm fake,+ SwarmComputers? computers, {+ bool read = true,+ }) async {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ computers: computers,+ )..foreground = false;+ addTearDown(host.dispose);+ final session = host.session!;+ if (read) await session.inbox.refresh();+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: Scaffold(+ body: Builder(+ builder: (context) => ListenableBuilder(+ listenable: session.inbox,+ builder: (context, _) =>+ swarmStartView(context, session) ??+ const Center(child: Text('Your Swarms')),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return (host: host, session: session);+ }++ Finder primary() => find.byType(TtyPrimaryButton);++ testWidgets('no computer at all: Connect a computer, which opens the steps '+ 'to add one', (tester) async {+ final computers = FakeComputers(const []);+ await pump(tester, backend(), computers, read: false);++ expect(find.text('No computer yet'), findsOneWidget);+ expect(primary(), findsOneWidget);+ expect(find.text('Try again'), findsNothing);++ await tester.tap(find.text('Connect a computer'));+ expect(computers.adds, 1);+ });++ testWidgets('no Swarm yet: what a Swarm is, and Show me how', (tester) async {+ await pump(tester, backend(), FakeComputers([mac]));++ expect(find.text('No Swarm yet'), findsOneWidget);+ expect(+ find.text(+ 'A Swarm is a team of agents that works on your projects. Start one '+ 'on your computer and it shows up here.',+ ),+ findsOneWidget,+ );+ expect(find.text('Invites to your email show up here.'), findsOneWidget);+ expect(primary(), findsOneWidget);++ await tester.tap(find.text('Show me how'));+ await tester.pumpAndSettle();++ expect(find.text('Start a Swarm'), findsOneWidget);+ expect(find.text('Open Harness on your computer.'), findsOneWidget);+ expect(find.text('Press ⌘S.'), findsOneWidget);+ expect(find.text('Name it and add your first project.'), findsOneWidget);+ expect(find.text("It shows up here when it's ready."), findsOneWidget);++ await tester.tap(find.text('Got it'));+ await tester.pumpAndSettle();+ expect(find.text('Start a Swarm'), findsNothing);+ expect(find.text('No Swarm yet'), findsOneWidget);+ });++ testWidgets('invited: the Swarm by name, the role offered, and Join', (+ tester,+ ) async {+ final fake = backend(invites: [invite('t-lab', 'Design Lab')]);+ final accepted = Completer<Object?>();+ var joined = false;+ fake.routes['/api/super-tabs/t-lab/commands'] = (_) async {+ await accepted.future;+ joined = true;+ return {'result': <String, dynamic>{}};+ };+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ if (joined)+ {'id': 't-lab', 'name': 'Design Lab', 'ownerId': 'person-o'},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/t-lab/parts'] = (_) =>+ firstLoad(tabId: 't-lab');+ await pump(tester, fake, FakeComputers([mac]));++ expect(find.text("You're invited to"), findsOneWidget);+ expect(find.text('Design Lab'), findsOneWidget);+ expect(find.text('You can collaborate'), findsOneWidget);+ expect(primary(), findsOneWidget);++ await tester.tap(find.text('Join Design Lab'));+ await tester.pump();+ expect(find.text('Joining…'), findsOneWidget);++ accepted.complete(null);+ await tester.pumpAndSettle();++ expect(fake.commands.single['type'], 'invite.accept');+ expect(find.text('Your Swarms'), findsOneWidget);+ });++ // Review of #1802 at bd73842: the ruling was the Swarm's name and the role.+ testWidgets('invited to view: says so; a role it does not know: says '+ 'nothing of it', (tester) async {+ final fake = backend(+ invites: [invite('t-lab', 'Design Lab', role: 'viewer')],+ );+ await pump(tester, fake, FakeComputers([mac]));++ expect(find.text('You can view'), findsOneWidget);+ expect(find.text('You can collaborate'), findsNothing);++ await tester.pumpWidget(const SizedBox());+ await pump(+ tester,+ backend(invites: [invite('t-lab', 'Design Lab', role: 'auditor')]),+ FakeComputers([mac]),+ );++ expect(find.text('Design Lab'), findsOneWidget);+ expect(find.textContaining('You can'), findsNothing);+ });++ // Review of #1802 at bd73842: invitations that could not be read showed+ // "No Swarm yet", as if there were none.+ testWidgets('invitations that could not be read: says so, and Try again '+ 'reads them again', (tester) async {+ final fake = backend(invites: [invite('t-lab', 'Design Lab')]);+ final read = fake.routes['/api/super-tabs/invitations']!;+ fake.routes['/api/super-tabs/invitations'] = (_) =>+ throw const SuperTabFailure(+ 'INTERNAL',+ 'Something went wrong.',+ statusCode: 500,+ );+ await pump(tester, fake, FakeComputers([mac]));++ expect(find.text("Couldn't check invitations"), findsOneWidget);+ expect(find.text('No Swarm yet'), findsNothing);+ expect(primary(), findsOneWidget);++ fake.routes['/api/super-tabs/invitations'] = read;+ await tester.tap(find.text('Try again'));+ await tester.pumpAndSettle();++ expect(find.text('Join Design Lab'), findsOneWidget);+ });++ testWidgets('a long Swarm name wraps, and is never cut', (tester) async {+ const name = 'Platform reliability and developer experience';+ await pump(+ tester,+ backend(invites: [invite('t-long', name)]),+ FakeComputers([mac]),+ );++ expect(+ tester.getSize(find.text(name)).height,+ greaterThan(2 * 28),+ reason: 'more than one line of the title',+ );+ });++ testWidgets('a Join that fails says why, and can be tried again', (+ tester,+ ) async {+ final fake = backend(invites: [invite('t-lab', 'Design Lab')]);+ fake.routes['/api/super-tabs/t-lab/commands'] = (_) =>+ throw const SuperTabFailure(+ 'INVITE_EXPIRED',+ 'This invitation has expired.',+ statusCode: 410,+ );+ await pump(tester, fake, FakeComputers([mac]));++ await tester.tap(find.text('Join Design Lab'));+ await tester.pumpAndSettle();++ expect(find.text('This invitation has expired.'), findsOneWidget);+ expect(find.text('Join Design Lab'), findsOneWidget);+ });++ testWidgets('Not now leaves the invitation for this session: no Swarm yet', (+ tester,+ ) async {+ final fake = backend(invites: [invite('t-lab', 'Design Lab')]);+ final app = await pump(tester, fake, FakeComputers([mac]));++ await tester.tap(find.text('Not now'));+ await tester.pumpAndSettle();++ expect(find.text('No Swarm yet'), findsOneWidget);+ expect(fake.commands, isEmpty, reason: 'nothing declined on the server');++ await app.session.inbox.refresh();+ await tester.pumpAndSettle();+ expect(find.text('No Swarm yet'), findsOneWidget, reason: 'read again');+ });++ group('Swarm turned off', () {+ Future<ExperimentalFeaturesStore> open(WidgetTester tester) async {+ final features = ExperimentalFeaturesStore(+ storage: MemoryKeyValueStore(),+ );+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => TextButton(+ onPressed: () => Navigator.of(context).push(+ MaterialPageRoute<void>(+ builder: (_) => SwarmIntroPage(features: features),+ ),+ ),+ child: const Text('Settings'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Settings'));+ await tester.pumpAndSettle();+ return features;+ }++ testWidgets('what Swarm does in three lines, and one button', (+ tester,+ ) async {+ await open(tester);++ expect(find.text('Your team of agents, on your phone'), findsOneWidget);+ expect(find.text('See what needs you'), findsOneWidget);+ expect(find.text('Answer in one tap'), findsOneWidget);+ expect(find.text('Brainstorm with your Buddy'), findsOneWidget);+ expect(find.text('Chat with your PM'), findsNothing);+ expect(primary(), findsOneWidget);+ });++ testWidgets('Turn on Swarm turns it on and goes back', (tester) async {+ final features = await open(tester);++ await tester.tap(find.text('Turn on Swarm'));+ await tester.pumpAndSettle();++ expect(features.isOn(PhoneExperiment.swarm), isTrue);+ expect(find.text('Your team of agents, on your phone'), findsNothing);+ });++ testWidgets('Not now goes back and leaves it off', (tester) async {+ final features = await open(tester);++ await tester.tap(find.text('Not now'));+ await tester.pumpAndSettle();++ expect(features.isOn(PhoneExperiment.swarm), isFalse);+ expect(find.text('Your team of agents, on your phone'), findsNothing);+ });+ });++ testWidgets('without the computers wired in, Home is as it was', (+ tester,+ ) async {+ await pump(tester, backend(), null);++ expect(find.text('Your Swarms'), findsOneWidget);+ });+}diff --git a/mobile/test/swarm/swarm_style_test.dart b/mobile/test/swarm/swarm_style_test.dartnew file mode 100644index 000000000..7b1b48cf0--- /dev/null+++ b/mobile/test/swarm/swarm_style_test.dart@@ -0,0 +1,207 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/shared/widgets/skeleton.dart';+import 'package:harness_mobile/swarm/swarm_style.dart';++/// [child] at the top left of a screen, as big as it asks to be.+Future<void> show(WidgetTester tester, Widget child) => tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Align(alignment: Alignment.topLeft, child: child),+ ),+ ),+);++void main() {+ group('a card of rows', () {+ testWidgets('is rounded at the card radius, 12', (tester) async {+ await show(tester, const SwarmGroup(children: [Text('a'), Text('b')]));++ final clip = tester.widget<ClipRRect>(+ find.descendant(+ of: find.byType(SwarmGroup),+ matching: find.byType(ClipRRect),+ ),+ );+ expect(clip.borderRadius, BorderRadius.circular(12));+ });+ });++ group('a caption', () {+ Future<double> top(WidgetTester tester, {required bool first}) async {+ await show(tester, SwarmCaption('Needs you', first: first));+ return tester.getTopLeft(find.text('Needs you')).dy -+ tester.getTopLeft(find.byType(SwarmCaption)).dy;+ }++ testWidgets('leaves 8 above the first on a screen, 24 above the rest', (+ tester,+ ) async {+ expect(await top(tester, first: true), 8);+ expect(await top(tester, first: false), 24);+ });++ testWidgets('is set in 13 points, a count beside it as well', (+ tester,+ ) async {+ await show(tester, const SwarmCaption('Needs you', count: 3));++ expect(tester.widget<Text>(find.text('Needs you')).style?.fontSize, 13);+ expect(find.text('3'), findsOneWidget);+ });+ });++ group('a count badge', () {+ testWidgets('is a pill 22 points tall', (tester) async {+ await show(tester, const UnconstrainedBox(child: SwarmBadge(3)));++ expect(tester.getSize(find.byType(SwarmBadge)).height, 22);+ final decoration = tester+ .widget<Container>(+ find.descendant(+ of: find.byType(SwarmBadge),+ matching: find.byType(Container),+ ),+ )+ .decoration;+ expect(decoration, isA<ShapeDecoration>());+ expect((decoration! as ShapeDecoration).shape, const StadiumBorder());+ });++ testWidgets('takes dark ink on the warning fill, white on the accent', (+ tester,+ ) async {+ await show(tester, const SwarmBadge(3, warn: true));+ expect(+ tester.widget<Text>(find.text('3')).style?.color,+ const Color(0xFF1A1200),+ );++ await show(tester, const SwarmBadge(3));+ expect(+ tester.widget<Text>(find.text('3')).style?.color,+ const Color(0xFFFFFFFF),+ );+ });++ testWidgets('keeps the room of its figure: 8 points each side', (+ tester,+ ) async {+ await show(tester, const UnconstrainedBox(child: SwarmBadge(1234)));++ final text = tester.getSize(find.text('1234')).width;+ expect(tester.getSize(find.byType(SwarmBadge)).width, text + 16);+ });+ });++ group('a button', () {+ Future<double> room(WidgetTester tester, SwarmButtonStyle style) async {+ await show(+ tester,+ SwarmButton(label: 'Open chat', style: style, onPressed: () {}),+ );+ return tester.getSize(find.byType(SwarmButton)).width -+ tester.getSize(find.text('Open chat')).width;+ }++ testWidgets('has 16 points of room either side, a link 12', (tester) async {+ expect(await room(tester, SwarmButtonStyle.plain), 2 * 16);+ expect(await room(tester, SwarmButtonStyle.fill), 2 * 16);+ expect(await room(tester, SwarmButtonStyle.link), 2 * 12);+ });++ testWidgets('rounds at 10, rimmed when plain', (tester) async {+ await show(tester, SwarmButton(label: 'Open chat', onPressed: () {}));++ final shape =+ tester+ .widget<Material>(+ find.descendant(+ of: find.byType(SwarmButton),+ matching: find.byType(Material),+ ),+ )+ .shape!+ as RoundedRectangleBorder;+ expect(shape.borderRadius, BorderRadius.circular(10));+ expect(shape.side, isNot(BorderSide.none));+ });++ testWidgets('writes the main action in white on the accent', (+ tester,+ ) async {+ await show(+ tester,+ SwarmButton(+ label: 'Open chat',+ style: SwarmButtonStyle.fill,+ onPressed: () {},+ ),+ );++ expect(+ tester.widget<Text>(find.text('Open chat')).style?.color,+ const Color(0xFFFFFFFF),+ );+ });+ });++ group('a person and a project', () {+ testWidgets("an avatar's initial is white on its colour", (tester) async {+ await show(tester, const SwarmAvatar(id: 'agent-1', name: 'Nova'));++ expect(+ tester.widget<Text>(find.text('N')).style?.color,+ const Color(0xFFFFFFFF),+ );+ });++ testWidgets("a project's tile rounds at the inset radius, 8", (+ tester,+ ) async {+ await show(tester, const SwarmProjectTile('Mobile'));++ final tile = tester.widget<Container>(+ find.descendant(+ of: find.byType(SwarmProjectTile),+ matching: find.byType(Container),+ ),+ );+ expect(+ (tile.decoration! as BoxDecoration).borderRadius,+ BorderRadius.circular(8),+ );+ });+ });++ group('a top bar', () {+ testWidgets('is 52 points tall, with a subtitle too', (tester) async {+ Future<double> height({String? subtitle}) async {+ await show(+ tester,+ SwarmTopBar(+ leading: const SizedBox.square(dimension: 44),+ title: 'Swarm',+ subtitle: subtitle,+ ),+ );+ return tester.getSize(find.byType(SwarmTopBar)).height;+ }++ expect(await height(), 52);+ expect(await height(subtitle: 'Mobile'), 52);+ });+ });++ group('a card row on its way', () {+ testWidgets("puts its mark 16 points in, as the real row's words are", (+ tester,+ ) async {+ await show(tester, SwarmSkeletonRows(id: 'rows', rows: 1));++ final row = find.byType(SwarmSkeletonRow);+ final mark = find.descendant(of: row, matching: find.byType(Skeleton));+ expect(tester.getTopLeft(mark.first).dx - tester.getTopLeft(row).dx, 16);+ });+ });+}diff --git a/mobile/test/swarm/swarm_task_rows_test.dart b/mobile/test/swarm/swarm_task_rows_test.dartnew file mode 100644index 000000000..48da22f8a--- /dev/null+++ b/mobile/test/swarm/swarm_task_rows_test.dart@@ -0,0 +1,500 @@+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/settings/experimental_features.dart';+import 'package:harness_mobile/shared/widgets/skeleton.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_home_view.dart';+import 'package:harness_mobile/swarm/swarm_page.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_task_status.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// The task status line on the phone's work rows (#2125, the mockup Tony+/// approved 10-29): under each task's name in the drawer, and after its+/// agent's name on the project sheet's work. Over a scripted backend: one+/// Swarm, project Mobile, where Nova waits on Tony in g-ask, waits for review+/// in g-review, Atlas works in g-work, and g-stranger waits on a person this+/// Swarm does not hold. With [second], another Swarm reuses the project's+/// id, Nova's agent id (as Orion) and g-ask's id, and does not hold Tony.+/// With [plain], Nova also waits on the person in g-plain, as an older+/// backend sends it: with no state.+void main() {+ const tony = 'person-tony';+ const other = 'tab-2';++ /// [now] is the test's clock: every age is from it.+ FakeSwarm backend(DateTime now, {bool second = false, bool plain = false}) {+ int ago(Duration age) => now.subtract(age).millisecondsSinceEpoch;+ const minute = Duration(minutes: 1);+ Map<String, dynamic> task(+ String id,+ String title,+ int number, {+ required String status,+ String worker = 'agent-builder',+ String? result,+ Duration? progress,+ Map<String, dynamic>? liveness,+ Map<String, dynamic>? leadAction,+ int sequence = 1,+ }) => {+ ...groupData(+ id,+ title: title,+ number: number,+ agentIds: [worker],+ lastMessageSequence: sequence,+ ),+ 'assignment': {+ 'id': 'attempt-$id',+ 'agentId': worker,+ 'status': status,+ 'result': result,+ 'progressAt': ?(progress == null ? null : ago(progress)),+ },+ 'liveness': ?liveness,+ 'leadAction': ?leadAction,+ };+ Map<String, dynamic> wait(String why, Duration since, {String? personId}) =>+ {+ 'state': 'waiting',+ 'why': why,+ 'since': ago(since),+ 'personId': ?personId,+ };++ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ if (second) {'id': other, 'name': 'Web Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-builder', displayName: 'Nova'),+ agent('agent-atlas', displayName: 'Atlas'),+ ],+ groups: [+ task(+ 'g-ask',+ 'Fix login',+ 4,+ status: 'needs_human',+ result: 'Ship it behind a flag?',+ liveness: wait('person', minute * 12, personId: tony),+ sequence: 9,+ ),+ task(+ 'g-review',+ 'Sync',+ 5,+ status: 'review',+ liveness: wait('review', minute * 3),+ leadAction: {'kind': 'post', 'at': ago(minute)},+ sequence: 8,+ ),+ task(+ 'g-work',+ 'Search page',+ 6,+ status: 'working',+ worker: 'agent-atlas',+ progress: minute * 4,+ sequence: 7,+ ),+ task(+ 'g-stranger',+ 'Docs',+ 7,+ status: 'needs_human',+ liveness: wait('person', minute * 2, personId: 'person-elsewhere'),+ sequence: 6,+ ),+ if (plain)+ groupData(+ 'g-plain',+ title: 'Plain',+ number: 8,+ status: 'needs_human',+ lastMessageSequence: 5,+ ),+ ],+ ),+ 'members': [part(me, 1, person(me)), part(tony, 1, person(tony))],+ };+ fake.routes['/api/super-tabs/$other/parts'] = (_) => {+ ...firstLoad(+ tabId: other,+ head: headData(id: other, name: 'Web Swarm'),+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'Cleo'),+ agent('agent-builder', displayName: 'Orion'),+ ],+ groups: [+ task(+ 'g-ask',+ 'Other login',+ 4,+ status: 'needs_human',+ liveness: wait('person', minute * 30, personId: tony),+ ),+ ],+ ),+ };+ for (final id in [tab, other]) {+ fake.routes['/api/super-tabs/$id/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$id/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$id/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$id/conversations/'] = (_) => {+ 'messages': <Object>[],+ 'next': null,+ };+ }+ return fake;+ }++ Future<SwarmHost> pump(WidgetTester tester, FakeSwarm fake) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmPage(),+ ),+ );+ await tester.pumpAndSettle();+ return host;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ /// Task [id]'s line as it reads, after its dot, under [within].+ String? line(WidgetTester tester, String id, {Finder? within}) {+ final found = within == null+ ? key('swarm-task-line-$id')+ : find.descendant(of: within, matching: key('swarm-task-line-$id'));+ if (found.evaluate().isEmpty) return null;+ return tester+ .widgetList<Text>(+ find.descendant(of: found, matching: find.byType(Text)),+ )+ .where((text) => text.key != ValueKey('swarm-task-mark-$id'))+ .map((text) => text.data!)+ .join();+ }++ /// The drawer, with [swarm]'s project Mobile's chats listed.+ Future<void> openChats(WidgetTester tester, {String swarm = tab}) async {+ await tester.tap(key('swarm-menu'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-drawer-chats-$swarm-$project'));+ await tester.pumpAndSettle();+ }++ /// [swarm]'s project sheet, over Home.+ Future<void> openSheet(WidgetTester tester, {String swarm = tab}) async {+ showSwarmProjectSheet(+ tester.element(find.byType(SwarmPage)),+ swarmId: swarm,+ projectId: project,+ );+ await tester.pumpAndSettle();+ }++ group('the drawer', () {+ testWidgets('each task under an open project has its line under its '+ 'name, its dot unheard; its project chat and leaderboard have none', (+ tester,+ ) async {+ await pump(tester, backend(clock.now()));+ await openChats(tester);++ for (final (id, text) in [+ ('g-ask', 'Waiting on person-tony · Ship it behind a flag? · 12m'),+ ('g-review', 'Waiting for review · 3m · PM posted 1m ago'),+ ('g-work', 'Working · 4m ago'),+ ]) {+ final row = key('swarm-drawer-chat-$id');+ expect(line(tester, id, within: row), text, reason: id);+ expect(+ tester.getTopLeft(key('swarm-task-line-$id')).dy,+ greaterThan(+ tester+ .getBottomLeft(+ find.descendant(+ of: row,+ matching: find.textContaining('#'),+ ),+ )+ .dy -+ 1,+ ),+ reason: '$id: the line is under the name',+ );+ }+ for (final id in [leadChat]) {+ expect(key('swarm-task-line-$id'), findsNothing, reason: id);+ }+ expect(+ find.descendant(+ of: key('swarm-drawer-leaderboard-$tab-$project'),+ matching: find.byType(SwarmTaskLine),+ ),+ findsNothing,+ );+ final handle = tester.ensureSemantics();+ expect(find.bySemanticsLabel(RegExp('●')), findsNothing);+ handle.dispose();+ });++ testWidgets('a person the Swarm does not hold is "a person": no name '+ 'from anywhere else', (tester) async {+ await pump(tester, backend(clock.now()));+ await openChats(tester);++ expect(line(tester, 'g-stranger'), 'Waiting on a person · 2m');+ expect(find.textContaining('person-elsewhere'), findsNothing);+ });++ testWidgets('its ages keep moving while the drawer is open', (+ tester,+ ) async {+ await pump(tester, backend(clock.now()));+ await openChats(tester);+ expect(+ line(tester, 'g-review'),+ 'Waiting for review · 3m · PM posted '+ '1m ago',+ );++ await tester.pump(const Duration(minutes: 1));+ expect(+ line(tester, 'g-review'),+ 'Waiting for review · 4m · PM posted '+ '2m ago',+ );+ expect(line(tester, 'g-work'), 'Working · 5m ago');+ });++ testWidgets('access revoked while it is open: every line goes with its '+ 'Swarm, and no timer is left', (tester) async {+ final fake = backend(clock.now());+ final host = await pump(tester, fake);+ await openChats(tester);+ expect(find.byType(SwarmTaskLine), findsWidgets);++ const refused = SuperTabFailure(+ 'FORBIDDEN',+ 'You cannot read this Swarm.',+ statusCode: 403,+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => throw refused;+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => throw refused;+ unawaited(host.session!.inbox.reader(tab)!.refresh());+ await tester.pumpAndSettle();++ expect(find.byType(SwarmTaskLine), findsNothing);+ expect(find.textContaining('Ship it behind a flag?'), findsNothing);+ expect(find.textContaining('person-tony'), findsNothing);+ // A minute on, nothing wakes for a row that is gone.+ await tester.pump(const Duration(minutes: 2));+ expect(tester.takeException(), isNull);+ });++ testWidgets('a read that fails keeps the lines it had, with no Loading, '+ 'and the next read moves them on', (tester) async {+ final fake = backend(clock.now());+ final host = await pump(tester, fake);+ await openChats(tester);+ final reader = host.session!.inbox.reader(tab)!;++ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ throw const SuperTabFailure('UNAVAILABLE', 'Down', statusCode: 503);+ unawaited(reader.refresh());+ await tester.pumpAndSettle();+ expect(+ line(tester, 'g-review'),+ 'Waiting for review · 3m · PM posted 1m ago',+ );+ expect(find.byType(Skeleton), findsNothing);++ // The task went quiet: the next read says so at once.+ final at = clock.now();+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part('g-review', 40, {+ ...groupData('g-review', title: 'Sync', number: 5),+ 'assignment': {+ 'id': 'attempt-g-review',+ 'agentId': 'agent-builder',+ 'status': 'working',+ },+ 'liveness': {+ 'state': 'quiet',+ 'why': 'silent',+ 'since': at+ .subtract(const Duration(minutes: 20))+ .millisecondsSinceEpoch,+ },+ 'lastMessageSequence': 8,+ }),+ ],+ );+ unawaited(reader.refresh());+ await tester.pumpAndSettle();+ expect(line(tester, 'g-review'), 'Quiet 20m');+ });++ testWidgets('with two Swarms, each task names only who its own Swarm '+ 'holds, though they share ids', (tester) async {+ await pump(tester, backend(clock.now(), second: true));+ // Both Swarms have a g-ask: each row reads its own, one Swarm listed at+ // a time.+ await openChats(tester);+ expect(key('swarm-drawer-chat-g-ask'), findsOneWidget);+ expect(+ line(tester, 'g-ask'),+ 'Waiting on person-tony · Ship it behind a flag? · 12m',+ );++ await tester.tap(key('swarm-drawer-chats-$tab-$project'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-drawer-chats-$other-$project'));+ await tester.pumpAndSettle();+ expect(key('swarm-drawer-chat-g-ask'), findsOneWidget);+ expect(line(tester, 'g-ask'), 'Waiting on a person · 30m');+ expect(find.textContaining('person-tony'), findsNothing);+ });+ });++ group('the project sheet', () {+ testWidgets("each task's row leads with its agent, then its line; "+ 'work with no status keeps its words', (tester) async {+ await pump(tester, backend(clock.now(), plain: true));+ await openSheet(tester);++ for (final (id, text) in [+ (+ 'g-ask',+ 'Nova · Waiting on person-tony · Ship it behind a flag? · 12m',+ ),+ ('g-review', 'Nova · Waiting for review · 3m · PM posted 1m ago'),+ ('g-work', 'Atlas · Working · 4m ago'),+ ]) {+ expect(+ line(tester, id, within: key('swarm-conversation-$id')),+ text,+ reason: id,+ );+ }+ // An older backend's wait has no state: its words as before.+ expect(key('swarm-task-line-g-plain'), findsNothing);+ expect(+ find.descendant(+ of: key('swarm-conversation-g-plain'),+ matching: find.text('Nova · Needs human'),+ ),+ findsOneWidget,+ );+ });++ testWidgets("another Swarm's sheet names its own agent for a reused id, "+ 'and not a person it does not hold', (tester) async {+ await pump(tester, backend(clock.now(), second: true));+ await openSheet(tester, swarm: other);++ expect(+ line(tester, 'g-ask', within: key('swarm-conversation-g-ask')),+ 'Orion · Waiting on a person · 30m',+ );+ // Home under the sheet is the first Swarm's; the sheet is the other's.+ for (final name in ['Nova', 'person-tony']) {+ expect(+ find.descendant(+ of: find.byType(SwarmProjectSheet),+ matching: find.textContaining(name),+ ),+ findsNothing,+ reason: name,+ );+ }+ });++ testWidgets('its ages keep moving while it is open', (tester) async {+ await pump(tester, backend(clock.now()));+ await openSheet(tester);++ await tester.pump(const Duration(minutes: 1));+ expect(line(tester, 'g-work'), 'Atlas · Working · 5m ago');+ });+ });++ test('a Home kept for a cold start keeps no task status: no question, no '+ 'state, no stale line', () {+ final now = DateTime.utc(2026, 10, 29, 12);+ final snapshot = SuperTabSnapshot.fromJson({+ ...headData(),+ 'people': [person(me)],+ 'agents': [agent('agent-builder', displayName: 'Nova')],+ 'conversations': [+ {+ ...groupData('g-ask', title: 'Fix login', number: 4),+ 'assignment': {+ 'id': 'attempt-g-ask',+ 'agentId': 'agent-builder',+ 'status': 'working',+ 'result': 'Ship it behind a flag?',+ 'progressAt': now.millisecondsSinceEpoch,+ },+ 'liveness': {+ 'state': 'waiting',+ 'why': 'person',+ 'since': now.millisecondsSinceEpoch,+ 'personId': me,+ },+ 'leadAction': {'kind': 'post', 'at': now.millisecondsSinceEpoch},+ },+ ],+ });+ expect(swarmTaskStatus(snapshot.conversations.single, now), isNotNull);++ final kept = SuperTabSnapshot.fromJson(+ swarmHomeSwarm(snapshot, const {}).state,+ );+ final chat = kept.conversations.single;+ expect(swarmTaskStatus(chat, now), isNull);+ expect(chat.liveness, isNull);+ expect(chat.leadAction, isNull);+ expect(chat.assignment?['result'], isNull);+ });+}diff --git a/mobile/test/swarm/swarm_task_status_model_test.dart b/mobile/test/swarm/swarm_task_status_model_test.dartnew file mode 100644index 000000000..e1272079b--- /dev/null+++ b/mobile/test/swarm/swarm_task_status_model_test.dart@@ -0,0 +1,43 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';++import 'swarm_fixture.dart';++/// A chat carries what the server last found about its task, as the+/// desktop's model does (desktop_parity_test): whether it waits on purpose or+/// is stuck, and its Product Manager's last action on it.+void main() {+ test(+ "a chat keeps its task's state and its Product Manager's last action",+ () {+ final chat = SuperTabConversation.fromJson({+ ...groupData('g1', title: 'Fix login'),+ 'liveness': {'state': 'quiet', 'why': 'silent', 'since': 1761714000000},+ 'leadAction': {'kind': 'post', 'at': 1761714600000},+ });++ expect(chat.liveness, {+ 'state': 'quiet',+ 'why': 'silent',+ 'since': 1761714000000,+ });+ expect(chat.leadAction, {'kind': 'post', 'at': 1761714600000});+ },+ );++ test('a task at work, an older backend, or a value that is no map, has '+ 'none', () {+ for (final row in [+ groupData('g1', title: 'Fix login'),+ {+ ...groupData('g1', title: 'Fix login'),+ 'liveness': 'quiet',+ 'leadAction': ['post'],+ },+ ]) {+ final chat = SuperTabConversation.fromJson(row);+ expect(chat.liveness, isNull);+ expect(chat.leadAction, isNull);+ }+ });+}diff --git a/mobile/test/swarm/swarm_task_status_shots_test.dart b/mobile/test/swarm/swarm_task_status_shots_test.dartnew file mode 100644index 000000000..bbbf63cf4--- /dev/null+++ b/mobile/test/swarm/swarm_task_status_shots_test.dart@@ -0,0 +1,287 @@+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_page.dart';+import 'package:harness_mobile/swarm/swarm_project_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// The drawer's and the project sheet's task lines in both phone themes, for+/// the pull request, written to the folder `SWARM_TASK_STATUS_SHOTS` names+/// (run this file alone, on a Mac). Scripted data only.+final shots = Platform.environment['SWARM_TASK_STATUS_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('task lines in the drawer and the project sheet, both themes', (+ tester,+ ) async {+ await tester.binding.setSurfaceSize(const Size(390, 844));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final now = clock.now();+ int ago(Duration age) => now.subtract(age).millisecondsSinceEpoch;+ const minute = Duration(minutes: 1);+ Map<String, dynamic> task(+ String id,+ String title,+ int number, {+ String? worker,+ String? status,+ String? result,+ Duration? progress,+ Map<String, dynamic>? liveness,+ Map<String, dynamic>? leadAction,+ required int sequence,+ }) => {+ ...groupData(+ id,+ title: title,+ number: number,+ agentIds: [?worker],+ lastMessageSequence: sequence,+ ),+ 'assignment': worker == null+ ? null+ : {+ 'id': 'attempt-$id',+ 'agentId': worker,+ 'status': status,+ 'result': result,+ 'progressAt': ?(progress == null ? null : ago(progress)),+ },+ 'liveness': ?liveness,+ 'leadAction': ?leadAction,+ };+ Map<String, dynamic> state(+ String state,+ String why,+ Duration since, {+ String? personId,+ }) => {+ 'state': state,+ 'why': why,+ 'since': ago(since),+ 'personId': ?personId,+ };++ 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(+ head: headData(+ name: 'OpenHarness',+ projects: [+ {+ 'id': project,+ 'name': 'openharness',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-nova', displayName: 'Nova'),+ agent('agent-lark', displayName: 'Lark'),+ agent('agent-atlas', displayName: 'Atlas'),+ ],+ groups: [+ task(+ 'g-ask',+ 'Mobile: task status line',+ 1036,+ worker: 'agent-lark',+ status: 'needs_human',+ result: 'mockup OK?',+ liveness: state(+ 'waiting',+ 'person',+ minute * 12,+ personId: 'person-tony',+ ),+ sequence: 9,+ ),+ task(+ 'g-review',+ 'Buddy replaces Chat with PM',+ 1031,+ worker: 'agent-nova',+ status: 'review',+ liveness: state('waiting', 'review', minute * 3),+ leadAction: {'kind': 'post', 'at': ago(minute)},+ sequence: 8,+ ),+ task(+ 'g-quiet',+ 'Leaderboard tabs',+ 1029,+ worker: 'agent-atlas',+ status: 'working',+ liveness: state('quiet', 'silent', minute * 34),+ leadAction: {'kind': 'assign', 'at': ago(minute)},+ sequence: 7,+ ),+ task(+ 'g-work',+ 'WS Phase 2b',+ 1027,+ worker: 'agent-nova',+ status: 'working',+ progress: minute * 4,+ sequence: 6,+ ),+ task(+ 'g-queued',+ 'Swarm machines probe',+ 1025,+ liveness: state('waiting', 'queued', minute * 25),+ leadAction: {'kind': 'route', 'at': ago(minute * 2)},+ sequence: 5,+ ),+ task(+ 'g-lost',+ 'Desktop release notes',+ 1023,+ worker: 'agent-atlas',+ status: 'working',+ liveness: state('orphaned', 'lost', minute * 5),+ sequence: 4,+ ),+ ],+ ),+ 'members': [+ part(me, 1, person(me)),+ part('person-tony', 1, {+ ...person('person-tony'),+ 'email': '[email protected]',+ }),+ ],+ };+ 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': [+ {+ 'id': 'm1',+ 'projectName': 'openharness',+ 'conversationId': 'g-ask',+ 'conversationTitle': 'Mobile: task status line',+ 'messageId': 'msg-1',+ 'leadName': 'River',+ 'text': 'Can you check the mockup?',+ },+ ],+ };+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => me,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ await host.session!.inbox.refresh();+ 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 SwarmPage(),+ ),+ ),+ );+ await tester.pumpAndSettle();+ Future<void> capture(String name) => tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File(+ '$shots/task-status-$name-${brightness.name}.png',+ ).writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });+ await tester.tap(find.byKey(const ValueKey('swarm-menu')));+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('swarm-drawer-chats-$tab-$project')),+ );+ await tester.pumpAndSettle();+ await tester.drag(find.byType(ListView).last, const Offset(0, -160));+ await tester.pumpAndSettle();+ await capture('drawer');+ await tester.tap(find.byKey(const ValueKey('swarm-drawer-close')));+ await tester.pumpAndSettle();+ showSwarmProjectSheet(+ tester.element(find.byType(SwarmPage)),+ swarmId: tab,+ projectId: project,+ );+ await tester.pumpAndSettle();+ await capture('sheet');+ await tester.pumpWidget(const SizedBox());+ host.dispose();+ account.dispose();+ }+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_task_status_test.dart b/mobile/test/swarm/swarm_task_status_test.dartnew file mode 100644index 000000000..2eb64dfab--- /dev/null+++ b/mobile/test/swarm/swarm_task_status_test.dart@@ -0,0 +1,601 @@+import 'dart:io';++import 'package:clock/clock.dart';+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_task_status.dart';++import 'swarm_fixture.dart';++/// The line under each task row, as the desktop's (#957, #2125, the mockup+/// Ken approved): whether the task is moving, waiting on purpose and for+/// what, or stuck, and what the PM did about it. The same data reads the+/// same words as `desktop/test/super_tab_task_status_test.dart`.+void main() {+ final now = DateTime.utc(2026, 10, 29, 12);+ int ago(Duration age) => now.subtract(age).millisecondsSinceEpoch;+ const minute = Duration(minutes: 1);++ SuperTabConversation task({+ String? status = 'working',+ Object? result,+ Duration? progress,+ Object? liveness,+ Object? leadAction,+ }) => SuperTabConversation.fromJson({+ ...groupData('g', title: 'Task', number: 931),+ 'assignment': status == null+ ? null+ : {+ 'id': 'a',+ 'agentId': 'w',+ 'status': status,+ 'result': result,+ 'progressAt': ?(progress == null ? null : ago(progress)),+ },+ 'liveness': ?liveness,+ 'leadAction': ?leadAction,+ });+ Map<String, dynamic> state(+ String state,+ String why,+ Duration since, {+ String? personId,+ }) => {+ 'state': state,+ 'why': why,+ 'since': ago(since),+ 'personId': ?personId,+ };+ String? person(String id) => id == 'ken' ? 'Ken' : null;++ /// The line as it reads, its parts in order.+ String? read(SuperTabConversation group, {DateTime? at}) =>+ switch (swarmTaskStatus(group, at ?? now, personName: person)) {+ final status? => swarmTaskStatusText(status),+ null => null,+ };+ SwarmTaskMark? mark(SuperTabConversation group) =>+ swarmTaskStatus(group, now, personName: person)?.mark;++ group('the line reads as the desktop\'s', () {+ test('a working task: how long since its agent last reported', () {+ expect(read(task(progress: minute * 4)), 'Working · 4m ago');+ expect(mark(task(progress: minute * 4)), SwarmTaskMark.working);+ expect(+ read(task(progress: const Duration(seconds: 20))),+ 'Working · just now',+ );+ // A planned task is at work too.+ expect(+ read(task(status: 'planned', progress: minute * 2)),+ 'Working · 2m ago',+ );+ });++ test('waiting on a person: who, their question and how long', () {+ final asked = task(+ status: 'needs_human',+ result: 'mockup OK?',+ liveness: state('waiting', 'person', minute * 12, personId: 'ken'),+ );+ expect(read(asked), 'Waiting on Ken · mockup OK? · 12m');+ expect(mark(asked), SwarmTaskMark.needsInput);+ // A person who has left, or one this read does not name, is still+ // waited on, unnamed.+ expect(+ read(+ task(+ status: 'needs_human',+ liveness: state('waiting', 'person', minute * 12, personId: 'gone'),+ ),+ ),+ 'Waiting on a person · 12m',+ );+ // A blank question asks nothing.+ expect(+ read(+ task(+ status: 'needs_human',+ result: ' ',+ liveness: state('waiting', 'person', minute * 12, personId: 'ken'),+ ),+ ),+ 'Waiting on Ken · 12m',+ );+ });++ test('queued for a free machine, with the PM retrying', () {+ final queued = task(+ status: null,+ liveness: state('waiting', 'queued', minute * 25),+ leadAction: {'kind': 'route', 'at': ago(minute * 2)},+ );+ expect(+ read(queued),+ 'Queued: no free machine · 25m · PM retrying 2m ago',+ );+ expect(mark(queued), SwarmTaskMark.unknown);+ });++ test('quiet, with what the PM did once it went quiet', () {+ final reassigned = task(+ liveness: state('quiet', 'silent', minute * 34),+ leadAction: {'kind': 'assign', 'at': ago(minute)},+ );+ expect(read(reassigned), 'Quiet 34m · PM reassigned it 1m ago');+ expect(mark(reassigned), SwarmTaskMark.failed);+ // What the PM did before it went quiet is not handling it.+ expect(+ read(+ task(+ liveness: state('quiet', 'silent', minute * 34),+ leadAction: {'kind': 'post', 'at': ago(minute * 40)},+ ),+ ),+ 'Quiet 34m',+ );+ expect(+ read(+ task(+ liveness: state('quiet', 'silent', minute * 34),+ leadAction: {'kind': 'post', 'at': ago(minute)},+ ),+ ),+ 'Quiet 34m · PM posted 1m ago',+ );+ expect(+ read(+ task(+ liveness: state('quiet', 'silent', minute * 34),+ leadAction: {'kind': 'start', 'at': ago(minute * 3)},+ ),+ ),+ 'Quiet 34m · PM retrying 3m ago',+ );+ // An action the desktop does not name says nothing.+ expect(+ read(+ task(+ liveness: state('quiet', 'silent', minute * 34),+ leadAction: {'kind': 'wave', 'at': ago(minute)},+ ),+ ),+ 'Quiet 34m',+ );+ });++ test('a reassigned task that is working again shows its agent\'s '+ 'progress, not the PM\'s old action', () {+ expect(+ read(+ task(+ progress: minute * 2,+ leadAction: {'kind': 'assign', 'at': ago(minute * 3)},+ ),+ ),+ 'Working · 2m ago',+ );+ });++ test('waiting on a review, a new revision, a blocker or a start', () {+ final cases = {+ task(+ status: 'review',+ liveness: state('waiting', 'review', minute * 3),+ ): (+ 'Waiting for review · 3m',+ SwarmTaskMark.needsInput,+ ),+ task(liveness: state('waiting', 'revision', minute * 3)): (+ 'Waiting for the new revision · 3m',+ SwarmTaskMark.needsInput,+ ),+ task(+ status: 'blocked',+ result: 'Needs a token',+ liveness: state('waiting', 'blocked', minute * 5),+ ): (+ 'Blocked · Needs a token · 5m',+ SwarmTaskMark.needsInput,+ ),+ task(status: 'blocked', liveness: state('waiting', 'blocked', minute)):+ ('Blocked · 1m', SwarmTaskMark.needsInput),+ task(status: null, liveness: state('waiting', 'starting', minute * 2)):+ ('Starting its agent · 2m', SwarmTaskMark.starting),+ };+ for (final MapEntry(key: group, value: (text, kind)) in cases.entries) {+ expect(read(group), text);+ expect(mark(group), kind, reason: text);+ }+ });++ test('stuck with nobody on it, and why', () {+ final cases = {+ 'removed': 'Stuck: its agent was removed · 5m',+ 'lost': 'Stuck: its agent stopped · 5m',+ 'start-failed': 'Stuck: its agent could not start · 5m',+ 'unstarted': 'Stuck: its agent has not started · 5m',+ };+ for (final MapEntry(key: why, value: text) in cases.entries) {+ final stuck = task(liveness: state('orphaned', why, minute * 5));+ expect(read(stuck), text, reason: why);+ expect(mark(stuck), SwarmTaskMark.failed, reason: why);+ }+ });++ test('ages read in seconds\' place under a minute, then minutes, hours '+ 'and days', () {+ final quiet = task(liveness: state('quiet', 'silent', Duration.zero));+ for (final (age, text) in [+ (const Duration(seconds: 30), 'Quiet <1m'),+ (minute * 59, 'Quiet 59m'),+ (const Duration(hours: 2, minutes: 5), 'Quiet 2h'),+ (const Duration(days: 3, hours: 1), 'Quiet 3d'),+ ]) {+ expect(read(quiet, at: now.add(age)), text);+ }+ // A clock behind the server's never reads a negative age.+ expect(read(quiet, at: now.subtract(minute)), 'Quiet <1m');+ });++ test('nothing for finished work, a group without work, a wait an older '+ 'backend sent no state for, or a state the phone does not know', () {+ for (final group in [+ task(status: 'done', progress: minute),+ task(status: null),+ task(status: 'needs_human', progress: minute),+ task(liveness: state('waiting', 'teleporting', minute)),+ task(liveness: state('sleeping', 'silent', minute)),+ ]) {+ expect(swarmTaskStatus(group, now), isNull);+ }+ });+ });++ group('a part the server sent wrong draws nothing rather than guessing', () {+ test('a state with no time, or a time that is no number', () {+ for (final liveness in [+ {'state': 'quiet', 'why': 'silent'},+ {'state': 'quiet', 'why': 'silent', 'since': '34 minutes'},+ {'state': 7, 'why': 'silent', 'since': ago(minute)},+ ]) {+ expect(swarmTaskStatus(task(liveness: liveness), now), isNull);+ }+ // A working task's progress that is no number.+ expect(+ swarmTaskStatus(+ SuperTabConversation.fromJson({+ ...groupData('g', title: 'Task'),+ 'assignment': {'status': 'working', 'progressAt': 'soon'},+ }),+ now,+ ),+ isNull,+ );+ });++ test(+ 'a PM action with no time, a question or a person that is no text',+ () {+ expect(+ read(+ task(+ liveness: state('quiet', 'silent', minute * 34),+ leadAction: {'kind': 'post'},+ ),+ ),+ 'Quiet 34m',+ );+ expect(+ read(+ task(+ status: 'needs_human',+ result: ['mockup OK?'],+ liveness: {+ ...state('waiting', 'person', minute * 12),+ 'personId': 42,+ },+ ),+ ),+ 'Waiting on a person · 12m',+ );+ },+ );+ });++ group('drawn', () {+ Widget app(Widget child, {double scale = 1}) => MaterialApp(+ home: MediaQuery(+ data: MediaQueryData(textScaler: TextScaler.linear(scale)),+ child: Material(child: child),+ ),+ );++ /// The line as it reads on screen: its words, in order, after its dot.+ String line(WidgetTester tester) => tester+ .widgetList<Text>(+ find.descendant(+ of: find.byKey(const ValueKey('swarm-task-line-g')),+ matching: find.byType(Text),+ ),+ )+ .where((text) => text.key != const ValueKey('swarm-task-mark-g'))+ .map((text) => text.data!)+ .join();++ testWidgets('its dot, then its words, the dot unheard', (tester) async {+ await withClock(+ Clock.fixed(now),+ () => tester.pumpWidget(+ app(+ SwarmTaskLine(+ task(+ status: 'needs_human',+ result: 'mockup OK?',+ liveness: state(+ 'waiting',+ 'person',+ minute * 12,+ personId: 'ken',+ ),+ ),+ personName: person,+ ),+ ),+ ),+ );+ expect(line(tester), 'Waiting on Ken · mockup OK? · 12m');+ expect(find.byKey(const ValueKey('swarm-task-mark-g')), findsOneWidget);+ final handle = tester.ensureSemantics();+ expect(+ find.bySemanticsLabel(RegExp('●')),+ findsNothing,+ reason: 'the words say what the dot shows',+ );+ handle.dispose();+ });++ testWidgets('a line the row cuts short loses its reason, never its age', (+ tester,+ ) async {+ final group = task(+ status: 'needs_human',+ result:+ 'Please approve the production deployment and confirm the '+ 'rollback plan',+ liveness: state('waiting', 'person', minute * 12, personId: 'ken'),+ leadAction: {'kind': 'post', 'at': ago(minute * 2)},+ );+ for (final scale in [1.0, 2.0]) {+ await withClock(+ Clock.fixed(now),+ () => tester.pumpWidget(+ app(+ Center(+ child: SizedBox(+ width: 180 * scale,+ child: SwarmTaskLine(group, personName: person),+ ),+ ),+ scale: scale,+ ),+ ),+ );+ RenderParagraph part(String text) =>+ tester.renderObject<RenderParagraph>(find.text(text));+ expect(part(' · 12m').didExceedMaxLines, isFalse, reason: '×$scale');+ expect(+ part(+ 'Waiting on Ken · Please approve the production deployment and '+ 'confirm the rollback plan',+ ).didExceedMaxLines,+ isTrue,+ reason: '×$scale',+ );+ expect(tester.takeException(), isNull);+ }+ });++ // In tests every glyph is a square of the font's size (13 points): these+ // rows fit their whole line, with room to spare, at either text size.+ testWidgets('a short part leaves its room to the other: a line that fits '+ 'is never cut', (tester) async {+ // Room for the widest row at twice the text size.+ await tester.binding.setSurfaceSize(const Size(1800, 600));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final cases = {+ // A short reason, a long PM action.+ task(+ liveness: state('quiet', 'silent', minute * 34),+ leadAction: {'kind': 'assign', 'at': ago(minute)},+ ): (+ width: 700.0,+ parts: ['Quiet', ' 34m', ' · PM reassigned it 1m ago'],+ ),+ // A long reason, a short PM action.+ task(+ status: 'blocked',+ result: 'Needs the staging token',+ liveness: state('waiting', 'blocked', minute * 5),+ leadAction: {'kind': 'post', 'at': ago(minute)},+ ): (+ width: 800.0,+ parts: [+ 'Blocked · Needs the staging token',+ ' · 5m',+ ' · PM posted 1m ago',+ ],+ ),+ };+ for (final MapEntry(key: group, value: (:width, :parts))+ in cases.entries) {+ for (final scale in [1.0, 2.0]) {+ await withClock(+ Clock.fixed(now),+ () => tester.pumpWidget(+ app(+ Center(+ child: SizedBox(+ width: width * scale,+ child: SwarmTaskLine(group),+ ),+ ),+ scale: scale,+ ),+ ),+ );+ for (final text in parts) {+ expect(+ tester+ .renderObject<RenderParagraph>(find.text(text))+ .didExceedMaxLines,+ isFalse,+ reason: '"$text" ×$scale',+ );+ }+ expect(tester.takeException(), isNull);+ }+ }+ });++ testWidgets('when neither fits, the reason and what the PM did are both '+ 'cut, never the age', (tester) async {+ final group = task(+ status: 'blocked',+ result: 'Needs the staging token and the release signing key',+ liveness: state('waiting', 'blocked', minute * 5),+ leadAction: {'kind': 'assign', 'at': ago(minute)},+ );+ await withClock(+ Clock.fixed(now),+ () => tester.pumpWidget(+ app(Center(child: SizedBox(width: 400, child: SwarmTaskLine(group)))),+ ),+ );+ RenderParagraph part(String text) =>+ tester.renderObject<RenderParagraph>(find.text(text));+ expect(part(' · 5m').didExceedMaxLines, isFalse);+ expect(+ part('Blocked · Needs the staging token and the release signing key')+ .didExceedMaxLines,+ isTrue,+ );+ expect(part(' · PM reassigned it 1m ago').didExceedMaxLines, isTrue);+ expect(tester.takeException(), isNull);+ });++ testWidgets('a name before the line, as a project\'s work row leads with '+ 'its agent, gives way with the reason', (tester) async {+ await withClock(+ Clock.fixed(now),+ () => tester.pumpWidget(+ app(+ SwarmTaskLine(+ task(liveness: state('waiting', 'review', minute * 3)),+ lead: 'Nova',+ ),+ ),+ ),+ );+ expect(line(tester), 'Nova · Waiting for review · 3m');+ });++ testWidgets('its ages keep moving on their own, the state\'s and the '+ 'PM\'s, with no other rebuild; gone with its row, no timer is left', (+ tester,+ ) async {+ var at = now;+ final group = task(+ liveness: state('quiet', 'silent', minute * 34),+ leadAction: {'kind': 'post', 'at': ago(minute)},+ );+ await withClock(Clock(() => at), () async {+ await tester.pumpWidget(app(SwarmTaskLine(group)));+ expect(line(tester), 'Quiet 34m · PM posted 1m ago');+ for (final expected in [+ 'Quiet 35m · PM posted 2m ago',+ 'Quiet 36m · PM posted 3m ago',+ ]) {+ at = at.add(minute);+ await tester.pump(minute + const Duration(milliseconds: 2));+ expect(line(tester), expected);+ }+ await tester.pumpWidget(const SizedBox());+ });+ // The test binding fails a test that leaves a timer pending.+ });++ testWidgets('a working task\'s age moves too, from "just now"', (+ tester,+ ) async {+ var at = now;+ final group = task(progress: const Duration(seconds: 30));+ await withClock(Clock(() => at), () async {+ await tester.pumpWidget(app(SwarmTaskLine(group)));+ expect(line(tester), 'Working · just now');+ at = at.add(const Duration(seconds: 31));+ await tester.pump(const Duration(seconds: 31));+ expect(line(tester), 'Working · 1m ago');+ await tester.pumpWidget(const SizedBox());+ });+ });++ testWidgets('a task with no status draws nothing and keeps no timer', (+ tester,+ ) async {+ await withClock(+ Clock.fixed(now),+ () => tester.pumpWidget(app(SwarmTaskLine(task(status: 'done')))),+ );+ expect(find.byKey(const ValueKey('swarm-task-line-g')), findsNothing);+ expect(find.byKey(const ValueKey('swarm-task-mark-g')), findsNothing);+ });++ testWidgets('a row whose task changes under it reads the new task at '+ 'once', (tester) async {+ Future<void> show(SuperTabConversation group) => withClock(+ Clock.fixed(now),+ () => tester.pumpWidget(app(SwarmTaskLine(group))),+ );+ await show(task(liveness: state('quiet', 'silent', minute * 34)));+ expect(line(tester), 'Quiet 34m');+ await show(task(progress: minute));+ expect(line(tester), 'Working · 1m ago');+ await show(task(status: 'done'));+ expect(find.byKey(const ValueKey('swarm-task-line-g')), findsNothing);+ await tester.pumpWidget(const SizedBox());+ });+ });++ // The desktop's words for each wait and stuck state, read from its model:+ // a state added or reworded there fails here until the phone says the same.+ test('every wait and stuck state the desktop\'s model names reads the '+ 'same words and mark on the phone', () {+ final source = File('../desktop/lib/super_tabs/task_status.dart');+ if (!source.existsSync()) {+ throw StateError(+ '${source.path} missing — run from mobile/ in the monorepo',+ );+ }+ final cases = RegExp(+ r"\('(\w+)', '([\w-]+)'\) => \(\s*HarnessActivity\.(\w+),\s*'([^']*)',?\s*\)",+ ).allMatches(source.readAsStringSync()).toList();+ // review, revision, queued, starting, and three ways to be stuck: fewer+ // means the desktop's table changed shape and this reads too little.+ expect(cases.length, greaterThanOrEqualTo(7));+ for (final match in cases) {+ final [state!, why!, activity!, words!] = [+ for (final i in [1, 2, 3, 4]) match.group(i),+ ];+ final status = swarmTaskStatus(+ task(liveness: {'state': state, 'why': why, 'since': ago(minute * 5)}),+ now,+ );+ expect(status?.reason, words, reason: '$state/$why');+ expect(status?.mark.name, activity, reason: '$state/$why');+ }+ });+}diff --git a/mobile/test/swarm/swarm_thread_model_test.dart b/mobile/test/swarm/swarm_thread_model_test.dartnew file mode 100644index 000000000..b7ae9e972--- /dev/null+++ b/mobile/test/swarm/swarm_thread_model_test.dart@@ -0,0 +1,145 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';++import 'swarm_fixture.dart';++/// Chat threads (#2132), read as the desktop's model reads them+/// (desktop_parity_test): a chat's newest message in its main stream, a+/// message's thread, and a page's thread summaries. The phone has no thread+/// view yet, so a reply only in its thread stays in the chat, but unread+/// follows the desktop's main-stream rule (PM, 10-29).+void main() {+ Map<String, dynamic> chat({required int last, int? main}) => {+ ...groupData('g1', title: 'Fix login', lastMessageSequence: last),+ 'lastMainSequence': ?main,+ };++ Map<String, dynamic> message(+ String id,+ int sequence, {+ String? thread,+ Object? alsoInChat,+ }) => {+ 'id': id,+ 'conversationId': 'g1',+ 'text': 'hello',+ 'sequence': sequence,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'Builder'},+ 'thread': ?thread,+ 'alsoInChat': ?alsoInChat,+ };++ group('unread counts from the main stream', () {+ /// What a chat read through [read] shows, as the desktop's+ /// `SuperTabController.unread` counts it.+ bool unread(Map<String, dynamic> row, {required int read}) =>+ SuperTabConversation.fromJson(row).mainSequence > read;++ test('a reply only in its thread leaves a read chat read', () {+ final group = SuperTabConversation.fromJson(chat(last: 11, main: 10));++ expect(group.lastMessageSequence, 11);+ expect(group.lastMainSequence, 10);+ expect(group.mainSequence, 10);+ expect(unread(chat(last: 11, main: 10), read: 10), isFalse);+ });++ test('a message in the main stream, or a reply also sent to it, makes '+ 'it unread', () {+ // A new top-level message, then a thread reply also sent to the chat:+ // the server moves the main stream for both (backend parts/commit.ts).+ expect(unread(chat(last: 12, main: 12), read: 10), isTrue);+ expect(unread(chat(last: 13, main: 13), read: 12), isTrue);+ });++ test('a backend before threads, or a chat with no message since, '+ 'counts every message', () {+ final group = SuperTabConversation.fromJson(chat(last: 7));++ expect(group.lastMainSequence, isNull);+ expect(group.mainSequence, 7);+ expect(unread(chat(last: 7), read: 6), isTrue);+ expect(unread(chat(last: 7), read: 7), isFalse);+ });+ });++ group('a message knows its thread', () {+ test('a top-level message roots its own thread and is in the chat', () {+ final m = SuperTabMessage.fromJson(message('m1', 1, thread: 'm1'));++ expect(m.thread, 'm1');+ expect(m.threadReply, isFalse);+ expect(m.inMainStream, isTrue);+ });++ test('a reply only in its thread is out of the main stream', () {+ final m = SuperTabMessage.fromJson(message('m2', 2, thread: 'm1'));++ expect(m.thread, 'm1');+ expect(m.alsoInChat, isFalse);+ expect(m.threadReply, isTrue);+ expect(m.inMainStream, isFalse);+ });++ test('a reply also sent to the chat is in both', () {+ final m = SuperTabMessage.fromJson(+ message('m3', 3, thread: 'm1', alsoInChat: true),+ );++ expect(m.alsoInChat, isTrue);+ expect(m.threadReply, isTrue);+ expect(m.inMainStream, isTrue);+ });++ test('a message from before threads, or an odd value, is in the chat', () {+ final before = SuperTabMessage.fromJson(message('m4', 4));+ expect(before.thread, isNull);+ expect(before.alsoInChat, isFalse);+ expect(before.threadReply, isFalse);+ expect(before.inMainStream, isTrue);++ for (final odd in ['true', 1]) {+ final m = SuperTabMessage.fromJson(+ message('m5', 5, thread: 'm1', alsoInChat: odd),+ );+ expect(m.alsoInChat, isFalse, reason: '$odd');+ expect(m.inMainStream, isFalse, reason: '$odd');+ }+ });+ });++ group("a page's thread summary", () {+ test('reads its replies, newest reply, authors and people', () {+ final thread = SuperTabThread.fromJson({+ 'id': 'm1',+ 'replies': 3,+ 'lastSequence': 9,+ 'lastAt': '2026-10-29T08:00:00.000Z',+ 'authors': [+ {'kind': 'agent', 'id': 'agent-builder', 'displayName': 'Builder'},+ {'kind': 'person', 'id': me, 'name': 'me'},+ ],+ 'people': [me, 'ken', 7],+ });++ expect(thread.id, 'm1');+ expect(thread.replies, 3);+ expect(thread.lastSequence, 9);+ expect(thread.lastAt, DateTime.utc(2026, 10, 29, 8));+ expect([for (final a in thread.authors) a['id']], ['agent-builder', me]);+ expect(thread.people, [me, 'ken']);+ });++ test('with no authors, people or date, has none', () {+ final thread = SuperTabThread.fromJson({+ 'id': 'm1',+ 'replies': 1,+ 'lastSequence': 2,+ });++ expect(thread.lastAt, isNull);+ expect(thread.authors, isEmpty);+ expect(thread.people, isEmpty);+ });+ });+}diff --git a/mobile/test/swarm/swarm_unread_test.dart b/mobile/test/swarm/swarm_unread_test.dartnew file mode 100644index 000000000..285535d13--- /dev/null+++ b/mobile/test/swarm/swarm_unread_test.dart@@ -0,0 +1,240 @@+import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/swarm/swarm_asks.dart';+import 'package:harness_mobile/swarm/swarm_read_marks.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_unread.dart';++import 'swarm_fixture.dart';++/// What a chat's or a project's row says is new (desktop design system,+/// People and conversations in lists): unread, its name in bold; the Lead's+/// tags still waiting on the person, bold too, with an `@N` count of them.+void main() {+ const other = 'project-2';++ Map<String, dynamic> mentionRow(+ String id, {+ String conversationId = 'g1',+ String projectId = project,+ }) => {+ 'id': id,+ 'projectId': projectId,+ 'projectName': 'Mobile',+ 'conversationId': conversationId,+ 'conversationTitle': 'Fix login',+ 'messageId': 'msg-$id',+ 'leadName': 'River',+ 'text': 'Look',+ 'createdAt': '2026-10-27T01:00:00.000Z',+ };++ /// A Swarm of two projects: Mobile with its project chat, work g1 and g2,+ /// closed work, a private chat and the reader's Buddy chat; Web with its+ /// project chat. Read once, so what is there counts as read; [tags] wait.+ Future<({FakeSwarm swarm, SwarmReader reader, SwarmAsks asks})> rig({+ List<Map<String, dynamic>> tags = const [],+ }) async {+ final swarm = FakeSwarm();+ Map<String, dynamic> inWeb(Map<String, dynamic> group) => {+ ...group,+ 'projectId': other,+ };+ final groups = [+ groupData('g1', title: 'Fix login', lastMessageSequence: 3),+ groupData('g2', title: 'Ship it', lastMessageSequence: 1),+ {...groupData('closed', lastMessageSequence: 1), 'archived': true},+ groupData('private', audience: [me], lastMessageSequence: 1),+ buddyChatData('buddy-chat', lastMessageSequence: 1),+ inWeb(groupData('web-lead', title: 'Web', lastMessageSequence: 1)),+ ];+ final head = headData(+ projects: [+ ...headData()['projects'] as List,+ {+ 'id': other,+ 'name': 'Web',+ 'ownerId': me,+ 'leadConversationId': 'web-lead',+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ );+ final derived = {'mentionsWaiting': tags.length};+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(head: head, groups: groups, derived: derived);+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': tags,+ };+ swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ swarm.routes['/api/super-tabs/$tab/conversations/'] = (body) => {+ 'sequence': body!['sequence'],+ };+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ final marks = reader.readMarks = SwarmReadMarks(reader, store: null);+ final asks = SwarmAsks(reader);+ addTearDown(() {+ asks.dispose();+ marks.dispose();+ reader.dispose();+ });+ await reader.refresh();+ await settle();+ return (swarm: swarm, reader: reader, asks: asks);+ }++ /// A change read in which [groups] moved, by id, to their [version].+ Future<void> moveOn(+ ({FakeSwarm swarm, SwarmReader reader, SwarmAsks asks}) r,+ Map<String, Map<String, dynamic>> groups, {+ int version = 20,+ }) async {+ r.swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c$version',+ groups: [+ for (final MapEntry(:key, :value) in groups.entries)+ part(key, version, value),+ ],+ );+ await r.reader.refresh();+ await settle();+ }++ SwarmRowNews chat(+ ({FakeSwarm swarm, SwarmReader reader, SwarmAsks asks}) r,+ String id,+ ) => swarmChatNews(r.reader, r.asks, r.reader.snapshot!.conversation(id)!);++ test('nothing is new after the first read', () async {+ final r = await rig();++ expect(chat(r, 'g1'), (bold: false, tags: 0));+ expect(swarmProjectNews(r.reader, r.asks), isEmpty);+ });++ test('an unread chat is bold, with no count', () async {+ final r = await rig();+ await moveOn(r, {+ 'g1': groupData('g1', title: 'Fix login', lastMessageSequence: 4),+ });++ expect(chat(r, 'g1'), (bold: true, tags: 0));+ expect(chat(r, 'g2'), (bold: false, tags: 0));+ });++ test('a reply only in a thread leaves a read chat and its project as they '+ 'were; a message in the main stream still makes them bold', () async {+ final r = await rig();+ await moveOn(r, {+ 'g1': {+ ...groupData('g1', title: 'Fix login', lastMessageSequence: 4),+ 'lastMainSequence': 3,+ },+ });++ expect(chat(r, 'g1'), (bold: false, tags: 0));+ expect(swarmProjectNews(r.reader, r.asks), isEmpty);++ await moveOn(r, version: 21, {+ 'g1': {+ ...groupData('g1', title: 'Fix login', lastMessageSequence: 5),+ 'lastMainSequence': 5,+ },+ });++ expect(chat(r, 'g1'), (bold: true, tags: 0));+ expect(swarmProjectNews(r.reader, r.asks), {+ project: (bold: true, tags: 0),+ });+ });++ test("a chat the Lead tagged the person in is bold with the count of the "+ "tags still waiting, read or not", () async {+ final r = await rig(+ tags: [+ mentionRow('t1'),+ mentionRow('t2'),+ mentionRow('t3', conversationId: 'g2'),+ ],+ );++ expect(chat(r, 'g1'), (bold: true, tags: 2));+ expect(chat(r, 'g2'), (bold: true, tags: 1));+ expect(chat(r, leadChat), (bold: false, tags: 0));+ });++ test('a project is bold while its project chat or open work is unread, '+ 'and counts every tag waiting in it', () async {+ final r = await rig(tags: [mentionRow('t1'), mentionRow('t2')]);++ expect(swarmProjectNews(r.reader, r.asks), {+ project: (bold: true, tags: 2),+ });++ final quiet = await rig();+ await moveOn(quiet, {+ leadChat: groupData(+ leadChat,+ title: 'Mobile',+ agentIds: ['agent-lead'],+ leadId: 'agent-lead',+ lastMessageSequence: 5,+ ),+ 'web-lead': {+ ...groupData('web-lead', title: 'Web', lastMessageSequence: 2),+ 'projectId': other,+ },+ });++ expect(swarmProjectNews(quiet.reader, quiet.asks), {+ project: (bold: true, tags: 0),+ other: (bold: true, tags: 0),+ });+ });++ test('a project is not bold for its closed work, a private chat or the '+ "person's Buddy chat, which has its own row", () async {+ final r = await rig();+ await moveOn(r, {+ 'closed': {+ ...groupData('closed', lastMessageSequence: 9),+ 'archived': true,+ },+ 'private': groupData('private', audience: [me], lastMessageSequence: 9),+ 'buddy-chat': buddyChatData('buddy-chat', lastMessageSequence: 9),+ });++ expect(swarmProjectNews(r.reader, r.asks), isEmpty);+ // The Buddy chat's own row is bold.+ expect(chat(r, 'buddy-chat'), (bold: true, tags: 0));+ });++ test('without read marks or tags read, nothing is new', () async {+ final swarm = FakeSwarm();+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) =>+ firstLoad(groups: [groupData('g1', lastMessageSequence: 3)]);+ final reader = SwarmReader(+ tabId: tab,+ accountId: me,+ request: swarm.request,+ );+ addTearDown(reader.dispose);+ await reader.refresh();++ expect(swarmChatNews(reader, null, reader.snapshot!.conversation('g1')!), (+ bold: false,+ tags: 0,+ ));+ expect(swarmProjectNews(reader, null), isEmpty);+ });+}diff --git a/mobile/test/swarm/team_glance_test.dart b/mobile/test/swarm/team_glance_test.dartnew file mode 100644index 000000000..e783942ca--- /dev/null+++ b/mobile/test/swarm/team_glance_test.dart@@ -0,0 +1,374 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/team_glance.dart';++import 'swarm_fixture.dart';++/// The team at a glance on the phone: who is working, who waits on a person,+/// who is down — read from the Swarm alone, as the phone sees no agent's+/// computer.+void main() {+ final now = DateTime(2026, 10, 27, 9);++ SuperTabSnapshot swarm({+ required List<Map<String, dynamic>> agents,+ List<Map<String, dynamic>> groups = const [],+ }) => SuperTabSnapshot.fromJson(+ SuperTabParts.firstLoad(firstLoad(agents: agents, groups: groups)).state,+ );++ Map<String, dynamic> working(String agentId, String status) => groupData(+ 'work-$agentId',+ title: 'Task of $agentId',+ agentIds: [agentId],+ status: status,+ workerId: agentId,+ );++ String stateOf(SwarmTeamGlance glance, String agentId) =>+ glance.agents.singleWhere((a) => a.agent.id == agentId).label;++ test('each agent in a word, from the work it holds and its health', () {+ final glance = swarmTeamGlance(+ swarm(+ agents: [+ agent('a-work', displayName: 'Ana'),+ agent('a-review', displayName: 'Bo'),+ agent('a-check', displayName: 'Cy'),+ agent('a-wait', displayName: 'Di'),+ agent('a-stuck', displayName: 'Ed'),+ {+ ...agent('a-down', displayName: 'Fy'),+ 'downSince': '2026-10-27T08:00:00Z',+ },+ {+ ...agent('a-limit', displayName: 'Gu'),+ 'limitedUntil': DateTime(+ 2026,+ 10,+ 27,+ 9,+ 5,+ ).toUtc().toIso8601String(),+ },+ agent('a-lost', displayName: 'Hu'),+ agent('a-idle', displayName: 'Io'),+ ],+ groups: [+ working('a-work', 'working'),+ working('a-review', 'review'),+ working('a-check', 'reconciling'),+ working('a-wait', 'needs_human'),+ working('a-stuck', 'blocked'),+ working('a-lost', 'lost'),+ ],+ ),+ now: now,+ );++ expect(stateOf(glance, 'a-work'), 'Working');+ expect(stateOf(glance, 'a-review'), 'In review');+ expect(stateOf(glance, 'a-check'), 'Checking');+ expect(stateOf(glance, 'a-wait'), 'Waiting');+ expect(stateOf(glance, 'a-stuck'), 'Stuck');+ expect(stateOf(glance, 'a-down'), 'Down');+ expect(stateOf(glance, 'a-limit'), 'Limited until 09:05');+ expect(stateOf(glance, 'a-lost'), 'Lost');+ expect(stateOf(glance, 'a-idle'), 'Idle');+ });++ test('down outranks the work it held; a limit that passed is no limit', () {+ final glance = swarmTeamGlance(+ swarm(+ agents: [+ {+ ...agent('a1', displayName: 'Ana'),+ 'downSince': '2026-10-27T08:00:00Z',+ },+ {+ ...agent('a2', displayName: 'Bo'),+ 'limitedUntil': DateTime(2026, 10, 27, 8).toUtc().toIso8601String(),+ },+ ],+ groups: [working('a1', 'needs_human'), working('a2', 'working')],+ ),+ now: now,+ );++ expect(stateOf(glance, 'a1'), 'Down');+ expect(stateOf(glance, 'a2'), 'Working');+ });++ test('the line counts working, waiting on a person, and down', () {+ final glance = swarmTeamGlance(+ swarm(+ agents: [+ agent('a1'),+ agent('a2'),+ agent('a3'),+ agent('a4'),+ {...agent('a5'), 'downSince': '2026-10-27T08:00:00Z'},+ agent('a6'),+ ],+ groups: [+ working('a1', 'working'),+ working('a2', 'review'),+ working('a3', 'needs_human'),+ working('a4', 'blocked'),+ ],+ ),+ now: now,+ );++ expect(glance.working, 2);+ expect(glance.waiting, 2, reason: 'stuck work waits on a person too');+ expect(glance.down, 1);+ expect(glance.line, '2 working · 2 waiting · 1 down');+ });++ test('the line leaves out what is none, and says when all are idle', () {+ expect(+ swarmTeamGlance(+ swarm(+ agents: [agent('a1'), agent('a2')],+ groups: [working('a1', 'working')],+ ),+ now: now,+ ).line,+ '1 working',+ );+ expect(+ swarmTeamGlance(swarm(agents: [agent('a1')]), now: now).line,+ 'All idle',+ );+ expect(swarmTeamGlance(swarm(agents: []), now: now).line, 'No agents yet');+ });++ test('who needs a person comes first, then who is down, then the rest', () {+ final glance = swarmTeamGlance(+ swarm(+ agents: [+ agent('a-idle', displayName: 'Ana'),+ agent('a-work', displayName: 'Bo'),+ {+ ...agent('a-down', displayName: 'Cy'),+ 'downSince': '2026-10-27T08:00:00Z',+ },+ agent('a-wait', displayName: 'Di'),+ ],+ groups: [+ working('a-work', 'working'),+ working('a-wait', 'needs_human'),+ ],+ ),+ now: now,+ );++ expect([for (final a in glance.agents) a.name], ['Di', 'Cy', 'Bo', 'Ana']);+ });++ test("an agent's task is the open work it holds", () {+ final glance = swarmTeamGlance(+ swarm(+ agents: [agent('a1')],+ groups: [+ {...working('a1', 'done'), 'id': 'old'},+ working('a1', 'working'),+ ],+ ),+ now: now,+ );++ expect(glance.agents.single.task?.id, 'work-a1');+ });++ group('in one project', () {+ test('only its agents: by their project, else by the work they are in', () {+ final glance = swarmTeamGlance(+ swarm(+ agents: [+ agent('mine'),+ {...agent('other'), 'projectId': 'project-2'},+ {...agent('placed'), 'projectId': null},+ {...agent('unplaced'), 'projectId': null},+ ],+ groups: [+ groupData('g1', agentIds: ['placed']),+ ],+ ),+ projectId: project,+ now: now,+ );++ expect({for (final a in glance.agents) a.agent.id}, {'mine', 'placed'});+ });+ });++ group('once per Swarm read', () {+ SuperTabSnapshot team() => swarm(+ agents: [+ agent('mine', displayName: 'Ana'),+ {...agent('other', displayName: 'Bo'), 'projectId': 'project-2'},+ ],+ groups: [working('mine', 'needs_human')],+ );++ test('the same read and project give the same glance, not a new one', () {+ final snapshot = team();++ final first = swarmTeamGlance(snapshot, projectId: project, now: now);++ expect(+ swarmTeamGlance(snapshot, projectId: project, now: now),+ same(first),+ );+ expect(+ swarmTeamGlance(snapshot, now: now),+ same(swarmTeamGlance(snapshot, now: now)),+ reason: 'the whole Swarm is kept too',+ );+ expect(+ swarmTeamGlance(snapshot, now: now),+ isNot(same(first)),+ reason: 'each project keeps its own',+ );+ });++ test('a new read is counted again', () {+ final before = swarmTeamGlance(team(), projectId: project, now: now);+ final after = swarmTeamGlance(+ swarm(+ agents: [agent('mine', displayName: 'Ana')],+ groups: [working('mine', 'working')],+ ),+ projectId: project,+ now: now,+ );++ expect(before.line, '1 waiting');+ expect(after.line, '1 working');+ });++ test('a limit that runs out reads again, on the same read', () {+ final snapshot = swarm(+ agents: [+ {+ ...agent('a1', displayName: 'Ana'),+ 'limitedUntil': DateTime(+ 2026,+ 10,+ 27,+ 9,+ 5,+ ).toUtc().toIso8601String(),+ },+ ],+ groups: [working('a1', 'working')],+ );+ String labelAt(DateTime at) =>+ swarmTeamGlance(snapshot, now: at).agents.single.label;++ expect(labelAt(now), 'Limited until 09:05');+ expect(+ labelAt(now.add(const Duration(minutes: 4))),+ 'Limited until 09:05',+ );+ expect(labelAt(DateTime(2026, 10, 27, 9, 5)), 'Working');+ expect(labelAt(now), 'Limited until 09:05', reason: 'asked for earlier');+ });+ test('a read after losing a project keeps nothing of it', () {+ final before = team();+ expect(+ swarmTeamGlance(before, projectId: 'project-2', now: now).agents,+ hasLength(1),+ );++ final after = swarm(+ agents: [agent('mine', displayName: 'Ana')],+ groups: [working('mine', 'needs_human')],+ );++ final glance = swarmTeamGlance(after, projectId: 'project-2', now: now);+ expect(glance.agents, isEmpty);+ expect(glance.line, 'No agents yet');+ expect(swarmTeamGlance(after, now: now).agents.map((a) => a.agent.id), [+ 'mine',+ ]);+ });+ });+ // Ken, 10-29: a Buddy is a person's own helper, never one of the team. The+ // phone's Agents lists and their counts leave every Buddy out, the person's+ // own included (it shows only under Buddies).+ group('with three Buddies running', () {+ final buddies = [+ buddyData('agent-wren', displayName: 'Wren'),+ buddyData('agent-ivy', owner: 'person-dee', displayName: 'Ivy'),+ {+ ...buddyData('agent-oak', owner: 'person-kai', displayName: 'Oak'),+ 'downSince': '2026-10-27T08:00:00Z',+ },+ ];+ final team = [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ agent('agent-ana', displayName: 'Ana'),+ ];++ Future<SuperTabSnapshot> read(List<Map<String, dynamic>> groups) async {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(+ agents: [...team, ...buddies],+ groups: [+ ...groups,+ buddyChatData('buddy-me', agentIds: ['agent-wren']),+ buddyChatData(+ 'buddy-dee',+ owner: 'person-dee',+ agentIds: ['agent-ivy'],+ ),+ buddyChatData(+ 'buddy-kai',+ owner: 'person-kai',+ agentIds: ['agent-oak'],+ ),+ ],+ );+ final r = SwarmReader(tabId: tab, accountId: me, request: fake.request);+ addTearDown(r.dispose);+ await r.refresh();+ return r.snapshot!;+ }++ test('the team and its counts leave every Buddy out', () async {+ final snapshot = await read([working('agent-ana', 'working')]);++ for (final glance in [+ swarmTeamGlance(snapshot, now: now),+ swarmTeamGlance(snapshot, projectId: project, now: now),+ ]) {+ expect(+ [for (final a in glance.agents) a.agent.id],+ ['agent-ana', 'agent-lead'],+ );+ expect(glance.line, '1 working', reason: "Oak's being down counts not");+ }+ });++ test('a Swarm read off the UI isolate leaves them out too', () async {+ final snapshot = await read([+ working('agent-ana', 'working'),+ for (var i = 0; i < swarmParseOffThreadParts; i++)+ groupData('g$i', title: 'Work $i'),+ ]);++ expect(+ [+ for (final a in swarmTeamGlance(snapshot, now: now).agents)+ a.agent.id,+ ],+ ['agent-ana', 'agent-lead'],+ );+ });+ });+}diff --git a/mobile/test/swarm/waiting_work_test.dart b/mobile/test/swarm/waiting_work_test.dartnew file mode 100644index 000000000..940d7310f--- /dev/null+++ b/mobile/test/swarm/waiting_work_test.dart@@ -0,0 +1,190 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/parts.dart';+import 'package:harness_mobile/swarm/waiting_work.dart';++import 'swarm_fixture.dart';++/// Work that waits on the reader: a worker needs a person or is stuck, in a+/// group whose partner is the reader, or with no partner in a project the+/// reader owns (Lead's ruling, 2026-10-27). Work named for someone else is+/// theirs alone.+void main() {+ /// What the reader would hold after a first load of [groups]: the Swarm, and its raw state.+ ({SuperTabSnapshot snapshot, Map<String, dynamic> state}) swarm(+ List<Map<String, dynamic>> groups, {+ String projectOwner = me,+ }) {+ final state = SuperTabParts.firstLoad(+ firstLoad(+ groups: groups,+ head: headData(+ projects: [+ {+ 'id': project,+ 'name': 'Mobile',+ 'ownerId': projectOwner,+ 'leadConversationId': leadChat,+ 'visibility': 'public',+ 'members': <Object>[],+ },+ ],+ ),+ ),+ ).state;+ return (snapshot: SuperTabSnapshot.fromJson(state), state: state);+ }++ List<SwarmWaitingWork> waitingIn(+ List<Map<String, dynamic>> groups, {+ String projectOwner = me,+ }) {+ final read = swarm(groups, projectOwner: projectOwner);+ return swarmWaitingWork(+ read.snapshot,+ me,+ partners: swarmPartners(read.state),+ );+ }++ test('needs-human and stuck work in my project wait on me', () {+ final waiting = waitingIn([+ groupData('g1', title: 'Login', status: 'needs_human'),+ groupData('g2', title: 'Sync', status: 'blocked'),+ groupData('g3', title: 'Docs', status: 'working'),+ groupData('g4', title: 'Icons', status: 'done'),+ groupData('g5', title: 'Chat'),+ ]);++ expect([for (final w in waiting) w.conversation.title], ['Login', 'Sync']);+ expect(waiting.first.status, 'needs_human');+ expect(waiting.first.agentName, 'Nova');+ expect(waiting.first.project.name, 'Mobile');+ });++ test("another person's project waits on them, not me", () {+ final waiting = waitingIn([+ groupData('g1', status: 'needs_human'),+ ], projectOwner: 'person-other');++ expect(waiting, isEmpty);+ });++ test("work whose partner is someone else is theirs alone", () {+ final partnered = {+ ...groupData('g1', status: 'needs_human'),+ 'partnerId': 'person-other',+ };++ expect(waitingIn([partnered]), isEmpty);+ });++ test("work whose partner is me waits on me, in anyone's project", () {+ final partnered = {...groupData('g1', status: 'blocked'), 'partnerId': me};++ expect(+ waitingIn([+ partnered,+ ], projectOwner: 'person-other').single.conversation.id,+ 'g1',+ );+ });++ test('its question is what the worker wrote', () {+ final row = {+ ...groupData('g1', status: 'needs_human'),+ 'assignment': {+ 'id': 'attempt-g1',+ 'agentId': 'agent-builder',+ 'status': 'needs_human',+ 'result': 'Keep the old screen?',+ },+ };++ expect(waitingIn([row]).single.question, 'Keep the old screen?');+ });++ group('once per Swarm read', () {+ test('the same read, reader and partners give the same list', () {+ final read = swarm([groupData('g1', status: 'needs_human')]);+ final partners = swarmPartners(read.state);++ final first = swarmWaitingWork(read.snapshot, me, partners: partners);++ expect(first, hasLength(1));+ expect(+ swarmWaitingWork(read.snapshot, me, partners: partners),+ same(first),+ );+ });++ test('a new read, another reader or new partners count again', () {+ final read = swarm([groupData('g1', status: 'needs_human')]);+ final partners = swarmPartners(read.state);+ final first = swarmWaitingWork(read.snapshot, me, partners: partners);++ expect(+ swarmWaitingWork(read.snapshot, 'person-other', partners: partners),+ isEmpty,+ );+ expect(+ swarmWaitingWork(read.snapshot, me, partners: {'g1': 'person-other'}),+ isEmpty,+ );+ expect(+ swarmWaitingWork(+ swarm([groupData('g1', status: 'working')]).snapshot,+ me,+ partners: partners,+ ),+ isEmpty,+ );+ expect(+ [+ for (final w in swarmWaitingWork(+ read.snapshot,+ me,+ partners: partners,+ ))+ w.conversation.id,+ ],+ [for (final w in first) w.conversation.id],+ reason: 'back to the first: still right',+ );+ });++ test('the list cannot be changed by a caller', () {+ final read = swarm([groupData('g1', status: 'needs_human')]);++ expect(+ () => swarmWaitingWork(read.snapshot, me).clear(),+ throwsUnsupportedError,+ );+ });+ test('a read after losing access, or another person signed in, keeps '+ 'nothing from before', () {+ final read = swarm([groupData('g1', status: 'needs_human')]);+ final partners = swarmPartners(read.state);+ expect(+ swarmWaitingWork(read.snapshot, me, partners: partners),+ hasLength(1),+ );++ final after = swarm([groupData('g2', status: 'working')]);+ expect(+ swarmWaitingWork(+ after.snapshot,+ me,+ partners: swarmPartners(after.state),+ ),+ isEmpty,+ reason: 'g1 is no longer in the read',+ );+ expect(+ swarmWaitingWork(read.snapshot, 'person-other', partners: partners),+ isEmpty,+ reason: 'signed out, then someone else on the same read',+ );+ });+ });+}diff --git a/mobile/test/terminal_page_out_of_sight_test.dart b/mobile/test/terminal_page_out_of_sight_test.dartnew file mode 100644index 000000000..a9f6d5e4e--- /dev/null+++ b/mobile/test/terminal_page_out_of_sight_test.dart@@ -0,0 +1,134 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/phone/out_of_sight.dart';+import 'package:harness_mobile/phone/terminal_page.dart';+import 'package:harness_mobile/phone/voice_input_controller.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';++import 'voice_fakes.dart';+import 'widget_rebuilds.dart';++/// A terminal kept out of sight (Harness under Swarm Home) does no work for+/// the app's updates or for its own output, and is current again once shown.+void main() {+ late AppNotifier notifier;+ late TerminalSession session;+ late VoiceInputController voice;+ late ValueNotifier<String> language;+ late ValueNotifier<bool> hidden;++ setUp(() {+ notifier = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ );+ session = TerminalSession(+ machineId: 'm',+ agentId: 'a',+ agentName: 'Agent',+ engineId: 'claude',+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ );+ session.status = TerminalSessionStatus.controlling;+ session.streamId = 's';+ session.terminal.write('output\r\n');+ notifier.adoptSessionForTest(session);+ language = ValueNotifier('en');+ voice = VoiceInputController(+ transcriber: FakeTranscriber().call,+ recorder: FakeVoiceRecorder(),+ language: language,+ );+ hidden = ValueNotifier(false);+ });++ tearDown(() {+ hidden.dispose();+ voice.dispose();+ language.dispose();+ notifier.dispose();+ });++ Future<void> pump(WidgetTester tester) async {+ await tester.pumpWidget(+ MaterialApp(+ home: ValueListenableBuilder(+ valueListenable: hidden,+ builder: (context, isHidden, child) =>+ OutOfSight(hidden: isHidden, child: child!),+ child: TerminalPage(+ notifier: notifier,+ machineId: 'm',+ agentId: 'a',+ voice: voice,+ ),+ ),+ ),+ );+ await tester.pump(const Duration(milliseconds: 100));+ }++ Future<void> hide(WidgetTester tester, bool value) async {+ hidden.value = value;+ await tester.pump();+ }++ /// A fact the page draws from moves, and the app says so.+ Future<void> statusMoves(WidgetTester tester) async {+ session.status = session.status == TerminalSessionStatus.controlling+ ? TerminalSessionStatus.resyncing+ : TerminalSessionStatus.controlling;+ notifier.notifyListeners();+ await tester.pump();+ }++ testWidgets('out of sight, an app update it would draw rebuilds nothing', (+ tester,+ ) async {+ await pump(tester);+ await hide(tester, true);++ final rebuilt = countRebuildsUnder<TerminalPage>();+ await statusMoves(tester);+ await statusMoves(tester);++ expect(rebuilt(), 0);+ });++ testWidgets('out of sight, output rebuilds nothing; it stays in the '+ 'terminal', (tester) async {+ await pump(tester);+ await hide(tester, true);++ final rebuilt = countRebuildsUnder<TerminalPage>();+ for (var i = 0; i < 60; i++) {+ session.terminal.write('line $i\r\n');+ }+ await tester.pump();++ expect(rebuilt(), 0);+ expect(+ session.terminal.buffer.lines[session.terminal.buffer.height - 2]+ .getText()+ .trim(),+ 'line 59',+ );+ });++ testWidgets('shown again, it listens again', (tester) async {+ await pump(tester);+ await hide(tester, true);+ await statusMoves(tester);+ await hide(tester, false);++ final rebuilt = countRebuildsUnder<TerminalPage>();+ await statusMoves(tester);++ expect(rebuilt(), greaterThan(0));+ });+}diff --git a/mobile/test/theme/phone_theme_alignment_test.dart b/mobile/test/theme/phone_theme_alignment_test.dartnew file mode 100644index 000000000..a19998fd6--- /dev/null+++ b/mobile/test/theme/phone_theme_alignment_test.dart@@ -0,0 +1,95 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/phone/phone_sheet.dart';+import 'package:harness_mobile/shared/theme/app_type.dart';++import 'sheet_shape.dart';++/// The phone takes Desktop's corners and roles, at the sizes the Phone section+/// of desktop/design/desktop-design-system.md gives them.+void main() {+ double radiusOf(ShapeBorder? shape) {+ final border = shape! as RoundedRectangleBorder;+ return (border.borderRadius as BorderRadius).topLeft.x;+ }++ for (final brightness in Brightness.values) {+ group('$brightness', () {+ final theme = buildAppTheme(brightness: brightness);++ test('action buttons are capsules', () {+ for (final style in [+ theme.filledButtonTheme.style,+ theme.outlinedButtonTheme.style,+ theme.textButtonTheme.style,+ ]) {+ expect(style!.shape!.resolve({}), isA<StadiumBorder>());+ }+ });++ test('fields round at 10', () {+ final border =+ theme.inputDecorationTheme.enabledBorder! as OutlineInputBorder;+ expect(border.borderRadius.topLeft.x, 10);+ });++ test('menus and popovers round at 16', () {+ expect(radiusOf(theme.popupMenuTheme.shape), 16);+ expect(radiusOf(theme.menuTheme.style!.shape!.resolve({})), 16);+ });++ test('dialogs round at 20', () {+ expect(radiusOf(theme.dialogTheme.shape), 20);+ });++ test('bottom sheets round their top corners at 12', () {+ expect(radiusOf(theme.bottomSheetTheme.shape), 12);+ });+ });+ }++ testWidgets('the shared phone sheet rounds its top corners at 12', (+ tester,+ ) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => TextButton(+ onPressed: () => showPhoneSheet(context, title: 'Menu'),+ child: const Text('Open'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ expect(sheetTopRadius(tester), 12);+ });++ test('type roles take their phone sizes', () {+ expect(AppType.display().fontSize, 34);+ expect(AppType.title().fontSize, 22);+ expect(AppType.heading().fontSize, 17);+ expect(AppType.heading().fontWeight, FontWeight.w600);+ expect(AppType.body().fontSize, 17);+ expect(AppType.label().fontSize, 17);+ expect(AppType.caption().fontSize, 13);+ expect(AppType.mono().fontSize, 13);+ expect(AppType.monoLabel().fontSize, 12);+ expect(AppType.monoMeta().fontSize, 11);+ });++ test('a role keeps the caller\'s colour, weight and tabular figures', () {+ const ink = Color(0xFF123456);+ final style = AppType.label(+ color: ink,+ fontWeight: FontWeight.w700,+ fontFeatures: const [FontFeature.tabularFigures()],+ );+ expect(style.color, ink);+ expect(style.fontWeight, FontWeight.w700);+ expect(style.fontFeatures, const [FontFeature.tabularFigures()]);+ });+}diff --git a/mobile/test/theme/phone_touch_targets_test.dart b/mobile/test/theme/phone_touch_targets_test.dartnew file mode 100644index 000000000..ed09df16f--- /dev/null+++ b/mobile/test/theme/phone_touch_targets_test.dart@@ -0,0 +1,84 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/phone/sheet_list.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';++/// Every themed button reaches the 44-point touch target on its own, while it+/// keeps the size it is drawn at; rows inside a sheet round at the row radius.+/// See the Phone section of desktop/design/desktop-design-system.md.+void main() {+ Future<int Function()> pump(+ WidgetTester tester,+ Widget Function(VoidCallback onPressed) button,+ ) async {+ var presses = 0;+ await tester.pumpWidget(+ MaterialApp(+ theme: buildAppTheme(),+ home: Scaffold(body: Center(child: button(() => presses++))),+ ),+ );+ return () => presses;+ }++ final buttons = <String, (Widget Function(VoidCallback), double)>{+ 'filled': ((p) => FilledButton(onPressed: p, child: const Text('Go')), 32),+ 'outlined': (+ (p) => OutlinedButton(onPressed: p, child: const Text('Go')),+ 32,+ ),+ 'text': ((p) => TextButton(onPressed: p, child: const Text('Go')), 32),+ 'icon': (+ (p) => IconButton(onPressed: p, icon: const Icon(Icons.close)),+ 40,+ ),+ };++ for (final MapEntry(key: name, value: (build, drawn)) in buttons.entries) {+ testWidgets('a $name button is drawn at $drawn and pressed across 44', (+ tester,+ ) async {+ final presses = await pump(tester, build);+ final ink = find.byType(InkWell);+ expect(tester.getSize(ink).height, drawn);++ final top = tester.getRect(ink).topCenter;+ final reach = (44 - drawn) / 2;+ await tester.tapAt(top - Offset(0, reach - 1));+ expect(presses(), 1);++ await tester.tapAt(top - Offset(0, reach + 2));+ expect(presses(), 1);+ });+ }++ testWidgets('a group of sheet rows rounds its corners at 10', (tester) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: buildAppTheme(),+ home: const Scaffold(+ body: SheetRow(+ leading: SizedBox(),+ title: Text('main'),+ first: true,+ last: true,+ ),+ ),+ ),+ );+ final box = tester+ .widgetList<Container>(+ find.descendant(+ of: find.byType(SheetRow),+ matching: find.byType(Container),+ ),+ )+ .map((c) => c.decoration)+ .whereType<BoxDecoration>()+ .firstWhere((d) => d.borderRadius != null);+ final radius = box.borderRadius!.resolve(TextDirection.ltr);+ expect(radius.topLeft.x, 10);+ expect(radius.bottomRight.x, 10);+ });+}diff --git a/mobile/test/theme/sheet_shape.dart b/mobile/test/theme/sheet_shape.dartnew file mode 100644index 000000000..9682ed647--- /dev/null+++ b/mobile/test/theme/sheet_shape.dart@@ -0,0 +1,16 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';++/// The top-left corner radius the open bottom sheet is drawn with.+double sheetTopRadius(WidgetTester tester) {+ final material = tester.widget<Material>(+ find+ .descendant(+ of: find.byType(BottomSheet),+ matching: find.byType(Material),+ )+ .first,+ );+ final shape = material.shape! as RoundedRectangleBorder;+ return shape.borderRadius.resolve(TextDirection.ltr).topLeft.x;+}diff --git a/mobile/test/viewer_app_fixture.dart b/mobile/test/viewer_app_fixture.dartindex 5e22c0ac6..74c6d797a 100644--- a/mobile/test/viewer_app_fixture.dart+++ b/mobile/test/viewer_app_fixture.dart@@ -2,6 +2,7 @@ import 'dart:async';import 'dart:convert';import 'dart:typed_data';+import 'package:dio/dio.dart' show CancelToken;import 'package:harness_mobile/api/api_client.dart';import 'package:harness_mobile/auth/auth_session.dart';import 'package:harness_mobile/auth/cli_link.dart';@@ -184,6 +185,27 @@ class FakeApi extends ApiClient {return {'accepted': true};}+ /// Answers each Swarm chat file sent; records what was sent, by+ /// `tab/conversation/name`. Never the network.+ final List<String> swarmUploads = [];+ Future<Map<String, dynamic>> Function() onSwarmUpload = () async => {+ 'attachment': <String, dynamic>{'id': 'att'},+ };++ @override+ Future<Map<String, dynamic>> uploadSwarmAttachment({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+ }) {+ swarmUploads.add('$tabId/$conversationId/$name');+ return onSwarmUpload();+ }+/// Answers `/api/auth/me` in place of [profile] when set — held open, or/// throwing.Future<Map<String, dynamic>?> Function()? onProfile;diff --git a/mobile/test/voice_input_controller_test.dart b/mobile/test/voice_input_controller_test.dartindex 27e2b9055..26f0d6b0c 100644--- a/mobile/test/voice_input_controller_test.dart+++ b/mobile/test/voice_input_controller_test.dart@@ -30,6 +30,95 @@ void main() {language.dispose();});+ test('a take that reaches its limit ends there, its words kept for the '+ 'next send', () {+ fakeAsync((async) {+ backend.replies.add('a long thought');+ unawaited(voice.startListening());+ async.flushMicrotasks();++ async.elapse(VoiceInputController.maxTake);+ async.flushMicrotasks();++ expect(recorder.stops, 1);+ expect(voice.status, VoiceInputStatus.idle);+ expect(voice.transcript, 'a long thought');+ });+ });++ test('an owner that takes over the limit is told, and the take runs on', () {+ fakeAsync((async) {+ var told = 0;+ voice.onTakeLimit = () async => told++;+ unawaited(voice.startListening());+ async.flushMicrotasks();++ async.elapse(VoiceInputController.maxTake - const Duration(seconds: 1));+ expect(told, 0);+ async.elapse(const Duration(seconds: 1));+ async.flushMicrotasks();++ expect(told, 1);+ expect(recorder.stops, 0);+ expect(backend.calls, isEmpty);+ expect(voice.status, VoiceInputStatus.listening);+ voice.clear();+ });+ });++ test('an owner that holds a take back keeps it from the backend until it '+ 'says yes, asked once the microphone has closed', () async {+ final gate = Completer<bool>();+ var asked = 0;+ voice.mayTranscribe = () {+ asked++;+ expect(recorder.stops, 1, reason: 'asked after the stop');+ return gate.future;+ };+ backend.replies.add('held words');+ await voice.startListening();++ final stopping = voice.stopListening();+ await Future<void>.delayed(Duration.zero);+ expect(asked, 1);+ expect(backend.calls, isEmpty);+ expect(voice.status, VoiceInputStatus.transcribing);++ gate.complete(true);+ await stopping;+ expect(backend.calls, hasLength(1));+ expect(voice.transcript, 'held words');+ });++ test('a take its owner will not let go is never transcribed', () async {+ voice.mayTranscribe = () async => false;+ backend.replies.add('kept back');+ await voice.startListening();++ await voice.stopListening();++ expect(backend.calls, isEmpty);+ expect(voice.transcript, isEmpty);+ expect(voice.isIdle, isTrue);+ expect(voice.notice, isNull, reason: 'nothing failed');+ });++ test('a take cleared while held back is not transcribed when it is let '+ 'go', () async {+ final gate = Completer<bool>();+ voice.mayTranscribe = () => gate.future;+ await voice.startListening();+ final stopping = voice.stopListening();+ await Future<void>.delayed(Duration.zero);++ voice.clear();+ gate.complete(true);+ await stopping;++ expect(backend.calls, isEmpty);+ expect(voice.isIdle, isTrue);+ });+test('at rest until the mic is pressed', () async {expect(voice.isIdle, isTrue);expect(recorder.starts, 0);diff --git a/mobile/test/widget_rebuilds.dart b/mobile/test/widget_rebuilds.dartnew file mode 100644index 000000000..9f0d9ac44--- /dev/null+++ b/mobile/test/widget_rebuilds.dart@@ -0,0 +1,28 @@+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';++/// Counts, from now until the test ends, every widget rebuilt at or under a+/// [T] — whether a listener marked it dirty or a parent handed it a new+/// widget. Read the count with the function returned.+///+/// Through the framework's own debug hook, which every rebuilt element passes+/// (`Element.rebuild`), so nothing in the app is instrumented for it.+int Function() countRebuildsUnder<T extends Widget>() => _count(+ (element) =>+ element.widget is T || element.findAncestorWidgetOfExactType<T>() != null,+);++/// Counts every rebuild of a widget whose type is one of [types].+int Function() countRebuildsOf(Set<Type> types) =>+ _count((element) => types.contains(element.widget.runtimeType));++int Function() _count(bool Function(Element element) counts) {+ var rebuilt = 0;+ final previous = debugOnRebuildDirtyWidget;+ debugOnRebuildDirtyWidget = (element, builtOnce) {+ previous?.call(element, builtOnce);+ if (counts(element)) rebuilt++;+ };+ addTearDown(() => debugOnRebuildDirtyWidget = previous);+ return () => rebuilt;+}diff --git a/scripts/ui-style-allowlist/mobile.json b/scripts/ui-style-allowlist/mobile.jsonindex 22d79145a..0967ef424 100644--- a/scripts/ui-style-allowlist/mobile.json+++ b/scripts/ui-style-allowlist/mobile.json@@ -1,5 +1 @@-{- "mobile/lib/swarm/swarm_page.dart": {- "edge-insets": 2- }-}+{}