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
Desktop + web: Swarm notifications for a Lead's tags (#1679)
0xken153a1b8ac65a49
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex ef0bd8c34..8fa0fbe48 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -2241,7 +2241,8 @@ class _SwarmScreenState extends State<SwarmScreen> {p.agentId != null &&app.questionFor(p.machineId, p.agentId!) != null,)- .length,+ .length ++ tabMentionsWaiting(app, swarm),if (tabActivity(app, swarm) case final activity?)'activity': nativeActivityPayload(activity,@@ -9045,6 +9046,7 @@ class _SwarmScreenState extends State<SwarmScreen> {final swarm = shown[index];final selected = app.activeSwarmId == swarm.id;final activity = activities[index];+ final tags = tabMentionsWaiting(app, swarm);// A status cell animates only while its tab is in view.Widget tabStatus(Widget Function(bool visible) mark) =>ListenableBuilder(@@ -9130,7 +9132,9 @@ class _SwarmScreenState extends State<SwarmScreen> {label: labels[index],selected: selected,tooltip: tabHint.isEmpty ? null : tabHint,- activityLabel: activity?.label,+ activityLabel: tags > 0+ ? tabMentionsLabel(tags)+ : activity?.label,sharedCount: share.count,onInvitePeople: menus && share.invite? () => unawaited(_invitePeople(swarm.id))@@ -9158,8 +9162,15 @@ class _SwarmScreenState extends State<SwarmScreen> {app.requestCloseSwarm(swarm.id),): null,- activity:- activity == null || activity.mark.isEmpty+ activity: tags > 0+ ? Text(+ '$tags',+ key: ValueKey('tab-tags:${swarm.id}'),+ style: DesktopChrome.metadata(+ color: grid.AppPalette.warn,+ ).copyWith(fontWeight: FontWeight.w600),+ )+ : activity == null || activity.mark.isEmpty? null: tabStatus((visible) => ActivityMark(diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 0ede9a98d..45fdf29f1 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -97,6 +97,7 @@ import '../core/harness_file_store.dart';import '../super_tabs/attachment_upload.dart';import '../super_tabs/client.dart';import '../super_tabs/controller.dart';+import '../super_tabs/notifications.dart' show superTabMentionNotice;import '../measurement/setup_preference_store.dart';import '../devices/device_hosts.dart';import '../stats/harness_stats.dart';@@ -1715,6 +1716,8 @@ class AppNotifier extends ChangeNotifier {late final superTabs = SuperTabClient(storage: localStore ?? HarnessFileStore.shared,upload: uploadWith(() => api),+ onMention: superTabMentionNotice(systemNotifications),+ onTagCounts: notifyListeners,discoveryInterval: kUnderTest ? Duration.zero : const Duration(seconds: 15),onTabs: (tabs, hidden) {// Discovery can finish while an already signed-in machine is re-seatingdiff --git a/desktop/lib/state/harness_activity.dart b/desktop/lib/state/harness_activity.dartindex 333b40f1c..db281da20 100644--- a/desktop/lib/state/harness_activity.dart+++ b/desktop/lib/state/harness_activity.dart@@ -94,9 +94,19 @@ HarnessActivity? harnessActivity(return HarnessActivity.idle;}+/// The tags waiting for this account in a Swarm tab, for the tab's badge.+int tabMentionsWaiting(AppNotifier app, Swarm tab) =>+ tab.superTabId == null ? 0 : app.superTabs.waitingTags(tab.superTabId!);++/// What a Swarm tab's tag count says: "Tagged in 2 messages".+String tabMentionsLabel(int count) =>+ 'Tagged in $count ${count == 1 ? 'message' : 'messages'}';+/// A viewer refers to its owner; showing the same harness twice adds no vote.+/// A Lead's tag waiting in a Swarm tab needs the person, like a question.HarnessActivity? tabActivity(AppNotifier app, Swarm tab) {if (tab.isStore || tab.isOrchestrator) return null;+ if (tabMentionsWaiting(app, tab) > 0) return HarnessActivity.needsInput;HarnessActivity? result;final seen = <(String, String)>{};for (final pane in tab.panes) {diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex 24218fc63..fed7ef064 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -5,6 +5,7 @@ import '../core/local_key_value_store.dart';import 'attachment_upload.dart';import 'controller.dart';import 'model.dart';+import 'notifications.dart';typedef SuperTabTransport = Future<Object?> Function(String method,@@ -23,6 +24,8 @@ class SuperTabClient {this.onSnapshot,this.onTabs,this.onSelection,+ this.onMention,+ this.onTagCounts,this.upload = refuseUpload,this.discoveryInterval = const Duration(seconds: 15),});@@ -33,6 +36,19 @@ class SuperTabClient {/// A tab's selected conversation changed, by a click here or by a device.final void Function(SuperTabController)? onSelection;++ /// A Lead tagged this account in one of its Swarms while the app was open.+ final void Function(SuperTabMention)? onMention;++ /// The waiting tags of a Swarm that is not open changed ([waitingTags]).+ final void Function()? onTagCounts;+ final _tagCounts = <String, int>{};+ final _tagsSeen = <String, Set<String>>{};++ /// The tags waiting for this account in a Swarm: its own state once open,+ /// else what discovery last read, so a tab not opened yet still shows them.+ int waitingTags(String id) =>+ _loaded[id]?.snapshot?.mentionsWaiting ?? _tagCounts[id] ?? 0;final SuperTabUpload upload;final Duration discoveryInterval;String? _account;@@ -80,6 +96,8 @@ class SuperTabClient {_hidden = {};_creating.clear();_visibility.clear();+ _tagCounts.clear();+ _tagsSeen.clear();discoveryError = null;for (final controller in _loaded.values) {controller.revokeAccess('The account changed. Open this Swarm again.');@@ -187,10 +205,12 @@ class SuperTabClient {}} while (after != null);discoveryError = null;- onTabs!(- tabs.values.toList(),- Set.unmodifiable({..._hidden, ..._creating}),- );+ final hidden = Set<String>.unmodifiable({..._hidden, ..._creating});+ onTabs!(tabs.values.toList(), hidden);+ await _readTags([+ for (final id in tabs.keys)+ if (!hidden.contains(id) && !_loaded.containsKey(id)) id,+ ], generation);} catch (error) {if (generation == _generation) {discoveryError = error;@@ -277,10 +297,47 @@ class SuperTabClient {onSnapshot?.call(controller);}});+ // What discovery already announced is not news when the Swarm opens.+ SuperTabMentions.of(controller)+ ..seen(_tagsSeen.remove(id))+ ..onArrived = onMention;+ _tagCounts.remove(id);_loaded[id] = controller;controller.start();return controller;}+ /// One light read per Swarm tab that is not open: its waiting tags. A+ /// failed read, a backend before tags included, changes nothing and is+ /// tried again on the next round.+ Future<void> _readTags(List<String> ids, int generation) async {+ var changed = false;+ for (final id in ids) {+ try {+ final answer = await map(+ 'GET',+ '/api/super-tabs/${Uri.encodeComponent(id)}/mentions?state=waiting',+ );+ if (generation != _generation || _loaded.containsKey(id)) continue;+ final waiting = [+ for (final row in answer['mentions'] as List)+ SuperTabMention.fromJson(superTabMap(row)),+ ];+ final seen = _tagsSeen[id];+ if (seen != null) {+ for (final mention in waiting.reversed) {+ if (!seen.contains(mention.id)) onMention?.call(mention);+ }+ }+ _tagsSeen[id] = {...?seen, for (final m in waiting) m.id};+ if (_tagCounts[id] != waiting.length) {+ _tagCounts[id] = waiting.length;+ changed = true;+ }+ } catch (_) {}+ }+ if (changed && generation == _generation) onTagCounts?.call();+ }+void dispose() => bind(null);}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 3ea16df33..b024dfe43 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -151,7 +151,7 @@ class SuperTabController extends ChangeNotifier {int _uploadRun = 0;final _messages = <String, List<SuperTabMessage>>{};final _before = <String, int?>{};- final _reading = <String>{};+ final _reading = <String, Future<void>>{};final expandedProjects = <String>{};final expandedMachines = <String>{};bool devicesSelected = false;@@ -548,15 +548,18 @@ class SuperTabController extends ChangeNotifier {}}- Future<void> loadMessages(String id, {bool older = false}) async {- if (_disposed ||- accessRevoked ||- _reading.contains(id) ||- snapshot?.conversation(id) == null) {+ /// Joins a read of [id] already under way, so a caller can wait for it.+ Future<void> loadMessages(String id, {bool older = false}) =>+ _reading[id] ??= _loadMessages(id, older: older).whenComplete(() {+ // A block: whenComplete would wait on the removed future, itself.+ _reading.remove(id);+ });++ Future<void> _loadMessages(String id, {required bool older}) async {+ if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {return;}if (older && !hasOlder(id)) return;- _reading.add(id);try {final known = _messages[id];final tail = known != null && known.isNotEmpty@@ -650,8 +653,6 @@ class SuperTabController extends ChangeNotifier {unawaited(refresh());}_changed();- } finally {- _reading.remove(id);}}diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 7acdacd15..d67654749 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -29,9 +29,13 @@ class SuperTabMessageRow extends StatefulWidget {this.onOpenAgent,this.references = const {},this.onOpenGroup,+ this.mentions = const [],});final SuperTabMessage message;++ /// The names of the people [message] tags.+ final List<String> mentions;final Map<int, String> references;final ValueChanged<String>? onOpenGroup;final String author;@@ -292,6 +296,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {message.text,references: widget.references,onOpenGroup: widget.onOpenGroup,+ mentions: widget.mentions,),),if (message.attachments.isNotEmpty)diff --git a/desktop/lib/super_tabs/message_text.dart b/desktop/lib/super_tabs/message_text.dartindex 2794655c7..e48454464 100644--- a/desktop/lib/super_tabs/message_text.dart+++ b/desktop/lib/super_tabs/message_text.dart@@ -15,11 +15,16 @@ class SuperTabMessageText extends StatelessWidget {super.key,this.references = const {},this.onOpenGroup,+ this.mentions = const [],});final String text;final Map<int, String> references;final ValueChanged<String>? onOpenGroup;+ /// The names a Lead tagged in this message. Each reads highlighted where+ /// the text says it; one the text does not say is shown before it.+ final List<String> mentions;+static Uri? webLink(String? href) {final uri = href == null ? null : Uri.tryParse(href);return uri != null &&@@ -32,12 +37,21 @@ class SuperTabMessageText extends StatelessWidget {@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);+ final unsaid = [+ for (final name in mentions)+ if (!_Mention.tag.allMatches(text).any((m) => _Mention.names(m, name)))+ '@$name',+ ];return MarkdownBody(- data: text,+ data: unsaid.isEmpty ? text : '${unsaid.join(' ')}\n\n$text',selectable: false,softLineBreak: true,- inlineSyntaxes: [_WebAutolink(), _WorkgroupReference(references)],- builders: {'pre': _WrappedCode()},+ inlineSyntaxes: [+ _WebAutolink(),+ _WorkgroupReference(references),+ if (mentions.isNotEmpty) _Mention(mentions),+ ],+ builders: {'pre': _WrappedCode(), 'mention': _MentionName()},paddingBuilders: {'a': _CompactLinkLabel()},styleSheet: desktopMarkdownStyleSheet(context),onTapLink: (_, href, _) {@@ -136,6 +150,47 @@ class _WorkgroupReference extends md.InlineSyntax {}}+/// `@name` or `@name@domain` for a tagged person; any other `@` stays text.+/// Parsed as inline Markdown, so code and fenced blocks remain literal.+class _Mention extends md.InlineSyntax {+ _Mention(this.mentions) : super(tag.pattern);+ // A name never ends in a dot: `@dee.` closes a sentence.+ static final tag = RegExp(+ r'(?<![\w@])@([\w+-]+(?:\.[\w+-]+)*)(@[\w-]+(?:\.[\w-]+)+)?',+ );+ static bool names(Match match, String name) =>+ match[1]!.toLowerCase() == name.toLowerCase();+ final List<String> mentions;+ @override+ bool onMatch(md.InlineParser parser, Match match) {+ parser.addNode(+ mentions.any((name) => names(match, name))+ ? md.Element.text('mention', match[0]!)+ : md.Text(match[0]!),+ );+ return true;+ }+}++class _MentionName 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: grid.AppPalette.accentOnSurface,+ backgroundColor: grid.AppSurface.accentWash,+ fontWeight: FontWeight.w600,+ ),+ ),+ );+}+class _WrappedCode extends MarkdownElementBuilder {@overrideWidget? visitText(md.Text text, TextStyle? preferredStyle) => Padding(diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 45e462107..70a067e73 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -189,7 +189,8 @@ class SuperTabSnapshot {(row) => Map<String, dynamic>.unmodifiable(row),),leadsConversationId = row['leadsConversationId'] as String?,- localModels = SuperTabLocalModels.read(row['localModels']) {+ localModels = SuperTabLocalModels.read(row['localModels']),+ mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0 {if (row['version'] != 1) {throw const FormatException('Update Harness to open this Swarm.');}@@ -226,6 +227,10 @@ class SuperTabSnapshot {/// The Local models add-on, once the owner has turned it on; null before.final SuperTabLocalModels? localModels;++ /// The reader's tags still waiting for them, Swarm-wide; 0 from a backend+ /// before tags (spec 2026-10-24-lead-mentions.md).+ final int mentionsWaiting;SuperTabConversation? conversation(String id) =>conversations.where((c) => c.id == id).firstOrNull;SuperTabAgent? agent(String id) =>@@ -531,6 +536,9 @@ class SuperTabMessage {source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),attachments = _attachments(row['attachments']),+ mentions = List.unmodifiable(+ (row['mentions'] as List?)?.whereType<String>() ?? const <String>[],+ ),deliveries = _list(row['deliveries'] ?? const [],(d) => Map<String, dynamic>.unmodifiable(d),@@ -542,6 +550,9 @@ class SuperTabMessage {final Map<String, dynamic> source;final DateTime? createdAt;final List<SuperTabAttachment> attachments;++ /// The people a Lead tagged in this message, by person id.+ final List<String> mentions;final List<Map<String, dynamic>> deliveries;// Preserve the recorded identity for history and for removed agents. Views// with a current roster resolve the visible name through Snapshot.authorName.diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dartnew file mode 100644index 000000000..d00d9447f--- /dev/null+++ b/desktop/lib/super_tabs/notifications.dart@@ -0,0 +1,330 @@+import 'dart:async';++import 'package:flutter/foundation.dart' show kIsWeb;+import 'package:flutter/material.dart';++import '../notify/system_notifications.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'machine_status.dart' show superTabAgo;+import 'model.dart';+import 'section_heading.dart';++/// A Lead's tag of the reader in one message (spec 2026-10-24-lead-mentions.md).+class SuperTabMention {+ SuperTabMention.fromJson(Map<String, dynamic> row)+ : id = row['id'] as String,+ projectId = row['projectId'] as String? ?? '',+ projectName = row['projectName'] as String? ?? '',+ conversationId = row['conversationId'] as String,+ conversationTitle = row['conversationTitle'] as String? ?? '',+ messageId = row['messageId'] as String,+ leadName = row['leadName'] as String? ?? 'Lead',+ text = row['text'] as String? ?? '',+ createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),+ resolvedBy = row['resolvedBy'] as String?;+ final String id, projectId, projectName, conversationId, conversationTitle;+ final String messageId, leadName, text;+ final DateTime? createdAt;++ /// `reply` or `done` once it moved to Earlier; null while it waits.+ final String? resolvedBy;+}++/// What tells the person about a new tag outside the window: the operating+/// system, on Desktop only. The web shows only the badge and the list (spec+/// decision 6). The Settings switch for system notifications still applies.+void Function(SuperTabMention)? superTabMentionNotice(+ SystemNotifications system, {+ bool web = kIsWeb,+}) => web+ ? null+ : (mention) => system.postNotice(+ id: 'harness-mention:${mention.id}',+ title: '${mention.leadName} tagged you',+ body:+ '${mention.projectName} · ${mention.conversationTitle}: '+ '${mention.text}',+ );++/// The reader's tags in one Swarm: Waiting and Earlier, read from the backend+/// whenever the Swarm changes while a tag waits or the count moves. One per+/// controller.+class SuperTabMentions extends ChangeNotifier {+ SuperTabMentions._(this.controller) {+ controller.addListener(_changed);+ _changed();+ }++ static final _all = Expando<SuperTabMentions>();+ static SuperTabMentions of(SuperTabController controller) =>+ _all[controller] ??= SuperTabMentions._(controller);++ final SuperTabController controller;++ /// A tag that arrived after the first read, while the app was open.+ void Function(SuperTabMention mention)? onArrived;++ List<SuperTabMention> waiting = const [], earlier = const [];+ String? error;+ int? _count;+ int _revision = -1;+ // Null until the first read: tags waiting then are not news.+ Set<String>? _seen;+ Future<void>? _loading;+ // Something changed while a read was under way: read once more after it.+ bool _dirty = false;++ /// Starts from tags already announced elsewhere, so they are not news here.+ void seen(Set<String>? ids) {+ if (ids != null) _seen = {...?_seen, ...ids};+ }++ String get _path =>+ '/api/super-tabs/${Uri.encodeComponent(controller.tabId)}';++ /// A tag can arrive while another is answered, leaving the count as it was,+ /// so any change of the Swarm is read while a tag waits. With none waiting+ /// and none answered (an idle Swarm, or a backend before tags) nothing is.+ void _changed() {+ final snapshot = controller.snapshot;+ if (snapshot == null) return;+ // A tag that expires moves the count without changing the Swarm.+ final count = snapshot.mentionsWaiting;+ final moved = count != _count;+ if (!moved && controller.revision == _revision) return;+ _revision = controller.revision;+ _count = count;+ if (count == 0 && (!moved || _seen == null)) {+ _seen ??= {};+ return;+ }+ unawaited(load());+ }++ /// Joins a read under way, and has it read once more when asked again.+ Future<void> load() {+ if (_loading case final running?) {+ _dirty = true;+ return running;+ }+ return _loading = () async {+ do {+ _dirty = false;+ await _read();+ } while (_dirty);+ }().whenComplete(() => _loading = null);+ }++ Future<List<SuperTabMention>> _list(String state) async {+ final Map<String, dynamic> answer;+ try {+ answer = await controller.request('GET', '$_path/mentions?state=$state');+ } on SuperTabFailure catch (failure) {+ // A backend from before tags has no list: there is nothing to show.+ if (failure.statusCode == 404) return const [];+ rethrow;+ }+ return List.unmodifiable([+ for (final row in answer['mentions'] as List)+ SuperTabMention.fromJson(superTabMap(row)),+ ]);+ }++ Future<void> _read() async {+ try {+ final [nextWaiting, nextEarlier] = await Future.wait([+ _list('waiting'),+ _list('earlier'),+ ]);+ waiting = nextWaiting;+ earlier = nextEarlier;+ error = null;+ final seen = _seen;+ _seen = {...?seen, for (final m in waiting) m.id};+ if (seen != null) {+ for (final m in waiting.reversed) {+ if (!seen.contains(m.id)) onArrived?.call(m);+ }+ }+ } catch (_) {+ error = 'Could not load notifications. Try again.';+ }+ notifyListeners();+ }++ /// The reader is finished with [mention]. Any reader of the Swarm may, read+ /// only included, so this does not wait behind the composer's pending send.+ Future<bool> done(SuperTabMention mention) async {+ try {+ await controller.request(+ 'POST',+ '$_path/commands',+ body: {+ 'operationId': superTabOperationId(),+ 'command': {'type': 'mention.done', 'mentionId': mention.id},+ },+ );+ } catch (_) {+ error = 'Could not mark it done. Try again.';+ notifyListeners();+ return false;+ }+ await load();+ unawaited(controller.refresh());+ return true;+ }+}++/// The reader's tags across the Swarm: Waiting first, then Earlier, newest+/// first in each. Opening one goes to its message.+class SuperTabNotifications extends StatefulWidget {+ const SuperTabNotifications({+ super.key,+ required this.mentions,+ required this.onOpen,+ this.now = DateTime.now,+ });+ final SuperTabMentions mentions;+ final ValueChanged<SuperTabMention> onOpen;+ final DateTime Function() now;++ @override+ State<SuperTabNotifications> createState() => _SuperTabNotificationsState();+}++class _SuperTabNotificationsState extends State<SuperTabNotifications> {+ final _marking = <String>{};++ @override+ void initState() {+ super.initState();+ unawaited(widget.mentions.load());+ }++ Future<void> _done(SuperTabMention mention) async {+ setState(() => _marking.add(mention.id));+ await widget.mentions.done(mention);+ if (mounted) setState(() => _marking.remove(mention.id));+ }++ Widget _heading(String title) => Padding(+ padding: const EdgeInsets.fromLTRB(12, 16, 12, 4),+ child: SuperTabSectionHeading(title, endInset: 0),+ );++ Widget _empty(String text) => Padding(+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),+ child: Text(text, style: DesktopChrome.metadata()),+ );++ Widget _row(SuperTabMention mention, {required bool waiting}) {+ final time = mention.createdAt;+ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 1),+ child: Material(+ color: Colors.transparent,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ key: ValueKey('super-mention-${mention.id}'),+ onTap: () => widget.onOpen(mention),+ hoverColor: grid.AppSurface.hoverFill,+ focusColor: grid.AppSurface.hoverFill,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(12, 10, 8, 10),+ child: Row(+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Flexible(+ child: Text(+ mention.leadName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(medium: waiting),+ ),+ ),+ if (time != null) ...[+ const SizedBox(width: 8),+ Text(+ superTabAgo(widget.now().difference(time)),+ style: DesktopChrome.metadata(),+ ),+ ],+ ],+ ),+ Text(+ '${mention.projectName} · ${mention.conversationTitle}',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 2),+ Text(+ mention.text,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(+ color: waiting ? null : DesktopChrome.muted,+ ),+ ),+ ],+ ),+ ),+ if (waiting)+ Padding(+ padding: const EdgeInsets.only(left: 8),+ child: TextButton(+ onPressed: _marking.contains(mention.id)+ ? null+ : () => unawaited(_done(mention)),+ child: const Text('Mark done'),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: widget.mentions,+ builder: (context, _) {+ grid.AppTheme.watch(context);+ final m = widget.mentions;+ return ListView(+ padding: const EdgeInsets.only(bottom: 16),+ children: [+ if (m.error case final error?)+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),+ child: Row(+ children: [+ Expanded(child: Text(error, style: DesktopChrome.control())),+ TextButton(+ onPressed: () => unawaited(m.load()),+ child: const Text('Retry'),+ ),+ ],+ ),+ ),+ _heading('Waiting'),+ if (m.waiting.isEmpty) _empty('Nothing waiting for you.'),+ for (final mention in m.waiting) _row(mention, waiting: true),+ _heading('Earlier'),+ if (m.earlier.isEmpty) _empty('Nothing earlier.'),+ for (final mention in m.earlier) _row(mention, waiting: false),+ ],+ );+ },+ );+}diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex 2770e7c61..f58b10116 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -25,6 +25,8 @@ class ProjectSidebar extends StatelessWidget {this.onNewProject,this.onYourDevices,this.devicesSelected = false,+ this.onNotifications,+ this.notificationsSelected = false,this.onOpenAgent,this.readLocal,this.now = DateTime.now,@@ -37,6 +39,10 @@ class ProjectSidebar extends StatelessWidget {final VoidCallback? onNewProject;final VoidCallback? onYourDevices;final bool devicesSelected;++ /// The reader's tags from every project's Lead; its count is what waits.+ final VoidCallback? onNotifications;+ final bool notificationsSelected;final ValueChanged<SuperTabAgent>? onOpenAgent;/// Forwarded to the embedded [SuperTabMachines]; a test gives it to have@@ -59,6 +65,7 @@ class ProjectSidebar extends StatelessWidget {required IconData icon,required VoidCallback? onTap,bool selected = false,+ int badge = 0,}) => Padding(padding: const EdgeInsets.only(bottom: 2),child: Material(@@ -106,6 +113,25 @@ class ProjectSidebar extends StatelessWidget {),),),+ if (badge > 0)+ Padding(+ padding: const EdgeInsets.only(right: 10),+ child: Container(+ constraints: const BoxConstraints(minWidth: 18),+ padding: const EdgeInsets.symmetric(horizontal: 5),+ decoration: BoxDecoration(+ color: grid.AppPalette.warn.withValues(alpha: .16),+ borderRadius: BorderRadius.circular(9),+ ),+ child: Text(+ '$badge',+ textAlign: TextAlign.center,+ style: DesktopChrome.metadata(+ color: grid.AppPalette.warn,+ ),+ ),+ ),+ ),],),),@@ -120,7 +146,10 @@ class ProjectSidebar extends StatelessWidget {String? label,IconData? icon,}) {- final selected = !devicesSelected && controller.selectedId == group.id;+ final selected =+ !devicesSelected &&+ !notificationsSelected &&+ controller.selectedId == group.id;final groups = project == null? [group]: controller.snapshot!.conversations.where(@@ -384,8 +413,18 @@ class ProjectSidebar extends StatelessWidget {onTap: onYourDevices,selected: devicesSelected,),+ if (onNotifications != null)+ _navigationRow(+ key: 'super-notifications',+ label: 'Notifications',+ icon: AppIcons.bell,+ onTap: onNotifications,+ selected: notificationsSelected,+ badge: snapshot?.mentionsWaiting ?? 0,+ ),if (onNewProject != null ||onYourDevices != null ||+ onNotifications != null ||controller.isOwner ||snapshot?.localModels?.enabled == true)const SizedBox(height: 20),diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 2863dddda..dea51c5cc 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -20,6 +20,7 @@ import 'dialog_scope.dart';import 'model.dart';import 'message_row.dart';import 'message_receipt.dart';+import 'notifications.dart';import 'route_row.dart';import 'terminal_row.dart';import 'work_details.dart';@@ -79,6 +80,10 @@ class _SuperTabViewState extends State<SuperTabView>bool _sidebarOpen = false;bool _rosterOpen = false;bool _showPullRequests = false;+ bool _showNotifications = false;+ // The message a tag opened, scrolled to once it is laid out.+ String? _target;+ final _targetKey = GlobalKey();bool _viewEnabled = true;bool _chatCovered = false;final _loadingOlder = <String>{};@@ -238,7 +243,8 @@ class _SuperTabViewState extends State<SuperTabView>c.accessRevoked ||_devicesVisible ||_terminalsVisible ||- _showPullRequests) {+ _showPullRequests ||+ _showNotifications) {return false;}final lifecycle = WidgetsBinding.instance.lifecycleState;@@ -700,24 +706,106 @@ class _SuperTabViewState extends State<SuperTabView>onAddAgent: widget.onAddAgent,onNewProject: widget.onNewProject,devicesSelected: _devicesVisible,+ notificationsSelected: _notificationsVisible,+ onNotifications: () {+ _closeSidebar();+ setState(() {+ _showNotifications = true;+ _showPullRequests = false;+ });+ widget.onCloseTerminal?.call();+ },onOpenAgent: (agent) {_closeSidebar();- setState(() => _showPullRequests = false);+ setState(() {+ _showPullRequests = false;+ _showNotifications = false;+ });(widget.onChooseAgentTerminal ?? widget.onOpenTerminal)(agent);},onYourDevices: widget.app?.devicesEnabled != true? null: () {_closeSidebar();+ setState(() => _showNotifications = false);widget.app!.openDevices();},needsHuman: (group) => _needsHuman(group).length,onSelect: (id) {+ setState(() => _showNotifications = false);c.select(id);_closeSidebar();},);+ bool get _notificationsVisible =>+ _showNotifications && !_devicesVisible && !c.accessRevoked;++ /// Opens the conversation a tag is in, at its message, replying to it. Older+ /// pages are read first, until the message is among them; one that is not+ /// found says so, and the list stays.+ Future<void> _openMention(SuperTabMention mention) async {+ final id = mention.conversationId;+ if (c.snapshot?.conversation(id) == null) return;+ SuperTabMessage? message;+ // Up to 50 pages (5,000 messages) back.+ for (var page = 0; page < 50; page++) {+ await c.loadMessages(id, older: c.messages(id).isNotEmpty);+ if (!mounted) return;+ message = c+ .messages(id)+ .where((m) => m.id == mention.messageId)+ .firstOrNull;+ if (message != null || !c.hasOlder(id)) break;+ }+ if (message == null) {+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ SnackBar(+ content: Text(+ c.hasOlder(id)+ ? 'This message is too far back to open.'+ : 'This message is no longer in the conversation.',+ ),+ ),+ );+ return;+ }+ if (!_showNotifications) return;+ _showNotifications = false;+ c.select(id);+ setState(() {+ if (c.canWrite && c.selected?.archived == false) _replies[id] = message!;+ _target = message!.id;+ // Stop following the end: the tagged message is what to see.+ _scrollRequest++;+ _jumpingToEnd = false;+ _following[id] = false;+ });+ _revealTarget(id, 0);+ _focus.requestFocus();+ }++ /// The list is lazy: jump near the target until its row is built, then+ /// bring it into view.+ void _revealTarget(String id, int attempt) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || c.selectedId != id || _target == null) return;+ if (_targetKey.currentContext case final target?) {+ unawaited(Scrollable.ensureVisible(target, alignment: .3));+ return;+ }+ final scroll = _scroll[id];+ final messages = c.messages(id);+ final index = messages.indexWhere((m) => m.id == _target);+ if (scroll == null || !scroll.hasClients || index < 0 || attempt > 20) {+ return;+ }+ scroll.jumpTo(scroll.position.maxScrollExtent * index / messages.length);+ _revealTarget(id, attempt + 1);+ });+ WidgetsBinding.instance.scheduleFrame();+ }+List<SuperTabAgent> _needsHuman(SuperTabConversation group) =>c.snapshot?.agents.where(@@ -779,6 +867,8 @@ class _SuperTabViewState extends State<SuperTabView>Text(_devicesVisible? 'Your devices'+ : _notificationsVisible+ ? 'Notifications': group == null? c.snapshot?.projects.isEmpty == true? c.snapshot!.name@@ -792,7 +882,7 @@ class _SuperTabViewState extends State<SuperTabView>overflow: TextOverflow.ellipsis,style: DesktopChrome.text(medium: true),),- if (!_devicesVisible)+ if (!_devicesVisible && !_notificationsVisible)if (c.reviewLine(group) case final line?)Text(line,@@ -805,7 +895,9 @@ class _SuperTabViewState extends State<SuperTabView>),),),- if (group != null && !_devicesVisible) ...[+ if (group != null &&+ !_devicesVisible &&+ !_notificationsVisible) ...[AppIconButton(key: const ValueKey('super-chat'),icon: AppIcons.messageSquare,@@ -989,6 +1081,13 @@ class _SuperTabViewState extends State<SuperTabView>key: ValueKey('super-message-${message.id}'),message: message,author: _shownAuthor(c, message),+ // A person is named by their address's first part, as people say it.+ mentions: [+ for (final id in message.mentions)+ if (c.snapshot?.people.where((p) => p.id == id).firstOrNull+ case final person?)+ person.email.split('@').first,+ ],references: {for (final g in c.snapshot?.conversations ?? <SuperTabConversation>[])if (g.number != null) g.number!: g.id,@@ -1216,11 +1315,16 @@ class _SuperTabViewState extends State<SuperTabView>: () => _openAgent(agent),)else- _message(- message,- grouped.contains(message.id),- byId,- showReceipt: message.id == latestOwn?.id,+ KeyedSubtree(+ key: message.id == _target+ ? _targetKey+ : null,+ child: _message(+ message,+ grouped.contains(message.id),+ byId,+ showReceipt: message.id == latestOwn?.id,+ ),),],);@@ -1636,6 +1740,8 @@ class _SuperTabViewState extends State<SuperTabView>child: IndexedStack(index: _devicesVisible? 1+ : _notificationsVisible+ ? 3: c.snapshot?.projects.isEmpty == true? 0: _terminalsVisible@@ -1653,6 +1759,13 @@ class _SuperTabViewState extends State<SuperTabView>visible: !_terminalsVisible,): const SizedBox.shrink(),+ _notificationsVisible+ ? SuperTabNotifications(+ mentions: SuperTabMentions.of(c),+ onOpen: (mention) =>+ unawaited(_openMention(mention)),+ )+ : const SizedBox.shrink(),],),),diff --git a/desktop/lib/web/tabs/web_tab_menu.dart b/desktop/lib/web/tabs/web_tab_menu.dartindex c6a72270c..b3566e55e 100644--- a/desktop/lib/web/tabs/web_tab_menu.dart+++ b/desktop/lib/web/tabs/web_tab_menu.dart@@ -143,7 +143,9 @@ List<Widget> webTabMenuRows(content: PaneMenuRow(selected: tab.id == app.activeSwarmId,title: '${index + 1}:${names[tab.id] ?? tab.name}',- status: _statusLabel(tabActivity(app, tab)),+ status: tabMentionsWaiting(app, tab) > 0+ ? tabMentionsLabel(tabMentionsWaiting(app, tab))+ : _statusLabel(tabActivity(app, tab)),),),// This tab's sharing with other accounts (1c) and its Agent Messages, asdiff --git a/desktop/lib/web/tabs/web_tab_switcher.dart b/desktop/lib/web/tabs/web_tab_switcher.dartindex d65f248d1..42d2bbffd 100644--- a/desktop/lib/web/tabs/web_tab_switcher.dart+++ b/desktop/lib/web/tabs/web_tab_switcher.dart@@ -36,13 +36,17 @@ class WebTabSwitcher extends StatelessWidget {final index = app.swarms.indexWhere((tab) => tab.id == app.activeSwarmId);final name = workspaceTabNames(app)[app.activeSwarmId] ?? '';final activity = tabActivity(app, app.activeSwarm);+ final tags = tabMentionsWaiting(app, app.activeSwarm);final panes = app.panes;final shown = panes.indexWhere((pane) => pane.id == soloPaneId(app));final label = ['${index + 1}:$name',// Which of the tab's harnesses is on screen: a phone draws one.if (panes.length > 1) '· ${shown + 1}/${panes.length}',- if (activity?.mark.isNotEmpty == true) activity!.mark,+ if (tags > 0)+ '$tags'+ else if (activity?.mark.isNotEmpty == true)+ activity!.mark,].join(' ');return Row(children: [diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dartnew file mode 100644index 000000000..f61604f5b--- /dev/null+++ b/desktop/test/super_tab_mentions_test.dart@@ -0,0 +1,758 @@+import 'dart:async';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/notify/system_notifications.dart';+import 'package:harness/state/harness_activity.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/message_text.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/notifications.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';+import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;+import 'swarm_screen_test.dart' show mount;+import 'swarm_state_test.dart' show MemoryStore;++/// What would have reached the operating system.+class ShownNotices implements SystemNotifier {+ final shown = <({String title, String body})>[];+ @override+ bool get supported => true;+ @override+ bool get clickOpensAgent => false;+ @override+ String get deniedAdvice => '';+ @override+ Future<NotificationPermission> authorize() async =>+ NotificationPermission.granted;+ @override+ Future<NotificationPermission> show({+ required String id,+ required String title,+ required String body,+ required String machineId,+ required String agentId,+ }) async {+ shown.add((title: title, body: body));+ return NotificationPermission.granted;+ }++ @override+ Future<void> withdraw(String id) async {}+ @override+ set onTap(void Function(String machineId, String agentId)? handler) {}+}++Map<String, dynamic> messageRow({Object? mentions}) => {+ 'id': 'm1',+ 'conversationId': 'lead',+ 'sequence': 1,+ 'text': 'Please confirm the release.',+ 'author': {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'},+ 'mentions': ?mentions,+};++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_MENTION_SHOTS'];+final _picture = GlobalKey();++Future<void> shot(WidgetTester tester, String name) async {+ if (shots == null) return;+ await tester.runAsync(() async {+ final boundary =+ _picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;+ final image = await boundary.toImage();+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/$name.png').writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+}++Future<SuperTabController> showView(+ WidgetTester tester,+ ConversationServer server,+) async {+ await tester.binding.setSurfaceSize(const Size(1200, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => RepaintBoundary(key: _picture, child: child),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return c;+}++String minutesAgo(int minutes) => DateTime.now()+ .toUtc()+ .subtract(Duration(minutes: minutes))+ .toIso8601String();++/// The styles of every run of [text] painted in the tree.+List<TextStyle?> runsOf(WidgetTester tester, String text) => [+ for (final rich in tester.widgetList<RichText>(find.byType(RichText)))+ ..._runs(rich.text, null, text),+];++Iterable<TextStyle?> _runs(+ InlineSpan span,+ TextStyle? inherited,+ String text,+) sync* {+ if (span is! TextSpan) return;+ final style = inherited?.merge(span.style) ?? span.style;+ if (span.text == text) yield style;+ for (final child in span.children ?? const <InlineSpan>[]) {+ yield* _runs(child, style, text);+ }+}++Future<void> showText(WidgetTester tester, String text, List<String> names) =>+ tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(body: SuperTabMessageText(text, mentions: names)),+ ),+ );++Finder notificationsEntry() =>+ find.byKey(const ValueKey('super-notifications'));++void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ group('mention fields', () {+ test('a message names the people it tags', () {+ final message = SuperTabMessage.fromJson(+ messageRow(mentions: ['owner', 'dee']),+ );+ expect(message.mentions, ['owner', 'dee']);+ });++ test('a message from an older backend tags nobody', () {+ expect(SuperTabMessage.fromJson(messageRow()).mentions, isEmpty);+ });++ test('the tab state counts the reader\'s waiting tags', () {+ final server = ConversationServer();+ server.state['mentionsWaiting'] = 3;+ expect(SuperTabSnapshot.fromJson(server.state).mentionsWaiting, 3);+ });++ test('an older backend\'s state has no waiting tags', () {+ final server = ConversationServer();+ expect(SuperTabSnapshot.fromJson(server.state).mentionsWaiting, 0);+ });+ });++ group('notification list', () {+ test('reads waiting and earlier tags, newest first', () async {+ final server = ConversationServer()+ ..tag('m1', text: 'First')+ ..tag('m2', text: 'Second')+ ..tag('m3', text: 'Third');+ server.mentions[0]+ ..['resolvedAt'] = '2026-10-24T05:30:00Z'+ ..['resolvedBy'] = 'reply';+ server.state['mentionsWaiting'] = 2;+ final controller = server.controller();+ final mentions = SuperTabMentions.of(controller);+ await controller.refresh();+ await mentions.load();+ expect(mentions.waiting.map((m) => m.text), ['Third', 'Second']);+ expect(mentions.earlier.map((m) => m.text), ['First']);+ final first = mentions.waiting.first;+ expect(first.projectName, 'web-project');+ expect(first.conversationTitle, 'Lead');+ expect(first.leadName, 'Wren');+ expect(first.messageId, 'm3');+ expect(first.createdAt, DateTime.utc(2026, 10, 24, 5));+ controller.dispose();+ });++ test('reports a new tag once, never the ones already waiting', () async {+ final server = ConversationServer()..tag('m1', text: 'Old');+ final controller = server.controller();+ final arrived = <String>[];+ SuperTabMentions.of(controller).onArrived = (m) => arrived.add(m.text);+ await controller.refresh();+ await pumpEventQueue();+ expect(arrived, isEmpty);+ server.tag('m2', text: 'New');+ await controller.refresh();+ await pumpEventQueue();+ await controller.refresh();+ await pumpEventQueue();+ expect(arrived, ['New']);+ controller.dispose();+ });++ test('a new tag is read even when the count stays the same', () async {+ final server = ConversationServer()..tag('m1', text: 'First');+ final controller = server.controller();+ final mentions = SuperTabMentions.of(controller);+ final arrived = <String>[];+ mentions.onArrived = (m) => arrived.add(m.text);+ await controller.refresh();+ await pumpEventQueue();+ // The first is answered and a second arrives between two reads: 1 → 1.+ server.mentions.single+ ..['resolvedAt'] = '2026-10-24T05:10:00Z'+ ..['resolvedBy'] = 'reply';+ server.tag('m2', text: 'Second');+ server.state['mentionsWaiting'] = 1;+ await controller.refresh();+ await pumpEventQueue();+ expect(arrived, ['Second']);+ expect(mentions.waiting.map((m) => m.text), ['Second']);+ expect(mentions.earlier.map((m) => m.text), ['First']);+ controller.dispose();+ });++ test('a change during a read is read once more after it', () async {+ final server = ConversationServer()..tag('m1', text: 'First');+ final controller = server.controller();+ final mentions = SuperTabMentions.of(controller);+ final hold = server.holdMentions = Completer<void>();+ await controller.refresh();+ await pumpEventQueue();+ final reads = server.mentionReads;+ server.tag('m2', text: 'Second');+ await controller.refresh();+ server.revision++;+ await controller.refresh();+ server.holdMentions = null;+ hold.complete();+ await pumpEventQueue();+ // The held read, then exactly one more (both lists each time).+ expect(server.mentionReads - reads, 2);+ expect(mentions.waiting.map((m) => m.text), ['Second', 'First']);+ controller.dispose();+ });++ test(+ 'a backend without the list shows an empty list, not an error',+ () async {+ final server = ConversationServer()..mentionsMissing = true;+ final controller = server.controller();+ final mentions = SuperTabMentions.of(controller);+ await controller.refresh();+ await mentions.load();+ expect(mentions.error, isNull);+ expect(mentions.waiting, isEmpty);+ expect(mentions.earlier, isEmpty);+ controller.dispose();+ },+ );++ test(+ 'a tag that expires empties an open list with no new revision',+ () async {+ final server = ConversationServer()..tag('m1', text: 'Old');+ final controller = server.controller();+ final mentions = SuperTabMentions.of(controller);+ await controller.refresh();+ await pumpEventQueue();+ expect(mentions.waiting, hasLength(1));+ // 30 days on, the backend drops it; the tab itself did not change.+ server.mentions.clear();+ server.state['mentionsWaiting'] = 0;+ await controller.refresh();+ await pumpEventQueue();+ expect(mentions.waiting, isEmpty);+ controller.dispose();+ },+ );++ test('a backend without tags is never asked for them', () async {+ final server = ConversationServer();+ final controller = server.controller();+ SuperTabMentions.of(controller);+ await controller.refresh();+ await pumpEventQueue();+ expect(server.mentionReads, 0);+ controller.dispose();+ });++ test('mark done sends the tag\'s done and moves it to earlier', () async {+ final server = ConversationServer()..tag('m1');+ final controller = server.controller();+ final mentions = SuperTabMentions.of(controller);+ await controller.refresh();+ await mentions.load();+ expect(await mentions.done(mentions.waiting.single), isTrue);+ expect(server.posts.last['command'], {+ 'type': 'mention.done',+ 'mentionId': 'mention-1',+ });+ expect(mentions.waiting, isEmpty);+ expect(mentions.earlier.single.resolvedBy, 'done');+ controller.dispose();+ });+ });++ group('notifications view', () {+ testWidgets('the entry counts what waits and lists Waiting and Earlier', (+ tester,+ ) async {+ final server = ConversationServer()+ ..append('Earlier ask')+ ..append('Ship it?')+ ..tag('message-1', text: 'Earlier ask', createdAt: minutesAgo(90))+ ..tag('message-2', text: 'Ship it?', createdAt: minutesAgo(3));+ server.mentions[0]+ ..['resolvedAt'] = minutesAgo(80)+ ..['resolvedBy'] = 'reply';+ server.state['mentionsWaiting'] = 1;+ await showView(tester, server);+ expect(+ find.descendant(of: notificationsEntry(), matching: find.text('1')),+ findsOneWidget,+ );+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ final waiting = find.byKey(const ValueKey('super-mention-mention-2'));+ final earlier = find.byKey(const ValueKey('super-mention-mention-1'));+ expect(find.text('Waiting'), findsOneWidget);+ expect(find.text('Earlier'), findsOneWidget);+ expect(+ tester.getTopLeft(waiting).dy,+ lessThan(tester.getTopLeft(earlier).dy),+ );+ for (final text in [+ 'web-project · Lead',+ 'Wren',+ 'Ship it?',+ '3 min ago',+ ]) {+ expect(+ find.descendant(of: waiting, matching: find.text(text)),+ findsOneWidget,+ reason: text,+ );+ }+ expect(+ find.descendant(of: earlier, matching: find.text('1 h ago')),+ findsOneWidget,+ );+ });++ testWidgets('mark done moves the tag to Earlier and clears the count', (+ tester,+ ) async {+ final server = ConversationServer()+ ..append('Ship it?')+ ..tag('message-1', text: 'Ship it?', createdAt: minutesAgo(3));+ await showView(tester, server);+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ await tester.tap(find.text('Mark done'));+ await tester.pumpAndSettle();+ expect(find.text('Mark done'), findsNothing);+ expect(find.text('Nothing waiting for you.'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-mention-mention-1')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: notificationsEntry(), matching: find.text('1')),+ findsNothing,+ );+ });++ testWidgets('a tag too far back says so and stays on the list', (+ tester,+ ) async {+ final server = ConversationServer();+ server.state['conversations'] = [+ ...server.state['conversations'] as List,+ conversationFixture('group', 'Release'),+ ];+ // More than the 50 pages opening a tag reads back.+ for (var i = 1; i <= 5050; i++) {+ server.append('Note $i', conversationId: 'group');+ }+ server.tag('message-1', conversationId: 'group', text: 'Note 1');+ final c = await showView(tester, server);+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-mention-mention-1')));+ await tester.pumpAndSettle();+ expect(+ find.text('This message is too far back to open.'),+ findsOneWidget,+ );+ expect(find.text('Waiting'), findsOneWidget);+ expect(c.selectedId, isNot('group'));+ });++ testWidgets('opening a tag shows its message with the reply box on it', (+ tester,+ ) async {+ final server = ConversationServer();+ server.state['conversations'] = [+ ...server.state['conversations'] as List,+ conversationFixture('group', 'Release'),+ ];+ // Two pages back, and far from either end of what is loaded.+ for (var i = 1; i <= 250; i++) {+ server.append('Note $i', conversationId: 'group');+ }+ server.tag(+ 'message-100',+ conversationId: 'group',+ text: 'Note 100',+ createdAt: minutesAgo(3),+ );+ final c = await showView(tester, server);+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-mention-mention-1')));+ await tester.pumpAndSettle();+ expect(c.selectedId, 'group');+ expect(find.text('Replying to [email protected]'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-message-message-100')).hitTestable(),+ findsOneWidget,+ );+ expect(find.text('Waiting'), findsNothing);+ });+ });++ group('tags in messages', () {+ testWidgets('a tagged name reads highlighted where the text says it', (+ tester,+ ) async {+ await showText(tester, 'Please @dee confirm, not @bob.', ['dee']);+ final dee = runsOf(tester, '@dee').single;+ expect(dee?.color, grid.AppPalette.accentOnSurface);+ expect(dee?.backgroundColor, isNotNull);+ // One paragraph: the name does not break the line it is in.+ expect(+ find.text('Please @dee confirm, not @bob.', findRichText: true),+ findsOneWidget,+ );+ final bob = runsOf(tester, '@bob');+ expect(bob.every((s) => s?.backgroundColor == null), isTrue);+ });++ testWidgets('a name ending a sentence is still the name', (tester) async {+ await showText(tester, 'Over to @dee.', ['dee']);+ expect(runsOf(tester, '@dee').single?.backgroundColor, isNotNull);+ expect(find.text('Over to @dee.', findRichText: true), findsOneWidget);+ // Not shown again before the text, as if the text had not said it.+ expect(find.text('@dee', findRichText: true), findsNothing);+ });++ testWidgets('a full address is the same person', (tester) async {+ await showText(tester, 'Ask @[email protected] first.', ['dee']);+ expect(+ runsOf(tester, '@[email protected]').single?.backgroundColor,+ isNotNull,+ );+ });++ testWidgets('a tag the text does not say is shown before it', (+ tester,+ ) async {+ await showText(tester, 'Please confirm the release.', ['dee']);+ expect(runsOf(tester, '@dee').single?.backgroundColor, isNotNull);+ expect(+ find.textContaining('Please confirm the release.'),+ findsOneWidget,+ );+ });++ testWidgets('a tag in code stays code', (tester) async {+ await showText(tester, 'Run `ping @dee` now.', ['dee']);+ expect(runsOf(tester, 'ping @dee'), isNotEmpty);+ });++ testWidgets('the conversation highlights the people a message tags', (+ tester,+ ) async {+ final server = ConversationServer()..append('Can you confirm?');+ server.messages.last['mentions'] = ['owner'];+ await showView(tester, server);+ expect(runsOf(tester, '@owner').single?.backgroundColor, isNotNull);+ });+ });++ group('tab and system notice', () {+ test('only Desktop hands a new tag to the operating system', () async {+ final notices = ShownNotices();+ final store = DesktopNotificationStore(storage: MemoryStore());+ await store.set(true);+ final system = SystemNotifications(store: store, notifier: notices);+ expect(superTabMentionNotice(system, web: true), isNull);+ final server = ConversationServer()..tag('message-1', text: 'Ship it?');+ superTabMentionNotice(system, web: false)!(+ SuperTabMention.fromJson(server.mentions.single),+ );+ await pumpEventQueue();+ expect(notices.shown, [+ (title: 'Wren tagged you', body: 'web-project · Lead: Ship it?'),+ ]);+ });++ test('the client hands each new tag of an open Swarm over', () async {+ final server = ConversationServer()..tag('message-1', text: 'Old');+ final arrived = <String>[];+ final client = SuperTabClient(+ storage: MemoryStore(),+ transport: (method, path, {body}) =>+ server.request(method, path, body: body),+ discoveryInterval: Duration.zero,+ onMention: (mention) => arrived.add(mention.text),+ );+ addTearDown(client.dispose);+ client.bind('owner');+ final c = await client.open('tab');+ await c.refresh();+ await pumpEventQueue();+ server.tag('message-2', text: 'New');+ await c.refresh();+ await pumpEventQueue();+ expect(arrived, ['New']);+ });++ test('a Swarm tab not opened yet counts and announces new tags', () async {+ final server = ConversationServer()..tag('message-1', text: 'Old');+ final arrived = <String>[];+ var counted = 0;+ final client = SuperTabClient(+ storage: MemoryStore(),+ transport: (method, path, {body}) async => path == '/api/super-tabs'+ ? {+ 'tabs': [+ {'id': 'tab', 'name': 'Pilot'},+ ],+ 'next': null,+ }+ : server.request(method, path, body: body),+ discoveryInterval: Duration.zero,+ onTabs: (_, _) {},+ onMention: (mention) => arrived.add(mention.text),+ onTagCounts: () => counted++,+ );+ addTearDown(client.dispose);+ client.bind('owner');+ await client.refreshTabs();+ expect(client.waitingTags('tab'), 1);+ expect(arrived, isEmpty);+ expect(counted, 1);+ server.tag('message-2', text: 'New');+ await client.refreshTabs();+ expect(client.waitingTags('tab'), 2);+ expect(arrived, ['New']);+ // Opened, the Swarm's own state counts, and nothing is announced twice.+ final c = await client.open('tab');+ await c.refresh();+ await pumpEventQueue();+ final reads = server.mentionReads;+ await client.refreshTabs();+ expect(server.mentionReads, reads);+ expect(client.waitingTags('tab'), 2);+ expect(arrived, ['New']);+ });++ test(+ 'one Swarm without the list does not stop the others, and is asked again',+ () async {+ final server = ConversationServer()..tag('message-1', text: 'Here');+ var goneMissing = true;+ final client = SuperTabClient(+ storage: MemoryStore(),+ transport: (method, path, {body}) async {+ if (path == '/api/super-tabs') {+ return {+ 'tabs': [+ {'id': 'gone', 'name': 'Older'},+ {'id': 'tab', 'name': 'Pilot'},+ ],+ 'next': null,+ };+ }+ if (path.startsWith('/api/super-tabs/gone/')) {+ if (goneMissing) {+ throw const SuperTabFailure(+ 'NOT_FOUND',+ 'Not found.',+ statusCode: 404,+ );+ }+ return {'mentions': server.mentions.reversed.toList()};+ }+ return server.request(method, path, body: body);+ },+ discoveryInterval: Duration.zero,+ onTabs: (_, _) {},+ );+ addTearDown(client.dispose);+ client.bind('owner');+ await client.refreshTabs();+ expect(client.waitingTags('tab'), 1);+ expect(client.waitingTags('gone'), 0);+ // Its backend is updated during the session.+ goneMissing = false;+ server.tag('message-2', text: 'There');+ await client.refreshTabs();+ expect(client.waitingTags('tab'), 2);+ expect(client.waitingTags('gone'), 2);+ },+ );++ test('a Swarm tab with waiting tags asks for its person', () async {+ final f = SuperTabLaunchFixture(local: true);+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ final tab = f.app.activeSwarm;+ expect(tabMentionsWaiting(f.app, tab), 0);+ expect(tabActivity(f.app, tab), isNot(HarnessActivity.needsInput));+ f.connection.server.tag('message-1');+ await c.refresh();+ expect(tabMentionsWaiting(f.app, tab), 1);+ expect(tabActivity(f.app, tab), HarnessActivity.needsInput);+ });+ });++ testWidgets('screenshots for review', (tester) async {+ final server = ConversationServer();+ server.state['projects'] = [projectFixture('lead', 'web-project', 'lead')];+ server.state['people'] = [+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},+ ];+ server.state['conversations'] = [+ conversationFixture('lead', 'Lead'),+ {+ ...conversationFixture('group', 'Mentions: Desktop + web'),+ 'projectId': 'lead',+ 'number': 162,+ },+ ];+ Map<String, dynamic> wren(String text, String group) {+ server.append(text, conversationId: group);+ return server.messages.last+ ..['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ 'displayName': 'Wren',+ };+ }++ wren('The backend part is merged.', 'group');+ wren(+ 'The Desktop build is ready. Can you try it on your Mac and confirm?',+ 'group',+ )['mentions'] = [+ 'owner',+ ];+ wren(+ '@ken please approve the release window for Monday.',+ 'lead',+ )['mentions'] = [+ 'owner',+ ];+ server+ ..tag(+ 'message-2',+ conversationId: 'group',+ text: 'The Desktop build is ready. Can you try it on your Mac and confirm?',+ createdAt: minutesAgo(4),+ )+ ..tag(+ 'message-3',+ text: '@ken please approve the release window for Monday.',+ createdAt: minutesAgo(52),+ );+ server.mentions[0]['conversationTitle'] = '#162 Mentions: Desktop + web';+ server.mentions[1]+ ..['resolvedAt'] = minutesAgo(40)+ ..['resolvedBy'] = 'reply';+ server.state['mentionsWaiting'] = 1;+ await showView(tester, server);+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ await shot(tester, 'notifications');+ await tester.tap(find.byKey(const ValueKey('super-mention-mention-1')));+ await tester.pumpAndSettle();+ expect(find.text('Replying to Wren'), findsOneWidget);+ await shot(tester, 'opened-at-message');+ }, skip: shots == null);++ for (final native in [false, true]) {+ testWidgets('a Swarm tab behind another counts its waiting tags '+ '(native=$native)', (tester) async {+ final updates = <Map>[];+ const channel = MethodChannel('harness/swarm_tabs');+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (+ call,+ ) async {+ if (call.method == 'update') updates.add(call.arguments as Map);+ return true;+ });+ addTearDown(+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ channel,+ null,+ ),+ );+ final f = SuperTabLaunchFixture(local: true);+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ final swarm = f.app.activeSwarm;+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ f.connection.server+ ..tag('message-1')+ ..tag('message-2');+ await c.refresh();+ f.app.newSwarm(name: 'other');+ await mount(tester, f.app, nativeTabs: native);+ await tester.pump(const Duration(milliseconds: 100));+ if (native) {+ final tab = (updates.last['tabs'] as List).cast<Map>().singleWhere(+ (t) => t['id'] == swarm.id,+ );+ expect(tab['attention'], 2);+ } else {+ expect(+ tester+ .widget<Text>(find.byKey(ValueKey('tab-tags:${swarm.id}')))+ .data,+ '2',+ );+ }+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ f.dispose();+ });+ }+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex d0afdb22a..d956c9852 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -46,6 +46,14 @@ class ConversationServer {final messages = <Map<String, dynamic>>[];// Route decisions by id, answered by GET .../route-decisions/:id.final routeDecisions = <String, Map<String, dynamic>>{};+ // The reader's tags, newest last, answered by GET .../mentions?state=.+ final mentions = <Map<String, dynamic>>[];+ // How many times the mentions list was read.+ int mentionReads = 0;+ // A backend from before tags: it has no list route.+ bool mentionsMissing = false;+ // While set, every read of the mentions list waits for it.+ Completer<void>? holdMentions;// The effective routing policy answered by GET .../routing-policy.Map<String, dynamic>? routingPolicy;final state = <String, dynamic>{@@ -172,6 +180,12 @@ class ConversationServer {);messages.last['replyTo'] = command['replyTo'];output['messageId'] = 'message-$revision';+ } else if (command['type'] == 'mention.done') {+ mentions.firstWhere((m) => m['id'] == command['mentionId'])+ ..['resolvedAt'] = '2026-10-24T06:00:00Z'+ ..['resolvedBy'] = 'done';+ state['mentionsWaiting'] = (state['mentionsWaiting'] as int) - 1;+ revision++;} else if (command['type'] == 'conversation.create') {revision++;final id = 'group-$revision';@@ -260,6 +274,21 @@ class ConversationServer {if (holdReads case final hold?) await hold.future;if (failReads) throw StateError('Offline');final uri = Uri.parse(path);+ if (uri.pathSegments.last == 'mentions') {+ mentionReads++;+ if (mentionsMissing) {+ throw const SuperTabFailure('NOT_FOUND', 'Not found.', statusCode: 404);+ }+ if (holdMentions case final hold?) await hold.future;+ final waiting = uri.queryParameters['state'] == 'waiting';+ return jsonDecode(+ jsonEncode({+ 'mentions': mentions.reversed+ .where((m) => (m['resolvedAt'] == null) == waiting)+ .toList(),+ }),+ ) as Map<String, dynamic>;+ }if (uri.pathSegments.last == 'routing-policy') {final policy = routingPolicy;if (policy == null) {@@ -302,6 +331,30 @@ class ConversationServer {as Map<String, dynamic>;}+ /// The Lead tags the reader in [conversationId], as the backend records it.+ void tag(+ String messageId, {+ String conversationId = 'lead',+ String text = 'Please confirm the release.',+ String createdAt = '2026-10-24T05:00:00Z',+ }) {+ mentions.add({+ 'id': 'mention-${mentions.length + 1}',+ 'projectId': 'lead',+ 'projectName': 'web-project',+ 'conversationId': conversationId,+ 'conversationTitle': 'Lead',+ 'messageId': messageId,+ 'leadName': 'Wren',+ 'text': text,+ 'createdAt': createdAt,+ 'resolvedAt': null,+ 'resolvedBy': null,+ });+ state['mentionsWaiting'] = ((state['mentionsWaiting'] as int?) ?? 0) + 1;+ revision++;+ }+SuperTabController controller({Map<String, dynamic>? initial,String account = 'owner',