web: notify failed and waiting runs from the browser Notification API (L5)

This commit is contained in:
2026-10-19 14:11:31 +01:00
parent 2fe63012f9
commit 878b1e0bf3
9 changed files with 1007 additions and 3 deletions
+1 -1
View File
@@ -146,7 +146,7 @@ delete command).
| L2 | Wide layout: left rail + two panes | client-side | todo |
| L3 | Narrow layout: bottom section strip + bottom navigation | client-side | todo |
| L4 | Responsive switch by viewport width (no hardcoded device) | `WindowSize.kt` analogue | todo |
| L5 | Notifications for failed/waiting runs (browser Notification API; HTTPS/localhost only) | derived | todo |
| L5 | Notifications for failed/waiting runs (browser Notification API; HTTPS/localhost only) | derived from `subscribe` / `run_event` | **partial** — the browser notification path is implemented and captured in Settings, but **no real OS notification was observed**, so the row is not `done`. The exact reason: headless Chrome cannot reliably show or capture an OS notification; the smoke stubs and records the `Notification` constructor, while the transition decisions run through the page's real socket `onmessage`/`frame` path. Pure logic lives in `src/notify.js` and mirrors `notify/RunAlerts.kt` + `ui/Attention.kt`: only a run becoming `failed` (headline `A run failed`) or `waiting` (headline `A run needs your decision`) notifies; `queued`, `running`, `succeeded`, `canceled`, `interrupted` and unknown statuses never do. Body is the attention label (trimmed title else pipeline) then ` · {pipeline}`, with no separator when the pipeline is blank or equal; identity/tag is the attention key `{runId}:{kind}` so one run+kind notifies once, duplicate frames repeat nothing, a key is forgotten when the run leaves that qualifying state, and a genuinely new transition may notify again. First-seen `failed`/`waiting` from the initial `list_runs` or the `subscribe` snapshot raises nothing (the snapshot is bracketed as a seed); a disconnect drops the baseline but keeps the page session's dedupe set and reseeds before resubscribing, so a gap never notifies. A key present in the attention surface's `dismissed` set (`state.attentionDismissed`) is suppressed. Settings now shows the Android rationale verbatim (`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.`) and honest copy for unsupported, insecure context, default, granted and denied; only `default` on a supported secure page offers the explicit `Enable notifications` control, which is the only call to `Notification.requestPermission()` (never on load). Only `{asked:true|false}` is stored under `pipelines.web.notify.v1`; malformed storage decodes to never-asked and the wording never claims consent. Clicking a notification focuses the page and opens Runs with the run selected through the **existing** navigation; **L6's `/runs/:id` URL route is still `todo`**, so no URL route is invented. `subscribeRuns`/`unsubscribeRuns` send exactly `{type:'subscribe',workspace:''}` and `{type:'unsubscribe'}` (no `run_ids`, no polling timer) and are sent only after the page is connected. Unit-tested in `test/notify.test.mjs` (qualification, wording/body, per-run dedupe, seed/snapshot suppression, dismissed keys, permission copy, asked storage) and `test/repository.test.mjs` (both request shapes + the not-connected guard). Captured 2026-10-19: `captures/L5-notifications-settings.png` (default state, control offered, 0 requests on load), `captures/L5-notifications-granted.png` (after the one explicit grant) and `captures/L5-notifications-denied.png` (honest denied copy, no control). The same checks live in `test/ui-smoke.mjs` behind `--notify` (a focused mode that runs exactly this evidence); that run finished `UI SMOKE PASS` and logged: queued→failed and running→waiting each raised exactly one recorded notification, duplicates/terminal/unknown statuses/first-seen/dismissed raised none, and the click opened the run. **Not observed:** the OS notification itself. The default full live suite could not reach this block cleanly on 2026-10-19 because unrelated live chat steps (C8/C9/C12) raced the shared operator session (another live worktree was streaming into it); the captured Settings states and transition assertions above are from the focused `--notify` run, not a full-suite pass |
| L6 | Deep links to a run (`pipelines://run/…` analogue → URL route) | — | todo |
| L7 | Accessibility: focus order, labels, keyboard operation | — | todo |
+180 -1
View File
@@ -174,6 +174,15 @@ import {
decodeAttentionDismissals,
encodeAttentionDismissals,
} from "./attention.js";
import {
NOTIFICATION_RATIONALE,
NOTIFY_STORAGE_KEY,
createAlertLedger,
decodeNotificationSettings,
encodeNotificationSettings,
notificationEnvironment,
notificationPermissionState,
} from "./notify.js";
import {
DEFAULT_SEARCH_KIND,
DEFAULT_SEARCH_SORT,
@@ -469,6 +478,10 @@ const state = {
attentionDismissed: new Set(),
attentionSheetOpen: false,
attentionSnapshot: null,
// Notifications (L5): whether the operator has already been asked, loaded once
// at boot from localStorage. The browser owns the permission itself; this flag
// only changes the honest wording in Settings and is never a claim of consent.
notifyAsked: false,
// Omni-search (S1/S2): the field/panel state, kept beside the view it never
// changes, plus the pure debounce/stale-token sequencer. Opening or closing the
// search leaves state.view, the selection and the loaded data untouched.
@@ -540,6 +553,11 @@ const state = {
chatSubscriptions: new Set(),
};
// The run-notification ledger (L5). It is seeded from the authoritative run list
// and from the subscribe snapshot, then observes pushed `run_event` frames; it
// never feeds the runs list (that is R10's separate fold).
const runAlerts = createAlertLedger();
let runPoll = null;
// One shared live clock for the runs list: it ticks only while a shown run is
@@ -1006,6 +1024,76 @@ function loadAttentionDismissed() {
}
}
/**
* Fold one pushed `run_event` frame into the notification ledger (L5). It does
* not touch the runs list (R10's fold is separate); it only decides whether this
* transition raises exactly one notification. A run already failed/waiting when
* seeded, a duplicate frame, a non-qualifying status and a key the operator
* dismissed all produce nothing.
*/
function onRunAlertFrame(frame) {
const alert = runAlerts.observe(frame, { dismissed: state.attentionDismissed });
if (!alert || !notificationsAllowed()) return;
try {
const notification = new Notification(alert.title, { body: alert.body, tag: alert.key });
notification.onclick = () => {
window.focus();
state.view = "runs";
render();
selectRun(alert.runId);
};
} catch {
// Some browsers can throw even with permission granted; the in-page Needs
// you surface remains the only honest channel and nothing is faked.
}
}
/** True only when a real browser notification can be constructed right now. */
function notificationsAllowed() {
return (
typeof globalThis.Notification === "function" &&
globalThis.isSecureContext === true &&
globalThis.Notification.permission === "granted"
);
}
/** Persist only the asked flag; never a permission claim, endpoint or credential. */
function persistNotifyAsked(asked) {
state.notifyAsked = Boolean(asked);
try {
localStorage.setItem(NOTIFY_STORAGE_KEY, encodeNotificationSettings({ asked }));
} catch {
// Storage disabled or full: the in-memory flag still applies for this session.
}
}
/** The asked flag from storage at boot; anything unreadable means never asked. */
function loadNotifyAsked() {
try {
return decodeNotificationSettings(localStorage.getItem(NOTIFY_STORAGE_KEY)).asked;
} catch {
return false;
}
}
/**
* Start the run-event watch for this connected epoch: seed from the list that is
* already in hand, treat the subscribe snapshot as seeds too (the server writes
* it before the ack), then observe deltas. A refused subscribe only means no
* pushes; the page keeps working and Settings stays honest.
*/
async function startRunAlertWatch() {
runAlerts.seed(state.runs);
runAlerts.beginSeed();
try {
await repo.subscribeRuns();
} catch {
// No live watch: notifications simply cannot raise on this connection.
} finally {
runAlerts.endSeed();
}
}
function render() {
renderHeader();
renderBanner();
@@ -1111,7 +1199,12 @@ function tabButton(view, label) {
*/
function renderSettingsView() {
const pane = h("div", { class: "settings" });
pane.append(renderSettingsConnection(), renderSettingsWorkspace(), renderSettingsTemplates());
pane.append(
renderSettingsConnection(),
renderSettingsWorkspace(),
renderSettingsNotifications(),
renderSettingsTemplates(),
);
return pane;
}
@@ -1200,6 +1293,75 @@ function renderSettingsConnection() {
return section;
}
/**
* The Notifications section (L5). The Android rationale is shown verbatim; the
* status line is the pure permission view for this page's real browser facts.
* Only the explicit control asks for permission, never page load. When the API
* is unavailable, the page is insecure or permission is denied, the wording says
* plainly that the in-app Needs you surface is the only channel — no fake
* notification is ever drawn.
*/
function renderSettingsNotifications() {
const view = notificationPermissionState({
...notificationEnvironment(),
asked: state.notifyAsked,
});
const section = h("section", { class: "settings-section", id: "settingsNotifications" });
section.append(h("h2", { class: "settings-title", text: "Notifications" }));
section.append(h("p", { class: "settings-helper", text: NOTIFICATION_RATIONALE }));
section.append(
h("p", {
id: "settingsNotificationState",
class: `settings-notify-state settings-notify-${view.state}`,
role: "status",
text: view.body,
}),
);
if (view.canRequest) {
section.append(
h(
"div",
{ class: "settings-actions" },
h("button", {
id: "settingsEnableNotifications",
class: "primary",
type: "button",
text: view.actionLabel,
onclick: requestNotifications,
}),
),
);
}
return section;
}
/**
* Ask for notification permission from the operator's explicit click. The asked
* flag is persisted first and the page re-renders from the browser's real answer;
* a refused/dismissed prompt leaves the honest default/denied wording in place.
*/
function requestNotifications() {
persistNotifyAsked(true);
const ctor = globalThis.Notification;
if (typeof ctor !== "function" || !globalThis.isSecureContext) {
renderContent();
return;
}
try {
const result = ctor.requestPermission();
if (result && typeof result.then === "function") {
result.then(
() => renderContent(),
() => renderContent(),
);
return;
}
} catch {
// A browser that refuses the request keeps the honest fallback wording.
}
renderContent();
}
/** The trusted-network warning card, SettingsScreen.kt's TrustWarning verbatim. */
function renderTrustWarning() {
return h(
@@ -6649,6 +6811,9 @@ async function onConnected() {
// local, so that path is a single render and nothing is fetched twice).
renderBanner();
await loadCurrentView();
// Seed from the authoritative list first, then watch: the subscribe snapshot
// and its ack are treated as seeds, so a reconnect gap never notifies.
await startRunAlertWatch();
}
async function loadCurrentView(force = false) {
@@ -6683,11 +6848,13 @@ async function loadCurrentView(force = false) {
// history from one that has not arrived yet.
const { runs, usage } = await repo.listRuns();
state.runs = runs;
runAlerts.seed(runs);
if (usage) state.usage = usage;
state.runsLoaded = true;
} else {
const { runs, usage } = await repo.listRuns();
state.runs = runs;
runAlerts.seed(runs);
state.usage = usage;
state.runsLoaded = true;
}
@@ -6931,6 +7098,10 @@ client.addEventListener("state", (event) => {
// gone, so no thread keeps claiming to run until a fresh frame proves it.
clearChatSubscriptions();
settleChatThreads();
// Drop the run-status baseline but keep this page session's notified keys:
// the reconnect reseeds from the fresh list before it resubscribes, so a
// transition hidden by the gap can never notify late.
runAlerts.reset();
}
// A reconnect (not a first connect): re-attach the open chat's stream and
// refresh its history wholesale, so a gap that swallowed the end of a turn is
@@ -6949,6 +7120,13 @@ client.addEventListener("state", (event) => {
client.addEventListener("frame", (event) => {
const message = event.detail;
if (!message) return;
if (message.type === Protocol.RUN_EVENT) {
// L5 only: observe the pushed transition for notifications. R10's runs-list
// fold is deliberately not implemented here.
const runFrame = message[Protocol.RUN_EVENT];
if (runFrame) onRunAlertFrame(runFrame);
return;
}
if (message.type === Protocol.CHAT_PERMISSION) {
const permission = message[ChatKeys.PERMISSION];
if (permission) onChatPermission(permission);
@@ -7022,4 +7200,5 @@ window.addEventListener("online", onForegroundActive);
// The attention surface's dismissed identities are loaded once here, before the
// first render, so the bell's badge is correct from the very first paint.
state.attentionDismissed = loadAttentionDismissed();
state.notifyAsked = loadNotifyAsked();
render();
+315
View File
@@ -0,0 +1,315 @@
// Pure, DOM-free notification model for failed/waiting runs (L5). It mirrors
// android/.../notify/RunAlerts.kt: the same two qualifying kinds, the same
// headlines, the same run line and the same one-notification-per-run+kind rule.
//
// Everything here is pure: no DOM, no clock, no storage access. The page owns
// the Notification constructor, the permission request gesture and localStorage;
// the unit tests own the state machine. The attention model in `attention.js`
// is the single authority for which runs qualify and for the dismissal identity,
// so the in-page "Needs you" surface and the tray can never disagree.
import { AttentionKind, attentionKey, attentionKindOf } from "./attention.js";
// ---------------------------------------------------------------------------
// Kinds, headlines and the run line
// ---------------------------------------------------------------------------
/** The two run events that raise a notification (RunAlerts.kt RunAlertKind). */
export const RunAlertKind = Object.freeze({
Decision: AttentionKind.Decision,
Failed: AttentionKind.Failed,
});
/** `alertKindOf`: an attention kind is already exactly the notification kind. */
export function alertKindOf(kind) {
if (kind === AttentionKind.Decision || kind?.name === AttentionKind.Decision.name) {
return AttentionKind.Decision;
}
if (kind === AttentionKind.Failed || kind?.name === AttentionKind.Failed.name) {
return AttentionKind.Failed;
}
return null;
}
/** The short headline one kind shows (RunAlerts.alertTitle). */
export function alertTitle(kind) {
switch (alertKindOf(kind)?.name) {
case "Decision":
return "A run needs your decision";
case "Failed":
return "A run failed";
default:
return "";
}
}
/** The stable run+kind identity, the unit of dedupe (RunAlerts.alertKey). */
export function alertKey(runId, kind) {
const resolved = alertKindOf(kind);
return resolved ? attentionKey(runId, resolved) : "";
}
/**
* The line naming the run (RunAlerts.alertText): the attention label, then the
* pipeline it belongs to. The label is the run's trimmed title, falling back to
* the pipeline name; a blank or equal pipeline is never repeated, so there is no
* trailing separator.
*/
export function alertBody(run) {
const pipeline = String(run?.pipeline ?? run?.name ?? "");
const title = String(run?.label ?? run?.title ?? "").trim();
const label = title !== "" ? title : pipeline;
if (pipeline === "" || pipeline === label) return label;
return `${label} \u00b7 ${pipeline}`;
}
// ---------------------------------------------------------------------------
// The ledger: seed, observe, dedupe
// ---------------------------------------------------------------------------
/**
* Tracks the last status seen for every run and the run+kind alerts already
* raised in this page session.
*
* - `seed(runs)` records the authoritative list without raising anything, so a
* run that was already failed/waiting when the page loaded (or when the socket
* reconnected) never notifies.
* - `beginSeed()`/`endSeed()` bracket the `subscribe` snapshot: the server writes
* the current state of every watched run before its ack, and those frames are
* seeds too, not transitions.
* - `observe(frame)` raises only when a known run's status changes *into*
* `failed` or `waiting`. A duplicate frame (same status), an unchanged
* qualifying state, an unknown status and a first-seen run all return null.
* - A run+kind key is forgotten when the run leaves that qualifying state, so a
* genuinely new transition (for example failed -> running -> failed again) can
* notify once more; the same transition can never repeat.
* - A key present in the attention surface's dismissed set is suppressed. The
* dismissal is the attention model's own `{runId}:{kind}` identity.
* - `reset()` drops the status baseline on a socket drop but keeps the notified
* keys, so a gap that swallows a transition cannot raise a notification after
* the reconnect; the next seed establishes the new baseline.
*/
export function createAlertLedger() {
const lastStatus = new Map();
const notified = new Set();
let seeding = false;
function seed(runs) {
const next = new Map();
for (const run of runs ?? []) {
const runId = runIdOf(run?.id ?? run?.run_id);
if (runId == null) continue;
next.set(runId, normalizeStatus(run?.status));
}
lastStatus.clear();
for (const [runId, status] of next) lastStatus.set(runId, status);
pruneNotified(next);
}
function observe(frame, { dismissed } = {}) {
const runId = runIdOf(frame?.run_id ?? frame?.runId ?? frame?.id);
const status = normalizeStatus(frame?.status);
if (runId == null || status === "") return null;
const previous = lastStatus.get(runId);
lastStatus.set(runId, status);
const kind = attentionKindOf(status);
if (!kind) {
forget(runId, AttentionKind.Decision);
forget(runId, AttentionKind.Failed);
return null;
}
// A run can only be in one qualifying state; forget the other kind's key so
// a later transition back into it is a new event.
forget(runId, kind === AttentionKind.Decision ? AttentionKind.Failed : AttentionKind.Decision);
if (seeding) return null;
if (previous === undefined || previous === status) return null;
const key = alertKey(runId, kind);
if (notified.has(key)) return null;
notified.add(key);
const dismissedKeys =
dismissed instanceof Set ? dismissed : new Set(Array.isArray(dismissed) ? dismissed : []);
if (dismissedKeys.has(key)) return null;
return {
runId,
kind,
key,
title: alertTitle(kind),
body: alertBody(frame),
};
}
function reset() {
lastStatus.clear();
seeding = false;
}
function beginSeed() {
seeding = true;
}
function endSeed() {
seeding = false;
}
function forget(runId, kind) {
const key = alertKey(runId, kind);
if (key !== "") notified.delete(key);
}
function pruneNotified(statuses) {
for (const key of [...notified]) {
const split = key.lastIndexOf(":");
if (split < 0) continue;
const runId = runIdOf(key.slice(0, split));
const kindName = key.slice(split + 1);
const status = runId == null ? undefined : statuses.get(runId);
// A run that is absent from this read tells us nothing; keep its key.
if (status === undefined) continue;
const kind = attentionKindOf(status);
if (!kind || kind.name !== kindName) notified.delete(key);
}
}
return {
seed,
observe,
reset,
beginSeed,
endSeed,
/** Test/introspection helper; returns a copy, never the live set. */
notifiedKeys: () => [...notified],
statusOf: (runId) => lastStatus.get(runIdOf(runId)),
};
}
/** Trim/lowercase the server's status word; an absent value is "". */
function normalizeStatus(status) {
return String(status ?? "").trim().toLowerCase();
}
/** A positive run id as a number, or null for anything malformed. */
function runIdOf(value) {
const id = Number(value);
return Number.isFinite(id) && id > 0 ? id : null;
}
// ---------------------------------------------------------------------------
// Permission wording and persistence
// ---------------------------------------------------------------------------
/** Android's NOTIFICATION_RATIONALE, verbatim (RunAlerts.kt). */
export const NOTIFICATION_RATIONALE =
"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 explicit-gesture control's label; shown only when a request is possible. */
export const NOTIFICATION_REQUEST_LABEL = "Enable notifications";
export const NOTIFICATION_UNSUPPORTED =
"This browser does not support notifications. The in-app Needs you surface is the only channel.";
export const NOTIFICATION_INSECURE =
"Notifications need a secure context (https or localhost). This page is not secure, so the " +
"in-app Needs you surface is the only channel.";
export const NOTIFICATION_GRANTED =
"Notifications are on. Failed and waiting runs will raise a browser notification.";
export const NOTIFICATION_DENIED =
"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.";
export const NOTIFICATION_DEFAULT =
"Notifications are off. Enable them to be told when a run fails or needs your decision.";
export const NOTIFICATION_DEFAULT_ASKED =
"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 Settings. `supported` and `secureContext` are
* the browser's own facts; `permission` is the Notification API's own word
* (`default` | `granted` | `denied`, anything else treated as default).
*
* Only a supported, secure page whose permission is still `default` offers the
* request control. The request is always an explicit user gesture; nothing here
* asks on its own, and the `asked` flag only changes the honest wording.
*/
export function notificationPermissionState({
supported = true,
secureContext = true,
permission = "default",
asked = false,
} = {}) {
const state = !supported
? "unsupported"
: !secureContext
? "insecure"
: permission === "granted"
? "granted"
: permission === "denied"
? "denied"
: "default";
const canRequest = state === "default";
let body = NOTIFICATION_DEFAULT;
switch (state) {
case "unsupported":
body = NOTIFICATION_UNSUPPORTED;
break;
case "insecure":
body = NOTIFICATION_INSECURE;
break;
case "granted":
body = NOTIFICATION_GRANTED;
break;
case "denied":
body = NOTIFICATION_DENIED;
break;
default:
body = asked ? NOTIFICATION_DEFAULT_ASKED : NOTIFICATION_DEFAULT;
}
return {
state,
body,
canRequest,
actionLabel: canRequest ? NOTIFICATION_REQUEST_LABEL : null,
asked: Boolean(asked),
};
}
/**
* The browser facts the permission view needs. Pure enough to unit-test with a
* fake scope; the real page passes `globalThis`. An unrecognised permission
* value is read as `default` rather than guessed.
*/
export function notificationEnvironment(scope = globalThis) {
const ctor = scope?.Notification;
const supported = typeof ctor === "function";
const raw = supported ? ctor.permission : "default";
const permission = raw === "granted" || raw === "denied" ? raw : "default";
return { supported, secureContext: scope?.isSecureContext === true, permission };
}
/** The one localStorage key for this page's notification preference. */
export const NOTIFY_STORAGE_KEY = "pipelines.web.notify.v1";
/** Encode only the asked flag; no endpoint, credential or permission claim. */
export function encodeNotificationSettings(settings) {
return JSON.stringify({ asked: Boolean(settings?.asked) });
}
/**
* Decode the stored preference. Total: blank, unreadable JSON, a non-object, a
* non-boolean or a throwing getter all mean "never asked", so a malformed value
* can never throw into the page or claim the operator was asked.
*/
export function decodeNotificationSettings(stored) {
const text = stored == null ? "" : String(stored).trim();
if (text === "") return { asked: false };
let parsed;
try {
parsed = JSON.parse(text);
} catch {
return { asked: false };
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { asked: false };
return { asked: parsed.asked === true };
}
+8
View File
@@ -27,6 +27,14 @@ export const Protocol = Object.freeze({
GET_RUN: "get_run",
RUN: "run",
// Live run state (internal/protocol/runevents.go, L5/R10). `subscribe` sends
// the current state of the watched runs as `run_event` frames and then a
// compact delta on each transition; `unsubscribe` stops the watch. The page
// uses the frames for run notifications without changing R10's runs-list fold.
SUBSCRIBE: "subscribe",
UNSUBSCRIBE: "unsubscribe",
RUN_EVENT: "run_event",
// Omni-search (internal/protocol/search.go): the command and its reply type.
// The per-kind payloads and the kind/limit vocabulary live in src/search.js.
SEARCH: "search",
+18
View File
@@ -115,6 +115,24 @@ export class PipelinesRepository {
return response.run_detail;
}
/**
* Watches run state (L5), mirroring `PipelinesRepository.subscribeRuns` for the
* blank "any workspace" scope the runs list shows: exactly `{type:'subscribe',
* workspace:''}` and no `run_ids` (an empty list would watch the whole scope,
* but omitting the field is the shape the Android client sends). The server
* replies with the current state of every matching run as unsolicited
* `run_event` frames, then an id-matched ack, then deltas. Awaiting the ack is
* how the page knows the snapshot has been delivered.
*/
async subscribeRuns() {
return this.#client.call({ type: Protocol.SUBSCRIBE, workspace: "" });
}
/** Stops this connection's run-state watch. Best effort; a disconnect drops it. */
async unsubscribeRuns() {
return this.#client.call({ type: Protocol.UNSUBSCRIBE });
}
/**
* Omni-search. Sends exactly `SearchRequest{query, kind, limit}` from
* internal/protocol/search.go: `kind` is the empty string for every kind, and
+13
View File
@@ -2028,6 +2028,19 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
}
.settings-warning-title { margin: 0; font-weight: 600; color: var(--bad); }
.settings-warning-body { margin: 0; font-size: 12.5px; color: var(--muted); }
.settings-notify-state {
margin: 0;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--surface-2);
padding: 12px 14px;
font-size: 13px;
color: var(--muted);
}
.settings-notify-granted { border-color: color-mix(in srgb, var(--ok) 45%, var(--border)); color: var(--ok); }
.settings-notify-denied,
.settings-notify-insecure,
.settings-notify-unsupported { color: var(--warn); }
.settings-saved { margin: 0; font-size: 12px; color: var(--muted); }
.settings-save { justify-self: start; }
.settings-card {
+214
View File
@@ -0,0 +1,214 @@
// The pure notification model (L5): qualifying transitions, exactly-once
// dedupe, pre-existing/dismissed suppression, the app's exact wording and the
// total permission/storage helpers. No DOM, no timer, no live server.
import { test } from "node:test";
import assert from "node:assert/strict";
import { AttentionKind, attentionKey } from "../src/attention.js";
import {
NOTIFICATION_DEFAULT,
NOTIFICATION_DEFAULT_ASKED,
NOTIFICATION_DENIED,
NOTIFICATION_GRANTED,
NOTIFICATION_INSECURE,
NOTIFICATION_UNSUPPORTED,
NOTIFY_STORAGE_KEY,
alertBody,
alertKey,
alertTitle,
createAlertLedger,
decodeNotificationSettings,
encodeNotificationSettings,
notificationEnvironment,
notificationPermissionState,
} from "../src/notify.js";
const frame = (runId, status, extra = {}) => ({
run_id: runId,
status,
name: "release",
title: "Ship it",
...extra,
});
test("headlines are exactly the app's two, and unknown kinds are blank", () => {
assert.equal(alertTitle(AttentionKind.Failed), "A run failed");
assert.equal(alertTitle(AttentionKind.Decision), "A run needs your decision");
assert.equal(alertTitle({ name: "Failed" }), "A run failed");
assert.equal(alertTitle({ name: "Other" }), "");
});
test("the alert identity is the attention identity", () => {
assert.equal(alertKey(7, AttentionKind.Failed), attentionKey(7, AttentionKind.Failed));
assert.equal(alertKey(7, AttentionKind.Decision), "7:Decision");
});
test("alert body is the title then the pipeline, with the pipeline fallback", () => {
assert.equal(alertBody({ label: "Ship it", pipeline: "release" }), "Ship it \u00b7 release");
assert.equal(alertBody({ title: " Ship it ", name: "release" }), "Ship it \u00b7 release");
assert.equal(alertBody({ title: " ", name: "release" }), "release");
assert.equal(alertBody({ label: "release", pipeline: "release" }), "release");
assert.equal(alertBody({ label: "Ship it", pipeline: "" }), "Ship it");
assert.equal(alertBody(frame(7, "failed")), "Ship it \u00b7 release");
});
test("queued -> failed raises one alert and duplicate frames never repeat it", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 4, status: "queued", name: "release", title: "Ship it" }]);
const alert = ledger.observe(frame(4, "failed"));
assert.equal(alert.title, "A run failed");
assert.equal(alert.body, "Ship it \u00b7 release");
assert.equal(alert.key, "4:Failed");
assert.equal(ledger.observe(frame(4, "failed")), null);
assert.equal(ledger.observe(frame(4, "failed")), null);
});
test("running -> waiting raises the decision alert; unchanged waiting raises none", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 9, status: "running", name: "release", title: "Ship it" }]);
const alert = ledger.observe(frame(9, "waiting"));
assert.equal(alert.title, "A run needs your decision");
assert.equal(alert.key, "9:Decision");
assert.equal(ledger.observe(frame(9, "waiting")), null);
});
test("succeeded, canceled, interrupted and unknown statuses raise nothing", () => {
for (const status of ["succeeded", "canceled", "interrupted", "mystery", ""]) {
const ledger = createAlertLedger();
ledger.seed([{ id: 11, status: "running" }]);
assert.equal(ledger.observe(frame(11, status)), null, `status ${status}`);
}
});
test("a first-seen failed/waiting run (a snapshot seed) raises nothing", () => {
const ledger = createAlertLedger();
assert.equal(ledger.observe(frame(21, "failed")), null);
assert.equal(ledger.observe(frame(22, "waiting")), null);
});
test("a run already failed/waiting in the seed raises nothing", () => {
const ledger = createAlertLedger();
ledger.seed([
{ id: 31, status: "failed" },
{ id: 32, status: "waiting" },
]);
assert.equal(ledger.observe(frame(31, "failed")), null);
assert.equal(ledger.observe(frame(32, "waiting")), null);
});
test("the subscribe snapshot is seeded, so a queued run that failed in the gap does not notify", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 41, status: "queued" }]);
ledger.beginSeed();
assert.equal(ledger.observe(frame(41, "failed")), null);
ledger.endSeed();
assert.equal(ledger.observe(frame(41, "failed")), null);
// A later real transition still raises exactly once.
assert.equal(ledger.observe(frame(41, "running")), null);
assert.equal(ledger.observe(frame(41, "failed")).key, "41:Failed");
});
test("leaving the qualifying state forgets the key for a genuinely new transition", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 51, status: "queued" }]);
assert.equal(ledger.observe(frame(51, "failed")).key, "51:Failed");
assert.equal(ledger.observe(frame(51, "running")), null);
assert.equal(ledger.observe(frame(51, "failed")).key, "51:Failed");
// And a failed -> waiting hand-off raises the other kind once.
assert.equal(ledger.observe(frame(51, "waiting")).key, "51:Decision");
assert.equal(ledger.observe(frame(51, "waiting")), null);
});
test("a dismissed attention key notifies nothing, even on a real transition", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 61, status: "queued" }]);
const alert = ledger.observe(frame(61, "failed"), {
dismissed: new Set([attentionKey(61, AttentionKind.Failed)]),
});
assert.equal(alert, null);
assert.deepEqual(ledger.notifiedKeys(), ["61:Failed"]);
});
test("reset drops the status baseline but keeps the page session's dedupe", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 71, status: "queued" }]);
assert.equal(ledger.observe(frame(71, "failed")).key, "71:Failed");
ledger.reset();
// Re-seeding the fresh (still failed) list is not a transition.
ledger.seed([{ id: 71, status: "failed" }]);
assert.equal(ledger.observe(frame(71, "failed")), null);
assert.deepEqual(ledger.notifiedKeys(), ["71:Failed"]);
});
test("a malformed frame is ignored, never crashed on", () => {
const ledger = createAlertLedger();
assert.equal(ledger.observe(null), null);
assert.equal(ledger.observe({}), null);
assert.equal(ledger.observe({ run_id: 0, status: "failed" }), null);
});
test("permission wording is honest for every browser state", () => {
assert.equal(notificationPermissionState({ supported: false }).body, NOTIFICATION_UNSUPPORTED);
assert.equal(
notificationPermissionState({ supported: true, secureContext: false }).body,
NOTIFICATION_INSECURE,
);
assert.equal(notificationPermissionState({ permission: "denied" }).body, NOTIFICATION_DENIED);
assert.equal(notificationPermissionState({ permission: "granted" }).body, NOTIFICATION_GRANTED);
assert.equal(notificationPermissionState({ asked: false }).body, NOTIFICATION_DEFAULT);
assert.equal(notificationPermissionState({ asked: true }).body, NOTIFICATION_DEFAULT_ASKED);
});
test("only a supported, secure default permission offers the request control", () => {
const defaultView = notificationPermissionState({ asked: false });
assert.equal(defaultView.state, "default");
assert.equal(defaultView.canRequest, true);
assert.equal(defaultView.actionLabel, "Enable notifications");
for (const options of [
{ supported: false },
{ supported: true, secureContext: false },
{ permission: "granted" },
{ permission: "denied" },
]) {
const view = notificationPermissionState(options);
assert.equal(view.canRequest, false, JSON.stringify(options));
assert.equal(view.actionLabel, null, JSON.stringify(options));
}
// Having been asked once does not remove the control while permission stays
// default (the browser itself decides whether it may prompt again).
assert.equal(notificationPermissionState({ asked: true }).canRequest, true);
});
test("the asked flag round-trips and malformed storage decodes safely", () => {
assert.equal(NOTIFY_STORAGE_KEY, "pipelines.web.notify.v1");
const stored = encodeNotificationSettings({ asked: true });
assert.deepEqual(JSON.parse(stored), { asked: true });
assert.equal(decodeNotificationSettings(stored).asked, true);
assert.equal(decodeNotificationSettings(encodeNotificationSettings({ asked: false })).asked, false);
for (const bad of ["", " ", "not json", "[]", "null", '"asked"', "{", '{"asked":"yes"}', "42"]) {
assert.deepEqual(decodeNotificationSettings(bad), { asked: false }, bad);
}
assert.deepEqual(decodeNotificationSettings(null), { asked: false });
});
test("notificationEnvironment reads the browser facts without guessing", () => {
const granted = notificationEnvironment({
Notification: Object.assign(function Notification() {}, { permission: "granted" }),
isSecureContext: true,
});
assert.deepEqual(granted, { supported: true, secureContext: true, permission: "granted" });
assert.deepEqual(notificationEnvironment({}), {
supported: false,
secureContext: false,
permission: "default",
});
const odd = notificationEnvironment({
Notification: Object.assign(function Notification() {}, { permission: "maybe" }),
isSecureContext: false,
});
assert.deepEqual(odd, { supported: true, secureContext: false, permission: "default" });
});
+24
View File
@@ -293,6 +293,30 @@ test("a run action throws when the reply has no run detail", async () => {
await assert.rejects(() => repo.cancelRun(7), ProtocolError);
});
test("subscribeRuns sends exactly the blank any-workspace watch and no run_ids", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "subscribe" });
await repo.subscribeRuns();
assert.deepEqual(lastFrame(ws), { type: "subscribe", workspace: "" });
});
test("unsubscribeRuns sends exactly {type:'unsubscribe'}", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "unsubscribe" });
await repo.unsubscribeRuns();
assert.deepEqual(lastFrame(ws), { type: "unsubscribe" });
});
test("subscribeRuns is not sent while the page is not connected", async () => {
FakeWebSocket.instances = [];
const client = new PipelinesClient({ WebSocketImpl: FakeWebSocket });
const repo = new PipelinesRepository(client);
await assert.rejects(() => repo.subscribeRuns(), { name: "NotConnectedError" });
assert.equal(FakeWebSocket.instances.length, 0);
});
// ---- The composer's own commands (C8/C9) ----------------------------------
test("chatPrompt trims the text, sends the operation and native message ids, and omits files when empty", async () => {
+234 -1
View File
@@ -32,6 +32,12 @@ import {
WORKSPACE_PLACEHOLDER,
WORKSPACE_STORAGE_KEY,
} from "../src/settings.js";
import {
NOTIFICATION_DEFAULT,
NOTIFICATION_DENIED,
NOTIFICATION_GRANTED,
NOTIFY_STORAGE_KEY,
} from "../src/notify.js";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
@@ -59,6 +65,8 @@ const out = resolve(
// Scratch mode: only the P5 create-from-template flow runs, against a throwaway
// server with its own database. The default (live) run sends no submit.
const scratch = process.argv.includes("--scratch");
// Focused notification evidence only; skips the unrelated live-suite steps.
const notifyOnly = process.argv.includes("--notify");
// The page must connect through its own proxy (the server rejects a cross-origin
// upgrade), but serve.mjs only proxies /connect — not /artifacts. Point the URL
@@ -372,6 +380,225 @@ const drag = (dx, dy) =>
return true;
})()`);
// L5: the notification Settings states and the synthetic transition assertions.
// Extracted so `--notify` can run exactly this evidence without the unrelated
// live-suite steps; the default full run calls it in its L1/L5 position.
async function runNotificationChecks() {
// L5: notifications. A real OS notification cannot be captured reliably in
// headless Chrome, so the browser's Notification constructor is stubbed and
// recorded before this document loads; the qualifying transitions are then
// pushed through the page's own socket `onmessage`/`frame` path and matched
// against the pure ledger's decisions. The Settings states are real renders.
// The stub also pre-dismisses one synthetic run+kind so suppression is proven
// through the same attention identity the page loads at boot.
step("L5: notification settings and synthetic run transitions");
await page.addInitScript(`(() => {
if (window.__notificationStubInstalled) return;
window.__notificationStubInstalled = true;
window.__notificationCalls = [];
window.__notificationObjects = [];
window.__notificationRequests = 0;
window.__notificationPermission = "default";
function FakeNotification(title, options) {
const call = {
title: String(title),
body: String(options && options.body != null ? options.body : ""),
tag: String(options && options.tag != null ? options.tag : ""),
};
window.__notificationCalls.push(call);
window.__notificationObjects.push(this);
this.title = call.title;
this.body = call.body;
this.tag = call.tag;
this.onclick = null;
this.close = function () {};
}
Object.defineProperty(FakeNotification, "permission", {
configurable: true,
get: function () { return window.__notificationPermission; },
});
FakeNotification.requestPermission = function () {
window.__notificationRequests += 1;
window.__notificationPermission = "granted";
return Promise.resolve("granted");
};
Object.defineProperty(window, "Notification", {
configurable: true,
writable: true,
value: FakeNotification,
});
localStorage.setItem("pipelines.web.attention.v1", JSON.stringify(["990001:Failed"]));
})()`);
await page.evaluate(`location.reload()`);
await page.waitForSelector("#url", { timeout: 15000 });
await page.fill("#url", `ws://127.0.0.1:${port}/connect`);
await page.click("#connectBtn");
await page.waitForSelector(".conn-banner.conn-ok", { timeout: 25000 });
// The watch is sent once per connected epoch, after the list has seeded the
// ledger. Wait for that send (and its ack continuation) so the synthetic
// frames below are observed as deltas rather than as part of the snapshot.
await eventually(
() => page.evaluate(`(window.__pipelinesSentTypes || []).includes("subscribe")`),
{ timeout: 15000, what: "the run-event subscribe frame" },
);
await page.evaluate(`new Promise((resolve) => setTimeout(resolve, 250))`);
await page.clickText("nav.tabs button.tab", "Settings");
await page.waitForSelector("#settingsNotificationState", { timeout: 15000 });
// Default state: honest wording, one explicit control, and nothing asked on
// load or on connect.
const defaultNotificationState = await text("#settingsNotificationState");
if (defaultNotificationState !== NOTIFICATION_DEFAULT) {
throw new Error(`default notification copy: ${defaultNotificationState}`);
}
const notificationsOnLoad = await page.evaluate(`window.__notificationRequests`);
if (notificationsOnLoad !== 0) {
throw new Error(`the page requested notification permission on load: ${notificationsOnLoad}`);
}
const enableControl = await page.evaluate(
`document.querySelector("#settingsEnableNotifications")?.textContent ?? ""`,
);
if (enableControl !== "Enable notifications") {
throw new Error(`notification request control: ${enableControl}`);
}
await page.evaluate(`document.querySelector("#settingsNotifications")?.scrollIntoView({ block: "center" })`);
await shot("L5-notifications-settings.png");
console.log(` notifications default: "${defaultNotificationState}" (0 permission requests on load)`);
// The explicit control grants through the stub; the page must remember that it
// asked and stop offering the control.
await page.click("#settingsEnableNotifications");
await eventually(
() => page.evaluate(`document.querySelector("#settingsNotificationState")?.textContent === ${JSON.stringify(NOTIFICATION_GRANTED)}`),
{ timeout: 10000, what: "the granted notification wording" },
);
const grantState = await page.evaluate(`({
requests: window.__notificationRequests,
stored: localStorage.getItem(${JSON.stringify(NOTIFY_STORAGE_KEY)}),
control: !!document.querySelector("#settingsEnableNotifications"),
})`);
if (grantState.requests !== 1 || grantState.control) {
throw new Error(`grant state: ${JSON.stringify(grantState)}`);
}
if (grantState.stored !== JSON.stringify({ asked: true })) {
throw new Error(`asked flag not stored: ${grantState.stored}`);
}
await page.evaluate(`document.querySelector("#settingsNotifications")?.scrollIntoView({ block: "center" })`);
await shot("L5-notifications-granted.png");
console.log(` notifications granted after one explicit click; asked=${grantState.stored}`);
// Drive the real frame path. The run id is a real run so the notification's
// click can open it through the page's existing Runs navigation (L6 is todo).
await page.clickText("nav.tabs button.tab", "Runs");
await page.waitForSelector(".list.runs .run-row-meta[data-run-id]", { timeout: 25000 });
const realRunId = await page.evaluate(
`Number(document.querySelector(".list.runs .run-row-meta[data-run-id]")?.getAttribute("data-run-id"))`,
);
if (!(realRunId > 0)) throw new Error(`no real run id for the notification click: ${realRunId}`);
const runFrame = (runId, status, extra = {}) => ({
run_id: runId,
status,
name: "Smoke pipeline",
title: "Smoke run",
...extra,
});
const replayRunEvents = (frames) =>
page.evaluate(`(() => {
const ws = window.__pipelinesSocket;
if (!ws || typeof ws.onmessage !== "function") return false;
for (const frame of ${JSON.stringify(frames)}) {
ws.onmessage({ data: JSON.stringify({ type: "run_event", run_event: frame }) });
}
return true;
})()`);
const notificationCount = () => page.evaluate(`window.__notificationCalls.length`);
const notifications = () => page.evaluate(`window.__notificationCalls`);
// queued -> failed raises exactly one; duplicate/terminal/unknown frames add none.
if (!(await replayRunEvents([runFrame(realRunId, "queued")]))) {
throw new Error("L5: the socket shim did not expose the live socket for run events");
}
await replayRunEvents([runFrame(realRunId, "failed")]);
if ((await notificationCount()) !== 1) {
throw new Error(`queued->failed should notify once: ${JSON.stringify(await notifications())}`);
}
const failedAlert = (await notifications())[0];
const failedTag = `${realRunId}:Failed`;
if (
failedAlert.title !== "A run failed" ||
failedAlert.body !== "Smoke run \u00b7 Smoke pipeline" ||
failedAlert.tag !== failedTag
) {
throw new Error(`failed alert wording/tag: ${JSON.stringify(failedAlert)}`);
}
await replayRunEvents([runFrame(realRunId, "failed")]);
if ((await notificationCount()) !== 1) throw new Error("a duplicate failed frame repeated the notification");
for (const status of ["succeeded", "canceled", "interrupted", "mystery"]) {
await replayRunEvents([runFrame(realRunId, status)]);
}
if ((await notificationCount()) !== 1) {
throw new Error(`a non-qualifying status raised a notification: ${JSON.stringify(await notifications())}`);
}
console.log(` queued -> failed raised one: ${JSON.stringify(failedAlert)}`);
// running -> waiting raises exactly one decision alert; a duplicate adds none.
await replayRunEvents([runFrame(realRunId, "running"), runFrame(realRunId, "waiting")]);
if ((await notificationCount()) !== 2) {
throw new Error(`running->waiting should notify once: ${JSON.stringify(await notifications())}`);
}
const waitingAlert = (await notifications())[1];
if (
waitingAlert.title !== "A run needs your decision" ||
waitingAlert.body !== "Smoke run \u00b7 Smoke pipeline" ||
waitingAlert.tag !== `${realRunId}:Decision`
) {
throw new Error(`waiting alert wording/tag: ${JSON.stringify(waitingAlert)}`);
}
await replayRunEvents([runFrame(realRunId, "waiting")]);
if ((await notificationCount()) !== 2) throw new Error("a duplicate waiting frame repeated the notification");
// First-seen failed/waiting (the subscribe/seed rule) and a dismissed key
// raise nothing; the dismissed identity is the one loaded at boot.
await replayRunEvents([
runFrame(990002, "failed"),
runFrame(990003, "waiting"),
runFrame(990001, "queued"),
runFrame(990001, "failed"),
]);
if ((await notificationCount()) !== 2) {
throw new Error(`pre-existing/dismissed runs notified: ${JSON.stringify(await notifications())}`);
}
console.log(" running -> waiting raised one; duplicates, terminal/unknown statuses, first-seen and dismissed runs raised none");
// The click focuses the page and uses the existing Runs navigation to select
// the run (L6's URL route is still todo; no route is invented).
await page.evaluate(`window.__notificationObjects[0]?.onclick?.()`);
await eventually(
() =>
page.evaluate(
`!!document.querySelector('.list.runs .run-row.selected .run-row-meta[data-run-id="${realRunId}"]')`,
),
{ timeout: 20000, what: "the notification click to open Runs with the run selected" },
);
console.log(` notification click opened Runs with run ${realRunId} selected`);
// The denied state is rendered from the same pure wording and offers no control.
await page.evaluate(`window.__notificationPermission = "denied"`);
await page.clickText("nav.tabs button.tab", "Settings");
await eventually(
() => page.evaluate(`document.querySelector("#settingsNotificationState")?.textContent === ${JSON.stringify(NOTIFICATION_DENIED)}`),
{ timeout: 10000, what: "the denied notification wording" },
);
const deniedControl = await page.evaluate(`!!document.querySelector("#settingsEnableNotifications")`);
if (deniedControl) throw new Error("the denied state still offers the request control");
await page.evaluate(`document.querySelector("#settingsNotifications")?.scrollIntoView({ block: "center" })`);
await shot("L5-notifications-denied.png");
console.log(` notifications denied: "${NOTIFICATION_DENIED}" (no request control)`);
console.log(
" NOTE: the notification frames above are synthetic and the browser Notification was recorded by a stub; no real OS notification was observed",
);
}
try {
await mkdir(out, { recursive: true });
@@ -509,7 +736,11 @@ try {
for (const shot of shots) console.log(` ${shot}`);
}
if (!scratch) {
if (notifyOnly) {
await runNotificationChecks();
console.log("\nUI SMOKE PASS");
for (const shot of shots) console.log(` ${shot}`);
} else if (!scratch) {
const pipelineCount = await page.evaluate(
`document.querySelectorAll("#pipelineRows button.row").length`,
);
@@ -4651,6 +4882,8 @@ try {
}
console.log(` reload restored url=${restoredUrl} workspace=${restoredWorkspace}`);
await runNotificationChecks();
// C11: the background-tasks bar. The live server has no running shell to read
// safely, so the bar is driven from synthetic `shell` frames replayed through
// the page's own socket handler (the same shim) and the bounded output pages are