merge(app): land notification capability after a retained deadline

This commit is contained in:
2026-10-22 02:05:36 +01:00
19 changed files with 2882 additions and 0 deletions
@@ -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<String> 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();
@@ -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<String> requestPermission() async => 'default';
@override
bool show(NotificationMessage message, {void Function()? onTap}) => false;
}
NotificationBridge createNotificationBridge() =>
const UnsupportedNotificationBridge();
@@ -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<JSString> 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<JSAny?>('Notification'.toJS).isA<JSFunction>();
/// The browser's own secure-context flag; anything but a real boolean is false.
bool _secureContext() {
final value = globalContext.getProperty<JSAny?>('isSecureContext'.toJS);
return value.isA<JSBoolean>() && (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<String> 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();
@@ -0,0 +1,250 @@
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 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
/// 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();
/// 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 transition instance announced this session for each identity: a new
/// instance means the run entered the state again.
final Map<String, AttentionTransition> _announced = {};
/// The queued ledger writes, so an older snapshot cannot land after a newer one.
Future<void> _writes = Future<void>.value();
/// The platform's own permission state for this page.
NotificationPermissionState get permission => _permission;
/// 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;
/// A copy of the transition identities this client has already announced.
/// Returned unmodifiable, so a caller cannot mutate the ledger behind
/// [publishTransitions]' back.
Set<String> get notified => Set<String>.unmodifiable(_ledger.notified);
/// True only when the platform itself reported `granted`.
bool get canNotify => _permission == NotificationPermissionState.granted;
/// 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<void> load() async {
NotificationLedger ledger;
try {
ledger = decodeNotificationLedger(await store.read());
} catch (_) {
ledger = const NotificationLedger();
}
if (_disposed) return;
_ledger = ledger;
_announced.clear();
_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<NotificationPermissionState> 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.
///
/// [qualifying] is [notificationQualifyingKeys] for the *same* snapshot as
/// [transitions]: a transition whose run has left the state is stale and
/// neither posts nor records anything, then every recorded identity outside
/// [qualifying] is forgotten so the next gate can notify. Only the latest
/// entry per run+kind in a backlog is announced.
///
/// A caller that misses the leaving frame still gets the new transition: the
/// detector creates one instance per genuine transition, so an identity
/// announced earlier this session with a different instance is a new
/// occurrence; the same instance, and an identity loaded from the store before
/// this session, stay silent.
///
/// The initial seed raises no transition. A transition the operator dismissed,
/// one already recorded and one past [maxNotificationsPerBatch] post nothing.
/// Returns how many notifications the platform accepted.
int publishTransitions(
Iterable<AttentionTransition> transitions, {
required Set<String> qualifying,
Set<String> dismissed = const {},
}) {
if (_disposed) return 0;
var posted = 0;
var changed = false;
// A backlog may hold several entries for one run+kind; only the latest one
// describes the state that is current, so a coalesced burst notifies once.
final latest = <String, AttentionTransition>{};
for (final transition in transitions) {
latest[notificationIdentity(transition)] = transition;
}
for (final transition in latest.values) {
if (posted >= maxNotificationsPerBatch) break;
final identity = notificationIdentity(transition);
// 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(
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++;
}
}
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, one write
/// at a time so their order matches the calls.
Future<void> _persist(NotificationLedger ledger) {
final encoded = encodeNotificationLedger(ledger);
final write = _writes.then((_) async {
if (_disposed) return;
try {
await store.write(encoded);
} catch (_) {
// The in-memory ledger still applies for this session.
}
});
_writes = write;
return write;
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
@@ -0,0 +1,122 @@
import 'dart:convert';
import '../../../core/api_gateway.dart';
import '../domain/attention_models.dart';
import '../domain/attention_transitions.dart';
/// This client's own storage key for the notification ledger, namespaced like
/// the rest of the app. It is deliberately not the legacy web key, so neither
/// client rewrites the other's local state on a shared origin.
const notificationStorageKey = 'pipelines.next.notify.v1';
/// The identity of one announced transition: the run and kind, exactly the
/// attention surface's own key and the browser's `alertKey`.
///
/// It is deliberately *not* keyed by a timestamp. A waiting run has no
/// `finished_at`, and its creation time never changes, so a marker derived from
/// them cannot tell a run's first decision gate from a later one. Instead the
/// ledger only holds identities for the runs that are qualifying *right now*:
/// [notificationQualifyingKeys] supplies that set, and an identity is forgotten
/// as soon as its run leaves the qualifying state (see [NotificationLedger.pruning]).
/// The next entry into the same state is therefore a new announcement, exactly
/// as in `web/src/notify.js`.
String notificationIdentity(AttentionTransition transition) => transition.key;
/// The `{runId}:{Kind}` identities of the runs currently in a qualifying state,
/// built from the same rows the attention surface draws.
///
/// Dismissals and the local-day window are deliberately ignored: a dismissal
/// does not stop a run qualifying, and an old failure is still the same
/// announced transition rather than a new one.
Set<String> notificationQualifyingKeys(Iterable<JsonMap>? runs) {
final keys = <String>{};
for (final run in runs ?? const <JsonMap>[]) {
final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']);
final kind = attentionKindForRun(run);
if (runId == null || kind == null) continue;
keys.add(attentionKey(runId, kind));
}
return keys;
}
/// What this client has already announced, plus whether the operator has ever
/// been asked.
///
/// The ledger is pure: it records identities, decides whether one is new and
/// drops the ones whose run no longer qualifies. Persistence is the store's job.
///
/// An identity lives only while its run is in the qualifying state it announced:
/// publishing the same list again is idempotent, a reconnect cannot repeat a
/// notification, and a genuinely new transition (a second decision gate, or a
/// later failure of a new run id) notifies once more because leaving the state
/// dropped the old identity. This is the browser's `forget` model; unlike a
/// timestamp marker it can tell two decision gates of one run apart.
class NotificationLedger {
const NotificationLedger({
this.notified = const <String>{},
this.asked = false,
});
/// The transition identities already recorded, in no particular order.
final Set<String> notified;
/// Whether the operator has ever been asked for permission.
final bool asked;
bool hasNotified(String identity) => notified.contains(identity);
/// The ledger with [identity] recorded.
NotificationLedger recording(String identity) =>
NotificationLedger(notified: {...notified, identity}, asked: asked);
NotificationLedger withAsked(bool value) =>
NotificationLedger(notified: notified, asked: value);
/// The ledger with every identity outside [qualifying] dropped.
///
/// A run that is no longer failed or waiting has left its announced state, so
/// a later entry is a new event and must be able to notify again. Keeping only
/// the current qualifying identities also bounds the ledger to the runs the
/// surface currently holds instead of growing with every event ever seen.
NotificationLedger pruning(Set<String> qualifying) {
final kept = notified.where(qualifying.contains).toSet();
if (kept.length == notified.length) return this;
return NotificationLedger(notified: kept, asked: asked);
}
}
/// The one-line JSON the ledger is stored as. The identities are sorted so an
/// unchanged ledger always encodes to the same bytes.
String encodeNotificationLedger(NotificationLedger ledger) {
final identities = ledger.notified.where((id) => id.isNotEmpty).toList()
..sort();
return jsonEncode({'asked': ledger.asked, 'notified': identities});
}
/// Decodes a stored value into a ledger. Total: blank text, unreadable JSON, a
/// non-map, a non-boolean `asked` and non-string members all decode to the
/// members that can be read, and a malformed value never throws.
///
/// A value written by an older build may still contain timestamped identities;
/// they simply stop matching [notificationQualifyingKeys] and are dropped on the
/// next publish, so no migration step is needed.
NotificationLedger decodeNotificationLedger(String? stored) {
final text = (stored ?? '').trim();
if (text.isEmpty) return const NotificationLedger();
dynamic parsed;
try {
parsed = jsonDecode(text);
} catch (_) {
return const NotificationLedger();
}
if (parsed is! Map) return const NotificationLedger();
final raw = parsed['notified'];
return NotificationLedger(
notified: {
if (raw is List)
for (final value in raw)
if (value is String && value.isNotEmpty) value,
},
asked: parsed['asked'] == true,
);
}
@@ -0,0 +1,169 @@
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;
}
@@ -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<String?> read();
Future<bool> 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<SharedPreferences?> _preferences() async {
try {
return await SharedPreferences.getInstance();
} catch (_) {
return null;
}
}
@override
Future<String?> read() async {
final preferences = await _preferences();
if (preferences == null) return null;
try {
return preferences.getString(notificationStorageKey);
} catch (_) {
return null;
}
}
@override
Future<bool> 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<String?> read() async {
if (failReads) throw StateError('notification store unavailable');
return stored;
}
@override
Future<bool> write(String value) async {
writes++;
if (failWrites) throw StateError('notification store is read-only');
stored = value;
return true;
}
}
@@ -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<String>('notification-permission-tile');
/// The explicit-gesture Enable action, present only when a request is possible.
const notificationEnableKey = ValueKey<String>(
'notification-permission-enable',
);
/// The honest state line, which says plainly when the in-app surface is the
/// only channel.
const notificationStateKey = ValueKey<String>('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),
);
}
}
+182
View File
@@ -0,0 +1,182 @@
# 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; outside those
paths only this note, the notify tests and the isolated probe changed.
## What is there
| File | Lines | Role |
| --- | --- | --- |
| `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` | 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` | 250 | the `ChangeNotifier` capability |
| `ui/notification_permission_tile.dart` | 127 | the reusable native tile |
| `tool/notification_probe.dart` / `.mjs` | 291 / 314 | 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, 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.
- `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
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.
- `notified` returns an unmodifiable copy, so a caller cannot mutate the ledger
behind the controller's back.
## 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 *every* authoritative read and pushed frame the attention controller handles:
notify.publishTransitions(
attention.transitions,
qualifying: notificationQualifyingKeys(attention.rows),
dismissed: attention.dismissed,
);
```
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` — **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).
- `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 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 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
- `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 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.
@@ -0,0 +1,181 @@
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';
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(publish(notify, attention), 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(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');
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(publish(notify, attention), 1);
attention.observeFrame(runFrame(1, 'failed'));
expect(attention.transitions, hasLength(1));
expect(publish(notify, attention), 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(publish(notify, attention), 1);
attention.resetForReconnect();
attention.seedRows([runSummary(1, 'failed')], reconnect: true);
expect(publish(notify, attention), 0);
attention.observeFrame(runFrame(1, 'failed'));
expect(publish(notify, attention), 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(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'));
expect(publish(restarted, attention), 0);
expect(bridge.shown, hasLength(1));
});
test('a later failure of another run notifies independently', () 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'), runSummary(2, 'running')]);
attention.observeFrame(runFrame(1, 'failed'));
expect(publish(notify, attention), 1);
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('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();
attention.seedRows([runSummary(1, 'running')]);
attention.observeFrame(runFrame(1, 'failed'));
expect(publish(notify, attention), 1);
// 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));
});
});
}
@@ -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 = <int>[];
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<void>.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<String> writes = [];
@override
Future<String?> read() async => stored;
@override
Future<bool> write(String value) async {
active++;
if (active > maxActive) maxActive = active;
await Future<void>.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<String> requestPermission() async => 'granted';
@override
bool show(NotificationMessage message, {void Function()? onTap}) =>
throw StateError('the browser refused to construct a notification');
}
@@ -0,0 +1,143 @@
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 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');
expect(notificationIdentity(second), '7:Failed');
});
test('a waiting run needs no finish time to have an identity', () {
final entry = transitionFor(7, status: 'waiting', finishedAt: '');
expect(notificationIdentity(entry), '7:Decision');
});
test('the kind separates a decision from a failure of one run', () {
expect(
notificationIdentity(transitionFor(7)),
isNot(notificationIdentity(transitionFor(7, status: 'waiting'))),
);
});
});
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');
final twice = once.recording('7:Failed');
expect(base.notified, isEmpty);
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);
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),
);
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',
);
});
});
}
@@ -0,0 +1,158 @@
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');
});
});
}
@@ -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);
},
);
});
}
@@ -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');
});
}
@@ -0,0 +1,136 @@
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';
/// 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<String, dynamic> runSummary(
int id,
String status, {
String name = 'release',
String? title,
Duration age = const Duration(hours: 1),
String diagnostic = '',
Object? exportPending,
Map<String, dynamic> extra = const {},
}) => {
'id': id,
'name': name,
'title': title ?? 'Run $id',
'status': status,
'diagnostic': diagnostic,
'created_at': at(age),
// 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 waiting or running frame has no `finished_at`, matching the server; pass
/// [finishedAt] only to describe a settled run.
Map<String, dynamic> 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 ??
(status == 'waiting' || status == 'running'
? ''
: 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),
)!,
);
/// Let the controller's fire-and-forget ledger write land.
Future<void> settle() => Future<void>.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);
/// 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<NotificationMessage> shown = [];
final List<void Function()?> taps = [];
@override
NotificationEnvironment environment() => NotificationEnvironment(
supported: supported,
secureContext: secureContext,
permission: permission,
);
@override
Future<String> requestPermission() async {
requests++;
permission = answer;
return answer;
}
@override
bool show(NotificationMessage message, {void Function()? onTap}) {
shown.add(message);
taps.add(onTap);
return accepts;
}
}
@@ -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, String>{
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<RenderParagraph>(
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<RenderParagraph>(
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);
});
}
}
+291
View File
@@ -0,0 +1,291 @@
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_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';
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 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() {
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<String, dynamic> _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)),
// 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<String, dynamic> _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': 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 {
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<void> _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'),
]);
_publish(notify, attention);
case 'dismissed':
attention.seedRows([_summary(1, 'running')]);
await attention.dismiss(attentionEntryFor(_summary(1, 'failed'))!);
attention.observeFrame(_frame(1, 'failed'));
_publish(notify, attention);
case 'reconnect':
attention.seedRows([_summary(1, 'running')]);
attention.observeFrame(_frame(1, 'failed'));
_publish(notify, attention);
attention.resetForReconnect();
attention.seedRows([_summary(1, 'failed')], reconnect: true);
_publish(notify, attention);
attention.observeFrame(_frame(1, 'failed'));
_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'));
_publish(notify, attention);
default:
attention.seedRows([_summary(1, 'running', name: 'nightly')]);
attention.observeFrame(
_frame(
1,
'failed',
name: 'nightly',
title: 'Nightly audit',
diagnostic: 'Stage 3 stopped',
),
);
_publish(notify, attention);
}
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: () {}),
],
],
),
),
),
);
}
}
+314
View File
@@ -0,0 +1,314 @@
// Real-browser acceptance for the attention notification capability.
//
// flutter build web -t tool/notification_probe.dart -o build/notification_probe_web
// OPENCODE_ARTIFACT_DIR=<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
// 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';
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', 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');
// 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());
// 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 });
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 });
}