Files
pipelines/app/notes/A2-notify.md
T

183 lines
11 KiB
Markdown

# 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.