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