diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index b8e6d4b561..09f2f9ade4 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -381,6 +381,20 @@ alerts-intake-token`, resolved by name at runtime within 24 hours. A class under 10% acted-on over the rolling four-week window renders as a default-off _proposal_ — display only; the page never changes a preference or a default. +- **Preferences**: `/alerts/preferences` (#3318) is the + per-class subscription page: toggles for every class in + `NOTIFICATION_CLASS_DEFAULTS`, quiet-hours editing, this + browser's subscription state, and a send-test button per class + (`POST /api/push/test-class`). Saving writes through the same + subscription upsert; the engine reads the stored classes/quiet + on its next tick, and a per-class test honours the toggle (a + class that is off receives no test). Test landings follow the + design §3 deep-link contract (`notificationTestLanding`): a real + candidate's own URL when one is supplied, otherwise the class's + own view — never the origin root; the digest test is the only + list-shaped landing (attention filtered to its refs). The JSON + twin is `/api/alerts/preferences.json`. `/notifications` stays + the read-only #3319 measurement page. - **Ack surface**: `/alerts` lists open incidents with Ack/Close. Ack is exactly-once: only the open→acked transition writes an event (and stamps the sends' `acted_on_at`); a repeat ack returns diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index 35d56aa55a..03ce75cfc0 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -25,8 +25,10 @@ import { sendPush, type PushOutcome, type PushTarget } from "./push.ts"; import { getSupabaseClient, sqlInt, sqlJson, sqlStr, type SupabaseClient } from "./supabase.ts"; import { buildNotificationCandidates, + classTestObjectRef, decideNotification, nextNotificationDigestAt, + notificationTestLanding, NOTIFICATION_CLASS_DEFAULTS, type NotificationHistoryEntry, type NotificationSnapshot, @@ -598,6 +600,84 @@ export class AlertsStore { } } +/** Per-class test sends (#3318): the preferences page's send-test + * button per class. The payload carries the class under test and + * lands per the design §3 deep-link contract + * (notificationTestLanding): a real candidate's own triage-capable + * URL when one is supplied, otherwise the test item's class view — + * never the origin root, and the digest test is the only + * list-shaped landing (attention filtered to its refs). */ +export function buildClassTestPayload( + cls: string, + origin: string, + candidate?: { objectRef: string; title: string; url: string } | null, +): PushPayload { + return { + class: cls, + objectRef: candidate?.objectRef ?? classTestObjectRef(cls), + url: notificationTestLanding(cls, origin, candidate), + title: `Test ${cls} — PM Stack`, + body: candidate + ? `Test ${cls} notification for ${candidate.title}. If you can read this, ${cls} delivery and its deep link work on this device.` + : `Test ${cls} notification (test item ${classTestObjectRef(cls)}). If you can read this, ${cls} delivery and its deep link work on this device.`, + }; +} + +export interface ClassTestPushSummary extends TestPushSummary { + cls: string; + /** Subscriptions the class toggle let through (all of them for + * the digest test, which is a delivery shape, not a class). */ + eligible: number; + /** The deep-link landing the test notification opens. */ + url: string; +} + +/** + * Send the per-class test push. Unlike the generic test, this one + * honours the stored preference: a subscription whose class toggle + * is off receives nothing — the same classEnabled check the engine + * applies, so the test proves the toggle's effect. One sends-ledger + * row per attempted subscription, under the tested class with the + * test object ref. The sender is injectable, like sendTestPush. + */ +export async function sendClassTestPush( + store: Pick, + origin: string, + cls: string, + send: typeof sendPush = sendPush, + candidate?: { objectRef: string; title: string; url: string } | null, +): Promise { + const payload = buildClassTestPayload(cls, origin, candidate); + const subs = await store.listSubscriptions(); + const targets = cls === "digest" ? subs : subs.filter((sub) => classEnabled(sub, cls)); + const summary: ClassTestPushSummary = { + subscriptions: subs.length, + eligible: targets.length, + sent: 0, + gone: 0, + errors: 0, + cls, + url: payload.url, + }; + for (const sub of targets) { + const target: PushTarget = { endpoint: sub.endpoint, p256dh: sub.p256dh, auth: sub.auth }; + const outcome = await send(target, payload); + if (outcome.ok) { + summary.sent += 1; + await store.logSend({ class: cls, objectRef: payload.objectRef, outcome: "sent" }); + await store.noteSubscriptionAlive(sub.endpoint); + } else if (outcome.gone) { + summary.gone += 1; + await store.logSend({ class: cls, objectRef: payload.objectRef, outcome: "gone" }); + await store.noteSubscriptionGone(sub.endpoint); + } else { + summary.errors += 1; + await store.logSend({ class: cls, objectRef: payload.objectRef, outcome: "error" }); + } + } + return summary; +} + /** The test alert (#3676 follow-up, Drew 2026-11-01): the /alerts * page's "Send a test alert" button. Clearly a test in title + body; * objectRef is a stable non-incident ref so the sends ledger keeps diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts index 52057a647e..d5ec728f5e 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -37,6 +37,101 @@ export const NOTIFICATION_CLASS_DEFAULTS: Record = { "blocked-age": true, }; +/** Notification preference classes (#3318, slice (d) of the #1254 + * design): the classes a subscription can toggle on the preferences + * page (/alerts/preferences). Ids are exactly the keys of + * NOTIFICATION_CLASS_DEFAULTS — the stored subscription `classes` + * map and the engine's classEnabled check read the same keys, so a + * toggle on the page is the next engine decision. */ +export interface NotificationClassMeta { + id: string; + label: string; + blurb: string; +} + +export const NOTIFICATION_CLASSES: NotificationClassMeta[] = [ + { + id: "incident", + label: "Incident alerts", + blurb: "A watchdog reports something down. Always immediate — quiet hours never hold an incident.", + }, + { + id: "needs-drew", + label: "Needs Drew", + blurb: "An item enters the needs-Drew tier on the attention page.", + }, + { + id: "quota-wall", + label: "Quota wall", + blurb: "A pool hits its limit well before reset, or a sole-door pool walls at all.", + }, + { + id: "quota-near-wall", + label: "Quota near wall", + blurb: "A sole-door pool crosses 85% of a window.", + }, + { + id: "stack-health", + label: "Stack health", + blurb: "A monitored stack service starts failing its probe.", + }, + { + id: "blocked-age", + label: "Blocked-age reminders", + blurb: "A needs-Drew item stays unacted for 24/48 hours, then weekly (digest-only except the 48-hour breakthrough).", + }, +]; + +/** Classes a per-class test send accepts: every preference class, + * plus "digest" — the digest is not a stored preference (it is the + * delivery shape quiet/digest-only candidates take), but its landing + * is part of the deep-link acceptance, so it gets a test too. */ +export const NOTIFICATION_TEST_CLASSES: string[] = [...NOTIFICATION_CLASSES.map((c) => c.id), "digest"]; + +export function isNotificationTestClass(value: unknown): value is string { + return typeof value === "string" && NOTIFICATION_TEST_CLASSES.includes(value); +} + +/** The test item's stable object ref for a class test send. The + * `test:` prefix keeps test traffic distinguishable in the sends + * ledger from real candidates of the same class. */ +export const classTestObjectRef = (cls: string): string => `test:${cls}`; + +/** Deep-link landing for a per-class test notification (design §3, + * #3318 acceptance). With a real candidate in hand, the landing is + * the candidate's own URL — the same URL its dashboard card links + * to. Without one, the test item lands on the view the engine itself + * assigns that class: incident → its anchored Alerts card, quota + * classes → /quota, stack-health → /health, and the attention + * classes → /attention anchored to the test item (mirroring + * tierItemCandidate's fallback for items with no session/GitHub + * ref). Never the origin root; the only list-shaped landing is the + * digest case, filtered to the digest's refs. */ +export function notificationTestLanding( + cls: string, + origin: string, + candidate?: Pick | null, +): string { + if (candidate?.url) return /^https?:\/\//.test(candidate.url) ? candidate.url : `${origin}${candidate.url}`; + switch (cls) { + case "incident": + return `${origin}/alerts#incident-test`; + case "quota-wall": + case "quota-near-wall": + return `${origin}/quota`; + case "stack-health": + return `${origin}/health`; + case "digest": + return `${origin}/attention?refs=${encodeURIComponent("test:needs-drew,test:blocked-age")}`; + case "needs-drew": + return `${origin}/attention#test-needs-drew`; + case "blocked-age": + return `${origin}/attention#test-blocked-age`; + default: + return `${origin}/alerts`; + } +} + export const NOTIFICATION_COOLDOWN_MS = 6 * 60 * 60_000; export const BLOCKED_AGE_REMINDER_MS = 24 * 60 * 60_000; export const BLOCKED_AGE_BREAKTHROUGH_MS = 48 * 60 * 60_000; diff --git a/pm-stack/aggregator/src/pages.ts b/pm-stack/aggregator/src/pages.ts index 99ab034794..daa14fa088 100644 --- a/pm-stack/aggregator/src/pages.ts +++ b/pm-stack/aggregator/src/pages.ts @@ -275,6 +275,9 @@ export const SUBROUTE_PARENTS: { name: string; prefix: string; parent: string }[ { name: "discuss", prefix: "/discuss/", parent: "/" }, { name: "program-project", prefix: "/program/", parent: "/program" }, { name: "service-detail", prefix: "/quota/service/", parent: "/quota" }, + // #3318: the notification preferences page is reached from /alerts + // (and linked from the /notifications measurement page). + { name: "alerts-preferences", prefix: "/alerts/preferences", parent: "/alerts" }, // #1497: Projects merged into Program — /projects redirects to the // pool section of /program, which is its manifest parent. { name: "projects-merge", prefix: "/projects", parent: "/program" }, diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 714b432a8b..cc1e004c77 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -59,6 +59,7 @@ import { summarizeDns } from "./dns.ts"; import type { NeedsDrewCensus } from "./needs-drew.ts"; import type { Incident, IncidentEvent, PushSubscriptionRow } from "./alerts.ts"; import type { NotificationRollup } from "./notifications.ts"; +import { NOTIFICATION_CLASS_DEFAULTS, NOTIFICATION_CLASSES } from "./notifications.ts"; import { ageMsText, feedAgeText } from "./feed.ts"; import { providerDisplayNames } from "./provider-display.ts"; import type { QueueView, QueueRow } from "./queue-view.ts"; @@ -7039,7 +7040,7 @@ export function renderAlerts(view: AlertsPageView, provenance: Provenance, vapid const formQuietStart = formSub?.quiet?.start ?? "23:00"; const formQuietEnd = formSub?.quiet?.end ?? "07:00"; const body = `

Alerts

-

The alert throat (#3676): every sentinel posts to one intake; this page is the ack surface. Critical incidents push immediately to subscribed browsers; an unacknowledged critical escalates once after ${view.ackWindowMin} minutes. Warnings are recorded here and in the ledger — no push in v1. Machine-first: /api/alerts.json.

+

The alert throat (#3676): every sentinel posts to one intake; this page is the ack surface. Critical incidents push immediately to subscribed browsers; an unacknowledged critical escalates once after ${view.ackWindowMin} minutes. Warnings are recorded here and in the ledger — no push in v1. Machine-first: /api/alerts.json. Per-class toggles, quiet hours, and per-class test sends live on the notification preferences page.

Push delivery on this browser

@@ -7214,6 +7215,187 @@ document.getElementById("push-test").addEventListener("click", async () => { return layout("Alerts", body, provenance, "/alerts", script); } +// --- Notification preferences page (#3318, slice (d) of #1254) ------------ + +export interface NotificationPreferencesView { + available: boolean; + subscriptions: PushSubscriptionRow[]; +} + +/** The /alerts/preferences page: per-class subscription toggles, + * quiet-hours editing, this browser's subscription state, and a + * send-test button per class. Preferences are subscription state — + * saving writes through the same /api/push/subscriptions upsert the + * Alerts form uses (provided-classes merge: only the keys sent + * change), and the engine reads the stored map via classEnabled / + * inQuietHours on its next tick, so a toggle here IS the next + * engine decision. The route is /alerts/preferences, not + * /notifications: that route is the #3319 measurement page and + * stays read-only. */ +export function renderNotificationPreferences( + view: NotificationPreferencesView, + provenance: Provenance, + vapidPublicKey: string, +): string { + if (!view.available) { + return layout( + "Notification preferences", + `

Notification preferences

The alerts ledger (Supabase alerts schema) is unreachable from this process right now — subscription preferences cannot be read or saved until it is back. The rest of the dashboard is unaffected.

`, + provenance, + "/alerts/preferences", + ); + } + // Same initial-state rule as the Alerts form: render the newest + // stored subscription's saved truth server-side; the client + // script refines it to this browser's own subscription. + const formSub = [...view.subscriptions].sort((a, b) => (a.last_seen_at < b.last_seen_at ? 1 : -1))[0]; + const quietOn = !formSub || formSub.quiet?.enabled !== false; + const quietStart = formSub?.quiet?.start ?? "23:00"; + const quietEnd = formSub?.quiet?.end ?? "07:00"; + const classRows = NOTIFICATION_CLASSES.map((c) => { + const checked = !formSub || (formSub.classes?.[c.id] ?? NOTIFICATION_CLASS_DEFAULTS[c.id]) !== false; + return `


+${esc(c.blurb)}

+
`; + }).join("\n"); + const body = `

Notification preferences

+

Per-class push preferences for this browser's subscription (#3318, slice (d) of the #1254 design). Toggling a class or editing quiet hours and saving changes the stored subscription; the notification engine reads the stored values on its next tick, so the change is the next engine decision. This browser's subscription state is shown below. Machine-first: /api/alerts/preferences.json. The /notifications page stays the read-only measurement roll-up (#3319).

+

This browser

+
+checking… +

+

+
+

Classes

+${classRows} +


+Pause non-urgent notifications between and (Chicago time). Untick for no time-of-day limit at all. Incident alerts always come through immediately, quiet hours or not; digest-only notifications wait for the quiet window to end.

+ +The digest is the one list-shaped landing allowed: the attention view filtered to the digest's refs.
+


+

Subscriptions (${view.subscriptions.length})

+${view.subscriptions.length ? view.subscriptions.map(subscriptionRow).join("") : `

No push subscriptions yet — enable push above.

`}`; + const script = ``; + return layout("Notification preferences", body, provenance, "/alerts/preferences", script); +} + // --- Notifications page (#3319, notification measurement) ------------------- export interface NotificationsPageView { @@ -7249,7 +7431,7 @@ export function renderNotifications(view: NotificationsPageView, provenance: Pro ? `

Default-off proposals

${proposals .map( (c) => - `
Proposal: default class ${esc(c.class)} off — acted-on ratio ${pct(c.ratio)} over the rolling window (${c.acted} of ${c.sent} sends acted on within 24h), under the 10% threshold.
Proposal only — this page never changes a preference or a default. Turning a class off by default is Drew's call, made on the Alerts page's subscription preferences.
`, + `
Proposal: default class ${esc(c.class)} off — acted-on ratio ${pct(c.ratio)} over the rolling window (${c.acted} of ${c.sent} sends acted on within 24h), under the 10% threshold.
Proposal only — this page never changes a preference or a default. Turning a class off by default is Drew's call, made on the notification preferences page.
`, ) .join("")}` : `

Default-off proposals

No class is under the 10% acted-on threshold over the rolling window.

`; diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 143d27af0b..8c2e4f9254 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -118,6 +118,7 @@ import { buildDigest, listDigestArchives, readDigestArchive, type Digest, type D import { timingSafeEqual } from "node:crypto"; import { getAlertsStore, + sendClassTestPush, sendTestPush, startAlertEngine, toPublicSubscription, @@ -127,8 +128,15 @@ import { import { recordSwProbe, swProbeSummary, VAPID_PUBLIC_KEY } from "./push.ts"; import { resolveBwsSecret } from "./secrets.ts"; import { SW_SOURCE } from "./sw-source.ts"; -import { renderAlerts, renderNotifications, renderDigest, esc } from "./render.ts"; -import { deriveSoleDoorPoolIds, rollupNotificationSends, type NotificationSnapshot } from "./notifications.ts"; +import { renderAlerts, renderNotificationPreferences, renderNotifications, renderDigest, esc } from "./render.ts"; +import { + deriveSoleDoorPoolIds, + isNotificationTestClass, + NOTIFICATION_CLASS_DEFAULTS, + NOTIFICATION_CLASSES, + rollupNotificationSends, + type NotificationSnapshot, +} from "./notifications.ts"; import { readJsonBody } from "./request-body.ts"; import { parseRegistryQuery, queryRegistry } from "./registry-view.ts"; import { searchWork } from "./search-view.ts"; @@ -2241,6 +2249,23 @@ async function handler(req: Request): Promise { return json(summary); } + // Per-class test sends (#3318): one test per preference class, + // honouring the stored class toggles, landing per design §3. + if (path === "/api/push/test-class") { + if (req.method !== "POST") return json({ error: "method not allowed" }, 405); + let cls: unknown; + try { + cls = ((await readJsonBody(req)) as { class?: unknown })?.class; + } catch { + return json({ error: "invalid test-class body" }, 400); + } + if (!isNotificationTestClass(cls)) return json({ error: "unknown notification class" }, 400); + const store = await getAlertsStore(); + if (!store) return json({ error: "alerts store unavailable" }, 503); + const summary = await sendClassTestPush(store, cfg.publicOrigin, cls); + return json(summary); + } + // --- Alert throat (#3676): incident intake + ack/close -------------- if (req.method === "POST" && path === "/api/alerts") { if (!(await alertsIntakeAuthorized(req))) return json({ error: "unauthorized" }, 401); @@ -2304,6 +2329,33 @@ async function handler(req: Request): Promise { : json({ error: "alerts store unavailable" }, 503); } } + if (path === "/alerts/preferences" || path === "/api/alerts/preferences.json") { + // #3318: subscription preferences — per-class toggles, quiet + // hours, this-browser state, per-class test sends. Writes go + // through the existing /api/push/subscriptions upsert; this + // route only reads the stored subscriptions for the form. + const store = await getAlertsStore(); + if (!store) { + return path === "/alerts/preferences" + ? html(renderNotificationPreferences({ available: false, subscriptions: [] }, prov(), VAPID_PUBLIC_KEY)) + : json({ error: "alerts store unavailable" }, 503); + } + try { + const subscriptions = await store.listSubscriptions(); + if (path === "/api/alerts/preferences.json") + return json({ + available: true, + subscriptions: subscriptions.map(toPublicSubscription), + classes: NOTIFICATION_CLASSES, + defaults: NOTIFICATION_CLASS_DEFAULTS, + }); + return html(renderNotificationPreferences({ available: true, subscriptions }, prov(), VAPID_PUBLIC_KEY)); + } catch { + return path === "/alerts/preferences" + ? html(renderNotificationPreferences({ available: false, subscriptions: [] }, prov(), VAPID_PUBLIC_KEY)) + : json({ error: "alerts store unavailable" }, 503); + } + } if (path === "/notifications" || path === "/api/notifications.json") { // #3319: the weekly sent-vs-acted roll-up over the send ledger. // Same reachability as every dashboard page (the tailnet origin); diff --git a/pm-stack/aggregator/test/notification-preferences-3318.test.ts b/pm-stack/aggregator/test/notification-preferences-3318.test.ts new file mode 100644 index 0000000000..9cb009b3a3 --- /dev/null +++ b/pm-stack/aggregator/test/notification-preferences-3318.test.ts @@ -0,0 +1,233 @@ +// #3318 (slice (d) of the #1254 design): the notification +// preferences page — per-class toggles, quiet-hours editing, +// this-browser subscription state, and per-class test sends whose +// landings follow the design §3 deep-link contract. +import { describe, expect, test } from "bun:test"; +import { + buildClassTestPayload, + classEnabled, + inQuietHours, + sendClassTestPush, + validateNewSubscription, + type PushSubscriptionRow, +} from "../src/alerts.ts"; +import { + classTestObjectRef, + isNotificationTestClass, + NOTIFICATION_CLASSES, + NOTIFICATION_CLASS_DEFAULTS, + notificationTestLanding, +} from "../src/notifications.ts"; +import { renderNotificationPreferences } from "../src/render.ts"; +import { manifestRouteFor } from "../src/pages.ts"; +import type { Provenance } from "../src/model.ts"; + +const ORIGIN = "https://amd-6.example.ts.net"; +const PROV: Provenance = { + board: "test", + roadmap: "test", + items: "test", + comments: "test", + quota: "test", + usage: "test", + attention: "test", + orchestration: "test", +} as Provenance; + +const row = (overrides: Partial = {}): PushSubscriptionRow => ({ + id: "99999999-8888-7777-6666-555555555555", + endpoint: "https://push.example.test/send/abc", + p256dh: "p", + auth: "a", + classes: { incident: true, "quota-wall": true }, + quiet: { start: "22:30", end: "06:15", tz: "America/Chicago", enabled: true }, + user_agent: "test", + created_at: "2026-11-01T00:00:00Z", + last_seen_at: "2026-11-01T00:00:00Z", + gone_count: 0, + ...overrides, +}); + +function stubStore(subs: PushSubscriptionRow[]) { + const sends: { class: string; objectRef: string; outcome: string }[] = []; + const gone: string[] = []; + const alive: string[] = []; + const store = { + listSubscriptions: async () => subs, + logSend: async (e: { class: string; objectRef: string; outcome: "sent" | "gone" | "error" }) => { + sends.push(e); + }, + noteSubscriptionGone: async (endpoint: string) => { + gone.push(endpoint); + return "marked" as const; + }, + noteSubscriptionAlive: async (endpoint: string) => { + alive.push(endpoint); + }, + }; + return { store, sends, gone, alive }; +} + +describe("preference class metadata (#3318)", () => { + test("the page's classes are exactly the stored-defaults keys", () => { + expect(NOTIFICATION_CLASSES.map((c) => c.id).sort()).toEqual(Object.keys(NOTIFICATION_CLASS_DEFAULTS).sort()); + }); + + test("test-class validation accepts every preference class plus digest, rejects anything else", () => { + for (const c of NOTIFICATION_CLASSES) expect(isNotificationTestClass(c.id)).toBe(true); + expect(isNotificationTestClass("digest")).toBe(true); + expect(isNotificationTestClass("test")).toBe(false); + expect(isNotificationTestClass("nope")).toBe(false); + expect(isNotificationTestClass(42)).toBe(false); + expect(isNotificationTestClass(undefined)).toBe(false); + }); +}); + +describe("deep-link landings for per-class tests (design §3)", () => { + test("each class lands on its own triage-capable view, never the origin root", () => { + expect(notificationTestLanding("incident", ORIGIN)).toBe(`${ORIGIN}/alerts#incident-test`); + expect(notificationTestLanding("quota-wall", ORIGIN)).toBe(`${ORIGIN}/quota`); + expect(notificationTestLanding("quota-near-wall", ORIGIN)).toBe(`${ORIGIN}/quota`); + expect(notificationTestLanding("stack-health", ORIGIN)).toBe(`${ORIGIN}/health`); + expect(notificationTestLanding("needs-drew", ORIGIN)).toBe(`${ORIGIN}/attention#test-needs-drew`); + expect(notificationTestLanding("blocked-age", ORIGIN)).toBe(`${ORIGIN}/attention#test-blocked-age`); + for (const c of NOTIFICATION_CLASSES) { + expect(notificationTestLanding(c.id, ORIGIN)).not.toBe(ORIGIN); + expect(notificationTestLanding(c.id, ORIGIN)).not.toBe(`${ORIGIN}/`); + } + }); + + test("the digest landing is the only list-shaped one, and it is filtered to its refs", () => { + const url = notificationTestLanding("digest", ORIGIN); + expect(url.startsWith(`${ORIGIN}/attention?refs=`)).toBe(true); + expect(decodeURIComponent(url.split("refs=")[1])).toBe("test:needs-drew,test:blocked-age"); + }); + + test("a real candidate's own URL wins over the class fallback", () => { + const candidate = { objectRef: "quota:pool-1", title: "Quota wall: pool-1", url: "/quota" }; + const payload = buildClassTestPayload("quota-wall", ORIGIN, candidate); + expect(payload.url).toBe(`${ORIGIN}/quota`); + expect(payload.objectRef).toBe("quota:pool-1"); + const abs = buildClassTestPayload("needs-drew", ORIGIN, { + objectRef: "session:s1", + title: "Session one", + url: "/sessions?id=s1", + }); + expect(abs.url).toBe(`${ORIGIN}/sessions?id=s1`); + expect(abs.body).toContain("Session one"); + }); + + test("the fallback payload is unmistakably a test and names its test item", () => { + const p = buildClassTestPayload("stack-health", ORIGIN); + expect(p.class).toBe("stack-health"); + expect(p.objectRef).toBe(classTestObjectRef("stack-health")); + expect(p.objectRef).toBe("test:stack-health"); + expect(p.title.toLowerCase()).toContain("test"); + expect(p.body).toContain("test:stack-health"); + }); +}); + +describe("per-class test sends honour the stored toggles", () => { + test("a subscription with the class off receives nothing and logs nothing", async () => { + const off = row({ classes: { incident: true, "quota-wall": false } }); + const { store, sends } = stubStore([off]); + const summary = await sendClassTestPush(store, ORIGIN, "quota-wall", async () => ({ ok: true, status: 201 })); + expect(summary.subscriptions).toBe(1); + expect(summary.eligible).toBe(0); + expect(summary.sent).toBe(0); + expect(sends).toEqual([]); + }); + + test("a subscription with the class on gets the test, logged under the class with the test ref", async () => { + const { store, sends, alive } = stubStore([row()]); + const summary = await sendClassTestPush(store, ORIGIN, "quota-wall", async () => ({ ok: true, status: 201 })); + expect(summary.eligible).toBe(1); + expect(summary.sent).toBe(1); + expect(summary.url).toBe(`${ORIGIN}/quota`); + expect(sends).toEqual([{ class: "quota-wall", objectRef: "test:quota-wall", outcome: "sent" }]); + expect(alive).toEqual(["https://push.example.test/send/abc"]); + }); + + test("the digest test reaches every subscription (digest is a delivery shape, not a class)", async () => { + const off = row({ classes: { incident: false } }); + const { store, sends } = stubStore([off]); + const summary = await sendClassTestPush(store, ORIGIN, "digest", async () => ({ ok: true, status: 201 })); + expect(summary.eligible).toBe(1); + expect(summary.sent).toBe(1); + expect(sends).toEqual([{ class: "digest", objectRef: "test:digest", outcome: "sent" }]); + }); + + test("a gone endpoint is logged gone and marked", async () => { + const { store, sends, gone } = stubStore([row()]); + const summary = await sendClassTestPush(store, ORIGIN, "incident", async () => ({ + ok: false, + gone: true, + status: 410, + error: "gone", + })); + expect(summary.gone).toBe(1); + expect(sends).toEqual([{ class: "incident", objectRef: "test:incident", outcome: "gone" }]); + expect(gone).toEqual(["https://push.example.test/send/abc"]); + }); +}); + +describe("a saved toggle is the next engine decision (acceptance 1)", () => { + test("the subscription-save validation carries class + quiet choices into the engine's checks", () => { + const parsed = validateNewSubscription({ + endpoint: "https://push.example.test/send/abc", + keys: { p256dh: "p", auth: "a" }, + classes: { "quota-wall": false }, + quiet: { enabled: false, start: "23:00", end: "07:00", tz: "America/Chicago" }, + }); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + // classEnabled is the exact check the engine's per-subscription + // candidate filter applies. + expect(classEnabled(parsed.value, "quota-wall")).toBe(false); + expect(classEnabled(parsed.value, "incident")).toBe(true); + // inQuietHours is the exact check the engine applies per tick. + expect(inQuietHours(parsed.value.quiet, new Date("2026-11-03T05:00:00Z"))).toBe(false); + }); +}); + +describe("the preferences page", () => { + test("renders a toggle and a test button per class, the digest test, and the saved quiet window", () => { + const html = renderNotificationPreferences({ available: true, subscriptions: [row()] }, PROV, "VAPID-TEST"); + for (const c of NOTIFICATION_CLASSES) { + expect(html).toContain(`id="pref-class-${c.id}"`); + expect(html).toContain(`data-test-class="${c.id}"`); + } + expect(html).toContain('data-test-class="digest"'); + expect(html).toContain('id="pref-quiet-enabled"'); + expect(html).toContain('value="22:30"'); + expect(html).toContain('value="06:15"'); + expect(html).toContain('id="pref-save"'); + expect(html).toContain('id="pref-enable"'); + expect(html).toContain('id="pref-status"'); + // The stored class-off state renders unticked. + const htmlOff = renderNotificationPreferences( + { available: true, subscriptions: [row({ classes: { incident: true, "quota-wall": false } })] }, + PROV, + "VAPID-TEST", + ); + expect(htmlOff).toContain('id="pref-class-quota-wall">'); + expect(htmlOff).not.toContain('id="pref-class-quota-wall" checked'); + }); + + test("saving posts every class plus quiet through pmPush.updatePrefs", () => { + const html = renderNotificationPreferences({ available: true, subscriptions: [] }, PROV, "VAPID-TEST"); + expect(html).toContain("window.pmPush.updatePrefs(p)"); + expect(html).toContain("CLASS_IDS"); + expect(html).toContain("/api/push/test-class"); + }); + + test("unavailable state says the ledger is unreachable, with no form", () => { + const html = renderNotificationPreferences({ available: false, subscriptions: [] }, PROV, "VAPID-TEST"); + expect(html).toContain("unreachable"); + expect(html).not.toContain('id="pref-save"'); + }); + + test("the page is reachable in the manifest as a sub-route of /alerts", () => { + expect(manifestRouteFor("/alerts/preferences")).toBe("/alerts"); + }); +});