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