Repository navigation
feat(notifications): actionable input notifications, answer endpoint and dismiss #328
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
579f150
eecd570
0da2255
a9bc720
b09a867
ae33fff
2495bc0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import packageJson from "../../../package.json"; | ||
|
|
||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| /** | ||
| * Capability handshake for native clients. Rides the normal /api auth gate; it | ||
| * carries the package version and which server-side features exist, never any | ||
| * credential or configuration value. | ||
| */ | ||
| export function GET() { | ||
| return NextResponse.json({ | ||
| name: "ompweb", | ||
| version: packageJson.version, | ||
| api: 1, | ||
| capabilities: { | ||
| notificationDialogs: true, | ||
| notificationAnswer: true, | ||
| notificationDismiss: true, | ||
| heartbeatParam: true, | ||
| }, | ||
| }); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; | ||
| import type { ExtensionUiResponse, RpcAskDialogAnswer } from "@/lib/pi-types"; | ||
| import { getRpcSession, isAskAnswers, WebRpcError } from "@/lib/rpc-manager"; | ||
| import { isRecord } from "@/lib/type-guards"; | ||
|
|
||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| /** Answers are text; 64 KB leaves room for a long ask customInput without becoming a payload channel. */ | ||
| const MAX_BODY_BYTES = 64 * 1024; | ||
| const MAX_ID_CHARS = 256; | ||
|
|
||
| const invalid = (error: string) => NextResponse.json({ error, code: "invalid_answer_request" }, { status: 400 }); | ||
|
|
||
| function isId(value: unknown): value is string { | ||
| return typeof value === "string" && value.length > 0 && value.length <= MAX_ID_CHARS; | ||
| } | ||
|
|
||
| /** | ||
| * Exactly one response variant, and nothing else. Shapes come from | ||
| * ExtensionDialog; the ask payload reuses the agent route's validation. | ||
| */ | ||
| function parseResponse(value: unknown): ExtensionUiResponse | null { | ||
| if (!isRecord(value)) return null; | ||
| const keys = Object.keys(value); | ||
| if (keys.length !== 1) return null; | ||
| switch (keys[0]) { | ||
| case "value": | ||
| return typeof value.value === "string" ? { value: value.value } : null; | ||
| case "confirmed": | ||
| return typeof value.confirmed === "boolean" ? { confirmed: value.confirmed } : null; | ||
| case "cancelled": | ||
| return value.cancelled === true ? { cancelled: true } : null; | ||
| case "answers": | ||
| return isAskAnswers(value.answers) ? { answers: value.answers as RpcAskDialogAnswer[] } : null; | ||
| default: | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * POST /api/notifications/answer — answer a pending blocking extension dialog | ||
| * from a notification action. Looks up the live wrapper (also through moved- | ||
| * session aliases) and never spawns omp. Behind the normal auth gate. | ||
| * | ||
| * 200 {status:"answered"} routed through extension_ui_response | ||
| * 200 {status:"alreadySettled"} the request id is not pending | ||
| * 200 {status:"sessionGone"} no live wrapper for the session | ||
| * 400 on an invalid body | ||
| */ | ||
| export async function POST(req: Request) { | ||
| let body: unknown; | ||
| try { | ||
| body = await parseJsonWithinLimit<unknown>(req, MAX_BODY_BYTES); | ||
| } catch (error) { | ||
| if (error instanceof RequestBodyTooLargeError) { | ||
| return NextResponse.json({ error: "Answer is too large", code: "request_too_large" }, { status: 413 }); | ||
| } | ||
| return invalid("Invalid JSON request body"); | ||
| } | ||
| if (!isRecord(body) || !isId(body.sessionId) || !isId(body.requestId)) { | ||
| return invalid("sessionId, requestId and response are required"); | ||
| } | ||
| const response = parseResponse(body.response); | ||
| if (!response) return invalid("response must be exactly one of value, confirmed, cancelled or answers"); | ||
|
|
||
| const session = getRpcSession(body.sessionId); | ||
| if (!session || !session.isAlive()) return NextResponse.json({ status: "sessionGone" }); | ||
|
|
||
| try { | ||
| return NextResponse.json({ status: session.answerExtensionUiRequest(body.requestId, response) }); | ||
| } catch (error) { | ||
| if (error instanceof WebRpcError) { | ||
| return NextResponse.json({ error: error.message, code: error.code }, { status: 400 }); | ||
| } | ||
| throw error; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<string, string | undefined>(); | ||
| const showToast = (rendered: RenderedNotification, type: NotificationEvent["type"], requestId?: string) => { | ||
| const show = type === "error" ? toast.error : toast.info; | ||
| const target = rendered.sessionId; | ||
| toastRequests.set(rendered.tag, requestId); | ||
| // The whole card opens the session (click, tap, or Enter on the focused card); following it is reading it. | ||
| show(rendered.title, rendered.body, { | ||
| id: rendered.tag, | ||
|
|
@@ -132,14 +136,33 @@ export function useNotifications({ sessionId, locale, onOpenSession }: { session | |
| notificationHistory.add(event); | ||
| const rendered = renderNotification(event, translate); | ||
| if (kind === "toast") { | ||
| showToast(rendered, event.type); | ||
| showToast(rendered, event.type, event.requestId); | ||
| return; | ||
| } | ||
| // Permission withdrawn or never granted: the toast is the only way left to tell the user. | ||
| void showSystemNotification(rendered).then((shown) => { | ||
| if (!shown) showToast(rendered, event.type); | ||
| void showSystemNotification(rendered, event.requestId).then((shown) => { | ||
| if (!shown) showToast(rendered, event.type, event.requestId); | ||
| }); | ||
| }; | ||
| // The dialog was answered, cancelled or expired elsewhere. Close only the | ||
| // notification of that request id: a buffered push can arrive after the | ||
| // next dialog for the same tag is already shown, and that one stays. | ||
| const dismiss = async (tag: string, requestId: string) => { | ||
| if (toastRequests.get(tag) === requestId) { | ||
| toastRequests.delete(tag); | ||
| toast.close(tag); | ||
| } | ||
| try { | ||
| const registration = "serviceWorker" in navigator ? await navigator.serviceWorker.getRegistration() : undefined; | ||
| const shown = await registration?.getNotifications({ tag }) ?? []; | ||
| for (const notification of shown) { | ||
| const data: unknown = notification.data; | ||
| if (isRecord(data) && data.requestId === requestId) notification.close(); | ||
|
Comment on lines
+155
to
+160
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } | ||
| } catch { | ||
| // A closing registration must not break the toast path. | ||
| } | ||
| }; | ||
| const onOpen = (raw: Event) => { | ||
| if (raw instanceof CustomEvent && typeof raw.detail === "string" && raw.detail) openRef.current(raw.detail); | ||
| }; | ||
|
|
@@ -154,12 +177,20 @@ export function useNotifications({ sessionId, locale, onOpenSession }: { session | |
| if (data.type === "omp-notification-shown") void notificationHistory.load(); | ||
| }; | ||
| // This tab's own channel: the server delivers here while it is open, on any | ||
| // view (the chat, Settings, ...), and counts the tab as reachable. | ||
| // view (the chat, Settings, ...), and counts the tab as reachable. A settled | ||
| // input dialog arrives as a dismiss frame and retracts only its own request. | ||
| const stream = openEventStream({ kind: "notifications", clientId: notificationClientId }); | ||
| stream.onmessage = ({ data }) => { | ||
| try { | ||
| const frame: unknown = JSON.parse(data); | ||
| if (!isRecord(frame) || frame.type !== "notification" || (frame.kind !== "toast" && frame.kind !== "os") || !isRecord(frame.event)) return; | ||
| if (!isRecord(frame)) return; | ||
| if (frame.type === "notification-dismiss") { | ||
| if (typeof frame.tag === "string" && frame.tag && typeof frame.requestId === "string" && frame.requestId) { | ||
| void dismiss(frame.tag, frame.requestId); | ||
| } | ||
|
Comment on lines
+187
to
+190
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| 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); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import assert from "node:assert/strict"; | ||
| import { readFileSync } from "node:fs"; | ||
| import test from "node:test"; | ||
| import { fileURLToPath } from "node:url"; | ||
| import { createJiti } from "jiti"; | ||
|
|
||
| const jiti = createJiti(import.meta.url, { | ||
| tryNative: false, | ||
| alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, | ||
| }); | ||
| const route = await jiti.import("../app/api/app-info/route.ts"); | ||
| const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); | ||
|
|
||
| test("app-info identifies ompweb, its version and the notification and heartbeat capabilities", async () => { | ||
| const response = await route.GET(); | ||
| assert.equal(response.status, 200); | ||
| const body = await response.json(); | ||
| assert.equal(body.name, "ompweb"); | ||
| assert.equal(body.version, pkg.version); | ||
| assert.equal(body.api, 1); | ||
| assert.deepEqual(body.capabilities, { | ||
| notificationDialogs: true, | ||
| notificationAnswer: true, | ||
| notificationDismiss: true, | ||
| heartbeatParam: true, | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,7 +11,7 @@ const jiti = createJiti(import.meta.url, { | |
| "@/": new URL("../", import.meta.url).pathname, | ||
| }, | ||
| }); | ||
| const { EventStreamConnection, getEventStreamConnection } = await jiti.import("./event-stream-hub.ts"); | ||
| const { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } = await jiti.import("./event-stream-hub.ts"); | ||
| const route = await jiti.import("../app/api/events/route.ts"); | ||
| const { AgentSessionWrapper } = await jiti.import("./rpc-manager.ts"); | ||
| const idleSnapshot = () => ({ cursor: { streamId: "test-stream", sequence: 0 } }); | ||
|
|
@@ -241,7 +241,7 @@ test("slow consumer receives a coalesced message_update on resume without a new | |
| try { | ||
| await subscribeSession(connection, reader, "s1", "test-sess-resume"); | ||
| // Consumer stalled: v1/v2 fill the queue, v3 is coalesced. Only a resumed | ||
| // pull() can deliver it — no heartbeat yet, no new event. | ||
| // pull() can deliver it — no heartbeat yet, no new event. | ||
| session.emit({ type: "message_update", message: { id: "m1", content: "v1" } }); | ||
| session.emit({ type: "message_update", message: { id: "m1", content: "v2" } }); | ||
| session.emit({ type: "message_update", message: { id: "m1", content: "v3" } }); | ||
|
|
@@ -477,3 +477,53 @@ test("file channel enforces the allow-list and reports content changes", { timeo | |
| assert.equal(change.data.type, "change"); | ||
| assert.equal(change.data.size, 7); | ||
| }); | ||
|
|
||
| test("the per-connection heartbeat is clamped to a safe range", () => { | ||
| assert.equal(parseHeartbeatSeconds("15"), 15); | ||
| assert.equal(parseHeartbeatSeconds("110"), 110); | ||
| assert.equal(parseHeartbeatSeconds(" 60 "), 60); | ||
| // Anything a client cannot be trusted with keeps the 30 s default. | ||
| for (const value of [null, undefined, "", "14", "111", "0", "-5", "15.5", "abc", "1e3"]) { | ||
| assert.equal(parseHeartbeatSeconds(value), 30, String(value)); | ||
| } | ||
| }); | ||
|
|
||
| test("a connection created with a custom interval emits its keep-alive at that interval", async () => { | ||
| const connection = new EventStreamConnection(undefined, 40); | ||
| const reader = connection.stream.getReader(); | ||
| const hello = await readFrame(reader); | ||
| assert.equal(hello.data.type, "hello"); | ||
| const started = Date.now(); | ||
| const heartbeat = await Promise.race([ | ||
| reader.read(), | ||
| new Promise((_, reject) => setTimeout(() => reject(new Error("no heartbeat within 2 s")), 2000)), | ||
| ]); | ||
| const elapsed = Date.now() - started; | ||
| assert.equal(decoder.decode(heartbeat.value), ":\n\n"); | ||
| assert.ok(elapsed < 1000, `heartbeat arrived after ${elapsed} ms`); | ||
| connection.close(); | ||
|
Comment on lines
+502
to
+504
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| }); | ||
|
|
||
| test("GET honours the heartbeat query parameter", async (t) => { | ||
| // Only the keep-alive interval is faked; readFrame's own watchdog stays real. | ||
| t.mock.timers.enable({ apis: ["setInterval"] }); | ||
| const ac = new AbortController(); | ||
| const res = route.GET(new Request("http://localhost/api/events?heartbeat=60", { signal: ac.signal })); | ||
| const reader = res.body.getReader(); | ||
| try { | ||
| assert.equal((await readFrame(reader)).data.type, "hello"); | ||
| let keepAliveArrived = false; | ||
| const keepAlive = reader.read().then((chunk) => { | ||
| keepAliveArrived = true; | ||
| return chunk; | ||
| }); | ||
| t.mock.timers.tick(30_000); | ||
| await setImmediate(); | ||
| assert.equal(keepAliveArrived, false, "no keep-alive before the requested 60 s"); | ||
| t.mock.timers.tick(30_000); | ||
| assert.equal(decoder.decode((await keepAlive).value), ":\n\n"); | ||
| } finally { | ||
| ac.abort(); | ||
| t.mock.timers.reset(); | ||
| } | ||
| }); | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: kahme247/ompweb
Length of output: 42731
Script executed:
Repository: kahme247/ompweb
Length of output: 38685
Script executed:
Repository: kahme247/ompweb
Length of output: 23299
Cancel in-flight system notification displays.
When dismissal arrives while
showSystemNotificationis still pending,dismissqueries notifications only once. The later display can remain visible. Track dismissed request IDs and close or suppress the notification after the display resolves.