Skip to content
Closed
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: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,18 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

### Fixes & Improvements

- **A busy omp is no longer killed by a slow answer.** Every command timeout used to destroy the child and report `session_unresponsive`; omp blocks its event loop for tens of seconds on large sessions, so a status poll that timed out looked like a dead session and recycled a live run. A timeout now keeps the child and answers `503 session_slow` on the status routes: the web UI retries the poll, a prompt that may already have reached omp is reported as `maybeStarted` instead of being dropped, and an unconfirmed abort says so. Only a child that produced no frame and no answer for five minutes (`OMP_WEB_STALL_DESTROY_MS`, `0` disables) is reaped; it is recorded as `exited` with `detail: "stalled"`. Stop still reaches the child when its command queue is full, and a prompt whose ack timed out keeps the child until that stall window instead of the shorter disconnect cleanup.
- **An idle session no longer looks like a working one.** The agent routes distinguish `running` (a turn is in flight) from `alive` (the child exists), so a freshly spawned omp that is still loading a large session stops showing a busy chat. While a run is marked but the child sends no events, the answer carries `silentForMs` and the composer appends "no events for N min" past three minutes. The 503 reports the child's real `alive` state, and a session switch whose ack timed out is rekeyed once a later state read shows the new identity, so the old id stops routing to the new conversation.
- **Renaming a session cannot be written behind the live child's back.** A rename that times out answers 503 instead of falling back to the on-disk title slot, which the child would overwrite on its next flush.
- **A rejected background task no longer ends the server.** An unhandled rejection is journaled and logged (rate-limited) while the server keeps serving; uncaught exceptions keep their crash semantics.
- **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails.
- **An update whose worker died is reported as failed.** A running update whose worker process is gone, or whose lease has expired, now becomes a failed attempt the dialog can show and clean up, instead of waiting forever.
- **A chat another omp process owns is no longer silently forked.** omp ≥ 18.5 grants one writer per session file; a second `--resume` does not fail, it moves the conversation into a copy on its first write, which looked like a brand-new empty chat. omp-web now detects a foreign owner from portable read-only signals (another omp-web instance's resume list, a live `omp --resume` process, a transcript that is still being written; `OMP_WEB_FOREIGN_SCAN=0` disables only the process scan), marks the chat in the sidebar and composer, and refuses to spawn: `POST /api/agent/[id]` answers `409 session_running_elsewhere`, auto-naming and session resume skip it, and `/api/mcp` reports the live server list as unavailable. An explicit "Send anyway (copy)" sends with `?force=1`; a move that follows it is reported as `session_contention_fork` with links to both the original and the copy. Spawned service and scan children no longer inherit omp-web's own secrets on non-Windows platforms.
- **The sidebar keeps the ownership map the live stream delivered.** A session-list request that was already in flight can no longer replace a newer ownership snapshot, so foreign-session badges do not blink out until the next frame, and a foreign owner that is idle between turns no longer counts as a running session in the project totals or the running filter.
- **A confirmed "Send anyway" also covers shell commands.** A `!` command now forwards the confirmation as `?force=1`, so a chat another omp process owns runs the copy the user just approved instead of answering `session_running_elsewhere`.
- **A chat whose prompt never started still reports its child's death.** The exit notification is published before the terminal event clears the run flags, so a prompt that reached omp's stdin without an `agent_start` no longer loses the stall/crash notice. A late answer to a timed-out poll no longer resets the no-events clock, so a silent run stays measurable.
- **A timed-out preset on a fresh session no longer leaves an orphaned child.** When `set_model`/`set_thinking_level` times out during an `ensure_session` request, the route destroys the child it can never hand out; a session-owner refresh that lands while another scan is running is queued for the next pass instead of being dropped; and an exited child no longer keeps reporting the pid the ownership scan should ignore.
- **Naming a session no longer clears another chat's naming indicator.** A title-less auto-name response now honours the same active-session guard as the titled and error branches.

---

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ host (KDE Plasma, and most Wayland/X11 desktops).
| `OMP_WEB_DISABLE_AUTOUPDATE` | Set to `1` to disable update checks and in-app updates; restart after changing | `0` |
| `OMP_WEB_NAME` | Name shown in browser tabs and installed-app names. `url`, `host` or `domain` (any case) uses the hostname the browser connected to, without port; localhost and IP addresses keep `omp web`. Any other value is used as-is. Restart after changing | `omp web` |
| `OMP_WEB_OMP_BIN` | Path to `omp` binary if not on `PATH` | _auto-detected_ |
| `OMP_WEB_FOREIGN_SCAN` | Set to `0` to stop scanning the OS process table for `omp --resume <session>` owners (10 s cache). The other ownership signals stay active: a session held by another omp-web instance is still detected from its resume list, and a session file that is still being written is detected from its transcript. A terminal `omp` that sits idle on a file is then no longer detected | `1` (enabled) |
| `OMP_WEB_DEV_ORIGIN` | Additional allowed hostname for the development server (no scheme or port); ignored in production | _None_ |
| `PI_CODING_AGENT_DIR` | Custom omp agent directory | `~/.omp/agent` |
| `OMP_WEB_STT_ENDPOINT` | OpenAI-compatible transcription endpoint URL. Leave unset to transcribe with `OMP_WEB_STT_MODEL` through omp's own credentials | _None_ |
Expand Down
68 changes: 61 additions & 7 deletions app/api/agent/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { NextResponse } from "next/server";
import { readSessionHeader } from "@/lib/session-reader";
import { readSessionHeader, resolveSessionPath } from "@/lib/session-reader";
import { apiErrorResponse, resolveSessionPathOr404 } from "@/lib/api-utils";
import { startRpcSession, getRpcSession, resolveSpawnCwdResult, WebRpcError } from "@/lib/rpc-manager";
import { startRpcSession, getOwnChildPids, getRpcSession, isLocallyOwnedSession, isOwnCrashedSession, resolveSpawnCwdResult, WebRpcError } from "@/lib/rpc-manager";
import { detectSessionOwner } from "@/lib/session-owner";
import { RpcCommandError } from "@/lib/omp/rpc-process";
import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data";
import { MAX_AGENT_COMMAND_REQUEST_BYTES } from "@/lib/image-attachments";
Expand Down Expand Up @@ -35,7 +36,7 @@ function commandErrorResponse(error: unknown) {
return NextResponse.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 });
}
if (error instanceof WebRpcError) {
return NextResponse.json({ error: error.message, code: error.code }, { status: 400 });
return NextResponse.json({ error: error.message, code: error.code, ...error.details }, { status: 400 });
}
if (error instanceof RpcCommandError) {
return NextResponse.json({ error: error.message, code: error.code ?? "rpc_command_failed" }, { status: 400 });
Expand Down Expand Up @@ -87,6 +88,29 @@ export async function POST(
if ("response" in resolved) return resolved.response;
const filePath = resolved.filePath;

// omp ≥ 18.5 grants one writer per session. A second `--resume` does not
// fail: it silently moves the conversation to a copy on its first write,
// which is exactly the "new chat appeared from nowhere" bug. Refuse the
// spawn (409) unless the client explicitly asked for the copy.
const force = new URL(req.url).searchParams.get("force") === "1";
if (!force) {
const elsewhere = await detectSessionOwner(id, filePath, {
isLocal: isLocallyOwnedSession,
ownCrashed: isOwnCrashedSession,
excludePids: getOwnChildPids(),
});
if (elsewhere) {
return NextResponse.json(
{
error: "This session is being run by another omp process",
code: "session_running_elsewhere",
elsewhere,
},
{ status: 409 },
);
}
}

const header = readSessionHeader(filePath);
const { cwd } = resolveSpawnCwdResult(header?.cwd);

Expand Down Expand Up @@ -150,14 +174,44 @@ export async function GET(
try {
const session = getRpcSession(id);
if (!session || !session.isAlive()) {
return NextResponse.json({ running: false });
// Not ours: tell the client who is running it, if anyone. Never spawns.
const filePath = await resolveSessionPath(id).catch(() => null);
const elsewhere = filePath
? await detectSessionOwner(id, filePath, { isLocal: isLocallyOwnedSession, ownCrashed: isOwnCrashedSession, excludePids: getOwnChildPids() })
: null;
return NextResponse.json({ running: false, alive: false, elsewhere });
}
try {
const state = await session.send({ type: "get_state" });
return NextResponse.json({ running: true, state });
// `running` is the run, `alive` the child. A live omp that is merely idle
// (freshly spawned, between turns) must never look like a run in flight,
// or every client shows a working state over a chat nobody asked anything.
// `get_state` reconciled the wrapper's flags above, so the run state is
// authoritative here.
return NextResponse.json({ running: session.isRunning(), alive: true, state, elsewhere: null });
} catch (error) {
if (error instanceof WebRpcError && error.code === "session_unresponsive") {
return NextResponse.json({ running: false, recovered: true });
// omp being slow is not the run ending: answer 503 so clients retry the
// poll instead of treating the session as idle/recovered. 0.6.0's own
// get_state timeout reports `session_state_timeout`; native clients know
// only one "still running, retry" state, so both codes answer as
// `session_slow`.
if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) {
// A blocked child answers nothing, so this 503 is the client's only
// chance to learn how long the run it still shows has been silent — and
// whether that run exists at all: an idle child that is just loading a
// large session answers `session_slow` too, and clients must be able to
// settle on that instead of keeping the run marked until the next
// successful poll.
return NextResponse.json({
error: error.message,
code: "session_slow",
...error.details,
running: session.isRunning(),
// The timeout that answers this 503 may just have disposed a stalled
// child; the body must not advertise a process that is gone.
alive: session.isAlive(),
silentForMs: session.silentForMs(),
}, { status: 503 });
}
throw error;
}
Expand Down
29 changes: 28 additions & 1 deletion app/api/agent/new/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ function newSessionErrorResponse(error: unknown) {
}
if (error instanceof WebRpcError || error instanceof RpcCommandError) {
return NextResponse.json(
{ error: error.message, code: error instanceof WebRpcError ? error.code : (error.code ?? "rpc_command_failed") },
{
error: error.message,
code: error instanceof WebRpcError ? error.code : (error.code ?? "rpc_command_failed"),
// `maybeStarted`/`abortUnconfirmed` must reach the client, exactly as on
// POST /api/agent/[id]: without them a timeout looks like "not sent".
...(error instanceof WebRpcError ? error.details : undefined),
},
{ status: 400 },
);
}
Expand Down Expand Up @@ -83,6 +89,27 @@ export async function POST(req: Request) {

return NextResponse.json({ success: true, sessionId: realSessionId, data: result });
} catch (error) {
// A command timeout means omp is busy, not dead: the frame may already sit
// in the child's stdin and a run it started must survive. Same contract as
// POST /api/agent/[id]; the liveness watchdog alone may dispose the child.
// The body carries the real session id so a client that posted the prompt
// directly here can still poll and adopt the run `maybeStarted` announced.
// `ensure_session` is the exception: it only asked for a runtime, so a
// timeout there can only be a preset (`set_model`/`set_thinking_level`)
// that never dispatched a run. The caller never receives that id
// (`ensureNewSession` throws before reading it), so nothing could adopt
// the child — destroy it instead of leaving an orphan to the watchdog.
if (error instanceof WebRpcError && error.code === "session_slow" && promptCommand.type !== "ensure_session") {
return NextResponse.json(
{
error: error.message,
code: error.code,
sessionId: realSessionId,
...error.details,
},
{ status: 400 },
);
}
// The child was spawned but the prompt never ran: without this cleanup a
// failed set_model/set_thinking_level/prompt leaves an orphaned omp
// process and a registry entry nobody will ever use.
Expand Down
41 changes: 32 additions & 9 deletions app/api/mcp/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { NextResponse } from "next/server";
import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access";
import { deleteMcpServer, parseMcpListOutput, readDiscoveredMcpServers, readMcpConfig, readUserMcpConfig, type McpLiveServer, validateMcpServer, writeMcpServer } from "@/lib/omp/mcp-config";
import { readSessionHeader, resolveSessionPath } from "@/lib/session-reader";
import { WebRpcError, getRpcSession, resolveSpawnCwdResult, startRpcSession } from "@/lib/rpc-manager";
import { WebRpcError, getOwnChildPids, getRpcSession, isLocallyOwnedSession, isOwnCrashedSession, resolveSpawnCwdResult, startRpcSession } from "@/lib/rpc-manager";
import { detectSessionOwner } from "@/lib/session-owner";
import { RpcCommandError } from "@/lib/omp/rpc-process";
import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data";
import { redactMcpServer } from "@/lib/omp/mcp-config";
Expand Down Expand Up @@ -85,22 +86,44 @@ export async function GET(request: Request) {
// /api/agent/[id]): an alive child is reused as-is below, never replaced —
// listing servers must stay side-effect-free.
const advisor = params.get("advisor") === "1";
let liveServers: ReturnType<typeof parseMcpListOutput> | undefined;
let liveServers: McpLiveServer[] | undefined;
let liveError: string | undefined;
if (includeLive && sessionId) {
try {
let session = getRpcSession(sessionId);
let foreignOwned = false;
if (!session?.isAlive()) {
const sessionFile = await resolveSessionPath(sessionId);
if (!sessionFile) throw new Error("Session not found");
const header = readSessionHeader(sessionFile);
const { cwd } = resolveSpawnCwdResult(header?.cwd);
// Fresh spawn only (an alive child is reused above): apply the
// caller's advisor opinion so a racing prompt doesn't inherit a
// wrong-flag child for its whole turn.
({ session } = await startRpcSession(sessionId, sessionFile, cwd, undefined, advisor, header?.cwd));
// Same gate as POST /api/agent/[id]: listing servers must not start a
// second writer. omp ≥ 18.5 moves a chat whose file another live
// process owns into a copy on its first write — that spawn is exactly
// the silent fork the ownership detection exists to prevent.
const elsewhere = await detectSessionOwner(sessionId, sessionFile, {
isLocal: isLocallyOwnedSession,
ownCrashed: isOwnCrashedSession,
excludePids: getOwnChildPids(),
});
if (elsewhere) {
// Answer through the existing error path: an empty live list reads
// as "no MCP servers" in both clients, so the ownership message is
// what makes them fall back to the configured inventory and explain
// the missing live status.
foreignOwned = true;
liveError = "This session is being run by another omp process.";
} else {
const header = readSessionHeader(sessionFile);
const { cwd } = resolveSpawnCwdResult(header?.cwd);
// Fresh spawn only (an alive child is reused above): apply the
// caller's advisor opinion so a racing prompt doesn't inherit a
// wrong-flag child for its whole turn.
({ session } = await startRpcSession(sessionId, sessionFile, cwd, undefined, advisor, header?.cwd));
}
}
if (!foreignOwned) {
if (!session) throw new Error("Session not found");
liveServers = mergeMcpServers(parseMcpListOutput(await session.getMcpList()), inventory);
}
liveServers = mergeMcpServers(parseMcpListOutput(await session.getMcpList()), inventory);
} catch (error) {
liveError = sanitizeMcpLiveError(error);
}
Expand Down
17 changes: 16 additions & 1 deletion app/api/sessions/[id]/auto-name/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { NextResponse } from "next/server";
import { scanSessionInfo, setSessionTitle } from "@/lib/omp/session-files";
import { deriveSessionTitleFromFirstMessage, sanitizeSessionTitle } from "@/lib/session-title";
import { getRpcSession, resolveSpawnCwdResult, startRpcSession, WebRpcError } from "@/lib/rpc-manager";
import { getOwnChildPids, getRpcSession, isLocallyOwnedSession, isOwnCrashedSession, resolveSpawnCwdResult, startRpcSession, WebRpcError } from "@/lib/rpc-manager";
import { invalidateSessionCaches, readSessionHeader } from "@/lib/session-reader";
import { detectSessionOwner } from "@/lib/session-owner";
import { resolveSessionPathOr404 } from "@/lib/api-utils";

/**
Expand All @@ -29,6 +30,20 @@ export async function POST(
if (!rpc?.isAlive?.()) {
const resolved = await resolveSessionPathOr404(id);
if ("response" in resolved) return resolved.response;
// A title is cosmetic: never spawn a second omp for a session another
// process owns (that spawn would fork the conversation on its dispose).
// Report the stored title instead, and write nothing to a foreign file.
const elsewhere = await detectSessionOwner(id, resolved.filePath, {
isLocal: isLocallyOwnedSession,
ownCrashed: isOwnCrashedSession,
excludePids: getOwnChildPids(),
});
if (elsewhere) {
// No title yet is a valid answer here, not an error: the caller treats
// a 200 without a title as a silent no-op (another process owns it).
const stored = sanitizeSessionTitle(scanSessionInfo(resolved.filePath, false)?.title) || null;
return NextResponse.json({ title: stored, generated: false, usage: null });
}
try {
const header = readSessionHeader(resolved.filePath);
const { cwd } = resolveSpawnCwdResult(header?.cwd);
Expand Down
Loading