330 lines
12 KiB
JavaScript
330 lines
12 KiB
JavaScript
// Pure, DOM-free notification model. Auto retains failed/waiting alerts;
|
|
// per-run on also alerts terminal success and off suppresses every tray alert.
|
|
//
|
|
// 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
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** Notification kinds; success does not create a Needs you entry. */
|
|
export const RunAlertKind = Object.freeze({
|
|
Decision: AttentionKind.Decision,
|
|
Failed: AttentionKind.Failed,
|
|
Succeeded: Object.freeze({ name: "Succeeded" }),
|
|
});
|
|
|
|
/** `alertKindOf`: an attention kind is already exactly the notification kind. */
|
|
export function alertKindOf(kind) {
|
|
if (kind?.name === "Succeeded") return RunAlertKind.Succeeded;
|
|
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";
|
|
case "Succeeded":
|
|
return "A run succeeded";
|
|
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 modes = new Map();
|
|
const notified = new Set();
|
|
let seeding = false;
|
|
|
|
function seed(runs) {
|
|
const next = new Map();
|
|
modes.clear();
|
|
for (const run of runs ?? []) {
|
|
const runId = runIdOf(run?.id ?? run?.run_id);
|
|
if (runId == null) continue;
|
|
next.set(runId, normalizeStatus(run?.status));
|
|
modes.set(runId, normalizeStatus(run?.notify_mode) || "auto");
|
|
}
|
|
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);
|
|
|
|
if (frame?.notify_mode != null) modes.set(runId, normalizeStatus(frame.notify_mode));
|
|
const mode = modes.get(runId) || "auto";
|
|
|
|
const kind = status === "succeeded" && mode === "on" ? RunAlertKind.Succeeded : attentionKindOf(status, frame?.export_pending_sequence);
|
|
if (!kind) {
|
|
forget(runId, AttentionKind.Decision);
|
|
forget(runId, AttentionKind.Failed);
|
|
forget(runId, RunAlertKind.Succeeded);
|
|
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.
|
|
for (const other of Object.values(RunAlertKind)) {
|
|
if (other !== kind) forget(runId, other);
|
|
}
|
|
if (seeding) return null;
|
|
if (mode === "off") 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();
|
|
modes.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 };
|
|
}
|