From 579f150e012573e554d53d07610fb840242aaec7 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:01:06 +0100 Subject: [PATCH 1/6] feat(api): add /api/app-info handshake for native clients A native client needs to know which server-side features exist before it offers them. GET /api/app-info rides the normal /api auth gate and returns the package name, version and API level, never credentials or settings. --- app/api/app-info/route.ts | 17 +++++++++++++++++ lib/app-info-route.test.mjs | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 app/api/app-info/route.ts create mode 100644 lib/app-info-route.test.mjs diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts new file mode 100644 index 000000000..8086f068f --- /dev/null +++ b/app/api/app-info/route.ts @@ -0,0 +1,17 @@ +import { NextResponse } from "next/server"; +import packageJson from "../../../package.json"; + +export const dynamic = "force-dynamic"; + +/** + * Capability handshake for native clients. Rides the normal /api auth gate; it + * carries the package version and which server-side features exist, never any + * credential or configuration value. + */ +export function GET() { + return NextResponse.json({ + name: "ompweb", + version: packageJson.version, + api: 1, + }); +} diff --git a/lib/app-info-route.test.mjs b/lib/app-info-route.test.mjs new file mode 100644 index 000000000..1e4835673 --- /dev/null +++ b/lib/app-info-route.test.mjs @@ -0,0 +1,21 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { + tryNative: false, + alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, +}); +const route = await jiti.import("../app/api/app-info/route.ts"); +const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); + +test("app-info identifies ompweb and its version", async () => { + const response = await route.GET(); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.name, "ompweb"); + assert.equal(body.version, pkg.version); + assert.equal(body.api, 1); +}); From eecd570838ed194900fa38eea4de511326bbe291 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:04:58 +0100 Subject: [PATCH 2/6] feat(events): let a connection choose its heartbeat (15-110 s) A native client keeps its radio asleep for the whole idle heartbeat, so a per-connection interval is a battery win without touching the shared browser stream. GET /api/events?heartbeat= accepts 15-110 s and falls back to the 30 s default for anything else; capabilities advertise it as heartbeatParam. --- app/api/app-info/route.ts | 3 +++ app/api/events/route.ts | 5 +++-- lib/app-info-route.test.mjs | 3 ++- lib/event-stream-hub.test.mjs | 30 ++++++++++++++++++++++++++++-- lib/event-stream-hub.ts | 16 ++++++++++++++-- 5 files changed, 50 insertions(+), 7 deletions(-) diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts index 8086f068f..aa9a2099b 100644 --- a/app/api/app-info/route.ts +++ b/app/api/app-info/route.ts @@ -13,5 +13,8 @@ export function GET() { name: "ompweb", version: packageJson.version, api: 1, + capabilities: { + heartbeatParam: true, + }, }); } diff --git a/app/api/events/route.ts b/app/api/events/route.ts index c36a33a7d..ba321565a 100644 --- a/app/api/events/route.ts +++ b/app/api/events/route.ts @@ -1,6 +1,6 @@ import { NextResponse } from "next/server"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -import { EventStreamConnection, getEventStreamConnection } from "@/lib/event-stream-hub"; +import { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } from "@/lib/event-stream-hub"; import { parseEventStreamRequest, UNKNOWN_CONNECTION_CODE } from "@/lib/event-stream-protocol"; export const dynamic = "force-dynamic"; @@ -10,7 +10,8 @@ const MAX_REQUEST_BYTES = 16 * 1024; // GET /api/events — the browser's single multiplexed live-event stream. // Subscriptions are attached with POST (see lib/event-stream-protocol.ts). export function GET(req: Request) { - const connection = new EventStreamConnection(req.signal); + const heartbeat = parseHeartbeatSeconds(new URL(req.url).searchParams.get("heartbeat")); + const connection = new EventStreamConnection(req.signal, heartbeat * 1000); return new Response(connection.stream, { headers: { "Content-Type": "text/event-stream", diff --git a/lib/app-info-route.test.mjs b/lib/app-info-route.test.mjs index 1e4835673..3699dd5c1 100644 --- a/lib/app-info-route.test.mjs +++ b/lib/app-info-route.test.mjs @@ -11,11 +11,12 @@ const jiti = createJiti(import.meta.url, { const route = await jiti.import("../app/api/app-info/route.ts"); const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); -test("app-info identifies ompweb and its version", async () => { +test("app-info identifies ompweb, its version and the heartbeat capability", async () => { const response = await route.GET(); assert.equal(response.status, 200); const body = await response.json(); assert.equal(body.name, "ompweb"); assert.equal(body.version, pkg.version); assert.equal(body.api, 1); + assert.deepEqual(body.capabilities, { heartbeatParam: true }); }); diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index c929c832f..6d985e79f 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -11,7 +11,7 @@ const jiti = createJiti(import.meta.url, { "@/": new URL("../", import.meta.url).pathname, }, }); -const { EventStreamConnection, getEventStreamConnection } = await jiti.import("./event-stream-hub.ts"); +const { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } = await jiti.import("./event-stream-hub.ts"); const route = await jiti.import("../app/api/events/route.ts"); const { AgentSessionWrapper } = await jiti.import("./rpc-manager.ts"); const idleSnapshot = () => ({ cursor: { streamId: "test-stream", sequence: 0 } }); @@ -241,7 +241,7 @@ test("slow consumer receives a coalesced message_update on resume without a new try { await subscribeSession(connection, reader, "s1", "test-sess-resume"); // Consumer stalled: v1/v2 fill the queue, v3 is coalesced. Only a resumed - // pull() can deliver it — no heartbeat yet, no new event. + // pull() can deliver it — no heartbeat yet, no new event. session.emit({ type: "message_update", message: { id: "m1", content: "v1" } }); session.emit({ type: "message_update", message: { id: "m1", content: "v2" } }); session.emit({ type: "message_update", message: { id: "m1", content: "v3" } }); @@ -477,3 +477,29 @@ test("file channel enforces the allow-list and reports content changes", { timeo assert.equal(change.data.type, "change"); assert.equal(change.data.size, 7); }); + +test("the per-connection heartbeat is clamped to a safe range", () => { + assert.equal(parseHeartbeatSeconds("15"), 15); + assert.equal(parseHeartbeatSeconds("110"), 110); + assert.equal(parseHeartbeatSeconds(" 60 "), 60); + // Anything a client cannot be trusted with keeps the 30 s default. + for (const value of [null, undefined, "", "14", "111", "0", "-5", "15.5", "abc", "1e3"]) { + assert.equal(parseHeartbeatSeconds(value), 30, String(value)); + } +}); + +test("a connection created with a custom interval emits its keep-alive at that interval", async () => { + const connection = new EventStreamConnection(undefined, 40); + const reader = connection.stream.getReader(); + const hello = await readFrame(reader); + assert.equal(hello.data.type, "hello"); + const started = Date.now(); + const heartbeat = await Promise.race([ + reader.read(), + new Promise((_, reject) => setTimeout(() => reject(new Error("no heartbeat within 2 s")), 2000)), + ]); + const elapsed = Date.now() - started; + assert.equal(decoder.decode(heartbeat.value), ":\n\n"); + assert.ok(elapsed < 1000, `heartbeat arrived after ${elapsed} ms`); + connection.close(); +}); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 32be7067d..e7df75f4f 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -18,7 +18,19 @@ import { // the browser's shared worker. // Heartbeat keeps the socket alive through proxies (Next.js idles ~120-150s). +// A native client may ask for a longer one per connection (`/api/events?heartbeat=`). const HEARTBEAT_MS = 30_000; +export const MIN_HEARTBEAT_SECONDS = 15; +export const MAX_HEARTBEAT_SECONDS = 110; + +/** `?heartbeat=` in [15, 110]; anything else keeps the 30 s default. */ +export function parseHeartbeatSeconds(value: string | null | undefined): number { + if (typeof value !== "string" || !/^\d{1,4}$/.test(value.trim())) return HEARTBEAT_MS / 1000; + const seconds = Number(value.trim()); + if (seconds < MIN_HEARTBEAT_SECONDS || seconds > MAX_HEARTBEAT_SECONDS) return HEARTBEAT_MS / 1000; + return seconds; +} + const encoder = new TextEncoder(); export type SubscribeResult = @@ -77,7 +89,7 @@ export class EventStreamConnection { private readonly subscriptions = new Map(); private readonly signal: AbortSignal | undefined; - constructor(signal?: AbortSignal) { + constructor(signal?: AbortSignal, heartbeatMs: number = HEARTBEAT_MS) { this.signal = signal; this.stream = new ReadableStream({ start: (controller) => { @@ -86,7 +98,7 @@ export class EventStreamConnection { this.control({ type: "hello", connectionId: this.id }); this.heartbeat = setInterval(() => { if (this.flushAll()) this.write(":\n\n"); - }, HEARTBEAT_MS); + }, heartbeatMs); }, // A slow consumer resumed reading: deliver coalesced updates now rather // than waiting for the next event or heartbeat. From 0da2255955900af9bf3e75c738e74a11f3a31e8b Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:05:02 +0100 Subject: [PATCH 3/6] docs(changelog): app-info handshake and per-connection heartbeat --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..50c1adb70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Added + +- **A handshake for native clients.** `GET /api/app-info` answers with the package name, version, API level and which server-side capabilities exist. It carries no configuration and no credentials (it sits behind the normal auth gate), and it lets a client tell "not an ompweb server" from "server too old" from "OK" instead of probing endpoints. A native client can also ask for its own keep-alive interval with `GET /api/events?heartbeat=` (15-110 s; any other value keeps the 30 s default). The interval belongs to that connection only, so the browser's shared stream is unchanged, and a phone's radio can sleep for the whole idle interval. + ### Fixes & Improvements - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. From a9bc7201bb9210128bd990d0e0f5b4fe0e57dfb9 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:55:55 +0100 Subject: [PATCH 4/6] feat(notifications): actionable input notifications, answer endpoint and dismiss --- app/api/app-info/route.ts | 3 + app/api/notifications/answer/route.ts | 78 ++++++++++++ components/ui/toast.click.test.mjs | 67 +++++++++- hooks/useNotifications.ts | 43 ++++++- lib/app-info-route.test.mjs | 9 +- lib/notification-answer-route.test.mjs | 122 +++++++++++++++++++ lib/notification-client.ts | 6 +- lib/notification-events.test.mjs | 131 +++++++++++++++++++- lib/notification-events.ts | 161 ++++++++++++++++++++++++- lib/notification-hub.test.mjs | 152 +++++++++++++++++++++++ lib/notification-hub.ts | 156 ++++++++++++++++++++++-- lib/notification-sw.test.mjs | 52 +++++++- lib/pi-types.ts | 10 ++ lib/rpc-manager.test.mjs | 85 ++++++++++++- lib/rpc-manager.ts | 75 ++++++++++-- public/sw.js | 23 +++- 16 files changed, 1139 insertions(+), 34 deletions(-) create mode 100644 app/api/notifications/answer/route.ts create mode 100644 lib/notification-answer-route.test.mjs diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts index aa9a2099b..e802bee26 100644 --- a/app/api/app-info/route.ts +++ b/app/api/app-info/route.ts @@ -14,6 +14,9 @@ export function GET() { version: packageJson.version, api: 1, capabilities: { + notificationDialogs: true, + notificationAnswer: true, + notificationDismiss: true, heartbeatParam: true, }, }); diff --git a/app/api/notifications/answer/route.ts b/app/api/notifications/answer/route.ts new file mode 100644 index 000000000..b0f3c51f9 --- /dev/null +++ b/app/api/notifications/answer/route.ts @@ -0,0 +1,78 @@ +import { NextResponse } from "next/server"; +import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import type { ExtensionUiResponse, RpcAskDialogAnswer } from "@/lib/pi-types"; +import { getRpcSession, isAskAnswers, WebRpcError } from "@/lib/rpc-manager"; +import { isRecord } from "@/lib/type-guards"; + +export const dynamic = "force-dynamic"; + +/** Answers are text; 64 KB leaves room for a long ask customInput without becoming a payload channel. */ +const MAX_BODY_BYTES = 64 * 1024; +const MAX_ID_CHARS = 256; + +const invalid = (error: string) => NextResponse.json({ error, code: "invalid_answer_request" }, { status: 400 }); + +function isId(value: unknown): value is string { + return typeof value === "string" && value.length > 0 && value.length <= MAX_ID_CHARS; +} + +/** + * Exactly one response variant, and nothing else. Shapes come from + * ExtensionDialog; the ask payload reuses the agent route's validation. + */ +function parseResponse(value: unknown): ExtensionUiResponse | null { + if (!isRecord(value)) return null; + const keys = Object.keys(value); + if (keys.length !== 1) return null; + switch (keys[0]) { + case "value": + return typeof value.value === "string" ? { value: value.value } : null; + case "confirmed": + return typeof value.confirmed === "boolean" ? { confirmed: value.confirmed } : null; + case "cancelled": + return value.cancelled === true ? { cancelled: true } : null; + case "answers": + return isAskAnswers(value.answers) ? { answers: value.answers as RpcAskDialogAnswer[] } : null; + default: + return null; + } +} + +/** + * POST /api/notifications/answer — answer a pending blocking extension dialog + * from a notification action. Looks up the live wrapper (also through moved- + * session aliases) and never spawns omp. Behind the normal auth gate. + * + * 200 {status:"answered"} routed through extension_ui_response + * 200 {status:"alreadySettled"} the request id is not pending + * 200 {status:"sessionGone"} no live wrapper for the session + * 400 on an invalid body + */ +export async function POST(req: Request) { + let body: unknown; + try { + body = await parseJsonWithinLimit(req, MAX_BODY_BYTES); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) { + return NextResponse.json({ error: "Answer is too large", code: "request_too_large" }, { status: 413 }); + } + return invalid("Invalid JSON request body"); + } + if (!isRecord(body) || !isId(body.sessionId) || !isId(body.requestId)) { + return invalid("sessionId, requestId and response are required"); + } + const response = parseResponse(body.response); + if (!response) return invalid("response must be exactly one of value, confirmed, cancelled or answers"); + + const session = getRpcSession(body.sessionId); + if (!session || !session.isAlive()) return NextResponse.json({ status: "sessionGone" }); + + try { + return NextResponse.json({ status: session.answerExtensionUiRequest(body.requestId, response) }); + } catch (error) { + if (error instanceof WebRpcError) { + return NextResponse.json({ error: error.message, code: error.code }, { status: 400 }); + } + throw error; + } +} diff --git a/components/ui/toast.click.test.mjs b/components/ui/toast.click.test.mjs index 861808e7f..76c6866d7 100644 --- a/components/ui/toast.click.test.mjs +++ b/components/ui/toast.click.test.mjs @@ -23,10 +23,13 @@ const eventWorker = { else if (message.op === "close") eventStreams.delete(message.id); }, }; -function deliverNotification(message) { +function deliverFrame(frame) { const id = [...eventStreams].findLast(([, channel]) => channel.kind === "notifications")?.[0]; assert.ok(id, "useNotifications must hold a notifications channel"); - eventWorker.onmessage({ data: { id, type: "message", data: JSON.stringify({ type: "notification", ...message }) } }); + eventWorker.onmessage({ data: { id, type: "message", data: JSON.stringify(frame) } }); +} +function deliverNotification(message) { + deliverFrame({ type: "notification", ...message }); } before(() => { @@ -175,3 +178,63 @@ test("a push the service worker showed reloads the list from the server; other m act(() => notificationHistory.clear()); } }); + +test("a dismiss frame closes only the toast of its request id, not the next dialog's", () => { + render(React.createElement(ToastProvider, null)); + renderHook(() => useNotifications({ sessionId: null, locale: "en", onOpenSession: () => {} })); + const cards = () => Array.from(document.querySelectorAll(".toast-card")) + .filter((card) => card.querySelector(".display-serif")?.textContent === "Approve?"); + const input = (requestId) => ({ type: "notification", kind: "toast", event: { type: "input", sessionId: "s5", sessionName: "Approve?", requestId } }); + const retract = (requestId) => ({ type: "notification-dismiss", sessionId: "s5", tag: "s5:input", requestId }); + const ended = (card) => card.hasAttribute("data-ending-style"); + const live = () => cards().filter((card) => !ended(card)); + + act(() => deliverFrame(input("r1"))); + act(() => deliverFrame(retract("r2"))); + assert.equal(live().length, 1, "a retraction of another request keeps the toast"); + act(() => deliverFrame(retract("r1"))); + assert.equal(live().length, 0, "the retraction of its own request closes the toast"); + + act(() => deliverFrame(input("rA"))); + act(() => deliverFrame(input("rB"))); + act(() => deliverFrame(retract("rA"))); + assert.equal(live().length, 1, "a late retraction must not close the dialog that replaced it"); + act(() => deliverFrame(retract("rB"))); + assert.equal(live().length, 0); +}); + +test("a dismiss frame closes only the system notification of its request id", async () => { + const shown = []; + const registration = { + showNotification: async (title, options) => { shown.push({ title, options, closed: 0 }); }, + getNotifications: async ({ tag }) => shown + .filter((entry) => entry.options.tag === tag) + .map((entry) => ({ data: entry.options.data, close: () => { entry.closed += 1; } })), + }; + const worker = new window.EventTarget(); + worker.getRegistration = async () => registration; + Object.defineProperty(window.navigator, "serviceWorker", { configurable: true, value: worker }); + globalThis.Notification = window.Notification = class { static permission = "granted"; }; + const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + try { + renderHook(() => useNotifications({ sessionId: null, locale: "en", onOpenSession: () => {} })); + await act(async () => { + deliverFrame({ type: "notification", kind: "os", event: { type: "input", sessionId: "s6", sessionName: "Answer", requestId: "r1" } }); + await tick(); + }); + assert.deepEqual(shown.map((entry) => [entry.options.tag, entry.options.data.requestId]), [["s6:input", "r1"]]); + const retract = async (requestId) => act(async () => { + deliverFrame({ type: "notification-dismiss", sessionId: "s6", tag: "s6:input", requestId }); + await tick(); + }); + await retract("r2"); + assert.equal(shown[0].closed, 0, "a retraction of another request keeps the notification"); + await retract("r1"); + assert.equal(shown[0].closed, 1); + } finally { + delete window.navigator.serviceWorker; + delete window.Notification; + delete globalThis.Notification; + act(() => notificationHistory.clear()); + } +}); diff --git a/hooks/useNotifications.ts b/hooks/useNotifications.ts index 7958554e9..c9f98285c 100644 --- a/hooks/useNotifications.ts +++ b/hooks/useNotifications.ts @@ -115,9 +115,13 @@ export function useNotifications({ sessionId, locale, onOpenSession }: { session // OPEN_SESSION_EVENT, so listeners such as the bell popover see each one. useEffect(() => { const openSession = (sessionId: string) => window.dispatchEvent(new CustomEvent(OPEN_SESSION_EVENT, { detail: sessionId })); - const showToast = (rendered: RenderedNotification, type: NotificationEvent["type"]) => { + // Request id of the toast each tag currently shows. A retraction names the + // request it closes, so a toast replaced by the next dialog of that tag stays. + const toastRequests = new Map(); + const showToast = (rendered: RenderedNotification, type: NotificationEvent["type"], requestId?: string) => { const show = type === "error" ? toast.error : toast.info; const target = rendered.sessionId; + toastRequests.set(rendered.tag, requestId); // The whole card opens the session (click, tap, or Enter on the focused card); following it is reading it. show(rendered.title, rendered.body, { id: rendered.tag, @@ -132,14 +136,33 @@ export function useNotifications({ sessionId, locale, onOpenSession }: { session notificationHistory.add(event); const rendered = renderNotification(event, translate); if (kind === "toast") { - showToast(rendered, event.type); + showToast(rendered, event.type, event.requestId); return; } // Permission withdrawn or never granted: the toast is the only way left to tell the user. - void showSystemNotification(rendered).then((shown) => { - if (!shown) showToast(rendered, event.type); + void showSystemNotification(rendered, event.requestId).then((shown) => { + if (!shown) showToast(rendered, event.type, event.requestId); }); }; + // The dialog was answered, cancelled or expired elsewhere. Close only the + // notification of that request id: a buffered push can arrive after the + // next dialog for the same tag is already shown, and that one stays. + const dismiss = async (tag: string, requestId: string) => { + if (toastRequests.get(tag) === requestId) { + toastRequests.delete(tag); + toast.close(tag); + } + try { + const registration = "serviceWorker" in navigator ? await navigator.serviceWorker.getRegistration() : undefined; + const shown = await registration?.getNotifications({ tag }) ?? []; + for (const notification of shown) { + const data: unknown = notification.data; + if (isRecord(data) && data.requestId === requestId) notification.close(); + } + } catch { + // A closing registration must not break the toast path. + } + }; const onOpen = (raw: Event) => { if (raw instanceof CustomEvent && typeof raw.detail === "string" && raw.detail) openRef.current(raw.detail); }; @@ -154,12 +177,20 @@ export function useNotifications({ sessionId, locale, onOpenSession }: { session if (data.type === "omp-notification-shown") void notificationHistory.load(); }; // This tab's own channel: the server delivers here while it is open, on any - // view (the chat, Settings, ...), and counts the tab as reachable. + // view (the chat, Settings, ...), and counts the tab as reachable. A settled + // input dialog arrives as a dismiss frame and retracts only its own request. const stream = openEventStream({ kind: "notifications", clientId: notificationClientId }); stream.onmessage = ({ data }) => { try { const frame: unknown = JSON.parse(data); - if (!isRecord(frame) || frame.type !== "notification" || (frame.kind !== "toast" && frame.kind !== "os") || !isRecord(frame.event)) return; + if (!isRecord(frame)) return; + if (frame.type === "notification-dismiss") { + if (typeof frame.tag === "string" && frame.tag && typeof frame.requestId === "string" && frame.requestId) { + void dismiss(frame.tag, frame.requestId); + } + return; + } + if (frame.type !== "notification" || (frame.kind !== "toast" && frame.kind !== "os") || !isRecord(frame.event)) return; // Built by our own server's notification hub from a NotificationEvent. const event = frame.event as unknown as NotificationEvent; deliver(frame.kind, event); diff --git a/lib/app-info-route.test.mjs b/lib/app-info-route.test.mjs index 3699dd5c1..b83efb4aa 100644 --- a/lib/app-info-route.test.mjs +++ b/lib/app-info-route.test.mjs @@ -11,12 +11,17 @@ const jiti = createJiti(import.meta.url, { const route = await jiti.import("../app/api/app-info/route.ts"); const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); -test("app-info identifies ompweb, its version and the heartbeat capability", async () => { +test("app-info identifies ompweb, its version and the notification and heartbeat capabilities", async () => { const response = await route.GET(); assert.equal(response.status, 200); const body = await response.json(); assert.equal(body.name, "ompweb"); assert.equal(body.version, pkg.version); assert.equal(body.api, 1); - assert.deepEqual(body.capabilities, { heartbeatParam: true }); + assert.deepEqual(body.capabilities, { + notificationDialogs: true, + notificationAnswer: true, + notificationDismiss: true, + heartbeatParam: true, + }); }); diff --git a/lib/notification-answer-route.test.mjs b/lib/notification-answer-route.test.mjs new file mode 100644 index 000000000..1a1266739 --- /dev/null +++ b/lib/notification-answer-route.test.mjs @@ -0,0 +1,122 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath } from "node:url"; +import { createJiti } from "jiti"; + +// Real POST /api/notifications/answer with fake live wrappers: no omp spawn, +// no notification store writes beyond the throwaway agent dir. +const agentDir = mkdtempSync(join(tmpdir(), "omp-web-answer-route-")); +const previousAgentDir = process.env.PI_CODING_AGENT_DIR; +process.env.PI_CODING_AGENT_DIR = agentDir; +after(() => { + globalThis.__ompSessions = undefined; + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + rmSync(agentDir, { recursive: true, force: true }); +}); + +const jiti = createJiti(import.meta.url, { + tryNative: false, + alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, +}); +const route = await jiti.import("../app/api/notifications/answer/route.ts"); +const { WebRpcError } = await jiti.import("@/lib/rpc-manager"); + +const URL_ = "http://localhost/api/notifications/answer"; +const post = (body, headers = {}) => route.POST(new Request(URL_, { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body: typeof body === "string" ? body : JSON.stringify(body), +})); + +function fakeSession({ alive = true, result = "answered", error = null } = {}) { + const calls = []; + return { + calls, + session: { + isAlive: () => alive, + answerExtensionUiRequest(id, response) { + calls.push([id, response]); + if (error) throw error; + return result; + }, + }, + }; +} + +test("a valid answer reaches the live wrapper exactly once", async () => { + const { calls, session } = fakeSession(); + globalThis.__ompSessions = new Map([["s1", session]]); + const response = await post({ sessionId: "s1", requestId: "req-1", response: { confirmed: true } }); + assert.equal(response.status, 200); + assert.deepEqual(await response.json(), { status: "answered" }); + assert.deepEqual(calls, [["req-1", { confirmed: true }]]); +}); + +test("all four response variants are accepted", async () => { + const { calls, session } = fakeSession(); + globalThis.__ompSessions = new Map([["s1", session]]); + for (const answer of [{ value: "main" }, { confirmed: false }, { cancelled: true }, { answers: [{ id: "q", selectedOptions: ["A"], customInput: "other" }] }]) { + assert.equal((await post({ sessionId: "s1", requestId: "req", response: answer })).status, 200); + } + assert.deepEqual(calls.map(([, answer]) => answer), [ + { value: "main" }, { confirmed: false }, { cancelled: true }, { answers: [{ id: "q", selectedOptions: ["A"], customInput: "other" }] }, + ]); +}); + +test("alreadySettled and sessionGone are reported, not treated as errors", async () => { + globalThis.__ompSessions = new Map([["s1", fakeSession({ result: "alreadySettled" }).session]]); + const settled = await post({ sessionId: "s1", requestId: "req", response: { value: "x" } }); + assert.deepEqual(await settled.json(), { status: "alreadySettled" }); + + const dead = await post({ sessionId: "s2", requestId: "req", response: { value: "x" } }); + assert.deepEqual(await dead.json(), { status: "sessionGone" }); + + globalThis.__ompSessions = new Map([["s3", fakeSession({ alive: false }).session]]); + const exited = await post({ sessionId: "s3", requestId: "req", response: { value: "x" } }); + assert.deepEqual(await exited.json(), { status: "sessionGone" }); +}); + +test("malformed requests are rejected before touching any session", async () => { + const { calls, session } = fakeSession(); + globalThis.__ompSessions = new Map([["s1", session]]); + const cases = [ + null, + [], + "text", + { sessionId: "s1", requestId: "req" }, + { sessionId: "", requestId: "req", response: { value: "x" } }, + { sessionId: "s1", requestId: "r".repeat(257), response: { value: "x" } }, + { sessionId: "s1", requestId: "req", response: {} }, + { sessionId: "s1", requestId: "req", response: { value: 1 } }, + { sessionId: "s1", requestId: "req", response: { cancelled: false } }, + { sessionId: "s1", requestId: "req", response: { value: "x", confirmed: true } }, + { sessionId: "s1", requestId: "req", response: { answers: "yes" } }, + { sessionId: "s1", requestId: "req", response: { answers: [{ id: 1, selectedOptions: [] }] } }, + ]; + for (const body of cases) { + const response = await post(body); + assert.equal(response.status, 400, JSON.stringify(body)); + assert.equal((await response.json()).code, "invalid_answer_request"); + } + assert.deepEqual(calls, []); +}); + +test("invalid JSON and an oversized body get distinct statuses", async () => { + assert.equal((await post("{not json")).status, 400); + const huge = JSON.stringify({ sessionId: "s1", requestId: "req", response: { value: "x".repeat(70_000) } }); + const response = await post(huge, { "content-length": String(Buffer.byteLength(huge)) }); + assert.equal(response.status, 413); + assert.equal((await response.json()).code, "request_too_large"); +}); + +test("a wrapper validation error becomes a 400 with its own code", async () => { + const { session } = fakeSession({ error: new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers") }); + globalThis.__ompSessions = new Map([["s1", session]]); + const response = await post({ sessionId: "s1", requestId: "req", response: { value: "x" } }); + assert.equal(response.status, 400); + assert.deepEqual(await response.json(), { error: "Invalid ask dialog answers", code: "invalid_ask_answers" }); +}); diff --git a/lib/notification-client.ts b/lib/notification-client.ts index e48415910..f36dffc32 100644 --- a/lib/notification-client.ts +++ b/lib/notification-client.ts @@ -199,14 +199,16 @@ export const OPEN_SESSION_EVENT = "omp-open-session"; * Show a system notification the same way the service worker shows pushes. * Returns false when the browser does not allow it, so the caller can fall back. */ -export async function showSystemNotification(notification: RenderedNotification): Promise { +export async function showSystemNotification(notification: RenderedNotification, requestId?: string): Promise { if (!("Notification" in window) || Notification.permission !== "granted") return false; const options: NotificationOptions = { body: notification.body, icon: "/icon-192.png", badge: "/badge-96.png", tag: notification.tag, - data: { url: notification.url, sessionId: notification.sessionId }, + // A dismiss closes only the notification of the same request id, so a + // pushed/shown dialog must carry it too. + data: { url: notification.url, sessionId: notification.sessionId, ...(requestId ? { requestId } : {}) }, }; try { const registration = "serviceWorker" in navigator ? await navigator.serviceWorker.getRegistration() : undefined; diff --git a/lib/notification-events.test.mjs b/lib/notification-events.test.mjs index 440480bc6..d1c705650 100644 --- a/lib/notification-events.test.mjs +++ b/lib/notification-events.test.mjs @@ -3,7 +3,7 @@ import test from "node:test"; import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const { createNotificationDetector, parseNotificationPrefs, renderNotification } = await jiti.import("./notification-events.ts"); +const { buildNotificationDialog, createNotificationDetector, parseNotificationPrefs, renderNotification } = await jiti.import("./notification-events.ts"); const session = { sessionId: "s1", sessionName: "Refactor auth" }; @@ -129,3 +129,132 @@ test("a pasted overlong session name is clipped so push payloads stay small", () assert.ok(rendered.title.endsWith("…")); assert.equal(renderNotification({ type: "completed", sessionId: "s1", sessionName: "Fix bug" }, (key) => key).title, "Fix bug"); }); + +test("an input notification carries the answerable select dialog with display text clipped", () => { + const [event] = run([{ + type: "extension_ui_request", + id: "req-1", + method: "select", + title: " Choose a target ", + options: [{ label: "alpha" }, "beta"], + expiresAt: 1234, + }]); + assert.equal(event.requestId, "req-1", "the event carries the id a retraction matches"); + assert.deepEqual(event.dialog, { + requestId: "req-1", + method: "select", + title: "Choose a target", + options: ["alpha", "beta"], + expiresAt: 1234, + }); + assert.equal(event.detail, " Choose a target "); +}); + +test("answer labels are kept byte-for-byte; labels that would have to change omit the dialog", () => { + const select = (options) => buildNotificationDialog({ id: "s", method: "select", title: "Pick", options }); + assert.deepEqual(select(["main", "next"]).options, ["main", "next"]); + assert.deepEqual(select(["Yes,\nplease", " padded "]).options, ["Yes,\nplease", " padded "], "whitespace is part of the label"); + assert.equal(select(["A".repeat(161)]), undefined, "a label over the cap is never clipped"); + assert.equal(select([{ value: "no-label" }]), undefined, "an option without a label cannot be shown exactly"); + assert.equal(select([""]), undefined); + assert.equal(select(Array.from({ length: 13 }, (_, index) => `option ${index}`)), undefined, "more options than the cap"); + const ask = buildNotificationDialog({ + id: "a", + method: "ask", + questions: [{ id: "q1", question: "Which?", options: ["B".repeat(121)] }], + }); + assert.equal(ask, undefined, "an ask option over the per-option cap is not clipped"); +}); + +test("an input event keeps its request id even when no dialog can be carried", () => { + const [event] = run([{ type: "extension_ui_request", id: "open-1", method: "open_url", title: "Open the docs" }]); + assert.equal(event.type, "input"); + assert.equal(event.requestId, "open-1"); + assert.equal(event.dialog, undefined); +}); + +test("confirm, input and editor dialogs expose only what the app can answer", () => { + assert.deepEqual(buildNotificationDialog({ id: "c", method: "confirm", title: "Deploy?", message: "This writes to prod." }), { + requestId: "c", + method: "confirm", + title: "Deploy?", + message: "This writes to prod.", + }); + assert.deepEqual(buildNotificationDialog({ id: "i", method: "input", title: "Branch name", placeholder: "feature/x" }), { + requestId: "i", + method: "input", + title: "Branch name", + placeholder: "feature/x", + }); + assert.deepEqual(buildNotificationDialog({ id: "e", method: "editor", title: "Commit message", prefill: "secret body" }), { + requestId: "e", + method: "editor", + title: "Commit message", + }); +}); + +test("ask dialogs keep question ids, options and the Other input rule", () => { + const dialog = buildNotificationDialog({ + id: "ask", + method: "ask", + title: "Ship it?", + questions: [ + { id: "q1", question: "Which branch?", options: [{ label: "main" }, { label: "next" }], multi: true, allowCustom: false }, + { id: "q2", question: "Notes?" }, + ], + }); + assert.deepEqual(dialog, { + requestId: "ask", + method: "ask", + title: "Ship it?", + questions: [ + { id: "q1", question: "Which branch?", options: ["main", "next"], multi: true }, + { id: "q2", question: "Notes?", allowCustom: true }, + ], + }); + // Missing/duplicate ids make the whole dialog unusable: omp could not match answers. + assert.equal(buildNotificationDialog({ id: "a", method: "ask", questions: [{ question: "no id" }] }), undefined); + assert.equal(buildNotificationDialog({ id: "a", method: "ask", questions: [{ id: "x", question: "one" }, { id: "x", question: "two" }] }), undefined); + assert.equal(buildNotificationDialog({ id: "a", method: "ask", questions: [{ id: "x", question: "one" }, { id: "y", question: "two" }, { id: "z", question: "three" }, { id: "w", question: "four" }, { id: "v", question: "five" }, { id: "u", question: "six" }] }), undefined); +}); + +test("dialogs that cannot be represented or would not fit a push are omitted entirely", () => { + assert.equal(buildNotificationDialog({ id: "u", method: "open_url", title: "https://example.test" }), undefined); + assert.equal(buildNotificationDialog({ id: "u", method: "notify", message: "fyi" }), undefined); + assert.equal(buildNotificationDialog({ id: "", method: "confirm", title: "No id" }), undefined); + assert.equal(buildNotificationDialog({ id: "x".repeat(129), method: "confirm", title: "Long id" }), undefined); + assert.equal(buildNotificationDialog({ id: "s", method: "select", title: "No options" }), undefined); + const huge = buildNotificationDialog({ + id: "huge", + method: "ask", + title: "T".repeat(160), + questions: Array.from({ length: 5 }, (_, index) => ({ + id: `q${index}`, + question: "Q".repeat(240), + options: Array.from({ length: 9 }, () => "O".repeat(120)), + })), + }); + assert.equal(huge, undefined, "real content above the byte cap must not be truncated into a misleading dialog"); +}); + +test("exhausted retries end the run as exactly one error notification", () => { + const events = run([ + { type: "agent_start" }, + { type: "auto_retry_start", attempt: 1, errorMessage: "429 rate limit" }, + { type: "auto_retry_end", success: false, attempt: 3 }, + { type: "auto_retry_start", attempt: 4, errorMessage: "provider unavailable" }, + { type: "auto_retry_end", success: false, attempt: 5 }, + { type: "prompt_result", agentInvoked: true, status: "error", error: { message: "Retry budget exhausted" } }, + { type: "session_settled" }, + ]); + assert.deepEqual(summary(events), [["error", "Retry budget exhausted"]]); +}); + +test("a crash mid-run notifies once, even when omp later reports the same failure again", () => { + const events = run([ + { type: "agent_start" }, + { type: "process_exit", detail: "code 3221225477" }, + { type: "prompt_result", agentInvoked: true, status: "error", error: { message: "child exited" } }, + ]); + assert.deepEqual(summary(events), [["error", "code 3221225477"]]); +}); diff --git a/lib/notification-events.ts b/lib/notification-events.ts index 3939f96f4..e25ebb58b 100644 --- a/lib/notification-events.ts +++ b/lib/notification-events.ts @@ -8,6 +8,34 @@ import { isRecord } from "./type-guards"; export const NOTIFICATION_TYPES = ["completed", "input", "error", "modelSwitch"] as const; export type NotificationType = (typeof NOTIFICATION_TYPES)[number]; +/** One question of an `ask` dialog, reduced to what a notification can answer. */ +export interface NotificationDialogQuestion { + id: string; + question: string; + /** Option labels (the web dialog sends labels back as `selectedOptions`). */ + options?: string[]; + multi?: boolean; + /** The web dialog always offers an "Other" free-text field unless omp forbids it. */ + allowCustom?: boolean; +} + +/** + * The blocking extension dialog behind an `input` notification. Carried in the + * SSE frame, the history entry and the push body so the native app can render + * Yes/No/option buttons or a reply field without an open chat tab. + */ +export interface NotificationDialog { + requestId: string; + method: "select" | "confirm" | "input" | "editor" | "ask"; + title?: string; + message?: string; + options?: string[]; + questions?: NotificationDialogQuestion[]; + placeholder?: string; + /** Wall-clock expiry (ms), present when omp set a timeout. */ + expiresAt?: number; +} + export interface NotificationEvent { /** `test` is only sent by the settings "Send test notification" button. */ type: NotificationType | "test"; @@ -19,6 +47,10 @@ export interface NotificationEvent { to?: string; /** Earlier ids of this conversation (omp moved it to a new file); tabs may still show one. */ aliases?: string[]; + /** `input` only: the id a retraction (`publishNotificationDismiss`) matches. */ + requestId?: string; + /** `input` only: the dialog waiting for an answer, when it fits a push payload. */ + dialog?: NotificationDialog; } /** One entry of the persisted notification history; `id` is the replace-tag `:`. */ @@ -130,6 +162,126 @@ export function isValidNotificationId(value: unknown): value is string { const str = (value: unknown): string | undefined => (typeof value === "string" && value.trim() ? value : undefined); +// Push payloads must stay well under the 4 KB Web Push limit. A dialog that +// cannot be represented within these caps is omitted entirely so the app falls +// back to "Open" instead of showing a partial question. +const DIALOG_TEXT = { title: 160, message: 480, placeholder: 80, option: 160, question: 240, questionOption: 120 }; +const DIALOG_COUNTS = { options: 12, questions: 5, questionOptions: 9 }; +const DIALOG_ID_CHARS = 128; +const MAX_DIALOG_BYTES = 1800; +const DIALOG_METHODS: Record = { select: true, confirm: true, input: true, editor: true, ask: true }; +const encoder = new TextEncoder(); + +/** Flatten and clip one line of dialog text that is only displayed. */ +function clipDialogText(value: unknown, max: number): string | undefined { + if (typeof value !== "string") return undefined; + const flat = value.replace(/\s+/g, " ").trim(); + if (!flat) return undefined; + return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat; +} + +/** + * Option labels travel back to omp as the answer and are compared verbatim + * (`extension_ui_response.selectedOptions`), so they are never trimmed, + * flattened or clipped. A set that has to be altered to fit the notification + * makes the whole dialog unrepresentable: the notification then only opens + * the session instead of sending an answer omp would not match. + */ +function exactDialogOptions(value: unknown, maxCount: number, maxChars: number): string[] | undefined { + if (!Array.isArray(value) || value.length > maxCount) return undefined; + const labels: string[] = []; + for (const entry of value) { + const label = typeof entry === "string" ? entry : isRecord(entry) ? entry.label : undefined; + if (typeof label !== "string" || label.length === 0 || label.length > maxChars) return undefined; + labels.push(label); + } + return labels.length > 0 ? labels : undefined; +} + +/** `ask` questions: ids must be unique and complete, or the whole dialog is unusable. */ +function dialogQuestions(value: unknown): NotificationDialogQuestion[] | undefined { + if (!Array.isArray(value) || value.length === 0 || value.length > DIALOG_COUNTS.questions) return undefined; + const questions: NotificationDialogQuestion[] = []; + const ids = new Set(); + for (const raw of value) { + if (!isRecord(raw)) return undefined; + // The id is the key omp matches the answer against; trimming it could + // answer a different question, so a padded id makes the dialog unusable. + const id = typeof raw.id === "string" ? raw.id : ""; + const question = clipDialogText(raw.question, DIALOG_TEXT.question); + if (!id || id.trim() !== id || id.length > DIALOG_ID_CHARS || ids.has(id) || !question) return undefined; + ids.add(id); + const entry: NotificationDialogQuestion = { id, question }; + // A non-empty list must survive exactly or the question would lose + // choices; an empty list is just a free-text question. + if (raw.options !== undefined && raw.options !== null) { + if (!Array.isArray(raw.options)) return undefined; + if (raw.options.length > 0) { + const options = exactDialogOptions(raw.options, DIALOG_COUNTS.questionOptions, DIALOG_TEXT.questionOption); + if (!options) return undefined; + entry.options = options; + } + } + if (raw.multi === true) entry.multi = true; + // Same rule as ExtensionDialog: every question may be answered with "Other". + if (raw.allowCustom !== false) entry.allowCustom = true; + questions.push(entry); + } + return questions; +} + +/** + * Reduce a blocking `extension_ui_request` frame to the answerable dialog a + * notification carries. Returns undefined for `open_url` (no answer) and for + * frames whose payload would not fit a push payload. + */ +export function buildNotificationDialog(frame: Record): NotificationDialog | undefined { + const method = typeof frame.method === "string" ? frame.method : ""; + if (!DIALOG_METHODS[method]) return undefined; + // The id is echoed in the answer; never trim it into a different request. + const requestId = typeof frame.id === "string" ? frame.id : ""; + if (!requestId || requestId.trim() !== requestId || requestId.length > DIALOG_ID_CHARS) return undefined; + + const dialog: NotificationDialog = { requestId, method: method as NotificationDialog["method"] }; + const title = clipDialogText(frame.title, DIALOG_TEXT.title); + if (title) dialog.title = title; + + switch (dialog.method) { + case "select": { + const options = exactDialogOptions(frame.options, DIALOG_COUNTS.options, DIALOG_TEXT.option); + if (!options) return undefined; + dialog.options = options; + break; + } + case "confirm": { + const message = clipDialogText(frame.message, DIALOG_TEXT.message); + if (message) dialog.message = message; + break; + } + case "input": { + const placeholder = clipDialogText(frame.placeholder, DIALOG_TEXT.placeholder); + if (placeholder) dialog.placeholder = placeholder; + break; + } + case "editor": + // The editor body (prefill) is not part of the notification contract: the + // app opens the session to edit it. The title is enough to name it. + break; + case "ask": { + const questions = dialogQuestions(frame.questions); + if (!questions) return undefined; + dialog.questions = questions; + break; + } + } + + // Nothing user-visible to show: the notification body already carries detail. + if (!dialog.title && !dialog.message && !dialog.placeholder && !dialog.questions && !dialog.options) return undefined; + if (typeof frame.expiresAt === "number" && Number.isFinite(frame.expiresAt) && frame.expiresAt > 0) dialog.expiresAt = frame.expiresAt; + if (encoder.encode(JSON.stringify(dialog)).byteLength > MAX_DIALOG_BYTES) return undefined; + return dialog; +} + type Detect = (frame: Record, session: { sessionId: string; sessionName: string | null }) => NotificationEvent[]; /** @@ -214,7 +366,14 @@ export function createNotificationDetector(): Detect { // auto-approved ones before they are emitted). if (typeof frame.method !== "string" || !BLOCKING_UI_METHODS.has(frame.method)) return []; const firstQuestion = Array.isArray(frame.questions) && isRecord(frame.questions[0]) ? str(frame.questions[0].question) : undefined; - return [{ ...base, type: "input", detail: str(frame.title) ?? firstQuestion ?? str(frame.message) ?? str(frame.instructions) }]; + const event: NotificationEvent = { ...base, type: "input", detail: str(frame.title) ?? firstQuestion ?? str(frame.message) ?? str(frame.instructions) }; + // Carried even without a dialog (open_url, oversized payload) so the + // matching retraction can still close this notification. + if (typeof frame.id === "string" && frame.id) event.requestId = frame.id; + // `open_url` has no answerable dialog; buildNotificationDialog rejects it. + const dialog = buildNotificationDialog(frame); + if (dialog) event.dialog = dialog; + return [event]; } default: return []; diff --git a/lib/notification-hub.test.mjs b/lib/notification-hub.test.mjs index 98e654eff..c0da15400 100644 --- a/lib/notification-hub.test.mjs +++ b/lib/notification-hub.test.mjs @@ -316,6 +316,79 @@ test("a retry is dropped once the device turned notifications off", async (t) => assert.equal(attempts, 1); }); +test("an input push retry never re-delivers a question answered during the backoff", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout"] }); + t.mock.method(console, "warn", () => {}); + const sent = []; + let inputAttempts = 0; + webpush.sendNotification = async (_subscription, payload) => { + const body = JSON.parse(payload); + if (body.type === "input") { + inputAttempts += 1; + throw offline(); + } + sent.push(body); + }; + store.saveDevice("phone-device", prefs({ locale: "en" }), subscription); + hub.publishNotification({ + type: "input", + sessionId: "s1", + sessionName: "Deploy", + detail: "Ship it?", + requestId: "req-1", + dialog: { requestId: "req-1", method: "confirm", title: "Deploy?" }, + }); + await flush(); + assert.equal(inputAttempts, 1, "the first attempt failed and a retry is waiting"); + + // Another client answers while the retry sleeps. + hub.publishNotificationDismiss("s1", "req-1"); + await flush(); + t.mock.timers.tick(hub.PUSH_RETRY_DELAYS_MS[0]); + await flush(); + + assert.equal(inputAttempts, 1, "the sleeping retry must not deliver the settled question"); + assert.deepEqual(sent.map((body) => [body.type, body.requestId]), [["dismiss", "req-1"]]); +}); + +test("a retraction stops suppressing after the retry window", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + t.mock.method(console, "warn", () => {}); + const sent = []; + let inputAttempts = 0; + webpush.sendNotification = async (_subscription, payload) => { + const body = JSON.parse(payload); + if (body.type !== "input") return; + inputAttempts += 1; + if (inputAttempts === 1) throw offline(); + sent.push(body); + }; + store.saveDevice("phone-device", prefs({ locale: "en" }), subscription); + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", detail: "Ship it?", requestId: "req-2" }); + await flush(); + hub.publishNotificationDismiss("s2", "req-2"); + await flush(); + assert.equal(inputAttempts, 1, "the retraction suppressed the first retry"); + + t.mock.timers.tick(hub.PUSH_RETRACTION_TTL_MS + 1); + await flush(); + assert.equal(inputAttempts, 2, "a retry beyond the window is no longer suppressed"); + assert.deepEqual(sent.map((body) => [body.type, body.requestId]), [["input", "req-2"]]); +}); + +test("an input push for a different dialog is not suppressed by another retraction", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload) => { sent.push(JSON.parse(payload)); }; + store.saveDevice("phone-device", prefs({ locale: "en" }), subscription); + hub.publishNotificationDismiss("s1", "req-old"); + hub.publishNotification({ type: "input", sessionId: "s1", sessionName: "Deploy", detail: "Ship it?", requestId: "req-new" }); + await flush(); + assert.deepEqual(sent.filter((body) => body.type === "input").map((body) => body.requestId), ["req-new"]); +}); + test("the test button gets one attempt and the network failure's cause", async (t) => { isolatedStore(t); t.mock.method(console, "warn", () => {}); @@ -331,3 +404,82 @@ test("the test button gets one attempt and the network failure's cause", async ( }); assert.equal(attempts, 1); }); + +test("an input push carries the answerable dialog so the app can answer without SSE", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload) => { sent.push(JSON.parse(payload)); }; + store.saveDevice("phone-device", prefs({ locale: "en" }), subscription); + const dialog = { requestId: "req-1", method: "confirm", title: "Deploy?" }; + hub.publishNotification({ type: "input", sessionId: "s1", sessionName: "Deploy", detail: "Deploy?", requestId: "req-1", dialog }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(sent[0].dialog, dialog); + assert.equal(sent[0].type, "input"); + assert.equal(sent[0].requestId, "req-1", "the push carries the id its retraction matches"); +}); + +test("an input push without a dialog still carries the request id its retraction matches", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload) => { sent.push(JSON.parse(payload)); }; + store.saveDevice("phone-device", prefs({ locale: "en" }), subscription); + hub.publishNotification({ type: "input", sessionId: "s1", sessionName: "Docs", detail: "Open the docs", requestId: "open-1" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(sent[0].requestId, "open-1"); + assert.equal(sent[0].dialog, undefined); +}); + +test("a settled dialog marks its history entry read and dismisses SSE tabs and non-Apple pushes", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload, options) => { sent.push({ payload: JSON.parse(payload), urgency: options.urgency }); }; + store.saveDevice("phone-device", prefs(), subscription); + hub.publishNotification({ type: "input", sessionId: "s1", sessionName: "Session", detail: "Ship it?" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(store.listHistory().find((entry) => entry.id === "s1:input").read, false); + + const messages = []; + hub.attachNotificationClient("tab-0001", (message) => messages.push(message)); + hub.reportPresence({ clientId: "tab-0001", deviceId: "phone-device", visible: false, sessionId: null, seq: 1 }); + hub.publishNotificationDismiss("s1", "req-1"); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(messages, [{ kind: "dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }]); + assert.equal(store.listHistory().find((entry) => entry.id === "s1:input").read, true); + assert.deepEqual(sent.filter(({ payload }) => payload.type === "dismiss").map(({ payload, urgency }) => [payload.type, payload.tag, payload.requestId, urgency]), [ + ["dismiss", "s1:input", "req-1", "normal"], + ]); +}); + +test("dismiss pushes never go to Apple endpoints; SSE still dismisses them", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload) => { sent.push(JSON.parse(payload)); }; + const apple = { ...subscription, endpoint: "https://web.push.apple.com/abc" }; + store.saveDevice("iphone-device", prefs(), apple); + const messages = []; + hub.attachNotificationClient("tab-0001", (message) => messages.push(message.kind)); + hub.reportPresence({ clientId: "tab-0001", deviceId: "iphone-device", visible: false, sessionId: null, seq: 1 }); + hub.publishNotificationDismiss("s1", "req-1"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(sent, []); + assert.deepEqual(messages, ["dismiss"]); + assert.equal(hub.isApplePushEndpoint("https://web.push.apple.com/x"), true); + assert.equal(hub.isApplePushEndpoint("https://abc.push.apple.com/x"), true); + assert.equal(hub.isApplePushEndpoint("https://push.example/x"), false); + assert.equal(hub.isApplePushEndpoint("not a url"), false); +}); + +test("devices with the input type switched off receive no dismiss at all", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async () => { sent.push("push"); }; + store.saveDevice("phone-device", prefs({ types: { ...DEFAULT_NOTIFICATION_PREFS.types, input: false } }), subscription); + const messages = []; + hub.attachNotificationClient("tab-0001", (message) => messages.push(message)); + hub.reportPresence({ clientId: "tab-0001", deviceId: "phone-device", visible: false, sessionId: null, seq: 1 }); + hub.publishNotificationDismiss("s1", "req-1"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(messages, []); + assert.deepEqual(sent, []); +}); diff --git a/lib/notification-hub.ts b/lib/notification-hub.ts index 67e133ce8..4c005ef9a 100644 --- a/lib/notification-hub.ts +++ b/lib/notification-hub.ts @@ -7,7 +7,7 @@ import { type NotificationEvent, type RenderedNotification, } from "./notification-events"; -import { dropDeviceSubscription, getDevice, getVapidKeys, listDevices, recordHistory, type NotificationDevice } from "./notification-store"; +import { dropDeviceSubscription, getDevice, getVapidKeys, listDevices, markHistoryRead, recordHistory, type NotificationDevice } from "./notification-store"; /** * Server side of notifications: presence of open tabs, per-device preferences @@ -21,6 +21,13 @@ const PUSH_TTL_SECONDS = 3600; const PUSH_TIMEOUT_MS = 10_000; /** Waits before each retry of a push the push service never answered or answered 429/5xx. Well inside the TTL. */ export const PUSH_RETRY_DELAYS_MS = [2_000, 10_000, 30_000]; +/** + * How long a retraction keeps suppressing further delivery attempts of the + * same `input` push: one retry cycle is its backoff waits plus the time a + * single attempt may hang, and no retry can outlive that. + */ +export const PUSH_RETRACTION_TTL_MS = PUSH_RETRY_DELAYS_MS.reduce((total, delay) => total + delay, 0) + + (PUSH_RETRY_DELAYS_MS.length + 1) * PUSH_TIMEOUT_MS; // Apple's push service rejects VAPID subjects it cannot resolve (e.g. localhost mail). const VAPID_SUBJECT = "https://github.com/kahme247/ompweb"; @@ -35,7 +42,13 @@ export interface NotificationPresence { lastSeen: number; } -export type NotificationMessage = { kind: "toast" | "os"; event: NotificationEvent }; +/** + * A toast/system notification, or the retraction of a session's `input` + * notification once its dialog was answered, cancelled, expired or destroyed. + */ +export type NotificationMessage = + | { kind: "toast" | "os"; event: NotificationEvent } + | { kind: "dismiss"; tag: string; sessionId: string; requestId: string }; type Send = (message: NotificationMessage) => void; @@ -47,6 +60,8 @@ interface HubState { presence: Map; /** Open SSE streams per tab. Independent of presence: streams reconnect, overlap, and close while the tab stays put. */ streams: Map>; + /** `:` → when it was retracted. A push retry of a settled dialog must deliver nothing (see `publishNotificationDismiss`). */ + retractions: Map; } declare global { @@ -54,7 +69,11 @@ declare global { } function hub(): HubState { - return (globalThis.__ompNotificationHub ??= { presence: new Map(), streams: new Map() }); + const state = (globalThis.__ompNotificationHub ??= { presence: new Map(), streams: new Map(), retractions: new Map() }); + // Next evaluates this module once per route bundle: a state object another + // bundle created may predate a field added here. + state.retractions ??= new Map(); + return state; } export function getVapidPublicKey(): string { @@ -152,14 +171,71 @@ function stillSubscribed(deviceId: string, endpoint: string): boolean { } /** Never throws: a failed push must not break delivery to anyone else. */ +async function sendPushPayload( + device: NotificationDevice, + payload: unknown, + urgency: "high" | "normal", +): Promise<{ ok: true } | { ok: false; error: string }> { + const subscription = device.subscription; + if (!subscription) return { ok: false, error: "no push subscription" }; + try { + const { publicKey, privateKey } = getVapidKeys(webpush.generateVAPIDKeys); + await webpush.sendNotification(subscription, JSON.stringify(payload), { + TTL: PUSH_TTL_SECONDS, + urgency, + timeout: PUSH_TIMEOUT_MS, + vapidDetails: { subject: VAPID_SUBJECT, publicKey, privateKey }, + }); + return { ok: true }; + } catch (error) { + const status = error instanceof webpush.WebPushError ? error.statusCode : undefined; + try { + // 404/410: the browser unsubscribed or the subscription expired. + if (status === 404 || status === 410) dropDeviceSubscription(device.deviceId, subscription.endpoint); + } catch { + // A store write failure only delays the cleanup to the next push. + } + const message = status ? `push service answered ${status}` : describePushError(error); + console.warn("[notifications] push failed:", message); + return { ok: false, error: message }; + } +} + +/** The dialog a retraction is about. */ +function retractionKey(sessionId: string, requestId: string): string { + return `${sessionId}:${requestId}`; +} + +/** + * True while this dialog's retraction still covers a push retry. Every path + * that settles a dialog (answer, cancel, expiry, process exit) records one, + * and `sendPush` asks before every attempt: a retry that wakes up after + * another client answered must never re-deliver a question nobody can answer. + */ +function isRetracted(sessionId: string, requestId: string, now: number): boolean { + const at = hub().retractions.get(retractionKey(sessionId, requestId)); + return at !== undefined && now - at <= PUSH_RETRACTION_TTL_MS; +} + async function sendPush(device: NotificationDevice, event: NotificationEvent, retryDelaysMs: readonly number[] = []): Promise<{ ok: true } | { ok: false; error: string }> { const subscription = device.subscription; if (!subscription) return { ok: false, error: "no push subscription" }; for (let attempt = 0; ; attempt++) { + // A retry can wake long after the dialog was answered, cancelled, expired + // or its omp child died: delivering now would show a dead question. + if (event.type === "input" && event.requestId && isRetracted(event.sessionId, event.requestId, Date.now())) { + return { ok: false, error: "dialog settled" }; + } try { const { publicKey, privateKey } = getVapidKeys(webpush.generateVAPIDKeys); - // `type` lets the service worker tell open tabs which kind of entry to list. - await webpush.sendNotification(subscription, JSON.stringify({ ...renderFor(event, device.prefs.locale), type: event.type }), { + // `type` lets the service worker tell open tabs which kind of entry to list; + // `dialog` lets the native app answer without opening the session. + await webpush.sendNotification(subscription, JSON.stringify({ + ...renderFor(event, device.prefs.locale), + type: event.type, + ...(event.requestId ? { requestId: event.requestId } : {}), + ...(event.dialog ? { dialog: event.dialog } : {}), + }), { TTL: PUSH_TTL_SECONDS, urgency: event.type === "input" || event.type === "error" ? "high" : "normal", timeout: PUSH_TIMEOUT_MS, @@ -188,6 +264,22 @@ async function sendPush(device: NotificationDevice, event: NotificationEvent, re } } +/** + * Apple's push service is the one endpoint where a push that displays nothing + * costs the permission itself: iOS revokes Web Push for the site. Dismiss + * pushes therefore never go there; the app clears the notification when its + * own answer reaches the server, or the stale one is replaced by the next + * `input` push of the same tag. + */ +export function isApplePushEndpoint(endpoint: string): boolean { + try { + const host = new URL(endpoint).hostname.toLowerCase(); + return host === "web.push.apple.com" || host.endsWith(".push.apple.com"); + } catch { + return false; + } +} + /** Never throws: callers publish from the RPC frame path, and a store failure must not cost them the frame. */ export function publishNotification(event: NotificationEvent): void { const state = hub(); @@ -224,8 +316,58 @@ export function publishNotification(event: NotificationEvent): void { } } -/** Settings "Send test notification" for a device with push: reports whether the push service accepted it. - * One attempt, so the button answers at once. */ +/** + * Retract a session's `input` notification: its dialog was answered by any + * client, cancelled, expired, or its omp child went away. Reachable tabs of + * devices that enabled `input` get an SSE frame; subscribed devices get a + * dismiss push unless the endpoint is Apple's (see isApplePushEndpoint). The + * history entry becomes read because the question is settled. + * + * Never throws: callers run on the RPC frame path. + */ +export function publishNotificationDismiss(sessionId: string, requestId: string): void { + const tag = `${sessionId}:input`; + // Recorded first: a retry of that `input` push may be sleeping right now. + const state = hub(); + const now = Date.now(); + for (const [key, at] of state.retractions) { + if (now - at > PUSH_RETRACTION_TTL_MS) state.retractions.delete(key); + } + state.retractions.set(retractionKey(sessionId, requestId), now); + try { + markHistoryRead([tag]); + } catch (error) { + console.warn("[notifications] history read mark failed:", error); + } + let devices: NotificationDevice[] = []; + try { + devices = listDevices(); + } catch (error) { + console.warn("[notifications] store unavailable:", error); + } + if (devices.length === 0) return; + const presence = livePresence(Date.now()); + const reachable = new Set(state.streams.keys()); + for (const device of devices) { + if (!device.prefs.enabled || !device.prefs.types.input) continue; + for (const tab of presence) { + if (tab.deviceId !== device.deviceId || !reachable.has(tab.clientId)) continue; + for (const send of state.streams.get(tab.clientId) ?? []) { + try { + send({ kind: "dismiss", tag, sessionId, requestId }); + } catch { + // A closing stream must not break delivery to the others. + } + } + } + if (device.subscription && !isApplePushEndpoint(device.subscription.endpoint)) { + // urgency "normal": a retraction must not wake a phone like a question. + void sendPushPayload(device, { type: "dismiss", tag, sessionId, requestId }, "normal"); + } + } +} + +/** Settings "Send test notification" for a device with push: reports whether the push service accepted it. */ export async function sendTestPush(deviceId: string): Promise<{ ok: true } | { ok: false; error: string }> { const device = getDevice(deviceId); if (!device) return { ok: false, error: "unknown device" }; diff --git a/lib/notification-sw.test.mjs b/lib/notification-sw.test.mjs index 860510e36..d001906a3 100644 --- a/lib/notification-sw.test.mjs +++ b/lib/notification-sw.test.mjs @@ -6,13 +6,16 @@ import vm from "node:vm"; // Runs public/sw.js against a fake worker scope: the push handler is the only // way a subscribed browser learns about a notification, so it must tell open tabs. // Messages are cloned as postMessage does, which also drops the vm realm. -function loadWorker(windows) { +function loadWorker(windows, { notifications = [] } = {}) { const listeners = {}; const shown = []; const self = { addEventListener: (type, listener) => { listeners[type] = listener; }, skipWaiting() {}, - registration: { showNotification: async (title, options) => { shown.push({ title, options }); } }, + registration: { + showNotification: async (title, options) => { shown.push({ title, options }); }, + getNotifications: async ({ tag } = {}) => notifications.filter((notification) => tag === undefined || notification.tag === tag), + }, clients: { claim: async () => {}, matchAll: async () => windows }, }; vm.runInNewContext(readFileSync(new URL("../public/sw.js", import.meta.url), "utf8"), { self, URL }); @@ -43,3 +46,48 @@ test("an unreadable push still shows a notification and reports it as info", asy assert.equal(worker.shown[0].title, "omp web"); assert.deepEqual(messages[0].notification, { type: "info", title: "omp web", body: "", tag: "", sessionId: "" }); }); + +test("a dismiss push closes the notification with its tag and displays nothing", async () => { + const messages = []; + const closed = []; + const existing = [ + { tag: "s1:input", data: { requestId: "req-1" }, close: () => closed.push("s1:input") }, + { tag: "s2:input", data: { requestId: "req-2" }, close: () => closed.push("s2:input") }, + ]; + const worker = loadWorker([{ postMessage: (message) => messages.push(structuredClone(message)) }], { notifications: existing }); + await worker.push({ type: "dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + assert.deepEqual(worker.shown, []); + assert.deepEqual(messages, []); + assert.deepEqual(closed, ["s1:input"]); +}); + +test("a late dismiss for an older request leaves the current notification alone", async () => { + const closed = []; + const existing = [{ tag: "s1:input", data: { requestId: "req-2" }, close: () => closed.push("s1:input") }]; + const worker = loadWorker([], { notifications: existing }); + await worker.push({ type: "dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + assert.deepEqual(worker.shown, []); + assert.deepEqual(closed, [], "unrelated request ids must not close the notification"); +}); + +test("a shown push keeps its dialog request id for a later dismiss", async () => { + const worker = loadWorker([]); + await worker.push({ + type: "input", + title: "Deploy?", + body: "Waiting", + tag: "s1:input", + sessionId: "s1", + requestId: "req-1", + dialog: { requestId: "req-1", method: "confirm" }, + }); + assert.deepEqual(structuredClone(worker.shown[0].options.data), { url: "/", sessionId: "s1", requestId: "req-1" }); +}); + +test("a dismiss without a tag is a no-op instead of closing every notification", async () => { + const closed = []; + const worker = loadWorker([], { notifications: [{ tag: "s1:input", close: () => closed.push("s1:input") }] }); + await worker.push({ type: "dismiss", sessionId: "s1", requestId: "req-1" }); + assert.deepEqual(worker.shown, []); + assert.deepEqual(closed, []); +}); diff --git a/lib/pi-types.ts b/lib/pi-types.ts index f3a7dca25..f0e342177 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -222,6 +222,16 @@ export interface RpcAskDialogAnswer { customInput?: string; } +/** + * One answer to a blocking extension dialog. Exactly one variant is sent, both + * by the web dialog (ExtensionDialog) and by the notification answer endpoint. + */ +export type ExtensionUiResponse = + | { value: string } + | { confirmed: boolean } + | { cancelled: true } + | { answers: RpcAskDialogAnswer[] }; + /** * omp's rpc-ui extension UI request frames, including the methods missing from * the browser-facing union in lib/types.ts (`open_url`, `cancel`). The wrapper diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index a153e829d..0cced07ab 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -717,9 +717,13 @@ async function notifyingSession(t) { saveDevice("desk-0001", { enabled: true, types: { completed: true, input: true, error: true, modelSwitch: true }, whenActive: "toast", locale: "en" }); globalThis.__ompExitedSessions = new Map(); const delivered = []; + const dismissed = []; globalThis.__ompNotificationHub = { presence: new Map([["tab-0001", { clientId: "tab-0001", deviceId: "desk-0001", visible: false, sessionId: null, lastSeen: Date.now() }]]), - streams: new Map([["tab-0001", new Set([(message) => delivered.push([message.event.type, message.event.detail])])]]), + streams: new Map([["tab-0001", new Set([ + (message) => delivered.push([message.event.type, message.event.detail]), + (message) => { if (message.kind === "dismiss") dismissed.push([message.tag, message.requestId]); }, + ])]]), }; let feed; /** What omp's get_state answers; tests change it to simulate session moves and switches. */ @@ -747,7 +751,7 @@ async function notifyingSession(t) { globalThis.__ompNotificationStore = undefined; rmSync(dir, { recursive: true, force: true }); }); - return { wrapper, feed, delivered, ompState }; + return { wrapper, feed, delivered, dismissed, ompState }; } test("after a moved session switches to another conversation, a tab left on the old id no longer silences it", async (t) => { @@ -768,6 +772,31 @@ test("after a moved session switches to another conversation, a tab left on the assert.deepEqual(delivered.filter(([type]) => type === "completed"), [["completed", undefined]]); }); +test("a dialog without a notification payload is dismissed under the id it was published with", async (t) => { + const { feed, dismissed, ompState } = await notifyingSession(t); + // open_url has no answerable dialog, so the notification is published under + // the session id but no dialog map entry used to be written. + feed({ type: "extension_ui_request", id: "open-1", method: "open_url", url: "https://example.test" }); + assert.deepEqual(dismissed, []); + // omp moves the conversation before the request settles. + Object.assign(ompState, { sessionId: "moved-session", sessionFile: "/tmp/moved-session.jsonl" }); + feed({ type: "notice", level: "warning", source: "session-persistence", message: "moved" }); + await new Promise((resolve) => setImmediate(resolve)); + feed({ type: "extension_ui_request", method: "cancel", targetId: "open-1" }); + assert.deepEqual(dismissed, [["notify-session:input", "open-1"]], "the retraction uses the published session, not the new one"); +}); + +test("an expired dialog is retracted when a reconnect replays it", async (t) => { + const { wrapper, feed, dismissed } = await notifyingSession(t); + feed({ type: "extension_ui_request", id: "late-1", method: "confirm", title: "Still there?" }); + const pending = wrapper.pendingUiRequests.get("late-1"); + assert.ok(pending, "the dialog is pending before the replay"); + pending.expiresAt = Date.now() - 1; + wrapper.onEvent(() => {}); + assert.deepEqual(dismissed, [["notify-session:input", "late-1"]]); + assert.equal(wrapper.pendingUiRequests.has("late-1"), false); +}); + test("omp frames reach the user as notifications: settled run, pending question", async (t) => { const { feed, delivered } = await notifyingSession(t); feed({ type: "agent_start" }); @@ -1226,6 +1255,58 @@ test("expired dialogs are not replayed by a later stream subscription", async (t assert.deepEqual(received, []); }); +test("answering from a notification settles once, forwards the frame and retracts other tabs", async (t) => { + const { wrapper, emit, sentFrames } = snapshotSession(t, undefined, SnapshotWrapper, "dialog-session"); + const events = []; + wrapper.onEvent((event) => events.push(event)); + emit({ type: "extension_ui_request", id: "q1", method: "confirm", title: "Continue?" }); + assert.equal(wrapper.answerExtensionUiRequest("q1", { confirmed: true }), "answered"); + assert.deepEqual(sentFrames, [{ type: "extension_ui_response", id: "q1", confirmed: true }]); + const cancel = events.at(-1); + assert.equal(cancel.type, "extension_ui_request"); + assert.equal(cancel.id, "cancel:q1"); + assert.equal(cancel.method, "cancel"); + assert.equal(cancel.targetId, "q1"); + assert.equal(wrapper.answerExtensionUiRequest("q1", { confirmed: true }), "alreadySettled"); + assert.equal(sentFrames.length, 1, "a settled id is never forwarded twice"); + emit({ type: "extension_ui_request", method: "cancel", targetId: "q1" }); + assert.equal(sentFrames.length, 1); +}); + +test("a notification answer must match the pending dialog method", async (t) => { + const { wrapper, emit } = snapshotSession(t); + emit({ type: "extension_ui_request", id: "ask", method: "ask", questions: [{ id: "q", question: "Pick", options: [{ label: "A" }] }] }); + assert.throws(() => wrapper.answerExtensionUiRequest("ask", { value: "A" }), /Invalid ask dialog answers/); + assert.equal(wrapper.answerExtensionUiRequest("ask", { cancelled: true }), "answered"); + + emit({ type: "extension_ui_request", id: "confirm", method: "confirm", title: "Continue?" }); + assert.throws(() => wrapper.answerExtensionUiRequest("confirm", { answers: [] }), /does not take answers/); + assert.equal(wrapper.answerExtensionUiRequest("confirm", { confirmed: true }), "answered"); +}); + +test("a new run retracts a dialog the previous run left open", async (t) => { + const { wrapper, emit, sentFrames } = snapshotSession(t); + emit({ type: "extension_ui_request", id: "old", method: "input", title: "Value" }); + emit({ type: "agent_start" }); + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay.some((event) => event.id === "old"), false, "the old dialog is not replayed into a new run"); + assert.equal(wrapper.answerExtensionUiRequest("old", { value: "late" }), "alreadySettled"); + assert.deepEqual(sentFrames, []); +}); + +test("an expired or destroyed dialog answers as already settled", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + const { wrapper, emit } = snapshotSession(t); + emit({ type: "extension_ui_request", id: "late", method: "input", title: "Value", timeout: 50 }); + t.mock.timers.tick(51); + assert.equal(wrapper.answerExtensionUiRequest("late", { value: "x" }), "alreadySettled"); + + emit({ type: "extension_ui_request", id: "gone", method: "input", title: "Value" }); + await wrapper.destroyAndWait(); + assert.equal(wrapper.answerExtensionUiRequest("gone", { value: "x" }), "alreadySettled"); +}); + test("native web metadata cannot forge either wire or cached tool snapshot sequencing", async (t) => { const { wrapper, emit } = snapshotSession(t); const events = []; diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index f8e23cee8..4cbbfd98e 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -33,12 +33,13 @@ import { comparableProjectPath } from "./comparable-path"; import { samePath } from "./paths"; import { isRecord } from "./type-guards"; import { BLOCKING_UI_METHODS, createNotificationDetector } from "./notification-events"; -import { publishNotification } from "./notification-hub"; +import { publishNotification, publishNotificationDismiss } from "./notification-hub"; import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "./skill-diagnostics"; import { isReservedLaunchArg, loadProjectRegistry } from "./project-registry"; import { eventWithToolResultImageUrls } from "./media-cache"; import type { BashResultInfo, + ExtensionUiResponse, OmpModel, RpcAvailableSlashCommand, RpcSessionState, @@ -129,7 +130,7 @@ export class WebRpcError extends Error { } /** Shape check for an ask-dialog `answers` payload; omp validates the content. */ -function isAskAnswers(value: unknown): boolean { +export function isAskAnswers(value: unknown): boolean { return Array.isArray(value) && value.every((answer: unknown) => isRecord(answer) && typeof answer.id === "string" @@ -331,6 +332,8 @@ export class AgentSessionWrapper { private listeners: EventListener[] = []; private pendingUiRequests = new Map(); private uiExpiryTimers = new Map>(); + /** Session id each input notification was published under, keyed by request id. */ + private inputNotificationSessions = new Map(); private extensionStatuses = new Map(); private extensionWidgets = new Map(); private promptRunning = false; @@ -777,6 +780,14 @@ export class AgentSessionWrapper { sessionName: this._sessionName || this.cwd.split(/[\\/]/).filter(Boolean).pop() || null, }; for (const notification of this.detectNotification(frame, session)) { + if (notification.type === "input") { + // Dismiss uses the id the notification was published under, even after + // omp moved the conversation to a new file. Remember it even when the + // dialog did not fit a notification (`open_url`, oversized payload): + // the retraction still has to reach the published tag. + const requestId = notification.requestId ?? notification.dialog?.requestId ?? (typeof frame.id === "string" ? frame.id : ""); + if (requestId) this.inputNotificationSessions.set(requestId, notification.sessionId); + } publishNotification(this.movedFromIds.length ? { ...notification, aliases: this.movedFromIds } : notification); } } @@ -818,6 +829,9 @@ export class AgentSessionWrapper { this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; + // A new run supersedes any dialog the previous run left open: its + // notification must not offer an answer that would now reach the wrong run. + this.clearPendingUiRequests(); // The session file can appear just after the prompt acknowledgement. // Invalidate and signal the sidebar now rather than waiting for the // agent's first reply or terminal event. @@ -1030,17 +1044,59 @@ export class AgentSessionWrapper { } } + /** + * A pending dialog is settled (answered, cancelled, expired or its child is + * gone): forget it and retract the `input` notification it produced. + */ + private settlePendingUiRequest(id: string): boolean { + if (!this.pendingUiRequests.has(id)) return false; + const sessionId = this.inputNotificationSessions.get(id) ?? this._sessionId; + this.forgetPendingUiRequest(id); + this.inputNotificationSessions.delete(id); + if (sessionId) publishNotificationDismiss(sessionId, id); + return true; + } + private clearPendingUiRequests(): void { for (const timer of this.uiExpiryTimers.values()) clearTimeout(timer); this.uiExpiryTimers.clear(); - this.pendingUiRequests.clear(); + for (const id of [...this.pendingUiRequests.keys()]) this.settlePendingUiRequest(id); + this.inputNotificationSessions.clear(); + } + + /** + * Answer a blocking dialog from a notification action. Uses the same + * validation and frame as the agent route's `extension_ui_response` command, + * and returns whether the request was still pending. + */ + answerExtensionUiRequest(id: string, response: ExtensionUiResponse): "answered" | "alreadySettled" { + const pending = this.pendingUiRequests.get(id); + if (!pending) return "alreadySettled"; + const pendingAsk = pending.method === "ask"; + // A pending ask accepts only its answers or a cancel; any other pending + // dialog accepts no answers. Anything else would drop it from reconnect + // replay while omp rejects the payload. + if (pendingAsk) { + if (!("cancelled" in response) && !isAskAnswers("answers" in response ? response.answers : undefined)) { + throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); + } + } else if ("answers" in response) { + throw new WebRpcError("This dialog does not take answers", "invalid_ask_answers"); + } + const wasPending = this.settlePendingUiRequest(id); + this.proc.sendFrame({ type: "extension_ui_response", id, ...response }); + // omp sends no cancel for an answered dialog; other tabs on this session + // would keep showing it, so settle it for them here. + if (wasPending) this.emit({ type: "extension_ui_request", id: `cancel:${id}`, method: "cancel", targetId: id }); + return "answered"; } private trackExtensionUiRequest(event: UnsequencedAgentEvent): boolean { const method = event.method as string; const id = event.id as string; if (method === "cancel") { - this.forgetPendingUiRequest(event.targetId as string); + const targetId = typeof event.targetId === "string" ? event.targetId : ""; + if (targetId) this.settlePendingUiRequest(targetId); return false; } // Only the “Allow tool: ” confirmation is covered. Other extension @@ -1063,7 +1119,7 @@ export class AgentSessionWrapper { const timeout = typeof event.timeout === "number" ? event.timeout : undefined; if (timeout && timeout > 0) { event.expiresAt = Date.now() + timeout; - const timer = setTimeout(() => this.forgetPendingUiRequest(id), timeout); + const timer = setTimeout(() => this.settlePendingUiRequest(id), timeout); timer.unref?.(); this.uiExpiryTimers.set(id, timer); } @@ -1296,7 +1352,9 @@ export class AgentSessionWrapper { for (const [id, event] of this.pendingUiRequests) { const expiresAt = event.expiresAt as number | undefined; if (expiresAt !== undefined && expiresAt <= now) { - this.forgetPendingUiRequest(id); + // Same retraction as the expiry timer: forget alone would leave the + // notification and history entry behind after a reconnect. + this.settlePendingUiRequest(id); continue; } listener({ ...event, web: { streamId: this.streamId, sequence: ++this.streamSequence } }); @@ -2076,8 +2134,9 @@ export class AgentSessionWrapper { if (("answers" in rest || pendingAsk) && !isAskAnswers(rest.answers) && !(pendingAsk && rest.cancelled === true)) { throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); } - const wasPending = this.pendingUiRequests.has(id); - this.forgetPendingUiRequest(id); + // Forgets the pending dialog and retracts its notification for other + // tabs/devices; the cancel frame below settles it in other tabs. + const wasPending = this.settlePendingUiRequest(id); this.proc.sendFrame({ type: "extension_ui_response", id, ...rest }); // omp sends no cancel for an answered dialog; other tabs on this // session would keep showing it, so settle it for them here. diff --git a/public/sw.js b/public/sw.js index 8fecfa4f0..f7abad5d3 100644 --- a/public/sw.js +++ b/public/sw.js @@ -11,6 +11,27 @@ self.addEventListener("push", (event) => { } catch { // Unreadable payload: still show something (iOS revokes silent pushes). } + // A settled dialog is retracted by tag. This branch never displays anything, + // which is why the server sends dismiss pushes only to endpoints that are not + // Apple's: iOS revokes Web Push permission for a push that shows no notification. + if (data.type === "dismiss") { + const tag = typeof data.tag === "string" ? data.tag : ""; + const requestId = typeof data.requestId === "string" ? data.requestId : ""; + event.waitUntil((async () => { + // Web Push is not ordered and can be buffered while the device is + // offline: a late retraction must not close the next dialog's + // notification of the same tag, so only the matching request closes. + if (!tag || !requestId || typeof self.registration.getNotifications !== "function") return; + const shown = await self.registration.getNotifications({ tag }); + for (const notification of shown) { + if (notification.data && notification.data.requestId === requestId) notification.close(); + } + })()); + return; + } + const requestId = typeof data.requestId === "string" + ? data.requestId + : typeof data.dialog?.requestId === "string" ? data.dialog.requestId : ""; const shown = { type: data.type === "error" ? "error" : "info", title: data.title || "omp web", @@ -26,7 +47,7 @@ self.addEventListener("push", (event) => { badge: "/badge-96.png", tag: shown.tag || undefined, renotify: Boolean(shown.tag), - data: { url: data.url || "/", sessionId: shown.sessionId }, + data: { url: data.url || "/", sessionId: shown.sessionId, ...(requestId ? { requestId } : {}) }, }); // Open tabs list it in their Notifications tab, like a notification the page showed itself. const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true }); From b09a8671438ea11f0252ff3bc1baaf8b0ba80b37 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:55:55 +0100 Subject: [PATCH 5/6] docs(changelog): answer notifications and dialog dismiss --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50c1adb70..036cae57b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added +- **Answer a blocking dialog straight from a notification.** An `input` notification now carries the open dialog (request id, method, title, message, options, ask questions), clipped so a push stays under 4 KB; dialogs that cannot be answered (`open_url`, oversized payloads) are left out. `POST /api/notifications/answer { sessionId, requestId, response }` answers a pending dialog without an open event stream: it validates exactly like the agent route, never spawns omp, accepts 64 KB, and answers `answered`, `alreadySettled` or `sessionGone`. Once a dialog settles — answered anywhere, cancelled, expired, its session gone or a new run started — a dismiss is published to open tabs and subscribed devices so the stale question disappears (never as a silent push to Apple endpoints, because iOS revokes the permission for one). The web toast and native clients share the same behaviour. - **A handshake for native clients.** `GET /api/app-info` answers with the package name, version, API level and which server-side capabilities exist. It carries no configuration and no credentials (it sits behind the normal auth gate), and it lets a client tell "not an ompweb server" from "server too old" from "OK" instead of probing endpoints. A native client can also ask for its own keep-alive interval with `GET /api/events?heartbeat=` (15-110 s; any other value keeps the 30 s default). The interval belongs to that connection only, so the browser's shared stream is unchanged, and a phone's radio can sleep for the whole idle interval. ### Fixes & Improvements From ae33fff2f015dcab6bc162f2a909b1117782fee8 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Thu, 29 Oct 2026 06:48:33 +0100 Subject: [PATCH 6/6] docs: name the app-info identity and cover the new paths The handshake answers `name: "ompweb"`, which is not the npm package name; the changelog now says so. Two coverage gaps from review: the proxy test asserts `/api/app-info` sits behind the password gate, and a route-level test sends `?heartbeat=60` and proves the keep-alive is not the fixed 30 s default. --- CHANGELOG.md | 2 +- lib/event-stream-hub.test.mjs | 24 ++++++++++++++++++++++++ lib/web-auth.test.mjs | 5 +++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50c1adb70..a9f77a48d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added -- **A handshake for native clients.** `GET /api/app-info` answers with the package name, version, API level and which server-side capabilities exist. It carries no configuration and no credentials (it sits behind the normal auth gate), and it lets a client tell "not an ompweb server" from "server too old" from "OK" instead of probing endpoints. A native client can also ask for its own keep-alive interval with `GET /api/events?heartbeat=` (15-110 s; any other value keeps the 30 s default). The interval belongs to that connection only, so the browser's shared stream is unchanged, and a phone's radio can sleep for the whole idle interval. +- **A handshake for native clients.** `GET /api/app-info` answers with the app name `ompweb` (not the npm package name `@kahme247/ompweb`), version, API level and which server-side capabilities exist. It carries no configuration and no credentials (it sits behind the normal auth gate), and it lets a client tell "not an ompweb server" from "server too old" from "OK" instead of probing endpoints. A native client can also ask for its own keep-alive interval with `GET /api/events?heartbeat=` (15-110 s; any other value keeps the 30 s default). The interval belongs to that connection only, so the browser's shared stream is unchanged, and a phone's radio can sleep for the whole idle interval. ### Fixes & Improvements diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 6d985e79f..44d83df3d 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -503,3 +503,27 @@ test("a connection created with a custom interval emits its keep-alive at that i assert.ok(elapsed < 1000, `heartbeat arrived after ${elapsed} ms`); connection.close(); }); + +test("GET honours the heartbeat query parameter", async (t) => { + // Only the keep-alive interval is faked; readFrame's own watchdog stays real. + t.mock.timers.enable({ apis: ["setInterval"] }); + const ac = new AbortController(); + const res = route.GET(new Request("http://localhost/api/events?heartbeat=60", { signal: ac.signal })); + const reader = res.body.getReader(); + try { + assert.equal((await readFrame(reader)).data.type, "hello"); + let keepAliveArrived = false; + const keepAlive = reader.read().then((chunk) => { + keepAliveArrived = true; + return chunk; + }); + t.mock.timers.tick(30_000); + await setImmediate(); + assert.equal(keepAliveArrived, false, "no keep-alive before the requested 60 s"); + t.mock.timers.tick(30_000); + assert.equal(decoder.decode((await keepAlive).value), ":\n\n"); + } finally { + ac.abort(); + t.mock.timers.reset(); + } +}); diff --git a/lib/web-auth.test.mjs b/lib/web-auth.test.mjs index dfb96d979..15acc5f92 100644 --- a/lib/web-auth.test.mjs +++ b/lib/web-auth.test.mjs @@ -170,6 +170,11 @@ test("redirects browser requests to the password screen and blocks unauthenticat const apiResponse = proxy(new NextRequest("http://localhost:30177/api/sessions")); assert.equal(apiResponse.status, 401); + // The handshake endpoint is documented as sitting behind the normal auth + // gate; an exemption for just this path must not pass the suite. + const appInfoResponse = proxy(new NextRequest("http://localhost:30177/api/app-info")); + assert.equal(appInfoResponse.status, 401); + const signedInResponse = proxy(new NextRequest("http://localhost:30177/", { headers: { cookie: `omp_web_session=${createWebSession()}` }, }));