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.

Merge batch 11-03 bm: #2672 (#2706)

0xken15426223cb1a3e
diff --git a/docs/plans/2026-11-03-phone-swarm-message-markdown-plan.md b/docs/plans/2026-11-03-phone-swarm-message-markdown-plan.md
new file mode 100644
index 000000000..3ab257bde
--- /dev/null
+++ b/docs/plans/2026-11-03-phone-swarm-message-markdown-plan.md
@@ -0,0 +1,112 @@
+# Phone Swarm Message Markdown Implementation Plan
+
+> **Execution:** The assigned Engineer implements each task natively in this worktree, test first, then requests one independent review from Cleo.
+
+**Goal:** Render Swarm phone message prose with the same Markdown subset as Desktop and make web links and numbered conversations open from messages.
+
+**Architecture:** Replace the phone message's plain prose span with a focused Markdown widget styled with existing phone tokens. Keep the existing fenced-code widget and message-row actions, and pass conversation-number references from the loaded Swarm snapshot so links can use existing navigation.
+
+**Tech Stack:** Flutter, `flutter_markdown_plus` and its `markdown` syntax extensions (the same maintained Markdown renderer Desktop uses), existing `url_launcher`, Flutter widget tests.
+
+**Spec:** Harness task #2256, conversation `e91e0b56aa51d3beeb519dd7`.
+
+## Screen sketch
+
+```text
+┌─────────────────────────────────────────┐
+│ River · PM 10:42 │
+│ │
+│ Findings │
+│ │
+│ The **reconnect** change is ready. │
+│ • Handles *slow* networks │
+│ • See #42 and the review link │
+│ │
+│ ┃ “No agent work was lost.” │
+│ │
+│ ┌─────────────────────────────────────┐ │
+│ │ name.txt Copy │ │
+│ │ one line of code │ │
+│ └─────────────────────────────────────┘ │
+└─────────────────────────────────────────┘
+```
+
+Web links and `#42` render as phone link text and open their destination when tapped. The message surface still opens its existing reply action on a non-link tap and its existing long-press menu on a hold.
+
+## Global Constraints
+
+- Mobile only (`mobile/`); base the change on current `main`.
+- Follow the existing Swarm screen styles and design tokens; add no colors or icons.
+- Never install builds on anyone's phone; tests use fakes and never sign out a real account.
+- Keep long press, reply tap, code Copy/Show more, and scrolling for long reports working.
+- Add no on/off switch. If the Markdown package is added to mobile, use the maintained renderer already used by Desktop and note that choice in the PR.
+- Put the ASCII sketch and this plan in the draft PR before implementation; commit failing tests before production changes.
+
+## Review Focus
+
+- A tap on a Markdown link or `#N` must not also trigger the message's reply action; exercise the real nested gesture behavior.
+- A long press that starts on a rendered link must still open the message's existing menu.
+- Long reports with headings, lists, tables, and links must lay out and scroll without overflow.
+- Code spans and fenced or indented code must not become tappable links or lose literal Markdown characters.
+- Unknown conversation numbers and non-HTTP(S) link schemes must not open an unintended destination.
+
+---
+
+### Task 1: Render Markdown in message prose
+
+**Files:**
+- Create: `mobile/lib/swarm/swarm_message_text.dart`
+- Create: `mobile/lib/swarm/swarm_message_style.dart` (the chat text and surface tokens shared by the row and renderer)
+- Modify: `mobile/lib/swarm/swarm_message_row.dart`
+- Test: `mobile/test/swarm/swarm_message_markdown_test.dart`
+- Modify: `mobile/pubspec.yaml`, `mobile/pubspec.lock` (only if the renderer is not already a mobile dependency)
+
+**Interfaces:**
+- Consumes: `SwarmTextPart` from `swarm_code_block.dart`, `SwarmMentions`, `swarmChatText`, `AppPalette`, and the existing code-block row.
+- Produces: `SwarmMessageText({required String text, required SwarmMentions mentions, Iterable<String> tagged = const [], Map<String, String> addresses = const {}})`, which renders Markdown prose; `SwarmMessageRow` continues to own code blocks and message actions.
+
+- [x] **Step 1: Write failing widget tests** named `headings render as headings`, `strong and emphasis render with Markdown styles`, `ordered and unordered lists render their items`, `inline code is styled as code`, `quotes render as blockquotes`, `GFM tables render rows and cells`, `prose tap still opens reply`, and `a long report list remains scrollable`.
+- [x] **Step 2: Run the focused widget test on the unchanged implementation** and record the expected failures where Markdown is still literal.
+- [x] **Step 3: Implement `SwarmMessageText`** with `MarkdownBody`, the GitHub Flavored Markdown extension set, and phone design tokens; preserve the existing message prose tap and mention styling.
+- [x] **Step 4: Run the focused widget test** and confirm each element renders and long content has no layout exception.
+- [x] **Step 5: Commit the failing tests, then commit the passing implementation.**
+
+### Task 2: Open web links and numbered conversations
+
+**Files:**
+- Modify: `mobile/lib/swarm/swarm_message_text.dart`
+- Modify: `mobile/lib/swarm/swarm_message_row.dart`
+- Modify: `mobile/lib/swarm/swarm_conversation_page.dart`
+- Test: `mobile/test/swarm/swarm_message_markdown_test.dart`
+- Test: `mobile/test/swarm/swarm_chat_test.dart` (snapshot-backed conversation routing)
+
+**Interfaces:**
+- Consumes: Task 1's `SwarmMessageText`, and loaded `SuperTabConversation.number` values from the Swarm snapshot.
+- Produces: message link taps call `launchUrl` only for validated HTTP(S) URLs; a known `#N` calls the existing conversation opener with that conversation id; unknown references remain plain text.
+
+- [x] **Step 1: Write failing widget tests** named `Markdown web links open their destination without replying`, `bare web links open in the in-app browser`, `a numbered task message opens that task conversation`, `a numbered PR message opens that PR conversation`, `an unknown conversation number does not open a chat`, and `long pressing a rendered link opens the message menu`.
+- [x] **Step 2: Run the focused widget tests on the unchanged implementation** and confirm web destinations and numbered task/PR routing fail.
+- [x] **Step 3: Implement validated web-link handling and snapshot-backed `#N` routing** without changing the message row's outer long-press behavior.
+- [x] **Step 4: Run the focused widget tests** and confirm expected destinations and no unintended reply tap.
+- [x] **Step 5: Commit the failing tests, then commit the passing implementation.**
+
+### Task 3: Capture the long agent report
+
+**Files:**
+- Test: `mobile/test/swarm/swarm_message_markdown_shots_test.dart`
+- Screenshot: `mobile/test/swarm/screenshots/swarm-message-markdown-dark.png`
+- Screenshot: `mobile/test/swarm/screenshots/swarm-message-markdown-light.png`
+
+**Interfaces:**
+- Consumes: the production message row and deterministic fake message/conversation data.
+- Produces: a reviewable image of a long agent report with Markdown and links, included in the PR.
+
+- [x] **Step 1: Add a screenshot test** for a long report containing headings, emphasis, a list, a quote, a table, a web link, `#N`, and a code block, following `swarm_project_c_shots_test.dart`'s environment-selected output convention.
+- [x] **Step 2: Capture the screenshot and inspect that it shows a readable long report.**
+- [x] **Step 3: Attach the screenshot in the PR and commit the screenshot test.**
+
+## Validation
+
+- Run `flutter test test/swarm/swarm_message_markdown_test.dart` from `mobile/` for each Task 1 and Task 2 red/green cycle.
+- Run the affected mobile Swarm widget tests, including existing code-block and chat tests.
+- Generate and inspect the long-report screenshot, then attach it to the PR.
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index 095ecbe39..fc1686eb0 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -38,6 +38,7 @@ import 'swarm_face.dart';
import 'swarm_file_picker.dart';
import 'swarm_outgoing_files.dart';
import 'swarm_inbox.dart';
+import 'swarm_reader.dart';
import 'swarm_live_card.dart';
import 'swarm_message_link.dart';
import 'swarm_message_receipt.dart';
@@ -58,6 +59,33 @@ import 'swarm_unread_line.dart';
import 'swarm_voice.dart';
import 'team_glance.dart';
+final _conversationReferencePattern = RegExp(r'(?<![\w/])#([1-9][0-9]*)(?!\w)');
+
+/// What a message can link to from the current read of its Swarm. A chat may
+/// still hold an older reader while the inbox has replaced it.
+@visibleForTesting
+Map<int, String> swarmNumberedReferences(SwarmReader? reader, String text) {
+ if (reader == null || reader.accessRevoked) return const {};
+ final numbers = _conversationReferencePattern
+ .allMatches(text)
+ .map((match) => int.tryParse(match[1]!))
+ .whereType<int>()
+ .toSet();
+ return {
+ for (final conversation
+ in reader.snapshot?.conversations ?? const <SuperTabConversation>[])
+ if (conversation.number != null && numbers.contains(conversation.number))
+ conversation.number!: conversation.id,
+ };
+}
+
+/// The same current-reader access check used when a numbered link is tapped.
+@visibleForTesting
+bool swarmCanOpenNumberedConversation(SwarmReader? reader, String id) =>
+ reader != null &&
+ !reader.accessRevoked &&
+ reader.snapshot?.conversation(id) != null;
+
/// Opens [conversationId] of Swarm [swarmId] over the current page: a
/// project's own chat as its project ([SwarmOpenedChat]).
void openSwarmConversation(
@@ -933,6 +961,31 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
};
}
+ void _openNumberedConversation(SwarmConversation c, String id) {
+ final reader = _session?.inbox.reader(c.reader.tabId);
+ if (mounted && swarmCanOpenNumberedConversation(reader, id)) {
+ openSwarmConversation(context, widget.swarmId, id);
+ }
+ }
+
+ ({Map<int, String> references, String key}) _numberedReferences(
+ SwarmConversation c,
+ String text,
+ ) {
+ final numbers = _conversationReferencePattern
+ .allMatches(text)
+ .map((match) => int.tryParse(match[1]!))
+ .whereType<int>()
+ .toSet();
+ final reader = _session?.inbox.reader(c.reader.tabId);
+ final references = swarmNumberedReferences(reader, text);
+ return (
+ references: references,
+ key: [for (final number in numbers) '$number:${references[number] ?? ''}']
+ .join(','),
+ );
+ }
+
/// One of thread [t]'s messages as the chat draws its own, less what only
/// the chat has: no quote, no thread line, no Reply (the box is the reply).
Widget _threadRow(
@@ -960,6 +1013,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
taggedAddresses: _taggedOf(c, m),
readerId: c.reader.accountId,
onOpenTask: _taskOpener(c, m),
+ references: _numberedReferences(c, m.text).references,
+ onOpenConversation: (id) => _openNumberedConversation(c, id),
grouped: grouped,
lit: lit,
followed: followed,
@@ -1340,7 +1395,10 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
children: [
Positioned.fill(
child: ListenableBuilder(
- listenable: Listenable.merge([c, _held]),
+ // Message links can target any conversation in the
+ // Swarm, not only this chat. Rebuild when that index
+ // changes even if this chat's messages did not.
+ listenable: Listenable.merge([c, session.inbox, _held]),
builder: (context, _) =>
_messages(context, session, c, view, tty),
),
@@ -1844,10 +1902,13 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
final card = snapshot == null || group == null
? null
: SwarmCardFacts.of(snapshot, group, m.id);
+ final numbered = _numberedReferences(c, m.text);
+ final references = numbered.references;
return _row(
key,
(
m,
+ numbered.key,
// Drop a cached opener when access to its target changes.
snapshot?.conversation(
m.source['taskId'] is String
@@ -1893,6 +1954,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
taggedAddresses: tagged,
readerId: c.reader.accountId,
onOpenTask: _taskOpener(c, m),
+ references: references,
+ onOpenConversation: (id) => _openNumberedConversation(c, id),
grouped: grouped,
lit: lit,
followed: followed,
diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dart
index 0645cc784..9023d3596 100644
--- a/mobile/lib/swarm/swarm_message_row.dart
+++ b/mobile/lib/swarm/swarm_message_row.dart
@@ -12,37 +12,19 @@ import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
export 'swarm_file_links.dart' show swarmAttachmentHost, swarmAttachmentLink;
+export 'swarm_message_style.dart'
+ show swarmChatCard, swarmChatHair, swarmChatText;
import 'model.dart';
import 'swarm_attachment.dart';
import 'swarm_code_block.dart';
import 'swarm_file_links.dart';
+import 'swarm_message_text.dart';
+import 'swarm_message_style.dart';
import 'swarm_face.dart';
import 'swarm_ship_row.dart';
import 'swarm_task_line.dart';
-/// 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);
-
/// `@name` or `@name@domain`, as people tag in chat. Never right after a
/// letter, digit, `@` or `/` (an address, a path, a link), and a name never
/// ends in a dot: `@dee.` closes a sentence. The backend and the desktop read
@@ -293,6 +275,8 @@ class SwarmMessageRow extends StatelessWidget {
this.card,
this.onLongPress,
this.onOpenTask,
+ this.references = const {},
+ this.onOpenConversation,
});
final SuperTabMessage message;
@@ -329,6 +313,12 @@ class SwarmMessageRow extends StatelessWidget {
/// Opens a task held by the current reader; null for an unavailable target.
final VoidCallback? onOpenTask;
+ /// The numbered conversations `#N` links in a message can open.
+ final Map<int, String> references;
+
+ /// Opens a conversation resolved from [references].
+ final ValueChanged<String>? onOpenConversation;
+
/// Null where the person cannot post, or in the thread itself.
final VoidCallback? onReply;
@@ -434,28 +424,16 @@ class SwarmMessageRow extends StatelessWidget {
if (part.code)
SwarmCodeBlock(code: part.text, name: part.name, onTap: onTap)
else
- Semantics(
- button: true,
- hint: 'Reply to this message',
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
+ Padding(
+ padding: const EdgeInsets.only(top: SwarmMessageFrame.bodyGap),
+ child: SwarmMessageText(
+ text: part.text,
+ mentionNames: mentions.names,
+ references: references,
+ tagged: tagged,
+ addresses: taggedAddresses,
onTap: onTap,
- child: Padding(
- padding: const EdgeInsets.only(
- top: SwarmMessageFrame.bodyGap,
- ),
- child: SizedBox(
- width: double.infinity,
- child: Text.rich(
- mentions.span(
- part.text,
- swarmChatText(16, height: 1.42),
- tagged: tagged,
- addresses: taggedAddresses,
- ),
- ),
- ),
- ),
+ onOpenConversation: onOpenConversation,
),
),
for (final file in message.attachments) _attachment(context, file),
diff --git a/mobile/lib/swarm/swarm_message_style.dart b/mobile/lib/swarm/swarm_message_style.dart
new file mode 100644
index 000000000..2a4a21085
--- /dev/null
+++ b/mobile/lib/swarm/swarm_message_style.dart
@@ -0,0 +1,24 @@
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/phone/tty.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+/// The chat's prose in the app's own face: messages, quotes, names and fields.
+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);
diff --git a/mobile/lib/swarm/swarm_message_text.dart b/mobile/lib/swarm/swarm_message_text.dart
new file mode 100644
index 000000000..a8bd1606a
--- /dev/null
+++ b/mobile/lib/swarm/swarm_message_text.dart
@@ -0,0 +1,228 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
+import 'package:markdown/markdown.dart' as md;
+import 'package:url_launcher/url_launcher.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_message_style.dart';
+
+/// Markdown prose in a Swarm message, styled with the phone's chat tokens.
+class SwarmMessageText extends StatelessWidget {
+ const SwarmMessageText({
+ super.key,
+ required this.text,
+ required this.mentionNames,
+ this.references = const {},
+ this.tagged = const [],
+ this.addresses = const {},
+ this.onTap,
+ this.onOpenConversation,
+ });
+
+ final String text;
+ final List<String> mentionNames;
+ final Map<int, String> references;
+ final List<String> tagged;
+ final Map<String, String> addresses;
+ final VoidCallback? onTap;
+ final ValueChanged<String>? onOpenConversation;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final body = swarmChatText(16, height: 1.42);
+ final heading = body.copyWith(fontWeight: FontWeight.w600);
+ final names = [...mentionNames, ...tagged];
+ return Semantics(
+ button: onTap != null,
+ hint: onTap == null ? null : 'Reply to this message',
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: SizedBox(
+ width: double.infinity,
+ child: MarkdownBody(
+ // MarkdownBody caches its parsed tree while its source and style
+ // stay the same. Reparse when a #N target arrives or disappears.
+ key: ValueKey(
+ references.entries
+ .map((entry) => '${entry.key}:${entry.value}')
+ .join(','),
+ ),
+ data: text,
+ extensionSet: md.ExtensionSet.gitHubFlavored,
+ softLineBreak: true,
+ inlineSyntaxes: [
+ _WebAutolink(),
+ _ConversationReference(references),
+ _SwarmMention(names, addresses),
+ ],
+ builders: {'mention': _SwarmMentionBuilder()},
+ styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context))
+ .copyWith(
+ p: body,
+ a: TextStyle(
+ color: AppPalette.accentOnSurface,
+ decoration: TextDecoration.underline,
+ ),
+ h1: AppType.title(),
+ h2: AppType.heading(),
+ h3: heading,
+ h4: heading,
+ h5: heading,
+ h6: heading,
+ strong: const TextStyle(fontWeight: FontWeight.w600),
+ code: tty
+ .style(size: 14)
+ .copyWith(backgroundColor: swarmChatCard(tty)),
+ blockSpacing: 8,
+ listIndent: 20,
+ listBullet: body,
+ blockquote: body.copyWith(color: AppPalette.textSecondary),
+ blockquotePadding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.m,
+ vertical: AppSpace.xs,
+ ),
+ blockquoteDecoration: BoxDecoration(
+ border: Border(
+ left: BorderSide(color: AppPalette.divider, width: 2),
+ ),
+ ),
+ tableHead: heading,
+ tableColumnWidth: const FlexColumnWidth(),
+ tableBody: body,
+ tableBorder: TableBorder.all(color: AppPalette.divider),
+ tableCellsPadding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.s,
+ vertical: AppSpace.xs,
+ ),
+ ),
+ imageBuilder: (uri, title, alt) => Text(
+ alt?.isNotEmpty == true ? 'Image: $alt' : 'Image',
+ style: AppType.caption(color: AppPalette.textSecondary),
+ ),
+ onTapLink: (_, href, _) {
+ final number = href?.startsWith('workgroup:') == true
+ ? int.tryParse(href!.substring(10))
+ : null;
+ final conversation = number == null ? null : references[number];
+ if (conversation != null) {
+ onOpenConversation?.call(conversation);
+ return;
+ }
+ final uri = _webLink(href);
+ if (uri != null) {
+ unawaited(launchUrl(uri, mode: LaunchMode.inAppBrowserView));
+ }
+ },
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+Uri? _webLink(String? href) {
+ final uri = href == null ? null : Uri.tryParse(href);
+ return uri != null &&
+ (uri.scheme == 'https' || uri.scheme == 'http') &&
+ uri.host.isNotEmpty
+ ? uri
+ : null;
+}
+
+/// Keep bare URL destinations as written, including their encoded query.
+class _WebAutolink extends md.AutolinkExtensionSyntax {
+ @override
+ bool onMatch(md.InlineParser parser, Match match) {
+ final source = match[0]!;
+ if (!source.toLowerCase().startsWith('http')) {
+ return super.onMatch(parser, match);
+ }
+ final nodes = md.Document(
+ extensionSet: md.ExtensionSet.gitHubFlavored,
+ encodeHtml: false,
+ ).parseInline(source);
+ final anchor = nodes.firstOrNull;
+ if (anchor is! md.Element ||
+ anchor.tag != 'a' ||
+ _webLink(anchor.textContent) == null) {
+ return super.onMatch(parser, match);
+ }
+ anchor.attributes['href'] = anchor.textContent;
+ parser
+ ..addNode(anchor)
+ ..consume(anchor.textContent.length);
+ return true;
+ }
+}
+
+class _ConversationReference extends md.InlineSyntax {
+ _ConversationReference(this.references)
+ : super(r'(?<![\w/])#([1-9][0-9]*)(?!\w)');
+
+ final Map<int, String> references;
+
+ @override
+ bool onMatch(md.InlineParser parser, Match match) {
+ final number = int.tryParse(match[1]!);
+ if (number == null || !references.containsKey(number)) {
+ parser.addNode(md.Text(match[0]!));
+ return true;
+ }
+ parser.addNode(
+ md.Element.text('a', match[0]!)..attributes['href'] = 'workgroup:$number',
+ );
+ return true;
+ }
+}
+
+class _SwarmMention extends md.InlineSyntax {
+ _SwarmMention(this.names, this.addresses)
+ : super(r'(?<![\w@/])@([\w+-]+(?:\.[\w+-]+)*)(@[\w-]+(?:\.[\w-]+)+)?');
+
+ final List<String> names;
+ final Map<String, String> addresses;
+
+ @override
+ bool onMatch(md.InlineParser parser, Match match) {
+ final name = match[1]!.toLowerCase();
+ final domain = match[2]?.toLowerCase();
+ final tagged = names.any((candidate) {
+ final key = candidate.toLowerCase();
+ final email = addresses[candidate]?.toLowerCase();
+ if (domain == null) return key == name;
+ if (email != null) return '$name$domain' == email;
+ return key == name;
+ });
+ parser.addNode(
+ tagged ? md.Element.text('mention', match[0]!) : md.Text(match[0]!),
+ );
+ return true;
+ }
+}
+
+class _SwarmMentionBuilder extends MarkdownElementBuilder {
+ @override
+ Widget? visitElementAfterWithContext(
+ BuildContext context,
+ md.Element element,
+ TextStyle? preferredStyle,
+ TextStyle? parentStyle,
+ ) => Text.rich(
+ TextSpan(
+ text: element.textContent,
+ style: (parentStyle ?? const TextStyle()).copyWith(
+ color: AppPalette.accentOnSurface,
+ backgroundColor: AppSurface.accentWash,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ );
+}
diff --git a/mobile/lib/swarm/swarm_thread_page.dart b/mobile/lib/swarm/swarm_thread_page.dart
index 054d4a8cc..9684aec2c 100644
--- a/mobile/lib/swarm/swarm_thread_page.dart
+++ b/mobile/lib/swarm/swarm_thread_page.dart
@@ -414,7 +414,13 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {
child: NotificationListener<Notification>(
onNotification: _measured,
child: ListenableBuilder(
- listenable: _thread,
+ // Message links resolve against the inbox's current
+ // reader, which can change independently of this
+ // thread's older conversation reader.
+ listenable: Listenable.merge([
+ _thread,
+ if (_session case final session?) session.inbox,
+ ]),
builder: (context, _) => _body(tty),
),
),
diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock
index 5d3725cac..6a9cde9ef 100644
--- a/mobile/pubspec.lock
+++ b/mobile/pubspec.lock
@@ -315,6 +315,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.1"
+ flutter_markdown_plus:
+ dependency: "direct main"
+ description:
+ name: flutter_markdown_plus
+ sha256: fce641d6c2106cc495de1cd603f97a4f9d615a97a64011928ded380dbdade935
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.12"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
@@ -583,6 +591,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.19"
+ markdown:
+ dependency: "direct main"
+ description:
+ name: markdown
+ sha256: ee85086ad7698b42522c6ad42fe195f1b9898e4d974a1af4576c1a3a176cada9
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.3.1"
matcher:
dependency: transitive
description:
diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml
index e316a71b9..94af37eb2 100644
--- a/mobile/pubspec.yaml
+++ b/mobile/pubspec.yaml
@@ -19,6 +19,9 @@ environment:
dependencies:
flutter:
sdk: flutter
+ # Swarm messages use the same maintained Markdown renderer and GFM parser as Desktop.
+ flutter_markdown_plus: ^1.0.12
+ markdown: ^7.3.1
# `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
diff --git a/mobile/test/swarm/screenshots/swarm-message-markdown-dark.png b/mobile/test/swarm/screenshots/swarm-message-markdown-dark.png
new file mode 100644
index 000000000..bb5ee1578
Binary files /dev/null and b/mobile/test/swarm/screenshots/swarm-message-markdown-dark.png differ
diff --git a/mobile/test/swarm/screenshots/swarm-message-markdown-light.png b/mobile/test/swarm/screenshots/swarm-message-markdown-light.png
new file mode 100644
index 000000000..7d0067d87
Binary files /dev/null and b/mobile/test/swarm/screenshots/swarm-message-markdown-light.png differ
diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dart
index 5c90884d0..c2aeb01c6 100644
--- a/mobile/test/swarm/swarm_chat_test.dart
+++ b/mobile/test/swarm/swarm_chat_test.dart
@@ -14,6 +14,7 @@ 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/model.dart';
import 'package:harness_mobile/swarm/swarm_request.dart';
import 'package:harness_mobile/swarm/swarm_session.dart';
import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';
@@ -103,6 +104,7 @@ void main() {
List<Map<String, dynamic>>? members,
List<Map<String, dynamic>>? projects,
List<Map<String, dynamic>>? agents,
+ List<Map<String, dynamic>> additionalGroups = const [],
Map<String, dynamic> g1 = const {},
}) {
// The Swarm's counts say a decision waits: what has its list read.
@@ -119,6 +121,7 @@ void main() {
head: projects == null ? null : headData(projects: projects),
agents: agents,
groups: [
+ ...additionalGroups,
{
...groupData(
'g1',
@@ -472,6 +475,137 @@ void main() {
expect(opened, ['https://cdn.harness.autonomous.ai/f1/plan.md']);
});
+ testWidgets('a numbered task message opens that task conversation', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ backend(
+ [message('m1', 1, text: '#42')],
+ additionalGroups: [groupData('task-42', number: 42, title: 'Task 42')],
+ ),
+ );
+
+ await tester.tap(find.text('#42', findRichText: true));
+ await tester.pumpAndSettle();
+
+ final pages = tester.widgetList<SwarmConversationPage>(
+ find.byType(SwarmConversationPage),
+ );
+ expect(pages.last.conversationId, 'task-42');
+ });
+
+ testWidgets('a message links when its numbered conversation arrives', (
+ tester,
+ ) async {
+ final fake = backend([message('m1', 1, text: '#42')]);
+ final host = await pump(tester, fake);
+ expect(find.text('#42', findRichText: true), findsOneWidget);
+ final cachedRow = tester.widget<SwarmMessageRow>(
+ find.byWidgetPredicate(
+ (widget) => widget is SwarmMessageRow && widget.message.id == 'm1',
+ ),
+ );
+ expect(cachedRow.references, isEmpty);
+
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
+ cursor: 'c3',
+ lastChangedAt: 200,
+ groups: [
+ part('task-42', 2, groupData('task-42', number: 42, title: 'Task 42')),
+ ],
+ );
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+
+ expect(
+ host.session!.inbox
+ .reader(tab)!
+ .snapshot!
+ .conversation('task-42')
+ ?.number,
+ 42,
+ );
+ final row = tester.widget<SwarmMessageRow>(
+ find.byWidgetPredicate(
+ (widget) => widget is SwarmMessageRow && widget.message.id == 'm1',
+ ),
+ );
+ expect(row.references[42], 'task-42');
+ expect(row, isNot(same(cachedRow)));
+
+ await tester.tap(find.text('#42', findRichText: true));
+ await tester.pumpAndSettle();
+ var pages = tester.widgetList<SwarmConversationPage>(
+ find.byType(SwarmConversationPage),
+ );
+ expect(pages.last.conversationId, 'task-42');
+ final openPages = pages.length;
+ Navigator.of(tester.element(find.byType(SwarmConversationPage).last)).pop();
+ await tester.pumpAndSettle();
+
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
+ cursor: 'c4',
+ lastChangedAt: 300,
+ groups: [
+ {'key': 'task-42', 'version': 3, 'changedAt': 3, 'deleted': true},
+ ],
+ );
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+
+ final revokedRow = tester.widget<SwarmMessageRow>(
+ find.byWidgetPredicate(
+ (widget) => widget is SwarmMessageRow && widget.message.id == 'm1',
+ ),
+ );
+ expect(revokedRow.references, isEmpty);
+ expect(revokedRow, isNot(same(row)));
+
+ await tester.tap(find.text('#42', findRichText: true));
+ await tester.pumpAndSettle();
+ pages = tester.widgetList<SwarmConversationPage>(
+ find.byType(SwarmConversationPage),
+ );
+ expect(pages, hasLength(openPages));
+ });
+
+ testWidgets('a numbered PR message opens that PR conversation', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ backend(
+ [message('m1', 1, text: '#43')],
+ additionalGroups: [groupData('pr-43', number: 43, title: 'PR 43')],
+ ),
+ );
+
+ await tester.tap(find.text('#43', findRichText: true));
+ await tester.pumpAndSettle();
+
+ final pages = tester.widgetList<SwarmConversationPage>(
+ find.byType(SwarmConversationPage),
+ );
+ expect(pages.last.conversationId, 'pr-43');
+ });
+
+ testWidgets('an unknown conversation number does not open a chat', (
+ tester,
+ ) async {
+ await pump(tester, backend([message('m1', 1, text: '#999')]));
+
+ await tester.tap(find.text('#999', findRichText: true));
+ await tester.pumpAndSettle();
+
+ expect(
+ tester.widgetList<SwarmConversationPage>(
+ find.byType(SwarmConversationPage),
+ ),
+ hasLength(1),
+ );
+ });
+
testWidgets('a notification opens an earlier message and highlights it', (
tester,
) async {
@@ -2230,6 +2364,114 @@ void main() {
matching: find.text(text),
);
+ testWidgets('an open thread refreshes numbered links when its target '
+ 'arrives and is revoked', (tester) async {
+ final rootMessage = message('m1', 1, text: '#42', thread: 'm1');
+ final threadLine = line('m1', 1, 2);
+ final fake = backend([rootMessage], threads: [threadLine]);
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {
+ 'id': tab,
+ 'name': 'Phone Swarm',
+ 'ownerId': me,
+ 'lastChangedAt': 100,
+ },
+ ],
+ 'next': null,
+ };
+ fake.routes['$messages?thread=m1'] = (_) => {
+ 'messages': [rootMessage],
+ 'next': null,
+ 'threads': [threadLine],
+ };
+ final host = await pump(tester, fake);
+
+ await tester.tap(key('swarm-thread-line-m1'));
+ await tester.pumpAndSettle();
+ expect(find.text('Thread'), findsOneWidget);
+ final before = tester.widget<SwarmMessageRow>(
+ key('swarm-thread-message-m1'),
+ );
+ expect(before.references, isEmpty);
+
+ final currentReader = host.session!.inbox.reader(tab)!;
+ SuperTabSnapshot currentSnapshot({required bool includeTarget}) =>
+ SuperTabSnapshot.fromJson({
+ 'version': 1,
+ 'id': tab,
+ 'name': 'Phone Swarm',
+ 'ownerId': me,
+ 'people': <Object>[],
+ 'agents': <Object>[],
+ 'machines': <Object>[],
+ 'projects': <Object>[],
+ 'invitations': <Object>[],
+ 'conversations': [
+ groupData('g1', title: 'Fix login'),
+ if (includeTarget)
+ groupData('task-42', number: 42, title: 'Task 42'),
+ ],
+ });
+ // Update what the inbox currently exposes without notifying the older
+ // reader held by the open thread. The changed listing emits an inbox
+ // notification, as a reader replacement does.
+ currentReader.snapshot = currentSnapshot(includeTarget: true);
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {
+ 'id': tab,
+ 'name': 'Phone Swarm updated',
+ 'ownerId': me,
+ 'lastChangedAt': 100,
+ },
+ ],
+ 'next': null,
+ };
+ await host.session!.inbox.refresh();
+ await tester.pumpAndSettle();
+
+ final arrived = tester.widget<SwarmMessageRow>(
+ key('swarm-thread-message-m1'),
+ );
+ expect(arrived.references[42], 'task-42');
+ expect(arrived, isNot(same(before)));
+
+ final pagesBeforeRevocation = tester
+ .widgetList<SwarmConversationPage>(find.byType(SwarmConversationPage))
+ .length;
+ currentReader.snapshot = currentSnapshot(includeTarget: false);
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {
+ 'id': tab,
+ 'name': 'Phone Swarm changed again',
+ 'ownerId': me,
+ 'lastChangedAt': 100,
+ },
+ ],
+ 'next': null,
+ };
+ await host.session!.inbox.refresh();
+ await tester.pumpAndSettle();
+
+ final revoked = tester.widget<SwarmMessageRow>(
+ key('swarm-thread-message-m1'),
+ );
+ expect(revoked.references, isEmpty);
+ expect(revoked, isNot(same(arrived)));
+
+ await tester.tap(inThread('#42'));
+ await tester.pumpAndSettle();
+ expect(
+ tester.widgetList<SwarmConversationPage>(
+ find.byType(SwarmConversationPage),
+ ),
+ hasLength(pagesBeforeRevocation),
+ );
+ expect(find.text('Thread'), findsOneWidget);
+ });
+
Future<void> back(WidgetTester tester) async {
await tester.tap(find.bySemanticsLabel('Back'));
await tester.pumpAndSettle();
diff --git a/mobile/test/swarm/swarm_message_markdown_shots_test.dart b/mobile/test/swarm/swarm_message_markdown_shots_test.dart
new file mode 100644
index 000000000..a3732b2ca
--- /dev/null
+++ b/mobile/test/swarm/swarm_message_markdown_shots_test.dart
@@ -0,0 +1,149 @@
+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/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_message_row.dart';
+
+/// Review captures of a long agent report in both phone themes. Set
+/// `SWARM_MESSAGE_MARKDOWN_SHOTS` to the output folder when capturing them.
+final shots = Platform.environment['SWARM_MESSAGE_MARKDOWN_SHOTS'];
+
+final report =
+ '''
+## Reconnect review
+
+The **retry path** now handles *slow networks* without dropping agent work.
+Read the [pull request](https://github.com/example/mobile/pull/42) and task #42.
+
+### What changed
+
+- Messages resume from the last saved event.
+- The reader can scroll a long report without losing its place.
+- Code remains easy to copy.
+
+> “A disconnected reader should not lose the conversation.”
+
+| Check | Result |
+| --- | --- |
+| Replay | Passed |
+| Links | Open |
+
+```dart
+await reader.resume();
+```
+
+### Agent notes
+
+${[for (var i = 1; i <= 24; i++) '- Finding $i remains visible while scrolling.'].join('\n')}
+''';
+
+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('a long agent report renders in both phone themes', (
+ tester,
+ ) async {
+ if (shots == null) return;
+ addTearDown(tester.view.reset);
+ tester.view
+ ..physicalSize = const Size(390, 844) * 3
+ ..devicePixelRatio = 3;
+ final previousPalette = grid.AppTheme.palette.value;
+ final previousBrightness = grid.AppTheme.brightness.value;
+ addTearDown(() {
+ grid.AppTheme.palette.value = previousPalette;
+ grid.AppTheme.brightness.value = previousBrightness;
+ });
+ final message = SuperTabMessage.fromJson({
+ 'id': 'report-1',
+ 'conversationId': 'conversation-1',
+ 'text': report,
+ 'sequence': 1,
+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},
+ 'createdAt': DateTime.utc(2026, 11, 3, 10, 42).toIso8601String(),
+ });
+ await tester.runAsync(() => Directory(shots!).create(recursive: true));
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ grid.AppTheme.palette.value = palette;
+ grid.AppTheme.brightness.value = palette.brightness;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: palette.brightness),
+ home: RepaintBoundary(
+ key: const ValueKey('swarm-message-markdown-shot'),
+ child: Scaffold(
+ body: ListView(
+ children: [
+ SwarmMessageRow(
+ message: message,
+ name: 'River',
+ look: (picture: null, status: null),
+ role: 'PM',
+ pm: true,
+ mentions: SwarmMentions(const []),
+ references: const {42: 'task-42'},
+ onOpenConversation: (_) {},
+ grouped: false,
+ lit: false,
+ quote: null,
+ actions: false,
+ onTap: () {},
+ onLongPress: () {},
+ onReply: null,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final boundary = tester.renderObject<RenderRepaintBoundary>(
+ find.byKey(const ValueKey('swarm-message-markdown-shot')),
+ );
+ final name = palette == HarnessPalette.graphite ? 'dark' : 'light';
+ final saved = await tester.runAsync(() async {
+ final image = await boundary.toImage(pixelRatio: 1);
+ try {
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/swarm-message-markdown-$name.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ return true;
+ } finally {
+ image.dispose();
+ }
+ });
+ expect(saved, isTrue);
+ }
+ });
+}
diff --git a/mobile/test/swarm/swarm_message_markdown_test.dart b/mobile/test/swarm/swarm_message_markdown_test.dart
new file mode 100644
index 000000000..73a0a3984
--- /dev/null
+++ b/mobile/test/swarm/swarm_message_markdown_test.dart
@@ -0,0 +1,250 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_message_row.dart';
+
+InlineSpan? paragraph(WidgetTester tester, String text) {
+ for (final rich in tester.widgetList<RichText>(find.byType(RichText))) {
+ if (rich.text.toPlainText() == text) return rich.text;
+ }
+ return null;
+}
+
+List<TextSpan> spans(InlineSpan root) {
+ final found = <TextSpan>[];
+ root.visitChildren((span) {
+ if (span is TextSpan) found.add(span);
+ return true;
+ });
+ return found;
+}
+
+void main() {
+ Future<void> show(
+ WidgetTester tester,
+ String text, {
+ VoidCallback? onTap,
+ VoidCallback? onLongPress,
+ }) async {
+ final message = SuperTabMessage.fromJson({
+ 'id': 'm1',
+ 'conversationId': 'g1',
+ 'text': text,
+ 'sequence': 1,
+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},
+ 'createdAt': DateTime.utc(2026, 1, 1).toIso8601String(),
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListView(
+ children: [
+ SwarmMessageRow(
+ message: message,
+ name: 'River',
+ look: (picture: null, status: null),
+ role: null,
+ mentions: SwarmMentions(const []),
+ grouped: false,
+ lit: false,
+ quote: null,
+ actions: false,
+ onTap: onTap ?? () {},
+ onLongPress: onLongPress ?? () {},
+ onReply: null,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('headings render as headings', (tester) async {
+ await show(tester, '## Build report\n\nA short summary.');
+
+ expect(find.text('## Build report'), findsNothing);
+ expect(find.text('Build report'), findsOneWidget);
+ });
+
+ testWidgets('strong and emphasis render with Markdown styles', (
+ tester,
+ ) async {
+ await show(tester, 'A **bold** and *italic* report.');
+
+ final paragraphText = paragraph(tester, 'A bold and italic report.');
+ expect(paragraphText?.toPlainText(), 'A bold and italic report.');
+ final rendered = spans(paragraphText ?? const TextSpan());
+ expect(
+ rendered.any(
+ (span) =>
+ span.text == 'bold' && span.style?.fontWeight == FontWeight.w600,
+ ),
+ isTrue,
+ );
+ expect(
+ rendered.any(
+ (span) =>
+ span.text == 'italic' && span.style?.fontStyle == FontStyle.italic,
+ ),
+ isTrue,
+ );
+ });
+
+ testWidgets('ordered and unordered lists render their items', (tester) async {
+ await show(tester, '1. First\n2. Second\n\n- Third');
+
+ expect(find.text('1. First'), findsNothing);
+ expect(find.text('2. Second'), findsNothing);
+ expect(find.text('- Third'), findsNothing);
+ for (final item in ['First', 'Second', 'Third']) {
+ expect(find.text(item), findsOneWidget);
+ }
+ });
+
+ testWidgets('inline code renders without Markdown delimiters', (
+ tester,
+ ) async {
+ await show(tester, 'Run `flutter test` before review.');
+
+ final paragraphText = paragraph(tester, 'Run flutter test before review.');
+ expect(paragraphText?.toPlainText(), 'Run flutter test before review.');
+ final rendered = spans(paragraphText ?? const TextSpan());
+ expect(
+ rendered.any(
+ (span) => span.text == 'flutter test' && span.style?.fontFamily != null,
+ ),
+ isTrue,
+ );
+ });
+
+ testWidgets('quotes render without the Markdown quote marker', (
+ tester,
+ ) async {
+ await show(tester, '> No agent work was lost.');
+
+ expect(find.text('> No agent work was lost.'), findsNothing);
+ expect(find.text('No agent work was lost.'), findsOneWidget);
+ });
+
+ testWidgets('GFM tables render rows and cells', (tester) async {
+ await show(tester, '| Area | Result |\n| --- | --- |\n| Chat | Ready |');
+
+ expect(find.textContaining('| Area |'), findsNothing);
+ for (final cell in ['Area', 'Result', 'Chat', 'Ready']) {
+ expect(find.text(cell), findsOneWidget);
+ }
+ });
+
+ testWidgets('a prose tap still opens the message reply action', (
+ tester,
+ ) async {
+ var taps = 0;
+ await show(tester, '## Findings', onTap: () => taps++);
+
+ await tester.tap(find.text('Findings'));
+ expect(taps, 1);
+ });
+
+ testWidgets('a long report list remains scrollable', (tester) async {
+ final report = [for (var i = 1; i <= 80; i++) '- Finding $i'].join('\n');
+ await show(tester, report);
+
+ await tester.scrollUntilVisible(
+ find.text('Finding 80'),
+ 300,
+ scrollable: find.byType(Scrollable).first,
+ );
+ expect(find.text('Finding 80'), findsOneWidget);
+ });
+
+ testWidgets('Markdown web links open their destination without replying', (
+ tester,
+ ) async {
+ final opened = <Object?>[];
+ var replies = 0;
+ 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 show(
+ tester,
+ '[Review](https://example.com/review)',
+ onTap: () => replies++,
+ );
+
+ await tester.tap(find.text('Review', findRichText: true));
+ await tester.pump();
+
+ expect(opened, ['https://example.com/review']);
+ expect(replies, 0);
+ });
+
+ testWidgets('bare web links open in the in-app browser', (tester) async {
+ 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 show(tester, 'https://example.com/review');
+
+ await tester.tap(
+ find.text('https://example.com/review', findRichText: true),
+ );
+ await tester.pump();
+
+ expect(opened, ['https://example.com/review']);
+ });
+
+ testWidgets('non-web Markdown destinations do not open', (tester) async {
+ 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 show(tester, '[Unsafe](javascript:alert(1))');
+
+ await tester.tap(find.text('Unsafe', findRichText: true));
+ await tester.pump();
+
+ expect(opened, isEmpty);
+ });
+
+ testWidgets('Markdown images show a label without creating an image', (
+ tester,
+ ) async {
+ await show(tester, '![private report](https://example.com/private.png)');
+
+ expect(find.text('Image: private report'), findsOneWidget);
+ expect(find.byType(Image), findsNothing);
+ });
+
+ testWidgets('long pressing a rendered link opens the message menu', (
+ tester,
+ ) async {
+ var holds = 0;
+ await show(
+ tester,
+ '[Guide](https://example.com/guide)',
+ onLongPress: () => holds++,
+ );
+
+ await tester.longPress(find.text('Guide', findRichText: true));
+
+ expect(holds, 1);
+ });
+}
diff --git a/mobile/test/swarm/swarm_numbered_references_test.dart b/mobile/test/swarm/swarm_numbered_references_test.dart
new file mode 100644
index 000000000..94a75776f
--- /dev/null
+++ b/mobile/test/swarm/swarm_numbered_references_test.dart
@@ -0,0 +1,44 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart'
+ show swarmCanOpenNumberedConversation, swarmNumberedReferences;
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+
+import 'swarm_fixture.dart';
+
+void main() {
+ test(
+ 'numbered links resolve and authorize against the current reader',
+ () async {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();
+ final stale = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: fake.request,
+ );
+ addTearDown(stale.dispose);
+ await stale.refresh();
+
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
+ groups: [groupData('task-42', number: 42, title: 'Task 42')],
+ );
+ final current = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: fake.request,
+ );
+ addTearDown(current.dispose);
+ await current.refresh();
+
+ expect(swarmNumberedReferences(stale, '#42'), isEmpty);
+ expect(swarmNumberedReferences(current, '#42'), {42: 'task-42'});
+ expect(swarmCanOpenNumberedConversation(stale, 'task-42'), isFalse);
+ expect(swarmCanOpenNumberedConversation(current, 'task-42'), isTrue);
+
+ current.revoke();
+
+ expect(swarmNumberedReferences(current, '#42'), isEmpty);
+ expect(swarmCanOpenNumberedConversation(current, 'task-42'), isFalse);
+ },
+ );
+}