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
+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