Notifications: agent notify reaches every device and clears everywhere

- Server: chat ntfy messages carry a sequence id derived from their app id;
  clearing a chat app notification also clears it in ntfy (PUT
  /<topic>/<seq>/clear, verified on ntfy v2.38.1).
- Server: a turn that sent an agent notify does not also send chat_reply.
- notify tool and MCP instructions: Pipelines already notifies at reply end
  and for questions/approvals; notify is for mid-turn or background news.
- Shown notify items carry channels (apps/phone); the transcript row says
  where it went.
- App: NotificationBridge.close(tag); web closes tracked Notifications and
  tells other tabs over a BroadcastChannel; native bridge cancels by tag and
  now supports macOS. AgentNotices closes on notifications_cleared and on
  resubscribe cleared ids, and a tap sends clear_notifications.
- Docs: skill, chat reference, ntfy/notifications docs, app note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 19:43:55 +00:00
parent c441400f36
commit b91ef04ab0
32 changed files with 743 additions and 73 deletions
@@ -31,6 +31,13 @@ class AgentToast {
/// ones within [agentNoticeReplayWindow] are shown once and every id is
/// recorded in the persisted notification ledger, so neither a reload nor a
/// reconnect repeats one.
///
/// It also keeps the system notifications in step with the server: a clear
/// (`notifications_cleared`, pushed when the operator opened the chat, tapped
/// or dismissed the notification on any device, or the reply to this client's
/// own clear) and the cleared ids a reconnect reports close the matching
/// notification here, and a tap clears it on the server, so it vanishes from
/// every other device too.
class AgentNotices {
AgentNotices({
required this.gateway,
@@ -96,6 +103,7 @@ class AgentNotices {
}
void _onSubscribed(JsonMap reply) {
_closeCleared(reply['ids']);
final raw = reply['notifications'];
if (_disposed || raw is! List) return;
final notices = [for (final value in raw) ?AgentNotice.parse(value)];
@@ -107,6 +115,10 @@ class AgentNotices {
_onSubscribed(frame);
return;
}
if (frame['type'] == 'notifications_cleared') {
_closeCleared(frame['ids']);
return;
}
if (frame['type'] != 'notification') return;
final notice = AgentNotice.parse(frame['notification']);
if (notice == null) return;
@@ -119,6 +131,42 @@ class AgentNotices {
});
}
/// Closes the system notifications for server ids cleared on any device.
void _closeCleared(Object? ids) {
if (_disposed || ids is! List) return;
for (final id in ids) {
if (id is! String || id.isEmpty) continue;
try {
notifications.bridge.close(id);
} catch (_) {
// Nothing shown for it here.
}
}
}
/// Clears [id] on the server: every other device then drops it, and the
/// equivalent acknowledgement marks the chat seen.
void _clearOnServer(String id) {
final send = sendOnly;
try {
if (send != null) {
send('clear_notifications', {
'ids': [id],
});
} else {
unawaited(
gateway
.call('clear_notifications', {
'ids': [id],
})
.then((_) {}, onError: (Object _) {}),
);
}
} catch (_) {
// Not connected: opening the chat marks it seen when it connects.
}
}
/// Runs deliveries one at a time, in arrival order.
void _enqueue(Future<void> Function() step) {
_queue = _queue.then((_) => step()).catchError((Object _) {});
@@ -164,7 +212,13 @@ class AgentNotices {
void open() => openChat(notice.sessionId);
var badge = delivery.badge;
// A system notification the OS refused is counted in the tab title.
if (delivery.system && !_showSystem(notice, headline, open)) badge = true;
if (delivery.system &&
!_showSystem(notice, headline, () {
_clearOnServer(notice.id);
open();
})) {
badge = true;
}
if (delivery.toast) {
showToast(
AgentToast(headline: headline, message: notice.message, open: open),
@@ -21,8 +21,13 @@ abstract interface class NotificationBridge {
Future<String> requestPermission();
/// Shows one notification, attaching [onTap] as its tap intent when given.
/// Returns whether the platform accepted it.
/// Returns whether the platform accepted it. A notification with the same
/// [NotificationMessage.tag] replaces the earlier one.
bool show(NotificationMessage message, {void Function()? onTap});
/// Removes the notification this device shows for [tag], if any: it was
/// read or cleared on this or another device. Unknown tags are ignored.
void close(String tag);
}
/// The bridge for the current platform: the browser `Notification` on the web,
@@ -5,8 +5,9 @@ import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'notification_bridge.dart';
import 'notification_models.dart';
/// System notifications on a phone: Android's notification shade (and iOS's
/// centre). The permission is cached so [environment] stays synchronous; it
/// System notifications from the native app: Android's notification shade (when
/// its background notification service is off), iOS's and macOS's
/// notification centre. [close] removes a delivered one by its tag. The permission is cached so [environment] stays synchronous; it
/// is refreshed when the bridge starts and after every request.
class NativeNotificationBridge implements NotificationBridge {
NativeNotificationBridge() {
@@ -15,6 +16,9 @@ class NativeNotificationBridge implements NotificationBridge {
final _plugin = FlutterLocalNotificationsPlugin();
final Map<int, void Function()> _taps = {};
/// The platform id each shown tag was posted with, so [close] can remove it.
final Map<String, int> _ids = {};
late final Future<void> _ready;
String _permission = 'default';
bool _started = false;
@@ -30,20 +34,25 @@ class NativeNotificationBridge implements NotificationBridge {
priority: Priority.high,
);
static const _darwin = DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
);
Future<void> _start() async {
try {
await _plugin.initialize(
settings: const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
iOS: DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
),
iOS: _darwin,
macOS: _darwin,
),
onDidReceiveNotificationResponse: (response) {
final id = response.id;
if (id != null) _taps.remove(id)?.call();
if (id == null) return;
_ids.removeWhere((_, posted) => posted == id);
_taps.remove(id)?.call();
},
);
_started = true;
@@ -61,12 +70,19 @@ class NativeNotificationBridge implements NotificationBridge {
>()
?.areNotificationsEnabled();
_permission = enabled == true ? 'granted' : 'default';
} else if (Platform.isMacOS) {
final options = await _plugin
.resolvePlatformSpecificImplementation<
MacOSFlutterLocalNotificationsPlugin
>()
?.checkPermissions();
_permission = options?.isEnabled == true ? 'granted' : 'default';
}
}
@override
NotificationEnvironment environment() => NotificationEnvironment(
supported: Platform.isAndroid || Platform.isIOS,
supported: Platform.isAndroid || Platform.isIOS || Platform.isMacOS,
// A native app needs no secure origin.
secureContext: true,
permission: _permission,
@@ -89,6 +105,12 @@ class NativeNotificationBridge implements NotificationBridge {
IOSFlutterLocalNotificationsPlugin
>()
?.requestPermissions(alert: true, badge: true, sound: true);
} else if (Platform.isMacOS) {
granted = await _plugin
.resolvePlatformSpecificImplementation<
MacOSFlutterLocalNotificationsPlugin
>()
?.requestPermissions(alert: true, badge: true, sound: true);
}
_permission = granted == true
? 'granted'
@@ -101,17 +123,35 @@ class NativeNotificationBridge implements NotificationBridge {
@override
bool show(NotificationMessage message, {void Function()? onTap}) {
if (!_started || _permission != 'granted') return false;
final id = _nextId++;
if (onTap != null) _taps[id] = onTap;
// The same tag reuses its platform id, so the new one replaces the old.
final id = _ids[message.tag] ??= _nextId++;
if (onTap != null) {
_taps[id] = onTap;
} else {
_taps.remove(id);
}
_plugin.show(
id: id,
title: message.title,
body: message.body,
notificationDetails: const NotificationDetails(android: _channel),
notificationDetails: const NotificationDetails(
android: _channel,
iOS: DarwinNotificationDetails(),
macOS: DarwinNotificationDetails(),
),
payload: message.tag,
);
return true;
}
@override
void close(String tag) {
final id = _ids.remove(tag);
if (id == null || !_started) return;
_taps.remove(id);
// Removes the delivered notification (Android shade, Darwin centre).
_plugin.cancel(id: id).catchError((Object _) {});
}
}
NotificationBridge createNotificationBridge() => NativeNotificationBridge();
@@ -21,6 +21,9 @@ class UnsupportedNotificationBridge implements NotificationBridge {
@override
bool show(NotificationMessage message, {void Function()? onTap}) => false;
@override
void close(String tag) {}
}
NotificationBridge createNotificationBridge() =>
@@ -1,6 +1,8 @@
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:web/web.dart' as web;
import 'notification_bridge.dart';
import 'notification_models.dart';
@@ -20,6 +22,8 @@ extension type _Notification._(JSObject _) implements JSObject {
external set onclick(JSFunction? handler);
external set onclose(JSFunction? handler);
external void close();
}
@@ -38,6 +42,40 @@ bool _secureContext() {
return value.isA<JSBoolean>() && (value as JSBoolean).toDart;
}
/// The notifications this tab posted and still shows, by tag, so a clear (from
/// the server, or from another tab) can close them. Shared by every bridge in
/// the tab.
final Map<String, _Notification> _open = {};
/// Tells the other tabs and installed-app windows of this origin to close a
/// tag too: each one closes only the `Notification` objects it created.
web.BroadcastChannel? _channel;
web.BroadcastChannel? _tabs() {
if (_channel != null) return _channel;
try {
final channel = web.BroadcastChannel('pipelines.notifications');
channel.onmessage = ((web.MessageEvent event) {
final data = event.data;
if (data.isA<JSString>()) _closeLocal((data as JSString).toDart);
}).toJS;
_channel = channel;
} catch (_) {
// No BroadcastChannel: every tab still receives the server's clear.
}
return _channel;
}
void _closeLocal(String tag) {
final notification = _open.remove(tag);
if (notification == null) return;
try {
notification.close();
} catch (_) {
// Already gone.
}
}
/// The browser bridge: the real `Notification` API, reached through
/// `dart:js_interop`.
///
@@ -79,17 +117,30 @@ class WebNotificationBridge implements NotificationBridge {
bool show(NotificationMessage message, {void Function()? onTap}) {
if (!_supported()) return false;
try {
final tag = message.tag;
// The new one replaces any earlier one with this tag; forget the old
// object first so its close event is not mistaken for this one's.
_open.remove(tag);
final notification = _Notification(
message.title.toJS,
_NotificationOptions(body: message.body.toJS, tag: message.tag.toJS),
_NotificationOptions(body: message.body.toJS, tag: tag.toJS),
);
_tabs();
_open[tag] = notification;
// A close event (the operator's dismissal, but also a notification
// daemon's timeout or another tab replacing it) only forgets it here: it
// is not reported to the server, so a timeout never clears it on the
// operator's other devices.
notification.onclose = (() {
if (identical(_open[tag], notification)) _open.remove(tag);
}).toJS;
final open = onTap;
if (open != null) {
notification.onclick = (() {
// Bring this tab forward first: a click on a notification does not
// focus the page that posted it on its own.
globalContext.callMethod<JSAny?>('focus'.toJS);
notification.close();
close(tag);
open();
}).toJS;
}
@@ -100,6 +151,16 @@ class WebNotificationBridge implements NotificationBridge {
return false;
}
}
@override
void close(String tag) {
_closeLocal(tag);
try {
_tabs()?.postMessage(tag.toJS);
} catch (_) {
// The other tabs still receive the server's clear.
}
}
}
NotificationBridge createNotificationBridge() => const WebNotificationBridge();
@@ -3,15 +3,28 @@ import 'package:flutter/material.dart';
import '../../../../../core/api_gateway.dart';
import 'chat_shown_surface.dart';
/// What a `notify` entry says: the phone notification was accepted for
/// delivery, or why it was not sent.
/// What a `notify` entry says: where the notification went (the server's
/// `channels`: the operator's signed-in Pipelines `apps` and/or their `phone`),
/// or why it was not sent.
String chatShownNotifyText(JsonMap item) {
final title = chatShownTitle(item, 'notification');
if (item['delivered'] == true) return 'Notified your phone: $title';
if (item['delivered'] == true) return '${_notifiedWhere(item)}: $title';
final detail = '${item['detail'] ?? ''}'.trim();
return detail.isEmpty
? 'Phone notification not sent: $title'
: 'Phone notification not sent: $title — $detail';
? 'Notification not sent: $title'
: 'Notification not sent: $title — $detail';
}
String _notifiedWhere(JsonMap item) {
final raw = item['channels'];
final channels = raw is List ? raw.map((c) => '$c').toSet() : <String>{};
final apps = channels.contains('apps');
final phone = channels.contains('phone');
if (apps && phone) return 'Notified your apps and phone';
if (apps) return 'Notified your apps';
if (phone) return 'Notified your phone';
// An entry recorded before the server said where it went.
return 'Notified you';
}
/// One secondary line in the agent's column for a `notify` entry, with the
+27
View File
@@ -29,3 +29,30 @@ view, insecure unfocused toast with `document.title == "(1) Pipelines"` and back
to `Pipelines` on focus, and the Settings hints for secure and insecure pages.
Browser system notifications themselves were not captured (headless Chrome,
permission not granted); unit tests cover that path.
## Clearing everywhere
`AgentNotices` closes the system notification for every id in a
`notifications_cleared` frame (a push after a clear on another device or the
chat being opened, or the reply to this client's own clear) and for the cleared
ids a resubscribe reports. A tap sends `clear_notifications` for the notice
before opening the chat. `NotificationBridge.close(tag)` does the platform work:
the web bridge keeps the `Notification` objects it posted by tag, closes the one
for the tag and posts the tag on the `pipelines.notifications`
`BroadcastChannel` so the origin's other tabs and installed-app windows close
theirs; the native bridge (Android without the background service, iOS, and now
macOS) cancels the platform id it used for the tag. A browser `close` event is
deliberately not sent to the server: Chrome raises it for a notification
daemon's timeout and for a same-tag replacement by another tab, which would
clear the notice on every device seconds after it appeared. The transcript row
says where a notify went from the item's `channels` ("Notified your apps and
phone", "Notified your apps", "Notified your phone").
Browser check (headless Chromium, `tool/capture`, fixture
`?ui-review=1&agentNotice=6000[&agentNoticeClear=9000]`, notification
permission granted through CDP, `window.Notification` wrapped to record): the
notice posted `show chat:ui-review:notify:shown_capture`; a pushed
`notifications_cleared` then recorded `close` for that tag; without the clear,
a message on the `pipelines.notifications` BroadcastChannel (as another tab
sends) closed it. The transcript row reads "Notified your apps and phone:
Release ready" (`?chats=1&timestamps=1&shown=1`, route `/chat/perf-chat-0`).
@@ -17,6 +17,7 @@ class _Gateway implements ApiGateway {
final controller = StreamController<JsonMap>.broadcast();
List<JsonMap> backlog = [];
final calls = <String>[];
final sent = <JsonMap>[];
@override
Stream<JsonMap> get frames => controller.stream;
@@ -24,6 +25,7 @@ class _Gateway implements ApiGateway {
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(type);
sent.add({'type': type, ...fields});
return {
'type': 'notifications_subscribed',
'notifications': backlog,
@@ -140,6 +142,50 @@ void main() {
expect(opened, ['ses_1']);
});
test(
'a tap clears the notice on the server so other devices drop it',
() async {
await setUpWith();
gateway.controller.add(_push(_notice('a')));
await pump();
bridge.taps.first!();
await pump();
expect(opened, ['ses_1']);
expect(gateway.sent.last, {
'type': 'clear_notifications',
'ids': ['chat:ses_1:notify:a'],
});
},
);
test('a clear from the server (another device, or the chat opened) closes '
'the system notification here', () async {
await setUpWith();
gateway.controller.add(_push(_notice('a')));
await pump();
expect(bridge.shown, hasLength(1));
gateway.controller.add({
'type': 'notifications_cleared',
'ids': ['chat:ses_1:notify:a'],
});
await pump();
expect(bridge.closed, ['chat:ses_1:notify:a']);
});
test(
'ids cleared while away close their notifications on resubscribe',
() async {
await setUpWith();
gateway.controller.add({
'type': 'notifications_subscribed',
'notifications': <JsonMap>[],
'ids': ['chat:ses_1:notify:old'],
});
await pump();
expect(bridge.closed, ['chat:ses_1:notify:old']);
},
);
test('nothing shows when the chat is already in view', () async {
await setUpWith();
active = 'ses_1';
@@ -276,4 +276,7 @@ class _ThrowingBridge implements NotificationBridge {
@override
bool show(NotificationMessage message, {void Function()? onTap}) =>
throw StateError('the browser refused to construct a notification');
@override
void close(String tag) {}
}
@@ -114,6 +114,7 @@ class FakeNotificationBridge implements NotificationBridge {
int requests = 0;
final List<NotificationMessage> shown = [];
final List<void Function()?> taps = [];
final List<String> closed = [];
@override
NotificationEnvironment environment() => NotificationEnvironment(
@@ -135,4 +136,7 @@ class FakeNotificationBridge implements NotificationBridge {
taps.add(onTap);
return accepts;
}
@override
void close(String tag) => closed.add(tag);
}
@@ -188,16 +188,34 @@ void main() {
expect(find.byKey(const Key('stub-html')), findsNothing);
});
testWidgets('notify rows say whether the phone was notified', (tester) async {
testWidgets('notify rows say where the notification went', (tester) async {
await pump(tester, {
'id': 'n',
'kind': 'notify',
'title': 'Build done',
'message': 'All green',
'delivered': true,
'channels': ['apps', 'phone'],
});
expect(find.text('Notified your phone: Build done'), findsOneWidget);
expect(
find.text('Notified your apps and phone: Build done'),
findsOneWidget,
);
expect(find.text('All green'), findsOneWidget);
for (final (channels, text) in [
(['apps'], 'Notified your apps: Build done'),
(['phone'], 'Notified your phone: Build done'),
(null, 'Notified you: Build done'),
]) {
await pump(tester, {
'id': 'n-$text',
'kind': 'notify',
'title': 'Build done',
'delivered': true,
'channels': ?channels,
});
expect(find.text(text), findsOneWidget);
}
await pump(tester, {
'id': 'n2',
'kind': 'notify',
@@ -207,7 +225,7 @@ void main() {
});
expect(
find.text(
'Phone notification not sent: Build done — notifications are not set up',
'Notification not sent: Build done — notifications are not set up',
),
findsOneWidget,
);
+12
View File
@@ -6,6 +6,9 @@
// for the `ui-review` chat (add `ui-review=1` so the
// chat has its title). `agentNoticePriority=2|3|4`
// sets its priority (default 3).
// `?agentNoticeClear=<ms>` then pushes `notifications_cleared` for it <ms>
// after the subscription, as when the operator opens
// the chat or taps the notification on another device.
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
@@ -40,6 +43,15 @@ JsonMap? agentNoticeReply(JsonMap request, void Function(JsonMap) emit) {
});
});
}
final clear = int.tryParse(_params['agentNoticeClear'] ?? '');
if (clear != null) {
Timer(Duration(milliseconds: clear), () {
emit({
'type': 'notifications_cleared',
'ids': ['chat:ui-review:notify:shown_capture'],
});
});
}
return {
'id': request['id'],
'type': 'notifications_subscribed',
+1
View File
@@ -69,6 +69,7 @@ JsonMap chatShownFixture(Object? sessionId) => {
'message': 'All three stages passed; the release is ready to publish.',
'priority': 'default',
'delivered': true,
'channels': ['apps', 'phone'],
},
{
'id': 'shown-diff',