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.

desktop: agent alerts reach you outside the window as system notifications (#264) (#346)

0xken15cbb01a0c58ed
diff --git a/desktop/lib/core/startup.dart b/desktop/lib/core/startup.dart
index f2a3163a8..352cf9fdd 100644
--- a/desktop/lib/core/startup.dart
+++ b/desktop/lib/core/startup.dart
@@ -3,6 +3,7 @@ import '../stats/harness_stats.dart';
import '../terminal/terminal_font_store.dart';
import '../terminal/terminal_theme_store.dart';
import '../notify/alert_sounds.dart';
+import '../notify/system_notifications.dart';
/// Every preference that has to be in place BEFORE the first frame.
///
@@ -23,6 +24,7 @@ Future<void> loadPersistedSettings({
HarnessStats? stats,
AlertSoundStore? alertSounds,
ScreenAlertStore? screenAlerts,
+ DesktopNotificationStore? desktopNotifications,
}) async {
// Independent stores may load together, but all must finish before runApp.
// Font and appearance share a serialized file store; each reads its related
@@ -43,5 +45,6 @@ Future<void> loadPersistedSettings({
// noise, and a late read would let one through on the default while the person had it off.
(alertSounds ?? alertSoundStore).load(),
(screenAlerts ?? screenAlertStore).load(),
+ (desktopNotifications ?? desktopNotificationStore).load(),
]);
}
diff --git a/desktop/lib/notify/alert_sounds.dart b/desktop/lib/notify/alert_sounds.dart
index 9a4436476..1df0e3ca6 100644
--- a/desktop/lib/notify/alert_sounds.dart
+++ b/desktop/lib/notify/alert_sounds.dart
@@ -26,26 +26,21 @@ enum AlertKind {
final String sound;
}
-/// Whether this computer plays a sound when an agent finishes or gets stuck.
+/// An on/off preference kept in the app's own store.
///
-/// OFF by default. An app that makes a noise nobody asked for is a bad guest,
-/// and a swarm is many agents: the first thing a new user would hear is a
-/// sound they did not choose, from a window they may not be looking at. It is
-/// one switch away in Settings ▸ Notifications for anybody who wants it.
-class AlertSoundStore extends ValueNotifier<bool> {
- AlertSoundStore({LocalKeyValueStore? storage})
+/// OFF by default, and only the exact string `on` switches it on — a truncated
+/// or hand-edited file lands on the default, so a damaged store cannot start
+/// interrupting somebody who never asked. Every alert switch follows that rule,
+/// so it is written once.
+abstract class OnOffPreference extends ValueNotifier<bool> {
+ OnOffPreference(this._key, {LocalKeyValueStore? storage})
: _storage = storage ?? HarnessFileStore.shared,
super(false);
- static const _key = 'app_alert_sounds';
-
+ final String _key;
final LocalKeyValueStore _storage;
Future<void>? _save;
- /// Read the saved choice. Tolerant: a missing or hand-edited value lands on
- /// the default rather than throwing, the same rule the appearance store
- /// follows. Only the exact string `on` switches it on, so a truncated file
- /// cannot start making noises nobody asked for.
Future<void> load() async {
try {
value = (await _storage.read(_key)) == 'on';
@@ -67,41 +62,23 @@ class AlertSoundStore extends ValueNotifier<bool> {
}
}
+/// Whether this computer plays a sound when an agent finishes or gets stuck.
+///
+/// OFF by default. An app that makes a noise nobody asked for is a bad guest,
+/// and a swarm is many agents: the first thing a new user would hear is a
+/// sound they did not choose, from a window they may not be looking at. It is
+/// one switch away in Settings ▸ Notifications for anybody who wants it.
+class AlertSoundStore extends OnOffPreference {
+ AlertSoundStore({super.storage}) : super('app_alert_sounds');
+}
+
/// Whether a banner appears in the window when an agent finishes or gets stuck.
///
/// OFF by default, like the sound. Both are interruptions, and an app that
/// interrupts without being asked is a bad guest whichever sense it reaches
/// for. One switch each in Settings ▸ Notifications.
-class ScreenAlertStore extends ValueNotifier<bool> {
- ScreenAlertStore({LocalKeyValueStore? storage})
- : _storage = storage ?? HarnessFileStore.shared,
- super(false);
-
- static const _key = 'app_screen_alerts';
-
- final LocalKeyValueStore _storage;
- Future<void>? _save;
-
- /// Only the exact string `on` switches it on — a truncated or hand-edited
- /// file lands on the default, so a damaged store cannot start interrupting
- /// somebody who never asked. The same rule [AlertSoundStore] follows.
- Future<void> load() async {
- try {
- value = (await _storage.read(_key)) == 'on';
- } catch (_) {
- value = false;
- }
- }
-
- Future<void> set(bool on) {
- if (value == on) return _save ?? Future.value();
- value = on;
- final pending = (_save ?? Future.value()).then(
- (_) => _storage.write(_key, on ? 'on' : 'off'),
- );
- _save = pending;
- return pending;
- }
+class ScreenAlertStore extends OnOffPreference {
+ ScreenAlertStore({super.storage}) : super('app_screen_alerts');
}
/// The stores the app reads, loaded at start-up beside the other preferences.
diff --git a/desktop/lib/notify/system_notifications.dart b/desktop/lib/notify/system_notifications.dart
new file mode 100644
index 000000000..bd8ccb25e
--- /dev/null
+++ b/desktop/lib/notify/system_notifications.dart
@@ -0,0 +1,364 @@
+library;
+
+import 'dart:async';
+import 'dart:io' show Platform, Process, ProcessException, ProcessResult;
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+
+import 'agent_alerts.dart';
+import 'alert_sounds.dart';
+
+/// Whether an agent's news is ALSO handed to the operating system, so it reaches
+/// somebody whose window is behind their editor, on another desktop, or minimised.
+///
+/// OFF by default, like the banner and the sound: all three are interruptions.
+/// Turning it on is also the moment macOS asks for permission — an app that asks
+/// before anybody wanted it to say anything is a bad guest.
+class DesktopNotificationStore extends OnOffPreference {
+ DesktopNotificationStore({super.storage})
+ : super('app_desktop_notifications');
+}
+
+/// What the operating system said about posting notifications.
+enum NotificationPermission {
+ /// Nobody has asked yet, or the answer is not known.
+ unknown,
+ granted,
+
+ /// The person said no, or turned Harness off in the system's own settings.
+ /// Only they can change it, and only there.
+ denied,
+
+ /// This build or this computer cannot post at all: an ad-hoc-signed dev build
+ /// on macOS, a Linux desktop without `notify-send`.
+ unavailable;
+
+ static NotificationPermission parse(Object? value) => switch (value) {
+ 'granted' => granted,
+ 'denied' => denied,
+ 'unavailable' => unavailable,
+ _ => unknown,
+ };
+}
+
+/// The operating-system half: what actually puts a notification on screen.
+///
+/// Every call is best-effort. A platform that cannot post answers [unavailable]
+/// or does nothing; it never throws into the event dispatcher that carried the news.
+abstract class SystemNotifier {
+ /// Whether this platform has a notifier at all. The Settings row is not shown
+ /// where it would be a switch connected to nothing.
+ bool get supported;
+
+ /// Whether clicking a notification opens its agent. Settings only promises
+ /// what the platform does.
+ bool get clickOpensAgent;
+
+ /// Ask for permission if it has not been asked, and say what the answer is.
+ Future<NotificationPermission> authorize();
+
+ /// Post, or replace the one already posted under [id].
+ Future<NotificationPermission> show({
+ required String id,
+ required String title,
+ required String body,
+ required String machineId,
+ required String agentId,
+ });
+
+ /// Take down the one posted under [id], if it is still there.
+ Future<void> withdraw(String id);
+
+ /// Called with the agent a person clicked a notification for.
+ set onTap(void Function(String machineId, String agentId)? handler);
+}
+
+/// No system notifications — Windows, tests, and anything else.
+class NoSystemNotifier implements SystemNotifier {
+ const NoSystemNotifier();
+
+ @override
+ bool get supported => false;
+
+ @override
+ bool get clickOpensAgent => false;
+
+ @override
+ Future<NotificationPermission> authorize() async =>
+ NotificationPermission.unavailable;
+
+ @override
+ Future<NotificationPermission> show({
+ required String id,
+ required String title,
+ required String body,
+ required String machineId,
+ required String agentId,
+ }) async => NotificationPermission.unavailable;
+
+ @override
+ Future<void> withdraw(String id) async {}
+
+ @override
+ set onTap(void Function(String machineId, String agentId)? handler) {}
+}
+
+/// macOS: `UNUserNotificationCenter`, in `HarnessNotifications.swift`.
+///
+/// Works for the signed and notarized build people install. A local
+/// `flutter run` build is ad-hoc signed, and there the centre refuses with an
+/// error — which comes back as [NotificationPermission.unavailable], and the
+/// banner keeps doing the job.
+class MacSystemNotifier implements SystemNotifier {
+ MacSystemNotifier({MethodChannel? channel})
+ : _channel = channel ?? const MethodChannel('harness/notifications');
+
+ final MethodChannel _channel;
+
+ @override
+ bool get supported => true;
+
+ @override
+ bool get clickOpensAgent => true;
+
+ @override
+ Future<NotificationPermission> authorize() => _ask('authorize', null);
+
+ @override
+ Future<NotificationPermission> show({
+ required String id,
+ required String title,
+ required String body,
+ required String machineId,
+ required String agentId,
+ }) => _ask('show', {
+ 'id': id,
+ 'title': title,
+ 'body': body,
+ 'machineId': machineId,
+ 'agentId': agentId,
+ });
+
+ @override
+ Future<void> withdraw(String id) async {
+ try {
+ await _channel.invokeMethod<void>('withdraw', {'id': id});
+ } catch (_) {}
+ }
+
+ @override
+ set onTap(void Function(String machineId, String agentId)? handler) {
+ _channel.setMethodCallHandler(
+ handler == null
+ ? null
+ : (call) async {
+ if (call.method != 'tapped') return;
+ final args = call.arguments;
+ if (args is! Map) return;
+ final machineId = args['machineId'];
+ final agentId = args['agentId'];
+ if (machineId is String &&
+ machineId.isNotEmpty &&
+ agentId is String &&
+ agentId.isNotEmpty) {
+ handler(machineId, agentId);
+ }
+ },
+ );
+ }
+
+ Future<NotificationPermission> _ask(String method, Object? args) async {
+ try {
+ return NotificationPermission.parse(
+ await _channel.invokeMethod<String>(method, args),
+ );
+ } on MissingPluginException {
+ return NotificationPermission.unavailable;
+ } catch (_) {
+ return NotificationPermission.unknown;
+ }
+ }
+}
+
+/// Runs a command and hands back its result. Injected so a test can see what
+/// would have been run without a notification daemon.
+typedef ProcessRunner = Future<ProcessResult> Function(
+ String executable,
+ List<String> arguments,
+);
+
+/// Linux: `notify-send`, which talks to whatever notification daemon the
+/// desktop already runs. No native dependency, and no click action — the tool
+/// has none, so a click does what the desktop's own default is.
+class LinuxSystemNotifier implements SystemNotifier {
+ LinuxSystemNotifier({ProcessRunner? run}) : _run = run ?? Process.run;
+
+ final ProcessRunner _run;
+
+ /// The daemon's id for each agent's notification, so the next one REPLACES it
+ /// (`--replace-id`) rather than stacking — the banner's rule.
+ final _ids = <String, String>{};
+
+ /// Whether this `notify-send` knows `--print-id`/`--replace-id` (libnotify
+ /// 0.7.9 and later). An older one refuses the flags; it is asked once, and
+ /// every notification after that is posted plainly.
+ bool _canReplace = true;
+
+ @override
+ bool get supported => true;
+
+ @override
+ bool get clickOpensAgent => false;
+
+ @override
+ Future<NotificationPermission> authorize() async {
+ try {
+ final result = await _run('notify-send', ['--version']);
+ return result.exitCode == 0
+ ? NotificationPermission.granted
+ : NotificationPermission.unavailable;
+ } on ProcessException {
+ return NotificationPermission.unavailable;
+ }
+ }
+
+ @override
+ Future<NotificationPermission> show({
+ required String id,
+ required String title,
+ required String body,
+ required String machineId,
+ required String agentId,
+ }) async {
+ List<String> args({required bool replace}) => [
+ '--app-name=Harness',
+ if (replace) '--print-id',
+ if (replace && _ids[id] != null) '--replace-id=${_ids[id]}',
+ // `--` so an agent called "-u critical" is a title and not a flag.
+ '--',
+ title,
+ body,
+ ];
+ try {
+ if (_canReplace) {
+ final result = await _run('notify-send', args(replace: true));
+ if (result.exitCode == 0) {
+ final printed = '${result.stdout}'.trim();
+ if (int.tryParse(printed) != null) _ids[id] = printed;
+ return NotificationPermission.granted;
+ }
+ // Only a notify-send that does not KNOW the flags gives them up. Any
+ // other failure is the daemon, and the next alert should still replace.
+ if ('${result.stderr}'.toLowerCase().contains('unknown option')) {
+ _canReplace = false;
+ }
+ }
+ final result = await _run('notify-send', args(replace: false));
+ // A failure here is the desktop's daemon, not a missing tool — one that
+ // is restarting, or not up yet at login. Unknown, so the next alert tries
+ // again rather than the channel going dark for the rest of the session.
+ return result.exitCode == 0
+ ? NotificationPermission.granted
+ : NotificationPermission.unknown;
+ } on ProcessException {
+ return NotificationPermission.unavailable;
+ }
+ }
+
+ /// `notify-send` cannot close a notification. The desktop's daemon expires it.
+ @override
+ Future<void> withdraw(String id) async => _ids.remove(id);
+
+ @override
+ set onTap(void Function(String machineId, String agentId)? handler) {}
+}
+
+/// The notifier for the platform this build runs on.
+SystemNotifier platformSystemNotifier() {
+ if (kIsWeb) return const NoSystemNotifier();
+ if (Platform.isMacOS) return MacSystemNotifier();
+ if (Platform.isLinux) return LinuxSystemNotifier();
+ return const NoSystemNotifier();
+}
+
+/// The third channel beside the banner and the sound: news the operating system
+/// delivers, so it survives the window being somewhere else.
+///
+/// Decides whether to post — the switch, and what the platform last said — and
+/// leaves HOW to the [SystemNotifier]. It does not decide WHEN: the caller posts
+/// only while the window is not in front, because in front of the window the
+/// banner already says it.
+class SystemNotifications {
+ SystemNotifications({
+ DesktopNotificationStore? store,
+ SystemNotifier? notifier,
+ }) : store = store ?? desktopNotificationStore,
+ notifier = notifier ?? platformSystemNotifier();
+
+ final DesktopNotificationStore store;
+ final SystemNotifier notifier;
+
+ /// What the platform last answered. Settings reads it to explain a switch that
+ /// is on but cannot do anything.
+ final permission = ValueNotifier(NotificationPermission.unknown);
+
+ bool get supported => notifier.supported;
+
+ /// One notification per AGENT, as for banners: a busy agent replaces its own
+ /// last message instead of stacking a column of them in Notification Center.
+ static String idFor(String machineId, String agentId) =>
+ 'harness-agent:$machineId/$agentId';
+
+ /// Turn the channel on or off, asking the platform for permission on the way on.
+ Future<void> setEnabled(bool on) async {
+ await store.set(on);
+ if (on) permission.value = await notifier.authorize();
+ }
+
+ /// Hand [alert] to the operating system. Silent when the switch is off, and
+ /// when this build or computer cannot post at all.
+ ///
+ /// A DENIAL is not remembered the same way: the person can allow Harness in
+ /// the system's settings at any moment, and the next alert has to find that
+ /// out without a restart. Asking a denied app costs no prompt — the system
+ /// answers from what the person chose.
+ ///
+ /// Never throws and never makes the caller wait.
+ void post(AgentAlert alert) {
+ if (!store.value || !supported) return;
+ if (permission.value == NotificationPermission.unavailable) return;
+ unawaited(
+ notifier
+ .show(
+ id: idFor(alert.machineId, alert.agentId),
+ title: alert.title,
+ body: alert.sentence,
+ machineId: alert.machineId,
+ agentId: alert.agentId,
+ )
+ .then((answer) {
+ if (answer != NotificationPermission.unknown) {
+ permission.value = answer;
+ }
+ })
+ .catchError((_) {}),
+ );
+ }
+
+ /// The person got to this agent some other way. Its notification is old news.
+ void withdraw(String machineId, String agentId) {
+ if (!supported) return;
+ unawaited(notifier.withdraw(idFor(machineId, agentId)).catchError((_) {}));
+ }
+
+ /// Where a click on a notification goes. Null stops listening.
+ set onTap(void Function(String machineId, String agentId)? handler) =>
+ notifier.onTap = handler;
+}
+
+/// The store the app reads, loaded at start-up beside the other preferences.
+final desktopNotificationStore = DesktopNotificationStore();
+
+/// The app's one channel to the operating system's notifications.
+final systemNotifications = SystemNotifications();
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 4de32e050..adefe78b8 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -305,6 +305,18 @@ class _SwarmScreenState extends State<SwarmScreen> {
onStateChange: app.appLifecycleChanged,
);
app.appLifecycleChanged(WidgetsBinding.instance.lifecycleState);
+ // A click on a system notification does what a click on its banner does,
+ // from wherever the window was: bring it forward, then open that agent.
+ app.systemNotifications.onTap = (machineId, agentId) async {
+ await revealWindow();
+ if (!mounted) return;
+ try {
+ await app.revealAgentFromAlert(machineId, agentId);
+ } catch (_) {
+ // An agent deleted since, or a machine this window no longer reaches.
+ // The window came forward, which is most of what a click asked for.
+ }
+ };
app.addListener(_syncToolbarNotices);
_toolbarNotices.addListener(_toolbarNoticesChanged);
_onboarding.addListener(_onboardingChanged);
@@ -427,6 +439,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_commandFocus.dispose();
if (_hasCommandBar) _commandBar.dispose();
unawaited(_spokenTasks?.cancel());
+ app.systemNotifications.onTap = null;
if (_native) {
unawaited(_channel.invokeMethod<void>('machinesState', {'machines': []}));
app.removeListener(_syncNative);
diff --git a/desktop/lib/settings/sections/alerts_card.dart b/desktop/lib/settings/sections/alerts_card.dart
index eaf62ad83..cfa84a6b9 100644
--- a/desktop/lib/settings/sections/alerts_card.dart
+++ b/desktop/lib/settings/sections/alerts_card.dart
@@ -5,28 +5,37 @@ import 'dart:async';
import 'package:flutter/material.dart';
import '../../notify/alert_sounds.dart';
+import '../../notify/system_notifications.dart';
import '../../shared/theme/app_theme.dart' as grid;
import '../../shared/widgets/setting_row.dart';
/// Settings ▸ Notifications: how an agent gets your attention.
///
-/// Two switches, because there are two CHANNELS and people differ about them —
-/// a banner is welcome in a quiet office where a sound is not. "Finished" and
+/// One switch per CHANNEL, because people differ about them — a banner is
+/// welcome in a quiet office where a sound is not, and a notification from the
+/// system reaches somebody the window cannot. "Finished" and
/// "needs you" are not split the same way: those are two triggers of one thing,
/// and somebody who wants to know about a stuck agent wants to know about a
/// finished one.
class AlertsCard extends StatelessWidget {
- const AlertsCard({super.key, this.store, this.screenStore});
+ const AlertsCard({
+ super.key,
+ this.store,
+ this.screenStore,
+ this.notifications,
+ });
/// Injected by tests; the app reads the ones the window loaded at start-up.
final AlertSoundStore? store;
final ScreenAlertStore? screenStore;
+ final SystemNotifications? notifications;
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
final sound = store ?? alertSoundStore;
final screen = screenStore ?? screenAlertStore;
+ final system = notifications ?? systemNotifications;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -63,7 +72,53 @@ class AlertsCard extends StatelessWidget {
),
),
),
+ // Only where there is a notifier to switch: a row on Windows would be a
+ // switch connected to nothing.
+ if (system.supported) ...[
+ const SizedBox(height: 10),
+ ListenableBuilder(
+ listenable: Listenable.merge([system.store, system.permission]),
+ builder: (context, _) => SettingRow(
+ title: 'Desktop notifications',
+ detail: _systemDetail(
+ clickOpensAgent: system.notifier.clickOpensAgent,
+ on: system.store.value,
+ permission: system.permission.value,
+ ),
+ control: Align(
+ alignment: Alignment.centerLeft,
+ child: Switch(
+ key: const Key('settings-desktop-notifications'),
+ value: system.store.value,
+ onChanged: (next) => unawaited(system.setEnabled(next)),
+ ),
+ ),
+ ),
+ ),
+ ],
],
);
}
}
+
+/// What the notifications row says under its title. A switch that is on and
+/// can do nothing has to say why, or it reads as broken.
+String _systemDetail({
+ required bool clickOpensAgent,
+ required bool on,
+ required NotificationPermission permission,
+}) {
+ final base =
+ 'Let the system tell you at the same two moments while Harness is not '
+ 'in front.${clickOpensAgent ? ' Click one to go to that agent.' : ''}';
+ if (!on) return base;
+ return switch (permission) {
+ NotificationPermission.denied =>
+ 'Harness is not allowed to post notifications. Allow it in System '
+ 'Settings ▸ Notifications ▸ Harness.',
+ NotificationPermission.unavailable =>
+ 'Notifications cannot be posted from this build or this computer. The '
+ 'on-screen banner still works.',
+ _ => base,
+ };
+}
diff --git a/desktop/lib/settings/sections/notifications_section.dart b/desktop/lib/settings/sections/notifications_section.dart
index c887d45f4..3724f253d 100644
--- a/desktop/lib/settings/sections/notifications_section.dart
+++ b/desktop/lib/settings/sections/notifications_section.dart
@@ -13,9 +13,10 @@ import 'alerts_card.dart';
/// is not a look — somebody who wants to silence one does not go looking under
/// Appearance for it, which is exactly how it went the first time.
///
-/// One switch today. The row exists because this is where the next ones belong
-/// — a desktop notification, a single agent muted, a choice of sound — and each
-/// of those would otherwise find the same wrong home for the same reason.
+/// A switch per channel — banner, sound, and the system's own notifications.
+/// The next ones belong here too — a single agent muted, a choice of sound —
+/// and each of those would otherwise find the same wrong home for the same
+/// reason.
class NotificationsSection extends StatelessWidget {
const NotificationsSection({super.key});
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index bf234cc88..80fcb95d1 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -75,6 +75,8 @@ import '../usage/usage_accounts.dart';
import '../orchestrator/orchestrator_controller.dart';
import '../notify/agent_alerts.dart';
import '../notify/alert_sounds.dart';
+import '../notify/system_notifications.dart';
+import '../notify/system_notifications.dart' as notify_system;
enum AppStatus {
bootstrapping,
@@ -485,6 +487,10 @@ class AppNotifier extends ChangeNotifier {
/// a banner appearing does not rebuild the workspace.
final AgentAlerts agentAlerts;
+ /// And what it hands the operating system, for when the window is not in
+ /// front and neither the banner nor the badge can be seen.
+ final SystemNotifications systemNotifications;
+
/// Which agents have news nobody has looked at. Marked on the same two
/// moments and NOT behind the banner or sound switches — see [AgentUnread].
final AgentUnread agentUnread;
@@ -1692,8 +1698,11 @@ class AppNotifier extends ChangeNotifier {
AlertSounds? alerts,
AgentAlerts? agentAlerts,
AgentUnread? agentUnread,
+ SystemNotifications? systemNotifications,
}) : alerts = alerts ?? AlertSounds(store: alertSoundStore),
agentAlerts = agentAlerts ?? AgentAlerts(),
+ systemNotifications =
+ systemNotifications ?? notify_system.systemNotifications,
agentUnread = agentUnread ?? AgentUnread(),
_paneLayout = paneLayoutStore,
// Remembers "a dial has been seen here" on the same terms the pane
@@ -6569,6 +6578,9 @@ class AppNotifier extends ChangeNotifier {
void _forgetUnread(String machineId, String agentId) {
if (agentUnread.kindFor(machineId, agentId) == null) return;
agentUnread.clear(machineId, agentId);
+ // Notification Center would otherwise keep saying "Finished" about an agent
+ // the person has already gone and looked at.
+ systemNotifications.withdraw(machineId, agentId);
_announceAgentSeen(machineId, agentId);
}
@@ -6643,19 +6655,25 @@ class AppNotifier extends ChangeNotifier {
// still say when somebody has turned the interrupting halves off.
agentUnread.mark(machine.machine.machineId, agentId, kind);
alerts.play(kind);
- agentAlerts.post(
- AgentAlert(
- machineId: machine.machine.machineId,
- agentId: agentId,
- // The agent's own name, and its id only when it has none — a banner
- // naming a uuid tells nobody which pane to look at.
- title: (agent?.name.trim().isNotEmpty ?? false)
- ? agent!.name.trim()
- : agentId,
- kind: kind,
- at: DateTime.now(),
- ),
+ final alert = AgentAlert(
+ machineId: machine.machine.machineId,
+ agentId: agentId,
+ // The agent's own name, and its id only when it has none — a banner
+ // naming a uuid tells nobody which pane to look at.
+ title: (agent?.name.trim().isNotEmpty ?? false)
+ ? agent!.name.trim()
+ : agentId,
+ kind: kind,
+ at: DateTime.now(),
);
+ agentAlerts.post(alert);
+ // The operating system only while the window is NOT in front. In front of
+ // it the banner already says this, and a second notice in the corner of the
+ // screen for the window you are looking at is the same news twice. Unknown
+ // counts as not in front, for the reason [lifecycle] gives.
+ if (lifecycle() != AppLifecycleState.resumed) {
+ systemNotifications.post(alert);
+ }
}
/// What clicking a banner does: show that agent, wherever it is.
@@ -6666,6 +6684,7 @@ class AppNotifier extends ChangeNotifier {
/// same order [placeFork] uses for the same reason.
Future<void> revealAgentFromAlert(String machineId, String agentId) async {
markAgentSeen(machineId, agentId);
+ systemNotifications.withdraw(machineId, agentId);
agentAlerts.dismiss(
AgentAlert(
machineId: machineId,
diff --git a/desktop/macos/Runner.xcodeproj/project.pbxproj b/desktop/macos/Runner.xcodeproj/project.pbxproj
index 16a5d6df9..476420bb7 100644
--- a/desktop/macos/Runner.xcodeproj/project.pbxproj
+++ b/desktop/macos/Runner.xcodeproj/project.pbxproj
@@ -23,6 +23,7 @@
/* Begin PBXBuildFile section */
B20100000000000000000001 /* SwarmTitlebar.swift in Sources */ = {isa = PBXBuildFile; fileRef = B20100000000000000000002 /* SwarmTitlebar.swift */; };
B20100000000000000000003 /* HarnessKeymap.swift in Sources */ = {isa = PBXBuildFile; fileRef = B20100000000000000000004 /* HarnessKeymap.swift */; };
+ B20100000000000000000A01 /* HarnessNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = B20100000000000000000A02 /* HarnessNotifications.swift */; };
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
@@ -66,6 +67,7 @@
/* Begin PBXFileReference section */
B20100000000000000000002 /* SwarmTitlebar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwarmTitlebar.swift; sourceTree = "<group>"; };
B20100000000000000000004 /* HarnessKeymap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HarnessKeymap.swift; sourceTree = "<group>"; };
+ B20100000000000000000A02 /* HarnessNotifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HarnessNotifications.swift; sourceTree = "<group>"; };
331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
@@ -177,6 +179,7 @@
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
B20100000000000000000002 /* SwarmTitlebar.swift */,
B20100000000000000000004 /* HarnessKeymap.swift */,
+ B20100000000000000000A02 /* HarnessNotifications.swift */,
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
33E51914231749380026EE4D /* Release.entitlements */,
33CC11242044D66E0003C045 /* Resources */,
@@ -367,6 +370,7 @@
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
B20100000000000000000001 /* SwarmTitlebar.swift in Sources */,
B20100000000000000000003 /* HarnessKeymap.swift in Sources */,
+ B20100000000000000000A01 /* HarnessNotifications.swift in Sources */,
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
);
diff --git a/desktop/macos/Runner/HarnessNotifications.swift b/desktop/macos/Runner/HarnessNotifications.swift
new file mode 100644
index 000000000..9dd7d47f2
--- /dev/null
+++ b/desktop/macos/Runner/HarnessNotifications.swift
@@ -0,0 +1,132 @@
+import Cocoa
+import FlutterMacOS
+import UserNotifications
+
+/// An agent's news, handed to macOS so it reaches somebody whose window is elsewhere.
+///
+/// Dart decides WHETHER and WHEN (`lib/notify/system_notifications.dart`): only with the switch on,
+/// and only while the window is not in front. This side only posts, replaces, withdraws, and reports
+/// a click back.
+///
+/// Answers are strings Dart parses — `granted`, `denied`, `unavailable`. `unavailable` is what an
+/// ad-hoc-signed `flutter run` build gets: the centre refuses an app with no team identifier with an
+/// error rather than a prompt. The signed and notarized release is not refused.
+final class HarnessNotifications: NSObject, UNUserNotificationCenterDelegate {
+ private let channel: FlutterMethodChannel
+
+ init(messenger: FlutterBinaryMessenger) {
+ channel = FlutterMethodChannel(name: "harness/notifications", binaryMessenger: messenger)
+ super.init()
+ // Set here, at window creation, so a click on a notification is heard as early as this app can
+ // hear one. A click that LAUNCHES Harness only opens it: nothing here is ready to open an agent
+ // before sign-in and the machines have answered.
+ UNUserNotificationCenter.current().delegate = self
+ channel.setMethodCallHandler { [weak self] call, result in
+ guard let self else { result(nil); return }
+ switch call.method {
+ case "authorize":
+ self.authorize { result($0) }
+ case "show":
+ guard let args = call.arguments as? [String: Any],
+ let id = args["id"] as? String,
+ let title = args["title"] as? String,
+ let body = args["body"] as? String else {
+ result(FlutterError(code: "INVALID_NOTIFICATION", message: "Missing id, title or body", details: nil))
+ return
+ }
+ self.show(id: id, title: title, body: body,
+ machineId: args["machineId"] as? String ?? "",
+ agentId: args["agentId"] as? String ?? "") { result($0) }
+ case "withdraw":
+ if let id = (call.arguments as? [String: Any])?["id"] as? String {
+ let center = UNUserNotificationCenter.current()
+ center.removeDeliveredNotifications(withIdentifiers: [id])
+ center.removePendingNotificationRequests(withIdentifiers: [id])
+ }
+ result(nil)
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
+ }
+
+ /// Ask once; after that the system answers from what the person chose, without a prompt.
+ ///
+ /// `.alert` only. The sound is its own switch and its own channel (`playAlert`), and a notification
+ /// that also chimed would make one event two noises for somebody who has both on.
+ private func authorize(_ done: @escaping (String) -> Void) {
+ let center = UNUserNotificationCenter.current()
+ center.requestAuthorization(options: [.alert]) { granted, error in
+ if granted {
+ DispatchQueue.main.async { done("granted") }
+ return
+ }
+ // An error does not by itself mean this build cannot post: macOS answers a person's "no" with
+ // one too. What the settings say after asking is what tells them apart — a person who said no
+ // is `.denied`; a build the centre will not deal with at all is still `.notDetermined`.
+ center.getNotificationSettings { settings in
+ let answer: String
+ switch settings.authorizationStatus {
+ case .authorized, .provisional: answer = "granted"
+ case .denied: answer = "denied"
+ default: answer = error != nil ? "unavailable" : "denied"
+ }
+ DispatchQueue.main.async { done(answer) }
+ }
+ }
+ }
+
+ private func show(id: String, title: String, body: String, machineId: String, agentId: String,
+ _ done: @escaping (String) -> Void) {
+ let center = UNUserNotificationCenter.current()
+ center.getNotificationSettings { settings in
+ let post = {
+ let content = UNMutableNotificationContent()
+ content.title = title
+ content.body = body
+ content.userInfo = ["machineId": machineId, "agentId": agentId]
+ // The same identifier REPLACES what is already delivered, which is what keeps a busy agent
+ // to one entry in Notification Center rather than a column of them.
+ center.add(UNNotificationRequest(identifier: id, content: content, trigger: nil)) { error in
+ // A failed add is this one notification, not the channel: "unknown" keeps the next alert trying.
+ DispatchQueue.main.async { done(error == nil ? "granted" : "unknown") }
+ }
+ }
+ switch settings.authorizationStatus {
+ case .authorized, .provisional:
+ post()
+ case .notDetermined:
+ // The switch was on before this Mac was ever asked (a restored preference). Ask now, at the
+ // first thing there is to say.
+ self.authorize { answer in
+ if answer == "granted" { post() } else { done(answer) }
+ }
+ default:
+ DispatchQueue.main.async { done("denied") }
+ }
+ }
+ }
+
+ /// Shown even though Harness is the active app. Dart already decided the window is not in front —
+ /// it can be active and still out of sight, on another Space or covered — and returning nothing
+ /// here would drop the notification with no trace anywhere.
+ func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
+ completionHandler([.banner, .list])
+ }
+
+ /// A click: the window forward, then Dart opens that agent — the same thing a click on its banner does.
+ func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
+ withCompletionHandler completionHandler: @escaping () -> Void) {
+ defer { completionHandler() }
+ guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else { return }
+ let info = response.notification.request.content.userInfo
+ DispatchQueue.main.async {
+ NSApp.activate(ignoringOtherApps: true)
+ self.channel.invokeMethod("tapped", arguments: [
+ "machineId": info["machineId"] as? String ?? "",
+ "agentId": info["agentId"] as? String ?? "",
+ ])
+ }
+ }
+}
diff --git a/desktop/macos/Runner/MainFlutterWindow.swift b/desktop/macos/Runner/MainFlutterWindow.swift
index 786f788e1..885ac996c 100644
--- a/desktop/macos/Runner/MainFlutterWindow.swift
+++ b/desktop/macos/Runner/MainFlutterWindow.swift
@@ -18,6 +18,7 @@ class MainFlutterWindow: NSWindow {
private var swarmTitlebar: SwarmTitlebar?
private var menuChannel: FlutterMethodChannel?
private var clipboardImageChannel: FlutterMethodChannel?
+ private var notifications: HarnessNotifications?
override func awakeFromNib() {
let flutterViewController = FlutterViewController()
@@ -33,6 +34,7 @@ class MainFlutterWindow: NSWindow {
)
swarmTitlebar = SwarmTitlebar(window: self, messenger: flutterViewController.engine.binaryMessenger)
installClipboardImageChannel(messenger: flutterViewController.engine.binaryMessenger)
+ notifications = HarnessNotifications(messenger: flutterViewController.engine.binaryMessenger)
// Harness Desktop is dark-only. Flutter's own theme does not reach AppKit —
// every native surface (the standard About panel, the menu bar, the
diff --git a/desktop/test/system_notifications_test.dart b/desktop/test/system_notifications_test.dart
new file mode 100644
index 000000000..10a269f6c
--- /dev/null
+++ b/desktop/test/system_notifications_test.dart
@@ -0,0 +1,484 @@
+// The third alert channel: news the operating system delivers, so it reaches somebody whose window
+// is somewhere else. When it is posted, what replaces what, what takes it down, what a click does,
+// and how each platform's notifier is driven.
+import 'dart:io' show ProcessException, ProcessResult;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/notify/agent_alerts.dart';
+import 'package:harness/notify/alert_sounds.dart';
+import 'package:harness/notify/system_notifications.dart';
+import 'package:harness/settings/sections/alerts_card.dart';
+import 'package:harness/state/app_state.dart';
+
+class _Memory implements LocalKeyValueStore {
+ final values = <String, String?>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+/// Records what would have reached the operating system.
+class _Recorder implements SystemNotifier {
+ _Recorder({
+ this.answer = NotificationPermission.granted,
+ this.isSupported = true,
+ });
+
+ NotificationPermission answer;
+ final bool isSupported;
+ final shown =
+ <
+ ({
+ String id,
+ String title,
+ String body,
+ String machineId,
+ String agentId,
+ })
+ >[];
+ final withdrawn = <String>[];
+ int authorizations = 0;
+ void Function(String machineId, String agentId)? tap;
+
+ @override
+ bool get supported => isSupported;
+
+ @override
+ bool get clickOpensAgent => true;
+
+ @override
+ Future<NotificationPermission> authorize() async {
+ authorizations++;
+ return answer;
+ }
+
+ @override
+ Future<NotificationPermission> show({
+ required String id,
+ required String title,
+ required String body,
+ required String machineId,
+ required String agentId,
+ }) async {
+ shown.add((
+ id: id,
+ title: title,
+ body: body,
+ machineId: machineId,
+ agentId: agentId,
+ ));
+ return answer;
+ }
+
+ @override
+ Future<void> withdraw(String id) async => withdrawn.add(id);
+
+ @override
+ set onTap(void Function(String machineId, String agentId)? handler) =>
+ tap = handler;
+}
+
+AgentAlert _alert(
+ String agentId, {
+ AlertKind kind = AlertKind.done,
+ String? title,
+}) => AgentAlert(
+ machineId: 'm1',
+ agentId: agentId,
+ title: title ?? agentId,
+ kind: kind,
+ at: DateTime(2026, 9, 25, 12),
+);
+
+const _machine = Machine(
+ machineId: 'm1',
+ authMode: MachineAuthMode.remote,
+ name: 'MacBook-Pro.local',
+);
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ DesktopNotificationStore store({bool on = true}) =>
+ DesktopNotificationStore(storage: _Memory())..value = on;
+
+ group('the switch', () {
+ test('is OFF until somebody asks for it', () {
+ expect(DesktopNotificationStore(storage: _Memory()).value, isFalse);
+ });
+
+ test('survives a restart, and only a real "on" turns it on', () async {
+ final memory = _Memory();
+ await DesktopNotificationStore(storage: memory).set(true);
+ final reopened = DesktopNotificationStore(storage: memory);
+ await reopened.load();
+ expect(reopened.value, isTrue);
+
+ memory.values['app_desktop_notifications'] = 'o';
+ final garbled = DesktopNotificationStore(storage: memory);
+ await garbled.load();
+ expect(garbled.value, isFalse);
+ });
+
+ test('turning it on is when permission is asked, and not before', () async {
+ final os = _Recorder();
+ final system = SystemNotifications(store: store(on: false), notifier: os);
+ expect(os.authorizations, 0);
+ await system.setEnabled(true);
+ expect(os.authorizations, 1);
+ expect(system.permission.value, NotificationPermission.granted);
+ await system.setEnabled(false);
+ expect(os.authorizations, 1, reason: 'turning it off asks nothing');
+ });
+ });
+
+ group('posting', () {
+ test('nothing while the switch is off', () async {
+ final os = _Recorder();
+ SystemNotifications(
+ store: store(on: false),
+ notifier: os,
+ ).post(_alert('a'));
+ await Future<void>.delayed(Duration.zero);
+ expect(os.shown, isEmpty);
+ });
+
+ test(
+ 'says who and what, under one id per agent so a busy one replaces itself',
+ () async {
+ final os = _Recorder();
+ final system = SystemNotifications(store: store(), notifier: os);
+ system.post(_alert('a', title: 'Fix login'));
+ system.post(_alert('a', kind: AlertKind.needsYou, title: 'Fix login'));
+ system.post(_alert('b'));
+ await Future<void>.delayed(Duration.zero);
+ expect(os.shown.map((s) => s.body), [
+ 'Finished',
+ 'Waiting on you',
+ 'Finished',
+ ]);
+ expect(os.shown.first.title, 'Fix login');
+ expect(os.shown[0].id, os.shown[1].id);
+ expect(os.shown[0].id, isNot(os.shown[2].id));
+ expect(os.shown.first.machineId, 'm1');
+ expect(os.shown.first.agentId, 'a');
+ },
+ );
+
+ test('a build that cannot post stops being asked', () async {
+ final os = _Recorder(answer: NotificationPermission.unavailable);
+ final system = SystemNotifications(store: store(), notifier: os);
+ system.post(_alert('a'));
+ await Future<void>.delayed(Duration.zero);
+ expect(system.permission.value, NotificationPermission.unavailable);
+ system.post(_alert('b'));
+ await Future<void>.delayed(Duration.zero);
+ expect(os.shown, hasLength(1));
+ });
+
+ test('a denial is asked about again, so allowing it later works without a restart', () async {
+ final os = _Recorder(answer: NotificationPermission.denied);
+ final system = SystemNotifications(store: store(), notifier: os);
+ system.post(_alert('a'));
+ await Future<void>.delayed(Duration.zero);
+ expect(system.permission.value, NotificationPermission.denied);
+ // The person allows Harness in System Settings.
+ os.answer = NotificationPermission.granted;
+ system.post(_alert('b'));
+ await Future<void>.delayed(Duration.zero);
+ expect(os.shown, hasLength(2));
+ expect(system.permission.value, NotificationPermission.granted);
+ });
+
+ test('a platform with no notifier is never asked', () async {
+ final os = _Recorder(isSupported: false);
+ final system = SystemNotifications(store: store(), notifier: os);
+ system.post(_alert('a'));
+ system.withdraw('m1', 'a');
+ await Future<void>.delayed(Duration.zero);
+ expect(os.shown, isEmpty);
+ expect(os.withdrawn, isEmpty);
+ });
+ });
+
+ group('the window', () {
+ late _Recorder os;
+ late AppLifecycleState state;
+
+ AppNotifier wired() {
+ os = _Recorder();
+ state = AppLifecycleState.inactive;
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ alerts: AlertSounds(
+ store: AlertSoundStore(storage: _Memory()),
+ channel: const MethodChannel('test/no-sound'),
+ ),
+ agentAlerts: AgentAlerts(
+ store: ScreenAlertStore(storage: _Memory())..value = true,
+ ),
+ systemNotifications: SystemNotifications(store: store(), notifier: os),
+ )..lifecycle = () => state;
+ app.machines = [_machine];
+ app.machineStates['m1'] = MachineState(_machine)
+ ..agents = [const Agent(id: 'a1', name: 'Fix login', engine: 'codex')];
+ return app;
+ }
+
+ Future<void> finish(AppNotifier app) =>
+ app.handleMachineEventForTest('m1', {
+ 'type': 'turn_ended',
+ 'agentId': 'a1',
+ 'payload': {'agentId': 'a1'},
+ });
+
+ test('an agent that finishes while the window is behind something reaches the system', () async {
+ final app = wired();
+ addTearDown(app.dispose);
+ await finish(app);
+ await Future<void>.delayed(Duration.zero);
+ expect(os.shown.single.title, 'Fix login');
+ expect(os.shown.single.body, 'Finished');
+ });
+
+ test(
+ 'in front of the window, the banner says it and the system does not',
+ () async {
+ final app = wired();
+ addTearDown(app.dispose);
+ state = AppLifecycleState.resumed;
+ await finish(app);
+ await Future<void>.delayed(Duration.zero);
+ expect(app.agentAlerts.alerts, hasLength(1));
+ expect(os.shown, isEmpty);
+ },
+ );
+
+ test('going to the agent takes its notification down', () async {
+ final app = wired();
+ addTearDown(app.dispose);
+ await finish(app);
+ app.markAgentSeen('m1', 'a1');
+ expect(os.withdrawn, [SystemNotifications.idFor('m1', 'a1')]);
+ });
+ });
+
+ group('macOS', () {
+ const channel = MethodChannel('harness/notifications');
+ late List<MethodCall> calls;
+ late Object? Function(MethodCall) reply;
+
+ setUp(() {
+ calls = [];
+ reply = (_) => 'granted';
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(channel, (call) async {
+ calls.add(call);
+ return reply(call);
+ });
+ });
+
+ tearDown(() {
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(channel, null);
+ });
+
+ test(
+ 'posts through the native channel with the agent it is about',
+ () async {
+ final mac = MacSystemNotifier(channel: channel);
+ final answer = await mac.show(
+ id: 'harness-agent:m1/a1',
+ title: 'Fix login',
+ body: 'Finished',
+ machineId: 'm1',
+ agentId: 'a1',
+ );
+ expect(answer, NotificationPermission.granted);
+ expect(calls.single.method, 'show');
+ expect(calls.single.arguments, {
+ 'id': 'harness-agent:m1/a1',
+ 'title': 'Fix login',
+ 'body': 'Finished',
+ 'machineId': 'm1',
+ 'agentId': 'a1',
+ });
+ },
+ );
+
+ test('an ad-hoc build the system refuses reads as unavailable', () async {
+ reply = (_) => 'unavailable';
+ expect(
+ await MacSystemNotifier(channel: channel).authorize(),
+ NotificationPermission.unavailable,
+ );
+ });
+
+ test('a click comes back as the agent to open; a click about nobody does nothing', () async {
+ final mac = MacSystemNotifier(channel: channel);
+ final taps = <String>[];
+ mac.onTap = (m, a) => taps.add('$m/$a');
+ Future<void> tap(Map<String, String> args) =>
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ MethodCall('tapped', args),
+ ),
+ (_) {},
+ );
+ await tap({'machineId': 'm1', 'agentId': 'a1'});
+ await tap({'machineId': '', 'agentId': ''});
+ expect(taps, ['m1/a1']);
+ mac.onTap = null;
+ });
+ });
+
+ group('Linux', () {
+ late List<List<String>> ran;
+
+ LinuxSystemNotifier linux(
+ ProcessResult Function(List<String> args) answer,
+ ) {
+ ran = [];
+ return LinuxSystemNotifier(
+ run: (exe, args) async {
+ expect(exe, 'notify-send');
+ ran.add(args);
+ return answer(args);
+ },
+ );
+ }
+
+ Future<NotificationPermission> post(
+ LinuxSystemNotifier n, {
+ String title = 'Fix login',
+ }) => n.show(
+ id: 'x',
+ title: title,
+ body: 'Finished',
+ machineId: 'm1',
+ agentId: 'a1',
+ );
+
+ test('the second notification for an agent replaces the first', () async {
+ var next = 41;
+ final n = linux((_) => ProcessResult(0, 0, '${++next}\n', ''));
+ expect(await post(n), NotificationPermission.granted);
+ await post(n);
+ expect(ran[0], containsAll(['--app-name=Harness', '--print-id']));
+ expect(ran[0].any((a) => a.startsWith('--replace-id')), isFalse);
+ expect(ran[1], contains('--replace-id=42'));
+ });
+
+ test('an agent named like a flag is still a title', () async {
+ final n = linux((_) => ProcessResult(0, 0, '7', ''));
+ await post(n, title: '-u critical');
+ final args = ran.single;
+ expect(args.indexOf('--'), lessThan(args.indexOf('-u critical')));
+ });
+
+ test(
+ 'an old notify-send that refuses the flags still gets its notification',
+ () async {
+ final n = linux(
+ (args) => args.contains('--print-id')
+ ? ProcessResult(0, 1, '', 'Unknown option --print-id')
+ : ProcessResult(0, 0, '', ''),
+ );
+ expect(await post(n), NotificationPermission.granted);
+ await post(n);
+ expect(
+ ran,
+ hasLength(3),
+ reason: 'the flags are tried once, then left off',
+ );
+ expect(ran.last.contains('--print-id'), isFalse);
+ },
+ );
+
+ test('a daemon that is not up yet is tried again next time', () async {
+ var up = false;
+ final n = linux(
+ (_) => up
+ ? ProcessResult(0, 0, '9', '')
+ : ProcessResult(0, 1, '', 'Could not connect'),
+ );
+ expect(await post(n), NotificationPermission.unknown);
+ up = true;
+ expect(await post(n), NotificationPermission.granted);
+ // A daemon that was down is not a notify-send without the flags.
+ expect(ran.last, contains('--print-id'));
+ });
+
+ test(
+ 'a desktop without notify-send is unavailable, not an error',
+ () async {
+ final n = LinuxSystemNotifier(
+ run: (_, _) async => throw const ProcessException('notify-send', []),
+ );
+ expect(await n.authorize(), NotificationPermission.unavailable);
+ expect(await post(n), NotificationPermission.unavailable);
+ },
+ );
+ });
+
+ group('Settings', () {
+ Future<void> pump(WidgetTester tester, SystemNotifications system) =>
+ tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: AlertsCard(
+ store: AlertSoundStore(storage: _Memory()),
+ screenStore: ScreenAlertStore(storage: _Memory()),
+ notifications: system,
+ ),
+ ),
+ ),
+ );
+
+ testWidgets('a switch that asks for permission when turned on', (
+ tester,
+ ) async {
+ final os = _Recorder();
+ final system = SystemNotifications(store: store(on: false), notifier: os);
+ await pump(tester, system);
+ await tester.tap(find.byKey(const Key('settings-desktop-notifications')));
+ await tester.pumpAndSettle();
+ expect(system.store.value, isTrue);
+ expect(os.authorizations, 1);
+ });
+
+ testWidgets('says where to fix it when the system said no', (tester) async {
+ final system = SystemNotifications(
+ store: store(on: false),
+ notifier: _Recorder(answer: NotificationPermission.denied),
+ );
+ await pump(tester, system);
+ await tester.tap(find.byKey(const Key('settings-desktop-notifications')));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('System Settings'), findsOneWidget);
+ });
+
+ testWidgets('no row where there is no notifier to switch', (tester) async {
+ await pump(
+ tester,
+ SystemNotifications(store: store(), notifier: const NoSystemNotifier()),
+ );
+ expect(
+ find.byKey(const Key('settings-desktop-notifications')),
+ findsNothing,
+ );
+ });
+ });
+}