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. 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 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 _frames; late final StreamSubscription _focus; Future _queue = Future.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 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) { 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'] != '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); }); } /// Runs deliveries one at a time, in arrival order. void _enqueue(Future Function() step) { _queue = _queue.then((_) => step()).catchError((Object _) {}); } Future _replay(List notices) async { await notifications.ready; if (_disposed) return; final now = _now(); final fresh = []; 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 _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 toast = delivery.toast; if (delivery.system && !_showSystem(notice, headline, open)) toast = true; if (toast) { showToast( AgentToast(headline: headline, message: notice.message, open: open), ); } if (delivery.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()); } }