Skip to content

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.

Phone: live PR and task cards that update in place (Slack parity) (#2226)

harness-for-autonomous[bot]03a3c1c0a060
diff --git a/desktop/lib/super_tabs/live_card.dart b/desktop/lib/super_tabs/live_card.dart
index 08fead88f..a11190b88 100644
--- a/desktop/lib/super_tabs/live_card.dart
+++ b/desktop/lib/super_tabs/live_card.dart
@@ -109,7 +109,9 @@ class _SuperTabLiveCardState extends State<SuperTabLiveCard> {
List<Widget> _task() {
final checks = widget.group.checks;
- final passed = checks.where((c) => c['evidence'] != null).length;
+ // A failed check keeps its evidence; only a pass names who passed it
+ // (backend commands.ts `work.check`).
+ final passed = checks.where((c) => c['passedBy'] != null).length;
return [
Text(widget.group.label, style: DesktopChrome.control(medium: true)),
SuperTabCardLine([
diff --git a/desktop/test/super_tab_live_card_test.dart b/desktop/test/super_tab_live_card_test.dart
index c108de138..11b30c6ed 100644
--- a/desktop/test/super_tab_live_card_test.dart
+++ b/desktop/test/super_tab_live_card_test.dart
@@ -51,7 +51,12 @@ ConversationServer cardServer({int? mergedAt}) {
'agentIds': ['kai', 'ivy'],
'brief': 'Add avatars.',
'checks': [
- {'id': 'a', 'description': 'Tests pass', 'evidence': 'ok'},
+ {
+ 'id': 'a',
+ 'description': 'Tests pass',
+ 'evidence': 'ok',
+ 'passedBy': 'agent:kai',
+ },
{'id': 'b', 'description': 'Screens', 'evidence': null},
],
'assignment': {'id': 'w', 'agentId': 'kai', 'status': 'working'},
@@ -185,6 +190,26 @@ void main() {
);
});
+ testWidgets('a failed check keeps its evidence and is not counted passed', (
+ tester,
+ ) async {
+ final server = cardServer();
+ final group = (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'work');
+ // As the server records a failed check: its evidence, nobody passing it.
+ (group['checks'] as List)[1] = {
+ 'id': 'b',
+ 'description': 'Screens',
+ 'evidence': 'Two screens cut off',
+ 'passedBy': null,
+ };
+ final facts = SuperTabPullRequestFacts(null);
+ addTearDown(facts.dispose);
+ await show(tester, server, facts, 'message-1');
+ expect(find.text('1 of 2 checks passed'), findsOneWidget);
+ });
+
testWidgets('the card updates in place as the PR changes', (tester) async {
var answer = found(pr, passed: 3, pending: 9);
final facts = reading(() => [answer]);
diff --git a/mobile/lib/swarm/live_card_model.dart b/mobile/lib/swarm/live_card_model.dart
new file mode 100644
index 000000000..15ea82290
--- /dev/null
+++ b/mobile/lib/swarm/live_card_model.dart
@@ -0,0 +1,67 @@
+/// One linked pull request's card: the message that is it, and whether the
+/// Swarm recorded its merge (backend superTabs/cards.ts).
+class SuperTabPullRequestCard {
+ const SuperTabPullRequestCard(
+ this.url,
+ this.messageId, {
+ this.merged = false,
+ });
+ final String url, messageId;
+ final bool merged;
+}
+
+/// What one message is a card of: its group's task, its pull requests, or both.
+typedef SuperTabCard = ({
+ bool task,
+ List<SuperTabPullRequestCard> pullRequests,
+});
+
+/// The messages a group shows as live cards (Slack parity): its task card and
+/// one card per linked pull request. Each updates in place from the group
+/// state the Swarm already sends, so only a reader of the group sees one.
+class SuperTabCards {
+ const SuperTabCards._(this.task, this.pullRequests);
+
+ factory SuperTabCards.fromJson(Object? row) {
+ if (row is! Map) return const SuperTabCards._(null, []);
+ return SuperTabCards._(
+ row['task'] is String ? row['task'] as String : null,
+ [
+ for (final card in row['pullRequests'] as List? ?? const [])
+ if (card is Map &&
+ card['messageId'] is String &&
+ card['url'] is String &&
+ _pullRequest(card['url'] as String))
+ SuperTabPullRequestCard(
+ card['url'] as String,
+ card['messageId'] as String,
+ merged: card['mergedAt'] is num,
+ ),
+ ],
+ );
+ }
+
+ final String? task;
+ final List<SuperTabPullRequestCard> pullRequests;
+
+ /// The server binds only GitHub pull request links; anything else is not a
+ /// card this app can draw.
+ static bool _pullRequest(String url) {
+ final uri = Uri.tryParse(url);
+ return uri != null &&
+ uri.scheme == 'https' &&
+ uri.host == 'github.com' &&
+ uri.pathSegments.length == 4 &&
+ uri.pathSegments[2] == 'pull';
+ }
+
+ /// The card [messageId] is, or null for a plain message.
+ SuperTabCard? of(String messageId) {
+ final linked = [
+ for (final card in pullRequests)
+ if (card.messageId == messageId) card,
+ ];
+ if (task != messageId && linked.isEmpty) return null;
+ return (task: task == messageId, pullRequests: linked);
+ }
+}
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index 877a71f8a..ef7593207 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -1,4 +1,5 @@
import 'identity.dart' show superTabPersonName;
+import 'live_card_model.dart';
import 'profile_model.dart';
export 'profile_model.dart';
@@ -173,6 +174,8 @@ class SuperTabConversation {
(row['pullRequestUrls'] as List?)?.whereType<String>() ??
const <String>[],
),
+ cards = SuperTabCards.fromJson(row['cards']),
+ reviewOf = row['reviewOf'] as String?,
brief = _text(row, 'brief'),
task = row['task'] is Map
? SuperTabTask.fromJson(superTabMap(row['task']))
@@ -225,6 +228,13 @@ class SuperTabConversation {
/// Persisted links may be absent on older backends; loaded messages still supply links.
final List<String> pullRequestUrls;
+
+ /// Its messages drawn as live cards (swarm_live_card.dart); none from an
+ /// older backend.
+ final SuperTabCards cards;
+
+ /// A review group's reviewed group; null for any other conversation.
+ final String? reviewOf;
final int lastMessageSequence;
/// Its newest message in the main stream: a reply only in its thread
diff --git a/mobile/lib/swarm/review_verdict.dart b/mobile/lib/swarm/review_verdict.dart
new file mode 100644
index 000000000..7063ab821
--- /dev/null
+++ b/mobile/lib/swarm/review_verdict.dart
@@ -0,0 +1,36 @@
+import 'dart:math';
+
+/// The last review verdict a group's reviewer posted: `Ready: yes|no|with fixes`,
+/// with the revision it covers when the message names one.
+class SuperTabVerdict {
+ const SuperTabVerdict(this.ready, this.revision);
+ final String ready;
+ final String? revision;
+
+ String get label =>
+ revision == null ? 'Ready: $ready' : 'Ready: $ready on $revision';
+}
+
+final _ready = RegExp(
+ r'^\W*Ready:\s*(yes|no|with fixes)\b',
+ caseSensitive: false,
+ multiLine: true,
+);
+final _labeledRevision = RegExp(
+ r'\b(?:revision|head|commit|sha)\b\W{0,3}([0-9a-f]{7,40})\b',
+ caseSensitive: false,
+);
+final _bareRevision = RegExp(r'\b(?=[0-9a-f]*\d)[0-9a-f]{7,40}\b');
+
+/// Null when the text carries no `Ready:` line.
+SuperTabVerdict? parseSuperTabVerdict(String text) {
+ final ready = _ready.firstMatch(text)?.group(1);
+ if (ready == null) return null;
+ final revision =
+ _labeledRevision.firstMatch(text)?.group(1) ??
+ _bareRevision.firstMatch(text)?.group(0);
+ return SuperTabVerdict(
+ ready.toLowerCase(),
+ revision?.substring(0, min(revision.length, 9)),
+ );
+}
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index 6dc81b097..832691765 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -28,6 +28,7 @@ import 'swarm_face.dart';
import 'swarm_file_picker.dart';
import 'swarm_outgoing_files.dart';
import 'swarm_inbox.dart';
+import 'swarm_live_card.dart';
import 'swarm_message_row.dart';
import 'swarm_need_rows.dart';
import 'swarm_profile_sheet.dart';
@@ -1153,10 +1154,17 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
final lit = _lit == m.id, followed = _target == m.id;
final acting = _acting == m.id;
final reactions = c.reactionsOf(m);
+ // A card's facts are its group's: only a reader of the group has
+ // them, and a change to them draws the row again.
+ final group = c.conversation;
+ final card = snapshot == null || group == null
+ ? null
+ : SwarmCardFacts.of(snapshot, group, m.id, c.messages);
return _row(
key,
(
m,
+ card,
name,
swarmLookKey(look),
role,
@@ -1211,6 +1219,12 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
? () => _openThread(c, root)
: () => _reply(c, m),
inThread: root != null,
+ card: card == null
+ ? null
+ : SwarmLiveCard(
+ key: ValueKey('swarm-card-${m.id}'),
+ facts: card,
+ ),
thread: line == null || line.replies == 0
? null
: SwarmThreadLine(
@@ -1594,6 +1608,7 @@ class _ChatView {
required this.decisions,
required this.buddyProject,
required this.hint,
+ required this.cards,
});
/// [c] as its Swarm's read and asks have it now. The decisions of [before]
@@ -1655,6 +1670,15 @@ class _ChatView {
hint: buddyProject != null && swarmBuddy(reader, buddyProject) != null
? 'Message $buddy'
: 'Message',
+ cards: snapshot == null || group == null
+ ? const {}
+ : {
+ for (final id in {
+ ?group.cards.task,
+ for (final pull in group.cards.pullRequests) pull.messageId,
+ })
+ id: ?SwarmCardFacts.of(snapshot, group, id, c.messages),
+ },
);
}
@@ -1683,6 +1707,11 @@ class _ChatView {
/// What the empty composer says.
final String hint;
+ /// Each live card's facts by its message's id: a change to the group that
+ /// changes a card draws the chat again (its rows make their own from the
+ /// messages too).
+ final Map<String, SwarmCardFacts> cards;
+
/// 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;
@@ -1714,7 +1743,8 @@ class _ChatView {
listEquals(other.mentionable, mentionable) &&
identical(other.decisions, decisions) &&
other.buddyProject == buddyProject &&
- other.hint == hint;
+ other.hint == hint &&
+ mapEquals(other.cards, cards);
@override
int get hashCode => Object.hash(
@@ -1728,6 +1758,7 @@ class _ChatView {
decisions,
buddyProject,
hint,
+ Object.hashAll(cards.values),
);
}
diff --git a/mobile/lib/swarm/swarm_live_card.dart b/mobile/lib/swarm/swarm_live_card.dart
new file mode 100644
index 000000000..68c65896e
--- /dev/null
+++ b/mobile/lib/swarm/swarm_live_card.dart
@@ -0,0 +1,146 @@
+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/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import 'swarm_live_card_facts.dart';
+import 'swarm_message_row.dart';
+
+export 'swarm_live_card_facts.dart';
+
+/// Like a Slack app's message that updates itself (backend superTabs/cards.ts,
+/// the desktop's live_card.dart): a task or a pull request drawn as one card
+/// under its message, changing in place as the Swarm's state does. On the
+/// phone it shows the Swarm's own facts: the task, its checks, the verdict,
+/// each PR's link and a recorded merge.
+class SwarmLiveCard extends StatelessWidget {
+ const SwarmLiveCard({super.key, required this.facts});
+
+ final SwarmCardFacts facts;
+
+ @override
+ Widget build(BuildContext context) {
+ final task = facts.task;
+ final muted = swarmChatText(14, color: AppPalette.textSecondary);
+ return Padding(
+ padding: const EdgeInsets.only(top: AppSpace.s),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: AppPalette.cardBg,
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ border: Border.all(color: AppGlass.hair),
+ ),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ child: IntrinsicHeight(
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ // A colored edge, as a Slack attachment has.
+ SizedBox(
+ width: AppSpace.xs,
+ child: ColoredBox(color: AppPalette.swarmAccent),
+ ),
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.m,
+ vertical: AppSpace.s,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (task != null) ...[
+ Text(
+ task.title,
+ style: swarmChatText(15.5, weight: FontWeight.w600),
+ ),
+ Text(task.line, style: muted),
+ ],
+ for (final pull in facts.pulls) _PullRow(pull),
+ if (facts.review case final review?)
+ Padding(
+ padding: const EdgeInsets.only(top: AppSpace.xs),
+ child: Text(review, style: muted),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// One pull request on a card: its repository and number, and Merged once the
+/// Swarm recorded it. Opens in the in-app browser.
+class _PullRow extends StatelessWidget {
+ const _PullRow(this.pull);
+
+ final SwarmCardPull pull;
+
+ @override
+ Widget build(BuildContext context) {
+ final url = pull.url;
+ final label = '${url.pathSegments[1]} · PR #${url.pathSegments[3]}';
+ return Semantics(
+ button: true,
+ link: true,
+ label: pull.merged ? 'Open $label, merged' : 'Open $label',
+ excludeSemantics: true,
+ child: InkWell(
+ key: ValueKey('swarm-card-pr-$url'),
+ onTap: () {
+ HapticFeedback.selectionClick();
+ unawaited(launchUrl(url, mode: LaunchMode.inAppBrowserView));
+ },
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: 44),
+ child: Row(
+ children: [
+ Icon(
+ pull.merged
+ ? LucideIcons.gitMerge300
+ : LucideIcons.gitPullRequest300,
+ size: 16,
+ color: pull.merged
+ ? AppPalette.swarmAccent
+ : AppPalette.textSecondary,
+ ),
+ const SizedBox(width: AppSpace.s),
+ // Its words wrap together at large text, Merged after the name.
+ Expanded(
+ child: Wrap(
+ spacing: AppSpace.s,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ Text(label, style: swarmChatText(15)),
+ if (pull.merged)
+ Text(
+ 'Merged',
+ style: swarmChatText(14, color: AppPalette.swarmAccent),
+ ),
+ Icon(
+ LucideIcons.externalLink300,
+ size: 14,
+ color: AppPalette.textFaint,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_live_card_facts.dart b/mobile/lib/swarm/swarm_live_card_facts.dart
new file mode 100644
index 000000000..e46bed667
--- /dev/null
+++ b/mobile/lib/swarm/swarm_live_card_facts.dart
@@ -0,0 +1,143 @@
+import 'package:flutter/foundation.dart';
+
+import 'model.dart';
+import 'review_verdict.dart';
+
+/// A task's state in a few words, from its assignment's status: the desktop's
+/// `superTabCardStatus` (live_card.dart), word for word.
+String swarmCardStatus(Map<String, dynamic>? assignment) =>
+ switch (assignment?['status']) {
+ 'planned' => 'Planned',
+ 'working' => 'Working',
+ 'needs_human' => 'Waiting on a person',
+ 'blocked' => 'Blocked',
+ 'review' => 'In review',
+ 'done' => 'Done',
+ 'stopped' || 'lost' => 'Stopped',
+ 'cancelled' => 'Cancelled',
+ 'reconciling' => 'Checking its agent',
+ _ => 'Not started',
+ };
+
+/// "Reviewer: Ivy · Ready: no on 050bab807", as the desktop's
+/// `SuperTabController.reviewLine` reads it: the newest review chat's recorded
+/// verdict for [group] (its result or check evidence), else the newest
+/// `Ready:` line a reviewer posted in [messages]. Only workgroups of
+/// [group]'s own project count as its review chats: never a Buddy chat or the
+/// Leads chat. Null without a reviewer.
+String? swarmReviewLine(
+ SuperTabSnapshot snapshot,
+ SuperTabConversation group,
+ List<SuperTabMessage> messages,
+) {
+ final reviews =
+ snapshot.conversations
+ .where(
+ (c) =>
+ c.reviewOf == group.id &&
+ c.projectId == group.projectId &&
+ c.kind == null,
+ )
+ .toList()
+ ..sort((a, b) => (b.number ?? 0).compareTo(a.number ?? 0));
+ final reviewers = {
+ for (final r in [
+ ...snapshot.reviewers(group),
+ for (final review in reviews) ...snapshot.reviewers(review),
+ ])
+ r.id: r,
+ }.values;
+ if (reviewers.isEmpty) return null;
+ final ids = {for (final r in reviewers) r.id};
+ final recorded = reviews
+ .expand(
+ (review) => [
+ review.assignment?['result'],
+ for (final check in review.checks) check['evidence'],
+ ],
+ )
+ .whereType<String>();
+ final posted = messages.reversed
+ .where((m) => m.fromAgent && ids.contains(m.authorId))
+ .map((m) => m.text);
+ final verdict = [
+ ...recorded,
+ ...posted,
+ ].map(parseSuperTabVerdict).nonNulls.firstOrNull;
+ final names = reviewers.map((r) => snapshot.agentName(r.id)).join(', ');
+ return 'Reviewer: $names · ${verdict?.label ?? 'No verdict yet'}';
+}
+
+/// One pull request on a card: its link and whether the Swarm recorded its
+/// merge.
+typedef SwarmCardPull = ({Uri url, bool merged});
+
+/// What a live card shows (backend superTabs/cards.ts): the Swarm's own facts
+/// of its group, which only a reader of the group has. The phone reads no
+/// GitHub (Lead, 10-29), so no title or CI of a PR. Equal facts draw the
+/// same card: the chat keeps the row as it was.
+@immutable
+class SwarmCardFacts {
+ const SwarmCardFacts({
+ required this.task,
+ required this.pulls,
+ required this.review,
+ });
+
+ /// The task's title and its state line, for a task card.
+ final ({String title, String line})? task;
+ final List<SwarmCardPull> pulls;
+ final String? review;
+
+ /// The card message [messageId] is in [group], or null for a plain message.
+ /// A task card lists every PR its group linked; a PR card its own.
+ static SwarmCardFacts? of(
+ SuperTabSnapshot snapshot,
+ SuperTabConversation group,
+ String messageId,
+ List<SuperTabMessage> messages,
+ ) {
+ final card = group.cards.of(messageId);
+ if (card == null) return null;
+ final merged = {
+ for (final c in group.cards.pullRequests)
+ if (c.merged) c.url,
+ };
+ final urls = card.task
+ ? group.pullRequestUrls
+ : [for (final c in card.pullRequests) c.url];
+ final checks = group.checks;
+ // A failed check keeps its evidence; only a pass names who passed it
+ // (backend commands.ts `work.check`).
+ final passed = checks.where((c) => c['passedBy'] != null).length;
+ return SwarmCardFacts(
+ task: card.task
+ ? (
+ title: group.label,
+ line: [
+ swarmCardStatus(group.assignment),
+ if (checks.isNotEmpty)
+ '$passed of ${checks.length} checks passed',
+ ].join(' · '),
+ )
+ : null,
+ pulls: [
+ for (final url in urls)
+ if (Uri.tryParse(url) case final uri?
+ when uri.pathSegments.length == 4)
+ (url: uri, merged: merged.contains(url)),
+ ],
+ review: swarmReviewLine(snapshot, group, messages),
+ );
+ }
+
+ @override
+ bool operator ==(Object other) =>
+ other is SwarmCardFacts &&
+ other.task == task &&
+ other.review == review &&
+ listEquals(other.pulls, pulls);
+
+ @override
+ int get hashCode => Object.hash(task, review, Object.hashAll(pulls));
+}
diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dart
index 5283196c5..6ac2c447d 100644
--- a/mobile/lib/swarm/swarm_message_row.dart
+++ b/mobile/lib/swarm/swarm_message_row.dart
@@ -204,6 +204,7 @@ class SwarmMessageRow extends StatelessWidget {
this.reactions,
this.thread,
this.below,
+ this.card,
this.onLongPress,
});
@@ -233,6 +234,10 @@ class SwarmMessageRow extends StatelessWidget {
/// Who wrote it, in a sheet; null where nothing opens.
final VoidCallback? onAuthor;
+ /// Under its text and files: the live card this message is
+ /// (swarm_live_card.dart); null for a plain message.
+ final Widget? card;
+
/// Drawn under its text and files: its reaction counts.
final Widget? reactions;
@@ -320,6 +325,7 @@ class SwarmMessageRow extends StatelessWidget {
link: swarmAttachmentLink(file.url),
),
),
+ ?card,
?reactions,
?thread,
?below,
diff --git a/mobile/test/swarm/desktop_parity_test.dart b/mobile/test/swarm/desktop_parity_test.dart
index d5e72a044..599ff8ac1 100644
--- a/mobile/test/swarm/desktop_parity_test.dart
+++ b/mobile/test/swarm/desktop_parity_test.dart
@@ -14,6 +14,12 @@ import 'package:harness_mobile/swarm/swarm_buddy.dart';
const _copies = {
'lib/swarm/parts.dart': 'lib/super_tabs/parts.dart',
'lib/swarm/profile_model.dart': 'lib/super_tabs/profile_model.dart',
+ // Live cards (Slack parity, #2212): which messages are cards, and the
+ // review verdict a card shows. The phone reads no GitHub yet (Lead, 10-29:
+ // that request is a security change of its own), so Desktop's PR facts
+ // reader has no copy here.
+ 'lib/swarm/live_card_model.dart': 'lib/super_tabs/live_card_model.dart',
+ 'lib/swarm/review_verdict.dart': 'lib/super_tabs/review_verdict.dart',
};
/// The phone's model is ahead of main's desktop copy, so it is no exact copy
diff --git a/mobile/test/swarm/swarm_live_card_test.dart b/mobile/test/swarm/swarm_live_card_test.dart
new file mode 100644
index 000000000..1affe0fd6
--- /dev/null
+++ b/mobile/test/swarm/swarm_live_card_test.dart
@@ -0,0 +1,493 @@
+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' 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_live_card.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' show MemoryKeyValueStore;
+import 'swarm_fixture.dart';
+
+/// Set to a folder to write the phone cards' screenshots there (run this file
+/// alone, on a Mac). Scripted data only.
+final shots = Platform.environment['SWARM_CARD_SHOTS'];
+
+const pr = 'https://github.com/example/app/pull/7';
+const other = 'https://github.com/example/app/pull/8';
+
+/// The phone's live cards (Slack parity, #2212): a task's brief and the first
+/// message linking each PR are cards that change in place as the Swarm's state
+/// does. The phone reads no GitHub (Lead, 10-29), so a card shows what the
+/// Swarm knows: the task, its checks, the verdict, a recorded merge, the link.
+void main() {
+ // Real faces for the screenshots, read outside a test's fake clock.
+ 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();
+ }
+ });
+
+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';
+
+ Map<String, dynamic> message(
+ String id,
+ int sequence,
+ String text, {
+ String author = 'agent-builder',
+ }) => {
+ 'id': id,
+ 'conversationId': 'g1',
+ 'text': text,
+ 'sequence': sequence,
+ 'thread': id,
+ 'author': {
+ 'kind': 'agent',
+ 'id': author,
+ 'name': author == 'agent-lead' ? 'River' : 'Nova',
+ },
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': DateTime.utc(2026, 10, 29, 1, sequence).toIso8601String(),
+ };
+
+ /// Chat g1, "#12 Fix login": River's brief is its task card, Nova's
+ /// "Opened" its PR card; one of its two checks passed.
+ Map<String, dynamic> work({
+ String status = 'working',
+ int? mergedAt,
+ List<String> prs = const [pr],
+ }) => {
+ ...groupData(
+ 'g1',
+ title: 'Fix login',
+ number: 12,
+ agentIds: ['agent-lead', 'agent-builder'],
+ status: status,
+ lastMessageSequence: 3,
+ ),
+ 'checks': [
+ {
+ 'id': 'a',
+ 'description': 'Tests pass',
+ 'evidence': 'ok',
+ 'passedBy': 'agent:agent-builder',
+ },
+ // A failed check, as the server records one: its evidence, nobody
+ // passing it.
+ {
+ 'id': 'b',
+ 'description': 'Screens',
+ 'evidence': 'Two screens cut off',
+ 'passedBy': null,
+ },
+ ],
+ 'pullRequestUrls': prs,
+ 'cards': {
+ 'task': 'm1',
+ 'pullRequests': [
+ {'url': pr, 'messageId': 'm2', 'mergedAt': ?mergedAt},
+ ],
+ },
+ };
+
+ /// Ivy reviewed #12 in the review chat g2 of [projectId].
+ Map<String, dynamic> review({String projectId = project}) => {
+ ...groupData(
+ 'g2',
+ title: 'Review: Fix login',
+ number: 13,
+ agentIds: ['agent-review'],
+ status: 'done',
+ workerId: 'agent-review',
+ ),
+ 'projectId': projectId,
+ 'reviewOf': 'g1',
+ 'assignment': {
+ 'id': 'attempt-g2',
+ 'agentId': 'agent-review',
+ 'status': 'done',
+ 'result': 'Ready: no — revision 050bab807. Two findings.',
+ },
+ };
+
+ FakeSwarm backend({
+ List<Map<String, dynamic>>? groups,
+ List<Map<String, dynamic>> agents = const [],
+ }) {
+ 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: groups ?? [work(), review()],
+ agents: [
+ agent('agent-lead', name: 'Lead', displayName: 'River'),
+ agent('agent-builder', displayName: 'Nova'),
+ {...agent('agent-review', displayName: 'Ivy'), 'role': 'reviewer'},
+ ...agents,
+ ],
+ );
+ 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': [
+ message('m3', 3, 'CI is running on $pr'),
+ message('m2', 2, 'Opened $pr'),
+ message('m1', 1, 'Add a sign-in screen.', author: 'agent-lead'),
+ ],
+ 'next': null,
+ 'threads': <Object>[],
+ };
+ return fake;
+ }
+
+ Future<SwarmHost> pump(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ Brightness brightness = Brightness.dark,
+ double textScale = 1,
+ Key? boundary,
+ }) async {
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ upload: refuseSwarmUpload,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(textScale)),
+ child: SwarmScope(notifier: host, child: child!),
+ ),
+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return host;
+ }
+
+ /// The Swarm's next read brings [groups].
+ Future<void> change(
+ WidgetTester tester,
+ SwarmHost host,
+ FakeSwarm fake,
+ List<Map<String, dynamic>> groups,
+ ) async {
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c3', lastChangedAt: 200, groups: groups);
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ }
+
+ Finder card(String messageId) =>
+ find.byKey(ValueKey('swarm-card-$messageId'));
+ Finder inCard(String messageId, String text) =>
+ find.descendant(of: card(messageId), matching: find.text(text));
+
+ testWidgets('a task card shows its title, status, checks, PRs and the '
+ 'verdict from the review chat', (tester) async {
+ await pump(tester, backend());
+ expect(card('m1'), findsOneWidget);
+ expect(inCard('m1', '#12 Fix login'), findsOneWidget);
+ expect(inCard('m1', 'Working · 1 of 2 checks passed'), findsOneWidget);
+ expect(inCard('m1', 'app · PR #7'), findsOneWidget);
+ expect(
+ inCard('m1', 'Reviewer: Ivy · Ready: no on 050bab807'),
+ findsOneWidget,
+ );
+ // A later link of the same PR stays a plain message.
+ expect(card('m3'), findsNothing);
+ });
+
+ testWidgets('a PR card updates in place when its merge is recorded', (
+ tester,
+ ) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ expect(inCard('m2', 'app · PR #7'), findsOneWidget);
+ expect(inCard('m2', 'Merged'), findsNothing);
+ final built = <String>[];
+ final before = debugOnRebuildDirtyWidget;
+ debugOnRebuildDirtyWidget = (element, _) {
+ if (element.widget case SwarmMessageRow(:final message)) {
+ built.add(message.id);
+ }
+ };
+ try {
+ await change(tester, host, fake, [part('g1', 9, work(mergedAt: 5))]);
+ } finally {
+ debugOnRebuildDirtyWidget = before;
+ }
+ // Both cards show the merge; the plain message is drawn as it was.
+ expect(built.toSet(), {'m1', 'm2'});
+ expect(inCard('m2', 'Merged'), findsOneWidget);
+ expect(inCard('m1', 'Merged'), findsOneWidget);
+ expect(card('m2'), findsOneWidget);
+ });
+
+ testWidgets('a task card follows its task in place', (tester) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ await change(tester, host, fake, [part('g1', 9, work(status: 'review'))]);
+ expect(inCard('m1', 'In review · 1 of 2 checks passed'), findsOneWidget);
+ await change(tester, host, fake, [
+ part('g1', 10, work(status: 'done', prs: [pr, other])),
+ ]);
+ expect(inCard('m1', 'Done · 1 of 2 checks passed'), findsOneWidget);
+ expect(inCard('m1', 'app · PR #8'), findsOneWidget);
+ });
+
+ testWidgets('a group taken away while open leaves no card behind', (
+ tester,
+ ) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ expect(card('m1'), findsOneWidget);
+ await change(tester, host, fake, [
+ {'key': 'g1', 'version': 9, 'changedAt': 9, 'deleted': true},
+ ]);
+ expect(card('m1'), findsNothing);
+ expect(card('m2'), findsNothing);
+ expect(find.text('#12 Fix login'), findsNothing);
+ });
+
+ testWidgets('a review chat of another project is never read for a card', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ backend(
+ groups: [
+ work(),
+ review(projectId: 'other'),
+ ],
+ ),
+ );
+ expect(inCard('m1', '#12 Fix login'), findsOneWidget);
+ expect(find.textContaining('Ivy'), findsNothing);
+ expect(find.textContaining('050bab807'), findsNothing);
+ });
+
+ testWidgets('screenshots for review: 375 points, both themes, large text', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(375, 812));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final shotsOf = [
+ (HarnessPalette.paper, 1.0, 'light'),
+ (HarnessPalette.graphite, 1.0, 'dark'),
+ (HarnessPalette.graphite, 1.75, 'dark-175'),
+ ];
+ for (final (palette, scale, name) in shotsOf) {
+ grid.AppTheme.palette.value = palette;
+ grid.AppTheme.brightness.value = palette.brightness;
+ final boundary = GlobalKey();
+ final fake = backend(
+ groups: [
+ work(mergedAt: 5, prs: [pr, other]),
+ review(),
+ ],
+ );
+ await pump(
+ tester,
+ fake,
+ brightness: palette.brightness,
+ textScale: scale,
+ boundary: boundary,
+ );
+ 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-cards-$name.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.pumpWidget(const SizedBox());
+ }
+ grid.AppTheme.palette.value = HarnessPalette.graphite;
+ grid.AppTheme.brightness.value = Brightness.dark;
+ }, skip: shots == null || !Platform.isMacOS);
+
+ testWidgets('another project\'s reviewer of the same name is never read', (
+ tester,
+ ) async {
+ // Two Ivys: this project's reviews #12 here; another project's Ivy
+ // "reviews" it from a chat of that project.
+ final elsewhere = {
+ ...review(projectId: 'other'),
+ 'id': 'g3',
+ 'number': 14,
+ 'agentIds': ['agent-ivy-2'],
+ 'assignment': {
+ 'id': 'attempt-g3',
+ 'agentId': 'agent-ivy-2',
+ 'status': 'done',
+ 'result': 'Ready: yes on deadbeef1',
+ },
+ };
+ await pump(
+ tester,
+ backend(
+ groups: [work(), review(), elsewhere],
+ agents: [
+ {
+ ...agent('agent-ivy-2', displayName: 'Ivy'),
+ 'projectId': 'other',
+ 'role': 'reviewer',
+ },
+ ],
+ ),
+ );
+ expect(
+ inCard('m1', 'Reviewer: Ivy · Ready: no on 050bab807'),
+ findsOneWidget,
+ );
+ expect(find.textContaining('deadbeef1'), findsNothing);
+ });
+
+ testWidgets('a Buddy chat or the Leads chat is never read as a review', (
+ tester,
+ ) async {
+ Map<String, dynamic> posing(String id, Map<String, dynamic> chat) => {
+ ...chat,
+ 'reviewOf': 'g1',
+ 'agentIds': ['agent-review'],
+ 'assignment': {
+ 'id': 'attempt-$id',
+ 'agentId': 'agent-review',
+ 'status': 'done',
+ 'result': 'Ready: yes on deadbeef1',
+ },
+ };
+ await pump(
+ tester,
+ backend(
+ groups: [
+ work(),
+ posing('buddy-me', buddyChatData('buddy-me')),
+ posing('leads', {
+ ...groupData('leads', title: 'Leads'),
+ 'kind': 'leads',
+ }),
+ ],
+ ),
+ );
+ expect(inCard('m1', '#12 Fix login'), findsOneWidget);
+ expect(find.textContaining('Ivy'), findsNothing);
+ expect(find.textContaining('deadbeef1'), findsNothing);
+ });
+
+ testWidgets('the verdict goes when the review chat is taken away, and the '
+ 'task card stays', (tester) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ expect(find.textContaining('050bab807'), findsWidgets);
+ await change(tester, host, fake, [
+ {'key': 'g2', 'version': 9, 'changedAt': 9, 'deleted': true},
+ ]);
+ expect(inCard('m1', '#12 Fix login'), findsOneWidget);
+ expect(find.textContaining('050bab807'), findsNothing);
+ expect(find.textContaining('Ivy'), findsNothing);
+ });
+
+ testWidgets('a failed read keeps the card as it was, with no loading left', (
+ tester,
+ ) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ throw SuperTabFailure('UNAVAILABLE', 'offline', statusCode: 503);
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(inCard('m1', 'Working · 1 of 2 checks passed'), findsOneWidget);
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ });
+
+ testWidgets('a group read without its cards shows plain messages', (
+ tester,
+ ) async {
+ // An older backend, or a group whose cards never came: nothing is drawn
+ // half way.
+ await pump(
+ tester,
+ backend(
+ groups: [
+ {...work()}..remove('cards'),
+ ],
+ ),
+ );
+ expect(card('m1'), findsNothing);
+ expect(find.text('Add a sign-in screen.'), findsOneWidget);
+ });
+
+ test("a task's status reads in the desktop's words", () {
+ final desktop = File('../desktop/lib/super_tabs/live_card.dart')
+ .readAsStringSync();
+ final words = {
+ for (final m in RegExp(
+ r"((?:'\w+'(?: \|\| )?)+) => '([^']+)'",
+ ).allMatches(desktop))
+ for (final status in RegExp(r"'(\w+)'").allMatches(m.group(1)!))
+ status.group(1)!: m.group(2)!,
+ };
+ expect(words, isNotEmpty);
+ for (final MapEntry(key: status, value: word) in words.entries) {
+ expect(swarmCardStatus({'status': status}), word, reason: status);
+ }
+ expect(swarmCardStatus(null), 'Not started');
+ });
+}