The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Phone: @ people by username, and Copy link to message that opens on the phone (Desktop parity) (#2257)
0xken15606767041fe3
diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xmlindex c19465a47..aa0759d0b 100644--- a/mobile/android/app/src/main/AndroidManifest.xml+++ b/mobile/android/app/src/main/AndroidManifest.xml@@ -52,6 +52,21 @@<action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>+ <!-- harness://swarm/<tab>/<conversation>/<message>: the message link Desktop's Copy+ link to message makes. MainActivity hands it to Dart over `harness/links`, which+ opens the chat at that message; the link names ids only and grants nothing. -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="harness" android:host="swarm" />+ </intent-filter>+ <!-- Off: a message link goes through `harness/links`, never Flutter's own route push,+ which this app's navigator has no route for. -->+ <meta-data+ android:name="flutter_deeplinking_enabled"+ android:value="false"+ /></activity><!-- "Back to Harness" on the last page of "Continue with Google / Apple": brings the appback over the Custom Tab the sign-in ran in, and takes the tab down with it (seediff --git a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.ktindex 8801a1f2d..631ff775e 100644--- a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt+++ b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt@@ -137,6 +137,41 @@ class MainActivity : FlutterActivity() {else -> result.notImplemented()}}++ // `harness/links` — the message links (`harness://swarm/<tab>/<conversation>/<message>`,+ // Desktop's Copy link to message) this phone was asked to open (Dart: `SwarmLinkChannel` in+ // `lib/swarm/swarm_message_link.dart`). Each waits here until Dart's `take` answers it, so one+ // that launched the app, or came before sign-in, waits for the signed-in screen to ask;+ // `arrived` tells a listening Dart that more wait. At most 20 wait, the newest kept.+ links = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "harness/links").also {+ it.setMethodCallHandler { call, result ->+ if (call.method != "take") { result.notImplemented(); return@setMethodCallHandler }+ result.success(ArrayList(waitingLinks))+ waitingLinks.clear()+ }+ }+ receiveLink(intent)+ }++ private var links: MethodChannel? = null+ private val waitingLinks = mutableListOf<String>()++ // singleTop: a link opened while the app runs comes here, not to a new activity.+ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ receiveLink(intent)+ }++ private fun receiveLink(intent: Intent?) {+ if (intent == null) return+ val data = intent.data ?: return+ // Reopened from Recents, Android hands back the intent that first started the app: that link+ // was opened then.+ if ((intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return+ if (intent.action != Intent.ACTION_VIEW || data.scheme != "harness" || data.host != "swarm") return+ waitingLinks.add(data.toString())+ while (waitingLinks.size > 20) waitingLinks.removeAt(0)+ links?.invokeMethod("arrived", null)}private var setupNetwork: ConnectivityManager.NetworkCallback? = nulldiff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swiftindex 2f335dcc3..81938601e 100644--- a/mobile/ios/Runner/AppDelegate.swift+++ b/mobile/ios/Runner/AppDelegate.swift@@ -28,6 +28,69 @@ import UserNotificationsChimeChannel.register(with: engineBridge.pluginRegistry)AppBadgeChannel.register(with: engineBridge.pluginRegistry)DictationChannel.register(with: engineBridge.pluginRegistry)+ LinkChannel.register(with: engineBridge.pluginRegistry)+ }+}++/// `harness/links` — the message links (`harness://swarm/<tab>/<conversation>/<message>`, Desktop's+/// Copy link to message) this phone was asked to open (Dart: `SwarmLinkChannel` in+/// `lib/swarm/swarm_message_link.dart`). A link that launches the app comes with the scene's+/// connection options, one that arrives while it runs through `openURLContexts`; Flutter's scene+/// delegate passes both to plugins registered for scene events, as this is.+///+/// Each link waits here until Dart's `take` answers it (and empties the list), so one that launched+/// the app, or came before sign-in, waits for the signed-in screen to ask; `arrived` tells a+/// listening Dart that more wait. At most 20 wait, the newest kept. Only `harness://swarm` links are+/// taken; any other URL is left to whoever else handles it.+final class LinkChannel: NSObject, FlutterSceneLifeCycleDelegate {+ /// Held here: the registrar keeps scene delegates weakly.+ private static var shared: LinkChannel?++ private let channel: FlutterMethodChannel+ private var waiting: [String] = []++ static func register(with registry: FlutterPluginRegistry) {+ guard let registrar = registry.registrar(forPlugin: "HarnessLinks") else { return }+ let links = LinkChannel(messenger: registrar.messenger())+ registrar.addSceneDelegate(links)+ shared = links+ }++ private init(messenger: FlutterBinaryMessenger) {+ channel = FlutterMethodChannel(name: "harness/links", binaryMessenger: messenger)+ super.init()+ channel.setMethodCallHandler { [weak self] call, result in+ guard call.method == "take", let self else {+ result(FlutterMethodNotImplemented)+ return+ }+ result(self.waiting)+ self.waiting.removeAll()+ }+ }++ @objc(scene:willConnectToSession:options:)+ func scene(+ _ scene: UIScene,+ willConnectTo session: UISceneSession,+ options connectionOptions: UIScene.ConnectionOptions?+ ) -> Bool {+ receive(connectionOptions?.urlContexts ?? [])+ }++ @objc(scene:openURLContexts:)+ func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) -> Bool {+ receive(URLContexts)+ }++ private func receive(_ contexts: Set<UIOpenURLContext>) -> Bool {+ let links = contexts.map(\.url)+ .filter { $0.scheme == "harness" && $0.host == "swarm" }+ .map(\.absoluteString)+ if links.isEmpty { return false }+ waiting = Array((waiting + links).suffix(20))+ channel.invokeMethod("arrived", arguments: nil)+ return true}}diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plistindex da55332a9..8ec34cf40 100644--- a/mobile/ios/Runner/Info.plist+++ b/mobile/ios/Runner/Info.plist@@ -22,6 +22,21 @@<string>$(FLUTTER_BUILD_NAME)</string><key>CFBundleSignature</key><string>????</string>+ <!-- harness://swarm/<tab>/<conversation>/<message>: the message link Desktop's+ Copy link to message makes (and the phone's long-press sheet copies).+ LinkChannel in AppDelegate.swift takes it to Dart, which opens the chat+ at that message; the link names ids only and grants nothing. -->+ <key>CFBundleURLTypes</key>+ <array>+ <dict>+ <key>CFBundleURLName</key>+ <string>ai.autonomous.harness.swarm-link</string>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>harness</string>+ </array>+ </dict>+ </array><key>CFBundleVersion</key><string>$(FLUTTER_BUILD_NUMBER)</string><!-- ⚠️ DECISION, NOT A DEFAULT — and it is currently the OPTIMISTIC one.@@ -35,6 +50,10 @@sits still until someone answers. --><key>ITSAppUsesNonExemptEncryption</key><false/>+ <!-- Off: a message link goes through LinkChannel, never Flutter's own+ route push, which this app's navigator has no route for. -->+ <key>FlutterDeepLinkingEnabled</key>+ <false/><key>LSRequiresIPhoneOS</key><true/><!-- Taking a picture to send to an agent or into a Swarm chat. Picking fromdiff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex 874d08aa3..f3a065f53 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -13,6 +13,7 @@ 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_message_link.dart';import '../swarm/swarm_profile.dart';import '../swarm/swarm_session.dart';import '../swarm/swarm_tabs.dart';@@ -77,6 +78,8 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {/// 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 SwarmLinkChannel _links;+late final SwarmNotices _swarmNotices =switch (widget.notifier.agentNotices.system) {final SwarmNotices notices => notices,@@ -130,6 +133,9 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {)..foreground = state == null || _inFront(state);_swarmFiles = SwarmAttachmentKeeper(_swarm);_swarmNotices.openedSwarm.addListener(_openNoticedSwarm);+ // A message link (Desktop's Copy link to message): one that launched the+ // app or came before sign-in waits on the native side until now.+ _links = SwarmLinkChannel(_openLinkedMessage)..listen();// Install tap callbacks and read the launch payload even when no new notice// arrives. Checking permission does not ask for it.unawaited(noticesEnabled(notices));@@ -169,6 +175,7 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {_openNoticedDevice,);_swarmNotices.openedSwarm.removeListener(_openNoticedSwarm);+ _links.close();_home.dispose();_swarmFiles.dispose();_swarm.dispose();@@ -357,6 +364,33 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {_showNoticedChat(target);}+ /// A message link: Swarm Home, and over it the chat at that message. The+ /// chat says "not open" for one the person cannot read, as for a notice.+ void _openLinkedMessage(SwarmMessageLink link) {+ if (!mounted) return;+ if (_navigator.currentState == null) {+ WidgetsBinding.instance.addPostFrameCallback(+ (_) => _openLinkedMessage(link),+ );+ WidgetsBinding.instance.ensureVisualUpdate();+ return;+ }+ if (_swarm.session == null) {+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ const SnackBar(+ content: Text('Turn on Swarm in Settings to open this link.'),+ ),+ );+ return;+ }+ _showNoticedChat((+ swarmId: link.tabId,+ conversationId: link.conversationId,+ messageId: link.messageId,+ decisionId: null,+ ));+ }+void _showNoticedChat(SwarmNoticeTarget target) {++_navigationRequest;final navigator = _navigator.currentState;diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex b7f92a0e3..65391c28d 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -41,14 +41,27 @@ class SuperTabPerson {generation = row['generation'] as String?,avatar = SuperTabAvatarPicture.fromJson(row['avatar']),status = SuperTabPersonStatus.fromJson(row['status']),- chosenUsername = row['username'] as String?;+ chosenUsername = row['username'] as String?,+ username =+ row['username'] as String? ??+ superTabDefaultUsername(_text(row, 'email'));+ SuperTabPerson._named(SuperTabPerson person, this.username)+ : id = person.id,+ email = person.email,+ role = person.role,+ generation = person.generation,+ avatar = person.avatar,+ status = person.status,+ chosenUsername = person.chosenUsername;final String id, email, role;final SuperTabAvatarPicture? avatar;final SuperTabPersonStatus? status;- /// The username the person chose (desktop usernames); null for a default.- /// The phone still names people by their email prefix until it takes- /// usernames too.+ /// How the Swarm tags them (`@username`), as the server sends it; from an+ /// older server, their default ([superTabUsernames]). Desktop's rule.+ final String username;++ /// The name the server sent; null from a server without usernames.final String? chosenUsername;/// Their status while it lasts.@@ -61,6 +74,43 @@ class SuperTabPerson {bool get canWrite => role == 'owner' || role == 'collaborator';}+/// The name an email's prefix makes: lowercased, only the characters a+/// username takes, never too short. Unnumbered; [superTabUsernames] numbers+/// it. Desktop's `superTabDefaultUsername`, byte for byte.+String superTabDefaultUsername(String email) {+ var prefix = email+ .split('@')+ .first+ .toLowerCase()+ .replaceAll(RegExp(r'[^a-z0-9._-]'), '')+ .replaceFirst(RegExp(r'^[._-]+'), '');+ if (prefix.length > 30) prefix = prefix.substring(0, 30);+ if (prefix.isEmpty) return 'user';+ return prefix.length < 2 ? '${prefix}1' : prefix;+}++/// [people], each with their username: the one the server sent, else (an+/// older server, which sends none) their email prefix numbered (`ken2`) after+/// the people before them, as Desktop names them.+List<SuperTabPerson> superTabUsernames(List<SuperTabPerson> people) {+ final taken = {for (final p in people) ?p.chosenUsername};+ return List.unmodifiable([+ for (final person in people)+ if (person.chosenUsername != null)+ person+ else+ SuperTabPerson._named(person, () {+ final root = superTabDefaultUsername(person.email);+ var name = root;+ for (var n = 2; taken.contains(name); n++) {+ name = '$root$n';+ }+ taken.add(name);+ return name;+ }()),+ ]);+}+class SuperTabAgent {SuperTabAgent.fromJson(Map<String, dynamic> row): id = _text(row, 'id'),@@ -317,6 +367,11 @@ class SuperTabProject {for (final member in row['members'] as List? ?? const [])superTabMap(member)['id'] as String,],+ _memberGenerations = {+ for (final member in row['members'] as List? ?? const [])+ superTabMap(member)['id'] as String:+ superTabMap(member)['generation'] as String?,+ },updateMinutes = (row['updateMinutes'] as num?)?.toInt() ?? 5,repository = row['repository'] is Map? Map.unmodifiable(superTabMap(row['repository']))@@ -327,6 +382,16 @@ class SuperTabProject {final List<SuperTabRole>? roles;final bool isPrivate;final List<String> memberIds;++ /// Each member's Swarm membership when they were added: who left the Swarm+ /// and joined again is not a member until added again.+ final Map<String, String?> _memberGenerations;++ /// Whether [person] is a member at their membership now, as the server+ /// checks (`canReadProject`).+ bool hasMember(SuperTabPerson person) =>+ _memberGenerations.containsKey(person.id) &&+ _memberGenerations[person.id] == person.generation;final int updateMinutes;final Map<String, dynamic>? repository;}@@ -340,7 +405,7 @@ class SuperTabSnapshot {project = row['project'] == null? null: Map.unmodifiable(superTabMap(row['project'])),- people = _list(row['people'], SuperTabPerson.fromJson),+ people = superTabUsernames(_list(row['people'], SuperTabPerson.fromJson)),agents = _list(row['agents'], SuperTabAgent.fromJson),machines = _list(row['machines'] ?? const [],diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartindex 22842171a..cf8a8e8aa 100644--- a/mobile/lib/swarm/swarm_conversation.dart+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -207,7 +207,8 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {int _epoch = 0;String _draft = '';- /// Agents mentioned in the draft, by id, with the token that names them.+ /// Agents and people mentioned in the draft, by id, with the token that+ /// names them: an agent's is a recipient, a person's a tag.final _mentions = <String, String>{};/// The post on its way, then — while its answer never came — retried under@@ -314,24 +315,26 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {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) {+ /// [id]'s name — an agent's or a person's — in place of the @ being typed+ /// ([mentionQuery]), as [mention] adds it.+ void completeMention(String id) {if (mentionQuery case final query?) {_draft = _draft.substring(0, _draft.length - query.length - 1);}- mention(agentId);+ mention(id);}- /// Adds [agentId]'s name to the draft; the post goes to it while the name- /// stays in the text.- void mention(String agentId) {+ /// Adds [id]'s name to the draft: an agent's (the post goes to it) or a+ /// person's username (the post tags them), while the name stays in the+ /// text.+ void mention(String id) {final snapshot = reader.snapshot;if (snapshot == null) return;- final token = '@${snapshot.agentName(agentId)}';+ final person = snapshot.people.where((p) => p.id == id).firstOrNull;+ final token = '@${person?.username ?? snapshot.agentName(id)}';final spaced = _draft.isEmpty || RegExp(r'\s$').hasMatch(_draft);_draft = '$_draft${spaced ? '' : ' '}$token ';- _mentions[agentId] = token;+ _mentions[id] = token;_composer.changed();}@@ -343,6 +346,31 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {return [for (final agentId in group.agentIds) ?snapshot.agent(agentId)];}+ /// The people a post can tag, as Desktop offers them: those who read this+ /// conversation, never the reader. Nobody in the Leads conversation; in a+ /// Buddy chat only its owner reads it. The backend checks each tag again.+ List<SuperTabPerson> get mentionablePeople {+ final snapshot = reader.snapshot;+ final group = conversation;+ if (snapshot == null || group == null || group.kind == 'leads') {+ return const [];+ }+ final project = snapshot.projectFor(group.id);+ bool reads(SuperTabPerson person) => switch (group) {+ SuperTabConversation(:final audience?) => audience.contains(person.id),+ _ when group.buddyOwnerId != null => person.id == group.buddyOwnerId,+ _ =>+ project == null ||+ !project.isPrivate ||+ project.ownerId == person.id ||+ project.hasMember(person),+ };+ return [+ for (final person in snapshot.people)+ if (person.id != reader.accountId && reads(person)) person,+ ];+ }+/// The Swarm was read, changed or not.void _swarmChanged() {if (_disposed) return;@@ -367,6 +395,9 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {}_listed = true;if (_lost) _lost = _refused = false;+ // An open @ list follows who is in the Swarm and the chat now: someone+ // who left, or lost the chat, leaves it.+ if (mentionQuery != null) _composer.changed();final tail = messages.lastOrNull?.sequence ?? 0;if (!_read || group.lastMessageSequence > tail) {unawaited(load());@@ -872,7 +903,14 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {Map<String, dynamic>? _compose([List<String> attachmentIds = const []]) {final text = _draft.trim();final group = conversation;+ final people = {...?reader.snapshot?.people.map((p) => p.id)};if ((text.isEmpty && attachmentIds.isEmpty) || group == null) return null;+ // A person still in the Swarm whose username the text still says is+ // tagged, as Desktop sends it; the backend refuses one who cannot read.+ final tagged = [+ for (final MapEntry(key: id, value: token) in _mentions.entries)+ if (containsMention(text, token) && people.contains(id)) id,+ ];return {'operationId': superTabOperationId(),'command': {@@ -886,6 +924,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {group.agentIds.contains(agentId))agentId,],+ if (tagged.isNotEmpty) 'mentions': tagged,if (attachmentIds.isNotEmpty) 'attachmentIds': attachmentIds,},};diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex 80cf7d098..131feab07 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -31,6 +31,7 @@ import 'swarm_file_picker.dart';import 'swarm_outgoing_files.dart';import 'swarm_inbox.dart';import 'swarm_live_card.dart';+import 'swarm_message_link.dart';import 'swarm_message_row.dart';import 'swarm_need_rows.dart';import 'swarm_profile_sheet.dart';@@ -747,9 +748,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>nameOf: (kind, id) => _reactorName(c, kind, id),onReact: view.canPost ? (emoji) => unawaited(t.react(m, emoji)) : null,),- onLongPress: view.canPost- ? () => unawaited(_pickThreadReaction(c, t, m.id))- : null,+ onLongPress: () => unawaited(_pickThreadReaction(c, t, m.id)),);}@@ -1192,14 +1191,21 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>context,reactions: c.reactionsOf(message),readerId: c.reader.accountId,+ react: c.canPost,+ link: _linkTo(c, id),);if (emoji == null || !mounted) return;if (shown() case final now?) await t.react(now, emoji);}/// 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 {+ /// as it is by then. The long-press sheet also copies the message's link;+ /// the Add reaction chip's ([link] false) offers reactions alone.+ Future<void> _pickReaction(+ SwarmConversation c,+ String id, {+ bool link = true,+ }) async {SuperTabMessage? shown() => c.messages.where((m) => m.id == id).firstOrNull;final message = shown();if (message == null) return;@@ -1207,11 +1213,20 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>context,reactions: c.reactionsOf(message),readerId: c.reader.accountId,+ react: c.canPost,+ link: link ? _linkTo(c, id) : null,);if (emoji == null || !mounted) return;if (shown() case final now?) await c.react(now, emoji);}+ /// Message [id]'s link, the one Desktop copies.+ SwarmMessageLink _linkTo(SwarmConversation c, String id) => SwarmMessageLink(+ tabId: c.reader.tabId,+ conversationId: c.id,+ messageId: id,+ );+/// 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]):@@ -1433,12 +1448,10 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>? (emoji) => unawaited(c.react(m, emoji)): null,onAdd: widget.homeC && view.canPost- ? () => unawaited(_pickReaction(c, m.id))+ ? () => unawaited(_pickReaction(c, m.id, link: false)): null,),- onLongPress: view.canPost- ? () => unawaited(_pickReaction(c, m.id))- : null,+ onLongPress: () => unawaited(_pickReaction(c, m.id)),below: answerIn == null? null: _AnswerIn(@@ -1617,11 +1630,12 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>children: [if (query != null && snapshot != null)_MentionPicker(+ people: c.mentionablePeople,agents: c.mentionable,snapshot: snapshot,query: query,- onPick: (agent) {- c.completeMention(agent.id);+ onPick: (id) {+ c.completeMention(id);_focus.requestFocus();},),@@ -2515,20 +2529,25 @@ class _Ask extends StatelessWidget {}}-/// 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.+/// Over the composer, who the @ being typed can name, as Desktop offers+/// them: the chat's people whose username holds what follows it, then its+/// agents whose name starts with it, each with its role and what it is doing.class _MentionPicker extends StatelessWidget {const _MentionPicker({+ required this.people,required this.agents,required this.snapshot,required this.query,required this.onPick,});+ final List<SuperTabPerson> people;final List<SuperTabAgent> agents;final SuperTabSnapshot snapshot;final String query;- final ValueChanged<SuperTabAgent> onPick;++ /// The person's or agent's id.+ final ValueChanged<String> onPick;@overrideWidget build(BuildContext context) {@@ -2538,6 +2557,10 @@ class _MentionPicker extends StatelessWidget {glance.agent.id: glance,};final prefix = query.toLowerCase();+ final shownPeople = [+ for (final person in people)+ if (person.username.contains(prefix)) person,+ ];final shown = [for (final agent in agents)if (snapshot.agentName(agent.id).toLowerCase().startsWith(prefix))@@ -2554,11 +2577,11 @@ class _MentionPicker extends StatelessWidget {borderRadius: BorderRadius.circular(AppMenu.panelRadius),boxShadow: AppSurface.shadow,),- child: shown.isEmpty+ child: shown.isEmpty && shownPeople.isEmpty? Padding(padding: const EdgeInsets.all(AppSpace.l),child: Text(- 'No agent by that name.',+ 'No one by that name.',style: swarmChatText(14, color: AppPalette.textSecondary),),)@@ -2566,12 +2589,43 @@ class _MentionPicker extends StatelessWidget {shrinkWrap: true,padding: EdgeInsets.zero,children: [+ for (final person in shownPeople)+ TtyTap(+ key: ValueKey('swarm-pick-person-${person.id}'),+ semanticsLabel: person.username,+ minHeight: 52,+ onTap: () => onPick(person.id),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.l,+ ),+ child: Row(+ children: [+ SwarmChatAvatar(+ name: person.username,+ id: person.id,+ agent: false,+ picture: person.avatar,+ ),+ const SizedBox(width: 10),+ Expanded(+ child: Text(+ person.username,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(16, weight: FontWeight.w500),+ ),+ ),+ ],+ ),+ ),+ ),for (final agent in shown)TtyTap(key: ValueKey('swarm-pick-${agent.id}'),semanticsLabel: snapshot.agentName(agent.id),minHeight: 52,- onTap: () => onPick(agent),+ onTap: () => onPick(agent.id),child: Padding(padding: const EdgeInsets.symmetric(horizontal: AppSpace.l,diff --git a/mobile/lib/swarm/swarm_message_link.dart b/mobile/lib/swarm/swarm_message_link.dartnew file mode 100644index 000000000..ca9f9007a--- /dev/null+++ b/mobile/lib/swarm/swarm_message_link.dart@@ -0,0 +1,90 @@+import 'dart:async';++import 'package:flutter/services.dart';++/// A link to one message of a Swarm: `harness://swarm/<tab>/<conversation>/<message>`,+/// the link Desktop copies (desktop/lib/super_tabs/message_link.dart). It+/// names ids only, so it grants nothing: whoever opens it sees the message+/// only if the Swarm already lets them read that conversation. The message id+/// alone places it, so the link still works for a message in a thread.+class SwarmMessageLink {+ const SwarmMessageLink({+ required this.tabId,+ required this.conversationId,+ required this.messageId,+ });++ final String tabId, conversationId, messageId;++ String get url => 'harness://swarm/$tabId/$conversationId/$messageId';++ static final _id = RegExp(r'^[A-Za-z0-9_-]{1,160}$');++ /// The link [value] is, read as Desktop reads it; null for anything else.+ static SwarmMessageLink? parse(String value) {+ // Desktop's native URL-open limit.+ if (value.length > 240) return null;+ final uri = Uri.tryParse(value);+ if (uri == null ||+ uri.scheme != 'harness' ||+ uri.host != 'swarm' ||+ uri.hasPort ||+ uri.userInfo.isNotEmpty ||+ uri.hasQuery ||+ uri.hasFragment ||+ uri.pathSegments.length != 3 ||+ !uri.pathSegments.every(_id.hasMatch)) {+ return null;+ }+ final [tab, conversation, message] = uri.pathSegments;+ return SwarmMessageLink(+ tabId: tab,+ conversationId: conversation,+ messageId: message,+ );+ }+}++/// `harness/links`: the message links this phone was asked to open (iOS:+/// `LinkChannel` in AppDelegate.swift; Android: MainActivity.kt). The native+/// side holds each until `take` answers it, so one that launched the app, or+/// came before sign-in, waits for whoever listens next; `arrived` says more+/// wait. [onLink] hears each message link, in order; anything else is+/// dropped.+class SwarmLinkChannel {+ SwarmLinkChannel(this.onLink);++ static const _channel = MethodChannel('harness/links');+ final void Function(SwarmMessageLink) onLink;+ bool _closed = false;++ /// Takes what waits now, and whatever arrives until [close].+ void listen() {+ _channel.setMethodCallHandler((call) async {+ if (call.method == 'arrived') await _take();+ return null;+ });+ unawaited(_take());+ }++ Future<void> _take() async {+ List<String>? taken;+ try {+ taken = await _channel.invokeListMethod<String>('take');+ } on MissingPluginException {+ return;+ } on PlatformException {+ return;+ }+ if (_closed) return;+ for (final value in taken ?? const <String>[]) {+ if (SwarmMessageLink.parse(value) case final link?) onLink(link);+ }+ }++ /// Leaves links waiting for the next listener.+ void close() {+ _closed = true;+ _channel.setMethodCallHandler(null);+ }+}diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dartindex 27ee17bc8..73f371cdf 100644--- a/mobile/lib/swarm/swarm_message_row.dart+++ b/mobile/lib/swarm/swarm_message_row.dart@@ -249,7 +249,7 @@ class SwarmMessageRow extends StatelessWidget {/// PM's private line answered in the project chat.final Widget? below;- /// Null where the person cannot post: picks a reaction.+ /// Opens its long-press sheet: reactions, Copy link to message.final VoidCallback? onLongPress;@overridediff --git a/mobile/lib/swarm/swarm_reactions.dart b/mobile/lib/swarm/swarm_reactions.dartindex 2b0913f62..25fa09289 100644--- a/mobile/lib/swarm/swarm_reactions.dart+++ b/mobile/lib/swarm/swarm_reactions.dart@@ -6,8 +6,11 @@ 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 'model.dart';+import 'swarm_message_link.dart';import 'swarm_message_row.dart'show swarmChatCard, swarmChatHair, swarmChatText;@@ -188,13 +191,17 @@ class _AddChip extends StatelessWidget {}}-/// Opens the reactions a message can carry in a sheet, with a light tap of-/// the phone as a long-press gives: Desktop's seven, the reader's own marked.-/// Answers the one picked, or null when the sheet closed without one.+/// Opens a message's long-press sheet, with a light tap of the phone: the+/// reactions it can carry (Desktop's seven, the reader's own marked) where+/// the reader may [react], then Copy link to message with its [link], which+/// copies it and says so. Answers the reaction picked, or null when the sheet+/// closed without one.Future<SuperTabReactionEmoji?> showSwarmReactionPicker(BuildContext context, {required List<SuperTabReactionCount> reactions,required String readerId,+ bool react = true,+ SwarmMessageLink? link,}) {HapticFeedback.lightImpact();final mine = {@@ -205,14 +212,27 @@ Future<SuperTabReactionEmoji?> showSwarmReactionPicker(context: context,backgroundColor: AppGlass.rowFill,shape: AppControl.sheetShape,- builder: (context) => _Picker(mine: mine),+ builder: (context) => _Picker(mine: mine, react: react, link: link),);}class _Picker extends StatelessWidget {- const _Picker({required this.mine});+ const _Picker({required this.mine, required this.react, this.link});final Set<SuperTabReactionEmoji> mine;+ final bool react;+ final SwarmMessageLink? link;++ /// Desktop's Copy link to message: the link on the clipboard, the sheet+ /// closed, and "Link copied".+ Future<void> _copy(BuildContext context, SwarmMessageLink link) async {+ final messenger = ScaffoldMessenger.maybeOf(context);+ Navigator.of(context).pop();+ await Clipboard.setData(ClipboardData(text: link.url));+ messenger?.showSnackBar(+ const SnackBar(content: Text('Link copied'), duration: Durations.long4),+ );+ }@overrideWidget build(BuildContext context) {@@ -240,53 +260,95 @@ class _Picker extends StatelessWidget {shape: const StadiumBorder(),),),- Row(- mainAxisAlignment: MainAxisAlignment.spaceEvenly,- children: [- // Seven at 50 points are wider than a 375-point phone's- // sheet: each shares the row, never under a finger's 44.- for (final emoji in SuperTabReactionEmoji.values)- Flexible(- child: 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,+ if (react)+ Row(+ mainAxisAlignment: MainAxisAlignment.spaceEvenly,+ children: [+ // Seven at 50 points are wider than a 375-point phone's+ // sheet: each shares the row, never under a finger's 44.+ for (final emoji in SuperTabReactionEmoji.values)+ Flexible(+ child: Semantics(+ button: true,+ selected: mine.contains(emoji),+ label:+ '${emoji.key.replaceAll('_', ' ')}'+ '${mine.contains(emoji) ? ', yours' : ''}',+ excludeSemantics: true,onTap: () => Navigator.of(context).pop(emoji),- child: Container(- constraints: const BoxConstraints(- maxWidth: 50,- minHeight: 50,- maxHeight: 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,+ child: GestureDetector(+ key: ValueKey('swarm-react-${emoji.key}'),+ behavior: HitTestBehavior.opaque,+ onTap: () => Navigator.of(context).pop(emoji),+ child: Container(+ constraints: const BoxConstraints(+ maxWidth: 50,+ minHeight: 50,+ maxHeight: 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,+ ),),),),),),+ ],+ ),+ if (link case final link?)+ SizedBox(+ width: double.infinity,+ child: Semantics(+ button: true,+ child: InkWell(+ key: const ValueKey('swarm-copy-link'),+ borderRadius: BorderRadius.circular(AppControl.radius),+ onTap: () => _copy(context, link),+ child: ConstrainedBox(+ constraints: const BoxConstraints(+ minHeight: minTouchTarget,+ ),+ child: Padding(+ padding: EdgeInsets.fromLTRB(+ AppSpace.m,+ react ? AppSpace.m : AppSpace.s,+ AppSpace.m,+ AppSpace.s,+ ),+ child: Row(+ children: [+ Icon(+ LucideIcons.link300,+ size: 20,+ color: AppPalette.textPrimary,+ ),+ const SizedBox(width: AppSpace.m),+ Text(+ 'Copy link to message',+ style: AppType.body(+ color: AppPalette.textPrimary,+ ),+ ),+ ],+ ),+ ),+ ),),- ],- ),+ ),+ ),],),),diff --git a/mobile/test/phone/phone_shell_swarm_link_test.dart b/mobile/test/phone/phone_shell_swarm_link_test.dartnew file mode 100644index 000000000..235bea580--- /dev/null+++ b/mobile/test/phone/phone_shell_swarm_link_test.dart@@ -0,0 +1,141 @@+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/agent_home.dart';+import 'package:harness_mobile/phone/phone_shell.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 message link (Desktop's Copy link to message) opened on the phone: the+/// native side holds each until the app takes it, and the shell opens the+/// chat at that message over the Swarm page.+void main() {+ const channel = MethodChannel('harness/links');+ late DevicesApp app;+ late List<String> waiting;+ late int takes;++ setUp(() {+ app = _LinkApp()+ ..currentUser = const CurrentUserProfile(+ id: 'person-me',+ email: '[email protected]',+ );+ experimentalFeaturesStore.value = {PhoneExperiment.swarm};+ waiting = [];+ takes = 0;+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, (call) async {+ if (call.method != 'take') return null;+ takes++;+ final taken = List.of(waiting);+ waiting.clear();+ return taken;+ });+ });+ tearDown(() {+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, null);+ experimentalFeaturesStore.value = const {};+ app.dispose();+ });++ /// The native side saying a link arrived while the app runs.+ Future<void> arrive(WidgetTester tester, String url) async {+ waiting.add(url);+ await tester.binding.defaultBinaryMessenger.handlePlatformMessage(+ channel.name,+ const StandardMethodCodec().encodeMethodCall(const MethodCall('arrived')),+ (_) {},+ );+ await tester.pump();+ // The route transitions finish, as for a tapped notice.+ await tester.pump(const Duration(seconds: 1));+ }++ Future<void> start(WidgetTester tester) async {+ await tester.pumpWidget(MaterialApp(home: PhoneShell(notifier: app)));+ await tester.pump();+ // The route transitions finish, as for a tapped notice.+ await tester.pump(const Duration(seconds: 1));+ }++ void expectOpened(WidgetTester tester, (String, String, String) at) {+ final page = tester.widget<SwarmConversationPage>(+ find.byType(SwarmConversationPage),+ );+ expect((page.swarmId, page.conversationId, page.messageId), at);+ expect(find.byType(SwarmPage, skipOffstage: false), findsOneWidget);+ }++ testWidgets('a link that arrives opens its chat at the message, over the '+ 'Swarm page', (tester) async {+ await start(tester);+ await arrive(tester, 'harness://swarm/tab-b/g9/m7');++ expectOpened(tester, ('tab-b', 'g9', 'm7'));+ });++ testWidgets('a link that launched the app, or came before sign-in, opens '+ 'once the shell is up', (tester) async {+ waiting.add('harness://swarm/tab-b/g9/m7');+ await start(tester);++ expectOpened(tester, ('tab-b', 'g9', 'm7'));+ expect(waiting, isEmpty, reason: 'taken once');+ });++ testWidgets('a second link replaces the first chat, not stacks on it', (+ tester,+ ) async {+ await start(tester);+ await arrive(tester, 'harness://swarm/tab-b/g9/m7');+ await arrive(tester, 'harness://swarm/tab-b/g2/m1');++ expectOpened(tester, ('tab-b', 'g2', 'm1'));+ expect(find.byType(SwarmConversationPage), findsOneWidget);+ });++ testWidgets('what is not a message link opens nothing', (tester) async {+ await start(tester);+ await arrive(tester, 'harness://swarm/tab-b/g9');+ await arrive(tester, 'harness://swarm/tab-b/g9/m7?x=1');++ expect(find.byType(SwarmConversationPage), findsNothing);+ });++ testWidgets('with Swarm off, a link says to turn it on and opens nothing', (+ tester,+ ) async {+ experimentalFeaturesStore.value = const {};+ await start(tester);+ await arrive(tester, 'harness://swarm/tab-b/g9/m7');++ expect(find.byType(SwarmConversationPage), findsNothing);+ expect(find.byType(AgentHome), findsOneWidget);+ expect(+ find.text('Turn on Swarm in Settings to open this link.'),+ findsOneWidget,+ );+ });++ testWidgets('after the shell is gone (signed out) a link is left for the '+ 'next one', (tester) async {+ await start(tester);+ await tester.pumpWidget(const SizedBox());+ final before = takes;+ await arrive(tester, 'harness://swarm/tab-b/g9/m7');++ expect(takes, before, reason: 'nobody took it');+ expect(waiting, ['harness://swarm/tab-b/g9/m7']);+ });+}++class _LinkApp extends DevicesApp {+ @override+ void handleAppResumed() {}+}diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dartindex bb4395fcf..5c71ad60d 100644--- a/mobile/test/swarm/swarm_chat_test.dart+++ b/mobile/test/swarm/swarm_chat_test.dart@@ -97,6 +97,8 @@ void main() {List<Map<String, dynamic>> decisions = const [],List<String>? audience,List<Map<String, dynamic>>? members,+ List<Map<String, dynamic>>? projects,+ Map<String, dynamic> g1 = const {},}) {// The Swarm's counts say a decision waits: what has its list read.final derived = {'decisionsWaiting': decisions.length};@@ -109,19 +111,23 @@ void main() {};fake.routes['/api/super-tabs/$tab/parts'] = (_) => {...firstLoad(+ head: projects == null ? null : headData(projects: projects),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),- ),+ {+ ...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),+ ),+ ...g1,+ },],derived: derived,),@@ -163,10 +169,12 @@ void main() {Future<void> show(WidgetTester tester,SwarmHost host, {+ String swarmId = tab,String conversation = 'g1',String? messageId,String? decisionId,bool settle = true,+ bool homeC = false,}) async {await tester.pumpWidget(// The app's own theme, as the shell sets it: its field defaults are@@ -175,10 +183,11 @@ void main() {theme: grid.buildAppTheme(brightness: Brightness.dark),builder: (context, child) => SwarmScope(notifier: host, child: child!),home: SwarmConversationPage(- swarmId: tab,+ swarmId: swarmId,conversationId: conversation,messageId: messageId,decisionId: decisionId,+ homeC: homeC,),),);@@ -192,10 +201,12 @@ void main() {Future<SwarmHost> pump(WidgetTester tester,FakeSwarm fake, {+ String swarmId = tab,String conversation = 'g1',String? messageId,String? decisionId,bool settle = true,+ bool homeC = false,SwarmUpload upload = refuseSwarmUpload,}) async {features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())@@ -214,10 +225,12 @@ void main() {await show(tester,host,+ swarmId: swarmId,conversation: conversation,settle: settle,messageId: messageId,decisionId: decisionId,+ homeC: homeC,);return host;}@@ -643,7 +656,7 @@ void main() {await tester.enterText(find.byType(TextField), 'ask @zed');await tester.pump();- expect(find.text('No agent by that name.'), findsOneWidget);+ expect(find.text('No one by that name.'), findsOneWidget);await tester.enterText(find.byType(TextField), 'ask @N');await tester.pump();@@ -656,6 +669,304 @@ void main() {expect(key('swarm-mention-picker'), findsNothing);});+ group('@ people, by username, as Desktop tags them', () {+ // Ken chose a username; Dee keeps the default her email makes.+ final ken = {...person('ken', role: 'collaborator'), 'username': 'kenji'};+ final dee = person('dee', role: 'collaborator');+ final everyone = [person(me), ken, dee];+ String field(WidgetTester tester) =>+ tester.widget<TextField>(find.byType(TextField)).controller!.text;+ Future<void> type(WidgetTester tester, String text) async {+ await tester.enterText(find.byType(TextField), text);+ await tester.pump();+ }++ testWidgets('@ lists the people who read the chat by username, before '+ 'its agents, never the reader; what follows narrows it', (+ tester,+ ) async {+ await pump(tester, backend([message('m1', 1)], members: everyone));++ await type(tester, '@');+ expect(key('swarm-pick-person-ken'), findsOneWidget);+ expect(+ find.descendant(+ of: key('swarm-pick-person-ken'),+ matching: find.text('kenji'),+ ),+ findsOneWidget,+ );+ expect(key('swarm-pick-person-dee'), findsOneWidget);+ expect(key('swarm-pick-person-$me'), findsNothing);+ expect(+ tester.getTopLeft(key('swarm-pick-person-dee')).dy,+ lessThan(tester.getTopLeft(key('swarm-pick-agent-lead')).dy),+ );++ // Any part of the username, as on Desktop.+ await type(tester, 'ask @enj');+ expect(key('swarm-pick-person-ken'), findsOneWidget);+ expect(key('swarm-pick-person-dee'), findsNothing);+ expect(key('swarm-pick-agent-builder'), findsNothing);++ await type(tester, 'ask @zed');+ expect(find.text('No one by that name.'), findsOneWidget);+ });++ testWidgets('a picked person goes in as @username, and the post tags '+ 'them beside the agents it goes to, as Desktop sends it', (+ tester,+ ) async {+ final fake = backend([message('m1', 1)], members: everyone);+ await pump(tester, fake);++ await type(tester, 'ask @ke');+ await tester.tap(key('swarm-pick-person-ken'));+ await tester.pump();+ expect(field(tester), 'ask @kenji ');+ expect(key('swarm-mention-picker'), findsNothing);++ await type(tester, 'ask @kenji and @N');+ await tester.tap(key('swarm-pick-agent-builder'));+ await tester.pump();+ expect(field(tester), 'ask @kenji and @Nova ');++ await type(tester, 'ask @kenji and @Nova to look');+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(fake.commands.single, {+ 'type': 'message.send',+ 'conversationId': 'g1',+ 'text': 'ask @kenji and @Nova to look',+ 'replyTo': null,+ 'recipientIds': ['agent-builder'],+ 'mentions': ['ken'],+ });+ });++ testWidgets('a username taken out of the draft tags nobody', (+ tester,+ ) async {+ final fake = backend([message('m1', 1)], members: everyone);+ await pump(tester, fake);++ await type(tester, '@ke');+ await tester.tap(key('swarm-pick-person-ken'));+ await tester.pump();+ await type(tester, 'ask him later');+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(fake.commands.single.containsKey('mentions'), isFalse);+ expect(fake.commands.single['recipientIds'], <String>[]);+ });++ testWidgets('a refused tag puts the post back in the draft with the '+ 'backend\'s words, and the tag stays with it', (tester) async {+ final fake = backend([message('m1', 1)], members: everyone);+ var refuse = true;+ fake.routes[commands] = (_) => refuse+ ? throw const SuperTabFailure(+ 'INVALID_MENTION',+ 'kenji cannot read this conversation.',+ statusCode: 400,+ )+ : {'result': <String, dynamic>{}};+ await pump(tester, fake);++ await type(tester, '@ke');+ await tester.tap(key('swarm-pick-person-ken'));+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();++ expect(field(tester), '@kenji ');+ expect(find.text('kenji cannot read this conversation.'), findsOneWidget);++ refuse = false;+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();+ expect(fake.commands.last['mentions'], ['ken']);+ });++ testWidgets('a private chat offers only its own people', (tester) async {+ await pump(+ tester,+ backend([message('m1', 1)], members: everyone, audience: [me, 'dee']),+ );++ await type(tester, '@');+ expect(key('swarm-pick-person-dee'), findsOneWidget);+ expect(key('swarm-pick-person-ken'), findsNothing);+ expect(find.text('kenji'), findsNothing);+ });++ testWidgets('a private project offers its owner and members alone', (+ tester,+ ) async {+ await pump(+ tester,+ backend(+ [message('m1', 1)],+ members: everyone,+ projects: [+ {+ 'id': project,+ 'name': 'Mobile',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'private',+ 'members': [+ {'id': 'dee', 'generation': 'gen-dee'},+ ],+ 'updateMinutes': 5,+ },+ ],+ ),+ );++ await type(tester, '@');+ expect(key('swarm-pick-person-dee'), findsOneWidget);+ expect(key('swarm-pick-person-ken'), findsNothing);+ });++ testWidgets('a private project offers its members at the membership '+ 'they were added in: someone who left and rejoined is not offered', (+ tester,+ ) async {+ final fake = backend(+ [message('m1', 1)],+ members: everyone,+ projects: [+ {+ 'id': project,+ 'name': 'Mobile',+ 'ownerId': me,+ 'leadConversationId': leadChat,+ 'visibility': 'private',+ 'members': [+ {'id': 'dee', 'generation': 'gen-dee'},+ ],+ },+ ],+ );+ final host = await pump(tester, fake);+ await type(tester, '@');+ expect(key('swarm-pick-person-dee'), findsOneWidget);++ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c3', lastChangedAt: 200),+ 'members': [+ part('dee', 2, {+ ...dee,+ 'generation': 'rejoined-dee',+ 'username': 'new-dee',+ }),+ ],+ };+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pump();++ expect(+ key('swarm-pick-person-dee'),+ findsNothing,+ reason: 'the project holds their old membership, not this one',+ );+ expect(find.text('new-dee'), findsNothing);+ });++ testWidgets('a Buddy chat and the Leads conversation offer no people', (+ tester,+ ) async {+ for (final kind in [+ {'kind': 'buddy', 'buddyOwnerId': me},+ {'kind': 'leads'},+ ]) {+ await pump(+ tester,+ backend([message('m1', 1)], members: everyone, g1: kind),+ );+ await type(tester, '@');+ expect(key('swarm-pick-person-ken'), findsNothing, reason: '$kind');+ expect(key('swarm-pick-person-dee'), findsNothing, reason: '$kind');+ expect(find.text('kenji'), findsNothing, reason: '$kind');+ }+ });++ testWidgets('an agent of the same name in another project is never '+ 'offered', (tester) async {+ final fake = backend([message('m1', 1)], members: everyone);+ final full = fake.routes['/api/super-tabs/$tab/parts']!(null)! as Map;+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...full,+ 'agents': [+ ...full['agents'] as List,+ part('agent-other', 1, {+ ...agent('agent-other', displayName: 'Nova'),+ 'projectId': 'project-2',+ }),+ ],+ };+ await pump(tester, fake);++ await type(tester, '@N');+ expect(key('swarm-pick-agent-builder'), findsOneWidget);+ expect(key('swarm-pick-agent-other'), findsNothing);+ });++ testWidgets('losing the Swarm with the @ list open leaves no name on '+ 'screen', (tester) async {+ final fake = backend([message('m1', 1)], members: everyone);+ final host = await pump(tester, fake);+ await type(tester, '@');+ expect(find.text('kenji'), findsOneWidget);++ const refused = SuperTabFailure(+ 'FORBIDDEN',+ 'Not yours.',+ statusCode: 403,+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => throw refused;+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => throw refused;+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(key('swarm-mention-picker'), findsNothing);+ for (final name in ['kenji', 'dee', 'River', 'Nova']) {+ expect(find.textContaining(name), findsNothing, reason: name);+ }+ });++ testWidgets('someone who leaves the Swarm leaves the list, and a tag of '+ 'them in the draft is not sent', (tester) async {+ final fake = backend([message('m1', 1)], members: everyone);+ final host = await pump(tester, fake);++ await type(tester, '@ke');+ await tester.tap(key('swarm-pick-person-ken'));+ await tester.pump();+ await type(tester, '@kenji and @');+ expect(key('swarm-pick-person-ken'), findsOneWidget);++ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {+ ...changes(cursor: 'c3', lastChangedAt: 200),+ 'members': [+ {'key': 'ken', 'version': 2, 'changedAt': 2, 'deleted': true},+ ],+ };+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pump();+ expect(key('swarm-pick-person-ken'), findsNothing);+ expect(key('swarm-pick-person-dee'), findsOneWidget);++ await type(tester, '@kenji hello');+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();+ expect(fake.commands.single.containsKey('mentions'), isFalse);+ });+ });+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)]);@@ -1414,6 +1725,138 @@ void main() {});});+ group('Copy link to message', () {+ late List<String> copied;++ setUp(() {+ copied = [];+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {+ if (call.method == 'Clipboard.setData') {+ copied.add((call.arguments as Map)['text'] as String);+ }+ return null;+ });+ });+ tearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(SystemChannels.platform, null),+ );++ testWidgets('the long-press sheet copies the link Desktop copies, and '+ 'says so', (tester) async {+ final fake = backend([message('m1', 1, text: 'Plan')]);+ await pump(tester, fake);++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();+ expect(key('swarm-react-tada'), findsOneWidget);+ await tester.tap(key('swarm-copy-link'));+ await tester.pumpAndSettle();++ expect(copied, ['harness://swarm/$tab/g1/m1']);+ expect(key('swarm-copy-link'), findsNothing, reason: 'sheet closed');+ expect(find.text('Link copied'), findsOneWidget);+ expect(fake.commands, isEmpty);+ });++ testWidgets('the Add reaction chip opens the reactions alone: Copy link '+ 'is the long-press sheet\'s', (tester) async {+ final fake = backend([+ message(+ 'm1',+ 1,+ text: 'Plan',+ reactions: {+ 'eyes': [('agent', 'agent-lead')],+ },+ ),+ ]);+ await pump(tester, fake, homeC: true);++ await tester.tap(key('swarm-add-reaction-m1'));+ await tester.pumpAndSettle();+ expect(key('swarm-react-tada'), findsOneWidget);+ expect(key('swarm-copy-link'), findsNothing);+ await tester.tap(key('swarm-react-tada'));+ await tester.pumpAndSettle();++ expect(copied, isEmpty);+ expect(fake.commands.where((c) => c['type'] == 'message.react'), [+ {+ 'type': 'message.react',+ 'conversationId': 'g1',+ 'messageId': 'm1',+ 'emoji': 'tada',+ 'on': true,+ },+ ]);+ });++ testWidgets('a person who cannot post still copies the link; the sheet '+ 'offers no reactions', (tester) async {+ final fake = backend(+ [message('m1', 1, text: 'Plan')],+ members: [person(me, role: 'viewer')],+ );+ await pump(tester, fake);++ await tester.longPress(find.text('Plan'));+ await tester.pumpAndSettle();+ expect(key('swarm-react-tada'), findsNothing);+ await tester.tap(key('swarm-copy-link'));+ await tester.pumpAndSettle();++ expect(copied, ['harness://swarm/$tab/g1/m1']);+ expect(fake.commands, isEmpty);+ });++ testWidgets('a reply in a thread copies its own link: its id alone '+ 'places it', (tester) async {+ final fake = backend(+ [+ message('m1', 1, author: 'agent-lead', text: 'Root', thread: 'm1'),+ message('m2', 2, text: 'In thread', thread: 'm1', replyTo: 'm1'),+ ],+ threads: [+ {+ 'id': 'm1',+ 'replies': 1,+ 'lastSequence': 2,+ 'lastAt': DateTime.utc(2026, 10, 27, 1, 2).toIso8601String(),+ 'authors': [+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'Nova'},+ ],+ 'people': <String>[],+ },+ ],+ );+ fake.routes['$messages?thread=m1'] = (_) => {+ 'messages': [+ message('m2', 2, text: 'In thread', thread: 'm1', replyTo: 'm1'),+ message('m1', 1, author: 'agent-lead', text: 'Root', thread: 'm1'),+ ],+ 'next': null,+ 'threads': <Object>[],+ };+ await pump(tester, fake);+ await tester.tap(key('swarm-thread-line-m1'));+ await tester.pumpAndSettle();++ await tester.longPress(+ find.descendant(+ of: key('swarm-thread-messages'),+ matching: find.text('In thread'),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-copy-link'));+ await tester.pumpAndSettle();++ expect(copied, ['harness://swarm/$tab/g1/m2']);+ });+ });+group('threads', () {const parts = '/api/super-tabs/$tab/parts';const root = 'Can you check the drawer mockup?';@@ -2441,6 +2884,136 @@ void main() {});});+ // A message link opens the chat at its message (phone_shell.dart). One the+ // person cannot open says "not open" alike, whatever the reason, and shows+ // nothing of the chat: no title, project, message or name.+ group('opened from a message link', () {+ const notOpen = 'This chat is not open to you.';+ const secret = 'The secret plan';++ void nothingLeaks(WidgetTester tester) {+ expect(find.text(notOpen), findsOneWidget);+ expect(key('swarm-chat-skeleton'), findsNothing);+ for (final text in [secret, 'Fix login', 'Mobile', '#Mobile', 'Nova']) {+ expect(find.textContaining(text), findsNothing, reason: text);+ }+ }++ for (final (why, failure) in [+ (+ 'an unknown id',+ const SuperTabFailure('NOT_FOUND', 'No such chat.', statusCode: 404),+ ),+ (+ 'a private chat of others',+ const SuperTabFailure('FORBIDDEN', 'Not yours.', statusCode: 403),+ ),+ (+ 'someone else\'s Buddy chat',+ const SuperTabFailure('FORBIDDEN', 'Not yours.', statusCode: 403),+ ),+ ]) {+ testWidgets('$why is not open, and shows nothing of it', (tester) async {+ final fake = backend([message('m1', 1, text: secret)]);+ fake.routes['/api/super-tabs/$tab/groups/g9'] = (_) => throw failure;+ fake.routes['/api/super-tabs/$tab/conversations/g9/messages'] = (_) =>+ throw failure;++ await pump(tester, fake, conversation: 'g9', messageId: 'm1');++ nothingLeaks(tester);+ });+ }++ testWidgets('a chat of a Swarm the person is not in is not open', (+ tester,+ ) async {+ final fake = backend([message('m1', 1, text: secret)]);+ const other = 'tab-other';+ fake.routes['/api/super-tabs/$other/parts'] = (_) =>+ throw const SuperTabFailure(+ 'FORBIDDEN',+ 'Not yours.',+ statusCode: 403,+ );+ fake.routes['/api/super-tabs/$other/conversations/g1/messages'] = (_) =>+ throw const SuperTabFailure(+ 'FORBIDDEN',+ 'Not yours.',+ statusCode: 403,+ );++ await pump(+ tester,+ fake,+ swarmId: other,+ conversation: 'g1',+ messageId: 'm1',+ );++ nothingLeaks(tester);+ });++ testWidgets('a person removed from the Swarm while it is open loses it '+ 'at once: nothing of it stays', (tester) async {+ final fake = backend([message('m1', 1, text: secret)]);+ final host = await pump(tester, fake, messageId: 'm1');+ expect(find.text(secret), findsOneWidget);++ const refused = SuperTabFailure(+ 'FORBIDDEN',+ 'Not yours.',+ statusCode: 403,+ );+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => throw refused;+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => throw refused;+ fake.routes[messages] = (_) => throw refused;+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ nothingLeaks(tester);+ });++ testWidgets('a lookup that fails is asked again at the next read, and '+ 'opens the chat at the message then', (tester) async {+ final fake = backend([message('m1', 1, text: secret)]);+ var lookups = 0;+ final g9 = {+ 'group': part(+ 'g9',+ 9,+ groupData('g9', title: 'Found later', lastMessageSequence: 5),+ ),+ };+ fake.routes['/api/super-tabs/$tab/groups/g9'] = (_) {+ lookups++;+ if (lookups == 1) throw StateError('socket closed');+ return g9;+ };+ fake.routes['/api/super-tabs/$tab/conversations/g9/messages'] = (_) => {+ 'messages': [+ {...message('m5', 5, text: 'Found it'), 'conversationId': 'g9'},+ ],+ 'next': null,+ };+ final host = await pump(+ tester,+ fake,+ conversation: 'g9',+ messageId: 'm5',+ settle: false,+ );+ expect(lookups, 1);+ expect(find.text(notOpen), findsNothing);++ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(lookups, 2);+ expect(find.text('Found it'), findsOneWidget);+ });+ });+group('opened again', () {const parts = '/api/super-tabs/$tab/parts';diff --git a/mobile/test/swarm/swarm_message_link_test.dart b/mobile/test/swarm/swarm_message_link_test.dartnew file mode 100644index 000000000..93fd084c3--- /dev/null+++ b/mobile/test/swarm/swarm_message_link_test.dart@@ -0,0 +1,36 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_message_link.dart';++/// A message link reads as Desktop reads it+/// (desktop/lib/super_tabs/message_link.dart): three plain ids under+/// harness://swarm, nothing else.+void main() {+ test('three ids under harness://swarm name the Swarm, chat and message', () {+ final link = SwarmMessageLink.parse('harness://swarm/tab-1/g_1/m-1')!;+ expect(+ (link.tabId, link.conversationId, link.messageId),+ ('tab-1', 'g_1', 'm-1'),+ );+ expect(link.url, 'harness://swarm/tab-1/g_1/m-1');+ });++ test('anything else is not a message link', () {+ for (final value in [+ 'https://swarm/tab-1/g1/m1',+ 'harness://other/tab-1/g1/m1',+ 'harness://swarm/tab-1/g1',+ 'harness://swarm/tab-1/g1/m1/more',+ 'harness://swarm/tab-1//m1',+ 'harness://swarm/tab-1/g1/m1?x=1',+ 'harness://swarm/tab-1/g1/m1#top',+ 'harness://swarm:8080/tab-1/g1/m1',+ 'harness://me@swarm/tab-1/g1/m1',+ 'harness://swarm/tab-1/g.1/m1',+ 'harness://swarm/tab-1/g%2F1/m1',+ 'harness://swarm/tab-1/g1/${'m' * 240}',+ '',+ ]) {+ expect(SwarmMessageLink.parse(value), isNull, reason: value);+ }+ });+}diff --git a/mobile/test/swarm/swarm_usernames_test.dart b/mobile/test/swarm/swarm_usernames_test.dartnew file mode 100644index 000000000..cb0a65d40--- /dev/null+++ b/mobile/test/swarm/swarm_usernames_test.dart@@ -0,0 +1,36 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';++/// How the phone names people for @, as Desktop does: the username the+/// server sends, else (an older server) the email prefix, numbered after the+/// people before.+void main() {+ SuperTabPerson member(String id, String email, {String? username}) =>+ SuperTabPerson.fromJson({+ 'id': id,+ 'email': email,+ 'role': 'collaborator',+ 'username': ?username,+ });++ test('the server\'s username wins over the email prefix', () {+ final [ken] = superTabUsernames([+ member('p1', '[email protected]', username: 'kenji'),+ ]);+ expect(ken.username, 'kenji');+ });++ test('without one, the email prefix, numbered past names already taken', () {+ final people = superTabUsernames([+ member('p1', '[email protected]'),+ member('p2', '[email protected]'),+ member('p3', '[email protected]', username: 'ken.n3'),+ member('p4', '[email protected]'),+ member('p5', '[email protected]'),+ ]);+ expect(+ [for (final p in people) p.username],+ ['ken.n', 'ken.n2', 'ken.n3', 'ken.n4', 'user'],+ );+ });+}