From 26f3e606497d58ced8dcf69298456871bae66fbe Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:25:03 +0100 Subject: [PATCH 1/6] feat(notifications): answer a pending dialog from the notification A phone notification for a blocking dialog now answers it: POST /api/notifications/answer validates the answer against the pending dialog and sends the same extension_ui_response command the desktop dialog uses, so a server-owned confirm resolves and the offline or restarting gate applies instead of reporting an answer that never arrived. Every settlement path (desktop answer, omp cancel, expiry, replay-time expiry, server-owned dialogs dropped, clearing on restart/destroy and process exit) retracts the notification it produced. The retraction is its own `notification-dismiss` frame carrying the tag and request id, and a dismiss push for subscribed non-Apple endpoints; the request id also rides on the toast, the system notification and the push so a late retraction cannot close the next dialog of the same tag. The published session id is remembered per request, so a conversation omp moved to a new file still retracts under the tag it was published with. Push payloads carry the answerable dialog (confirm/select/input/editor/ ask) within a fixed size budget; a dialog that would have to be altered to fit is omitted and the notification only opens the session. --- app/api/notifications/answer/route.ts | 74 ++++++++++++ components/ui/toast.click.test.mjs | 59 +++++++++ hooks/useNotifications.ts | 46 ++++++- lib/event-stream-hub.test.mjs | 22 ++++ lib/event-stream-hub.ts | 10 +- lib/notification-answer-route.test.mjs | 143 ++++++++++++++++++++++ lib/notification-client.ts | 6 +- lib/notification-events.test.mjs | 31 +++++ lib/notification-events.ts | 161 ++++++++++++++++++++++++- lib/notification-hub.test.mjs | 73 +++++++++++ lib/notification-hub.ts | 154 ++++++++++++++++++++++- lib/notification-store.ts | 13 +- lib/notification-sw.test.mjs | 26 ++++ lib/pi-types.ts | 10 ++ lib/rpc-manager.test.mjs | 84 ++++++++++++- lib/rpc-manager.ts | 84 +++++++++++-- public/sw.js | 23 +++- server/routes.ts | 2 + 18 files changed, 989 insertions(+), 32 deletions(-) create mode 100644 app/api/notifications/answer/route.ts create mode 100644 lib/notification-answer-route.test.mjs diff --git a/app/api/notifications/answer/route.ts b/app/api/notifications/answer/route.ts new file mode 100644 index 000000000..8d57b12f4 --- /dev/null +++ b/app/api/notifications/answer/route.ts @@ -0,0 +1,74 @@ +import { commandErrorResponse } from "@/lib/agent-command"; +import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import type { ExtensionUiResponse, RpcAskDialogAnswer } from "@/lib/pi-types"; +import { getRpcSession, isAskAnswers } from "@/lib/rpc-manager"; +import { isRecord } from "@/lib/type-guards"; + +/** 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) => Response.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 the shared extension_ui_response command + * 200 {status:"alreadySettled"} the request id is not pending + * 200 {status:"sessionGone"} no live wrapper for the session + * 400 on an invalid body or an answer the pending dialog does not take + * 400 session_restarting / 503 {hostOffline: true} when it cannot be delivered + */ +export async function POST(req: Request) { + let body: unknown; + try { + body = await parseJsonWithinLimit(req, MAX_BODY_BYTES); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) { + return Response.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 Response.json({ status: "sessionGone" }); + + try { + return Response.json({ status: await session.answerExtensionUiRequest(body.requestId, response) }); + } catch (error) { + return commandErrorResponse(error); + } +} diff --git a/components/ui/toast.click.test.mjs b/components/ui/toast.click.test.mjs index cdefabd8a..dc5bbe032 100644 --- a/components/ui/toast.click.test.mjs +++ b/components/ui/toast.click.test.mjs @@ -26,6 +26,12 @@ function deliverNotification(message) { assert.ok(id, "useNotifications must hold a notifications channel"); eventWorker.onmessage({ data: { id, type: "message", data: JSON.stringify({ type: "notification", ...message }) } }); } +/** A frame the server's notification channel sends verbatim (lib/event-stream-hub.ts). */ +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(frame) } }); +} before(() => { globalThis.AbortController = window.AbortController; @@ -124,6 +130,59 @@ test("a session notification toast opens its session from a card click; one with assert.deepEqual(sessions, ["s1"]); }); +test("a retraction frame closes the toast of its own request and leaves a newer dialog of the same tag", async () => { + render(React.createElement(ToastProvider, null)); + renderHook(() => useNotifications({ sessionId: null, locale: "en", onOpenSession: () => {} })); + const cards = () => Array.from(document.querySelectorAll(".toast-card")); + const titles = () => cards().map((card) => card.querySelector(".display-serif")?.textContent); + + // The first dialog of this session, then the retraction that settles it. + act(() => { + deliverNotification({ kind: "toast", event: { type: "input", sessionId: "s1", sessionName: "Deploy", detail: "Ship it?", requestId: "req-1" } }); + }); + assert.deepEqual(titles(), ["Deploy"]); + act(() => { + deliverFrame({ type: "notification-dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + }); + assert.deepEqual(titles(), [], "the settled question's card is gone"); + + // A replacement dialog of the same tag: a late retraction of the old request + // must not close it, and the matching one does. + act(() => { + deliverNotification({ kind: "toast", event: { type: "input", sessionId: "s1", sessionName: "Deploy", detail: "Or now?", requestId: "req-2" } }); + }); + act(() => { + deliverFrame({ type: "notification-dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + }); + assert.deepEqual(titles(), ["Deploy"], "a stale retraction leaves the next dialog alone"); + act(() => { + deliverFrame({ type: "notification-dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-2" }); + }); + assert.deepEqual(titles(), []); +}); + +test("a retraction refreshes the history mirror, so a settled entry stops showing as unread", async () => { + const requests = []; + const previousFetch = globalThis.fetch; + globalThis.fetch = async (url, init = {}) => { + requests.push([init.method ?? "GET", String(url)]); + return { ok: true, json: async () => ({ entries: [] }) }; + }; + try { + renderHook(() => useNotifications({ sessionId: null, locale: "en", onOpenSession: () => {} })); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + requests.length = 0; + await act(async () => { + deliverFrame({ type: "notification-dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + assert.deepEqual(requests, [["GET", "/api/notifications/history"]], "the tab re-reads what the server marked read"); + } finally { + globalThis.fetch = previousFetch; + act(() => notificationHistory.clear()); + } +}); + test("a notification the OS showed is listed in history", async () => { const created = []; // Bare `Notification` in the code under test resolves to the global, not window. diff --git a/hooks/useNotifications.ts b/hooks/useNotifications.ts index 7958554e9..cceb71560 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,36 @@ 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. + } + // The server marked the entry read when the dialog settled; an open tab + // would otherwise keep showing it unread until a later refresh. + void notificationHistory.load(); + }; const onOpen = (raw: Event) => { if (raw instanceof CustomEvent && typeof raw.detail === "string" && raw.detail) openRef.current(raw.detail); }; @@ -154,12 +180,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/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 2dcf52118..30af2e193 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -12,15 +12,20 @@ const previousAgentDir = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = isolatedAgentDir; after(() => { closeOutboxStore(); + // publishNotificationDismiss opens the notification store; Windows cannot + // delete its directory while the database is open. + closeNotificationStore(); if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previousAgentDir; fs.rmSync(isolatedAgentDir, { recursive: true, force: true }); }); const { EventStreamConnection, getEventStreamConnection, broadcastBrowserTransport } = await import("./event-stream-hub.ts"); +const hub = await import("./notification-hub.ts"); const route = await import("../app/api/events/route.ts"); const { AgentSessionWrapper } = await import("./rpc-manager.ts"); const { closeOutboxStore } = await import("./message-outbox.ts"); +const { closeNotificationStore } = await import("./notification-store.ts"); const idleSnapshot = () => ({ cursor: { streamId: "test-stream", sequence: 0 } }); const decoder = new TextDecoder(); @@ -195,6 +200,23 @@ test("a notifications subscription keeps its tab reachable until it ends; malfor assert.equal(streams().has("tab-notify-02"), false, "a dropped socket must detach its tabs"); }); +test("a published retraction reaches the tab as a notification-dismiss frame naming its request", async () => { + const { connection, reader } = await connect(); + try { + assert.deepEqual(await connection.subscribe("s1", { kind: "notifications", clientId: "tab-notify-03" }), { ok: true }); + assert.deepEqual(await readFrame(reader), { event: "mux", data: { type: "open", sub: "s1" } }); + // The hub's own publish path, not a hand-built sender: this is the frame a + // real settlement produces. + hub.publishNotificationDismiss("s-done", "req-42"); + assert.deepEqual(await readFrame(reader), { + event: "s1", + data: { type: "notification-dismiss", tag: "s-done:input", sessionId: "s-done", requestId: "req-42" }, + }); + } finally { + await reader.cancel(); + } +}); + test("host-tools subscription delivers cross-session calls and releases its listener", async () => { globalThis.__ompHostToolListeners ??= new Set(); const listeners = globalThis.__ompHostToolListeners; diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 59bae17f1..3c9e6f383 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -397,7 +397,15 @@ function openRunningChannel(handle: SubscriptionHandle): SubscribeResult { // as reachable for toasts and in-page system notifications while this is open. function openNotificationsChannel(clientId: string, handle: SubscriptionHandle): SubscribeResult { handle.open(); - handle.setDetach(attachNotificationClient(clientId, (message) => handle.send({ type: "notification", ...message }))); + handle.setDetach(attachNotificationClient(clientId, (message) => { + // A retraction is its own frame type: the client's notification branch + // accepts only the toast/os kinds, so a wrapped dismiss would be dropped. + if (message.kind === "dismiss") { + handle.send({ type: "notification-dismiss", tag: message.tag, sessionId: message.sessionId, requestId: message.requestId }); + return; + } + handle.send({ type: "notification", ...message }); + })); return SUBSCRIBED; } diff --git a/lib/notification-answer-route.test.mjs b/lib/notification-answer-route.test.mjs new file mode 100644 index 000000000..416aa0f4b --- /dev/null +++ b/lib/notification-answer-route.test.mjs @@ -0,0 +1,143 @@ +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"; + +// 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 route = await import("../app/api/notifications/answer/route.ts"); +const { WebRpcError } = await import("./rpc-manager.ts"); + +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("a moved conversation answers through its old id", async () => { + // registerSession keeps the old ids routable after omp moves the file, so + // one registry entry under both keys is what the route sees. + const { calls, session } = fakeSession(); + globalThis.__ompSessions = new Map([["s1", session], ["s0", session]]); + const response = await post({ sessionId: "s0", requestId: "req-1", response: { value: "yes" } }); + assert.deepEqual(await response.json(), { status: "answered" }); + assert.deepEqual(calls, [["req-1", { value: "yes" }]]); +}); + +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" }); +}); + +test("an answer that cannot be delivered is not reported as answered", async () => { + // The wrapper's send() applies the offline/restarting gate; the route must + // surface it instead of claiming the question was answered. + for (const [error, status, body] of [ + [new WebRpcError("Laptop is offline. The run continues there; it reconnects automatically.", "host_offline", "refused"), 503, { hostOffline: true, delivery: "refused" }], + [new WebRpcError("This session is restarting — retry in a moment.", "session_restarting"), 400, { code: "session_restarting" }], + ]) { + const { session } = fakeSession({ error }); + globalThis.__ompSessions = new Map([["s1", session]]); + const response = await post({ sessionId: "s1", requestId: "req", response: { confirmed: true } }); + assert.equal(response.status, status, error.code); + const payload = await response.json(); + assert.equal(payload.status, undefined, "a failed delivery is never answered"); + for (const [key, value] of Object.entries(body)) assert.equal(payload[key], value, `${error.code} ${key}`); + } +}); diff --git a/lib/notification-client.ts b/lib/notification-client.ts index e48415910..0de69011d 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 + // 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 1fbd8fcf8..e9c3ea5b5 100644 --- a/lib/notification-events.test.mjs +++ b/lib/notification-events.test.mjs @@ -112,6 +112,37 @@ test("untrusted prefs fall back to defaults field by field", () => { }); }); +test("a blocking dialog carries its request id and answerable payload", () => { + const [event] = run([{ + type: "extension_ui_request", + id: "req-1", + method: "confirm", + title: "Allow tool: bash", + message: "Run rm -rf build?", + }]); + assert.equal(event.requestId, "req-1"); + assert.deepEqual(event.dialog, { requestId: "req-1", method: "confirm", title: "Allow tool: bash", message: "Run rm -rf build?" }); +}); + +test("an ask dialog keeps option labels verbatim and drops payloads that cannot be answered", () => { + const questions = [{ id: "q1", question: "Ship it?", options: ["Yes", "No"], multi: true }]; + const [event] = run([{ type: "extension_ui_request", id: "req-2", method: "ask", questions }]); + assert.deepEqual(event.dialog.questions, [{ id: "q1", question: "Ship it?", options: ["Yes", "No"], multi: true, allowCustom: true }]); + + // A label that would have to be clipped cannot be answered: no dialog, but + // the request id still reaches the notification so a retraction can close it. + const long = [{ id: "q1", question: "Ship it?", options: ["x".repeat(200)] }]; + const [clipped] = run([{ type: "extension_ui_request", id: "req-3", method: "ask", questions: long }]); + assert.equal(clipped.dialog, undefined); + assert.equal(clipped.requestId, "req-3"); +}); + +test("open_url has no answerable dialog but keeps its request id", () => { + const [event] = run([{ type: "extension_ui_request", id: "req-4", method: "open_url", url: "https://example.test", instructions: "Open it" }]); + assert.equal(event.requestId, "req-4"); + assert.equal(event.dialog, undefined); +}); + test("rendered notifications open their session and clip long details", () => { const t = (key, vars) => `${key}${vars ? JSON.stringify(vars) : ""}`; const rendered = renderNotification({ type: "error", sessionId: "a b", sessionName: null, detail: "x".repeat(500) }, t); 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 850771a4b..2ef2d6651 100644 --- a/lib/notification-hub.test.mjs +++ b/lib/notification-hub.test.mjs @@ -311,6 +311,79 @@ test("a retry is dropped once the device turned notifications off", async (t) => assert.equal(attempts, 1); }); +test("a settled dialog is retracted on every reachable stream and its history entry becomes read", (t) => { + isolatedStore(t); + store.saveDevice("phone-0001", prefs()); + const received = []; + hub.attachNotificationClient("phone-tab", (message) => received.push(message)); + hub.reportPresence({ clientId: "phone-tab", deviceId: "phone-0001", visible: false, sessionId: null, seq: 1 }); + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1", detail: "Ship it?" }); + assert.deepEqual(received.map((message) => message.kind), ["os"]); + assert.deepEqual(store.listHistory().map((entry) => [entry.id, entry.read]), [["s2:input", false]]); + + hub.publishNotificationDismiss("s2", "req-1"); + assert.deepEqual(received.at(-1), { kind: "dismiss", tag: "s2:input", sessionId: "s2", requestId: "req-1" }); + assert.deepEqual(store.listHistory().map((entry) => [entry.id, entry.read]), [["s2:input", true]]); +}); + +test("a retraction pushes a dismiss to subscribed devices, but never to Apple's endpoint", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload) => { + sent.push(JSON.parse(payload)); + }; + store.saveDevice("phone-0001", prefs(), subscription); + store.saveDevice("iphone-0001", prefs(), { ...subscription, endpoint: "https://web.push.apple.com/xyz" }); + hub.publishNotificationDismiss("s2", "req-1"); + await flush(); + assert.deepEqual(sent, [{ type: "dismiss", tag: "s2:input", sessionId: "s2", requestId: "req-1" }]); +}); + +test("the retraction reads only the entry of its own request, not a newer dialog of the same tag", (t) => { + isolatedStore(t); + store.saveDevice("phone-0001", prefs()); + // Request A's entry is replaced by request B's, which is still pending. + store.recordHistory({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-B", detail: "Or now?" }); + hub.publishNotificationDismiss("s2", "req-A"); + assert.deepEqual(store.listHistory().map((entry) => [entry.event.requestId, entry.read]), [["req-B", false]], "a stale retraction leaves the pending entry unread"); + hub.publishNotificationDismiss("s2", "req-B"); + assert.deepEqual(store.listHistory().map((entry) => [entry.event.requestId, entry.read]), [["req-B", true]]); +}); + +test("a retraction reaches a device that turned notifications off after receiving the question", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload) => { + sent.push(JSON.parse(payload)); + }; + // Each device needs its own endpoint: saving one moves it off any other device. + store.saveDevice("phone-0001", prefs({ enabled: false }), subscription); + store.saveDevice("phone-0002", prefs({ types: { ...DEFAULT_NOTIFICATION_PREFS.types, input: false } }), { ...subscription, endpoint: "https://push.example/def" }); + hub.publishNotificationDismiss("s2", "req-1"); + await flush(); + assert.deepEqual(sent.map((payload) => payload.type), ["dismiss", "dismiss"], "a retraction is not an alert and is not gated by alert prefs"); +}); + +test("a push retry after the dialog settled delivers nothing", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout"] }); + t.mock.method(console, "warn", () => {}); + let attempts = 0; + webpush.sendNotification = async (_subscription, payload) => { + // A retraction push is a separate, single-attempt delivery. + if (JSON.parse(payload).type !== "dismiss") attempts += 1; + throw offline(); + }; + store.saveDevice("phone-0001", prefs(), subscription); + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.equal(attempts, 1); + hub.publishNotificationDismiss("s2", "req-1"); + t.mock.timers.tick(hub.PUSH_RETRY_DELAYS_MS[0]); + await flush(); + assert.equal(attempts, 1, "the sleeping retry woke up after the answer and sent nothing"); +}); + test("the test button gets one attempt and the network failure's cause", async (t) => { isolatedStore(t); t.mock.method(console, "warn", () => {}); diff --git a/lib/notification-hub.ts b/lib/notification-hub.ts index 67e133ce8..3f30ffd0c 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,14 @@ 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 +43,16 @@ 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 its omp + * child went away. The retraction reaches a tab as `type: "notification-dismiss"` + * (lib/event-stream-hub.ts wraps it) and a device as a `type: "dismiss"` push + * (public/sw.js). + */ +export type NotificationMessage = + | { kind: "toast" | "os"; event: NotificationEvent } + | { kind: "dismiss"; tag: string; sessionId: string; requestId: string }; type Send = (message: NotificationMessage) => void; @@ -47,6 +64,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 +73,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() }); + // `bun --hot` keeps this object across a re-evaluation: a state created by + // the previous module instance may predate a field added here. + state.retractions ??= new Map(); + return state; } export function getVapidPublicKey(): string { @@ -152,14 +175,66 @@ 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 }; + } +} + +/** + * 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(`${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; + // `requestId`/`dialog` let the 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 +263,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,6 +315,59 @@ export function publishNotification(event: NotificationEvent): void { } } +/** + * Retract a session's `input` notification: its dialog was answered by any + * client, cancelled, expired, or its omp child went away. Every reachable tab + * gets the retraction on its stream, and 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`; + const state = hub(); + const now = Date.now(); + // Recorded first: a retry of that `input` push may be sleeping right now. + for (const [key, at] of state.retractions) { + if (now - at > PUSH_RETRACTION_TTL_MS) state.retractions.delete(key); + } + state.retractions.set(`${sessionId}:${requestId}`, now); + // Only the entry of this request is read: a newer dialog of the same tag + // replaced it in the history, and that one is still waiting for an answer. + try { + markHistoryRead([tag], requestId); + } catch (error) { + console.warn("[notifications] history read mark failed:", error); + } + // Every reachable tab hears it: one that never showed this notification + // closes nothing, and the frame names the request so a later dialog of the + // same tag stays. A tab whose stream died keeps nothing to clear. + for (const sends of state.streams.values()) { + for (const send of sends) { + try { + send({ kind: "dismiss", tag, sessionId, requestId }); + } catch { + // A closing stream must not break delivery to the others. + } + } + } + let devices: NotificationDevice[] = []; + try { + devices = listDevices(); + } catch (error) { + console.warn("[notifications] store unavailable:", error); + } + for (const device of devices) { + // A retraction is not an alert: a device that turned notifications off + // after receiving the question still has the old one on screen. + if (!device.subscription) continue; + if (isApplePushEndpoint(device.subscription.endpoint)) continue; + // 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. * One attempt, so the button answers at once. */ export async function sendTestPush(deviceId: string): Promise<{ ok: true } | { ok: false; error: string }> { diff --git a/lib/notification-store.ts b/lib/notification-store.ts index 66828425b..fef604d3a 100644 --- a/lib/notification-store.ts +++ b/lib/notification-store.ts @@ -260,11 +260,20 @@ export function recordHistory(event: NotificationEvent, { at = Date.now(), read return { id, event, at, read }; } -export function markHistoryRead(ids: string[]): void { +/** + * Mark entries read. With `requestId`, only an entry whose stored event still + * names that request is marked: a newer dialog of the same tag replaced the + * entry, and that one is still waiting for an answer. + */ +export function markHistoryRead(ids: string[], requestId?: string): void { const database = db(); const mark = database.prepare("UPDATE history SET read = 1 WHERE id = ?"); + const markMatching = database.prepare("UPDATE history SET read = 1 WHERE id = ? AND json_extract(event, '$.requestId') IS ?"); transaction(database, () => { - for (const id of ids) mark.run(id); + for (const id of ids) { + if (requestId === undefined) mark.run(id); + else markMatching.run(id, requestId); + } }); } diff --git a/lib/notification-sw.test.mjs b/lib/notification-sw.test.mjs index 3d0add0db..d0366075e 100644 --- a/lib/notification-sw.test.mjs +++ b/lib/notification-sw.test.mjs @@ -20,6 +20,7 @@ function loadWorker(windows = [], globals = {}) { }); return { shown, + registration: self.registration, message: (event) => listeners.message(event), push: async (payload) => { let done; @@ -44,6 +45,31 @@ test("a shown push is reported to every open tab with its kind, text and session assert.deepEqual(messages, [["a", { type: "omp-notification-shown", notification }], ["b", { type: "omp-notification-shown", notification }]]); }); +test("a dismiss push closes only the notification of its own request and shows nothing", async () => { + const closed = []; + const shown = []; + const worker = loadWorker(); + // The worker reads the shown notifications back by tag. + const notifications = [ + { data: { requestId: "req-1" }, close: () => closed.push("req-1") }, + { data: { requestId: "req-2" }, close: () => closed.push("req-2") }, + ]; + worker.registration.getNotifications = async ({ tag }) => { + shown.push(tag); + return notifications; + }; + await worker.push({ type: "dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + assert.deepEqual(shown, ["s1:input"]); + assert.deepEqual(closed, ["req-1"], "a late retraction must not close the next dialog of the same tag"); + assert.deepEqual(worker.shown, [], "a retraction push displays nothing"); +}); + +test("a dialog push carries its request id so a retraction can match it", async () => { + const worker = loadWorker(); + await worker.push({ type: "input", title: "Deploy", body: "Ship it?", tag: "s1:input", sessionId: "s1", requestId: "req-9" }); + assert.equal(worker.shown[0].options.data.requestId, "req-9"); +}); + test("an unreadable push still shows a notification and reports it as info", async () => { const messages = []; const worker = loadWorker([{ postMessage: (message) => messages.push(structuredClone(message)) }]); diff --git a/lib/pi-types.ts b/lib/pi-types.ts index c0b5e67a5..c55b3b9df 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -224,6 +224,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 c58bac61b..51aab27da 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -677,9 +677,14 @@ async function reachableTab() { 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 messages = []; 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) => { + messages.push(message); + // Retractions carry no event; the notification assertions read the kind. + if (message.kind !== "dismiss") delivered.push([message.event.type, message.event.detail]); + }])]]), }; const restore = () => { globalThis.__ompNotificationHub = previousHub; @@ -690,12 +695,12 @@ async function reachableTab() { closeNotificationStore(); rmSync(dir, { recursive: true, force: true }); }; - return { delivered, restore }; + return { delivered, messages, restore }; } /** A wrapper whose omp frames the test drives, with one reachable tab collecting notifications. */ async function notifyingSession(t) { - const { delivered, restore } = await reachableTab(); + const { delivered, messages, restore } = await reachableTab(); let feed; /** What omp's get_state answers; tests change it to simulate session moves and switches. */ const ompState = { sessionId: "notify-session", sessionFile: "/tmp/notify-session.jsonl", isStreaming: false, isCompacting: false }; @@ -715,7 +720,7 @@ async function notifyingSession(t) { await wrapper.destroyAndWait(); restore(); }); - return { wrapper, feed, delivered, ompState }; + return { wrapper, feed, delivered, messages, ompState }; } test("after a moved session switches to another conversation, a tab left on the old id no longer silences it", async (t) => { @@ -747,6 +752,77 @@ test("omp frames reach the user as notifications: settled run, pending question" assert.deepEqual(delivered, [["completed", undefined], ["input", "Delete the branch?"]]); }); +test("every settlement path retracts the pending question's notification, and only once", async (t) => { + const { wrapper, feed, messages } = await notifyingSession(t); + const dismisses = () => messages.filter((message) => message.kind === "dismiss"); + const ask = (id) => feed({ type: "extension_ui_request", id, method: "confirm", title: "Delete the branch?", message: "" }); + + // Answered from the desktop. + ask("q-answered"); + assert.deepEqual(dismisses(), []); + await wrapper.send({ type: "extension_ui_response", id: "q-answered", confirmed: true }); + assert.deepEqual(dismisses(), [{ kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "q-answered" }]); + + // Cancelled by omp. + ask("q-cancelled"); + feed({ type: "extension_ui_request", method: "cancel", targetId: "q-cancelled" }); + assert.deepEqual(dismisses().at(-1), { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "q-cancelled" }); + + // Expired by its own timeout. + feed({ type: "extension_ui_request", id: "q-expired", method: "input", title: "Value", timeout: 1 }); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.deepEqual(dismisses().at(-1), { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "q-expired" }); + + // Answered from a notification: the same path, so the same retraction. + ask("q-notification"); + assert.equal(await wrapper.answerExtensionUiRequest("q-notification", { confirmed: true }), "answered"); + assert.deepEqual(dismisses().at(-1), { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "q-notification" }); + // A second answer is not a settlement of anything. + assert.equal(await wrapper.answerExtensionUiRequest("q-notification", { confirmed: true }), "alreadySettled"); + assert.equal(dismisses().length, 4); +}); + +test("clearing every pending dialog (restart, destroy) retracts each one", async (t) => { + const { wrapper, feed, messages } = await notifyingSession(t); + feed({ type: "extension_ui_request", id: "q1", method: "input", title: "First" }); + feed({ type: "extension_ui_request", id: "q2", method: "select", title: "Second", options: ["A"] }); + await wrapper.destroyAndWait(); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss").map((message) => message.requestId).sort(), ["q1", "q2"]); +}); + +test("a retraction keeps the session id the notification was published under after omp moves the conversation", async (t) => { + const { wrapper, feed, messages, ompState } = await notifyingSession(t); + feed({ type: "extension_ui_request", id: "q-moved", method: "confirm", title: "Continue?", message: "" }); + // omp moves the conversation to a new file, then the dialog is answered. + 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)); + await wrapper.send({ type: "extension_ui_response", id: "q-moved", confirmed: true }); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [ + { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "q-moved" }, + ]); +}); + +test("a server-owned confirm is settled by the notification answer path, not just forgotten", async (t) => { + const { wrapper, messages } = await notifyingSession(t); + const events = []; + wrapper.onEvent((event) => events.push(event)); + const answer = wrapper.confirmFromServer("Start a session on build-box?"); + const request = events.find((event) => event.type === "extension_ui_request" && event.method === "confirm"); + assert.equal(await wrapper.answerExtensionUiRequest(request.id, { confirmed: true }), "answered"); + assert.equal(await answer, true, "the registered server resolver runs"); + assert.equal(messages.at(-1).requestId, request.id); +}); + +test("an answer the pending dialog does not take is refused before anything settles", async (t) => { + const { wrapper, feed, messages } = await notifyingSession(t); + feed({ type: "extension_ui_request", id: "q-select", method: "select", title: "Which?", options: ["A", "B"] }); + await assert.rejects(wrapper.answerExtensionUiRequest("q-select", { value: "C" }), { code: "invalid_dialog_answer" }); + await assert.rejects(wrapper.answerExtensionUiRequest("q-select", { confirmed: true }), { code: "invalid_dialog_answer" }); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [], "a refused answer leaves the dialog pending"); + assert.equal(await wrapper.answerExtensionUiRequest("q-select", { value: "B" }), "answered"); +}); + test("a crash during a run notifies the user once", async (t) => { const { wrapper, feed, delivered } = await notifyingSession(t); feed({ type: "agent_start" }); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 9436d4df2..d602700d2 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -22,11 +22,12 @@ import { RESUME_PROMPT } from "./hosts/host-resume"; 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 { 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" @@ -399,6 +400,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: omp can move the conversation to a new file before the dialog settles, and the retraction tag must still match. */ + private inputNotificationSessions = new Map(); /** Dialogs omp-web itself raised (confirmFromServer): answered here, never forwarded to omp. */ private serverUiRequests = new Map void>(); private extensionStatuses = new Map(); @@ -1150,6 +1153,11 @@ export class AgentSessionWrapper { const notifications = this.detectNotification(frame, session); if (this.hostOwnedLifecycle && !isNotifier(this.host.id)) return; for (const notification of notifications) { + // Remember the id it is published under: a later move changes + // `_sessionId`, and the retraction must still name the same tag. + if (notification.type === "input" && notification.requestId) { + this.inputNotificationSessions.set(notification.requestId, notification.sessionId); + } publishNotification(this.movedFromIds.length ? { ...notification, aliases: this.movedFromIds } : notification); } } @@ -1431,9 +1439,10 @@ export class AgentSessionWrapper { notifyRunningChange({ refreshSessionList }); } - /** Forget a pending dialog and its expiry timer. */ + /** Forget a pending dialog, its expiry timer and the id its notification was published under. */ private forgetPendingUiRequest(id: string): void { this.pendingUiRequests.delete(id); + this.inputNotificationSessions.delete(id); const timer = this.uiExpiryTimers.get(id); if (timer) { clearTimeout(timer); @@ -1441,18 +1450,74 @@ 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, so no + * other tab or device keeps offering an answer to a question that is gone. + */ + private settlePendingUiRequest(id: string): boolean { + if (!this.pendingUiRequests.has(id)) return false; + // Read before forgetting: the tag is the one the notification went out with. + const publishedSession = this.inputNotificationSessions.get(id); + this.forgetPendingUiRequest(id); + // One server publishes a notification and its retraction: a former + // notifier must not close what the elected one still owns. + if (publishedSession && (!this.hostOwnedLifecycle || isNotifier(this.host.id))) { + publishNotificationDismiss(publishedSession, id); + } + return true; + } + + /** + * Answer a blocking dialog from a notification action. The answer is checked + * against the pending dialog first (a select takes one of its own options, a + * confirm takes a confirmation, an ask takes answers), then it goes through + * the same `extension_ui_response` command the desktop dialog sends: that + * path resolves a server-owned confirm and applies the offline/restarting + * gate, so an answer is never reported when it could not be delivered. + */ + async answerExtensionUiRequest(id: string, response: ExtensionUiResponse): Promise<"answered" | "alreadySettled"> { + const pending = this.pendingUiRequests.get(id); + if (!pending) return "alreadySettled"; + const method = typeof pending.method === "string" ? pending.method : ""; + if (method === "ask") { + // A pending ask accepts only its answers or a cancel; anything else would + // drop it from reconnect replay while omp rejects the payload. + if (!("cancelled" in response) && !("answers" in response && isAskAnswers(response.answers))) { + 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"); + } else if (method === "confirm") { + if (!("confirmed" in response) && !("cancelled" in response)) { + throw new WebRpcError("This dialog takes a confirmation", "invalid_dialog_answer"); + } + } else if (method === "select") { + const options = Array.isArray(pending.options) ? pending.options : []; + if (!("cancelled" in response) && !("value" in response && options.includes(response.value))) { + throw new WebRpcError("The selected option is not offered by this dialog", "invalid_dialog_answer"); + } + } else if (!("cancelled" in response) && !("value" in response)) { + throw new WebRpcError("This dialog takes a text answer", "invalid_dialog_answer"); + } + await this.send({ type: "extension_ui_response", id, ...response }); + return "answered"; + } + private clearPendingUiRequests(): void { this.dropServerUiRequests(); for (const timer of this.uiExpiryTimers.values()) clearTimeout(timer); this.uiExpiryTimers.clear(); - this.pendingUiRequests.clear(); + // The child is going away (restart, destroy, process exit): every dialog it + // waited on is settled, and its notification must not outlive it. + for (const id of [...this.pendingUiRequests.keys()]) this.settlePendingUiRequest(id); } /** Settle every server dialog as declined and close it in attached tabs. */ private dropServerUiRequests(): void { for (const [id, resolve] of this.serverUiRequests) { this.serverUiRequests.delete(id); - this.forgetPendingUiRequest(id); + this.settlePendingUiRequest(id); this.emit({ type: "extension_ui_request", id: `cancel:${id}`, method: "cancel", targetId: id }); resolve(false); } @@ -1476,7 +1541,7 @@ export class AgentSessionWrapper { const method = event.method as string; const id = event.id as string; if (method === "cancel") { - this.forgetPendingUiRequest(event.targetId as string); + this.settlePendingUiRequest(event.targetId as string); return false; } // Only the “Allow tool: ” confirmation is covered. Other extension @@ -1493,7 +1558,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); } @@ -1828,7 +1893,7 @@ 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); + this.settlePendingUiRequest(id); continue; } listener({ ...event, web: { streamId: this.streamId, sequence: ++this.streamSequence } }); @@ -2803,8 +2868,7 @@ 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); + const wasPending = this.settlePendingUiRequest(id); const serverRequest = this.serverUiRequests.get(id); if (serverRequest) { this.serverUiRequests.delete(id); diff --git a/public/sw.js b/public/sw.js index e4a167257..150201786 100644 --- a/public/sw.js +++ b/public/sw.js @@ -15,6 +15,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 dismissTag = typeof data.tag === "string" ? data.tag : ""; + const dismissRequest = 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 (!dismissTag || !dismissRequest || typeof self.registration.getNotifications !== "function") return; + const shown = await self.registration.getNotifications({ tag: dismissTag }); + for (const notification of shown) { + if (notification.data && notification.data.requestId === dismissRequest) 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", @@ -30,7 +51,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 }); diff --git a/server/routes.ts b/server/routes.ts index e7e3ce3b2..a92c5e034 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -33,6 +33,7 @@ import * as modelsConfigCatalog from "@/app/api/models-config/catalog/route"; import * as modelsConfig from "@/app/api/models-config/route"; import * as modelsConfigTest from "@/app/api/models-config/test/route"; import * as models from "@/app/api/models/route"; +import * as notificationsAnswer from "@/app/api/notifications/answer/route"; import * as notificationsDevices from "@/app/api/notifications/devices/route"; import * as notificationsHistory from "@/app/api/notifications/history/route"; import * as notificationsPresence from "@/app/api/notifications/presence/route"; @@ -129,6 +130,7 @@ export const ROUTE_MODULES: Record = { "models-config": modelsConfig, "models-config/test": modelsConfigTest, "models": models, + "notifications/answer": notificationsAnswer, "notifications/devices": notificationsDevices, "notifications/history": notificationsHistory, "notifications/presence": notificationsPresence, From 5f06fb10994312e118dbdb3d887ee8c4b7b9188b Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:28:56 +0100 Subject: [PATCH 2/6] fix(notifications): validate ask answers against the pending questions An ask dialog accepted any shape-valid answers payload and settled the question, so a payload omp's own parseAskDialogResponse rejects (answers:[], an unknown question id, an unknown label, two labels on a single-select question) was forwarded and the ask tool failed with the dialog already gone. The answers are now checked against that dialog's questions in the one funnel every answer passes through: one answer per question in request order, each naming its own question, only labels that question offers, no label twice, and a single-select question takes either one label or free text, never both. customInput is trimmed before it counts, as omp trims it. A rejected payload is a 400 and leaves the question answerable. Also defines the resync/replay behaviour the review asked for: a resync that drops a pending dialog retracts its notification now, but as a temporary settlement, so a host replay of the same request id announces and pushes the question again instead of being suppressed for the retraction TTL. A permanent settlement of the same request is never lifted. Adds the Unreleased entry and documents the answer route, and strengthens the regressions for replay expiry, the server-owned confirm drop path and every blocking method's accepted/refused answer variants. --- CHANGELOG.md | 1 + docs/specs/2026-10-06-notifications-design.md | 43 +++- lib/notification-answer-route.test.mjs | 80 ++++++++ lib/notification-hub.test.mjs | 72 +++++++ lib/notification-hub.ts | 51 ++++- lib/notification-store.test.mjs | 18 ++ lib/rpc-manager.test.mjs | 187 +++++++++++++++++- lib/rpc-manager.ts | 78 ++++++-- 8 files changed, 514 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a747ff97..80ed3c63f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Updates belong to each host.** Settings → Hosts now shows the ompweb daemon and OMP runtime versions, available updates, and update actions for every machine, including This machine. Checks and installations run on that host. An incompatible or unverifiable daemon update stays visible but blocked, with a reason to update the web server first; OMP updates are independent of the link protocol. A daemon update is refused while session processes or subagents run on that host (close them, then start it again), and the host refuses new sessions while it installs. The host update retains a backup and reports progress after reconnect. **System & Updates** is now **System**, containing only the web server's controls; it no longer updates or restarts a host's OMP sessions globally. - **Messages wait safely until omp has them.** In an existing chat, the composer clears once IndexedDB has stored the message, and a dimmed bubble names the delivery leg: **Sending**, **Waiting for **, **Delivering**, or **Not sent** with the reason. Browser-held messages survive reloads and closed tabs; server-held messages survive web-server restarts and host outages, and appear on every device viewing the chat. Chromium's Background Sync can deliver after the last tab closes; other browsers retry when an ompweb page reopens. Duplicate submissions share one message id. If a lost host reply leaves delivery uncertain, the message is marked **Not sent** and never retried automatically. A prompt that omp stops (Stop, or a failure) before it reaches the transcript is marked **Not sent** at once, so the messages behind it go on without waiting. Held messages offer **Delete** until dispatched. Follow-ups and steers become omp's own queue chips when accepted. New chats keep their existing first-message path; a browser unable to store the message keeps the composer draft instead. +- **Answer a waiting question from the notification itself.** A notification for a blocking dialog (confirm, select, input, editor, or the ask tool's question panel) now carries the dialog, so a phone or a native client can answer it without opening the session: `POST /api/notifications/answer` takes the session id, the dialog's request id and one response (`confirmed`, `value`, `cancelled`, or `answers` for an ask). The answer goes through the same command the desktop dialog sends, so a server-owned confirmation resolves, an offline host or a restarting session is reported instead of silently dropping it, and no omp process is started for a session that is not running. An answer the pending dialog cannot take is refused with 400 before anything settles: a select accepts only one of its own labels, and an ask's answers are checked against that dialog's questions the way omp checks them (one answer per question in order, each naming its own question, only offered labels, no label twice, and a single-select question takes either one label or free text, never both), so a payload omp would reject never consumes the question. When the dialog settles anywhere, every other tab and device is told to close its notification of exactly that request, and a push retry that wakes up afterwards delivers nothing. ### Fixes & Improvements diff --git a/docs/specs/2026-10-06-notifications-design.md b/docs/specs/2026-10-06-notifications-design.md index 583dbc57f..99369ee9c 100644 --- a/docs/specs/2026-10-06-notifications-design.md +++ b/docs/specs/2026-10-06-notifications-design.md @@ -157,14 +157,55 @@ push: iOS Safari revokes push permission for pushes that show nothing. | Route | Method | Purpose | |---|---|---| -| `/api/agent/running/events?clientId=` | GET | existing SSE stream, now also `{type: "notification", kind, event}` | +| `/api/agent/running/events?clientId=` | GET | existing SSE stream, now also `{type: "notification", kind, event}` and `{type: "notification-dismiss", tag, sessionId, requestId}` | | `/api/notifications/presence` | POST | presence report | | `/api/notifications/devices?deviceId=` | GET | VAPID public key, whether this device has a subscription | | `/api/notifications/devices` | PUT | `{deviceId, prefs, subscription?}`; an omitted subscription keeps the stored one | | `/api/notifications/test` | POST | `{deviceId}`: a test push; 502 with the push service's answer when it fails | +| `/api/notifications/answer` | POST | `{sessionId, requestId, response}`: answer a pending blocking dialog from a notification | All routes sit behind the existing password gate and origin check. +### Answering from a notification + +A blocking dialog (`confirm`, `select`, `input`, `editor`, `ask`) is carried in +the `input` notification's `dialog` field, in the SSE frame, the history entry +and the push body, so a client can offer its answer without an open chat tab. +`POST /api/notifications/answer` takes `{sessionId, requestId, response}` with +exactly one response variant: `{confirmed}`, `{value}`, `{cancelled: true}`, or +`{answers}` for an `ask`. The body is capped at 64 KiB and read with +`parseJsonWithinLimit`. + +- The route looks the session up in the live registry (also through the aliases + omp's session moves left) and never spawns omp: an unknown or exited session + answers `200 {status: "sessionGone"}`, and a request id that is not pending + answers `200 {status: "alreadySettled"}`. Neither is an error. +- The answer is checked against the pending dialog first, so a payload the + dialog cannot take is a 400 and leaves the question answerable: a `select` + takes one of its own labels, a `confirm` a confirmation, an `input`/`editor` + a value, and an `ask` its answers. An `ask` payload is validated with omp's + own rules (`parseAskDialogResponse` in `rpc-mode.ts`): one answer per + question in request order, each answer naming its own question id, only + labels that question offers, no label twice, and a single-select question + takes either one label or free text — never both. `customInput` is trimmed + before it counts, as omp trims it. A cancel is always accepted. +- An accepted answer goes through the same `extension_ui_response` command the + desktop dialog sends, so it resolves a server-owned confirmation and applies + the offline/restarting gate: a host that is offline answers 503 + `{hostOffline: true}` and a restarting session 400 `session_restarting`, + never `answered`. The dialog is settled only after the answer was admitted. +- Settling a dialog retracts its notification everywhere: every reachable tab + gets `{type: "notification-dismiss", tag, sessionId, requestId}`, subscribed + devices get a `dismiss` push (never to Apple's endpoint, which revokes the + permission for a push that shows nothing), and the history entry of exactly + that request becomes read. A newer dialog of the same tag keeps its own + unread entry. A push retry that wakes after the settlement delivers nothing. +- A resync that dropped a dialog (a linked host discarding buffered output) + retracts it too, but as a *forgotten* settlement: the retraction is + temporary, so if the host replays the same request id the question is + announced and pushed again instead of being suppressed. A permanent + settlement of the same request is never lifted by that. + ## Settings: Notifications tab A `SettingsTabs` category `notifications` (icon `Bell`). Contents: diff --git a/lib/notification-answer-route.test.mjs b/lib/notification-answer-route.test.mjs index 416aa0f4b..5cca285cd 100644 --- a/lib/notification-answer-route.test.mjs +++ b/lib/notification-answer-route.test.mjs @@ -9,10 +9,14 @@ import test, { after } from "node:test"; const agentDir = mkdtempSync(join(tmpdir(), "omp-web-answer-route-")); const previousAgentDir = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = agentDir; +const { closeNotificationStore } = await import("./notification-store.ts"); after(() => { globalThis.__ompSessions = undefined; if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + // The live wrapper publishes notifications, which opens the store in this dir; + // Windows cannot delete a directory while that database is open. + closeNotificationStore(); rmSync(agentDir, { recursive: true, force: true }); }); @@ -141,3 +145,79 @@ test("an answer that cannot be delivered is not reported as answered", async () for (const [key, value] of Object.entries(body)) assert.equal(payload[key], value, `${error.code} ${key}`); } }); + +// The real wrapper and the real route: this is the boundary the ask +// validation has to hold at, not a fake session that only echoes. +const { AgentSessionWrapper } = await import("./rpc-manager.ts"); +const { localHost } = await import("./hosts/local-host.ts"); + +/** A live wrapper whose omp frames the test drives; `sent` collects what reached the child. */ +function liveAskSession(t) { + // Earlier tests left fake sessions in the registry; a running-change broadcast + // walks it, and those fakes are not wrappers. + globalThis.__ompSessions = new Map(); + let feed; + const sent = []; + const wrapper = new AgentSessionWrapper({ + isAlive: true, + waitReady: async () => ({ type: "ready", protocolVersion: 2 }), + negotiateProtocol: async () => {}, + onFrame(handler) { feed = handler; return () => {}; }, + sendCommand: async (command) => command.type === "get_state" + ? { sessionId: "ask-live", sessionFile: "/tmp/ask-live.jsonl", isStreaming: false, isCompacting: false } + : {}, + sendFrame(frame) { sent.push(frame); }, + dispose: async () => {}, + }, process.cwd(), null, false, "", undefined, localHost); + wrapper.start(); + t.after(() => wrapper.destroyAndWait()); + return { wrapper, sent, emit: (frame) => feed(frame) }; +} + +test("the real wrapper refuses ask answers omp would reject, and keeps the question answerable", async (t) => { + const { wrapper, sent, emit } = liveAskSession(t); + await wrapper.waitUntilReady(); + globalThis.__ompSessions = new Map([["ask-live", wrapper]]); + const ask = () => emit({ + type: "extension_ui_request", id: "ask-live-1", method: "ask", + questions: [ + { id: "q1", question: "Pick one", options: [{ label: "A" }, { label: "B" }] }, + { id: "q2", question: "Pick many", multi: true, options: [{ label: "X" }, { label: "Y" }] }, + ], + }); + ask(); + const rejected = [ + [[], "answers:[] for a nonempty ask"], + [[{ id: "q1", selectedOptions: ["A"] }], "one answer short"], + [[{ id: "q1", selectedOptions: ["A"] }, { id: "q2", selectedOptions: [] }, { id: "q2", selectedOptions: [] }], "one answer too many"], + [[{ id: "unknown", selectedOptions: ["A"] }, { id: "q2", selectedOptions: [] }], "unknown question id"], + [[{ id: "q1", selectedOptions: ["nope"] }, { id: "q2", selectedOptions: [] }], "unknown option label"], + [[{ id: "q1", selectedOptions: ["A", "B"] }, { id: "q2", selectedOptions: [] }], "two labels on a single-select question"], + ]; + for (const [answers, why] of rejected) { + const response = await post({ sessionId: "ask-live", requestId: "ask-live-1", response: { answers } }); + assert.equal(response.status, 400, why); + assert.equal((await response.json()).code, "invalid_ask_answers", why); + assert.deepEqual(sent, [], `${why}: nothing reaches omp`); + // Still answerable: the next request for it is not alreadySettled. + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.id, "ask-live-1", `${why}: the dialog stays pending for reconnects`); + } + + // The legitimate answers the same dialog accepts. + for (const answers of [ + [{ id: "q1", selectedOptions: ["A"] }, { id: "q2", selectedOptions: ["X", "Y"] }], + [{ id: "q1", selectedOptions: [], customInput: "typed" }, { id: "q2", selectedOptions: [] }], + ]) { + ask(); + const response = await post({ sessionId: "ask-live", requestId: "ask-live-1", response: { answers } }); + assert.deepEqual(await response.json(), { status: "answered" }, JSON.stringify(answers)); + assert.deepEqual(sent.at(-1), { type: "extension_ui_response", id: "ask-live-1", answers }); + } + + // A cancel is always accepted, and a second answer is already settled. + ask(); + assert.deepEqual(await (await post({ sessionId: "ask-live", requestId: "ask-live-1", response: { cancelled: true } })).json(), { status: "answered" }); + assert.deepEqual(await (await post({ sessionId: "ask-live", requestId: "ask-live-1", response: { cancelled: true } })).json(), { status: "alreadySettled" }); +}); diff --git a/lib/notification-hub.test.mjs b/lib/notification-hub.test.mjs index 2ef2d6651..66e8b4b33 100644 --- a/lib/notification-hub.test.mjs +++ b/lib/notification-hub.test.mjs @@ -350,6 +350,78 @@ test("the retraction reads only the entry of its own request, not a newer dialog assert.deepEqual(store.listHistory().map((entry) => [entry.event.requestId, entry.read]), [["req-B", true]]); }); +test("a forgotten dialog is retracted now, and a replay of the same request is announced and pushed again", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout"] }); + t.mock.method(console, "warn", () => {}); + const pushes = []; + webpush.sendNotification = async (_subscription, payload) => { + if (JSON.parse(payload).type !== "dismiss") pushes.push(JSON.parse(payload).requestId); + throw offline(); + }; + // One device takes pushes, another has only a reachable tab. + store.saveDevice("phone-0001", prefs(), subscription); + store.saveDevice("desk-0001", prefs()); + const frames = []; + hub.attachNotificationClient("tab-0001", (message) => frames.push(message)); + hub.reportPresence({ clientId: "tab-0001", deviceId: "desk-0001", visible: false, sessionId: null, seq: 1 }); + + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.deepEqual(pushes, ["req-1"]); + assert.equal(frames.at(-1).kind, "os", "the tab shows the question"); + + // A resync dropped the dialog: it is retracted now, so no tab keeps offering it. + hub.publishNotificationForgotten("s2", "req-1"); + assert.deepEqual(frames.at(-1), { kind: "dismiss", tag: "s2:input", sessionId: "s2", requestId: "req-1" }); + + // The host replays the same request id: the question is pending again, so its + // notification goes out and its push is attempted, not suppressed by the + // retraction the resync just recorded. + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.equal(frames.at(-1).kind, "os", "the replayed question is delivered again"); + assert.deepEqual(pushes, ["req-1", "req-1"], "the push of the replayed question is not suppressed"); +}); + +test("a forgotten dialog stays retracted while no replay restores it", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout"] }); + t.mock.method(console, "warn", () => {}); + let attempts = 0; + webpush.sendNotification = async (_subscription, payload) => { + if (JSON.parse(payload).type !== "dismiss") attempts += 1; + throw offline(); + }; + store.saveDevice("phone-0001", prefs(), subscription); + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.equal(attempts, 1); + hub.publishNotificationForgotten("s2", "req-1"); + t.mock.timers.tick(hub.PUSH_RETRY_DELAYS_MS[0]); + await flush(); + assert.equal(attempts, 1, "the sleeping retry woke up after the resync and sent nothing"); +}); + +test("a forgotten retraction never lifts a permanent settlement of the same request", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout"] }); + t.mock.method(console, "warn", () => {}); + let attempts = 0; + webpush.sendNotification = async (_subscription, payload) => { + if (JSON.parse(payload).type !== "dismiss") attempts += 1; + throw offline(); + }; + store.saveDevice("phone-0001", prefs(), subscription); + // Answered, then a resync forgets a dialog of the same session. + hub.publishNotificationDismiss("s2", "req-1"); + hub.publishNotificationForgotten("s2", "req-1"); + // A replay of the answered request must not reopen its notification. + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.equal(attempts, 0, "an answered dialog is never pushed again"); +}); + test("a retraction reaches a device that turned notifications off after receiving the question", async (t) => { isolatedStore(t); const sent = []; diff --git a/lib/notification-hub.ts b/lib/notification-hub.ts index 3f30ffd0c..8c84df641 100644 --- a/lib/notification-hub.ts +++ b/lib/notification-hub.ts @@ -66,6 +66,13 @@ interface HubState { streams: Map>; /** `:` → when it was retracted. A push retry of a settled dialog must deliver nothing (see `publishNotificationDismiss`). */ retractions: Map; + /** + * The same, for a settlement a replay may undo: a resync forgets a dialog + * whose replayed frame can restore the very same request id. The retraction + * still closes what is on screen and stops a sleeping retry, and publishing + * that request id again lifts it (see `publishNotification`). + */ + temporaryRetractions: Map; } declare global { @@ -73,10 +80,11 @@ declare global { } function hub(): HubState { - const state = (globalThis.__ompNotificationHub ??= { presence: new Map(), streams: new Map(), retractions: new Map() }); + const state = (globalThis.__ompNotificationHub ??= { presence: new Map(), streams: new Map(), retractions: new Map(), temporaryRetractions: new Map() }); // `bun --hot` keeps this object across a re-evaluation: a state created by // the previous module instance may predate a field added here. state.retractions ??= new Map(); + state.temporaryRetractions ??= new Map(); return state; } @@ -210,9 +218,13 @@ async function sendPushPayload( * 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. + * A temporary retraction (a resync that forgot the dialog) counts the same way + * until the request is published again. */ function isRetracted(sessionId: string, requestId: string, now: number): boolean { - const at = hub().retractions.get(`${sessionId}:${requestId}`); + const state = hub(); + const key = `${sessionId}:${requestId}`; + const at = state.retractions.get(key) ?? state.temporaryRetractions.get(key); return at !== undefined && now - at <= PUSH_RETRACTION_TTL_MS; } @@ -282,6 +294,10 @@ export function isApplePushEndpoint(endpoint: string): boolean { /** 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(); + // A replayed dialog (resync after a lost link) restores a request a resync + // had temporarily retracted: it is pending again, so its notification and + // its pushes must go out as for any other question. + if (event.type === "input" && event.requestId) state.temporaryRetractions.delete(`${event.sessionId}:${event.requestId}`); let devices: NotificationDevice[] = []; try { devices = listDevices(); @@ -325,6 +341,24 @@ export function publishNotification(event: NotificationEvent): void { * Never throws: callers run on the RPC frame path. */ export function publishNotificationDismiss(sessionId: string, requestId: string): void { + retract(sessionId, requestId, "permanent"); +} + +/** + * Retract a dialog this server only *forgot*: a resync dropped the pending + * request, and the replayed frames may restore the very same request id. + * Everything a retraction does happens (open tabs close it, a sleeping push + * retry stops, the history entry becomes read), but the record is temporary: + * publishing that request id again lifts it, so a replayed question is + * announced and pushed like a new one instead of being suppressed for the + * retraction TTL. A dialog that is really gone is never replayed, and its + * notification stays closed. + */ +export function publishNotificationForgotten(sessionId: string, requestId: string): void { + retract(sessionId, requestId, "temporary"); +} + +function retract(sessionId: string, requestId: string, kind: "permanent" | "temporary"): void { const tag = `${sessionId}:input`; const state = hub(); const now = Date.now(); @@ -332,7 +366,18 @@ export function publishNotificationDismiss(sessionId: string, requestId: string) for (const [key, at] of state.retractions) { if (now - at > PUSH_RETRACTION_TTL_MS) state.retractions.delete(key); } - state.retractions.set(`${sessionId}:${requestId}`, now); + for (const [key, at] of state.temporaryRetractions) { + if (now - at > PUSH_RETRACTION_TTL_MS) state.temporaryRetractions.delete(key); + } + const key = `${sessionId}:${requestId}`; + if (kind === "permanent") { + state.temporaryRetractions.delete(key); + state.retractions.set(key, now); + } else if (!state.retractions.has(key)) { + // A permanent settlement of the same request wins: a replay of an answered + // dialog must not reopen its notification. + state.temporaryRetractions.set(key, now); + } // Only the entry of this request is read: a newer dialog of the same tag // replaced it in the history, and that one is still waiting for an answer. try { diff --git a/lib/notification-store.test.mjs b/lib/notification-store.test.mjs index 71d43819d..d33b26130 100644 --- a/lib/notification-store.test.mjs +++ b/lib/notification-store.test.mjs @@ -202,6 +202,24 @@ test("mark read by ids, remove one, clear", (t) => { assert.deepEqual(store.listHistory(), []); }); +test("a request-scoped read marks only that request's entry, never a newer dialog or a legacy one", (t) => { + isolated(t); + // Request B replaced A's entry under the same tag. + store.recordHistory({ ...event("s2"), type: "input", requestId: "req-B" }); + store.markHistoryRead(["s2:input"], "req-A"); + assert.deepEqual(store.listHistory().map((e) => [e.event.requestId, e.read]), [["req-B", false]], "a stale retraction leaves the pending entry unread"); + store.markHistoryRead(["s2:input"], "req-B"); + assert.deepEqual(store.listHistory().map((e) => [e.event.requestId, e.read]), [["req-B", true]]); + // An entry recorded before request ids existed has no requestId at all: + // SQLite's `IS` compares NULL to a string as false, so it stays unread. + store.recordHistory({ ...event("s3"), type: "input" }); + store.markHistoryRead(["s3:input"], "req-anything"); + assert.deepEqual(store.listHistory().filter((e) => e.event.sessionId === "s3").map((e) => [e.event.requestId, e.read]), [[undefined, false]]); + // Without a request id the tag alone still marks it, as the client's own PATCH does. + store.markHistoryRead(["s3:input"]); + assert.deepEqual(store.listHistory().filter((e) => e.event.sessionId === "s3").map((e) => e.read), [true]); +}); + function writeLegacy(dir, content) { mkdirSync(join(dir, "omp-web"), { recursive: true }); const file = join(dir, "omp-web", "notifications.json"); diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 51aab27da..28ef6c571 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1253,6 +1253,73 @@ test("expired dialogs are not replayed by a later stream subscription", async (t assert.deepEqual(received, []); }); +test("an expired dialog is retracted once, is not answerable, and a later one of the same tag still is", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + const { messages, restore } = await reachableTab(); + let feed; + const ompState = { sessionId: "expiry-session", sessionFile: "/tmp/expiry-session.jsonl", isStreaming: false, isCompacting: false }; + const fakeProc = { + isAlive: true, + waitReady: async () => ({ type: "ready", protocolVersion: 2 }), + negotiateProtocol: async () => {}, + onFrame: (handler) => { feed = handler; return () => {}; }, + sendCommand: async (command) => command.type === "get_state" ? { ...ompState } : {}, + sendFrame: () => {}, + dispose: async () => {}, + }; + const wrapper = new SnapshotWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); + wrapper.start(); + await wrapper.waitUntilReady(); + t.after(async () => { + await wrapper.destroyAndWait(); + restore(); + }); + const dismisses = () => messages.filter((message) => message.kind === "dismiss"); + + feed({ type: "extension_ui_request", id: "q-old", method: "confirm", title: "Deploy?", message: "", timeout: 1_000 }); + t.mock.timers.tick(1_001); + assert.deepEqual(dismisses(), [{ kind: "dismiss", tag: "expiry-session:input", sessionId: "expiry-session", requestId: "q-old" }]); + // An expired request id is gone: answering it is not a settlement of anything. + assert.equal(await wrapper.answerExtensionUiRequest("q-old", { confirmed: true }), "alreadySettled"); + assert.equal(dismisses().length, 1, "an answer after expiry retracts nothing twice"); + + // The next dialog of the same tag is a new question with its own lifecycle. + feed({ type: "extension_ui_request", id: "q-new", method: "confirm", title: "Deploy?", message: "" }); + assert.equal(await wrapper.answerExtensionUiRequest("q-new", { confirmed: true }), "answered"); + assert.deepEqual(dismisses().at(-1), { kind: "dismiss", tag: "expiry-session:input", sessionId: "expiry-session", requestId: "q-new" }); +}); + +for (const [method, frame, accepted, refused] of [ + ["confirm", { title: "Continue?", message: "" }, { confirmed: false }, { value: "yes" }], + ["select", { title: "Which?", options: ["A", "B"] }, { value: "A" }, { confirmed: true }], + ["input", { title: "Value" }, { value: "text" }, { confirmed: true }], + ["editor", { title: "Edit" }, { value: "text" }, { confirmed: true }], + ["ask", { questions: [{ id: "q", question: "Pick", options: [{ label: "A" }] }] }, { answers: [{ id: "q", selectedOptions: ["A"] }] }, { value: "A" }], +]) { + test(`a ${method} dialog refuses the answer variants it does not take, and keeps the dialog pending`, async (t) => { + const { wrapper, emit, sentFrames } = snapshotSession(t); + emit({ type: "extension_ui_request", id: "d", method, ...frame }); + for (const response of [refused, { answers: [{ id: "q", selectedOptions: ["A"] }] }, { confirmed: true }]) { + // Only the variants that really do not belong to this method. + if (method === "confirm" && "confirmed" in response) continue; + if (method === "select" && "value" in response) continue; + if ((method === "input" || method === "editor") && "value" in response) continue; + if (method === "ask" && "answers" in response) continue; + await assert.rejects( + wrapper.answerExtensionUiRequest("d", response), + { name: "WebRpcError" }, + `${method} must refuse ${JSON.stringify(response)}`, + ); + } + assert.deepEqual(sentFrames, [], `${method}: a refused answer never reaches omp`); + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.id, "d", `${method}: a refused answer leaves the dialog pending`); + assert.equal(await wrapper.answerExtensionUiRequest("d", accepted), "answered"); + assert.equal(sentFrames.length, 1, `${method}: the accepted answer is forwarded once`); + }); +} + test("native web metadata cannot forge either wire or cached tool snapshot sequencing", async (t) => { const { wrapper, emit } = snapshotSession(t); const events = []; @@ -1373,7 +1440,7 @@ test("ask dialogs stay pending until a well-formed answers payload is forwarded" wrapper.onEvent((event) => replay.push(event)); assert.equal(replay[0]?.method, "ask", "a rejected answer leaves the dialog pending for reconnects"); - const answers = [{ id: "q", selectedOptions: ["A"], customInput: "more" }]; + const answers = [{ id: "q", selectedOptions: ["A"] }]; await wrapper.send({ type: "extension_ui_response", id: "ask", answers }); assert.deepEqual(sentFrames, [{ type: "extension_ui_response", id: "ask", answers }]); const afterAnswer = []; @@ -1385,6 +1452,72 @@ test("ask dialogs stay pending until a well-formed answers payload is forwarded" assert.deepEqual(sentFrames.at(-1), { type: "extension_ui_response", id: "ask2", cancelled: true }); }); +test("ask answers are validated against the pending questions before the dialog is consumed", async (t) => { + const { wrapper, emit, sentFrames } = snapshotSession(t); + emit({ + type: "extension_ui_request", id: "ask", method: "ask", + questions: [ + { id: "q1", question: "Pick one", options: [{ label: "A" }, { label: "B" }] }, + { id: "q2", question: "Pick many", multi: true, options: [{ label: "X" }, { label: "Y" }] }, + ], + }); + // Each of these is a payload omp's parseAskDialogResponse throws on: the + // dialog must stay pending and nothing may reach the child. + const rejected = [ + [[], "no answers for two questions"], + [[{ id: "q1", selectedOptions: ["A"] }], "one answer short"], + [[{ id: "q1", selectedOptions: ["A"] }, { id: "q2", selectedOptions: [] }, { id: "q2", selectedOptions: [] }], "one answer too many"], + [[{ id: "nope", selectedOptions: ["A"] }, { id: "q2", selectedOptions: [] }], "unknown question id"], + [[{ id: "q2", selectedOptions: ["A"] }, { id: "q1", selectedOptions: [] }], "answers out of question order"], + [[{ id: "q1", selectedOptions: ["C"] }, { id: "q2", selectedOptions: [] }], "unknown option label"], + [[{ id: "q1", selectedOptions: ["A", "B"] }, { id: "q2", selectedOptions: [] }], "two labels on a single-select question"], + [[{ id: "q1", selectedOptions: ["A"] }, { id: "q2", selectedOptions: ["X", "X"] }], "the same label twice"], + [[{ id: "q1", selectedOptions: ["A"], customInput: "free" }, { id: "q2", selectedOptions: [] }], "a single-select answer with both a label and free text"], + ]; + for (const [answers, why] of rejected) { + await assert.rejects( + wrapper.send({ type: "extension_ui_response", id: "ask", answers }), + { name: "WebRpcError", code: "invalid_ask_answers" }, + why, + ); + await assert.rejects( + wrapper.answerExtensionUiRequest("ask", { answers }), + { name: "WebRpcError", code: "invalid_ask_answers" }, + `notification path: ${why}`, + ); + } + assert.deepEqual(sentFrames, [], "no rejected answer reaches omp"); + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.method, "ask", "every rejection leaves the dialog pending for reconnects"); + + // Valid shapes omp accepts: a label, free text instead of a label, a blank + // customInput (omp trims it away), several labels on a multi-select, and a + // multi-select with no labels at all. + for (const answers of [ + [{ id: "q1", selectedOptions: ["B"] }, { id: "q2", selectedOptions: ["X", "Y"] }], + [{ id: "q1", selectedOptions: [], customInput: "typed instead" }, { id: "q2", selectedOptions: [] }], + [{ id: "q1", selectedOptions: ["A"], customInput: " " }, { id: "q2", selectedOptions: ["Y"], customInput: "and this" }], + ]) { + await wrapper.answerExtensionUiRequest("ask", { answers }); + assert.deepEqual(sentFrames.at(-1), { type: "extension_ui_response", id: "ask", answers }); + const afterAnswer = []; + wrapper.onEvent((event) => afterAnswer.push(event)); + assert.deepEqual(afterAnswer, [], "an accepted answer settles the dialog"); + emit({ + type: "extension_ui_request", id: "ask", method: "ask", + questions: [ + { id: "q1", question: "Pick one", options: [{ label: "A" }, { label: "B" }] }, + { id: "q2", question: "Pick many", multi: true, options: [{ label: "X" }, { label: "Y" }] }, + ], + }); + } + + // A cancel is still accepted whatever the questions are. + await wrapper.answerExtensionUiRequest("ask", { cancelled: true }); + assert.deepEqual(sentFrames.at(-1), { type: "extension_ui_response", id: "ask", cancelled: true }); +}); + test("answering a dialog in one tab dismisses it in every other attached tab", async (t) => { const { wrapper, emit } = snapshotSession(t); const other = []; @@ -3558,6 +3691,58 @@ test("a resync from the host reconciles the session", async (t) => { assert.equal(session.isRunning(), false); }); +test("a resync forgets a pending dialog without a tombstone that would suppress its replay", async (t) => { + const { messages, restore } = await reachableTab(); + let feed; + let resync; + const ompState = { sessionId: "resync-session", sessionFile: "/tmp/resync-session.jsonl", isStreaming: false, isCompacting: false }; + const fakeProc = { + isAlive: true, + // A host-owned child: the daemon owns the lifecycle and replays its open + // requests after a resync, which is the only path that forgets dialogs. + transport: { hostOwnedLifecycle: true, onResync: (listener) => { resync = listener; } }, + waitReady: async () => ({ type: "ready", protocolVersion: 2 }), + negotiateProtocol: async () => {}, + onFrame: (handler) => { feed = handler; return () => {}; }, + sendCommand: async (command) => command.type === "get_state" ? { ...ompState } : {}, + sendFrame: () => {}, + dispose: async () => {}, + }; + const wrapper = new SnapshotWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); + wrapper.start(); + await wrapper.waitUntilReady(); + t.after(async () => { + await wrapper.destroyAndWait(); + restore(); + }); + const dismisses = () => messages.filter((message) => message.kind === "dismiss"); + const shown = () => messages.filter((message) => message.kind !== "dismiss"); + const dialog = { type: "extension_ui_request", id: "q-replayed", method: "confirm", title: "Deploy?", message: "" }; + + feed(dialog); + assert.equal(shown().length, 1, "the question is announced"); + assert.deepEqual(dismisses(), []); + + // The link dropped buffered output: the dialog is forgotten, and its + // notification is retracted so no tab keeps offering an answer. + const cancelled = []; + wrapper.onEvent((event) => cancelled.push(event)); + // Attaching replays the pending dialog; only what the resync emits matters here. + cancelled.length = 0; + resync(); + assert.deepEqual(dismisses(), [{ kind: "dismiss", tag: "resync-session:input", sessionId: "resync-session", requestId: "q-replayed" }]); + assert.deepEqual(cancelled.map(({ type, method, targetId }) => ({ type, method, targetId })), [ + { type: "extension_ui_request", method: "cancel", targetId: "q-replayed" }, + ]); + + // The host replays the same request id: it is pending again, so the question + // is announced again. A permanent tombstone would have suppressed this. + feed(dialog); + assert.equal(shown().length, 2, "a replayed question is announced again"); + assert.equal(await wrapper.answerExtensionUiRequest("q-replayed", { confirmed: true }), "answered"); + assert.equal(dismisses().length, 2, "the replayed dialog is answerable and settles normally"); +}); + test("restartAllRpcSessions restarts only this machine's sessions", async (t) => { const { restartAllRpcSessions, startRpcSession } = await import("./rpc-manager.ts"); const localTransport = scriptedTransport("s-restart-local"); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index d602700d2..6fdd2c3f8 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -22,7 +22,7 @@ import { RESUME_PROMPT } from "./hosts/host-resume"; import { samePath } from "./paths"; import { isRecord } from "./type-guards"; import { BLOCKING_UI_METHODS, createNotificationDetector } from "./notification-events"; -import { publishNotification, publishNotificationDismiss } from "./notification-hub"; +import { publishNotification, publishNotificationDismiss, publishNotificationForgotten } from "./notification-hub"; import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "./skill-diagnostics"; import { eventWithToolResultImageUrls } from "./media-cache"; import type { @@ -129,7 +129,7 @@ export class WebRpcError extends Error { } } -/** Shape check for an ask-dialog `answers` payload; omp validates the content. */ +/** Shape check for an ask-dialog `answers` payload. */ export function isAskAnswers(value: unknown): boolean { return Array.isArray(value) && value.every((answer: unknown) => isRecord(answer) @@ -139,6 +139,45 @@ export function isAskAnswers(value: unknown): boolean { && (answer.customInput === undefined || typeof answer.customInput === "string")); } +/** + * Why `answers` cannot answer `questions`, or null when they can. Mirrors omp's + * `parseAskDialogResponse` (rpc-mode.ts), which throws on any mismatch: one + * answer per question in request order, each naming its own question, only + * labels that question offers, no label twice, and a single-select question + * takes either one option or free text, never both. omp trims `customInput`, so + * blank free text counts as absent. Checking here keeps a rejected payload from + * consuming the pending dialog, which would leave the ask tool failed. + */ +export function askAnswersProblem(answers: unknown, questions: unknown): string | null { + if (!Array.isArray(questions)) return "the pending ask carries no questions"; + if (!Array.isArray(answers)) return "answers must be an array"; + if (answers.length !== questions.length) return `answers must carry ${questions.length} entries in question order`; + for (const [index, raw] of questions.entries()) { + const question = isRecord(raw) ? raw : {}; + const id = typeof question.id === "string" ? question.id : ""; + const answer = answers[index]; + if (!isRecord(answer)) return `answer ${index} must be an object`; + if (answer.id !== id) return `answer ${index} must have id ${JSON.stringify(id)}`; + const options = Array.isArray(question.options) ? question.options : []; + const labels = options.flatMap((option) => (isRecord(option) && typeof option.label === "string" ? [option.label] : [])); + const selected = answer.selectedOptions; + if (!Array.isArray(selected)) return `answer ${JSON.stringify(id)} must carry a selectedOptions array`; + const chosen: string[] = []; + for (const label of selected) { + if (typeof label !== "string" || !labels.includes(label)) return `answer ${JSON.stringify(id)} selected unknown option ${JSON.stringify(label)}`; + if (chosen.includes(label)) return `answer ${JSON.stringify(id)} selected ${JSON.stringify(label)} twice`; + chosen.push(label); + } + const custom = answer.customInput; + if (custom !== undefined && typeof custom !== "string") return `answer ${JSON.stringify(id)} customInput must be a string`; + const text = typeof custom === "string" ? custom.trim() : ""; + if (question.multi !== true && (chosen.length > 1 || (chosen.length > 0 && text !== ""))) { + return `answer ${JSON.stringify(id)} is single-select but carries more than one answer`; + } + } + return null; +} + // Commands forwarded to omp verbatim (request shape already matches rpc-types). const PASSTHROUGH_COMMANDS = new Set([ "abort", @@ -752,9 +791,13 @@ export class AgentSessionWrapper { if (this.hostOwnedLifecycle) { this.clearLiveSnapshots(); this.recoveringUpdates = false; + // The frames that were lost may have answered a dialog, and the replay + // that follows may restore it: forget it now (its notification must not + // keep offering an answer this server no longer holds), but as a + // *forgotten* settlement, so the replayed request is published again. for (const id of [...this.pendingUiRequests.keys()]) { if (this.serverUiRequests.has(id)) continue; - this.forgetPendingUiRequest(id); + this.settlePendingUiRequest(id, "forgotten"); this.emit({ type: "extension_ui_request", id: `cancel:${id}`, method: "cancel", targetId: id }); } } @@ -1454,8 +1497,15 @@ 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, so no * other tab or device keeps offering an answer to a question that is gone. + * + * `forgotten` is the same for a dialog this server only *dropped*: a resync + * lost it, and the frames the host replays can restore the very same request + * id. The notification is retracted now (nothing on screen may keep offering + * an answer to a question this server no longer holds), but the retraction is + * temporary, so a replay of that request announces and pushes it again + * instead of being suppressed for the retraction TTL. */ - private settlePendingUiRequest(id: string): boolean { + private settlePendingUiRequest(id: string, reason: "settled" | "forgotten" = "settled"): boolean { if (!this.pendingUiRequests.has(id)) return false; // Read before forgetting: the tag is the one the notification went out with. const publishedSession = this.inputNotificationSessions.get(id); @@ -1463,7 +1513,8 @@ export class AgentSessionWrapper { // One server publishes a notification and its retraction: a former // notifier must not close what the elected one still owns. if (publishedSession && (!this.hostOwnedLifecycle || isNotifier(this.host.id))) { - publishNotificationDismiss(publishedSession, id); + if (reason === "forgotten") publishNotificationForgotten(publishedSession, id); + else publishNotificationDismiss(publishedSession, id); } return true; } @@ -1481,8 +1532,9 @@ export class AgentSessionWrapper { if (!pending) return "alreadySettled"; const method = typeof pending.method === "string" ? pending.method : ""; if (method === "ask") { - // A pending ask accepts only its answers or a cancel; anything else would - // drop it from reconnect replay while omp rejects the payload. + // A pending ask accepts only its answers or a cancel; the answers + // themselves are checked against this dialog's questions in + // dispatchCommand, the one funnel every answer passes through. if (!("cancelled" in response) && !("answers" in response && isAskAnswers(response.answers))) { throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); } @@ -2862,11 +2914,15 @@ export class AgentSessionWrapper { case "extension_ui_response": { const { id, ...rest } = command as { id: string; [key: string]: unknown }; - const pendingAsk = this.pendingUiRequests.get(id)?.method === "ask"; + const pending = this.pendingUiRequests.get(id); + const pendingAsk = pending?.method === "ask"; // A pending ask accepts only its answers or a cancel; anything else would - // drop it from reconnect replay while omp rejects the payload. - if (("answers" in rest || pendingAsk) && !isAskAnswers(rest.answers) && !(pendingAsk && rest.cancelled === true)) { - throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); + // drop it from reconnect replay while omp rejects the payload. The + // answers are checked against that dialog's questions, as omp does. + if (("answers" in rest || pendingAsk) && !(pendingAsk && rest.cancelled === true)) { + if (!isAskAnswers(rest.answers)) throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); + const problem = pendingAsk ? askAnswersProblem(rest.answers, pending.questions) : null; + if (problem) throw new WebRpcError(`Invalid ask dialog answers: ${problem}`, "invalid_ask_answers"); } const wasPending = this.settlePendingUiRequest(id); const serverRequest = this.serverUiRequests.get(id); From e005a153f67743aa613ea3e3e0398d79b7fc6f03 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:57:22 +0100 Subject: [PATCH 3/6] fix(notifications): never push a retraction, and refuse answers to non-dialogs A dismiss push displays nothing, which is a silent push: Chromium and Firefox substitute a generic card and eventually mute the origin, and iOS revokes the permission outright. Retractions now reach tab streams only; a device that is not reachable keeps the stale card until the next input push replaces it by tag. public/sw.js loses its dismiss branch, so it always shows what it receives. answerExtensionUiRequest accepted any pending blocking method, including open_url, for which omp registers no resolver: the frame was dropped there while the server reported answered and retracted the notification. Only DIALOG_UI_METHODS are answerable now, and DIALOG_UI_METHODS is the shared set BLOCKING_UI_METHODS is built from. Tests: the two lifecycle paths the maintainer named now have discriminating cases (destroying a server-owned confirm retracts under its own omp-web id; a dialog whose deadline passed while no timer could run is retracted on attach, not replayed). Both fail when settlePendingUiRequest is replaced by forgetPendingUiRequest. The open_url case fails without the new guard. --- AGENTS.md | 10 ++- CHANGELOG.md | 2 +- app/api/notifications/answer/route.ts | 3 +- docs/specs/2026-10-06-notifications-design.md | 30 +++++--- lib/notification-events.ts | 10 ++- lib/notification-hub.test.mjs | 26 ++++--- lib/notification-hub.ts | 76 +++---------------- lib/notification-sw.test.mjs | 21 ++--- lib/rpc-manager.test.mjs | 69 +++++++++++++++++ lib/rpc-manager.ts | 9 ++- public/sw.js | 18 ----- 11 files changed, 149 insertions(+), 125 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7ea44cfe6..e6e3849e3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,6 +103,7 @@ app/api/ hosts/route.ts GET hosts (this machine first) | POST { label } → token once + login command | PATCH { id, label?, allowAgentStart? } (`local`: label only, empty resets to "This machine") | DELETE ?id= revoke (registry first, then close the link); 503 if hosts.json is unreadable hosts/link/route.ts GET WebSocket upgrade (the `ompweb host` daemon; bearer checked before the upgrade, skipped by the `proxy.ts` gate) | POST 426 for pre-WebSocket daemons notifications/devices/route.ts GET VAPID key + subscribed | PUT { deviceId, prefs, subscription? } + notifications/answer/route.ts POST { sessionId, requestId, response } answer a pending dialog from a notification (never spawns omp) notifications/presence/route.ts POST { clientId, deviceId, visible, sessionId, seq } notifications/test/route.ts POST { deviceId } send a test push (502 on push-service refusal) notifications/history/route.ts GET entries | PATCH { ids } mark read | DELETE ?id= remove one, ?all=1 clear @@ -1808,8 +1809,13 @@ during the wait. leak it); else if a visible tab with an open stream exists, `whenActive: "toast"` devices get a toast on their active tabs only; else push (subscribed devices) or in-page `showNotification` (tabs with an open stream). -- The server decides before pushing: iOS revokes push permission for pushes - that display nothing, so `public/sw.js` always shows what it receives. +- The server decides before pushing: a push that displays nothing is a silent + push, and iOS revokes the permission for one while Chromium and Firefox + substitute a generic card and eventually mute the origin. `public/sw.js` + therefore always shows what it receives, and a settled dialog is retracted on + the tab streams only (`{type: "notification-dismiss", tag, sessionId, + requestId}`) — never by a push. A device that is not reachable keeps the + stale card until the next `input` push replaces it by tag or the app syncs. - Notifications have their own `notifications` channel (`clientId` = the tab's notification client id), opened by `useNotifications` in `AppShell`, so a tab stays reachable on every view, Settings included. A tab on diff --git a/CHANGELOG.md b/CHANGELOG.md index 80ed3c63f..c43b738b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,7 +33,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Updates belong to each host.** Settings → Hosts now shows the ompweb daemon and OMP runtime versions, available updates, and update actions for every machine, including This machine. Checks and installations run on that host. An incompatible or unverifiable daemon update stays visible but blocked, with a reason to update the web server first; OMP updates are independent of the link protocol. A daemon update is refused while session processes or subagents run on that host (close them, then start it again), and the host refuses new sessions while it installs. The host update retains a backup and reports progress after reconnect. **System & Updates** is now **System**, containing only the web server's controls; it no longer updates or restarts a host's OMP sessions globally. - **Messages wait safely until omp has them.** In an existing chat, the composer clears once IndexedDB has stored the message, and a dimmed bubble names the delivery leg: **Sending**, **Waiting for **, **Delivering**, or **Not sent** with the reason. Browser-held messages survive reloads and closed tabs; server-held messages survive web-server restarts and host outages, and appear on every device viewing the chat. Chromium's Background Sync can deliver after the last tab closes; other browsers retry when an ompweb page reopens. Duplicate submissions share one message id. If a lost host reply leaves delivery uncertain, the message is marked **Not sent** and never retried automatically. A prompt that omp stops (Stop, or a failure) before it reaches the transcript is marked **Not sent** at once, so the messages behind it go on without waiting. Held messages offer **Delete** until dispatched. Follow-ups and steers become omp's own queue chips when accepted. New chats keep their existing first-message path; a browser unable to store the message keeps the composer draft instead. -- **Answer a waiting question from the notification itself.** A notification for a blocking dialog (confirm, select, input, editor, or the ask tool's question panel) now carries the dialog, so a phone or a native client can answer it without opening the session: `POST /api/notifications/answer` takes the session id, the dialog's request id and one response (`confirmed`, `value`, `cancelled`, or `answers` for an ask). The answer goes through the same command the desktop dialog sends, so a server-owned confirmation resolves, an offline host or a restarting session is reported instead of silently dropping it, and no omp process is started for a session that is not running. An answer the pending dialog cannot take is refused with 400 before anything settles: a select accepts only one of its own labels, and an ask's answers are checked against that dialog's questions the way omp checks them (one answer per question in order, each naming its own question, only offered labels, no label twice, and a single-select question takes either one label or free text, never both), so a payload omp would reject never consumes the question. When the dialog settles anywhere, every other tab and device is told to close its notification of exactly that request, and a push retry that wakes up afterwards delivers nothing. +- **Answer a waiting question from the notification itself.** A notification for a blocking dialog (confirm, select, input, editor, or the ask tool's question panel) now carries the dialog, so a phone or a native client can answer it without opening the session: `POST /api/notifications/answer` takes the session id, the dialog's request id and one response (`confirmed`, `value`, `cancelled`, or `answers` for an ask). The answer goes through the same command the desktop dialog sends, so a server-owned confirmation resolves, an offline host or a restarting session is reported instead of silently dropping it, and no omp process is started for a session that is not running. An answer the pending dialog cannot take is refused with 400 before anything settles: a select accepts only one of its own labels, and an ask's answers are checked against that dialog's questions the way omp checks them (one answer per question in order, each naming its own question, only offered labels, no label twice, and a single-select question takes either one label or free text, never both), so a payload omp would reject never consumes the question. When the dialog settles anywhere, every other open tab is told to close its notification of exactly that request, and a push retry that wakes up afterwards delivers nothing. A settled dialog is never retracted by a push: a push that displays nothing is a silent push, which iOS punishes by revoking the permission and Chromium and Firefox by substituting a generic card and muting the site, so a device that is not reachable keeps the stale card until the next question of that session replaces it. A request that is not a dialog (open_url) takes no answer at all. ### Fixes & Improvements diff --git a/app/api/notifications/answer/route.ts b/app/api/notifications/answer/route.ts index 8d57b12f4..104b0dd99 100644 --- a/app/api/notifications/answer/route.ts +++ b/app/api/notifications/answer/route.ts @@ -44,7 +44,8 @@ function parseResponse(value: unknown): ExtensionUiResponse | null { * 200 {status:"answered"} routed through the shared extension_ui_response command * 200 {status:"alreadySettled"} the request id is not pending * 200 {status:"sessionGone"} no live wrapper for the session - * 400 on an invalid body or an answer the pending dialog does not take + * 400 on an invalid body, an answer the pending dialog does not take, or a + * request that is not a dialog at all (`open_url` takes no answer) * 400 session_restarting / 503 {hostOffline: true} when it cannot be delivered */ export async function POST(req: Request) { diff --git a/docs/specs/2026-10-06-notifications-design.md b/docs/specs/2026-10-06-notifications-design.md index 99369ee9c..08f5e553b 100644 --- a/docs/specs/2026-10-06-notifications-design.md +++ b/docs/specs/2026-10-06-notifications-design.md @@ -38,8 +38,14 @@ Rules: to Opus, rate limits, provider failures). A fallback still held at `auto_retry_end`, `prompt_result` or `session_settled` is sent without one. - Every notification has tag `:`, so a repeat replaces the - previous one instead of stacking. Notifications are not retracted when they - stop applying. + previous one instead of stacking. An `input` notification is retracted when + the dialog behind it settles (answered, cancelled, expired, or its omp child + went away): every reachable tab gets a `notification-dismiss` frame naming + the tag and request id. No push carries the retraction — a push that + displays nothing is a silent push, which browsers punish — so a device that + is not reachable keeps the stale card until the next `input` push replaces + it by tag. The request id rides on every delivery, so a retraction closes + only its own dialog and never the next one of the same tag. ## Architecture @@ -183,7 +189,10 @@ exactly one response variant: `{confirmed}`, `{value}`, `{cancelled: true}`, or - The answer is checked against the pending dialog first, so a payload the dialog cannot take is a 400 and leaves the question answerable: a `select` takes one of its own labels, a `confirm` a confirmation, an `input`/`editor` - a value, and an `ask` its answers. An `ask` payload is validated with omp's + a value, and an `ask` its answers. A request whose method is not a dialog + takes no answer at all: `open_url` is fire-and-forget (omp registers no + resolver for it), so any response to it is a 400 `invalid_dialog_answer` + before anything is sent. An `ask` payload is validated with omp's own rules (`parseAskDialogResponse` in `rpc-mode.ts`): one answer per question in request order, each answer naming its own question id, only labels that question offers, no label twice, and a single-select question @@ -194,12 +203,15 @@ exactly one response variant: `{confirmed}`, `{value}`, `{cancelled: true}`, or the offline/restarting gate: a host that is offline answers 503 `{hostOffline: true}` and a restarting session 400 `session_restarting`, never `answered`. The dialog is settled only after the answer was admitted. -- Settling a dialog retracts its notification everywhere: every reachable tab - gets `{type: "notification-dismiss", tag, sessionId, requestId}`, subscribed - devices get a `dismiss` push (never to Apple's endpoint, which revokes the - permission for a push that shows nothing), and the history entry of exactly - that request becomes read. A newer dialog of the same tag keeps its own - unread entry. A push retry that wakes after the settlement delivers nothing. +- Settling a dialog retracts its notification on every reachable tab: + `{type: "notification-dismiss", tag, sessionId, requestId}`, and the history + entry of exactly that request becomes read. A newer dialog of the same tag + keeps its own unread entry. A push retry that wakes after the settlement + delivers nothing. No push carries the retraction: a push that displays + nothing is a silent push (iOS revokes the permission, Chromium and Firefox + substitute a generic card and mute the origin), so a device that is not + reachable keeps the stale card until the next `input` push replaces it by + tag or the app syncs. - A resync that dropped a dialog (a linked host discarding buffered output) retracts it too, but as a *forgotten* settlement: the retraction is temporary, so if the host replays the same request id the question is diff --git a/lib/notification-events.ts b/lib/notification-events.ts index e25ebb58b..163b35cd0 100644 --- a/lib/notification-events.ts +++ b/lib/notification-events.ts @@ -150,8 +150,16 @@ export function renderNotification(event: NotificationEvent, t: Translate): Rend const MODEL_SWITCH_NOTICE_SOURCES = new Set(["prewalk", "plan-yolo"]); +/** + * Extension UI dialogs the user answers in the chat (omp's rpc.md "Extension UI + * Sub-Protocol": these expect an `extension_ui_response`). `open_url` is + * fire-and-forget — omp registers no resolver for it — so it is not a dialog + * and takes no answer; it is only *blocking* in the sense that it is replayed. + */ +export const DIALOG_UI_METHODS: ReadonlySet = new Set(["select", "confirm", "input", "editor", "ask"]); + /** Extension UI methods that block the agent until the user answers (rpc-manager replays these too). */ -export const BLOCKING_UI_METHODS = new Set(["select", "confirm", "input", "editor", "ask", "open_url"]); +export const BLOCKING_UI_METHODS = new Set([...DIALOG_UI_METHODS, "open_url"]); const NOTIFICATION_ID_PATTERN = /^[A-Za-z0-9_-]{8,64}$/; diff --git a/lib/notification-hub.test.mjs b/lib/notification-hub.test.mjs index 66e8b4b33..c00bed4b9 100644 --- a/lib/notification-hub.test.mjs +++ b/lib/notification-hub.test.mjs @@ -326,17 +326,20 @@ test("a settled dialog is retracted on every reachable stream and its history en assert.deepEqual(store.listHistory().map((entry) => [entry.id, entry.read]), [["s2:input", true]]); }); -test("a retraction pushes a dismiss to subscribed devices, but never to Apple's endpoint", async (t) => { +test("a retraction pushes nothing at all: a push that displays nothing is a silent push", async (t) => { isolatedStore(t); const sent = []; webpush.sendNotification = async (_subscription, payload) => { sent.push(JSON.parse(payload)); }; + // Both a subscribed phone and an iPhone: neither may get a dismiss push. + // Chromium and Firefox answer a push that shows nothing with a generic card + // and mute the origin; iOS revokes the permission outright. store.saveDevice("phone-0001", prefs(), subscription); store.saveDevice("iphone-0001", prefs(), { ...subscription, endpoint: "https://web.push.apple.com/xyz" }); hub.publishNotificationDismiss("s2", "req-1"); await flush(); - assert.deepEqual(sent, [{ type: "dismiss", tag: "s2:input", sessionId: "s2", requestId: "req-1" }]); + assert.deepEqual(sent, [], "no device is pushed a retraction"); }); test("the retraction reads only the entry of its own request, not a newer dialog of the same tag", (t) => { @@ -356,7 +359,7 @@ test("a forgotten dialog is retracted now, and a replay of the same request is a t.mock.method(console, "warn", () => {}); const pushes = []; webpush.sendNotification = async (_subscription, payload) => { - if (JSON.parse(payload).type !== "dismiss") pushes.push(JSON.parse(payload).requestId); + pushes.push(JSON.parse(payload).requestId); throw offline(); }; // One device takes pushes, another has only a reachable tab. @@ -389,8 +392,8 @@ test("a forgotten dialog stays retracted while no replay restores it", async (t) t.mock.timers.enable({ apis: ["setTimeout"] }); t.mock.method(console, "warn", () => {}); let attempts = 0; - webpush.sendNotification = async (_subscription, payload) => { - if (JSON.parse(payload).type !== "dismiss") attempts += 1; + webpush.sendNotification = async () => { + attempts += 1; throw offline(); }; store.saveDevice("phone-0001", prefs(), subscription); @@ -408,8 +411,8 @@ test("a forgotten retraction never lifts a permanent settlement of the same requ t.mock.timers.enable({ apis: ["setTimeout"] }); t.mock.method(console, "warn", () => {}); let attempts = 0; - webpush.sendNotification = async (_subscription, payload) => { - if (JSON.parse(payload).type !== "dismiss") attempts += 1; + webpush.sendNotification = async () => { + attempts += 1; throw offline(); }; store.saveDevice("phone-0001", prefs(), subscription); @@ -422,7 +425,7 @@ test("a forgotten retraction never lifts a permanent settlement of the same requ assert.equal(attempts, 0, "an answered dialog is never pushed again"); }); -test("a retraction reaches a device that turned notifications off after receiving the question", async (t) => { +test("a retraction never pushes, whatever the device's preferences are", async (t) => { isolatedStore(t); const sent = []; webpush.sendNotification = async (_subscription, payload) => { @@ -433,7 +436,7 @@ test("a retraction reaches a device that turned notifications off after receivin store.saveDevice("phone-0002", prefs({ types: { ...DEFAULT_NOTIFICATION_PREFS.types, input: false } }), { ...subscription, endpoint: "https://push.example/def" }); hub.publishNotificationDismiss("s2", "req-1"); await flush(); - assert.deepEqual(sent.map((payload) => payload.type), ["dismiss", "dismiss"], "a retraction is not an alert and is not gated by alert prefs"); + assert.deepEqual(sent, [], "a retraction is not an alert and is never pushed, gated or not"); }); test("a push retry after the dialog settled delivers nothing", async (t) => { @@ -441,9 +444,8 @@ test("a push retry after the dialog settled delivers nothing", async (t) => { t.mock.timers.enable({ apis: ["setTimeout"] }); t.mock.method(console, "warn", () => {}); let attempts = 0; - webpush.sendNotification = async (_subscription, payload) => { - // A retraction push is a separate, single-attempt delivery. - if (JSON.parse(payload).type !== "dismiss") attempts += 1; + webpush.sendNotification = async () => { + attempts += 1; throw offline(); }; store.saveDevice("phone-0001", prefs(), subscription); diff --git a/lib/notification-hub.ts b/lib/notification-hub.ts index 8c84df641..957beb589 100644 --- a/lib/notification-hub.ts +++ b/lib/notification-hub.ts @@ -47,8 +47,8 @@ export interface NotificationPresence { * A toast/system notification, or the retraction of a session's `input` * notification once its dialog was answered, cancelled, expired or its omp * child went away. The retraction reaches a tab as `type: "notification-dismiss"` - * (lib/event-stream-hub.ts wraps it) and a device as a `type: "dismiss"` push - * (public/sw.js). + * (lib/event-stream-hub.ts wraps it); it is never pushed (see + * `publishNotificationDismiss`). */ export type NotificationMessage = | { kind: "toast" | "os"; event: NotificationEvent } @@ -182,37 +182,6 @@ 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 }; - } -} - /** * True while this dialog's retraction still covers a push retry. Every path * that settles a dialog (answer, cancel, expiry, process exit) records one, @@ -275,22 +244,6 @@ 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(); @@ -334,9 +287,14 @@ export function publishNotification(event: NotificationEvent): void { /** * Retract a session's `input` notification: its dialog was answered by any * client, cancelled, expired, or its omp child went away. Every reachable tab - * gets the retraction on its stream, and subscribed devices get a dismiss push - * unless the endpoint is Apple's (see `isApplePushEndpoint`). The history entry - * becomes read because the question is settled. + * gets the retraction on its stream, and the history entry becomes read + * because the question is settled. + * + * No push goes out: a push that displays nothing counts as a silent push, and + * Chromium and Firefox answer one with a browser-substituted card ("This site + * has been updated in the background") and eventually mute the origin, exactly + * as iOS revokes the permission. A device that is not reachable keeps the stale + * card until the next `input` push replaces it by tag or the app syncs. * * Never throws: callers run on the RPC frame path. */ @@ -397,20 +355,6 @@ function retract(sessionId: string, requestId: string, kind: "permanent" | "temp } } } - let devices: NotificationDevice[] = []; - try { - devices = listDevices(); - } catch (error) { - console.warn("[notifications] store unavailable:", error); - } - for (const device of devices) { - // A retraction is not an alert: a device that turned notifications off - // after receiving the question still has the old one on screen. - if (!device.subscription) continue; - if (isApplePushEndpoint(device.subscription.endpoint)) continue; - // 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. diff --git a/lib/notification-sw.test.mjs b/lib/notification-sw.test.mjs index d0366075e..3e9d879f3 100644 --- a/lib/notification-sw.test.mjs +++ b/lib/notification-sw.test.mjs @@ -45,23 +45,16 @@ test("a shown push is reported to every open tab with its kind, text and session assert.deepEqual(messages, [["a", { type: "omp-notification-shown", notification }], ["b", { type: "omp-notification-shown", notification }]]); }); -test("a dismiss push closes only the notification of its own request and shows nothing", async () => { +test("every push the worker receives is displayed, including one that names a settled request", async () => { const closed = []; - const shown = []; const worker = loadWorker(); - // The worker reads the shown notifications back by tag. - const notifications = [ - { data: { requestId: "req-1" }, close: () => closed.push("req-1") }, - { data: { requestId: "req-2" }, close: () => closed.push("req-2") }, - ]; - worker.registration.getNotifications = async ({ tag }) => { - shown.push(tag); - return notifications; - }; + // The server never pushes a retraction (a push that shows nothing is a + // silent push), so the worker has no dismiss branch: it always displays. + const notifications = [{ data: { requestId: "req-1" }, close: () => closed.push("req-1") }]; + worker.registration.getNotifications = async () => notifications; await worker.push({ type: "dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); - assert.deepEqual(shown, ["s1:input"]); - assert.deepEqual(closed, ["req-1"], "a late retraction must not close the next dialog of the same tag"); - assert.deepEqual(worker.shown, [], "a retraction push displays nothing"); + assert.deepEqual(closed, [], "a payload is never acted on without being shown"); + assert.equal(worker.shown.length, 1, "even an unexpected payload becomes a visible notification"); }); test("a dialog push carries its request id so a retraction can match it", async () => { diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 28ef6c571..11699dbf2 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -814,6 +814,22 @@ test("a server-owned confirm is settled by the notification answer path, not jus assert.equal(messages.at(-1).requestId, request.id); }); +test("destroying a session retracts a server-owned confirm under its own omp-web request id", async (t) => { + const { wrapper, messages } = await notifyingSession(t); + const events = []; + wrapper.onEvent((event) => events.push(event)); + const answer = wrapper.confirmFromServer("Start a session on build-box?"); + const request = events.find((event) => event.type === "extension_ui_request" && event.method === "confirm"); + assert.match(request.id, /^omp-web:/, "the server owns this dialog's id"); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [], "nothing is retracted while it waits"); + + await wrapper.destroyAndWait(); + assert.equal(await answer, false, "the dialog is declined"); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [ + { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: request.id }, + ], "dropServerUiRequests settles the dialog instead of only forgetting it"); +}); + test("an answer the pending dialog does not take is refused before anything settles", async (t) => { const { wrapper, feed, messages } = await notifyingSession(t); feed({ type: "extension_ui_request", id: "q-select", method: "select", title: "Which?", options: ["A", "B"] }); @@ -1253,6 +1269,41 @@ test("expired dialogs are not replayed by a later stream subscription", async (t assert.deepEqual(received, []); }); +test("a dialog whose deadline passed while no timer could run is retracted when a tab attaches, not replayed", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + const { messages, restore } = await reachableTab(); + let feed; + const ompState = { sessionId: "replay-expiry", sessionFile: "/tmp/replay-expiry.jsonl", isStreaming: false, isCompacting: false }; + const fakeProc = { + isAlive: true, + waitReady: async () => ({ type: "ready", protocolVersion: 2 }), + negotiateProtocol: async () => {}, + onFrame: (handler) => { feed = handler; return () => {}; }, + sendCommand: async (command) => command.type === "get_state" ? { ...ompState } : {}, + sendFrame: () => {}, + dispose: async () => {}, + }; + const wrapper = new SnapshotWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); + wrapper.start(); + await wrapper.waitUntilReady(); + t.after(async () => { + await wrapper.destroyAndWait(); + restore(); + }); + + feed({ type: "extension_ui_request", id: "q-exp", method: "confirm", title: "Deploy?", message: "", timeout: 1_000 }); + // The deadline passes without its timer running (a wrapper that outlived the + // timer, e.g. across a hot reload): only the replay path can notice. + t.mock.timers.setTime(Date.now() + 5_000); + const replayed = []; + wrapper.onEvent((event) => replayed.push(event)); + assert.deepEqual(replayed.filter((event) => event.type === "extension_ui_request"), [], "an expired dialog is not offered again"); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [ + { kind: "dismiss", tag: "replay-expiry:input", sessionId: "replay-expiry", requestId: "q-exp" }, + ], "the replay-time expiry retracts the notification it published"); + assert.equal(await wrapper.answerExtensionUiRequest("q-exp", { confirmed: true }), "alreadySettled"); +}); + test("an expired dialog is retracted once, is not answerable, and a later one of the same tag still is", async (t) => { t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); const { messages, restore } = await reachableTab(); @@ -1320,6 +1371,24 @@ for (const [method, frame, accepted, refused] of [ }); } +test("an open_url request is never answerable: it takes no response and stays pending", async (t) => { + const { wrapper, emit, sentFrames } = snapshotSession(t); + emit({ type: "extension_ui_request", id: "u1", method: "open_url", url: "https://example.test", instructions: "Open it" }); + for (const response of [{ value: "opened" }, { confirmed: true }, { cancelled: true }]) { + await assert.rejects( + wrapper.answerExtensionUiRequest("u1", response), + { code: "invalid_dialog_answer" }, + `open_url must refuse ${JSON.stringify(response)}`, + ); + } + assert.deepEqual(sentFrames, [], "omp registers no resolver for open_url: nothing may be sent"); + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.id, "u1", "a refused answer leaves the request replayable"); + await assert.rejects(wrapper.answerExtensionUiRequest("u1", { value: "opened" }), { code: "invalid_dialog_answer" }, "and it never becomes answered"); + assert.deepEqual(sentFrames, [], "no answer of any kind reaches omp"); +}); + 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 6fdd2c3f8..5bdf3b5f0 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -21,7 +21,7 @@ import { markShuttingDown, recordRunningSessions, resumeOnHostLink, takeInterrup import { RESUME_PROMPT } from "./hosts/host-resume"; import { samePath } from "./paths"; import { isRecord } from "./type-guards"; -import { BLOCKING_UI_METHODS, createNotificationDetector } from "./notification-events"; +import { BLOCKING_UI_METHODS, createNotificationDetector, DIALOG_UI_METHODS } from "./notification-events"; import { publishNotification, publishNotificationDismiss, publishNotificationForgotten } from "./notification-hub"; import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "./skill-diagnostics"; import { eventWithToolResultImageUrls } from "./media-cache"; @@ -1531,6 +1531,13 @@ export class AgentSessionWrapper { const pending = this.pendingUiRequests.get(id); if (!pending) return "alreadySettled"; const method = typeof pending.method === "string" ? pending.method : ""; + // `open_url` (and anything else that is not a dialog) is stored as pending + // only so it is replayed; omp registers no resolver for it, so an + // "answer" would be dropped there while this server reported success and + // retracted the notification. Only DIALOG_UI_METHODS are answerable. + if (!DIALOG_UI_METHODS.has(method)) { + throw new WebRpcError("This request does not take an answer", "invalid_dialog_answer"); + } if (method === "ask") { // A pending ask accepts only its answers or a cancel; the answers // themselves are checked against this dialog's questions in diff --git a/public/sw.js b/public/sw.js index 150201786..f139b1c8d 100644 --- a/public/sw.js +++ b/public/sw.js @@ -15,24 +15,6 @@ 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 dismissTag = typeof data.tag === "string" ? data.tag : ""; - const dismissRequest = 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 (!dismissTag || !dismissRequest || typeof self.registration.getNotifications !== "function") return; - const shown = await self.registration.getNotifications({ tag: dismissTag }); - for (const notification of shown) { - if (notification.data && notification.data.requestId === dismissRequest) notification.close(); - } - })()); - return; - } const requestId = typeof data.requestId === "string" ? data.requestId : typeof data.dialog?.requestId === "string" ? data.dialog.requestId : ""; From 9da0e2366f53bc938929454121a75da61a849c49 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:39:57 +0100 Subject: [PATCH 4/6] feat(notifications): repeat an unanswered question every two hours A blocking dialog that stays unanswered is repeated on the device's own notification, with a per-device toggle in the notifications settings. Only `select`/`confirm`/`input`/`editor`/`ask` are armed: `open_url` has no answer, so `DIALOG_UI_METHODS` (introduced by #319) is reused instead of `BLOCKING_UI_METHODS`. The timer is released with the pending state, so every settlement path (answer from the desktop or a notification, omp's cancel, expiry, replay-time expiry, restart, destroy) stops it instead of leaving it to fire once more; the cap bounds a dialog nobody answers. The notifier election is rechecked on every fire, so a former notifier falls silent once another web server takes the host's notifications. A repeat states an elapsed duration ("2 hours") rather than a server-timezone clock time, which a device in another timezone cannot read. --- AGENTS.md | 12 +++ CHANGELOG.md | 12 +++ components/NotificationList.tsx | 3 +- components/SettingsConfig.tsx | 4 + hooks/useNotifications.ts | 3 +- lib/i18n/locales/en.json | 5 + lib/i18n/locales/ja.json | 5 + lib/i18n/locales/zh-CN.json | 5 + lib/notification-events.test.mjs | 51 +++++++++ lib/notification-events.ts | 50 ++++++++- lib/notification-hub.test.mjs | 34 ++++++ lib/notification-hub.ts | 28 ++++- lib/rpc-manager.test.mjs | 171 +++++++++++++++++++++++++++++++ lib/rpc-manager.ts | 124 +++++++++++++++++++++- 14 files changed, 494 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e6e3849e3..35416bc77 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1830,6 +1830,18 @@ during the wait. rendered server-side in the device's locale. Browsers with saved settings (enabled or not) sync on load; never-configured browsers do not. - A crash notifies "Run failed" while a run is live or while background work started by it has not settled yet (`unsettled`, cleared by `session_settled`). +- An unanswered `input` notification repeats while its dialog stays pending: + `INPUT_REMINDER_MS` (2 h) apart, at most `MAX_INPUT_REMINDERS` (12) times, + then it stays quiet until it settles. `OMP_WEB_INPUT_REMINDER_MS` overrides + the spacing for this process (`0` disables reminders; unset, negative, + non-numeric or above `2^31-1` keep the default — a larger value overflows + `setTimeout` and would fire immediately). Each device can turn the repeats + off with `prefs.inputReminder`; the first notification is unaffected. The + schedule is per request id and survives a host replay of the same id, so a + reconnecting host neither restarts the budget nor resets the "waiting for" + duration; only a real settlement drops it. The history entry is shared, so a + device that turned repeats off still sees the reminder rows another device + wanted. - The Settings test button pushes through the server for subscribed devices (502 with the push service's answer on failure) and shows a local notification otherwise, or a toast where none are allowed. diff --git a/CHANGELOG.md b/CHANGELOG.md index c43b738b3..a385bc5fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,18 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Messages wait safely until omp has them.** In an existing chat, the composer clears once IndexedDB has stored the message, and a dimmed bubble names the delivery leg: **Sending**, **Waiting for **, **Delivering**, or **Not sent** with the reason. Browser-held messages survive reloads and closed tabs; server-held messages survive web-server restarts and host outages, and appear on every device viewing the chat. Chromium's Background Sync can deliver after the last tab closes; other browsers retry when an ompweb page reopens. Duplicate submissions share one message id. If a lost host reply leaves delivery uncertain, the message is marked **Not sent** and never retried automatically. A prompt that omp stops (Stop, or a failure) before it reaches the transcript is marked **Not sent** at once, so the messages behind it go on without waiting. Held messages offer **Delete** until dispatched. Follow-ups and steers become omp's own queue chips when accepted. New chats keep their existing first-message path; a browser unable to store the message keeps the composer draft instead. - **Answer a waiting question from the notification itself.** A notification for a blocking dialog (confirm, select, input, editor, or the ask tool's question panel) now carries the dialog, so a phone or a native client can answer it without opening the session: `POST /api/notifications/answer` takes the session id, the dialog's request id and one response (`confirmed`, `value`, `cancelled`, or `answers` for an ask). The answer goes through the same command the desktop dialog sends, so a server-owned confirmation resolves, an offline host or a restarting session is reported instead of silently dropping it, and no omp process is started for a session that is not running. An answer the pending dialog cannot take is refused with 400 before anything settles: a select accepts only one of its own labels, and an ask's answers are checked against that dialog's questions the way omp checks them (one answer per question in order, each naming its own question, only offered labels, no label twice, and a single-select question takes either one label or free text, never both), so a payload omp would reject never consumes the question. When the dialog settles anywhere, every other open tab is told to close its notification of exactly that request, and a push retry that wakes up afterwards delivers nothing. A settled dialog is never retracted by a push: a push that displays nothing is a silent push, which iOS punishes by revoking the permission and Chromium and Firefox by substituting a generic card and muting the site, so a device that is not reachable keeps the stale card until the next question of that session replaces it. A request that is not a dialog (open_url) takes no answer at all. +- **A waiting question is repeated until you answer it.** A notification for a + blocking dialog now repeats every two hours while the dialog stays pending, + at most twelve times, then stays quiet until it settles. Each repeat says how + long the question has been open in the reader's language ("Waiting for 2 + hours: Deploy?"), not a clock time in the server's timezone. Repeats stop the + moment the dialog is answered, cancelled, expires, or its session ends, and + each device can turn them off in Settings → Notifications without losing the + first notification. `OMP_WEB_INPUT_REMINDER_MS` overrides the spacing (`0` + disables reminders). A host that replays its pending requests after a + reconnect does not restart the count or the elapsed label: the same question + keeps its own schedule until it is really settled. + ### Fixes & Improvements - **Anthropic stays visible when usage limits are unavailable.** The Provider Usage panel keeps accounts that omp reports without usage data and marks them as unavailable rather than unlimited. diff --git a/components/NotificationList.tsx b/components/NotificationList.tsx index e18f9aaee..9795392e4 100644 --- a/components/NotificationList.tsx +++ b/components/NotificationList.tsx @@ -80,7 +80,8 @@ export function NotificationList() { */ function NotificationRow({ entry }: { entry: NotificationHistoryEntry }) { const { t, locale } = useI18n(); - const { title, body } = renderNotification(entry.event, t); + // The locale makes a reminder's elapsed duration read in the same language. + const { title, body } = renderNotification(entry.event, t, locale); const { sessionId } = entry.event; // Following a notification is reading it. const open = sessionId ? () => { diff --git a/components/SettingsConfig.tsx b/components/SettingsConfig.tsx index 7178468ef..3a2a25161 100644 --- a/components/SettingsConfig.tsx +++ b/components/SettingsConfig.tsx @@ -228,6 +228,7 @@ const SETTING_INDEX: SettingIndexEntry[] = [ { id: "notifications-enable", tab: "notifications", sectionKey: "notifications.title", labelKey: "notifications.enable", descKey: "notifications.enableDesc", fallbackSection: "Notifications", fallbackLabel: "Enable notifications", fallbackDesc: "Asks the browser for permission to show notifications.", scope: "UI" }, { id: "notifications-completed", tab: "notifications", sectionKey: "notifications.title", labelKey: "notifications.typeCompleted", descKey: "notifications.typeCompletedDesc", fallbackSection: "Notifications", fallbackLabel: "Task finished", fallbackDesc: "A prompt and the background work it started are done. Subagents never notify.", scope: "UI" }, { id: "notifications-input", tab: "notifications", sectionKey: "notifications.title", labelKey: "notifications.typeInput", descKey: "notifications.typeInputDesc", fallbackSection: "Notifications", fallbackLabel: "Waiting for input", fallbackDesc: "The agent asks a question or needs an approval.", scope: "UI" }, + { id: "notifications-input-reminder", tab: "notifications", sectionKey: "notifications.title", labelKey: "notifications.inputReminder", descKey: "notifications.inputReminderDesc", fallbackSection: "Notifications", fallbackLabel: "Remind me about unanswered questions", fallbackDesc: "The notification repeats while a question stays unanswered, until it is answered or cancelled.", scope: "UI" }, { id: "notifications-error", tab: "notifications", sectionKey: "notifications.title", labelKey: "notifications.typeError", descKey: "notifications.typeErrorDesc", fallbackSection: "Notifications", fallbackLabel: "Run failed", fallbackDesc: "A run stops with an error after retries and fallbacks, or the omp process exits.", scope: "UI" }, { id: "notifications-modelSwitch", tab: "notifications", sectionKey: "notifications.title", labelKey: "notifications.typeModelSwitch", descKey: "notifications.typeModelSwitchDesc", fallbackSection: "Notifications", fallbackLabel: "Model switched automatically", fallbackDesc: "omp switches models on its own: a fallback after a refusal, rate limit, or usage limit, or a prewalk / plan hand-off.", scope: "UI" }, { id: "notifications-when-active", tab: "notifications", sectionKey: "notifications.title", labelKey: "notifications.whenActive", descKey: "notifications.whenActiveDesc", fallbackSection: "Notifications", fallbackLabel: "When I'm using omp-web in another tab", fallbackDesc: "Nothing is shown for the session you are viewing.", scope: "UI" }, @@ -699,6 +700,9 @@ function NotificationSettingsPanel() { save({ types: { ...prefs.types, [type]: next } })} /> ))} + + save({ inputReminder: next })} /> +