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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ 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.

Expand Down
35 changes: 30 additions & 5 deletions app/api/agent/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,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 @@ -150,14 +150,39 @@ export async function GET(
try {
const session = getRpcSession(id);
if (!session || !session.isAlive()) {
return NextResponse.json({ running: false });
return NextResponse.json({ running: false, alive: false });
}
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 });
} 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
30 changes: 24 additions & 6 deletions app/api/sessions/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ function sessionsErrorResponse(error: unknown): NextResponse {
if (error instanceof WebRpcError && error.code === "session_busy") {
return NextResponse.json({ error: error.message, code: error.code }, { status: 409 });
}
// Same "still running, retry" answer as the state polls: omp did not confirm
// the command within its bound, so the caller must not treat it as done.
if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) {
return NextResponse.json({ error: error.message, code: "session_slow" }, { status: 503 });
}
if (error instanceof SessionFileTooLargeError) {
return NextResponse.json(
{ error: "Session file is too large to open in omp-web", code: "session_file_too_large" },
Expand Down Expand Up @@ -234,18 +239,23 @@ export async function GET(
// ?includeState=1 inlines the wrapper's live agent state (same shape as
// GET /api/agent/[id]) so the client's post-turn refresh is one request
// instead of two. On a get_state failure the field is omitted entirely —
// callers treat a missing `agent` as "fetch it separately".
let agent: { running: boolean; state?: unknown } | undefined;
// callers treat a missing `agent` as "fetch it separately"; a child that is
// gone answers `{ running: false, alive: false }` like the other routes.
let agent: { running: boolean; alive: boolean; state?: unknown } | undefined;
if (includeState) {
const rpc = getRpcSession(id);
if (rpc?.isAlive()) {
try {
agent = { running: true, state: await rpc.send({ type: "get_state" }) };
// Same split as GET /api/agent/[id]: `running` is the run in flight,
// `alive` the child (an idle wrapper is alive, not running).
const state = await rpc.send({ type: "get_state" });
agent = { running: rpc.isRunning(), alive: true, state };
} catch {
// Leave agent unset; the session payload is still valid without it.
}
} else {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The includeState GET path has an empty else block: when the RPC session is not alive, agent stays undefined and the response omits the field entirely. That is inconsistent with every other response shape in this PR — the state route and the agent route emit alive: false for the not-found/exited cases — and it leaves the new alive field undocumented for this endpoint. Callers that pattern-match on agent.alive now get two different "not alive" representations depending on which route they hit.

🩹 The Fix:

} else {
  agent = { running: false, alive: false };
}

📏 Severity: suggestion

agent = { running: false };
// Same shape as GET /api/agent/[id]: a dead/absent child is not a run.
agent = { running: false, alive: false };
}
}

Expand Down Expand Up @@ -285,8 +295,16 @@ export async function PATCH(
await rpc.send({ type: "set_session_name", name: name.trim() });
renamed = true;
} catch (error) {
if (error instanceof WebRpcError && error.code === "session_busy") throw error;
// Fall back to the on-disk title slot below.
// A timeout was never confirmed by omp: it still holds the old name in
// memory and would clobber a file write on its next flush. Answer
// "busy, try again" instead of reporting a rename that did not happen.
if (error instanceof WebRpcError
&& (error.code === "session_busy" || error.code === "session_slow" || error.code === "session_state_timeout")) {
throw error;
}
// The child answered with an error (it rejected the command, nothing was
// applied) or went away before answering: with no live writer left, the
// on-disk title slot below is safe.
}
}
if (!renamed) {
Expand Down
29 changes: 24 additions & 5 deletions app/api/sessions/[id]/state/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,40 @@ export async function GET(
if (rpc?.isAlive()) {
try {
const state = await rpc.send({ type: "get_state" });
return NextResponse.json({ running: true, state });
// `running` = a run is in flight, `alive` = the child exists. An idle
// child that just answered `get_state` is alive and not running; the
// flags were reconciled by that answer, so this is authoritative.
return NextResponse.json({ running: rpc.isRunning(), alive: true, state });
} 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
// instead of treating the session as idle/recovered. Both the code
// this tree raises (`session_slow`) and 0.6.0's own
// `session_state_timeout` mean the same thing to a client.
if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) {
// Same clock as the success body: a blocked child answers nothing,
// so the 503 is where a client learns how long the run it still
// shows has been silent — and whether there is a run at all.
return NextResponse.json({
error: error.message,
code: "session_slow",
...error.details,
running: rpc.isRunning(),
// The timeout behind this 503 may have disposed a stalled child;
// `alive` is the child, so read it after the catch.
alive: rpc.isAlive(),
silentForMs: rpc.silentForMs(),
}, { status: 503 });
}
throw error;
}
}

const exited = getExitedRpcSession(id);
if (exited) return NextResponse.json({ running: false, exited });
if (exited) return NextResponse.json({ running: false, alive: false, exited });

const resolved = await resolveSessionPathOr404(id);
if ("response" in resolved) return resolved.response;
return NextResponse.json({ running: false });
return NextResponse.json({ running: false, alive: false });
} catch (error) {
return apiErrorResponse(error);
}
Expand Down
16 changes: 13 additions & 3 deletions components/ChatWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@ interface Props {
onOpenProviders?: () => void;
}

/** Below this a slow phase is merely slow. Past it the status line names how
* long omp has been silent (server frame clock): the child can answer
* `get_state` for hours while its run sits in an advisor/auto-retry loop, and
* "Thinking…" alone then claims progress that is not happening. The liveness
* watchdog's five-minute window is what actually ends such a run. */
const AGENT_SILENT_NOTICE_MS = 3 * 60_000;

function phaseLabel(phase: AgentPhase): string {
if (phase?.kind === "running_tools") {
const names = phase.tools.map((tool) => tool.name);
Expand Down Expand Up @@ -518,7 +525,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa
toolPreset,
liveModelMeta,
retryInfo, contextUsage, forkingEntryId, editingEntryId,
isCompacting, compactResult, tokensPerSecond, displayModel: displayModelValue, sessionStats,
isCompacting, compactResult, tokensPerSecond, agentSilentMs, displayModel: displayModelValue, sessionStats,
slashCommands, slashCommandsLoading, queuedMessages, advisorActive, advisorEnabled, handleAdvisorChange,
notices, dismissNotice, extensionDialog, extensionCustomUi, extensionStatuses, extensionWidgets, respondToExtensionUi, sendExtensionCustomInput,
skillDiagnostics, setSkillStartupDiagnostics,
Expand Down Expand Up @@ -1023,9 +1030,12 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa
if (bashRunning && !pendingBash) {
return t("chatWindow.runningCommand");
}
if (isCompacting || (agentRunning && !streamState.streamingMessage && pendingToolHeaders.length === 0)) {
if (agentRunning || isCompacting) {
return [
phaseLabel(agentPhase),
agentSilentMs != null && agentSilentMs >= AGENT_SILENT_NOTICE_MS
? t("chatWindow.agentSilent", { minutes: Math.max(1, Math.floor(agentSilentMs / 60_000)) })
: null,
activeSubagentCount > 0 ? tn("chatWindow.subagentCount", activeSubagentCount) : null,
isCompacting ? t("chatWindow.compactingContext") : null,
currentTodoPhase
Expand All @@ -1038,7 +1048,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionWorkspace, toolCa
].filter(Boolean).join(" · ");
}
return null;
}, [bashRunning, pendingBash, isCompacting, agentRunning, streamState.streamingMessage, pendingToolHeaders.length, agentPhase, activeSubagentCount, currentTodoPhase, t, tn]);
}, [bashRunning, pendingBash, isCompacting, agentRunning, agentPhase, agentSilentMs, activeSubagentCount, currentTodoPhase, t, tn]);

const askOpen = extensionDialog?.method === "ask";
const hiddenComposerRef = useRef<HTMLDivElement>(null);
Expand Down
11 changes: 10 additions & 1 deletion components/SessionSidebar-rows.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { memo, useCallback, useRef, useState } from "react";
import type { AgentMessage, ExitedRpcSession, ManagedProject, ProjectLaunchConfig, SessionInfo } from "@/lib/types";
import { formatExitedSessionNotice, useI18n } from "@/lib/i18n";
import { formatApiError } from "@/lib/i18n/api-error";
import { ChevronDown, ChevronRight, Folder, GitBranch, MoreHorizontal, Pin } from "lucide-react";
import { Tooltip } from "./ui/primitives";
import { ConfirmDialog } from "./ui/field";
Expand Down Expand Up @@ -645,7 +646,15 @@ const SessionItem = memo(function SessionItem({
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
if (!response.ok) throw new Error("Session rename failed");
if (!response.ok) {
// 503 means omp is busy and did not confirm the rename: the old title
// stays, so say "busy, try again" instead of failing silently.
if (response.status === 503) {
const payload = await response.json().catch(() => null) as { code?: string; error?: string } | null;
toast.error(formatApiError(payload));
}
return;
}
onRenamed?.();
} catch {
// The next refresh remains authoritative if the rename fails.
Expand Down
9 changes: 9 additions & 0 deletions hooks/useAgentSession-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ export type AgentStateResponse = {
isBashRunning?: boolean;
isCompacting?: boolean;
responseObserved?: boolean;
/** Milliseconds since the child's last frame while a run is marked (server
* frame clock; poll answers do not count). `null` when nothing runs. */
silentForMs?: number | null;
tokensPerSecond?: number | null;
extensionStatuses?: ExtensionStatusItem[];
extensionWidgets?: ExtensionWidgetItem[];
Expand Down Expand Up @@ -262,6 +265,12 @@ export const PROMPT_SETTLE_INITIAL_DELAY_MS = 800;
export const PROMPT_SETTLE_POLL_MS = 600;
export const PROMPT_SETTLE_MAX_MS = 20_000;
export const AGENT_STATE_RECONCILE_MS = 15_000;
// A 503 `session_slow` keeps the run marked so the next poll can settle it, but
// only while there is evidence the run exists: the answer itself carries the
// server's run state. A server that does not report it (older build) gets this
// bound — after this many consecutive slow answers the running list, the
// server's own run registry, decides instead of an "unknown" that never ends.
export const SLOW_STATE_MAX_ANSWERS = 3;
// Stop waits at most this long to take queued messages back before aborting.
export const WITHDRAW_BEFORE_ABORT_MS = 1_500;
export const BASH_STATE_RECONCILE_MS = 1_000;
Expand Down
Loading