Files
pipelines/app/lib/features/attention/notify/agent_notices.dart
T
alan b91ef04ab0 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>
2026-12-02 19:49:31 +00:00

262 lines
7.9 KiB
Dart

import 'dart:async';
import '../../../core/api_gateway.dart';
import 'agent_notice.dart';
import 'notification_controller.dart';
import 'notification_models.dart';
import 'page_signals.dart';
/// One in-app toast for an agent notice.
class AgentToast {
const AgentToast({
required this.headline,
required this.message,
required this.open,
});
final String headline;
final String message;
/// Opens the notice's chat.
final void Function() open;
}
/// Delivers agents' `notify` calls (the `chat_notify` app notifications) on
/// this device: a system notification, an in-app toast, a count in the tab
/// title and a chime, as [agentNoticeDelivery] decides for the page's presence
/// and the notification permission.
///
/// It subscribes to the server's notification stream on every connection
/// ([connected]), so notices sent while this client was away are replayed; the
/// 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,
required this.notifications,
required this.page,
required this.activeChatSessionId,
required this.sessionTitle,
required this.openChat,
required this.showToast,
this.sendOnly,
DateTime Function()? now,
}) : _now = now ?? DateTime.now {
_frames = gateway.frames.listen(_onFrame);
_focus = page.focused.listen((_) => _clearBadge());
}
final ApiGateway gateway;
final NotificationController notifications;
final PageSignals page;
final String? Function() activeChatSessionId;
final Future<String?> Function(String sessionId) sessionTitle;
final void Function(String sessionId) openChat;
final void Function(AgentToast toast) showToast;
/// Sends a request without awaiting its reply; see [connected].
final String Function(String type, JsonMap fields)? sendOnly;
final DateTime Function() _now;
late final StreamSubscription<JsonMap> _frames;
late final StreamSubscription<void> _focus;
Future<void> _queue = Future<void>.value();
bool _disposed = false;
int _badge = 0;
/// The count shown in the tab title.
int get badge => _badge;
/// Subscribes to the notification stream on a new connection and shows the
/// recent notices it missed. Safe to call on every reconnect: the server
/// replaces the subscription and the ledger drops repeats.
///
/// With [sendOnly] (the app passes the socket's send-only path) the request
/// does not hold the request lane for its reply, and the reply is read from
/// the pushed frames like the notifications that follow it.
Future<void> connected() async {
if (_disposed) return;
final send = sendOnly;
if (send != null) {
try {
send('subscribe_notifications', const {});
} catch (_) {
// Not connected: the next connection subscribes.
}
return;
}
JsonMap reply;
try {
reply = await gateway.call('subscribe_notifications');
} catch (_) {
return; // An older server or a dropped socket: live pushes still work.
}
_onSubscribed(reply);
}
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)];
_enqueue(() => _replay(notices));
}
void _onFrame(JsonMap frame) {
if (frame['type'] == 'notifications_subscribed') {
_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;
_enqueue(() async {
await notifications.ready;
if (_disposed || !notifications.claimAgentNotice(notice.id, _now())) {
return;
}
await _deliver(notice, replay: false);
});
}
/// 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 _) {});
}
Future<void> _replay(List<AgentNotice> notices) async {
await notifications.ready;
if (_disposed) return;
final now = _now();
final fresh = <AgentNotice>[];
for (final notice in notices) {
if (!notifications.claimAgentNotice(notice.id, now)) continue;
final at = notice.createdAt;
if (at != null && now.difference(at) <= agentNoticeReplayWindow) {
fresh.add(notice);
}
}
final start = fresh.length > agentNoticeReplayLimit
? fresh.length - agentNoticeReplayLimit
: 0;
for (final notice in fresh.skip(start)) {
if (_disposed) return;
await _deliver(notice, replay: true);
}
}
Future<void> _deliver(AgentNotice notice, {required bool replay}) async {
String? chat;
try {
chat = await sessionTitle(notice.sessionId);
} catch (_) {
// An unavailable chat list leaves the generic "Chat" headline.
}
if (_disposed) return;
final delivery = agentNoticeDelivery(
notice: notice,
presence: page.presence,
chatInView: activeChatSessionId() == notice.sessionId,
canNotify: notifications.canNotify,
replay: replay,
);
final headline = notice.headline(chat);
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, () {
_clearOnServer(notice.id);
open();
})) {
badge = true;
}
if (delivery.toast) {
showToast(
AgentToast(headline: headline, message: notice.message, open: open),
);
}
if (badge && page.presence != PagePresence.focused) {
_badge++;
page.setBadge(_badge);
}
if (delivery.chime) page.chime();
}
bool _showSystem(AgentNotice notice, String headline, void Function() open) {
try {
return notifications.bridge.show(
NotificationMessage(
chatSessionId: notice.sessionId,
title: headline,
body: notice.message,
tag: notice.id,
),
onTap: open,
);
} catch (_) {
return false;
}
}
void _clearBadge() {
if (_badge == 0) return;
_badge = 0;
page.setBadge(0);
}
void dispose() {
_disposed = true;
unawaited(_frames.cancel());
unawaited(_focus.cancel());
}
}