Skip to content
Merged
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
10 changes: 8 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ app/api/
hosts/cluster-config/file/[hash]/route.ts GET one file of the current manifest by its sha256 (404 for any other hash, an older version's included); same admission and gate as the manifest
hosts/[id]/cluster/route.ts PUT { projectsRoot } join the cluster (the host's Git projects bind to cluster projects by repository, `gitOrigins`; this machine is added too by any join while it is not a member; the host needs link protocol 10; 409 `host_in_other_cluster` when it holds another server's configuration), then sends the host its configuration (`clusterConfigOp` `apply`) | DELETE leave, then `restore` (none to a daemon below protocol 10, which never applied one); the body carries `restoreError` when the host could not put its own configuration back; 409 `{ error, code }` for offline/old daemon/`cluster_changed`, 503 if `pools.json` is unreadable
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 @@ -2068,8 +2069,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
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,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. 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 without a structured payload resolves; one whose decision text (from/to/delivery/cwd) cannot be represented publishes no dialog and only opens the session. An offline host or a restarting session is reported instead of silently dropping the answer, 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 dialog is only carried when it fits exactly: a title, confirmation message, question or option label that would have to be shortened makes the notification only open the session, and that request is not answerable from the notification either, so an approval is never shown and answered from its harmless prefix. The same fallback covers decision text the notification cannot show at all: a server-owned confirmation, an option description or preview, a question header, and a secret input.

### 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
2 changes: 1 addition & 1 deletion docs/plans/2026-10-29-local-daemon.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
}
// hello: channels: { ch: string; sessionId: string | null; pending: string[] | null }[]
```
Opened by `host_tool_call` and `extension_ui_request` with a method in `BLOCKING_UI_METHODS` (import from `lib/notification-events.ts` if it has no next/@ imports, else move the constant to a shared module). Closed by `host_tool_result`/`extension_ui_response` with the same id on stdin, or `host_tool_cancel` (`targetId`) / an `extension_ui_request` cancel frame from omp. A chunked frame's raw `rpc_chunk` lines are kept together.
Opened by `host_tool_call` and `extension_ui_request` with a blocking dialog method (`select`, `confirm`, `input`, `editor`, `askDialog`, `formDialog` or `approve`). Closed by `host_tool_result`/`extension_ui_response` with the same id on stdin, or `host_tool_cancel` (`targetId`) / an `extension_ui_request` cancel frame from omp. A chunked frame's raw `rpc_chunk` lines are kept together.
- [ ] **Step 1: Failing tests** — `pending-requests.test.mjs`: an `ask` request then its `extension_ui_response` → `lines()` is `[]`; an open `host_tool_call` → `lines()` holds its raw line; a request split into three `rpc_chunk` lines → `lines()` holds all three in order; `host_tool_cancel` with `targetId` closes the call; past `limitBytes` → `null`; a non-blocking `notify` UI request is not kept. `daemon.test.mjs`: after a link drop the next `hello` carries the open request's line for its channel.
- [ ] **Step 2: Run** `node --experimental-strip-types --test lib/hosts/pending-requests.test.mjs lib/hosts/daemon.test.mjs` → FAIL.
- [ ] **Step 3: Implement**; bump `LINK_PROTOCOL_VERSION` to 3 and update `decodeUp` for the new hello field.
Expand Down
Loading
Loading