feat(app): notification capability with transition dedupe

This commit is contained in:
2026-10-22 02:05:20 +01:00
parent 7718604268
commit b8e5c3e7e3
13 changed files with 871 additions and 393 deletions
@@ -18,13 +18,18 @@ import 'notification_store.dart';
///
/// Only live attention transitions raise a notification: the caller publishes
/// the transitions the attention model raised (never the initial seed), and one
/// identity is posted at most once, including across a reconnect, because the
/// ledger records the identity before the platform is asked to show it. A
/// dismissed identity is recorded but never shown.
/// identity is posted at most once per entry into its run's qualifying state,
/// including across a reconnect, because the ledger records the identity before
/// the platform is asked to show it. A dismissed identity is recorded but never
/// shown.
///
/// The manager wires it: set [onOpenRun] to open a run, call [load] once, and
/// call [publishTransitions] with the attention controller's transitions. That
/// call is idempotent, so passing the whole accumulated list is safe.
/// after *every* authoritative read and pushed frame call [publishTransitions]
/// with the attention controller's accumulated transitions, its current rows
/// (through [notificationQualifyingKeys]) and its dismissed set. Publishing the
/// frame that leaves a state is what forgets the old identity, so the next gate
/// or retry is a new announcement. The call is idempotent, so passing the whole
/// accumulated list is safe.
class NotificationController extends ChangeNotifier {
NotificationController({required this.store, NotificationBridge? bridge})
: bridge = bridge ?? createNotificationBridge();
@@ -45,6 +50,13 @@ class NotificationController extends ChangeNotifier {
bool _disposed = false;
int _posted = 0;
/// The transition instance announced this session for each identity: a new
/// instance means the run entered the state again.
final Map<String, AttentionTransition> _announced = {};
/// The queued ledger writes, so an older snapshot cannot land after a newer one.
Future<void> _writes = Future<void>.value();
/// The platform's own permission state for this page.
NotificationPermissionState get permission => _permission;
@@ -54,8 +66,10 @@ class NotificationController extends ChangeNotifier {
/// Whether the operator has ever been asked for permission.
bool get asked => _ledger.asked;
/// The transition identities this client has already recorded.
Set<String> get notified => _ledger.notified;
/// A copy of the transition identities this client has already announced.
/// Returned unmodifiable, so a caller cannot mutate the ledger behind
/// [publishTransitions]' back.
Set<String> get notified => Set<String>.unmodifiable(_ledger.notified);
/// True only when the platform itself reported `granted`.
bool get canNotify => _permission == NotificationPermissionState.granted;
@@ -73,6 +87,7 @@ class NotificationController extends ChangeNotifier {
}
if (_disposed) return;
_ledger = ledger;
_announced.clear();
_permission = notificationStateOf(bridge.environment());
_loaded = true;
notifyListeners();
@@ -131,25 +146,55 @@ class NotificationController extends ChangeNotifier {
/// Posts one notification per live transition, in order.
///
/// The initial seed raises no transition, so it never reaches here. A
/// transition the operator dismissed, one the ledger already recorded and one
/// past [maxNotificationsPerBatch] post nothing; every identity examined is
/// recorded first, so a later publish cannot repeat it. Returns how many
/// notifications the platform accepted.
/// [qualifying] is [notificationQualifyingKeys] for the *same* snapshot as
/// [transitions]: a transition whose run has left the state is stale and
/// neither posts nor records anything, then every recorded identity outside
/// [qualifying] is forgotten so the next gate can notify. Only the latest
/// entry per run+kind in a backlog is announced.
///
/// A caller that misses the leaving frame still gets the new transition: the
/// detector creates one instance per genuine transition, so an identity
/// announced earlier this session with a different instance is a new
/// occurrence; the same instance, and an identity loaded from the store before
/// this session, stay silent.
///
/// The initial seed raises no transition. A transition the operator dismissed,
/// one already recorded and one past [maxNotificationsPerBatch] post nothing.
/// Returns how many notifications the platform accepted.
int publishTransitions(
Iterable<AttentionTransition> transitions, {
required Set<String> qualifying,
Set<String> dismissed = const {},
}) {
if (_disposed) return 0;
var posted = 0;
var recorded = false;
var changed = false;
// A backlog may hold several entries for one run+kind; only the latest one
// describes the state that is current, so a coalesced burst notifies once.
final latest = <String, AttentionTransition>{};
for (final transition in transitions) {
latest[notificationIdentity(transition)] = transition;
}
for (final transition in latest.values) {
if (posted >= maxNotificationsPerBatch) break;
final identity = notificationIdentity(transition);
if (_ledger.hasNotified(identity)) continue;
_ledger = _ledger.recording(identity);
recorded = true;
if (dismissed.contains(transition.key)) continue;
// Older than the snapshot: the run already left this state.
if (!qualifying.contains(identity)) continue;
final announced = _announced[identity];
if (identical(announced, transition)) continue;
if (announced == null && _ledger.hasNotified(identity)) {
// Restored from the store before this session: adopt the instance so a
// republish is recognized, but do not announce it again.
_announced[identity] = transition;
continue;
}
// A new instance for an identity announced this session is a later entry.
if (!_ledger.hasNotified(identity)) {
_ledger = _ledger.recording(identity);
changed = true;
}
_announced[identity] = transition;
if (dismissed.contains(identity)) continue;
if (!canNotify) continue;
final open = onOpenRun;
final message = NotificationMessage(
@@ -172,18 +217,29 @@ class NotificationController extends ChangeNotifier {
_posted++;
}
}
if (recorded) unawaited(_persist(_ledger));
final pruned = _ledger.pruning(qualifying);
if (!identical(pruned, _ledger)) {
_ledger = pruned;
changed = true;
}
if (changed) unawaited(_persist(_ledger));
return posted;
}
/// Writes the ledger without ever throwing into the caller's frame.
Future<void> _persist(NotificationLedger ledger) async {
if (_disposed) return;
try {
await store.write(encodeNotificationLedger(ledger));
} catch (_) {
// The in-memory ledger still applies for this session.
}
/// Writes the ledger without ever throwing into the caller's frame, one write
/// at a time so their order matches the calls.
Future<void> _persist(NotificationLedger ledger) {
final encoded = encodeNotificationLedger(ledger);
final write = _writes.then((_) async {
if (_disposed) return;
try {
await store.write(encoded);
} catch (_) {
// The in-memory ledger still applies for this session.
}
});
_writes = write;
return write;
}
@override
@@ -1,6 +1,7 @@
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
@@ -8,34 +9,48 @@ import '../domain/attention_transitions.dart';
/// client rewrites the other's local state on a shared origin.
const notificationStorageKey = 'pipelines.next.notify.v1';
/// The marker that separates two transitions of one run and kind: the server's
/// own `finished_at` when it recorded one, else the run's creation time — the
/// same recency the attention surface orders by.
/// The identity of one announced transition: the run and kind, exactly the
/// attention surface's own key and the browser's `alertKey`.
///
/// A run that is retried and fails again carries a new marker, so its new
/// failure is a new identity and can notify once more; the same failure can
/// never notify twice.
String notificationMarker(JsonMap run) {
final finished = '${run['finished_at'] ?? ''}'.trim();
return finished.isNotEmpty ? finished : '${run['created_at'] ?? ''}'.trim();
}
/// 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 identity of one transition: run, kind and marker. The unit of dedupe.
String notificationIdentity(AttentionTransition transition) =>
'${transition.key}@${notificationMarker(transition.run)}';
/// 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<String> notificationQualifyingKeys(Iterable<JsonMap>? runs) {
final keys = <String>{};
for (final run in runs ?? const <JsonMap>[]) {
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 and decides whether one is new.
/// Persistence is the store's job.
/// 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 is never forgotten while the ledger lives, so publishing the same
/// transition list again is always idempotent. A genuinely new transition of the
/// same run and kind is a new identity because its marker changed (see
/// [notificationMarker]); the browser's in-session prune is deliberately not
/// reproduced, because a prune would let an already-announced transition that is
/// still in the caller's list be posted a second time.
/// 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 <String>{},
@@ -56,6 +71,18 @@ class NotificationLedger {
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<String> 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
@@ -69,6 +96,10 @@ String encodeNotificationLedger(NotificationLedger ledger) {
/// 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();
@@ -120,8 +120,7 @@ NotificationPermissionView notificationPermissionView(
final canRequest = state == NotificationPermissionState.notRequested;
final body = switch (state) {
NotificationPermissionState.unsupported => notificationUnsupportedCopy,
NotificationPermissionState.needsSecureContext =>
notificationInsecureCopy,
NotificationPermissionState.needsSecureContext => notificationInsecureCopy,
NotificationPermissionState.granted => notificationGrantedCopy,
NotificationPermissionState.denied => notificationDeniedCopy,
NotificationPermissionState.notRequested =>