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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user