From 77186042681273312d7f8519cc24c6964a2e9a3d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 01:23:24 +0100 Subject: [PATCH] feat(app): add the notification capability behind a platform seam An abstract NotificationBridge with a dart:js_interop web implementation and an honest unsupported stub; a NotificationController that reports only the platform's permission word, asks only from an explicit gesture, never re-prompts a denied answer, and notifies once per run+kind+finished marker under its own persisted ledger key. One reusable native NotificationPermissionTile for Settings, an isolated browser probe, and focused tests. No shell/settings wiring. --- .../attention/notify/notification_bridge.dart | 30 ++ .../notify/notification_bridge_stub.dart | 27 ++ .../notify/notification_bridge_web.dart | 95 +++++ .../notify/notification_controller.dart | 194 +++++++++ .../attention/notify/notification_ledger.dart | 91 ++++ .../attention/notify/notification_models.dart | 170 ++++++++ .../attention/notify/notification_store.dart | 83 ++++ .../ui/notification_permission_tile.dart | 127 ++++++ app/notes/A2-notify.md | 128 ++++++ .../notify/notification_controller_test.dart | 403 ++++++++++++++++++ .../notify/notification_ledger_test.dart | 89 ++++ .../notify/notification_models_test.dart | 155 +++++++ .../notify/notification_test_support.dart | 112 +++++ .../ui/notification_permission_tile_test.dart | 140 ++++++ app/tool/notification_probe.dart | 265 ++++++++++++ app/tool/notification_probe.mjs | 295 +++++++++++++ 16 files changed, 2404 insertions(+) create mode 100644 app/lib/features/attention/notify/notification_bridge.dart create mode 100644 app/lib/features/attention/notify/notification_bridge_stub.dart create mode 100644 app/lib/features/attention/notify/notification_bridge_web.dart create mode 100644 app/lib/features/attention/notify/notification_controller.dart create mode 100644 app/lib/features/attention/notify/notification_ledger.dart create mode 100644 app/lib/features/attention/notify/notification_models.dart create mode 100644 app/lib/features/attention/notify/notification_store.dart create mode 100644 app/lib/features/attention/ui/notification_permission_tile.dart create mode 100644 app/notes/A2-notify.md create mode 100644 app/test/features/attention/notify/notification_controller_test.dart create mode 100644 app/test/features/attention/notify/notification_ledger_test.dart create mode 100644 app/test/features/attention/notify/notification_models_test.dart create mode 100644 app/test/features/attention/notify/notification_test_support.dart create mode 100644 app/test/features/attention/ui/notification_permission_tile_test.dart create mode 100644 app/tool/notification_probe.dart create mode 100644 app/tool/notification_probe.mjs diff --git a/app/lib/features/attention/notify/notification_bridge.dart b/app/lib/features/attention/notify/notification_bridge.dart new file mode 100644 index 00000000..b1ec61bd --- /dev/null +++ b/app/lib/features/attention/notify/notification_bridge.dart @@ -0,0 +1,30 @@ +import 'notification_bridge_stub.dart' + if (dart.library.js_interop) 'notification_bridge_web.dart' + as impl; +import 'notification_models.dart'; + +/// Where the notification capability actually posts. +/// +/// The controller depends on this, not on any platform, so the dedupe, the +/// permission rules and the content are all testable without a browser. A bridge +/// answers the platform's real facts and never guesses: [environment] returns +/// what the platform says (including "unsupported"), [requestPermission] is only +/// called from an explicit gesture, and [show] reports whether the platform +/// accepted the notification. +abstract interface class NotificationBridge { + /// The platform's own facts: support, secure context and permission word. + NotificationEnvironment environment(); + + /// Asks the platform, from an explicit operator gesture, and returns its own + /// answer word. Never a guess, and never called by the controller on its own. + Future requestPermission(); + + /// Shows one notification, attaching [onTap] as its tap intent when given. + /// Returns whether the platform accepted it. + bool show(NotificationMessage message, {void Function()? onTap}); +} + +/// The bridge for the current platform: the browser `Notification` on the web, +/// an honest "unsupported" elsewhere. +NotificationBridge createNotificationBridge() => + impl.createNotificationBridge(); diff --git a/app/lib/features/attention/notify/notification_bridge_stub.dart b/app/lib/features/attention/notify/notification_bridge_stub.dart new file mode 100644 index 00000000..94e837ea --- /dev/null +++ b/app/lib/features/attention/notify/notification_bridge_stub.dart @@ -0,0 +1,27 @@ +import 'notification_bridge.dart'; +import 'notification_models.dart'; + +/// The non-web bridge: there is no browser Notification API to reach. +/// +/// It reports `unsupported` honestly rather than pretending a notification was +/// shown, so the surface falls back to the in-app `Needs you` channel. A native +/// platform notifier would replace this through the same seam. +class UnsupportedNotificationBridge implements NotificationBridge { + const UnsupportedNotificationBridge(); + + @override + NotificationEnvironment environment() => const NotificationEnvironment( + supported: false, + secureContext: false, + permission: 'default', + ); + + @override + Future requestPermission() async => 'default'; + + @override + bool show(NotificationMessage message, {void Function()? onTap}) => false; +} + +NotificationBridge createNotificationBridge() => + const UnsupportedNotificationBridge(); diff --git a/app/lib/features/attention/notify/notification_bridge_web.dart b/app/lib/features/attention/notify/notification_bridge_web.dart new file mode 100644 index 00000000..dcd1374f --- /dev/null +++ b/app/lib/features/attention/notify/notification_bridge_web.dart @@ -0,0 +1,95 @@ +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'notification_bridge.dart'; +import 'notification_models.dart'; + +/// The browser's `Notification` constructor. +/// +/// Declared with `dart:js_interop` rather than `dart:html`, so the same source +/// compiles for the JavaScript and WebAssembly web targets. Every member is +/// reached only after [_supported] has confirmed the global exists, so an +/// unsupported browser never touches it. +@JS('Notification') +extension type _Notification._(JSObject _) implements JSObject { + external factory _Notification(JSString title, _NotificationOptions options); + + external static JSString get permission; + + external static JSPromise requestPermission(); + + external set onclick(JSFunction? handler); +} + +/// The `{ body, tag }` options object one notification is created with. +extension type _NotificationOptions._(JSObject _) implements JSObject { + external factory _NotificationOptions({JSString body, JSString tag}); +} + +/// Whether `globalThis.Notification` is really a constructor right now. +bool _supported() => + globalContext.getProperty('Notification'.toJS).isA(); + +/// The browser's own secure-context flag; anything but a real boolean is false. +bool _secureContext() { + final value = globalContext.getProperty('isSecureContext'.toJS); + return value.isA() && (value as JSBoolean).toDart; +} + +/// The browser bridge: the real `Notification` API, reached through +/// `dart:js_interop`. +/// +/// Nothing is fabricated. [environment] reports the constructor's own +/// `permission` word and the page's own `isSecureContext`; an unsupported +/// browser is reported as unsupported rather than as a default grant. +class WebNotificationBridge implements NotificationBridge { + const WebNotificationBridge(); + + @override + NotificationEnvironment environment() { + if (!_supported()) { + return const NotificationEnvironment( + supported: false, + secureContext: false, + permission: 'default', + ); + } + final raw = _Notification.permission.toDart; + return NotificationEnvironment( + supported: true, + secureContext: _secureContext(), + permission: raw == 'granted' || raw == 'denied' ? raw : 'default', + ); + } + + @override + Future requestPermission() async { + if (!_supported()) return 'default'; + try { + return (await _Notification.requestPermission().toDart).toDart; + } catch (_) { + // A browser that refuses the request keeps the honest fallback wording. + return 'default'; + } + } + + @override + bool show(NotificationMessage message, {void Function()? onTap}) { + if (!_supported()) return false; + try { + final notification = _Notification( + message.title.toJS, + _NotificationOptions(body: message.body.toJS, tag: message.tag.toJS), + ); + final open = onTap; + if (open != null) notification.onclick = (() => open()).toJS; + return true; + } catch (_) { + // Some browsers can throw even with permission granted; the in-app Needs + // you surface remains the only honest channel and nothing is faked. + return false; + } + } +} + +NotificationBridge createNotificationBridge() => const WebNotificationBridge(); diff --git a/app/lib/features/attention/notify/notification_controller.dart b/app/lib/features/attention/notify/notification_controller.dart new file mode 100644 index 00000000..d0e67dae --- /dev/null +++ b/app/lib/features/attention/notify/notification_controller.dart @@ -0,0 +1,194 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../domain/attention_transitions.dart'; +import 'notification_bridge.dart'; +import 'notification_ledger.dart'; +import 'notification_models.dart'; +import 'notification_store.dart'; + +/// The live notification capability behind the `Needs you` surface. +/// +/// It never invents a permission: [permission] is the platform's own answer, +/// read from the [NotificationBridge], and `granted` is only ever reported when +/// the platform said so. Nothing asks for permission on its own — +/// [requestPermission] is the one explicit call — and a denied answer is never +/// re-asked. +/// +/// 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. +/// +/// 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. +class NotificationController extends ChangeNotifier { + NotificationController({required this.store, NotificationBridge? bridge}) + : bridge = bridge ?? createNotificationBridge(); + + /// The most notifications one publish posts, so a burst cannot flood the tray. + static const maxNotificationsPerBatch = 5; + + final NotificationStore store; + final NotificationBridge bridge; + + /// The tap seam: the manager sets this to open a run. Nothing here navigates. + void Function(int runId)? onOpenRun; + + NotificationLedger _ledger = const NotificationLedger(); + NotificationPermissionState _permission = + NotificationPermissionState.unsupported; + bool _loaded = false; + bool _disposed = false; + int _posted = 0; + + /// The platform's own permission state for this page. + NotificationPermissionState get permission => _permission; + + /// True once the persisted ledger and the platform facts have been read. + bool get loaded => _loaded; + + /// 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; + + /// True only when the platform itself reported `granted`. + bool get canNotify => _permission == NotificationPermissionState.granted; + + /// How many notifications this session has actually posted. + int get postedCount => _posted; + + /// Reads the persisted ledger and the platform's real permission facts once. + Future load() async { + NotificationLedger ledger; + try { + ledger = decodeNotificationLedger(await store.read()); + } catch (_) { + ledger = const NotificationLedger(); + } + if (_disposed) return; + _ledger = ledger; + _permission = notificationStateOf(bridge.environment()); + _loaded = true; + notifyListeners(); + } + + /// Re-reads the platform's facts without asking anything, for example after + /// the browser's site settings changed and the page regained focus. + void refreshPermission() { + if (_disposed) return; + final next = notificationStateOf(bridge.environment()); + if (next == _permission) return; + _permission = next; + notifyListeners(); + } + + /// The one explicit request, only ever called from an operator gesture. + /// + /// A supported, secure page that has not decided is asked, and every other + /// state answers with the platform's own word instead of prompting again. The + /// request is issued before any await, so it stays inside the gesture that + /// triggered it. + Future requestPermission() async { + if (_disposed) return _permission; + final environment = bridge.environment(); + _permission = notificationStateOf(environment); + if (_permission != NotificationPermissionState.notRequested) { + notifyListeners(); + return _permission; + } + // The operator was asked, whatever the answer; persisted without awaiting so + // the platform request stays in this gesture's frame. + _ledger = _ledger.withAsked(true); + unawaited(_persist(_ledger)); + notifyListeners(); + + String answer; + try { + answer = await bridge.requestPermission(); + } catch (_) { + answer = ''; + } + if (_disposed) return _permission; + final word = answer.trim().toLowerCase(); + _permission = notificationStateOf( + NotificationEnvironment( + supported: environment.supported, + secureContext: environment.secureContext, + permission: word == 'granted' || word == 'denied' + ? word + : environment.permission, + ), + ); + notifyListeners(); + return _permission; + } + + /// 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. + int publishTransitions( + Iterable transitions, { + Set dismissed = const {}, + }) { + if (_disposed) return 0; + var posted = 0; + var recorded = false; + for (final transition in transitions) { + 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; + if (!canNotify) continue; + final open = onOpenRun; + final message = NotificationMessage( + runId: transition.runId, + title: notificationAlertTitle(transition.kind), + body: notificationAlertBody(transition.entry), + tag: identity, + ); + var shown = false; + try { + shown = bridge.show( + message, + onTap: open == null ? null : () => open(transition.runId), + ); + } catch (_) { + shown = false; + } + if (shown) { + posted++; + _posted++; + } + } + if (recorded) 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. + } + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} diff --git a/app/lib/features/attention/notify/notification_ledger.dart b/app/lib/features/attention/notify/notification_ledger.dart new file mode 100644 index 00000000..3d8f35d6 --- /dev/null +++ b/app/lib/features/attention/notify/notification_ledger.dart @@ -0,0 +1,91 @@ +import 'dart:convert'; + +import '../../../core/api_gateway.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 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. +/// +/// 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(); +} + +/// The identity of one transition: run, kind and marker. The unit of dedupe. +String notificationIdentity(AttentionTransition transition) => + '${transition.key}@${notificationMarker(transition.run)}'; + +/// 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. +/// +/// 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. +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 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. +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, + ); +} diff --git a/app/lib/features/attention/notify/notification_models.dart b/app/lib/features/attention/notify/notification_models.dart new file mode 100644 index 00000000..f1f8777b --- /dev/null +++ b/app/lib/features/attention/notify/notification_models.dart @@ -0,0 +1,170 @@ +import '../domain/attention_models.dart'; + +/// The permission state the notification surface reports. +/// +/// The Dart names are this client's; [wireName] is the browser model's own word +/// (`unsupported` | `insecure` | `default` | `granted` | `denied`) so the two +/// clients' vocabularies stay traceable. [notRequested] is the Notification +/// API's `default`: supported and secure, but the operator has not decided yet. +enum NotificationPermissionState { + unsupported('unsupported'), + needsSecureContext('insecure'), + notRequested('default'), + granted('granted'), + denied('denied'); + + const NotificationPermissionState(this.wireName); + + /// The browser model's own word for this state (`web/src/notify.js`). + final String wireName; +} + +/// The platform's own notification facts, as the bridge answers them. +/// +/// [permission] is the Notification API's raw word; anything unrecognised is +/// read as `default` rather than guessed, exactly as the browser does. +class NotificationEnvironment { + const NotificationEnvironment({ + required this.supported, + required this.secureContext, + required this.permission, + }); + + final bool supported; + final bool secureContext; + final String permission; +} + +/// The permission state for one environment. +/// +/// Only the platform's own answers decide it: an unsupported API and an +/// insecure page are reported before the permission word, and `granted` is never +/// assumed — a page that has not been granted stays [notRequested]. +NotificationPermissionState notificationStateOf( + NotificationEnvironment environment, +) { + if (!environment.supported) return NotificationPermissionState.unsupported; + if (!environment.secureContext) { + return NotificationPermissionState.needsSecureContext; + } + switch (environment.permission) { + case 'granted': + return NotificationPermissionState.granted; + case 'denied': + return NotificationPermissionState.denied; + default: + return NotificationPermissionState.notRequested; + } +} + +/// Android's NOTIFICATION_RATIONALE, verbatim (`RunAlerts.kt`, `notify.js`). +const notificationRationale = + 'Pipelines can notify you when a run is waiting for your decision or has ' + 'failed. Without it, those runs still appear in the in-app Needs you ' + 'surface.'; + +/// The Settings section heading and the explicit-gesture action label. +const notificationSectionTitle = 'Notifications'; +const notificationRequestLabel = 'Enable notifications'; + +/// The honest wording for every state, verbatim from `web/src/notify.js`; each +/// says plainly that the in-app `Needs you` surface is the only channel when the +/// platform cannot notify. +const notificationUnsupportedCopy = + 'This browser does not support notifications. The in-app Needs you surface ' + 'is the only channel.'; +const notificationInsecureCopy = + 'Notifications need a secure context (https or localhost). This page is not ' + 'secure, so the in-app Needs you surface is the only channel.'; +const notificationGrantedCopy = + 'Notifications are on. Failed and waiting runs will raise a browser ' + 'notification.'; +const notificationDeniedCopy = + 'Notifications are blocked for this site. Allow them in the browser\'s site ' + 'settings to use them; until then the in-app Needs you surface is the only ' + 'channel.'; +const notificationDefaultCopy = + 'Notifications are off. Enable them to be told when a run fails or needs ' + 'your decision.'; +const notificationDefaultAskedCopy = + 'Notifications are still off. Your browser did not grant permission when ' + 'asked; you can ask again, or the in-app Needs you surface remains the only ' + 'channel.'; + +/// The total permission view for the Settings tile. +/// +/// Only a supported, secure page whose permission is still `default` offers the +/// request control, and [asked] only changes the honest wording — nothing here +/// asks for permission on its own. +class NotificationPermissionView { + const NotificationPermissionView({ + required this.state, + required this.body, + required this.canRequest, + required this.actionLabel, + required this.asked, + }); + + final NotificationPermissionState state; + final String body; + final bool canRequest; + final String? actionLabel; + final bool asked; +} + +/// The view for one state, with the browser's own copy for it. +NotificationPermissionView notificationPermissionView( + NotificationPermissionState state, { + bool asked = false, +}) { + final canRequest = state == NotificationPermissionState.notRequested; + final body = switch (state) { + NotificationPermissionState.unsupported => notificationUnsupportedCopy, + NotificationPermissionState.needsSecureContext => + notificationInsecureCopy, + NotificationPermissionState.granted => notificationGrantedCopy, + NotificationPermissionState.denied => notificationDeniedCopy, + NotificationPermissionState.notRequested => + asked ? notificationDefaultAskedCopy : notificationDefaultCopy, + }; + return NotificationPermissionView( + state: state, + body: body, + canRequest: canRequest, + actionLabel: canRequest ? notificationRequestLabel : null, + asked: asked, + ); +} + +/// The short headline one kind shows; the browser's `alertTitle` verbatim. +String notificationAlertTitle(AttentionKind kind) => switch (kind) { + AttentionKind.decision => 'A run needs your decision', + AttentionKind.failed => 'A run failed', +}; + +/// The line naming the run: its label, then the pipeline it belongs to. +/// +/// The words are the entry's own — a blank or equal pipeline is never repeated, +/// so there is no trailing separator and nothing is invented. +String notificationAlertBody(AttentionEntry entry) { + final pipeline = entry.pipeline; + final label = entry.label; + if (pipeline.isEmpty || pipeline == label) return label; + return '$label \u00b7 $pipeline'; +} + +/// One notification the platform is asked to show: the entry's own words, plus +/// the stable identity used as the browser's coalescing tag. +class NotificationMessage { + const NotificationMessage({ + required this.runId, + required this.title, + required this.body, + required this.tag, + }); + + final int runId; + final String title; + final String body; + final String tag; +} diff --git a/app/lib/features/attention/notify/notification_store.dart b/app/lib/features/attention/notify/notification_store.dart new file mode 100644 index 00000000..27b53806 --- /dev/null +++ b/app/lib/features/attention/notify/notification_store.dart @@ -0,0 +1,83 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import 'notification_ledger.dart'; + +/// The persistence seam for the notification ledger. +/// +/// The controller only ever hands over the exact string produced by +/// [encodeNotificationLedger], so a store cannot invent a different format. +/// Both directions are allowed to fail: a caller treats a null read as "nothing +/// recorded yet" and a false write as "this session only". +abstract interface class NotificationStore { + Future read(); + + Future write(String value); +} + +/// `shared_preferences` storage under the ledger's own key. +/// +/// Reads and writes are total: an unavailable plugin, a disabled store or a full +/// disk returns null/false instead of throwing into the caller's frame. Only the +/// documented [notificationStorageKey] is touched, never the attention key or the +/// legacy web key. +class SharedPreferencesNotificationStore implements NotificationStore { + const SharedPreferencesNotificationStore(); + + Future _preferences() async { + try { + return await SharedPreferences.getInstance(); + } catch (_) { + return null; + } + } + + @override + Future read() async { + final preferences = await _preferences(); + if (preferences == null) return null; + try { + return preferences.getString(notificationStorageKey); + } catch (_) { + return null; + } + } + + @override + Future write(String value) async { + final preferences = await _preferences(); + if (preferences == null) return false; + try { + return await preferences.setString(notificationStorageKey, value); + } catch (_) { + return false; + } + } +} + +/// An in-memory store for tests and isolated fixtures. +/// +/// It never touches the platform store, so a probe or widget test cannot mutate +/// a real operator's persisted ledger. [failReads] and [failWrites] reproduce an +/// unavailable store without throwing. +class MemoryNotificationStore implements NotificationStore { + MemoryNotificationStore({this.stored}); + + String? stored; + bool failReads = false; + bool failWrites = false; + int writes = 0; + + @override + Future read() async { + if (failReads) throw StateError('notification store unavailable'); + return stored; + } + + @override + Future write(String value) async { + writes++; + if (failWrites) throw StateError('notification store is read-only'); + stored = value; + return true; + } +} diff --git a/app/lib/features/attention/ui/notification_permission_tile.dart b/app/lib/features/attention/ui/notification_permission_tile.dart new file mode 100644 index 00000000..16de654d --- /dev/null +++ b/app/lib/features/attention/ui/notification_permission_tile.dart @@ -0,0 +1,127 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../notify/notification_models.dart'; + +/// The permission tile's root, so a caller can find it whichever host draws it. +const notificationTileKey = ValueKey('notification-permission-tile'); + +/// The explicit-gesture Enable action, present only when a request is possible. +const notificationEnableKey = ValueKey( + 'notification-permission-enable', +); + +/// The honest state line, which says plainly when the in-app surface is the +/// only channel. +const notificationStateKey = ValueKey('notification-permission-state'); + +/// The reusable Notifications permission tile for Settings. +/// +/// It renders the platform's own [state] with the browser's own copy, shows the +/// Android rationale verbatim, and offers the [notificationRequestLabel] action +/// only while a request is still possible. Nothing here asks for permission on +/// its own — [onRequest] is the caller's explicit-gesture handler, and the tile +/// never guesses a grant. +/// +/// The caller owns the surrounding section/card and passes the live state; the +/// tile reads no store, bridge or clock. +class NotificationPermissionTile extends StatelessWidget { + const NotificationPermissionTile({ + super.key, + required this.state, + this.asked = false, + this.onRequest, + this.cupertino, + }); + + final NotificationPermissionState state; + + /// Whether the operator has already been asked; only changes the wording. + final bool asked; + + /// The explicit-gesture handler. Absent means no action is drawn even when a + /// request would be possible. + final VoidCallback? onRequest; + + /// Forces the native host in tests and fixtures; otherwise the ambient + /// [usesCupertinoHost] decides. + final bool? cupertino; + + @override + Widget build(BuildContext context) { + final view = notificationPermissionView(state, asked: asked); + final native = cupertino ?? usesCupertinoHost(context); + final action = view.canRequest && onRequest != null + ? _action(native, view.actionLabel!, onRequest!) + : null; + final bodyStyle = native + ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ) + : Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + native + ? CupertinoListTile( + key: notificationTileKey, + leading: const Icon(CupertinoIcons.bell), + title: const Text(notificationSectionTitle), + ) + : ListTile( + key: notificationTileKey, + leading: const Icon(Icons.notifications_outlined), + title: const Text(notificationSectionTitle), + ), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(notificationRationale, style: bodyStyle), + const SizedBox(height: 8), + Semantics( + liveRegion: true, + child: Text( + view.body, + key: notificationStateKey, + style: bodyStyle, + ), + ), + // The action sits on its own row, as the browser's settings + // section does: a native button in a row's trailing slot would + // squeeze the section title to one character per line at large + // text, and its label is too long to share the row. + if (action != null) ...[ + const SizedBox(height: 8), + Align( + alignment: AlignmentDirectional.centerStart, + child: action, + ), + ], + ], + ), + ), + ], + ); + } + + Widget _action(bool native, String label, VoidCallback onRequest) { + if (native) { + return CupertinoButton( + key: notificationEnableKey, + padding: EdgeInsets.zero, + onPressed: onRequest, + child: Text(label), + ); + } + return TextButton( + key: notificationEnableKey, + onPressed: onRequest, + child: Text(label), + ); + } +} diff --git a/app/notes/A2-notify.md b/app/notes/A2-notify.md new file mode 100644 index 00000000..7045f533 --- /dev/null +++ b/app/notes/A2-notify.md @@ -0,0 +1,128 @@ +# A2 — notification capability behind a platform seam + +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). + +## What is there + +| File | Lines | Role | +| --- | --- | --- | +| `notify/notification_models.dart` | 170 | 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_store.dart` | 83 | injectable store seam; total `shared_preferences` impl + memory impl | +| `notify/notification_controller.dart` | 194 | the `ChangeNotifier` capability | +| `ui/notification_permission_tile.dart` | 127 | the reusable native tile | +| `tool/notification_probe.dart` / `.mjs` | 265 / 295 | isolated real-browser probe | + +## Platform seam + +`NotificationBridge` answers the platform's own facts +(`environment()` → `supported`, `secureContext`, raw `permission`), +`requestPermission()` (only ever called from an explicit gesture) and +`show(message, onTap:)`. The web bridge declares `@JS('Notification')` with +`external factory`, `external static permission`, `external static +requestPermission` and an `onclick` setter, and reaches the global only after a +`globalContext` support check, so an unsupported browser is never touched. The +stub returns `supported: false` and `show() == false`. + +`NotificationController.permission` is one of `unsupported`, +`needsSecureContext`, `notRequested` (the API's own `default` — `default` is a +Dart reserved word, and each state exposes `wireName` = `unsupported` | +`insecure` | `default` | `granted` | `denied`), `granted`, `denied`. It is +derived only from `notificationStateOf(environment)`; `granted` is never assumed +from an unrecognised word. `requestPermission()` asks only while the state is +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 + +- 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. +- 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 + needs your decision`) and `label · pipeline`, matching `web/src/notify.js` and + `RunAlerts.kt` verbatim. Nothing is invented, and no `stage` field is added + 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. + +## Wiring the manager still owes + +```dart +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); +``` + +`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 analyze` — **No issues found** (whole project). +- `flutter build web` (the real `lib/main.dart`) — **succeeded**. +- 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). + +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. + +## Deliberate limits + +- `PARITY.md`'s `Notifications` row is **still Missing**: this slice is a + 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. +- 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. diff --git a/app/test/features/attention/notify/notification_controller_test.dart b/app/test/features/attention/notify/notification_controller_test.dart new file mode 100644 index 00000000..e178a862 --- /dev/null +++ b/app/test/features/attention/notify/notification_controller_test.dart @@ -0,0 +1,403 @@ +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 { + final attention = attentionController(); + final bridge = FakeNotificationBridge(); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([ + runSummary(1, 'failed', diagnostic: 'Stage 3 stopped'), + runSummary(2, 'waiting'), + ]); + + expect(attention.transitions, isEmpty); + expect(notify.publishTransitions(attention.transitions), 0); + expect(bridge.shown, isEmpty); + }); + }); + + group('a live transition notifies once', () { + test('the frame\'s own words and identity are used', () 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(); + expect(notify.canNotify, isTrue); + + attention.seedRows([runSummary(1, 'running', name: 'nightly')]); + attention.observeFrame( + runFrame( + 1, + 'failed', + name: 'nightly', + title: 'Nightly audit', + diagnostic: 'Stage 3 stopped', + finishedAt: '2026-10-22T11:00:00Z', + ), + ); + + expect(notify.publishTransitions(attention.transitions), 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.runId, 1); + }); + + test('a duplicate frame and a republished list stay silent', () 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')]); + attention.observeFrame(runFrame(1, 'failed')); + expect(notify.publishTransitions(attention.transitions), 1); + + attention.observeFrame(runFrame(1, 'failed')); + expect(attention.transitions, hasLength(1)); + expect(notify.publishTransitions(attention.transitions), 0); + expect(bridge.shown, hasLength(1)); + }); + + test('a reconnect reseed cannot replay the notification', () 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')]); + attention.observeFrame(runFrame(1, 'failed')); + expect(notify.publishTransitions(attention.transitions), 1); + + attention.resetForReconnect(); + attention.seedRows([runSummary(1, 'failed')], reconnect: true); + expect(notify.publishTransitions(attention.transitions), 0); + attention.observeFrame(runFrame(1, 'failed')); + expect(notify.publishTransitions(attention.transitions), 0); + expect(bridge.shown, hasLength(1)); + }); + + test('a rebuilt controller with the same store stays silent', () async { + final store = MemoryNotificationStore(); + final bridge = FakeNotificationBridge(permission: 'granted'); + final attention = attentionController(); + final notify = NotificationController(store: store, bridge: bridge); + addTearDown(attention.dispose); + addTearDown(notify.dispose); + await attention.load(); + await notify.load(); + + attention.seedRows([runSummary(1, 'running')]); + attention.observeFrame(runFrame(1, 'failed')); + expect(notify.publishTransitions(attention.transitions), 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(bridge.shown, hasLength(1)); + }); + + test('a genuinely new failure 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(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.observeFrame(runFrame(1, 'failed')); + + expect(attention.transitions, isEmpty); + expect(notify.publishTransitions(attention.transitions), 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], dismissed: {transition.key}), + 0, + ); + expect(notify.notified, contains(notificationIdentity(transition))); + expect(bridge.shown, isEmpty); + }); + }); + + 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(); + 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_ledger_test.dart b/app/test/features/attention/notify/notification_ledger_test.dart new file mode 100644 index 00000000..b4658cf4 --- /dev/null +++ b/app/test/features/attention/notify/notification_ledger_test.dart @@ -0,0 +1,89 @@ +import 'package:flutter_test/flutter_test.dart'; +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', () { + 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))); + }); + + test('a run without a finish time falls back to its creation time', () { + final entry = transitionFor(7, status: 'waiting', finishedAt: ''); + expect( + notificationIdentity(entry), + '7:Decision@${attentionNow.subtract(const Duration(hours: 1)).toIso8601String()}', + ); + }); + + test('the kind separates a decision from a failure of one run', () { + expect( + notificationIdentity(transitionFor(7)), + isNot(notificationIdentity(transitionFor(7, status: 'waiting'))), + ); + }); + }); + + 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'); + expect(base.notified, isEmpty); + expect(once.hasNotified('7:Failed@a'), isTrue); + expect(twice.notified, {'7:Failed@a'}); + }); + + test('asked is carried without touching the identities', () { + final asked = const NotificationLedger( + notified: {'a'}, + ).withAsked(true); + expect(asked.asked, isTrue); + expect(asked.notified, {'a'}); + }); + }); + + 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)); + expect(decoded.asked, isTrue); + expect(decoded.notified, {'a', 'b'}); + }); + + test('an unchanged ledger always encodes to the same bytes', () { + final first = encodeNotificationLedger( + const NotificationLedger(notified: {'b', 'a'}), + ); + final second = encodeNotificationLedger( + const NotificationLedger(notified: {'a', 'b'}), + ); + expect(first, second); + }); + + test('blank, malformed and wrong-typed values never throw', () { + expect(decodeNotificationLedger(null).notified, isEmpty); + expect(decodeNotificationLedger('').asked, isFalse); + expect(decodeNotificationLedger('not json').notified, isEmpty); + expect(decodeNotificationLedger('[]').notified, isEmpty); + expect(decodeNotificationLedger('"text"').notified, isEmpty); + expect( + decodeNotificationLedger('{"asked":"yes","notified":[1,null,"a",""]}') + .notified, + {'a'}, + ); + expect( + decodeNotificationLedger('{"asked":"yes"}').asked, + isFalse, + reason: 'only a real true counts as asked', + ); + }); + }); +} diff --git a/app/test/features/attention/notify/notification_models_test.dart b/app/test/features/attention/notify/notification_models_test.dart new file mode 100644 index 00000000..2a3b02ec --- /dev/null +++ b/app/test/features/attention/notify/notification_models_test.dart @@ -0,0 +1,155 @@ +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_models.dart'; + +NotificationEnvironment _env({ + bool supported = true, + bool secure = true, + String permission = 'default', +}) => NotificationEnvironment( + supported: supported, + secureContext: secure, + permission: permission, +); + +void main() { + group('permission state is the platform\'s own answer', () { + test('an unsupported API and an insecure page win over the word', () { + expect( + notificationStateOf(_env(supported: false, permission: 'granted')), + NotificationPermissionState.unsupported, + ); + expect( + notificationStateOf(_env(secure: false, permission: 'granted')), + NotificationPermissionState.needsSecureContext, + ); + }); + + test('granted is never assumed from an unrecognised word', () { + expect( + notificationStateOf(_env(permission: 'prompt')), + NotificationPermissionState.notRequested, + ); + expect( + notificationStateOf(_env(permission: '')), + NotificationPermissionState.notRequested, + ); + expect( + notificationStateOf(_env(permission: 'granted')), + NotificationPermissionState.granted, + ); + expect( + notificationStateOf(_env(permission: 'denied')), + NotificationPermissionState.denied, + ); + }); + + test('each state carries the browser model\'s own wire word', () { + expect(NotificationPermissionState.unsupported.wireName, 'unsupported'); + expect( + NotificationPermissionState.needsSecureContext.wireName, + 'insecure', + ); + expect(NotificationPermissionState.notRequested.wireName, 'default'); + expect(NotificationPermissionState.granted.wireName, 'granted'); + expect(NotificationPermissionState.denied.wireName, 'denied'); + }); + }); + + group('the permission view', () { + test('only a still-undecided page can request', () { + final view = notificationPermissionView( + NotificationPermissionState.notRequested, + ); + expect(view.canRequest, isTrue); + expect(view.actionLabel, notificationRequestLabel); + expect(view.body, notificationDefaultCopy); + + for (final state in [ + NotificationPermissionState.unsupported, + NotificationPermissionState.needsSecureContext, + NotificationPermissionState.granted, + NotificationPermissionState.denied, + ]) { + final other = notificationPermissionView(state); + expect(other.canRequest, isFalse, reason: '$state'); + expect(other.actionLabel, isNull, reason: '$state'); + } + }); + + test('asked only changes the undecided wording', () { + expect( + notificationPermissionView( + NotificationPermissionState.notRequested, + asked: true, + ).body, + notificationDefaultAskedCopy, + ); + expect( + notificationPermissionView( + NotificationPermissionState.denied, + asked: true, + ).body, + notificationDeniedCopy, + ); + }); + + test('every unavailable state names the in-app channel', () { + for (final state in [ + NotificationPermissionState.unsupported, + NotificationPermissionState.needsSecureContext, + NotificationPermissionState.denied, + ]) { + expect( + notificationPermissionView(state).body, + contains('in-app Needs you surface'), + reason: '$state', + ); + } + }); + }); + + group('notification content is the entry\'s own words', () { + test('the headline is the kind, nothing invented', () { + expect( + notificationAlertTitle(AttentionKind.decision), + 'A run needs your decision', + ); + expect(notificationAlertTitle(AttentionKind.failed), 'A run failed'); + }); + + test('the body is the run label then its pipeline', () { + final entry = attentionEntryFor({ + 'id': 7, + 'name': 'nightly-audit', + 'title': 'Nightly audit', + 'status': 'failed', + 'diagnostic': 'Stage 3 stopped', + 'created_at': '2026-10-22T09:00:00Z', + 'finished_at': '2026-10-22T09:10:00Z', + })!; + expect(notificationAlertBody(entry), 'Nightly audit \u00b7 nightly-audit'); + }); + + test('a blank or equal pipeline is never repeated', () { + final untitled = attentionEntryFor({ + 'id': 7, + 'name': 'release', + 'status': 'failed', + 'created_at': '2026-10-22T09:00:00Z', + 'finished_at': '2026-10-22T09:10:00Z', + })!; + expect(notificationAlertBody(untitled), 'release'); + + final nameless = attentionEntryFor({ + 'id': 8, + 'name': '', + 'title': 'A title', + 'status': 'failed', + 'created_at': '2026-10-22T09:00:00Z', + 'finished_at': '2026-10-22T09:10:00Z', + })!; + expect(notificationAlertBody(nameless), 'A title'); + }); + }); +} diff --git a/app/test/features/attention/notify/notification_test_support.dart b/app/test/features/attention/notify/notification_test_support.dart new file mode 100644 index 00000000..a8dd35a8 --- /dev/null +++ b/app/test/features/attention/notify/notification_test_support.dart @@ -0,0 +1,112 @@ +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_models.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; + +/// The fixed local time the attention tests order and window by. +final attentionNow = DateTime(2026, 10, 22, 12); + +String at(Duration before) => attentionNow.subtract(before).toIso8601String(); + +/// One run summary, built exactly as the runs list holds it. +Map runSummary( + int id, + String status, { + String name = 'release', + String? title, + Duration age = const Duration(hours: 1), + String diagnostic = '', + Object? exportPending, + Map extra = const {}, +}) => { + 'id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'created_at': at(age), + 'finished_at': 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. +Map runFrame( + int id, + String status, { + String name = 'release', + String? title, + String diagnostic = '', + String? finishedAt, +}) => { + 'type': 'run_event', + 'run_id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'created_at': at(const Duration(hours: 1)), + 'finished_at': finishedAt ?? at(const Duration(minutes: 1)), +}; + +/// One transition for a run that just entered [status], for batch tests. +AttentionTransition transitionFor( + int id, { + String status = 'failed', + String name = 'release', + String? title, + String? finishedAt, +}) => AttentionTransition( + attentionEntryFor( + runFrame(id, status, name: name, title: title, finishedAt: finishedAt), + )!, +); + +AttentionController attentionController() => + AttentionController(store: MemoryAttentionStore(), now: () => attentionNow); + +/// A bridge whose answers are set explicitly, so every permission path is +/// exercised without a browser. It records what the controller asked for. +class FakeNotificationBridge implements NotificationBridge { + FakeNotificationBridge({ + this.supported = true, + this.secureContext = true, + this.permission = 'default', + this.answer = 'granted', + this.accepts = true, + }); + + bool supported; + bool secureContext; + String permission; + String answer; + bool accepts; + + int requests = 0; + final List shown = []; + final List taps = []; + + @override + NotificationEnvironment environment() => NotificationEnvironment( + supported: supported, + secureContext: secureContext, + permission: permission, + ); + + @override + Future requestPermission() async { + requests++; + permission = answer; + return answer; + } + + @override + bool show(NotificationMessage message, {void Function()? onTap}) { + shown.add(message); + taps.add(onTap); + return accepts; + } +} diff --git a/app/test/features/attention/ui/notification_permission_tile_test.dart b/app/test/features/attention/ui/notification_permission_tile_test.dart new file mode 100644 index 00000000..b764b941 --- /dev/null +++ b/app/test/features/attention/ui/notification_permission_tile_test.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/notify/notification_models.dart'; +import 'package:pipelines_app/features/attention/ui/notification_permission_tile.dart'; + +import 'needs_you_test_support.dart'; + +/// The tile inside a normal page, so both native hosts can draw it. The page +/// scrolls like the Settings list does, so the tile is never given a fixed +/// height to overflow. +Widget _page({ + required NotificationPermissionState state, + bool cupertino = false, + bool asked = false, + VoidCallback? onRequest, +}) => attentionApp( + Scaffold( + body: SingleChildScrollView( + child: NotificationPermissionTile( + state: state, + asked: asked, + onRequest: onRequest, + ), + ), + ), + cupertino: cupertino, +); + +void _noop() {} + +void main() { + for (final native in [false, true]) { + final host = native ? 'Cupertino' : 'Material'; + + testWidgets('$host shows the state\'s own honest copy', (tester) async { + final cases = { + NotificationPermissionState.unsupported: notificationUnsupportedCopy, + NotificationPermissionState.needsSecureContext: + notificationInsecureCopy, + NotificationPermissionState.granted: notificationGrantedCopy, + NotificationPermissionState.denied: notificationDeniedCopy, + NotificationPermissionState.notRequested: notificationDefaultCopy, + }; + for (final entry in cases.entries) { + await tester.pumpWidget( + _page(state: entry.key, cupertino: native, onRequest: _noop), + ); + expect(find.text(notificationSectionTitle), findsOneWidget); + expect(find.text(notificationRationale), findsOneWidget); + expect(find.text(entry.value), findsOneWidget, reason: '${entry.key}'); + expect( + find.byKey(notificationEnableKey), + entry.key == NotificationPermissionState.notRequested + ? findsOneWidget + : findsNothing, + reason: '${entry.key}', + ); + } + }); + + testWidgets('$host shows the asked wording without an action', ( + tester, + ) async { + await tester.pumpWidget( + _page( + state: NotificationPermissionState.notRequested, + asked: true, + cupertino: native, + ), + ); + expect(find.text(notificationDefaultAskedCopy), findsOneWidget); + expect(find.text(notificationDefaultCopy), findsNothing); + }); + + testWidgets('$host Enable runs the explicit request', (tester) async { + var requested = 0; + await tester.pumpWidget( + _page( + state: NotificationPermissionState.notRequested, + cupertino: native, + onRequest: () => requested++, + ), + ); + await tester.tap(find.byKey(notificationEnableKey)); + await tester.pump(); + expect(requested, 1); + }); + + testWidgets('$host tile wraps at 320 logical px and 2x in dark', ( + tester, + ) async { + tester.view.devicePixelRatio = 2; + tester.view.physicalSize = const Size(640, 1280); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + // The undecided state is the hardest: it carries the Enable action as well + // as the longest copy, so the section title must still have room to read. + await tester.pumpWidget( + attentionApp( + Scaffold( + body: SingleChildScrollView( + child: NotificationPermissionTile( + state: NotificationPermissionState.notRequested, + onRequest: _noop, + ), + ), + ), + cupertino: native, + dark: true, + textScale: 2, + ), + ); + expect(tester.takeException(), isNull); + + final title = tester.renderObject( + find.text(notificationSectionTitle), + ); + // Cupertino's list tile deliberately caps its title at one line; the + // defect this guards is the title being squeezed to a single glyph by the + // action sharing the row, so its width is the meaningful check. + expect( + title.size.width, + greaterThan(100), + reason: 'the action must not squeeze the section title to one glyph', + ); + final body = tester.renderObject( + find.text(notificationDefaultCopy), + ); + expect(body.didExceedMaxLines, isFalse); + expect(find.byKey(notificationEnableKey), findsOneWidget); + + final rect = tester.getRect(find.byKey(notificationStateKey)); + expect(rect.left, greaterThanOrEqualTo(0)); + expect(rect.right, lessThanOrEqualTo(320)); + expect(tester.takeException(), isNull); + }); + } +} diff --git a/app/tool/notification_probe.dart b/app/tool/notification_probe.dart new file mode 100644 index 00000000..ec849ab7 --- /dev/null +++ b/app/tool/notification_probe.dart @@ -0,0 +1,265 @@ +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:flutter/cupertino.dart'; +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_models.dart'; +import 'package:pipelines_app/features/attention/notify/notification_store.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:pipelines_app/features/attention/ui/notification_permission_tile.dart'; + +/// Browser capture entrypoint for the notification capability. +/// +/// 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 +/// every state on both hosts. Nothing here opens a socket or touches real +/// operator data; the store is in memory. +void main() { + final params = Uri.base.queryParameters; + final mode = params['mode'] ?? 'transition'; + final cupertino = params['host'] == 'cupertino'; + final scale = double.tryParse(params['scale'] ?? '') ?? 1; + final brightness = params['theme'] == 'light' + ? Brightness.light + : Brightness.dark; + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: TextScaler.linear(scale)), + child: app!, + ); + final home = switch (mode) { + 'tiles' => const _TileGallery(), + 'tile' => _SingleTile(state: _stateOf(params['state'])), + _ => _NotificationProbe(mode: mode), + }; + if (cupertino) { + runApp( + CupertinoApp( + theme: CupertinoThemeData(brightness: brightness), + builder: scaled, + home: home, + ), + ); + return; + } + runApp( + MaterialApp( + theme: ThemeData( + platform: TargetPlatform.android, + brightness: brightness, + ), + builder: scaled, + home: home, + ), + ); +} + +/// The report the browser drive reads, as a plain JS string. +void _publishReport(String value) => + globalContext.setProperty('__probeReport'.toJS, value.toJS); + +/// The permission state named by a `state` query parameter, defaulting to the +/// undecided one. +NotificationPermissionState _stateOf(String? name) { + for (final state in NotificationPermissionState.values) { + if (state.wireName == name) return state; + } + return NotificationPermissionState.notRequested; +} + +String _at(Duration before) => + DateTime.now().toUtc().subtract(before).toIso8601String(); + +Map _summary( + int id, + String status, { + String name = 'release', + String? title, + String diagnostic = '', +}) => { + 'id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'created_at': _at(const Duration(hours: 1)), + 'finished_at': _at(const Duration(minutes: 55)), +}; + +Map _frame( + int id, + String status, { + String name = 'release', + String? title, + String diagnostic = '', +}) => { + 'type': 'run_event', + 'run_id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'finished_at': _at(const Duration(minutes: 1)), +}; + +/// Runs one notification scenario against the real bridge, then reports it and +/// draws the live permission tile underneath. +class _NotificationProbe extends StatefulWidget { + const _NotificationProbe({required this.mode}); + + final String mode; + + @override + State<_NotificationProbe> createState() => _NotificationProbeState(); +} + +class _NotificationProbeState extends State<_NotificationProbe> { + String _report = 'running'; + NotificationPermissionState _permission = + NotificationPermissionState.unsupported; + bool _asked = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => _run()); + } + + Future _run() async { + final bridge = createNotificationBridge(); + final notify = NotificationController( + store: MemoryNotificationStore(), + bridge: bridge, + ); + await notify.load(); + final attention = AttentionController(store: MemoryAttentionStore()); + await attention.load(); + + switch (widget.mode) { + case 'seed': + attention.seedRows([ + _summary(1, 'failed', diagnostic: 'Stage 3 stopped'), + _summary(2, 'waiting'), + ]); + notify.publishTransitions(attention.transitions); + case 'dismissed': + attention.seedRows([_summary(1, 'running')]); + await attention.dismiss(attentionEntryFor(_summary(1, 'failed'))!); + attention.observeFrame(_frame(1, 'failed')); + notify.publishTransitions(attention.transitions); + case 'reconnect': + attention.seedRows([_summary(1, 'running')]); + attention.observeFrame(_frame(1, 'failed')); + notify.publishTransitions(attention.transitions); + attention.resetForReconnect(); + attention.seedRows([_summary(1, 'failed')], reconnect: true); + notify.publishTransitions(attention.transitions); + attention.observeFrame(_frame(1, 'failed')); + notify.publishTransitions(attention.transitions); + case 'denied': + case 'unsupported': + case 'default': + attention.seedRows([_summary(1, 'running')]); + attention.observeFrame(_frame(1, 'failed')); + notify.publishTransitions(attention.transitions); + default: + attention.seedRows([_summary(1, 'running', name: 'nightly')]); + attention.observeFrame( + _frame( + 1, + 'failed', + name: 'nightly', + title: 'Nightly audit', + diagnostic: 'Stage 3 stopped', + ), + ); + notify.publishTransitions(attention.transitions); + } + + if (!mounted) return; + final report = + 'mode=${widget.mode} posted=${notify.postedCount} ' + 'state=${notify.permission.wireName} asked=${notify.asked} ' + 'notified=${notify.notified.length}'; + _publishReport(report); + setState(() { + _report = report; + _permission = notify.permission; + _asked = notify.asked; + }); + notify.dispose(); + attention.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + Text(_report), + const SizedBox(height: 16), + NotificationPermissionTile( + state: _permission, + asked: _asked, + onRequest: () {}, + ), + ], + ), + ), + ); + } +} + +/// One permission state on its own, so each can be captured and read at the +/// hardest width and text scale. +class _SingleTile extends StatelessWidget { + const _SingleTile({required this.state}); + + final NotificationPermissionState state; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: NotificationPermissionTile(state: state, onRequest: () {}), + ), + ), + ); + } +} + +/// Every permission state at once, so both hosts can be captured and read in +/// one page without touching a real permission. +class _TileGallery extends StatelessWidget { + const _TileGallery(); + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final state in NotificationPermissionState.values) ...[ + Text(state.wireName), + NotificationPermissionTile(state: state, onRequest: () {}), + ], + ], + ), + ), + ), + ); + } +} diff --git a/app/tool/notification_probe.mjs b/app/tool/notification_probe.mjs new file mode 100644 index 00000000..7660adfe --- /dev/null +++ b/app/tool/notification_probe.mjs @@ -0,0 +1,295 @@ +// Real-browser acceptance for the attention notification capability. +// +// flutter build web -t tool/notification_probe.dart -o build/notification_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/notification_probe.mjs +// +// The page is served from an isolated loopback server. `window.Notification` is +// 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. +import { createServer } from 'node:http'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { existsSync } from 'node:fs'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; + +const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/notification_probe_web'); +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(artifactDir, { recursive: true }); +const defaultChrome = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const chromePath = process.env.CHROME_PATH ?? defaultChrome; +if (!existsSync(chromePath)) throw new Error(`Chrome not found at ${chromePath}; set CHROME_PATH`); + +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', +}; +const server = createServer(async (req, res) => { + try { + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end(); + const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const origin = `http://127.0.0.1:${port}`; + +// The spy is installed before every document, so the app only ever sees it. It +// delegates `permission` to the real constructor (which CDP granted or denied) +// and records each `new Notification(...)` call. +const spy = `(() => { + const mode = new URLSearchParams(location.search).get('mode') || ''; + window.__notifications = []; + window.__probeReport = ''; + if (mode === 'unsupported') { window.Notification = undefined; return; } + const Real = window.Notification; + function Spy(title, options) { + window.__notifications.push({ + title: String(title ?? ''), + body: String((options && options.body) || ''), + tag: String((options && options.tag) || ''), + }); + return { onclick: null, close() {} }; + } + Object.defineProperty(Spy, 'permission', { + get: () => (Real ? Real.permission : 'granted'), + }); + Spy.requestPermission = () => Promise.resolve(Spy.permission); + window.Notification = Spy; +})();`; + +const profile = await mkdtemp(join(tmpdir(), 'notification-chrome-')); +const chrome = spawn( + chromePath, + [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); +const waitFor = async (check) => { + for (let i = 0; i < 120; i++) { + const value = await check(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for Chrome DevTools\n${stderr.slice(-1200)}`); +}; + +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolveCall, rejectCall) => { + const callId = ++id; + pending.set(callId, (message) => { + if (message.error) rejectCall(new Error(`${method}: ${message.error.message}`)); + else resolveCall(message.result); + }); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + + const target = (await send('Target.createTarget', { url: 'about:blank' })).targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Page.addScriptToEvaluateOnNewDocument', { source: spy }, session); + + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.exceptionDetails) { + throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response.exceptionDetails)}`); + } + return response.result?.value; + }; + const semantics = () => evaluate( + "[...document.querySelectorAll('flt-semantics')].map(x=>{const r=x.getBoundingClientRect();return{label:(x.getAttribute('aria-label')||x.innerText||'').trim(),role:x.getAttribute('role'),x:r.x,y:r.y,w:r.width,h:r.height}})", + ); + const requireLabels = (all, needles, state) => { + for (const needle of needles) { + if (!all.some((label) => label.includes(needle))) { + throw new Error(`Missing ${JSON.stringify(needle)} in ${state}: ${JSON.stringify(all)}`); + } + } + }; + let viewport = { width: 320, height: 640 }; + const navigate = async ({ mode, host = 'material', scale = 1, theme = 'dark', width = 320, height = 640, semantics: enableSemantics = false, state } = {}) => { + viewport = { width, height }; + await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: theme }] }, session); + const query = new URLSearchParams({ mode, host, scale: String(scale), theme }); + if (state) query.set('state', state); + await send('Page.navigate', { url: `${origin}/?${query}` }, session); + await delay(2500); + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 2, mobile: true }, session); + await delay(1000); + if (enableSemantics) { + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(1200); + } + }; + const waitForReport = async (mode) => { + for (let attempt = 0; attempt < 80; attempt++) { + const report = await evaluate('window.__probeReport'); + if (report && report.includes(`mode=${mode}`)) return report; + await delay(150); + } + throw new Error(`The ${mode} scenario never reported`); + }; + const notifications = () => evaluate('JSON.stringify(window.__notifications)'); + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).data; + await writeFile(join(artifactDir, name), Buffer.from(data, 'base64')); + }; + + const grant = () => send('Browser.grantPermissions', { origin, permissions: ['notifications'] }); + const deny = () => send('Browser.setPermission', { + permission: { name: 'notifications' }, + setting: 'denied', + origin, + }); + const prompt = () => send('Browser.setPermission', { + permission: { name: 'notifications' }, + setting: 'prompt', + origin, + }); + + const checks = []; + const captures = []; + const check = (name, condition, detail) => { + if (!condition) throw new Error(`${name}: ${detail}`); + checks.push(name); + }; + + await prompt(); + + // 1. The initial list seed never notifies. + await navigate({ mode: 'seed' }); + const seedReport = await waitForReport('seed'); + check('seed report', seedReport.includes('posted=0'), seedReport); + check('seed silent', (await notifications()) === '[]', await notifications()); + + // 2. One live transition notifies exactly once, with the entry's own words. + await grant(); + await navigate({ mode: 'transition' }); + const transitionReport = await waitForReport('transition'); + check('transition posted once', transitionReport.includes('posted=1'), transitionReport); + const posted = JSON.parse(await notifications()); + 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])); + await capture('notification-transition-material-dark-320-2x.png'); + captures.push('notification-transition-material-dark-320-2x.png'); + + // 3. A dismissed transition never notifies. + await navigate({ mode: 'dismissed' }); + const dismissedReport = await waitForReport('dismissed'); + check('dismissed report', dismissedReport.includes('posted=0'), dismissedReport); + check('dismissed silent', (await notifications()) === '[]', await notifications()); + + // 4. A reconnect replay never notifies again. + await navigate({ mode: 'reconnect' }); + const reconnectReport = await waitForReport('reconnect'); + check('reconnect posted once', reconnectReport.includes('posted=1'), reconnectReport); + check('reconnect count', JSON.parse(await notifications()).length === 1, await notifications()); + + // 5. A denied page is honest and posts nothing. + await deny(); + await navigate({ mode: 'denied', semantics: true }); + const deniedReport = await waitForReport('denied'); + check('denied report', deniedReport.includes('state=denied') && deniedReport.includes('posted=0'), deniedReport); + check('denied silent', (await notifications()) === '[]', await notifications()); + requireLabels(await semantics().then((rows) => rows.map((r) => r.label)), [ + 'Notifications are blocked for this site.', + ], 'denied tile'); + await capture('notification-denied-material-dark-320-2x.png'); + captures.push('notification-denied-material-dark-320-2x.png'); + + // 6. An unsupported browser is honest and posts nothing. + await grant(); + await navigate({ mode: 'unsupported', semantics: true }); + const unsupportedReport = await waitForReport('unsupported'); + check('unsupported report', unsupportedReport.includes('state=unsupported'), unsupportedReport); + check('unsupported silent', (await notifications()) === '[]', await notifications()); + requireLabels(await semantics().then((rows) => rows.map((r) => r.label)), [ + 'This browser does not support notifications.', + ], 'unsupported tile'); + await capture('notification-unsupported-material-dark-320-2x.png'); + captures.push('notification-unsupported-material-dark-320-2x.png'); + + // 7. Each tile state reads honestly on both hosts, at the hardest case: + // 320 logical px and 2x text. + await prompt(); + const states = { + unsupported: 'This browser does not support notifications.', + insecure: 'Notifications need a secure context (https or localhost).', + default: 'Notifications are off. Enable them to be told when a run fails', + granted: 'Notifications are on. Failed and waiting runs will raise a browser notification.', + denied: 'Notifications are blocked for this site.', + }; + for (const host of ['material', 'cupertino']) { + for (const [state, copy] of Object.entries(states)) { + await navigate({ mode: 'tile', host, scale: 2, semantics: true, state }); + const labels = (await semantics()).map((row) => row.label); + requireLabels(labels, [ + 'Pipelines can notify you when a run is waiting', + copy, + ], `${host} ${state} tile`); + if (state === 'default') { + requireLabels(labels, ['Enable notifications'], `${host} ${state} action`); + } + checks.push(`${host} ${state} tile`); + const name = `notification-tile-${state}-${host}-dark-320-2x.png`; + await capture(name); + captures.push(name); + } + } + + console.log(JSON.stringify({ checks, captures }, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +}