import 'dart:convert'; import '../../../core/api_gateway.dart'; import '../domain/attention_models.dart'; import '../domain/attention_transitions.dart'; /// This client's own storage key for the notification ledger, namespaced like /// the rest of the app. It is deliberately not the legacy web key, so neither /// client rewrites the other's local state on a shared origin. const notificationStorageKey = 'pipelines.next.notify.v1'; /// The identity of one announced transition: the run and kind, exactly the /// attention surface's own key and the browser's `alertKey`. /// /// It is deliberately *not* keyed by a timestamp. A waiting run has no /// `finished_at`, and its creation time never changes, so a marker derived from /// them cannot tell a run's first decision gate from a later one. Instead the /// ledger only holds identities for the runs that are qualifying *right now*: /// [notificationQualifyingKeys] supplies that set, and an identity is forgotten /// as soon as its run leaves the qualifying state (see [NotificationLedger.pruning]). /// The next entry into the same state is therefore a new announcement, exactly /// as in `web/src/notify.js`. String notificationIdentity(AttentionTransition transition) => transition.key; /// The `{runId}:{Kind}` identities of the runs currently in a qualifying state, /// built from the same rows the attention surface draws. /// /// Dismissals and the local-day window are deliberately ignored: a dismissal /// does not stop a run qualifying, and an old failure is still the same /// announced transition rather than a new one. Set notificationQualifyingKeys(Iterable? runs) { final keys = {}; for (final run in runs ?? const []) { final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']); final kind = attentionKindForRun(run); if (runId == null || kind == null) continue; keys.add(attentionKey(runId, kind)); } return keys; } /// What this client has already announced, plus whether the operator has ever /// been asked. /// /// The ledger is pure: it records identities, decides whether one is new and /// drops the ones whose run no longer qualifies. Persistence is the store's job. /// /// An identity lives only while its run is in the qualifying state it announced: /// publishing the same list again is idempotent, a reconnect cannot repeat a /// notification, and a genuinely new transition (a second decision gate, or a /// later failure of a new run id) notifies once more because leaving the state /// dropped the old identity. This is the browser's `forget` model; unlike a /// timestamp marker it can tell two decision gates of one run apart. class NotificationLedger { const NotificationLedger({ this.notified = const {}, this.asked = false, this.agentShown = const {}, }); /// How many agent notification ids the ledger keeps, newest first. static const maxAgentShown = 200; /// How long an agent notification id is kept: longer than the replay window /// the client honours, so a replayed one is always recognised. static const agentShownRetention = Duration(days: 2); /// The transition identities already recorded, in no particular order. final Set notified; /// The agent notification ids (server ids of `chat_notify`) already shown on /// this device, with when they were shown (epoch milliseconds). Unlike /// [notified] they are not tied to a run state: they are only forgotten by /// age and count, so a reload or reconnect never repeats one. final Map agentShown; /// Whether the operator has ever been asked for permission. final bool asked; bool hasNotified(String identity) => notified.contains(identity); /// The ledger with [identity] recorded. NotificationLedger recording(String identity) => NotificationLedger( notified: {...notified, identity}, asked: asked, agentShown: agentShown, ); NotificationLedger withAsked(bool value) => NotificationLedger( notified: notified, asked: value, agentShown: agentShown, ); bool hasShownAgent(String id) => agentShown.containsKey(id); /// The ledger with agent notification [id] recorded as shown at [now], and /// every entry older than [agentShownRetention] or beyond [maxAgentShown] /// dropped. NotificationLedger recordingAgent(String id, DateTime now) { final at = now.millisecondsSinceEpoch; final oldest = now.subtract(agentShownRetention).millisecondsSinceEpoch; final entries = [ ...agentShown.entries.where((e) => e.key != id && e.value >= oldest), MapEntry(id, at), ]..sort((a, b) => b.value.compareTo(a.value)); return NotificationLedger( notified: notified, asked: asked, agentShown: Map.fromEntries(entries.take(maxAgentShown)), ); } /// The ledger with every identity outside [qualifying] dropped. /// /// A run that is no longer failed or waiting has left its announced state, so /// a later entry is a new event and must be able to notify again. Keeping only /// the current qualifying identities also bounds the ledger to the runs the /// surface currently holds instead of growing with every event ever seen. NotificationLedger pruning(Set qualifying) { final kept = notified.where(qualifying.contains).toSet(); if (kept.length == notified.length) return this; return NotificationLedger( notified: kept, asked: asked, agentShown: agentShown, ); } } /// The one-line JSON the ledger is stored as. The identities are sorted so an /// unchanged ledger always encodes to the same bytes. String encodeNotificationLedger(NotificationLedger ledger) { final identities = ledger.notified.where((id) => id.isNotEmpty).toList() ..sort(); final agent = ledger.agentShown.keys.where((id) => id.isNotEmpty).toList() ..sort(); return jsonEncode({ 'asked': ledger.asked, 'notified': identities, if (agent.isNotEmpty) 'agent': {for (final id in agent) id: ledger.agentShown[id]}, }); } /// Decodes a stored value into a ledger. Total: blank text, unreadable JSON, a /// non-map, a non-boolean `asked` and non-string members all decode to the /// members that can be read, and a malformed value never throws. /// /// A value written by an older build may still contain timestamped identities; /// they simply stop matching [notificationQualifyingKeys] and are dropped on the /// next publish, so no migration step is needed. NotificationLedger decodeNotificationLedger(String? stored) { final text = (stored ?? '').trim(); if (text.isEmpty) return const NotificationLedger(); dynamic parsed; try { parsed = jsonDecode(text); } catch (_) { return const NotificationLedger(); } if (parsed is! Map) return const NotificationLedger(); final raw = parsed['notified']; final agent = parsed['agent']; return NotificationLedger( agentShown: { if (agent is Map) for (final entry in agent.entries) if (entry.key is String && (entry.key as String).isNotEmpty && entry.value is int) entry.key as String: entry.value as int, }, notified: { if (raw is List) for (final value in raw) if (value is String && value.isNotEmpty) value, }, asked: parsed['asked'] == true, ); }