Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1808,10 +1809,29 @@ 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.
- A tab may declare its notification device with its stream
(`{kind: "notifications", clientId, deviceId}`); a malformed declaration is
refused at the channel boundary. Such a tab is reachable **without** a
presence report, which is how a native client with no push subscription
receives deliveries. Stream-only delivery is routed through that device's own
stored prefs, so the device must also be registered with
`PUT /api/notifications/devices` — declaring the id alone delivers nothing.
It never overrides the two rules above: a visible tab elsewhere still
silences the event, and a `whenActive: "toast"` device still gets only a
toast on its active tabs, so a background app can intentionally stay quiet.
The `deviceId` is syntax-checked, not bound to the caller's own device: any
authenticated tab of the same user may declare another device's id and would
then receive that device's `os` frames.
- 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`,
tab's notification client id, `deviceId` = the device it belongs to when it
declares one), opened by `useNotifications` in `AppShell`,
so a tab stays reachable on every view, Settings included. A tab on
Settings is visible, so it also counts as active.
- Prefs and push subscriptions are per device, in `localStorage` and mirrored to
Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,17 @@ 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 <host>**, **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 device can receive notifications on its open stream without a presence
report.** A native client with no push subscription keeps a `notifications`
stream open and declares its device id on it; the server then delivers to
that stream through the device's own stored preferences, so the device must
also be registered with `PUT /api/notifications/devices`. A malformed device
declaration is refused at the channel boundary. This never overrides the
existing rules: a visible tab on the session still silences the event, and a
device set to toast while active still gets only a toast on its active tabs,
so a background app can intentionally stay quiet.

### Fixes & Improvements

Expand Down
75 changes: 75 additions & 0 deletions app/api/notifications/answer/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
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, 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) {
let body: unknown;
try {
body = await parseJsonWithinLimit<unknown>(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);
}
}
59 changes: 59 additions & 0 deletions components/ui/toast.click.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand Down
Loading