From 20600a7d4a3aa6946b237a012804bc581cbffb39 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Fri, 6 Nov 2026 05:08:49 +0100 Subject: [PATCH 1/3] feat(api): app-info handshake and a per-connection heartbeat `GET /api/app-info` answers the package version, `api: 1` and the capabilities this server serves, so a native client can decide which features to use instead of probing for 404s. It rides the normal /api auth gate and carries no credential or configuration value. `GET /api/events?heartbeat=` lets a client choose its keep-alive between 15 and 110 seconds; out-of-range or malformed values keep the 30 s default, and the interval belongs to that connection only. --- app/api/app-info/route.ts | 22 ++++++++++++++ app/api/events/route.ts | 6 ++-- lib/app-info-route.test.mjs | 17 +++++++++++ lib/event-stream-hub.test.mjs | 54 ++++++++++++++++++++++++++++++++++- lib/event-stream-hub.ts | 29 +++++++++++++++---- server/routes.ts | 2 ++ 6 files changed, 122 insertions(+), 8 deletions(-) create mode 100644 app/api/app-info/route.ts create mode 100644 lib/app-info-route.test.mjs diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts new file mode 100644 index 000000000..3bf97adac --- /dev/null +++ b/app/api/app-info/route.ts @@ -0,0 +1,22 @@ +import packageJson from "../../../package.json"; + +/** + * 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. + * + * Every flag names a route or shape this server actually serves: a client that + * reads one and finds the feature missing would break, so a capability is added + * only together with its implementation. + */ +export function GET(): Response { + return Response.json({ + name: "ompweb", + version: packageJson.version, + api: 1, + capabilities: { + /** `GET /api/events?heartbeat=<15..110>` chooses this connection's keep-alive. */ + heartbeatParam: true, + }, + }, { headers: { "Cache-Control": "no-store" } }); +} diff --git a/app/api/events/route.ts b/app/api/events/route.ts index 0c163b7d9..98e6e2660 100644 --- a/app/api/events/route.ts +++ b/app/api/events/route.ts @@ -1,5 +1,5 @@ import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -import { EventStreamConnection, getEventStreamConnection } from "@/lib/event-stream-hub"; +import { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } from "@/lib/event-stream-hub"; import { parseEventStreamRequest, UNKNOWN_CONNECTION_CODE } from "@/lib/event-stream-protocol"; const MAX_REQUEST_BYTES = 16 * 1024; @@ -8,7 +8,9 @@ const MAX_REQUEST_BYTES = 16 * 1024; // Subscriptions are attached with POST (see lib/event-stream-protocol.ts). export function GET(req: Request, { disableIdleTimeout }: { disableIdleTimeout: () => void }) { disableIdleTimeout(); - const connection = new EventStreamConnection(req.signal); + // A native client may ask for a longer keep-alive (`?heartbeat=110`); the range is clamped server-side. + const heartbeat = parseHeartbeatSeconds(new URL(req.url).searchParams.get("heartbeat")); + const connection = new EventStreamConnection(req.signal, { heartbeatMs: heartbeat * 1000 }); return new Response(connection.stream, { headers: { "Content-Type": "text/event-stream", diff --git a/lib/app-info-route.test.mjs b/lib/app-info-route.test.mjs new file mode 100644 index 000000000..e1da07862 --- /dev/null +++ b/lib/app-info-route.test.mjs @@ -0,0 +1,17 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const route = await 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 every capability it serves", async () => { + const response = await route.GET(); + assert.equal(response.status, 200); + assert.equal(response.headers.get("cache-control"), "no-store"); + const body = await response.json(); + assert.equal(body.name, "ompweb"); + assert.equal(body.version, pkg.version); + assert.equal(body.api, 1); + assert.deepEqual(body.capabilities, { heartbeatParam: true }); +}); diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 637af130e..cd44a343b 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -17,7 +17,7 @@ after(() => { fs.rmSync(isolatedAgentDir, { recursive: true, force: true }); }); -const { EventStreamConnection, getEventStreamConnection, broadcastBrowserTransport } = await import("./event-stream-hub.ts"); +const { EventStreamConnection, getEventStreamConnection, broadcastBrowserTransport, parseHeartbeatSeconds } = await import("./event-stream-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"); @@ -850,3 +850,55 @@ test("a fresh outbox snapshot replaces the pending one when capacity returns bef done(); } }); + +test("the heartbeat query is clamped to 15..110 seconds", () => { + for (const value of [null, undefined, "", "abc", "0", "14", "111", "1e3", "-30", "100000"]) { + assert.equal(parseHeartbeatSeconds(value), 30, String(value)); + } + assert.equal(parseHeartbeatSeconds("15"), 15); + assert.equal(parseHeartbeatSeconds("30"), 30); + assert.equal(parseHeartbeatSeconds("110"), 110); + assert.equal(parseHeartbeatSeconds(" 60 "), 60); +}); + +test("GET /api/events applies the heartbeat query to that connection only", { timeout: 5000 }, async () => { + const open = async (query) => { + const ac = new AbortController(); + const response = route.GET(new Request(`http://localhost/api/events${query}`, { signal: ac.signal }), { disableIdleTimeout() {} }); + const reader = response.body.getReader(); + const hello = await readFrame(reader); + const connection = getEventStreamConnection(hello.data.connectionId); + assert.ok(connection); + return { connection, reader, ac }; + }; + const fast = await open("?heartbeat=17"); + const slow = await open("?heartbeat=500"); + const plain = await open(""); + try { + assert.equal(fast.connection.heartbeatMs, 17_000); + assert.equal(slow.connection.heartbeatMs, 30_000, "out-of-range values keep the default"); + assert.equal(plain.connection.heartbeatMs, 30_000); + } finally { + for (const { connection, reader } of [fast, slow, plain]) { + await reader.cancel(); + assert.equal(connection.isClosed, true); + } + } +}); + +test("the connection's keep-alive timer fires at the requested interval", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setInterval", "Date"], now: 1_000_000 }); + const connection = new EventStreamConnection(undefined, { heartbeatMs: 15_000 }); + const reader = connection.stream.getReader(); + try { + const hello = await readFrame(reader); + assert.equal(hello.event, "mux"); + t.mock.timers.tick(14_999); + t.mock.timers.tick(1); + const beat = await reader.read(); + assert.equal(decoder.decode(beat.value), ":\n\n"); + } finally { + connection.close(); + await reader.cancel(); + } +}); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 43b8686f7..0144c601b 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -26,7 +26,19 @@ import { isRecord } from "./type-guards"; // the browser's shared worker. // Heartbeat keeps the socket alive through reverse proxies that drop silent connections. +// A native client may ask for a longer one per connection (`/api/events?heartbeat=`). const HEARTBEAT_MS = 30_000; +export const MIN_HEARTBEAT_SECONDS = 15; +export const MAX_HEARTBEAT_SECONDS = 110; + +/** `?heartbeat=` in [15, 110]; anything else keeps the 30 s default. */ +export function parseHeartbeatSeconds(value: string | null | undefined): number { + if (typeof value !== "string" || !/^\d{1,4}$/.test(value.trim())) return HEARTBEAT_MS / 1000; + const seconds = Number(value.trim()); + if (seconds < MIN_HEARTBEAT_SECONDS || seconds > MAX_HEARTBEAT_SECONDS) return HEARTBEAT_MS / 1000; + return seconds; +} + const encoder = new TextEncoder(); export type SubscribeResult = @@ -85,11 +97,12 @@ export interface FrameSink { } class SseSink implements FrameSink { - readonly heartbeatMs = HEARTBEAT_MS; + readonly heartbeatMs: number; readonly stream: ReadableStream; private controller!: ReadableStreamDefaultController; - constructor(onPull: () => void, onCancel: () => void) { + constructor(onPull: () => void, onCancel: () => void, heartbeatMs = HEARTBEAT_MS) { + this.heartbeatMs = heartbeatMs; this.stream = new ReadableStream({ start: (controller) => { this.controller = controller; }, // A slow consumer resumed reading: deliver coalesced updates now rather @@ -149,13 +162,14 @@ export class EventStreamConnection { private readonly subscriptions = new Map(); private readonly signal: AbortSignal | undefined; - constructor(signal?: AbortSignal, sink?: FrameSink) { + /** `options.heartbeatMs` overrides the keep-alive for this connection's SSE sink. */ + constructor(signal?: AbortSignal, sink?: FrameSink | { heartbeatMs?: number }) { this.signal = signal; - if (sink) { + if (sink && "write" in sink) { this.sink = sink; this.stream = null; } else { - const sse = new SseSink(() => this.resume(), () => this.close()); + const sse = new SseSink(() => this.resume(), () => this.close(), sink?.heartbeatMs ?? HEARTBEAT_MS); this.sink = sse; this.stream = sse.stream; } @@ -186,6 +200,11 @@ export class EventStreamConnection { return this.closed; } + /** The keep-alive interval this connection's sink actually uses. */ + get heartbeatMs(): number { + return this.sink.heartbeatMs; + } + get subscriptionCount(): number { return this.subscriptions.size; } diff --git a/server/routes.ts b/server/routes.ts index f4be425be..081c07a6a 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -4,6 +4,7 @@ import * as agentIdBashOutput from "@/app/api/agent/[id]/bash-output/route"; import * as agentId from "@/app/api/agent/[id]/route"; import * as agentNew from "@/app/api/agent/new/route"; import * as agents from "@/app/api/agents/route"; +import * as appInfo from "@/app/api/app-info/route"; import * as appUpdateNotes from "@/app/api/app-update/notes/route"; import * as appUpdate from "@/app/api/app-update/route"; import * as authAccountsProvider from "@/app/api/auth/accounts/[provider]/route"; @@ -99,6 +100,7 @@ export const ROUTE_MODULES: Record = { "agent/[id]": agentId, "agent/new": agentNew, "agents": agents, + "app-info": appInfo, "app-update/notes": appUpdateNotes, "app-update": appUpdate, "auth/accounts/[provider]": authAccountsProvider, From fa8881149cd97d2283b867bdcd2be509771e8c84 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:57:03 +0100 Subject: [PATCH 2/3] test(events): assert the heartbeat never fires before its interval The keep-alive test waited out the advertised deadline and then read a frame, so an early heartbeat was already queued and passed: halving the interval went undetected. Keep one read pending across the wait and assert nothing arrives at 14,999 ms, then that exactly one comment frame arrives at 15,000 ms. Document the native-client contract alongside it: /api/app-info and the per-connection ?heartbeat= query in the live-stream contract, the reverse proxy read timeout a longer interval needs (nginx defaults to 60 s), and that out-of-range values fall back to the 30 s default instead of being clamped to a bound. --- AGENTS.md | 15 +++++++++++++++ README.md | 2 ++ app/api/events/route.ts | 3 ++- lib/event-stream-hub.test.mjs | 18 ++++++++++++++---- lib/event-stream-protocol.ts | 11 +++++++++++ 5 files changed, 44 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b49984576..36506f4fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -953,6 +953,21 @@ during the wait. CLOSED = fatal (e.g. 409 for a wrapper-less session; the chat hook then retries with backoff). Dead tabs are detected with a lifetime Web Lock — MessagePort has no close event. +- **Native-client handshake and keep-alive.** `GET /api/app-info` (behind the + normal `/api` auth gate) answers `{ name, version, api: 1, capabilities }` + with `Cache-Control: no-store`: package identity and which server-side + features exist, never a credential or configuration value. A capability is + added only together with its implementation, so a client may branch on it + instead of probing for 404s. Today it carries `heartbeatParam`. + `GET /api/events?heartbeat=` sets that one connection's keep-alive + (an idle stream gets a `:` comment frame): an integer in 15..110, otherwise + the 30 s default — out-of-range values fall back to the default, they are + not clamped to the nearest bound. The interval is per connection; other + connections and the browser link's own 15 s ping are unchanged. A value + above the reverse proxy's read timeout (nginx defaults to 60 s) disconnects + an idle stream before its first keep-alive, so a client selecting 110 s + needs a proxy read timeout above 110 s (see the README's reverse-proxy + section); the 30 s default needs one above 30 s. - Channels (`lib/event-stream-hub.ts`): `running` (sidebar badges + session-list hints), `notifications` (one tab's toasts and in-page system notifications, keyed by its `clientId`), `hosts` (the `GET /api/hosts` body on diff --git a/README.md b/README.md index 410765182..566e73245 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,8 @@ restart, without signing out of Windows. Forward WebSocket upgrades on `/api/events/link` (browsers) and `/api/hosts/link` (hosts); without the upgrade, a browser falls back to server-sent events after a few seconds. In nginx that means `proxy_http_version 1.1;`, `proxy_set_header Upgrade $http_upgrade;`, `proxy_set_header Connection "upgrade";`, and a `proxy_read_timeout` well above 30 s. +A server-sent-events client keeps its stream alive with a comment frame every 30 s by default; `GET /api/events?heartbeat=` (15 to 110) chooses another interval for that connection. A value outside that range falls back to the 30 s default. The proxy's read timeout must stay above the interval the client asks for: nginx's default `proxy_read_timeout` is 60 s, so a client selecting 110 s needs a timeout above 110 s (for example `proxy_read_timeout 120s;`), or the proxy drops the idle stream before its first keep-alive. `GET /api/app-info` tells a native client whether the server supports the query. + ### Two services: the web server and the local daemon ompweb runs this machine's `omp` sessions through a small daemon, `ompweb host`, diff --git a/app/api/events/route.ts b/app/api/events/route.ts index 98e6e2660..38b0c3ba6 100644 --- a/app/api/events/route.ts +++ b/app/api/events/route.ts @@ -8,7 +8,8 @@ const MAX_REQUEST_BYTES = 16 * 1024; // Subscriptions are attached with POST (see lib/event-stream-protocol.ts). export function GET(req: Request, { disableIdleTimeout }: { disableIdleTimeout: () => void }) { disableIdleTimeout(); - // A native client may ask for a longer keep-alive (`?heartbeat=110`); the range is clamped server-side. + // A native client may ask for a longer keep-alive (`?heartbeat=110`); values + // outside 15..110 fall back to the 30 s default rather than being clamped. const heartbeat = parseHeartbeatSeconds(new URL(req.url).searchParams.get("heartbeat")); const connection = new EventStreamConnection(req.signal, { heartbeatMs: heartbeat * 1000 }); return new Response(connection.stream, { diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index cd44a343b..69ad96c51 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -851,7 +851,7 @@ test("a fresh outbox snapshot replaces the pending one when capacity returns bef } }); -test("the heartbeat query is clamped to 15..110 seconds", () => { +test("the heartbeat query falls back to the 30 s default outside 15..110 seconds", () => { for (const value of [null, undefined, "", "abc", "0", "14", "111", "1e3", "-30", "100000"]) { assert.equal(parseHeartbeatSeconds(value), 30, String(value)); } @@ -886,17 +886,27 @@ test("GET /api/events applies the heartbeat query to that connection only", { ti } }); -test("the connection's keep-alive timer fires at the requested interval", { timeout: 5000 }, async (t) => { +test("the connection's keep-alive timer fires at the requested interval, never earlier", { timeout: 5000 }, async (t) => { t.mock.timers.enable({ apis: ["setInterval", "Date"], now: 1_000_000 }); const connection = new EventStreamConnection(undefined, { heartbeatMs: 15_000 }); const reader = connection.stream.getReader(); try { const hello = await readFrame(reader); assert.equal(hello.event, "mux"); + // One read stays pending across the wait: an early heartbeat settles it and + // fails here, instead of being read back after the advertised deadline. + const beat = reader.read(); t.mock.timers.tick(14_999); + assert.equal( + await Promise.race([ + beat.then(() => "beat"), + new Promise((resolve) => setTimeout(() => resolve("none"), 100)), + ]), + "none", + "no heartbeat before the requested interval", + ); t.mock.timers.tick(1); - const beat = await reader.read(); - assert.equal(decoder.decode(beat.value), ":\n\n"); + assert.equal(decoder.decode((await beat).value), ":\n\n", "one heartbeat at the requested interval"); } finally { connection.close(); await reader.cancel(); diff --git a/lib/event-stream-protocol.ts b/lib/event-stream-protocol.ts index 6b0cee5bd..4ec18ddd4 100644 --- a/lib/event-stream-protocol.ts +++ b/lib/event-stream-protocol.ts @@ -12,6 +12,17 @@ // Every frame also carries `id: `, read as `lastEventId`. // Subscriptions are added/removed with POST /api/events (EventStreamRequest). // +// Keep-alive: the server writes a comment frame (`:\n\n`) on an idle stream, +// 30 s by default. A native client may ask for another interval with +// `GET /api/events?heartbeat=`; the value belongs to that connection +// only, must be an integer in [15, 110], and anything else (absent, malformed, +// out of range) falls back to the 30 s default rather than being clamped. +// A longer interval needs a reverse-proxy read timeout above it: nginx's +// default `proxy_read_timeout` is 60 s, so `heartbeat=110` disconnects an idle +// stream there before its first keep-alive. Keep the proxy timeout above the +// requested interval (e.g. 120 s for 110 s) or request a shorter one. +// `GET /api/app-info` advertises `capabilities.heartbeatParam` for this query. +// // The browser link (`browserTransport` "ws"; lib/browser-link.ts, docs/specs/2026-11-01-browser-link-design.md): // one WebSocket per browser at GET /api/events/link, carrying every subscription and every agent command with the // host link's sequencing, pieces and fair queues (lib/hosts/link-protocol.ts). Its `e` messages carry exactly the From de5aba9bb3a8ff21fd62a6b83922c1ea9d4580f4 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:43:33 +0100 Subject: [PATCH 3/3] test(events): observe the armed heartbeat interval instead of a getter The route test read the new EventStreamConnection.heartbeatMs getter, which had no production caller: it echoed the sink's value rather than proving the route armed that interval. Drop the getter and assert the real keep-alive timing per connection under mocked timers, so an ignored ?heartbeat= query or a halved interval now fails. --- lib/event-stream-hub.test.mjs | 25 +++++++++++++++++++++---- lib/event-stream-hub.ts | 5 ----- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 69ad96c51..27c45c5c0 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -861,7 +861,8 @@ test("the heartbeat query falls back to the 30 s default outside 15..110 seconds assert.equal(parseHeartbeatSeconds(" 60 "), 60); }); -test("GET /api/events applies the heartbeat query to that connection only", { timeout: 5000 }, async () => { +test("GET /api/events applies the heartbeat query to that connection only", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setInterval", "Date"], now: 1_000_000 }); const open = async (query) => { const ac = new AbortController(); const response = route.GET(new Request(`http://localhost/api/events${query}`, { signal: ac.signal }), { disableIdleTimeout() {} }); @@ -874,10 +875,26 @@ test("GET /api/events applies the heartbeat query to that connection only", { ti const fast = await open("?heartbeat=17"); const slow = await open("?heartbeat=500"); const plain = await open(""); + // One pending read per connection: a heartbeat settles it, so the interval + // the route actually armed is observed, not a getter's echo of it. + const reads = { fast: fast.reader.read(), slow: slow.reader.read(), plain: plain.reader.read() }; + const outcome = (read) => Promise.race([ + read.then(() => "beat"), + new Promise((resolve) => setTimeout(() => resolve("none"), 100)), + ]); try { - assert.equal(fast.connection.heartbeatMs, 17_000); - assert.equal(slow.connection.heartbeatMs, 30_000, "out-of-range values keep the default"); - assert.equal(plain.connection.heartbeatMs, 30_000); + t.mock.timers.tick(16_999); + assert.equal(await outcome(reads.fast), "none", "no heartbeat before the requested 17 s"); + assert.equal(await outcome(reads.slow), "none"); + assert.equal(await outcome(reads.plain), "none"); + t.mock.timers.tick(1); + assert.equal(await outcome(reads.fast), "beat", "the requested 17 s interval"); + assert.equal(decoder.decode((await reads.fast).value), ":\n\n"); + assert.equal(await outcome(reads.slow), "none", "out-of-range values keep the default"); + assert.equal(await outcome(reads.plain), "none", "no query keeps the default"); + t.mock.timers.tick(13_000); + assert.equal(await outcome(reads.slow), "beat", "the 30 s default interval"); + assert.equal(await outcome(reads.plain), "beat", "the 30 s default interval"); } finally { for (const { connection, reader } of [fast, slow, plain]) { await reader.cancel(); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 0144c601b..5230737b8 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -200,11 +200,6 @@ export class EventStreamConnection { return this.closed; } - /** The keep-alive interval this connection's sink actually uses. */ - get heartbeatMs(): number { - return this.sink.heartbeatMs; - } - get subscriptionCount(): number { return this.subscriptions.size; }