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, }); /// The transition identities already recorded, in no particular order. final Set notified; /// 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); NotificationLedger withAsked(bool value) => NotificationLedger(notified: notified, asked: value); /// 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); } } /// 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(); return jsonEncode({'asked': ledger.asked, 'notified': identities}); } /// 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']; return NotificationLedger( notified: { if (raw is List) for (final value in raw) if (value is String && value.isNotEmpty) value, }, asked: parsed['asked'] == true, ); }