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
192 changes: 175 additions & 17 deletions AGENTS.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

### Fixes & Improvements

- **Streaming replies use about a sixth of the bandwidth.** ompweb now asks omp (18.13.2 or later) for only what changed in a streaming reply instead of the whole reply several times a second, and the browser rebuilds the reply itself. In one measured reply the live stream fell from 232 KB to 91 KB, and the reply updates themselves from 178 KB to 30 KB, so replies keep up on slow mobile links. A tab opened mid-reply, a reconnect and a restarted server still show the whole reply. An older omp keeps sending whole replies and works as before.
- **The host link is now one WebSocket**, with fewer requests and large results sent in the same connection. A reverse proxy in front of ompweb must forward WebSocket upgrades on `/api/hosts/link` (see the README's hosts section). Update ompweb on the server first, then on its hosts: a host linked with an earlier build of this release shows **needs upgrade** until it is updated.
- **The browser connection is now one WebSocket that survives drops.** Settings → Interface & Behavior → **Browser connection** now defaults to the **WebSocket link**: one connection per browser that carries live updates and chat commands with the same delivery as the host link. A large event no longer delays a command's answer, a slow answer never resets the connection, and after a short drop (up to 2 minutes) the connection picks up exactly where it stopped, without reloading the chat (if more than 32 MiB of updates piled up meanwhile, it reloads the chat instead). Longer outages and server restarts reload as before; a command that cannot be confirmed still says it may have run. The proxy must forward WebSocket upgrades on `/api/events/link`; a browser whose proxy refuses the upgrade falls back to server-sent events on its own. To use server-sent events + HTTP all the time, switch the setting back to it in Settings. The earlier experimental WebSocket choices are gone and read as the default.
- **ompweb now runs on Bun instead of Next.js.** The npm package brings its own Bun, so installs and updates work as before, with no change to URLs, ports, settings or the password gate. `OMP_WEB_DEV_ORIGIN` is removed: it only configured the Next development server. `npm run build` no longer interferes with `npm run dev`. The skills.sh search now gives up after 10 s and falls back to the `skills find` CLI instead of waiting on a stalled skills.sh.
- **If you start ompweb from a terminal (`ompweb` or `npx`), start it again once after the in-app update to this version.** The launcher that is already running applies the update and then tries to restart the server with Next, which the update removed, so the server does not come back. systemd, launchd and the tray start the new launcher and are not affected.
- Browsers older than Safari 16.2 or Chrome 111 lose the colours ompweb mixes with `color-mix()` (tints, borders and focus rings), which no longer carry a solid fallback. Those browsers were outside the Next.js build's targets too.
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ your user or system environment (for example `setx OMP_WEB_PASSWORD_HASH
started with. Changing or removing the hash takes effect at the next server
restart, without signing out of Windows.

### Behind a reverse proxy

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.

### Two services: the web server and the local daemon

ompweb runs this machine's `omp` sessions through a small daemon, `ompweb host`,
Expand Down Expand Up @@ -468,7 +472,7 @@ everything else on it: they resume when it wakes, and the link returns then. A
docked or no-sleep setup keeps running with the lid closed. Revoking a host in
Settings closes its link and the daemon stops its omp processes.

Behind a reverse proxy, forward WebSocket upgrades on `/api/hosts/link` (nginx: `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 reverse proxy must forward the upgrade on `/api/hosts/link`; see [Behind a reverse proxy](#behind-a-reverse-proxy).

Update ompweb on the server before its hosts: a host from before this version shows **needs upgrade** until it is updated.

Expand Down
142 changes: 16 additions & 126 deletions app/api/agent/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,14 @@
import { apiErrorResponse, hostOfflineResponse, resolveSessionHostOr404 } from "@/lib/api-utils";
import { startRpcSession, getRpcSession, WebRpcError } from "@/lib/rpc-manager";
import { sessionSpawnTarget } from "@/lib/hosts/session-index";
import { RpcCommandError } from "@/lib/omp/rpc-process";
import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data";
import { getRpcSession, WebRpcError } from "@/lib/rpc-manager";
import { commandErrorResponse, runAgentCommand } from "@/lib/agent-command";
import { parseJsonWithinLimit } from "@/lib/bounded-form-data";
import { MAX_AGENT_COMMAND_REQUEST_BYTES } from "@/lib/image-attachments";

// Commands that ride whatever child is alive and never spawn or replace one:
// keystroke predictions, and the side-question reads/cancel omp-web sends in
// the background (SSE connect, reconcile). Without a live process there is no
// ghost text, no running side question and nothing to cancel, so the reply is
// known without omp. Asking (`btw`) and opening the history start omp first.
const NO_SPAWN_REPLIES: Record<string, unknown> = {
predict_word: { suffix: null },
predict_word_feedback: null,
get_btw_history: { records: [] },
btw_cancel: { cancelled: false },
};

// Live diagnostics of a skill-resolving omp. A saved or exited session has none,
// and resuming a full child (MCP, LSP) just to answer a read-only inspection or
// flip one setting is not what the click asked for: with no live wrapper these
// answer 409 instead of starting omp, and a live idle child is never replaced
// because the advisor flag differs.
const LIVE_SESSION_ONLY = new Set(["get_skill_diagnostics", "set_skill_startup_diagnostics"]);

/** omp-web's own failures carry a stable code the client can localize; omp's
* errors stay opaque English text. */
function commandErrorResponse(error: unknown) {
if (error instanceof RequestBodyTooLargeError) {
return Response.json({ error: "Agent command is too large", code: "request_too_large" }, { status: 413 });
}
if (error instanceof SyntaxError) {
return Response.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 });
}
// host_offline falls through to apiErrorResponse: 503 {hostOffline: true}.
if (error instanceof WebRpcError && error.code !== "host_offline") {
return Response.json({ error: error.message, code: error.code }, { status: 400 });
}
if (error instanceof RpcCommandError) {
return Response.json({ error: error.message, code: error.code ?? "rpc_command_failed" }, { status: 400 });
}
return apiErrorResponse(error);
/** Stamp when the handler had the request and when it answered, so the browser
* can split network time from server time. */
function timed(receivedAt: number, res: Response): Response {
res.headers.set("x-omp-received-at", String(receivedAt));
res.headers.set("x-omp-replied-at", String(Date.now()));
return res;
}

// POST /api/agent/[id] - Send a command to an existing session
Expand All @@ -49,98 +17,20 @@ export async function POST(
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
// Once the body is in, as a socket's ack is stamped after its whole frame: proxies stream uploads through, so the
// handler starts before a large body has arrived. A body that fails to read is stamped when it failed.
let receivedAt: number | undefined;

try {
const body = await parseJsonWithinLimit<{ type?: unknown; [key: string]: unknown }>(req, MAX_AGENT_COMMAND_REQUEST_BYTES);
if (typeof body.type !== "string" || !body.type.trim()) {
return Response.json({ error: "command type is required", code: "command_type_required" }, { status: 400 });
}

const body = await parseJsonWithinLimit<unknown>(req, MAX_AGENT_COMMAND_REQUEST_BYTES);
receivedAt = Date.now();
// The per-chat advisor choice rides on the query string (never the RPC
// body, which is forwarded to omp verbatim) and only matters when this
// request spawns or replaces the session's omp process.
const advisor = new URL(req.url).searchParams.get("advisor") === "1";

// Fast path: already-running session. --advisor is a spawn-time flag with
// no runtime RPC, so a toggle that now differs from the live child's spawn
// flag must replace an idle child to take effect; busy children keep
// running and pick the flag up at the next natural respawn.
const existing = getRpcSession(id);
const noSpawn = Object.hasOwn(NO_SPAWN_REPLIES, body.type);
const liveOnly = LIVE_SESSION_ONLY.has(body.type);
if (existing?.isAlive()) {
if (noSpawn || liveOnly || existing.advisorSpawned === advisor || existing.isRunning() || existing.isEditingHistory()) {
const result = await existing.send(body);
return Response.json({ success: true, data: result });
}
// Disposing a child behind a down link would wait for the link to return.
const offline = hostOfflineResponse(existing.host);
if (offline) return offline;
await existing.destroyAndWait();
}
if (noSpawn) return Response.json({ success: true, data: NO_SPAWN_REPLIES[body.type] });
if (liveOnly) {
return Response.json(
{ error: "Skill diagnostics require a running session", code: "skill_diagnostics_unavailable" },
{ status: 409 },
);
}

const resolved = await resolveSessionHostOr404(id);
if ("response" in resolved) return resolved.response;
const { host } = resolved;
const offline = hostOfflineResponse(host);
if (offline) return offline;
const target = await sessionSpawnTarget(id, host);
if (!target) return Response.json({ error: "Session not found", code: "session_not_found" }, { status: 404 });

// A cold set_model must reach omp before the saved model is restored:
// spawning with only --resume lets omp exit on an unrestorable saved
// model before the RPC below ever runs (#277). Binding the requested
// model at spawn time skips that restore check. Live children never
// reach this path (they take the fast path above), and any other command
// keeps the previous spawn behavior.
const spawnModel =
body.type === "set_model" &&
typeof body.provider === "string" &&
typeof body.modelId === "string" &&
body.provider.trim() &&
body.modelId.trim() &&
!body.provider.startsWith("-") &&
!body.modelId.startsWith("-") &&
!/\s/.test(body.provider) &&
!/\s/.test(body.modelId)
? `${body.provider}/${body.modelId}`
: undefined;

const { session } = await startRpcSession(id, target.sessionFile, target.cwd, undefined, advisor, target.recordedCwd, spawnModel, host);
if (spawnModel) {
// Try the normal RPC first: when it succeeds it also records the new
// model in the session, so later spawns restore it without an override.
// But in omp 18.12.6 set_model can fail spuriously with "Model not
// found" for a catalog model whose provider has no credentials
// configured, even though the spawn already bound it. In that case the
// switch itself succeeded — verify from live state and report success
// rather than a false failure. A mismatch (e.g. an omp without --model
// precedence) rethrows the RPC error, so a real failure still surfaces.
try {
const result = await session.send(body);
return Response.json({ success: true, data: result });
} catch (error) {
const state = (await session.send({ type: "get_state" })) as {
model?: { id?: unknown; provider?: unknown };
} | null;
if (state?.model?.provider === body.provider && state?.model?.id === body.modelId) {
return Response.json({ success: true, data: { id: body.modelId, provider: body.provider } });
}
throw error;
}
}
const result = await session.send(body);

return Response.json({ success: true, data: result });
return timed(receivedAt, await runAgentCommand(id, body, advisor));
} catch (error) {
return commandErrorResponse(error);
return timed(receivedAt ?? Date.now(), commandErrorResponse(error));
}
}

Expand Down
7 changes: 7 additions & 0 deletions app/api/events/link/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { handleBrowserLinkUpgrade, type BrowserLinkData } from "@/lib/browser-link";

// GET /api/events/link — the browser link (lib/browser-link.ts); undefined once upgraded (server/app.ts). Gated like
// every API route: the password gate and origin check run before the upgrade, which binds the socket to its web session.
export function GET(req: Request, { upgrade }: { upgrade: (data: BrowserLinkData) => boolean }) {
return handleBrowserLinkUpgrade(req, upgrade);
}
26 changes: 26 additions & 0 deletions app/api/transport-metrics/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data";
import { appendTransportSamples } from "@/lib/transport-metrics";
import { isRecord } from "@/lib/type-guards";

const MAX_BODY_BYTES = 256 * 1024;
const MAX_SAMPLES = 1_000;

// GET /api/transport-metrics — the server clock, the SSE transport's clock probe.
export function GET() {
return Response.json({ now: Date.now() }, { headers: { "cache-control": "no-store" } });
}

// POST /api/transport-metrics { samples } — appended to <agent dir>/omp-web/transport-metrics.jsonl.
export async function POST(req: Request) {
let body: unknown;
try {
body = await parseJsonWithinLimit(req, MAX_BODY_BYTES);
} catch (error) {
if (error instanceof RequestBodyTooLargeError) return Response.json({ error: "Transport metrics request is too large", code: "request_too_large" }, { status: 413 });
body = null;
}
if (!isRecord(body) || !Array.isArray(body.samples) || body.samples.length > MAX_SAMPLES) {
return Response.json({ error: "samples must be an array of at most 1000 objects", code: "invalid_transport_metrics" }, { status: 400 });
}
return Response.json({ written: appendTransportSamples(body.samples, req.headers.get("user-agent")) });
}
18 changes: 16 additions & 2 deletions app/api/web-settings/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { broadcastBrowserTransport } from "@/lib/event-stream-hub";
import { BROWSER_TRANSPORTS } from "@/lib/event-stream-protocol";
import { syncInterruptibleSessions } from "@/lib/rpc-manager";
import { parseAgentEnvText, sanitizeAgentEnvValues, type AgentEnvParseResult } from "@/lib/omp/agent-env";
import { loadWebServerSettings, saveWebServerSettings, type WebServerSettings } from "@/lib/web-settings";
import { browserTransportState, loadWebServerSettings, saveWebServerSettings, type WebServerSettings } from "@/lib/web-settings";
import { isRecord } from "@/lib/type-guards";

/** GET/PUT /api/web-settings - omp-web's own server-side settings. */
Expand All @@ -24,7 +26,7 @@ export async function PUT(req: Request) {
if (!isRecord(body)) {
return Response.json({ error: "Request body must be a settings object", code: "invalid_settings" }, { status: 400 });
}
const payload = body as { autoResumeSessions?: unknown; agentToolsEnabled?: unknown; agentEnv?: unknown };
const payload = body as Partial<Record<keyof WebServerSettings, unknown>>;
const patch: Partial<WebServerSettings> = {};

// Both keys are optional so a caller can update one without reading the other;
Expand All @@ -45,6 +47,14 @@ export async function PUT(req: Request) {
patch.agentToolsEnabled = payload.agentToolsEnabled;
}

if (payload.browserTransport !== undefined) {
const transport = BROWSER_TRANSPORTS.find((value) => value === payload.browserTransport);
if (!transport) {
return Response.json({ error: `browserTransport must be one of ${BROWSER_TRANSPORTS.map((value) => `"${value}"`).join(", ")}`, code: "invalid_settings" }, { status: 400 });
}
patch.browserTransport = transport;
}

if (payload.agentEnv !== undefined) {
// Either raw KEY=VALUE text (what the settings textarea holds) or a record.
let parsed: AgentEnvParseResult;
Expand All @@ -67,9 +77,13 @@ export async function PUT(req: Request) {
patch.agentEnv = parsed.values;
}

const previousTransport = JSON.stringify(browserTransportState());
const settings = saveWebServerSettings(patch);
// Apply to sessions that are already running, not only the next run. Only when the
// flag was part of this save — an agentEnv-only write must not touch live sessions.
if (resumeProvided) syncInterruptibleSessions();
// Every open browser converges on the new state; an unchanged one is not sent (the worker ignores it anyway).
const transport = browserTransportState(settings);
if (JSON.stringify(transport) !== previousTransport) broadcastBrowserTransport(transport);
return Response.json({ ...settings, agentEnv: sanitizeAgentEnvValues(settings.agentEnv).values });
}
Loading
Loading