Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: Implement agent unread notifications and system notices

Dev jacob0414742b472f
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 364af3eed..12b06e9fb 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2495,6 +2495,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
return summarizeTurnText(text, signal, userMessage, session?.engine ?? 'claude', gateway, previousRecap)
},
}
+ // An Orchestrator specialist's turn end, or the Director's while specialists are still out, is not
+ // announced: the person asked to hear from the main agent once, not from every sub-agent. The dial
+ // hears it as `silent` on its summary card; the apps as `subagent` on `turn_ended` (below).
+ const isSubagentSession = (sessionId: string): boolean => {
+ const agentId = registry.bySession(sessionId)?.agentId
+ if (!agentId) return false
+ const role = backend.orchestratorRoleOf(agentId)
+ return role?.role === 'worker' || (role?.role === 'director' && role.busy)
+ }
const mirror = new CommanderMirror({
send: (frame) => backend.sendCommander(frame),
sendWeb: (frame) => backend.send(frame), // turn_summary_pending / turn_summary → web indicator
@@ -2505,14 +2514,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
...summarizer,
nameFor: (sessionId) => { const s = registry.bySession(sessionId); return s ? projectDisplayName(s) : undefined },
agentIdFor: (sessionId) => registry.bySession(sessionId)?.agentId,
- // An Orchestrator specialist's turn end, or the Director's while specialists are still out, is not
- // announced: the person asked to hear from the main agent once, not from every sub-agent.
- isSubagent: (sessionId) => {
- const agentId = registry.bySession(sessionId)?.agentId
- if (!agentId) return false
- const role = backend.orchestratorRoleOf(agentId)
- return role?.role === 'worker' || (role?.role === 'director' && role.busy)
- },
+ isSubagent: isSubagentSession,
// A claude sub-agent still at work is one whose transcript is still growing:
// `<session>/subagents/agent-<id>.jsonl` beside the parent's (the same file enrichSubagentStats
// reads). Written in the last SUBAGENT_IDLE_MS = alive; the held turn end waits for it.
@@ -2654,6 +2656,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// skips these; every other consumer ignores an unknown field. Measured before this existed: one
// agent credited with 42 turns in a single second, all re-reads.
if (event.type === 'turn_started' && (opts?.resumed || opts?.replay)) frame.replay = true
+ // The end of a turn carries the two facts an app needs to decide whether it is NEWS, in the clear
+ // for the same reason: `replay` — a turn re-read from disk, not one finishing now — and `subagent`
+ // — the dial's `silent`, a specialist's turn nobody asked to hear about. The phone notifies on
+ // neither. Absent = false, so an app that predates these reads every end as it always did.
+ if (event.type === 'turn_ended') {
+ if (opts?.resumed || opts?.replay) frame.replay = true
+ if (isSubagentSession(sessionId)) frame.subagent = true
+ }
backend.send(frame)
if (event.type === 'turn_started') {
turnStartedAt.set(sessionId, Date.now())
diff --git a/mobile/android/app/build.gradle.kts b/mobile/android/app/build.gradle.kts
index 4b34a9192..4c62fafb2 100644
--- a/mobile/android/app/build.gradle.kts
+++ b/mobile/android/app/build.gradle.kts
@@ -29,6 +29,8 @@ android {
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
+ // flutter_local_notifications (the "agent finished" notice) needs java.time on every API level.
+ isCoreLibraryDesugaringEnabled = true
}
defaultConfig {
@@ -70,3 +72,7 @@ kotlin {
flutter {
source = "../.."
}
+
+dependencies {
+ coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
+}
diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift
index 0969f9050..3c09f949d 100644
--- a/mobile/ios/Runner/AppDelegate.swift
+++ b/mobile/ios/Runner/AppDelegate.swift
@@ -1,5 +1,6 @@
import Flutter
import UIKit
+import UserNotifications
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
@@ -7,6 +8,9 @@ import UIKit
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
+ // The "agent finished" notice (Dart: `lib/notify/system_notices.dart`): a tap on it has to reach
+ // flutter_local_notifications, which only hears it while the app delegate is the centre's delegate.
+ UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
diff --git a/mobile/lib/notify/agent_unread.dart b/mobile/lib/notify/agent_unread.dart
new file mode 100644
index 000000000..42bac25f5
--- /dev/null
+++ b/mobile/lib/notify/agent_unread.dart
@@ -0,0 +1,38 @@
+import 'package:flutter/foundation.dart';
+
+import 'package:harness_mobile/core/last_opened_agent.dart';
+
+/// Which agents finished while the person was looking somewhere else.
+///
+/// The phone's half of the desktop's `AgentUnread` (`desktop/lib/notify/
+/// agent_alerts.dart`) and of the dial's bell badge: a mark that sits still
+/// until somebody goes to that agent. Its own notifier rather than app state,
+/// so a mark appearing redraws the rows that show it and nothing else.
+class AgentUnread extends ChangeNotifier {
+ final _unread = <String>{};
+
+ static String _key(AgentRef ref) => '${ref.machineId}/${ref.agentId}';
+
+ /// How many agents are carrying news. Agents, not turns — the number answers
+ /// "how many should I look at", and an agent that finished three turns is
+ /// still one place to go.
+ int get count => _unread.length;
+
+ bool contains(AgentRef ref) => _unread.contains(_key(ref));
+
+ void mark(AgentRef ref) {
+ if (_unread.add(_key(ref))) notifyListeners();
+ }
+
+ /// The person went and looked. Silent when there was nothing to clear, so a
+ /// pane being focused for any other reason does not redraw anything.
+ void clear(AgentRef ref) {
+ if (_unread.remove(_key(ref))) notifyListeners();
+ }
+
+ void clearAll() {
+ if (_unread.isEmpty) return;
+ _unread.clear();
+ notifyListeners();
+ }
+}
diff --git a/mobile/lib/notify/done_announcer.dart b/mobile/lib/notify/done_announcer.dart
new file mode 100644
index 000000000..1c5397c9f
--- /dev/null
+++ b/mobile/lib/notify/done_announcer.dart
@@ -0,0 +1,95 @@
+import 'package:flutter/services.dart';
+import 'package:flutter/widgets.dart';
+
+import 'package:harness_mobile/core/last_opened_agent.dart';
+
+import 'agent_unread.dart';
+import 'done_notice.dart';
+import 'system_notices.dart';
+
+/// Who finished, in the words the notice uses.
+typedef DoneAgent = ({AgentRef ref, String name, String machine});
+
+/// Carries out [decideDoneNotice]: the chime, the unread mark, the system
+/// notice. The notifier says what happened; this decides what it is worth and
+/// does it, so none of the three can drift from the rule.
+class DoneAnnouncer {
+ DoneAnnouncer({
+ required this.system,
+ Future<void> Function()? chime,
+ bool Function()? inFront,
+ }) : _chime = chime ?? _haptic,
+ _inFront = inFront ?? _appInFront;
+
+ final SystemNotices system;
+ final unread = AgentUnread();
+ final Future<void> Function() _chime;
+ final bool Function() _inFront;
+
+ /// The dial's three tones, as a phone says them without a sound: a tap the
+ /// hand feels even with the ringer off. Never worth an error — a plain
+ /// `test()` has no binding to send it through.
+ static Future<void> _haptic() async {
+ try {
+ await HapticFeedback.mediumImpact();
+ } catch (_) {}
+ }
+
+ /// Whether the app is on screen. ⚠️ Tolerant of there being NO binding, as
+ /// the desktop's `lifecycle` is: plain `test()`s drive the notifier without
+ /// one, and `WidgetsBinding.instance` throws rather than answering null.
+ /// Unknown counts as in front, which errs toward a mark over a notice.
+ static bool _appInFront() {
+ try {
+ final state = WidgetsBinding.instance.lifecycleState;
+ return state == null || state == AppLifecycleState.resumed;
+ } catch (_) {
+ return true;
+ }
+ }
+
+ bool get inFront => _inFront();
+
+ /// One turn ended. [watching] is whether [agent] is the one on screen —
+ /// only asked when the app is in front.
+ DoneNotice turnEnded(
+ DoneAgent agent,
+ TurnEnd end, {
+ required bool Function() watching,
+ }) {
+ final front = inFront;
+ final notice = decideDoneNotice(
+ end,
+ inFront: front,
+ watching: front && watching(),
+ );
+ if (notice.chimes && front) _chime();
+ if (notice.marks) unread.mark(agent.ref);
+ if (notice.alerts) {
+ system.show((
+ agent: agent.ref,
+ title: agent.name,
+ machine: agent.machine,
+ body: noticeBody(end.reply!),
+ ));
+ }
+ return notice;
+ }
+
+ /// [system] is left alone: the shell may still be letting go of its
+ /// [SystemNotices.opened] after the notifier has gone.
+ void dispose() => unread.dispose();
+}
+
+/// The reply, cut to what a lock screen shows: its last paragraph — where an
+/// agent says what it did — on one line, at most [limit] characters.
+String noticeBody(String reply, {int limit = 180}) {
+ final paragraphs = reply
+ .trim()
+ .split(RegExp(r'\n\s*\n'))
+ .where((p) => p.trim().isNotEmpty);
+ final last = paragraphs.isEmpty ? reply : paragraphs.last;
+ final line = last.replaceAll(RegExp(r'\s+'), ' ').trim();
+ if (line.length <= limit) return line;
+ return '${line.substring(0, limit - 1).trimRight()}…';
+}
diff --git a/mobile/lib/notify/done_notice.dart b/mobile/lib/notify/done_notice.dart
new file mode 100644
index 000000000..22b34399e
--- /dev/null
+++ b/mobile/lib/notify/done_notice.dart
@@ -0,0 +1,89 @@
+/// The dial's rule for a finished turn, on a phone.
+///
+/// Ported from the firmware, which is where this was decided and argued out:
+/// `devices/harness-device/firmware/main/cable_client.c` (the `summary` frame)
+/// and `ui_notify_task_done` in `firmware/main/ui/ui_screens.c`. Keep the two in
+/// step — a turn the dial stays quiet about must not make the phone buzz.
+library;
+
+/// One turn's end, as the machine socket reported it.
+///
+/// The flags come straight off the `turn_ended` frame. Every one of them is
+/// ABSENT from an older daemon and absent reads as false, so a phone talking to
+/// one notifies exactly as if the daemon had said "yes, this is news".
+typedef TurnEnd = ({
+ /// Killed by an interrupt. The dial draws a bare `done` for it — no beep, no
+ /// recap — because the person who pressed stop already knows.
+ bool aborted,
+
+ /// A turn re-read from disk while a session was picked back up, not one
+ /// finishing now. The dial's `restore` door: history being filled in must not
+ /// announce every turn that ended while nobody was connected.
+ bool replay,
+
+ /// An Orchestrator specialist's turn, or its Director's while specialists are
+ /// still out — the dial's `silent`. "chỉ cần báo thằng main thôi" (owner,
+ /// 2026-09-21): only the main agent is worth hearing from.
+ bool subagent,
+
+ /// What the turn said, or null when it said nothing. The dial rings on the
+ /// SUMMARY, never on the bare `done`: a tools-only or phantom turn has no
+ /// summary, stays silent, and the notification always has words in it.
+ String? reply,
+});
+
+/// Reads a [TurnEnd] off one `turn_ended` frame. [reply] is what the phone saw
+/// the turn say (`SessionPreview.turnReply`), which the frame does not carry.
+TurnEnd turnEndFrom(
+ Map<String, dynamic> event,
+ Map<String, dynamic> payload, {
+ required String? reply,
+}) => (
+ aborted: payload['aborted'] == true,
+ replay: event['replay'] == true,
+ subagent: event['subagent'] == true,
+ reply: reply,
+);
+
+/// What the phone does about one finished turn — escalating, each step doing
+/// everything the one before it does.
+enum DoneNotice {
+ /// Not news. Nothing at all.
+ none,
+
+ /// The person is looking straight at this agent. The tap still comes — the
+ /// dial's beep ALWAYS sounds, because somebody reading the last reply is not
+ /// watching for the next to end — but nothing is filed for later: they are
+ /// already where the news is.
+ chime,
+
+ /// The app is in front of the person, on something else. Chime, and mark the
+ /// agent unread — the dial's badge. Never more than that: an agent finishing
+ /// elsewhere must not yank anybody off what they are doing.
+ mark,
+
+ /// The app is not in front of anybody. Mark it, and post a system
+ /// notification — the dial waking its dark panel onto the drawer.
+ alert;
+
+ bool get chimes => this != none;
+ bool get marks => this == mark || this == alert;
+ bool get alerts => this == alert;
+}
+
+/// Decides what one turn's end is worth.
+///
+/// [inFront] is whether the app is on screen at all; [watching] whether the
+/// agent it is showing is the one that finished — only meaningful in front.
+DoneNotice decideDoneNotice(
+ TurnEnd end, {
+ required bool inFront,
+ required bool watching,
+}) {
+ if (end.aborted || end.replay || end.subagent) return DoneNotice.none;
+ final reply = end.reply;
+ if (reply == null || reply.trim().isEmpty) return DoneNotice.none;
+ if (!inFront) return DoneNotice.alert;
+ if (watching) return DoneNotice.chime;
+ return DoneNotice.mark;
+}
diff --git a/mobile/lib/notify/system_notices.dart b/mobile/lib/notify/system_notices.dart
new file mode 100644
index 000000000..e5e0e471a
--- /dev/null
+++ b/mobile/lib/notify/system_notices.dart
@@ -0,0 +1,169 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter_local_notifications/flutter_local_notifications.dart';
+
+import 'package:harness_mobile/core/last_opened_agent.dart';
+import 'package:harness_mobile/logging/app_log.dart';
+
+/// One "agent finished" notice, as the OS draws it: the agent's name, the
+/// machine it runs on, and what the turn said — the three lines of the dial's
+/// drawer row.
+typedef DoneNoticeMessage = ({
+ AgentRef agent,
+ String title,
+ String machine,
+ String body,
+});
+
+/// The OS notification centre, as far as the phone uses it.
+///
+/// An interface so the notifier's tests never reach a platform plugin — see
+/// [SilentSystemNotices].
+abstract interface class SystemNotices {
+ /// Asks the person, once, whether the phone may notify them. The OS
+ /// remembers the answer; asking again is a no-op.
+ Future<void> requestPermission();
+
+ Future<void> show(DoneNoticeMessage message);
+
+ /// The agent whose notice was tapped last — what the shell opens. Reset to
+ /// null by whoever acts on it.
+ ValueNotifier<AgentRef?> get opened;
+}
+
+/// Nothing leaves the process. What a test notifier is given.
+class SilentSystemNotices implements SystemNotices {
+ @override
+ final opened = ValueNotifier<AgentRef?>(null);
+
+ @override
+ Future<void> requestPermission() async {}
+
+ @override
+ Future<void> show(DoneNoticeMessage message) async {}
+}
+
+/// The real centre, through flutter_local_notifications.
+///
+/// Started lazily on first use, so a launch that never needs it — and every
+/// test — pays nothing for it.
+class LocalSystemNotices implements SystemNotices {
+ LocalSystemNotices([FlutterLocalNotificationsPlugin? plugin])
+ : _plugin = plugin ?? FlutterLocalNotificationsPlugin();
+
+ final FlutterLocalNotificationsPlugin _plugin;
+ Future<void>? _ready;
+
+ @override
+ final opened = ValueNotifier<AgentRef?>(null);
+
+ static const _channel = AndroidNotificationDetails(
+ 'agent-done',
+ 'Agent finished',
+ channelDescription: 'An agent finished its turn while Harness was away.',
+ importance: Importance.high,
+ priority: Priority.high,
+ );
+
+ Future<void> _init() => _ready ??= _start();
+
+ Future<void> _start() async {
+ await _plugin.initialize(
+ settings: const InitializationSettings(
+ android: AndroidInitializationSettings('@mipmap/ic_launcher'),
+ // Asked for explicitly in [requestPermission], never as a side effect
+ // of the first notice.
+ iOS: DarwinInitializationSettings(
+ requestAlertPermission: false,
+ requestBadgePermission: false,
+ requestSoundPermission: false,
+ ),
+ ),
+ onDidReceiveNotificationResponse: (response) => _open(response.payload),
+ );
+ // A notice tapped while the app was not running at all launches it; the
+ // tap reaches no callback then, only this.
+ final launch = await _plugin.getNotificationAppLaunchDetails();
+ if (launch?.didNotificationLaunchApp ?? false) {
+ _open(launch?.notificationResponse?.payload);
+ }
+ }
+
+ void _open(String? payload) {
+ final agent = decodeAgentPayload(payload);
+ if (agent != null) opened.value = agent;
+ }
+
+ @override
+ Future<void> requestPermission() async {
+ try {
+ await _init();
+ await _plugin
+ .resolvePlatformSpecificImplementation<
+ IOSFlutterLocalNotificationsPlugin
+ >()
+ ?.requestPermissions(alert: true, sound: true);
+ await _plugin
+ .resolvePlatformSpecificImplementation<
+ AndroidFlutterLocalNotificationsPlugin
+ >()
+ ?.requestNotificationsPermission();
+ } catch (error) {
+ appLog.warn('notify', 'permission request failed', error: error);
+ }
+ }
+
+ @override
+ Future<void> show(DoneNoticeMessage message) async {
+ try {
+ await _init();
+ await _plugin.show(
+ // One per AGENT: a newer turn replaces its own last notice rather than
+ // stacking beside it — the desktop banner's rule.
+ id: noticeIdFor(message.agent),
+ title: message.title,
+ body: message.body,
+ payload: encodeAgentPayload(message.agent),
+ notificationDetails: NotificationDetails(
+ android: AndroidNotificationDetails(
+ _channel.channelId,
+ _channel.channelName,
+ channelDescription: _channel.channelDescription,
+ importance: _channel.importance,
+ priority: _channel.priority,
+ subText: message.machine,
+ ),
+ iOS: DarwinNotificationDetails(
+ subtitle: message.machine,
+ threadIdentifier: 'agent-done',
+ ),
+ ),
+ );
+ } catch (error) {
+ appLog.warn('notify', 'notice failed', error: error);
+ }
+ }
+}
+
+/// A stable, positive id per agent, so a notice replaces the last one for the
+/// same agent across runs too.
+@visibleForTesting
+int noticeIdFor(AgentRef agent) {
+ // FNV-1a: `String.hashCode` is not guaranteed stable from one run to the next.
+ var hash = 0x811c9dc5;
+ for (final unit in encodeAgentPayload(agent).codeUnits) {
+ hash = ((hash ^ unit) * 0x01000193) & 0x7fffffff;
+ }
+ return hash;
+}
+
+@visibleForTesting
+String encodeAgentPayload(AgentRef agent) =>
+ '${agent.machineId}\n${agent.agentId}';
+
+@visibleForTesting
+AgentRef? decodeAgentPayload(String? payload) {
+ final parts = payload?.split('\n');
+ if (parts == null || parts.length != 2) return null;
+ if (parts[0].isEmpty || parts[1].isEmpty) return null;
+ return (machineId: parts[0], agentId: parts[1]);
+}
diff --git a/mobile/lib/notify/unread_marks.dart b/mobile/lib/notify/unread_marks.dart
new file mode 100644
index 000000000..3df5d0741
--- /dev/null
+++ b/mobile/lib/notify/unread_marks.dart
@@ -0,0 +1,92 @@
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import 'agent_unread.dart';
+
+/// The mark on one agent's row: it finished while you were elsewhere.
+///
+/// The row's own unread dot, iOS Mail's — small and in the accent, before the
+/// name, so it reads before the name does and never pushes anything else off.
+class UnreadDot extends StatelessWidget {
+ const UnreadDot({super.key});
+
+ static const double diameter = 8;
+
+ @override
+ Widget build(BuildContext context) => Container(
+ key: const ValueKey('unread-dot'),
+ width: diameter,
+ height: diameter,
+ margin: const EdgeInsets.only(right: 7),
+ decoration: const BoxDecoration(
+ color: AppPalette.accent,
+ shape: BoxShape.circle,
+ ),
+ );
+}
+
+/// [child] with the count of agents carrying news in its top-right corner —
+/// the dial's bell pill. Nothing is drawn while the count is zero.
+///
+/// Listens to [unread] alone, so a mark appearing redraws this badge and not
+/// the page it sits on.
+class UnreadCountBadge extends StatelessWidget {
+ const UnreadCountBadge({
+ super.key,
+ required this.unread,
+ required this.child,
+ });
+
+ final AgentUnread unread;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: unread,
+ child: child,
+ builder: (context, child) {
+ final count = unread.count;
+ return Stack(
+ clipBehavior: Clip.none,
+ children: [
+ child!,
+ if (count > 0)
+ Positioned(
+ top: -4,
+ right: -4,
+ child: IgnorePointer(child: _CountPill(count: count)),
+ ),
+ ],
+ );
+ },
+ );
+}
+
+class _CountPill extends StatelessWidget {
+ const _CountPill({required this.count});
+
+ final int count;
+
+ @override
+ Widget build(BuildContext context) => Container(
+ key: const ValueKey('unread-count'),
+ constraints: const BoxConstraints(minWidth: 18),
+ height: 18,
+ padding: const EdgeInsets.symmetric(horizontal: 5),
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: AppPalette.accent,
+ borderRadius: BorderRadius.circular(9),
+ ),
+ child: Text(
+ count > 9 ? '9+' : '$count',
+ style: const TextStyle(
+ color: Colors.white,
+ fontSize: 11,
+ fontWeight: FontWeight.w700,
+ height: 1,
+ ),
+ ),
+ );
+}
diff --git a/mobile/lib/phone/desk_tabs_panel.dart b/mobile/lib/phone/desk_tabs_panel.dart
index 28e2b7d7a..dbe4c8027 100644
--- a/mobile/lib/phone/desk_tabs_panel.dart
+++ b/mobile/lib/phone/desk_tabs_panel.dart
@@ -281,7 +281,11 @@ class _DeskTabsPanelState extends State<DeskTabsPanel> {
Widget build(BuildContext context) {
AppTheme.watch(context);
return ListenableBuilder(
- listenable: widget.notifier,
+ // The unread marks have their own notifier — see `notify/agent_unread.dart`.
+ listenable: Listenable.merge([
+ widget.notifier,
+ widget.notifier.doneNotices.unread,
+ ]),
builder: (context, _) => _panel(context),
);
}
@@ -375,6 +379,9 @@ class _DeskTabsPanelState extends State<DeskTabsPanel> {
final entry = group.entries[index];
return DeskAgentRow(
entry: entry,
+ unread: widget.notifier.doneNotices.unread.contains(
+ _refOf(entry),
+ ),
onScreen:
showing != null &&
entry.machineId == showing.machineId &&
@@ -403,10 +410,14 @@ class DeskAgentRow extends StatelessWidget {
required this.first,
required this.last,
required this.onTap,
+ this.unread = false,
});
final AgentEntry entry;
+ /// It finished a turn while you were elsewhere — see [SheetAgentTitle.unread].
+ final bool unread;
+
/// The agent on screen. It keeps its row — it is the one you came from, and
/// the list would read as missing an agent without it — and wears the check
/// where the others have a chevron.
@@ -434,6 +445,7 @@ class DeskAgentRow extends StatelessWidget {
title: SheetAgentTitle(
entry: entry,
now: DateTime.now(),
+ unread: unread,
name: Text(
agent.displayName,
maxLines: 1,
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 9045fe15e..6127feaab 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -60,11 +62,17 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
+ final notices = widget.notifier.doneNotices.system;
+ notices.opened.addListener(_openNoticedAgent);
+ // Signed in is the first moment a notice could be worth anything, so it is
+ // the moment to ask. The OS keeps the answer; every later ask is a no-op.
+ unawaited(notices.requestPermission());
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
+ widget.notifier.doneNotices.system.opened.removeListener(_openNoticedAgent);
_linkedMachineId.dispose();
_openAgentRequest.dispose();
for (final controller in _heroControllers.values) {
@@ -138,6 +146,16 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
});
}
+ /// A tapped "agent finished" notice: that agent, as the home screen — the
+ /// dial's drawer row opening its agent.
+ void _openNoticedAgent() {
+ final opened = widget.notifier.doneNotices.system.opened;
+ final agent = opened.value;
+ if (agent == null) return;
+ opened.value = null;
+ _openAgentAtHome(agent.machineId, agent.agentId);
+ }
+
/// Back in the foreground: a p2p retry waiting out its delay fires now, and so does every machine
/// socket the phone lost while it was away. Going to the background needs nothing — the OS
/// suspends the socket, and the redial tears the old wire down and negotiates a fresh one.
diff --git a/mobile/lib/phone/sheet_agent_lines.dart b/mobile/lib/phone/sheet_agent_lines.dart
index 4b813d8e4..b0a98f73a 100644
--- a/mobile/lib/phone/sheet_agent_lines.dart
+++ b/mobile/lib/phone/sheet_agent_lines.dart
@@ -3,6 +3,7 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/core/agent_output_stats.dart';
import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/notify/unread_marks.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'agent_index.dart';
@@ -60,10 +61,15 @@ class SheetAgentTitle extends StatelessWidget {
required this.entry,
required this.name,
required this.now,
+ this.unread = false,
});
final AgentEntry entry;
+ /// Whether the agent finished a turn nobody has looked at yet — see
+ /// `notify/done_notice.dart`. Marked with an [UnreadDot] before the name.
+ final bool unread;
+
/// The name as the caller draws it — plain in the tabs, with the query's hits in bold in search.
final Widget name;
@@ -76,6 +82,7 @@ class SheetAgentTitle extends StatelessWidget {
final attention = agentAttention(entry);
return Row(
children: [
+ if (unread) const UnreadDot(),
Flexible(child: name),
if (activity != null)
Padding(
diff --git a/mobile/lib/phone/terminal_action_column.dart b/mobile/lib/phone/terminal_action_column.dart
index d037ff3d6..8557f881b 100644
--- a/mobile/lib/phone/terminal_action_column.dart
+++ b/mobile/lib/phone/terminal_action_column.dart
@@ -2,6 +2,8 @@ import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show OverflowBoxFit;
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:harness_mobile/notify/agent_unread.dart';
+import 'package:harness_mobile/notify/unread_marks.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/terminal/terminal_session.dart';
@@ -42,10 +44,16 @@ class TerminalActionColumn extends StatefulWidget {
required this.voice,
required this.session,
required this.onSearch,
+ this.unread,
});
final VoiceInputController voice;
+ /// Agents that finished while you were on this one. Search is where they are
+ /// reached from, so it wears their count — the dial's bell pill. Null draws
+ /// the plain button.
+ final AgentUnread? unread;
+
/// Null while the terminal is still attaching: the mic is drawn dimmed and
/// dead, since there is nothing to talk to yet.
final TerminalSession? session;
@@ -128,11 +136,13 @@ class _TerminalActionColumnState extends State<TerminalActionColumn> {
const VoiceMicButton(face: VoiceMicFace.talk, onPressed: null),
const SizedBox(height: TerminalActionColumn._underMic),
_centred(
- TerminalRoundAction(
- key: const ValueKey('terminal-search'),
- icon: LucideIcons.search300,
- label: 'Search harnesses and machines',
- onTap: widget.onSearch,
+ _withUnread(
+ TerminalRoundAction(
+ key: const ValueKey('terminal-search'),
+ icon: LucideIcons.search300,
+ label: 'Search harnesses and machines',
+ onTap: widget.onSearch,
+ ),
),
),
],
@@ -190,6 +200,12 @@ class _TerminalActionColumnState extends State<TerminalActionColumn> {
);
}
+ Widget _withUnread(Widget button) {
+ final unread = widget.unread;
+ if (unread == null) return button;
+ return UnreadCountBadge(unread: unread, child: button);
+ }
+
Widget _centred(Widget child) => SizedBox(
width: TerminalActionColumn.width,
child: Center(child: child),
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 75d47654f..015ff6226 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -1392,6 +1392,8 @@ class _TerminalPageState extends State<TerminalPage>
voice: widget.voice,
session: session,
onSearch: _openSearch,
+ unread:
+ widget.notifier.doneNotices.unread,
),
),
],
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 700e02f93..95c338eda 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -34,6 +34,9 @@ import '../core/project_history.dart';
import '../core/retry.dart';
import '../logging/app_log.dart';
import '../logging/startup_trace.dart';
+import '../notify/done_announcer.dart';
+import '../notify/done_notice.dart';
+import '../notify/system_notices.dart';
import '../settings/config_store.dart';
import '../stats/harness_stats.dart';
import '../terminal/terminal_session.dart';
@@ -407,6 +410,10 @@ class AppNotifier extends ChangeNotifier {
),
);
+ /// What a finished turn is worth — a tap, an unread mark, a system notice —
+ /// decided by the dial's rule (`notify/done_notice.dart`).
+ final DoneAnnouncer doneNotices;
+
SessionPreviewKey previewKey(String machineId, Agent agent) =>
(machineId: machineId, agentId: agent.id, sessionId: agent.sessionId);
@@ -1096,7 +1103,12 @@ class AppNotifier extends ChangeNotifier {
/// no pointer behind it: the dial's scroll and focus frames, and which agent
/// the rail draws as current.
int? get focusedPaneId => activeSwarm.focusedPaneId;
- set focusedPaneId(int? value) => activeSwarm.focusedPaneId = value;
+ set focusedPaneId(int? value) {
+ activeSwarm.focusedPaneId = value;
+ // Every route onto an agent ends here, so none of them has to remember
+ // that going to an agent is what reads its news.
+ _seeWatchedAgent();
+ }
int _paneFocusRequest = 0;
@@ -1257,8 +1269,18 @@ class AppNotifier extends ChangeNotifier {
PeerLinkClient? peerLinks,
ViewerServices? viewer,
PaneLayoutStore? paneLayoutStore,
+ SystemNotices? systemNotices,
this.turnActivityTimeout = const Duration(seconds: 12),
}) : _paneLayout = paneLayoutStore,
+ // On the same terms as the stores below: no layout store means a test,
+ // which must never reach the OS notification centre.
+ doneNotices = DoneAnnouncer(
+ system:
+ systemNotices ??
+ (paneLayoutStore == null
+ ? SilentSystemNotices()
+ : LocalSystemNotices()),
+ ),
// Remembers "a dial has been seen here" on the same terms the pane
// layout is remembered: with a layout store there is a state file, and
// without one (the tests) nothing is written anywhere.
@@ -2815,6 +2837,7 @@ class AppNotifier extends ChangeNotifier {
// ever read after a sign-in that this clears the way for.
unawaited(_machineCache?.clear());
sessionPreviews.clear();
+ doneNotices.unread.clearAll();
expandedMachines.clear();
selectedMachineId = null;
status = AppStatus.unauthenticated;
@@ -4344,6 +4367,11 @@ class AppNotifier extends ChangeNotifier {
.where((agent) => agent.id != agentId)
.toList();
sessionPreviews.removeAgent(machine.machine.machineId, agentId);
+ // An agent that no longer exists cannot be gone to.
+ doneNotices.unread.clear((
+ machineId: machine.machine.machineId,
+ agentId: agentId,
+ ));
machine.sessionAgentIds.removeWhere((_, id) => id == agentId);
machine.agentActivityAt.remove(agentId);
_cancelTurnActivity(machine.machine.machineId, agentId);
@@ -6981,6 +7009,7 @@ class AppNotifier extends ChangeNotifier {
// The answer just landed — the moment a recency sort should follow.
machine.agentActivityAt[agentId] = DateTime.now();
_cancelTurnActivity(machine.machine.machineId, agentId);
+ _announceTurnEnd(machine, agentId, event, payload);
} else {
final sessionId = _eventSessionId(event, payload);
if (sessionId != null) {
@@ -7040,6 +7069,44 @@ class AppNotifier extends ChangeNotifier {
Map<String, dynamic> event,
) => _handleEvent(machineId, event);
+ /// The agent on screen, when the app is in front of anybody.
+ AgentRef? get _watchedAgent {
+ if (!doneNotices.inFront) return null;
+ final pane = focusedPane;
+ final agentId = pane?.agentId;
+ if (pane == null || agentId == null) return null;
+ return (machineId: pane.machineId, agentId: agentId);
+ }
+
+ void _seeWatchedAgent() {
+ final watched = _watchedAgent;
+ if (watched != null) doneNotices.unread.clear(watched);
+ }
+
+ /// One agent's turn ended: tell the person as the dial would — see
+ /// `notify/done_notice.dart` for when that is a tap, a mark or a notice.
+ void _announceTurnEnd(
+ MachineState machine,
+ String agentId,
+ Map<String, dynamic> event,
+ Map<String, dynamic> payload,
+ ) {
+ final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
+ if (agent == null) return;
+ final ref = (machineId: machine.machine.machineId, agentId: agentId);
+ doneNotices.turnEnded(
+ (ref: ref, name: agent.displayName, machine: machine.machine.displayName),
+ turnEndFrom(
+ event,
+ payload,
+ reply: sessionPreviews
+ .read(previewKey(ref.machineId, agent))
+ ?.turnReply,
+ ),
+ watching: () => _watchedAgent == ref,
+ );
+ }
+
/// The app is back in front of somebody: every machine socket the phone lost while it was away
/// dials again now instead of waiting out a backoff nobody is watching.
///
@@ -7052,6 +7119,9 @@ class AppNotifier extends ChangeNotifier {
/// and connections somebody closed on purpose, so a tab switch that cost nothing costs nothing.
void handleAppResumed() {
_pool?.reconnectAll();
+ // Back in front of the agent that was on screen: whatever it finished
+ // while the phone was in a pocket has now been seen.
+ _seeWatchedAgent();
// ⚠️ **The desk is re-read here and not only on a push.** A backgrounded
// phone runs no code, so every `desk_changed` sent while it was away
// reached a socket nobody was listening on: without this the tabs would be
@@ -7093,6 +7163,7 @@ class AppNotifier extends ChangeNotifier {
}
unawaited(_spokenTasks.close());
sessionPreviews.dispose();
+ doneNotices.dispose();
_desk.dispose();
super.dispose();
}
diff --git a/mobile/lib/state/session_preview.dart b/mobile/lib/state/session_preview.dart
index b6447ce21..599ee24e5 100644
--- a/mobile/lib/state/session_preview.dart
+++ b/mobile/lib/state/session_preview.dart
@@ -21,6 +21,13 @@ class SessionPreview {
final List<String> requests = [];
final List<String> earlierResponses = [];
String? currentRequest, liveText, completedText, savedText, activity;
+
+ /// What the turn that just ENDED said — its last reply, or null when it said
+ /// nothing. The phone's stand-in for the dial's summary card: a turn with no
+ /// reply (tools only, a phantom session, an empty prompt) is not news, and
+ /// `notify/done_notice.dart` stays silent for it. Unlike [completedText] it
+ /// never carries over from an earlier turn.
+ String? turnReply;
String _streamText = '';
String? _searchText;
bool turnOpen = false,
@@ -255,6 +262,7 @@ class SessionPreviewStore extends ChangeNotifier {
entry.currentRequest = previewText(payload['userMessage'], limit: 1600);
entry._rememberRequest(entry.currentRequest);
entry.liveText = null;
+ entry.turnReply = null;
entry._streamText = '';
entry.activity = null;
case 'user_message':
@@ -286,6 +294,7 @@ class SessionPreviewStore extends ChangeNotifier {
case 'turn_ended':
entry.turnOpen = false;
entry.interrupted = payload['aborted'] == true;
+ entry.turnReply = entry.liveText;
if (entry.liveText != null) entry.completedText = entry.liveText;
entry.liveText = null;
entry.activity = null;
diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock
index 0385c6ae1..b8aed2d11 100644
--- a/mobile/pubspec.lock
+++ b/mobile/pubspec.lock
@@ -105,6 +105,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.8.2"
+ dbus:
+ dependency: transitive
+ description:
+ name: dbus
+ sha256: a48d5da28e89bd02196e80d81ed8d7954923d00a0f4a68cc20b575038f023383
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.7.15"
dio:
dependency: "direct main"
description:
@@ -198,6 +206,46 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.0.0"
+ flutter_local_notifications:
+ dependency: "direct main"
+ description:
+ name: flutter_local_notifications
+ sha256: "9375211fd7df9c070504ac4db7047c7fae857e238291433b770cfe696b5c357a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "22.2.0"
+ flutter_local_notifications_linux:
+ dependency: transitive
+ description:
+ name: flutter_local_notifications_linux
+ sha256: "9ca97e63776f29ab1b955725c09999fc2c150523269db150c39274f2a43c5a8b"
+ url: "https://pub.dev"
+ source: hosted
+ version: "8.0.1"
+ flutter_local_notifications_platform_interface:
+ dependency: transitive
+ description:
+ name: flutter_local_notifications_platform_interface
+ sha256: "945a438a4779f3aca3a948718d8a4048cbe9f9c8c797492c00abd5d39112bf37"
+ url: "https://pub.dev"
+ source: hosted
+ version: "12.1.0"
+ flutter_local_notifications_web:
+ dependency: transitive
+ description:
+ name: flutter_local_notifications_web
+ sha256: "516afaf97a2d1e67a036c6617321b00d205d72f7a67b6eccf936cd565f985878"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.0"
+ flutter_local_notifications_windows:
+ dependency: transitive
+ description:
+ name: flutter_local_notifications_windows
+ sha256: "6f43bdd03b171b7a90f22647506fea33e2bb12294b7c7c7a3d690e960a382945"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.1"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
@@ -520,6 +568,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.3.0"
+ petitparser:
+ dependency: transitive
+ description:
+ name: petitparser
+ sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.0.2"
platform:
dependency: transitive
description:
@@ -701,6 +757,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.7.12"
+ timezone:
+ dependency: transitive
+ description:
+ name: timezone
+ sha256: "981d1020d6ef8fe1e7b3de5054e5b25579ae7c403d7734adc508ffc47668e9cb"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.11.1"
typed_data:
dependency: transitive
description:
@@ -845,6 +909,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.0"
+ xml:
+ dependency: transitive
+ description:
+ name: xml
+ sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4"
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.0.1"
xterm:
dependency: "direct main"
description:
diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml
index 4f7292093..15535218f 100644
--- a/mobile/pubspec.yaml
+++ b/mobile/pubspec.yaml
@@ -68,6 +68,12 @@ dependencies:
# recognizer was tried first and misheard Vietnamese badly.
record: ^7.1.1
+ # An agent finishing while the phone is in a pocket: the OS notification the
+ # dial's "wake the panel and open the drawer" becomes on a phone
+ # (`lib/notify/system_notices.dart`). Local only — it fires from the machine socket,
+ # so it reaches a phone whose app is still alive, not one iOS has suspended.
+ flutter_local_notifications: ^22.2.0
+
dev_dependencies:
flutter_test:
sdk: flutter
diff --git a/mobile/test/notify/app_done_notice_test.dart b/mobile/test/notify/app_done_notice_test.dart
new file mode 100644
index 000000000..3cb08fbe3
--- /dev/null
+++ b/mobile/test/notify/app_done_notice_test.dart
@@ -0,0 +1,82 @@
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/state/app_state.dart';
+
+import '../agent_pager_fixture.dart';
+
+/// The dial's rule, end to end: frames off the machine socket into the marks
+/// the phone draws.
+void main() {
+ /// One whole turn of [agentId], as the machine streams it.
+ Future<void> turn(
+ AppNotifier app,
+ String agentId, {
+ String? reply = 'Fixed the login screen.',
+ Map<String, dynamic> end = const {},
+ Map<String, dynamic> endPayload = const {},
+ }) async {
+ Future<void> send(String type, [Map<String, dynamic> payload = const {}]) =>
+ app.handleEventForTest('m', {
+ 'type': type,
+ 'agentId': agentId,
+ ...(type == 'turn_ended' ? end : const {}),
+ 'payload': {...payload},
+ });
+ await send('turn_started', {'userMessage': 'fix it'});
+ if (reply != null) await send('text_delta', {'content': reply});
+ await send('turn_ended', endPayload);
+ }
+
+ bool unread(AppNotifier app, String agentId) =>
+ app.doneNotices.unread.contains((machineId: 'm', agentId: agentId));
+
+ late AppNotifier app;
+
+ setUp(() async {
+ app = pagerApp(PagerConn());
+ addTearDown(app.dispose);
+ await liveAgent(app, 'a');
+ });
+
+ test('an agent finishing elsewhere is marked', () async {
+ await turn(app, 'b');
+ expect(unread(app, 'b'), isTrue);
+ expect(app.doneNotices.unread.count, 1);
+ });
+
+ test('the agent on screen is never marked', () async {
+ await turn(app, 'a');
+ expect(unread(app, 'a'), isFalse);
+ });
+
+ test('what the dial stays quiet about, the phone does too', () async {
+ await turn(app, 'b', reply: null);
+ await turn(app, 'b', endPayload: {'aborted': true});
+ await turn(app, 'b', end: {'subagent': true});
+ await turn(app, 'b', end: {'replay': true});
+ expect(app.doneNotices.unread.count, 0);
+ });
+
+ test('a turn with nothing to say does not borrow the last one', () async {
+ await turn(app, 'b');
+ app.doneNotices.unread.clearAll();
+ await turn(app, 'b', reply: null);
+ expect(unread(app, 'b'), isFalse);
+ });
+
+ test('going to the agent reads its news', () async {
+ await turn(app, 'b');
+ await liveAgent(app, 'b');
+ expect(unread(app, 'b'), isFalse);
+ });
+
+ test('a deleted agent takes its mark with it', () async {
+ await turn(app, 'b');
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'agentId': 'b',
+ 'payload': <String, dynamic>{},
+ });
+ expect(unread(app, 'b'), isFalse);
+ });
+}
diff --git a/mobile/test/notify/done_announcer_test.dart b/mobile/test/notify/done_announcer_test.dart
new file mode 100644
index 000000000..c727685db
--- /dev/null
+++ b/mobile/test/notify/done_announcer_test.dart
@@ -0,0 +1,117 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/core/last_opened_agent.dart';
+import 'package:harness_mobile/notify/done_announcer.dart';
+import 'package:harness_mobile/notify/done_notice.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+
+class _RecordingNotices implements SystemNotices {
+ final shown = <DoneNoticeMessage>[];
+
+ @override
+ final opened = ValueNotifier<AgentRef?>(null);
+
+ @override
+ Future<void> requestPermission() async {}
+
+ @override
+ Future<void> show(DoneNoticeMessage message) async => shown.add(message);
+}
+
+void main() {
+ const ref = (machineId: 'm', agentId: 'a');
+ const agent = (ref: ref, name: 'Fix login', machine: 'MacBook');
+ const news = (
+ aborted: false,
+ replay: false,
+ subagent: false,
+ reply: 'Looked at the form.\n\nFixed the login screen and pushed.',
+ );
+
+ late _RecordingNotices system;
+ late int chimes;
+ late bool front;
+ late DoneAnnouncer announcer;
+
+ setUp(() {
+ system = _RecordingNotices();
+ chimes = 0;
+ front = true;
+ announcer = DoneAnnouncer(
+ system: system,
+ chime: () async => chimes++,
+ inFront: () => front,
+ );
+ addTearDown(announcer.dispose);
+ });
+
+ test('watching: a chime, no mark, no notice', () {
+ final notice = announcer.turnEnded(agent, news, watching: () => true);
+
+ expect(notice, DoneNotice.chime);
+ expect(chimes, 1);
+ expect(announcer.unread.count, 0);
+ expect(system.shown, isEmpty);
+ });
+
+ test('elsewhere in the app: a chime and a mark, no notice', () {
+ announcer.turnEnded(agent, news, watching: () => false);
+
+ expect(chimes, 1);
+ expect(announcer.unread.contains(ref), isTrue);
+ expect(system.shown, isEmpty);
+ });
+
+ test(
+ 'away: a mark and one notice naming the agent, its machine, its news',
+ () {
+ front = false;
+ announcer.turnEnded(agent, news, watching: () => true);
+
+ expect(chimes, 0, reason: 'nobody is holding a backgrounded app');
+ expect(announcer.unread.contains(ref), isTrue);
+ expect(system.shown, hasLength(1));
+ final shown = system.shown.single;
+ expect(shown.agent, ref);
+ expect(shown.title, 'Fix login');
+ expect(shown.machine, 'MacBook');
+ expect(shown.body, 'Fixed the login screen and pushed.');
+ },
+ );
+
+ test('a sub-agent turn does nothing at all, even away', () {
+ front = false;
+ announcer.turnEnded(agent, (
+ aborted: false,
+ replay: false,
+ subagent: true,
+ reply: 'x',
+ ), watching: () => false);
+
+ expect(chimes, 0);
+ expect(announcer.unread.count, 0);
+ expect(system.shown, isEmpty);
+ });
+
+ test('an agent is one mark however many turns it finished', () {
+ announcer.turnEnded(agent, news, watching: () => false);
+ announcer.turnEnded(agent, news, watching: () => false);
+
+ expect(announcer.unread.count, 1);
+ announcer.unread.clear(ref);
+ expect(announcer.unread.count, 0);
+ });
+
+ group('noticeBody', () {
+ test('keeps the last paragraph, on one line', () {
+ expect(noticeBody('a\n\nb c\nd'), 'b c d');
+ });
+
+ test('cuts a long reply with an ellipsis', () {
+ final body = noticeBody('x' * 400, limit: 20);
+ expect(body.length, 20);
+ expect(body.endsWith('…'), isTrue);
+ });
+ });
+}
diff --git a/mobile/test/notify/done_notice_test.dart b/mobile/test/notify/done_notice_test.dart
new file mode 100644
index 000000000..5e0716059
--- /dev/null
+++ b/mobile/test/notify/done_notice_test.dart
@@ -0,0 +1,71 @@
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/notify/done_notice.dart';
+
+/// The dial's rule for a finished turn — `firmware/main/cable_client.c`,
+/// `summary` — as the phone reads it off `turn_ended`.
+void main() {
+ TurnEnd end({
+ bool aborted = false,
+ bool replay = false,
+ bool subagent = false,
+ String? reply = 'Fixed the login screen.',
+ }) => (aborted: aborted, replay: replay, subagent: subagent, reply: reply);
+
+ DoneNotice decide(TurnEnd e, {bool inFront = true, bool watching = false}) =>
+ decideDoneNotice(e, inFront: inFront, watching: watching);
+
+ test('a turn that is not news is silent wherever the phone is', () {
+ for (final e in [
+ end(aborted: true),
+ end(replay: true),
+ end(subagent: true),
+ end(reply: null),
+ end(reply: ' \n '),
+ ]) {
+ for (final inFront in [true, false]) {
+ expect(decide(e, inFront: inFront), DoneNotice.none, reason: '$e');
+ }
+ }
+ });
+
+ test('watching the agent: the chime still comes, nothing is filed', () {
+ final notice = decide(end(), watching: true);
+ expect(notice, DoneNotice.chime);
+ expect(notice.marks, isFalse);
+ expect(notice.alerts, isFalse);
+ });
+
+ test('in front on another agent: a mark, never a notice', () {
+ final notice = decide(end());
+ expect(notice, DoneNotice.mark);
+ expect(notice.chimes, isTrue);
+ expect(notice.alerts, isFalse);
+ });
+
+ test('away: marked and noticed, whatever was on screen', () {
+ for (final watching in [true, false]) {
+ final notice = decide(end(), inFront: false, watching: watching);
+ expect(notice, DoneNotice.alert);
+ expect(notice.marks, isTrue);
+ }
+ });
+
+ test('an older daemon says none of the flags, and every end is news', () {
+ final e = turnEndFrom(
+ {'type': 'turn_ended', 'agentId': 'a'},
+ <String, dynamic>{},
+ reply: 'done',
+ );
+ expect(e, (aborted: false, replay: false, subagent: false, reply: 'done'));
+ });
+
+ test('the flags are read where the daemon puts them', () {
+ final e = turnEndFrom(
+ {'type': 'turn_ended', 'replay': true, 'subagent': true},
+ {'aborted': true},
+ reply: null,
+ );
+ expect(e, (aborted: true, replay: true, subagent: true, reply: null));
+ });
+}
diff --git a/mobile/test/notify/system_notices_test.dart b/mobile/test/notify/system_notices_test.dart
new file mode 100644
index 000000000..2e3f8cfcd
--- /dev/null
+++ b/mobile/test/notify/system_notices_test.dart
@@ -0,0 +1,27 @@
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/notify/system_notices.dart';
+
+void main() {
+ const ref = (machineId: 'machine-1', agentId: 'agent-7');
+
+ test('a tapped notice leads back to the agent it was about', () {
+ expect(decodeAgentPayload(encodeAgentPayload(ref)), ref);
+ });
+
+ test('a payload that is not ours opens nothing', () {
+ for (final payload in [null, '', 'one-part', 'a\nb\nc', '\nagent']) {
+ expect(decodeAgentPayload(payload), isNull, reason: '$payload');
+ }
+ });
+
+ test('one id per agent, stable and positive', () {
+ final id = noticeIdFor(ref);
+ expect(noticeIdFor(ref), id);
+ expect(id, greaterThanOrEqualTo(0));
+ expect(
+ noticeIdFor((machineId: 'machine-1', agentId: 'agent-8')),
+ isNot(id),
+ );
+ });
+}