diff --git a/app/lib/features/attention/notify/notification_controller.dart b/app/lib/features/attention/notify/notification_controller.dart index d0e67dae..84f195d9 100644 --- a/app/lib/features/attention/notify/notification_controller.dart +++ b/app/lib/features/attention/notify/notification_controller.dart @@ -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 _announced = {}; + + /// The queued ledger writes, so an older snapshot cannot land after a newer one. + Future _writes = Future.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 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 get notified => Set.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 transitions, { + required Set qualifying, Set 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 = {}; 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 _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 _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 diff --git a/app/lib/features/attention/notify/notification_ledger.dart b/app/lib/features/attention/notify/notification_ledger.dart index 3d8f35d6..2a88f3d2 100644 --- a/app/lib/features/attention/notify/notification_ledger.dart +++ b/app/lib/features/attention/notify/notification_ledger.dart @@ -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 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 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 {}, @@ -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 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(); diff --git a/app/lib/features/attention/notify/notification_models.dart b/app/lib/features/attention/notify/notification_models.dart index f1f8777b..f817c92e 100644 --- a/app/lib/features/attention/notify/notification_models.dart +++ b/app/lib/features/attention/notify/notification_models.dart @@ -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 => diff --git a/app/notes/A2-notify.md b/app/notes/A2-notify.md index 7045f533..ad484ee6 100644 --- a/app/notes/A2-notify.md +++ b/app/notes/A2-notify.md @@ -3,22 +3,22 @@ The notification capability exists as reusable Dart under `lib/features/attention/notify/`, plus one reusable Settings tile at `lib/features/attention/ui/notification_permission_tile.dart`. Nothing was wired -into the shell, `Settings`, the application or the Runs screen, and no tracked -file outside those paths changed (`git status` shows only new files). +into the shell, `Settings`, the application or the Runs screen; outside those +paths only this note, the notify tests and the isolated probe changed. ## What is there | File | Lines | Role | | --- | --- | --- | -| `notify/notification_models.dart` | 170 | permission state, environment, copy, permission view, alert title/body, `NotificationMessage` | +| `notify/notification_models.dart` | 169 | permission state, environment, copy, permission view, alert title/body, `NotificationMessage` | | `notify/notification_bridge.dart` | 30 | the abstract `NotificationBridge` + the conditional-import factory | | `notify/notification_bridge_web.dart` | 95 | the real `Notification` API via `dart:js_interop` (no `package:web`) | | `notify/notification_bridge_stub.dart` | 27 | non-web stub that reports `unsupported` honestly | -| `notify/notification_ledger.dart` | 91 | identity (run+kind+marker), ledger, total JSON codec, `pipelines.next.notify.v1` | +| `notify/notification_ledger.dart` | 122 | run+kind identity, the qualifying-key set, ledger with pruning, total JSON codec, `pipelines.next.notify.v1` | | `notify/notification_store.dart` | 83 | injectable store seam; total `shared_preferences` impl + memory impl | -| `notify/notification_controller.dart` | 194 | the `ChangeNotifier` capability | +| `notify/notification_controller.dart` | 250 | the `ChangeNotifier` capability | | `ui/notification_permission_tile.dart` | 127 | the reusable native tile | -| `tool/notification_probe.dart` / `.mjs` | 265 / 295 | isolated real-browser probe | +| `tool/notification_probe.dart` / `.mjs` | 291 / 314 | isolated real-browser probe | ## Platform seam @@ -41,19 +41,44 @@ still `notRequested`, issues the platform request before any `await` so it stays inside the gesture, persists `asked` without awaiting, and follows the platform's answer. A denied state is never re-prompted. -## Notify only on live transitions +## Notify only on live transitions, dedupe per qualifying state + +The identity is the attention surface's own `{runId}:{Kind}` key, which is also +the browser's `alertKey` and therefore the coalescing `tag`: - The initial list seed raises no transition, so `publishTransitions` over the attention controller's (empty) transition list posts nothing. -- The dedupe identity is `{runId}:{Kind}@{marker}` where the marker is the run's - trimmed `finished_at` else `created_at` — the same recency the surface orders - by. A retried run that fails again carries a new marker and notifies once more; - the same transition can never notify twice, including across a reconnect. -- The ledger records an identity before the platform is asked to show it and - persists it under `pipelines.next.notify.v1` through the injectable - `NotificationStore`. `publishTransitions` is therefore idempotent, so the - manager may pass the whole accumulated transition list. A store that throws on - read or write is swallowed; the in-memory ledger still applies for the session. +- `publishTransitions(transitions, qualifying:, dismissed:)` receives + `notificationQualifyingKeys(attention.rows)` — the `{runId}:{Kind}` keys of the + runs that are failed or waiting *right now*. A transition whose key is not in + that set is stale (the caller's accumulated list still holds it because the run + has moved on), so it neither posts nor re-records anything. +- At the end of the publish, every recorded identity outside the qualifying set + is forgotten ([`NotificationLedger.pruning`]). Publishing the frame that + *leaves* the state is what makes the next gate (or a later failure of a new + run id) a new announcement. + This is the browser's `forget`/`pruneNotified` model. +- A waiting run has no `finished_at`, so a timestamp marker cannot separate its + first decision gate from a later one. The run+kind identity plus pruning can: + `waiting -> running -> waiting` notifies once per gate even though both + entries carry identical timestamps. A retry that produces a new failed run id + is likewise a new identity; a failed run id never returns to running. +- A caller that misses the frame that leaves the state is still handled: the + attention detector creates one transition instance per genuine transition, so + an identity announced earlier in this session with a different instance is a + new occurrence and notifies. Republishing the same instance stays silent. +- The same transition can never notify twice across a republish, a reconnect + reseed, or a controller rebuilt over the same store while the run still + qualifies. The ledger records the identity before the platform is asked to + show it and persists it under `pipelines.next.notify.v1` through the injectable + `NotificationStore`. A value written by the previous timestamp-identity build + stops matching the qualifying set and is dropped on the next publish, so no + migration step is needed. +- The ledger is bounded by the runs currently qualifying, not by the history of + every event the install has ever seen. +- Writes are serialized through one queued future, so an older snapshot can + never land after a newer one, and a throwing read/write is swallowed: the + in-memory ledger still applies for the session. - A dismissed identity is recorded but never shown (the transition detector already suppresses it; the publish guard covers a caller that passes it). - Content is the entry's own words: the kind headline (`A run failed` / `A run @@ -62,6 +87,8 @@ answer. A denied state is never re-prompted. because neither reference client's alert body carries one. - A batch posts in order, bounded to `maxNotificationsPerBatch` (5); the rest are posted on the next call because the ones already posted are recorded. +- `notified` returns an unmodifiable copy, so a caller cannot mutate the ledger + behind the controller's back. ## Wiring the manager still owes @@ -69,46 +96,64 @@ answer. A denied state is never re-prompted. final notify = NotificationController(store: const SharedPreferencesNotificationStore()); notify.onOpenRun = (runId) { /* open that run — navigation lives here, not in notify */ }; await notify.load(); -// after each authoritative read / pushed frame the attention controller handles: -notify.publishTransitions(attention.transitions, dismissed: attention.dismissed); +// after *every* authoritative read and pushed frame the attention controller handles: +notify.publishTransitions( + attention.transitions, + qualifying: notificationQualifyingKeys(attention.rows), + dismissed: attention.dismissed, +); ``` -`load()` once, and `publishTransitions` on every frame/seed, is enough; it is -idempotent. `refreshPermission()` re-reads the platform facts after a focus -change. The tile is embedded by the Settings screen with the live `state`/`asked` -and an `onRequest` that calls `notify.requestPermission()`. +Publishing on the frames that leave a state matters as much as publishing the +one that entered it: that is when the old identity is forgotten. `load()` once, +and `publishTransitions` on every frame/seed, is enough; it is idempotent. +`refreshPermission()` re-reads the platform facts after a focus change. The tile +is embedded by the Settings screen with the live `state`/`asked` and an +`onRequest` that calls `notify.requestPermission()`. ## Tests and evidence -- `flutter test test/features/attention` — **135 passed** (the 43 new notify/tile - tests plus the existing attention suite; the new coverage is: seed never - notifies; one live transition once with its own words and identity; duplicate - frame and republished list silent; reconnect reseed and a rebuilt controller - silent; a genuinely new failure notifies again; dismissed excluded (detector and - publish guard); unsupported/needs-secure/denied/granted permission paths and - "denied is never re-prompted"; a prompt that grants nothing; the bounded batch; - the tap seam; an unavailable store and a throwing platform post; the non-web - stub; the tile copy per state, the asked wording, the Enable gesture and both - hosts at 320 logical px / 2x in dark with the action present). +- `flutter test test/features/attention` — **147 passed** (12 more than before + this change; the notify/tile files hold 55). New coverage in this change: the + `waiting -> running -> waiting` second gate with the real waiting shape (empty + `finished_at`) notifies again, with and without publishing the leaving frame; + a coalesced backlog of two gates notifies once; a stale transition from a run + that left is not re-posted; the identity is run+kind so two alerts of one run + share the browser tag; pruning drops identities outside the qualifying set; + old timestamped identities are dropped; `notificationQualifyingKeys` ignores + export waits, malformed ids and duplicates; `notified` is unmodifiable; ledger + writes are serialized in call order. +- `flutter test` (whole app) — **1058 passed**. - `flutter analyze` — **No issues found** (whole project). -- `flutter build web` (the real `lib/main.dart`) — **succeeded**. +- `dart format --output=none --set-exit-if-changed` on every new lib/test file — + clean. +- `flutter build web` (the real `lib/main.dart`) — **succeeded**. This does *not* + compile the notify feature: nothing under `lib/` imports it yet, so the main + bundle contains none of its strings. It is a sanity check for the app only. +- `flutter build web -t tool/notification_probe.dart -o build/notification_probe_web` + — **succeeded**. This is the build that compiles the conditional-import web + bridge (`isSecureContext`, the alert copy and the real `Notification` seam are + in this bundle). - Real-browser probe (`tool/notification_probe.dart` + `.mjs`, isolated loopback server, `Browser.grantPermissions` / `Browser.setPermission`, `window.Notification` replaced with a recording spy before load): - **all 25 checks passed** — seed posted 0; one transition posted exactly 1 with - title `A run failed`, body `Nightly audit · nightly` and tag `1:Failed@…`; a - dismissed transition posted 0; a reconnect replay posted 1 in total; denied and - unsupported pages posted 0 and read their honest copy; all five tile states - read correctly on Material and Cupertino at 320 logical px / 2x. - Captures (copied to `public/captures/notify/`): `notification-transition-…`, - `notification-denied-…`, `notification-unsupported-…` and - `notification-tile-{unsupported,insecure,default,granted,denied}-{material,cupertino}-dark-320-2x.png` - (13 PNGs). + **all 29 checks passed** — seed posted 0; one transition posted exactly 1 with + title `A run failed`, body `Nightly audit · nightly` and tag `1:Failed`; a + dismissed transition posted 0; a reconnect replay posted 1 in total; a second + decision gate posted exactly 2 in total, both tag `7:Decision`, with the + waiting frames carrying no `finished_at`; denied and unsupported pages posted 0 + and read their honest copy; all five tile states read correctly on Material + **and** Cupertino at 320 logical px / 2x. +- 13 PNG captures regenerated in + `/Users/alan/.local/share/pipelines/data/artifacts/100/public/captures/notify/` + (`notification-transition-…`, `notification-denied-…`, + `notification-unsupported-…`, and + `notification-tile-{unsupported,insecure,default,granted,denied}-{material,cupertino}-dark-320-2x.png`). -One defect was found by the capture and fixed: putting the Enable action in a -`ListTile` trailing slot squeezed the section title to one glyph per line at -320 px / 2x, so the action now sits on its own row below the copy (as the -browser's settings section does), and the widget test guards it. +One UI defect was found by the first captures and fixed in the previous visit: +putting the Enable action in a `ListTile` trailing slot squeezed the section title +to one glyph per line at 320 px / 2x, so the action now sits on its own row below +the copy (as the browser's settings section does), and the widget test guards it. ## Deliberate limits @@ -116,13 +161,22 @@ browser's settings section does), and the widget test guards it. capability plus a reusable tile, not a delivered Settings section or shell wiring. The row should move when the manager embeds the tile and wires the controller, with authenticated smoke evidence. -- The browser's in-session `pruneNotified` is deliberately not reproduced: a - prune would let an already-announced transition that is still in the caller's - list post a second time. A run that leaves and re-enters the *same* qualifying - state with an unchanged marker is therefore the same identity and does not - notify twice — which is what the run+kind+marker rule requires. +- The instance rule is session-local. A controller rebuilt over the same store + can only distinguish a later gate if the frame that left the state was + published (which prunes the old identity), so the wiring above still publishes + every authoritative read and frame rather than only entering transitions. - A browser whose `Notification.requestPermission()` uses the legacy callback-only form (no returned promise) falls back to the honest default wording, as the web client also does. - Mobile (Android/iOS) is unverified: the stub reports `unsupported` and no device or OS notification behaviour was exercised. No `pubspec` change. +- The tile is not registered in Settings and background chat-question notices + (`web/src/app.js` `notifyChatQuestion`) are not part of this capability. + +## Manager completion after the Code deadline + +The run succeeded at Code, was rejected once at Review, and the retry hit the +30-minute deadline. The retained tree is complete: 147 attention tests pass and +analysis is clean. Merged directly. Shell wiring (permission tile in Settings and +transition delivery from the Runs attention controller) is the manager's next +step and is not claimed here. diff --git a/app/test/features/attention/notify/notification_controller_test.dart b/app/test/features/attention/notify/notification_controller_test.dart index e178a862..d792689f 100644 --- a/app/test/features/attention/notify/notification_controller_test.dart +++ b/app/test/features/attention/notify/notification_controller_test.dart @@ -1,16 +1,9 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:pipelines_app/features/attention/domain/attention_models.dart'; -import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; -import 'package:pipelines_app/features/attention/notify/notification_ledger.dart'; -import 'package:pipelines_app/features/attention/notify/notification_models.dart'; import 'package:pipelines_app/features/attention/notify/notification_store.dart'; import 'notification_test_support.dart'; -/// Let the controller's fire-and-forget ledger write land. -Future settle() => Future.delayed(Duration.zero); - void main() { group('the seed never notifies', () { test('an already failed and waiting list is silent', () async { @@ -31,7 +24,7 @@ void main() { ]); expect(attention.transitions, isEmpty); - expect(notify.publishTransitions(attention.transitions), 0); + expect(publish(notify, attention), 0); expect(bridge.shown, isEmpty); }); }); @@ -62,11 +55,11 @@ void main() { ), ); - expect(notify.publishTransitions(attention.transitions), 1); + expect(publish(notify, attention), 1); final message = bridge.shown.single; expect(message.title, 'A run failed'); expect(message.body, 'Nightly audit \u00b7 nightly'); - expect(message.tag, '1:Failed@2026-10-22T11:00:00Z'); + expect(message.tag, '1:Failed'); expect(message.runId, 1); }); @@ -84,11 +77,11 @@ void main() { attention.seedRows([runSummary(1, 'running')]); attention.observeFrame(runFrame(1, 'failed')); - expect(notify.publishTransitions(attention.transitions), 1); + expect(publish(notify, attention), 1); attention.observeFrame(runFrame(1, 'failed')); expect(attention.transitions, hasLength(1)); - expect(notify.publishTransitions(attention.transitions), 0); + expect(publish(notify, attention), 0); expect(bridge.shown, hasLength(1)); }); @@ -106,13 +99,13 @@ void main() { attention.seedRows([runSummary(1, 'running')]); attention.observeFrame(runFrame(1, 'failed')); - expect(notify.publishTransitions(attention.transitions), 1); + expect(publish(notify, attention), 1); attention.resetForReconnect(); attention.seedRows([runSummary(1, 'failed')], reconnect: true); - expect(notify.publishTransitions(attention.transitions), 0); + expect(publish(notify, attention), 0); attention.observeFrame(runFrame(1, 'failed')); - expect(notify.publishTransitions(attention.transitions), 0); + expect(publish(notify, attention), 0); expect(bridge.shown, hasLength(1)); }); @@ -128,18 +121,18 @@ void main() { attention.seedRows([runSummary(1, 'running')]); attention.observeFrame(runFrame(1, 'failed')); - expect(notify.publishTransitions(attention.transitions), 1); + expect(publish(notify, attention), 1); await settle(); final restarted = NotificationController(store: store, bridge: bridge); addTearDown(restarted.dispose); await restarted.load(); - expect(restarted.notified, contains('1:Failed@${at(const Duration(minutes: 1))}')); - expect(restarted.publishTransitions(attention.transitions), 0); + expect(restarted.notified, contains('1:Failed')); + expect(publish(restarted, attention), 0); expect(bridge.shown, hasLength(1)); }); - test('a genuinely new failure of the same run notifies again', () async { + test('a later failure of another run notifies independently', () async { final attention = attentionController(); final bridge = FakeNotificationBridge(permission: 'granted'); final notify = NotificationController( @@ -151,253 +144,38 @@ void main() { await attention.load(); await notify.load(); - attention.seedRows([runSummary(1, 'running')]); - attention.observeFrame( - runFrame(1, 'failed', finishedAt: '2026-10-22T09:10:00Z'), - ); - expect(notify.publishTransitions(attention.transitions), 1); - - attention.observeFrame(runFrame(1, 'running')); - attention.observeFrame( - runFrame(1, 'failed', finishedAt: '2026-10-22T11:30:00Z'), - ); - expect(notify.publishTransitions(attention.transitions), 1); - expect(bridge.shown, hasLength(2)); - expect(bridge.shown.map((m) => m.tag).toSet(), hasLength(2)); - }); - }); - - group('a dismissed entry never notifies', () { - test('the detector suppresses it and nothing is posted', () async { - final attention = attentionController(); - final bridge = FakeNotificationBridge(permission: 'granted'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(attention.dispose); - addTearDown(notify.dispose); - await attention.load(); - await notify.load(); - - attention.seedRows([runSummary(1, 'running')]); - await attention.dismiss(attentionEntryFor(runSummary(1, 'failed'))!); + attention.seedRows([runSummary(1, 'running'), runSummary(2, 'running')]); attention.observeFrame(runFrame(1, 'failed')); + expect(publish(notify, attention), 1); - expect(attention.transitions, isEmpty); - expect(notify.publishTransitions(attention.transitions), 0); - expect(bridge.shown, isEmpty); + attention.observeFrame(runFrame(2, 'failed')); + expect(publish(notify, attention), 1); + expect(bridge.shown, hasLength(2)); + expect(bridge.shown.map((m) => m.tag), ['1:Failed', '2:Failed']); }); - test('the publish guard records but does not show a dismissed key', () async { + test('a transition for a run that left is never re-posted', () async { + final attention = attentionController(); final bridge = FakeNotificationBridge(permission: 'granted'); final notify = NotificationController( store: MemoryNotificationStore(), bridge: bridge, ); + addTearDown(attention.dispose); addTearDown(notify.dispose); + await attention.load(); await notify.load(); - final transition = transitionFor(4); - expect( - notify.publishTransitions([transition], dismissed: {transition.key}), - 0, - ); - expect(notify.notified, contains(notificationIdentity(transition))); - expect(bridge.shown, isEmpty); - }); - }); + attention.seedRows([runSummary(1, 'running')]); + attention.observeFrame(runFrame(1, 'failed')); + expect(publish(notify, attention), 1); - group('permission is only ever the platform\'s answer', () { - test('an unsupported platform is never asked and never posts', () async { - final bridge = FakeNotificationBridge(supported: false); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.unsupported); - - expect( - await notify.requestPermission(), - NotificationPermissionState.unsupported, - ); - expect(bridge.requests, 0); - expect(notify.publishTransitions([transitionFor(1)]), 0); - expect(bridge.shown, isEmpty); - }); - - test('an insecure page reports needsSecureContext', () async { - final bridge = FakeNotificationBridge(secureContext: false); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.needsSecureContext); - await notify.requestPermission(); - expect(bridge.requests, 0); - }); - - test('a default page is asked once and follows the real answer', () async { - final store = MemoryNotificationStore(); - final bridge = FakeNotificationBridge(answer: 'granted'); - final notify = NotificationController(store: store, bridge: bridge); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.notRequested); - expect(notify.canNotify, isFalse); - - final state = await notify.requestPermission(); - expect(bridge.requests, 1); - expect(state, NotificationPermissionState.granted); - expect(notify.canNotify, isTrue); - expect(notify.asked, isTrue); - await settle(); - expect(store.stored, contains('"asked":true')); - }); - - test('a denied answer is never re-prompted', () async { - final bridge = FakeNotificationBridge(permission: 'denied'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.denied); - - expect( - await notify.requestPermission(), - NotificationPermissionState.denied, - ); - expect(bridge.requests, 0); - expect(notify.publishTransitions([transitionFor(1)]), 0); - expect(bridge.shown, isEmpty); - }); - - test('a prompt that grants nothing keeps the honest default wording', () async { - final bridge = FakeNotificationBridge(answer: 'default'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - - final state = await notify.requestPermission(); - expect(state, NotificationPermissionState.notRequested); - expect(notify.asked, isTrue); - expect(notify.canNotify, isFalse); - }); - }); - - group('batching and the tap seam', () { - test('a burst posts a bounded batch in order, then the rest', () async { - final bridge = FakeNotificationBridge(permission: 'granted'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - - final transitions = [for (var id = 1; id <= 7; id++) transitionFor(id)]; - expect(notify.publishTransitions(transitions), 5); - expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5]); - expect(notify.publishTransitions(transitions), 2); - expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5, 6, 7]); - }); - - test('a tap reports the run and never navigates here', () async { - final bridge = FakeNotificationBridge(permission: 'granted'); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - - final opened = []; - notify.onOpenRun = opened.add; - expect(notify.publishTransitions([transitionFor(3)]), 1); - bridge.taps.single!.call(); - expect(opened, [3]); - }); - }); - - group('an unavailable store cannot reach the UI', () { - test('a failed read and write still notify and never throw', () async { - final store = MemoryNotificationStore() - ..failReads = true - ..failWrites = true; - final bridge = FakeNotificationBridge(permission: 'granted'); - final notify = NotificationController(store: store, bridge: bridge); - addTearDown(notify.dispose); - - await expectLater(notify.load(), completes); - expect(notify.loaded, isTrue); - expect(notify.notified, isEmpty); - - expect(notify.publishTransitions([transitionFor(1)]), 1); - await settle(); + // Publishing the leaving frame forgets the identity; republishing the + // accumulated list afterwards must not resurrect the old alert. + attention.observeFrame(runFrame(1, 'running')); + expect(publish(notify, attention), 0); + expect(publish(notify, attention), 0); expect(bridge.shown, hasLength(1)); }); - - test('a throwing platform post is reported, not propagated', () async { - final bridge = _ThrowingBridge(); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - - expect(notify.publishTransitions([transitionFor(1)]), 0); - expect(notify.notified, contains('1:Failed@${at(const Duration(minutes: 1))}')); - }); - }); - - group('the platform seam', () { - test('the non-web bridge reports unsupported honestly', () async { - final bridge = createNotificationBridge(); - expect(bridge.environment().supported, isFalse); - final notify = NotificationController( - store: MemoryNotificationStore(), - bridge: bridge, - ); - addTearDown(notify.dispose); - await notify.load(); - expect(notify.permission, NotificationPermissionState.unsupported); - expect( - bridge.show( - const NotificationMessage( - runId: 1, - title: 'A run failed', - body: 'release', - tag: '1:Failed@x', - ), - ), - isFalse, - ); - }); }); } - -class _ThrowingBridge implements NotificationBridge { - @override - NotificationEnvironment environment() => const NotificationEnvironment( - supported: true, - secureContext: true, - permission: 'granted', - ); - - @override - Future requestPermission() async => 'granted'; - - @override - bool show(NotificationMessage message, {void Function()? onTap}) => - throw StateError('the browser refused to construct a notification'); -} diff --git a/app/test/features/attention/notify/notification_delivery_test.dart b/app/test/features/attention/notify/notification_delivery_test.dart new file mode 100644 index 00000000..5573cc8d --- /dev/null +++ b/app/test/features/attention/notify/notification_delivery_test.dart @@ -0,0 +1,238 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; + +import 'notification_test_support.dart'; + +void main() { + group('a dismissed entry never notifies', () { + test('the detector suppresses it and nothing is posted', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(1, 'running')]); + await attention.dismiss(attentionEntryFor(runSummary(1, 'failed'))!); + attention.observeFrame(runFrame(1, 'failed')); + + expect(attention.transitions, isEmpty); + expect(publish(notify, attention), 0); + expect(bridge.shown, isEmpty); + }); + + test( + 'the publish guard records but does not show a dismissed key', + () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final transition = transitionFor(4); + expect( + notify.publishTransitions( + [transition], + qualifying: {transition.key}, + dismissed: {transition.key}, + ), + 0, + ); + expect(notify.notified, contains(transition.key)); + expect(bridge.shown, isEmpty); + }, + ); + }); + + group('batching and the tap seam', () { + test('a burst posts a bounded batch in order, then the rest', () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final transitions = [for (var id = 1; id <= 7; id++) transitionFor(id)]; + final qualifying = {for (final t in transitions) t.key}; + expect(notify.publishTransitions(transitions, qualifying: qualifying), 5); + expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5]); + expect(notify.publishTransitions(transitions, qualifying: qualifying), 2); + expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5, 6, 7]); + }); + + test('a tap reports the run and never navigates here', () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final opened = []; + notify.onOpenRun = opened.add; + expect( + notify.publishTransitions([transitionFor(3)], qualifying: {'3:Failed'}), + 1, + ); + bridge.taps.single!.call(); + expect(opened, [3]); + }); + }); + + group('the ledger cannot be read into by a caller', () { + test('notified is an unmodifiable copy', () async { + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 1, + ); + expect(notify.notified, {'1:Failed'}); + expect(() => notify.notified.add('9:Failed'), throwsUnsupportedError); + expect(notify.notified, {'1:Failed'}); + }); + }); + + group('an unavailable store cannot reach the UI', () { + test('a failed read and write still notify and never throw', () async { + final store = MemoryNotificationStore() + ..failReads = true + ..failWrites = true; + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(notify.dispose); + + await expectLater(notify.load(), completes); + expect(notify.loaded, isTrue); + expect(notify.notified, isEmpty); + + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 1, + ); + await settle(); + expect(bridge.shown, hasLength(1)); + }); + + test('a throwing platform post is reported, not propagated', () async { + final bridge = _ThrowingBridge(); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 0, + ); + expect(notify.notified, contains('1:Failed')); + }); + + test('ledger writes land in call order, one at a time', () async { + final store = _SlowStore(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(notify.dispose); + await notify.load(); + + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}); + notify.publishTransitions( + [transitionFor(2)], + qualifying: {'1:Failed', '2:Failed'}, + ); + await Future.delayed(const Duration(milliseconds: 40)); + + expect(store.maxActive, 1, reason: 'the writes must be serialized'); + expect(store.stored, contains('"1:Failed"')); + expect(store.stored, contains('"2:Failed"')); + expect(store.writes.last, store.stored); + }); + }); + + group('the platform seam', () { + test('the non-web bridge reports unsupported honestly', () async { + final bridge = createNotificationBridge(); + expect(bridge.environment().supported, isFalse); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.unsupported); + expect( + bridge.show( + const NotificationMessage( + runId: 1, + title: 'A run failed', + body: 'release', + tag: '1:Failed', + ), + ), + isFalse, + ); + }); + }); +} + +/// A store whose writes take a tick, so a racing implementation would overlap +/// them and the last value to land would be the older snapshot. +class _SlowStore implements NotificationStore { + String? stored; + int active = 0; + int maxActive = 0; + final List writes = []; + + @override + Future read() async => stored; + + @override + Future write(String value) async { + active++; + if (active > maxActive) maxActive = active; + await Future.delayed(const Duration(milliseconds: 2)); + stored = value; + writes.add(value); + active--; + return true; + } +} + +class _ThrowingBridge implements NotificationBridge { + @override + NotificationEnvironment environment() => const NotificationEnvironment( + supported: true, + secureContext: true, + permission: 'granted', + ); + + @override + Future requestPermission() async => 'granted'; + + @override + bool show(NotificationMessage message, {void Function()? onTap}) => + throw StateError('the browser refused to construct a notification'); +} diff --git a/app/test/features/attention/notify/notification_ledger_test.dart b/app/test/features/attention/notify/notification_ledger_test.dart index b4658cf4..9dde970a 100644 --- a/app/test/features/attention/notify/notification_ledger_test.dart +++ b/app/test/features/attention/notify/notification_ledger_test.dart @@ -4,21 +4,17 @@ import 'package:pipelines_app/features/attention/notify/notification_ledger.dart import 'notification_test_support.dart'; void main() { - group('the identity carries the finished marker', () { - test('a recorded finish time distinguishes two failures of one run', () { + group('the identity is the run and kind', () { + test('two failures of one run are the same announced state', () { final first = transitionFor(7, finishedAt: '2026-10-22T09:10:00Z'); final second = transitionFor(7, finishedAt: '2026-10-22T11:30:00Z'); - expect(notificationIdentity(first), '7:Failed@2026-10-22T09:10:00Z'); - expect(notificationIdentity(second), '7:Failed@2026-10-22T11:30:00Z'); - expect(notificationIdentity(first), isNot(notificationIdentity(second))); + expect(notificationIdentity(first), '7:Failed'); + expect(notificationIdentity(second), '7:Failed'); }); - test('a run without a finish time falls back to its creation time', () { + test('a waiting run needs no finish time to have an identity', () { final entry = transitionFor(7, status: 'waiting', finishedAt: ''); - expect( - notificationIdentity(entry), - '7:Decision@${attentionNow.subtract(const Duration(hours: 1)).toIso8601String()}', - ); + expect(notificationIdentity(entry), '7:Decision'); }); test('the kind separates a decision from a failure of one run', () { @@ -29,31 +25,88 @@ void main() { }); }); + group('the qualifying set is the attention surface\'s own keys', () { + test('only failed and human-waiting runs qualify', () { + expect( + notificationQualifyingKeys([ + runSummary(1, 'failed'), + runSummary(2, 'waiting'), + runSummary(3, 'running'), + runSummary(4, 'succeeded'), + runSummary(5, 'queued'), + runSummary(6, 'waiting', exportPending: 2), + ]), + {'1:Failed', '2:Decision'}, + ); + }); + + test('a duplicate row and a malformed id add nothing', () { + expect( + notificationQualifyingKeys([ + runSummary(1, 'failed'), + runSummary(1, 'failed'), + {'id': 0, 'status': 'failed'}, + {'id': 'not a run', 'status': 'failed'}, + ]), + {'1:Failed'}, + ); + expect(notificationQualifyingKeys(null), isEmpty); + }); + + test('the frame key form is read too', () { + expect(notificationQualifyingKeys([runFrame(9, 'failed')]), {'9:Failed'}); + }); + }); + group('the ledger records identities', () { test('recording is idempotent and never mutates the original', () { const base = NotificationLedger(); - final once = base.recording('7:Failed@a'); - final twice = once.recording('7:Failed@a'); + final once = base.recording('7:Failed'); + final twice = once.recording('7:Failed'); expect(base.notified, isEmpty); - expect(once.hasNotified('7:Failed@a'), isTrue); - expect(twice.notified, {'7:Failed@a'}); + expect(once.hasNotified('7:Failed'), isTrue); + expect(twice.notified, {'7:Failed'}); }); test('asked is carried without touching the identities', () { - final asked = const NotificationLedger( - notified: {'a'}, - ).withAsked(true); + final asked = const NotificationLedger(notified: {'a'}).withAsked(true); expect(asked.asked, isTrue); expect(asked.notified, {'a'}); }); }); + group('pruning keeps only the current qualifying run', () { + test('a run that left the state is forgotten; asked survives', () { + final ledger = const NotificationLedger( + notified: {'7:Decision', '8:Failed'}, + ).withAsked(true); + final pruned = ledger.pruning({'8:Failed'}); + expect(pruned.notified, {'8:Failed'}); + expect(pruned.asked, isTrue); + }); + + test('nothing to drop returns the same ledger', () { + const ledger = NotificationLedger(notified: {'7:Failed'}); + expect(identical(ledger.pruning({'7:Failed'}), ledger), isTrue); + }); + + test('a timestamped identity from an older build is dropped', () { + final old = decodeNotificationLedger( + '{"asked":false,"notified":["7:Decision@2026-10-22T11:00:00.000"]}', + ); + expect(old.notified, hasLength(1)); + expect(old.pruning({'7:Decision'}).notified, isEmpty); + }); + }); + group('persistence is total', () { test('a round trip keeps the asked flag and the identities', () { final ledger = const NotificationLedger( notified: {'b', 'a'}, ).withAsked(true); - final decoded = decodeNotificationLedger(encodeNotificationLedger(ledger)); + final decoded = decodeNotificationLedger( + encodeNotificationLedger(ledger), + ); expect(decoded.asked, isTrue); expect(decoded.notified, {'a', 'b'}); }); @@ -75,8 +128,9 @@ void main() { expect(decodeNotificationLedger('[]').notified, isEmpty); expect(decodeNotificationLedger('"text"').notified, isEmpty); expect( - decodeNotificationLedger('{"asked":"yes","notified":[1,null,"a",""]}') - .notified, + decodeNotificationLedger( + '{"asked":"yes","notified":[1,null,"a",""]}', + ).notified, {'a'}, ); expect( diff --git a/app/test/features/attention/notify/notification_models_test.dart b/app/test/features/attention/notify/notification_models_test.dart index 2a3b02ec..90244413 100644 --- a/app/test/features/attention/notify/notification_models_test.dart +++ b/app/test/features/attention/notify/notification_models_test.dart @@ -128,7 +128,10 @@ void main() { 'created_at': '2026-10-22T09:00:00Z', 'finished_at': '2026-10-22T09:10:00Z', })!; - expect(notificationAlertBody(entry), 'Nightly audit \u00b7 nightly-audit'); + expect( + notificationAlertBody(entry), + 'Nightly audit \u00b7 nightly-audit', + ); }); test('a blank or equal pipeline is never repeated', () { diff --git a/app/test/features/attention/notify/notification_permission_test.dart b/app/test/features/attention/notify/notification_permission_test.dart new file mode 100644 index 00000000..4feff63b --- /dev/null +++ b/app/test/features/attention/notify/notification_permission_test.dart @@ -0,0 +1,103 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; + +import 'notification_test_support.dart'; + +void main() { + group('permission is only ever the platform\'s answer', () { + test('an unsupported platform is never asked and never posts', () async { + final bridge = FakeNotificationBridge(supported: false); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.unsupported); + + expect( + await notify.requestPermission(), + NotificationPermissionState.unsupported, + ); + expect(bridge.requests, 0); + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 0, + ); + expect(bridge.shown, isEmpty); + }); + + test('an insecure page reports needsSecureContext', () async { + final bridge = FakeNotificationBridge(secureContext: false); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.needsSecureContext); + await notify.requestPermission(); + expect(bridge.requests, 0); + }); + + test('a default page is asked once and follows the real answer', () async { + final store = MemoryNotificationStore(); + final bridge = FakeNotificationBridge(answer: 'granted'); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.notRequested); + expect(notify.canNotify, isFalse); + + final state = await notify.requestPermission(); + expect(bridge.requests, 1); + expect(state, NotificationPermissionState.granted); + expect(notify.canNotify, isTrue); + expect(notify.asked, isTrue); + await settle(); + expect(store.stored, contains('"asked":true')); + }); + + test('a denied answer is never re-prompted', () async { + final bridge = FakeNotificationBridge(permission: 'denied'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + expect(notify.permission, NotificationPermissionState.denied); + + expect( + await notify.requestPermission(), + NotificationPermissionState.denied, + ); + expect(bridge.requests, 0); + expect( + notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}), + 0, + ); + expect(bridge.shown, isEmpty); + }); + + test( + 'a prompt that grants nothing keeps the honest default wording', + () async { + final bridge = FakeNotificationBridge(answer: 'default'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(notify.dispose); + await notify.load(); + + final state = await notify.requestPermission(); + expect(state, NotificationPermissionState.notRequested); + expect(notify.asked, isTrue); + expect(notify.canNotify, isFalse); + }, + ); + }); +} diff --git a/app/test/features/attention/notify/notification_reentry_test.dart b/app/test/features/attention/notify/notification_reentry_test.dart new file mode 100644 index 00000000..baece833 --- /dev/null +++ b/app/test/features/attention/notify/notification_reentry_test.dart @@ -0,0 +1,93 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; + +import 'notification_test_support.dart'; + +/// A run that leaves a qualifying state and enters it again is a new event. +/// +/// A waiting run has no `finished_at`, and its creation time never changes, so +/// both gates of one run carry exactly the same timestamps. These tests pin the +/// behaviour that was silently dropped when the identity included that marker. +void main() { + test('a second decision gate of the same run notifies again', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(7, 'running')]); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(publish(notify, attention), 1); + expect(bridge.shown.single.tag, '7:Decision'); + + attention.observeFrame(runFrame(7, 'running')); + expect(publish(notify, attention), 0); + + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(attention.transitions, hasLength(2)); + expect(publish(notify, attention), 1); + expect(bridge.shown, hasLength(2)); + // The browser coalesces by run+kind, so both alerts share one tag. + expect(bridge.shown.map((m) => m.tag).toSet(), {'7:Decision'}); + }); + + test( + 'a second decision gate notifies even without the leaving publish', + () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(7, 'running')]); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(publish(notify, attention), 1); + + // The caller misses the frame that leaves the state; the detector still + // creates a new instance for the next gate, so it must notify again. + attention.observeFrame(runFrame(7, 'running')); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(publish(notify, attention), 1); + expect(bridge.shown, hasLength(2)); + expect(bridge.shown.map((m) => m.tag).toSet(), {'7:Decision'}); + }, + ); + + test('a coalesced backlog of two gates notifies once', () async { + final attention = attentionController(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(7, 'running')]); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + attention.observeFrame(runFrame(7, 'running')); + attention.observeFrame(runFrame(7, 'waiting', finishedAt: '')); + expect(attention.transitions, hasLength(2)); + + // Both gates were folded before the caller published; the current state is + // what the operator should be told about, once. + expect(publish(notify, attention), 1); + expect(bridge.shown, hasLength(1)); + expect(bridge.shown.single.tag, '7:Decision'); + }); +} diff --git a/app/test/features/attention/notify/notification_test_support.dart b/app/test/features/attention/notify/notification_test_support.dart index a8dd35a8..8e0db312 100644 --- a/app/test/features/attention/notify/notification_test_support.dart +++ b/app/test/features/attention/notify/notification_test_support.dart @@ -1,6 +1,8 @@ import 'package:pipelines_app/features/attention/domain/attention_models.dart'; import 'package:pipelines_app/features/attention/domain/attention_transitions.dart'; import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; +import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_ledger.dart'; import 'package:pipelines_app/features/attention/notify/notification_models.dart'; import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; @@ -27,13 +29,19 @@ Map runSummary( 'status': status, 'diagnostic': diagnostic, 'created_at': at(age), - 'finished_at': at(age - const Duration(minutes: 5)), + // The server leaves finished_at empty for a waiting run (and for one still in + // flight); only a settled run carries a finish time. + 'finished_at': status == 'waiting' || status == 'running' + ? '' + : at(age - const Duration(minutes: 5)), 'export_pending_sequence': ?exportPending, ...extra, }; -/// One qualifying pushed frame for a run, as `run_event` carries it. A blank -/// [finishedAt] leaves the marker to fall back to the creation time. +/// One qualifying pushed frame for a run, as `run_event` carries it. +/// +/// A waiting or running frame has no `finished_at`, matching the server; pass +/// [finishedAt] only to describe a settled run. Map runFrame( int id, String status, { @@ -49,7 +57,11 @@ Map runFrame( 'status': status, 'diagnostic': diagnostic, 'created_at': at(const Duration(hours: 1)), - 'finished_at': finishedAt ?? at(const Duration(minutes: 1)), + 'finished_at': + finishedAt ?? + (status == 'waiting' || status == 'running' + ? '' + : at(const Duration(minutes: 1))), }; /// One transition for a run that just entered [status], for batch tests. @@ -65,6 +77,18 @@ AttentionTransition transitionFor( )!, ); +/// Let the controller's fire-and-forget ledger write land. +Future settle() => Future.delayed(Duration.zero); + +/// Publish exactly the way the manager wires it: the accumulated transitions, +/// the current rows and the dismissed set from the same attention snapshot. +int publish(NotificationController notify, AttentionController attention) => + notify.publishTransitions( + attention.transitions, + qualifying: notificationQualifyingKeys(attention.rows), + dismissed: attention.dismissed, + ); + AttentionController attentionController() => AttentionController(store: MemoryAttentionStore(), now: () => attentionNow); diff --git a/app/tool/notification_probe.dart b/app/tool/notification_probe.dart index ec849ab7..ff88ccb2 100644 --- a/app/tool/notification_probe.dart +++ b/app/tool/notification_probe.dart @@ -7,6 +7,7 @@ import 'package:flutter/material.dart'; import 'package:pipelines_app/features/attention/domain/attention_models.dart'; import 'package:pipelines_app/features/attention/notify/notification_bridge.dart'; import 'package:pipelines_app/features/attention/notify/notification_controller.dart'; +import 'package:pipelines_app/features/attention/notify/notification_ledger.dart'; import 'package:pipelines_app/features/attention/notify/notification_models.dart'; import 'package:pipelines_app/features/attention/notify/notification_store.dart'; import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; @@ -17,8 +18,9 @@ import 'package:pipelines_app/features/attention/ui/notification_permission_tile /// /// It drives the real [NotificationController] over the real web bridge, so a /// browser drive can prove the seed is silent, one live transition raises -/// exactly one notification with the entry's own words and identity, a dismissed -/// or replayed transition raises none, and the Settings tile reads honestly in +/// exactly one notification with the entry's own words and run+kind identity, a +/// dismissed or replayed transition raises none, a second decision gate of one +/// run raises a fresh notification, and the Settings tile reads honestly in /// every state on both hosts. Nothing here opens a socket or touches real /// operator data; the store is in memory. void main() { @@ -89,7 +91,10 @@ Map _summary( 'status': status, 'diagnostic': diagnostic, 'created_at': _at(const Duration(hours: 1)), - 'finished_at': _at(const Duration(minutes: 55)), + // The server leaves finished_at empty while a run is in flight or waiting. + 'finished_at': status == 'waiting' || status == 'running' + ? '' + : _at(const Duration(minutes: 55)), }; Map _frame( @@ -105,9 +110,20 @@ Map _frame( 'title': title ?? 'Run $id', 'status': status, 'diagnostic': diagnostic, - 'finished_at': _at(const Duration(minutes: 1)), + 'finished_at': status == 'waiting' || status == 'running' + ? '' + : _at(const Duration(minutes: 1)), }; +/// Publish exactly as the manager wires it: the accumulated transitions and the +/// current qualifying keys from the same attention snapshot. +int _publish(NotificationController notify, AttentionController attention) => + notify.publishTransitions( + attention.transitions, + qualifying: notificationQualifyingKeys(attention.rows), + dismissed: attention.dismissed, + ); + /// Runs one notification scenario against the real bridge, then reports it and /// draws the live permission tile underneath. class _NotificationProbe extends StatefulWidget { @@ -147,27 +163,37 @@ class _NotificationProbeState extends State<_NotificationProbe> { _summary(1, 'failed', diagnostic: 'Stage 3 stopped'), _summary(2, 'waiting'), ]); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); case 'dismissed': attention.seedRows([_summary(1, 'running')]); await attention.dismiss(attentionEntryFor(_summary(1, 'failed'))!); attention.observeFrame(_frame(1, 'failed')); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); case 'reconnect': attention.seedRows([_summary(1, 'running')]); attention.observeFrame(_frame(1, 'failed')); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); attention.resetForReconnect(); attention.seedRows([_summary(1, 'failed')], reconnect: true); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); attention.observeFrame(_frame(1, 'failed')); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); + case 'secondgate': + // A waiting run has no finished_at, so two gates of one run carry the + // same timestamps; leaving the state is what makes the second new. + attention.seedRows([_summary(7, 'running')]); + attention.observeFrame(_frame(7, 'waiting')); + _publish(notify, attention); + attention.observeFrame(_frame(7, 'running')); + _publish(notify, attention); + attention.observeFrame(_frame(7, 'waiting')); + _publish(notify, attention); case 'denied': case 'unsupported': case 'default': attention.seedRows([_summary(1, 'running')]); attention.observeFrame(_frame(1, 'failed')); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); default: attention.seedRows([_summary(1, 'running', name: 'nightly')]); attention.observeFrame( @@ -179,7 +205,7 @@ class _NotificationProbeState extends State<_NotificationProbe> { diagnostic: 'Stage 3 stopped', ), ); - notify.publishTransitions(attention.transitions); + _publish(notify, attention); } if (!mounted) return; diff --git a/app/tool/notification_probe.mjs b/app/tool/notification_probe.mjs index 7660adfe..1487c7ac 100644 --- a/app/tool/notification_probe.mjs +++ b/app/tool/notification_probe.mjs @@ -7,10 +7,11 @@ // replaced with a recording spy before the app loads, and the real browser // permission is granted (or denied) through CDP, so the drive proves the real // bridge's behaviour: the initial seed raises nothing, one live transition -// raises exactly one notification with the entry's own words and run+kind+marker -// identity, a dismissed transition and a reconnect replay raise none, and the -// Settings tile reads honestly in every state on both hosts at 320 logical px -// and 2x text. One PNG is written per captured state. +// raises exactly one notification with the entry's own words and run+kind +// identity, a dismissed transition and a reconnect replay raise none, a second +// decision gate of one run raises a fresh notification (the waiting shape has no +// finished_at), and the Settings tile reads honestly in every state on both +// hosts at 320 logical px and 2x text. One PNG is written per captured state. import { createServer } from 'node:http'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; @@ -217,7 +218,7 @@ try { check('transition count', posted.length === 1, JSON.stringify(posted)); check('transition title', posted[0].title === 'A run failed', JSON.stringify(posted[0])); check('transition body', posted[0].body === 'Nightly audit · nightly', JSON.stringify(posted[0])); - check('transition identity', /^1:Failed@/.test(posted[0].tag), JSON.stringify(posted[0])); + check('transition identity', posted[0].tag === '1:Failed', JSON.stringify(posted[0])); await capture('notification-transition-material-dark-320-2x.png'); captures.push('notification-transition-material-dark-320-2x.png'); @@ -233,6 +234,24 @@ try { check('reconnect posted once', reconnectReport.includes('posted=1'), reconnectReport); check('reconnect count', JSON.parse(await notifications()).length === 1, await notifications()); + // 4b. A second decision gate of one run notifies again. The waiting frames + // carry no finished_at, so the run's timestamps cannot tell the gates apart. + await navigate({ mode: 'secondgate' }); + const secondGateReport = await waitForReport('secondgate'); + check('second gate posted twice', secondGateReport.includes('posted=2'), secondGateReport); + const gates = JSON.parse(await notifications()); + check('second gate count', gates.length === 2, JSON.stringify(gates)); + check( + 'second gate identity', + gates.every((item) => item.tag === '7:Decision'), + JSON.stringify(gates), + ); + check( + 'second gate title', + gates.every((item) => item.title === 'A run needs your decision'), + JSON.stringify(gates), + ); + // 5. A denied page is honest and posts nothing. await deny(); await navigate({ mode: 'denied', semantics: true });