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
15 changes: 15 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<seconds>` 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
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<seconds>` (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`,
Expand Down
22 changes: 22 additions & 0 deletions app/api/app-info/route.ts
Original file line number Diff line number Diff line change
@@ -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" } });
}
7 changes: 5 additions & 2 deletions app/api/events/route.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -8,7 +8,10 @@ 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`); 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 });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return new Response(connection.stream, {
headers: {
"Content-Type": "text/event-stream",
Expand Down
17 changes: 17 additions & 0 deletions lib/app-info-route.test.mjs
Original file line number Diff line number Diff line change
@@ -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 });
});
81 changes: 80 additions & 1 deletion lib/event-stream-hub.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -850,3 +850,82 @@ test("a fresh outbox snapshot replaces the pending one when capacity returns bef
done();
}
});

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));
}
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 (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() {} });
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("");
// 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 {
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();
assert.equal(connection.isClosed, true);
}
}
});

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);
assert.equal(decoder.decode((await beat).value), ":\n\n", "one heartbeat at the requested interval");
} finally {
connection.close();
await reader.cancel();
}
});
24 changes: 19 additions & 5 deletions lib/event-stream-hub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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=<seconds>` 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 =
Expand Down Expand Up @@ -85,11 +97,12 @@ export interface FrameSink {
}

class SseSink implements FrameSink {
readonly heartbeatMs = HEARTBEAT_MS;
readonly heartbeatMs: number;
readonly stream: ReadableStream<Uint8Array>;
private controller!: ReadableStreamDefaultController<Uint8Array>;

constructor(onPull: () => void, onCancel: () => void) {
constructor(onPull: () => void, onCancel: () => void, heartbeatMs = HEARTBEAT_MS) {
this.heartbeatMs = heartbeatMs;
this.stream = new ReadableStream<Uint8Array>({
start: (controller) => { this.controller = controller; },
// A slow consumer resumed reading: deliver coalesced updates now rather
Expand Down Expand Up @@ -149,13 +162,14 @@ export class EventStreamConnection {
private readonly subscriptions = new Map<string, Subscription>();
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;
}
Expand Down
11 changes: 11 additions & 0 deletions lib/event-stream-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@
// Every frame also carries `id: <server ms at emit>`, 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=<seconds>`; 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
Expand Down
2 changes: 2 additions & 0 deletions server/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -99,6 +100,7 @@ export const ROUTE_MODULES: Record<string, RouteModule> = {
"agent/[id]": agentId,
"agent/new": agentNew,
"agents": agents,
"app-info": appInfo,
"app-update/notes": appUpdateNotes,
"app-update": appUpdate,
"auth/accounts/[provider]": authAccountsProvider,
Expand Down
Loading