Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: restart sync worker with backoff

ogsamrat94af69542a37
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index a43f1488..1d72959a 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -413,6 +413,13 @@ export type OmniRushBestPractices = { enabled: boolean };
* show once (null when it could not be asked).
*/
export type OmniRushFilesUsed = { active: boolean | null; available: boolean | null; consentText: string | null };
+/** GET /omnirush/capture/status: whether session capture runs; "off" when signed out (nothing to capture). */
+export type OmniRushCaptureStatus = {
+ running: boolean;
+ mode: "off" | "starting" | "worker" | "local" | "restarting" | "down";
+ since: string | null;
+ restarts: number;
+};
export type OmniRushBestPracticesChange = OmniRushBestPractices & {
ok: boolean;
changed: boolean;
@@ -1908,6 +1915,8 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
}),
getFilesUsed: () =>
requestJson<OmniRushFilesUsed>(baseUrl, "/runtime-config/files-used", { token, hostToken, timeoutMs: FILES_USED_TIMEOUT_MS }),
+ getCaptureStatus: () =>
+ requestJson<OmniRushCaptureStatus>(baseUrl, "/omnirush/capture/status", { token, hostToken, timeoutMs: timeouts.config }),
getBestPractices: () =>
requestJson<OmniRushBestPractices>(baseUrl, "/runtime-config/best-practices", { token, hostToken, timeoutMs: timeouts.config }),
setBestPractices: (enabled: boolean) =>
diff --git a/apps/app/src/react-app/shell/app-root.tsx b/apps/app/src/react-app/shell/app-root.tsx
index f86ef0ca..00941973 100644
--- a/apps/app/src/react-app/shell/app-root.tsx
+++ b/apps/app/src/react-app/shell/app-root.tsx
@@ -46,6 +46,7 @@ import {
import { OmniRushContextPublisher } from "./omnirush-context-publisher";
import { SessionRoute } from "./session-route";
import { DesktopUpdaterProvider } from "../domains/settings/state/desktop-updater-provider";
+import { SyncRestartGate } from "./sync-restart-banner";
import { UpdateGate } from "./update-gate";
import { QualityRewards } from "../domains/quality/quality-notice";
import { TurnRunningSync } from "../domains/quality/good-session";
@@ -385,6 +386,7 @@ export function AppRoot() {
<DevProfiler id="AppRoot">
<DesktopUpdaterProvider>
<UpdateGate>
+ <SyncRestartGate>
<ShellConfigProvider>
<AppMenuProvider>
<OmniRushControlProvider>
@@ -523,6 +525,7 @@ export function AppRoot() {
</OmniRushControlProvider>
</AppMenuProvider>
</ShellConfigProvider>
+ </SyncRestartGate>
</UpdateGate>
</DesktopUpdaterProvider>
</DevProfiler>
diff --git a/apps/app/src/react-app/shell/sync-restart-banner.tsx b/apps/app/src/react-app/shell/sync-restart-banner.tsx
new file mode 100644
index 00000000..b4fb7282
--- /dev/null
+++ b/apps/app/src/react-app/shell/sync-restart-banner.tsx
@@ -0,0 +1,96 @@
+/** @jsxImportSource react */
+import { useEffect, useState, type ReactNode } from "react";
+import { RefreshCw } from "lucide-react";
+
+import { createOmniRushServerClient, type OmniRushCaptureStatus } from "../../app/lib/omnirush-server";
+import { resolveOmniRushConnection } from "./omnirush-connection";
+import { BANNER_CLASS, BANNER_HEIGHT_PX, bannerShiftStyle } from "./update-gate";
+
+export const SYNC_RESTART_BANNER_TEXT = "Session sync is restarting. Your work is safe; it will catch up automatically.";
+
+const POLL_MS = 5_000;
+/** A capture worker takes a moment to start; only a start longer than this shows the banner. */
+const SLOW_START_MS = 10_000;
+
+/**
+ * Whether the app shows the sync banner: capture is restarting, stopped while
+ * the server still answers, or slow to start. No answer (the server is
+ * unreachable) and "off" (signed out) show none.
+ */
+export function captureBannerVisible(status: OmniRushCaptureStatus | null, now: number): boolean {
+ if (!status || status.running) return false;
+ switch (status.mode) {
+ case "restarting":
+ case "down":
+ return true;
+ case "starting":
+ return status.since !== null && now - Date.parse(status.since) > SLOW_START_MS;
+ default:
+ return false;
+ }
+}
+
+/** GET /omnirush/capture/status every five seconds while the window is visible. Never blocks prompts. */
+export function useCaptureBannerVisible(): boolean {
+ const [visible, setVisible] = useState(false);
+ useEffect(() => {
+ let stopped = false;
+ let inflight = false;
+ const poll = async () => {
+ if (inflight || document.visibilityState !== "visible") return;
+ inflight = true;
+ let status: OmniRushCaptureStatus | null = null;
+ try {
+ const connection = await resolveOmniRushConnection();
+ if (connection.normalizedBaseUrl && connection.resolvedToken) {
+ status = await createOmniRushServerClient({
+ baseUrl: connection.normalizedBaseUrl,
+ token: connection.resolvedToken,
+ hostToken: connection.resolvedHostToken,
+ }).getCaptureStatus();
+ }
+ } catch {
+ // Unreachable, or an older server without the route: no banner.
+ } finally {
+ inflight = false;
+ }
+ if (!stopped) setVisible(captureBannerVisible(status, Date.now()));
+ };
+ void poll();
+ const timer = window.setInterval(() => void poll(), POLL_MS);
+ const onVisibility = () => void poll();
+ document.addEventListener("visibilitychange", onVisibility);
+ return () => {
+ stopped = true;
+ window.clearInterval(timer);
+ document.removeEventListener("visibilitychange", onVisibility);
+ };
+ }, []);
+ return visible;
+}
+
+export function SyncRestartBanner() {
+ return (
+ <div role="status" aria-live="polite" data-testid="sync-restart-banner" className={BANNER_CLASS} style={{ height: BANNER_HEIGHT_PX }}>
+ <RefreshCw className="size-4 shrink-0" aria-hidden="true" />
+ <span className="truncate">{SYNC_RESTART_BANNER_TEXT}</span>
+ </div>
+ );
+}
+
+/**
+ * The top banner while session capture is not running, in the required-update
+ * banner's style (below it when both show). Nothing is blocked: prompts go
+ * on, and their sessions resume once capture is back.
+ */
+export function SyncRestartGate({ children }: { children: ReactNode }) {
+ const visible = useCaptureBannerVisible();
+ return (
+ <>
+ {visible ? <SyncRestartBanner /> : null}
+ <div data-sync-restart-shifted={visible ? "" : undefined} style={bannerShiftStyle(visible)}>
+ {children}
+ </div>
+ </>
+ );
+}
diff --git a/apps/app/src/react-app/shell/update-gate.tsx b/apps/app/src/react-app/shell/update-gate.tsx
index 4bfbf975..dc30e892 100644
--- a/apps/app/src/react-app/shell/update-gate.tsx
+++ b/apps/app/src/react-app/shell/update-gate.tsx
@@ -1,5 +1,5 @@
/** @jsxImportSource react */
-import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { ArrowUpCircle, Download, Loader2 } from "lucide-react";
import {
@@ -16,8 +16,16 @@ import { useBrandAppName } from "../domains/cloud/brand-theme";
import { useDesktopUpdater } from "../domains/settings/state/desktop-updater-provider";
import { InstallCommand } from "./install-command";
-/** Height of the required-update banner; the app below it is shifted by this much. */
-const BANNER_HEIGHT_PX = 36;
+/** Height of the app's top banners; the app below one is shifted by this much. */
+export const BANNER_HEIGHT_PX = 36;
+export const BANNER_CLASS = "fixed inset-x-0 top-0 z-[70] flex items-center justify-center gap-3 border-b border-amber-700/30 bg-amber-300 px-4 text-[12px] font-medium text-amber-950 mac:titlebar-drag mac:ps-20";
+
+/** The app below a top banner: shifted beneath it (its transform also makes it the containing block of a nested banner, which stacks below this one). */
+export function bannerShiftStyle(shifted: boolean): CSSProperties {
+ return shifted
+ ? { position: "fixed", inset: `${BANNER_HEIGHT_PX}px 0 0 0`, transform: "translateZ(0)", overflow: "hidden" }
+ : { display: "contents" };
+}
function useNow(active: boolean, intervalMs = 15_000): number {
const [now, setNow] = useState(() => Date.now());
@@ -189,7 +197,7 @@ export function RequiredUpdateBanner(props: { gate: UpdateGateState; appName: st
aria-live="polite"
data-testid="update-required-banner"
data-update-deadline={props.gate.deadline ?? undefined}
- className="fixed inset-x-0 top-0 z-[70] flex items-center justify-center gap-3 border-b border-amber-700/30 bg-amber-300 px-4 text-[12px] font-medium text-amber-950 mac:titlebar-drag mac:ps-20"
+ className={BANNER_CLASS}
style={{ height: BANNER_HEIGHT_PX }}
>
<ArrowUpCircle className="size-4 shrink-0" aria-hidden="true" />
@@ -292,9 +300,7 @@ export function UpdateGate({ children }: { children: ReactNode }) {
{banner ? <RequiredUpdateBanner gate={gate} appName={appName} update={update} /> : null}
<div
data-update-gate-shifted={banner ? "" : undefined}
- style={banner
- ? { position: "fixed", inset: `${BANNER_HEIGHT_PX}px 0 0 0`, transform: "translateZ(0)", overflow: "hidden" }
- : { display: "contents" }}
+ style={bannerShiftStyle(banner)}
>
{children}
</div>
diff --git a/apps/app/tests/sync-restart-banner.test.tsx b/apps/app/tests/sync-restart-banner.test.tsx
new file mode 100644
index 00000000..d4dc8ceb
--- /dev/null
+++ b/apps/app/tests/sync-restart-banner.test.tsx
@@ -0,0 +1,36 @@
+import { describe, expect, test } from "bun:test";
+import { renderToStaticMarkup } from "react-dom/server";
+
+import type { OmniRushCaptureStatus } from "../src/app/lib/omnirush-server";
+import { captureBannerVisible, SyncRestartBanner, SYNC_RESTART_BANNER_TEXT } from "../src/react-app/shell/sync-restart-banner";
+
+const NOW = Date.parse("2026-10-10T12:00:00Z");
+const status = (mode: OmniRushCaptureStatus["mode"], secondsAgo: number | null = 1): OmniRushCaptureStatus => ({
+ running: mode === "worker" || mode === "local" || mode === "off",
+ mode,
+ since: secondsAgo === null ? null : new Date(NOW - secondsAgo * 1_000).toISOString(),
+ restarts: 0,
+});
+
+describe("sync restart banner", () => {
+ test("shows while capture restarts or is down, and for a start longer than ten seconds", () => {
+ expect(captureBannerVisible(status("restarting"), NOW)).toBe(true);
+ expect(captureBannerVisible(status("down"), NOW)).toBe(true);
+ expect(captureBannerVisible(status("starting", 3), NOW)).toBe(false);
+ expect(captureBannerVisible(status("starting", 11), NOW)).toBe(true);
+ });
+
+ test("hides while capture runs, when signed out, and when the server does not answer", () => {
+ expect(captureBannerVisible(status("worker"), NOW)).toBe(false);
+ expect(captureBannerVisible(status("local"), NOW)).toBe(false);
+ expect(captureBannerVisible(status("off", null), NOW)).toBe(false);
+ expect(captureBannerVisible(null, NOW)).toBe(false);
+ });
+
+ test("says the work is safe, with nothing to dismiss or click", () => {
+ const html = renderToStaticMarkup(<SyncRestartBanner />);
+ expect(html).toContain(SYNC_RESTART_BANNER_TEXT);
+ expect(html).toContain('role="status"');
+ expect(html).not.toContain("<button");
+ });
+});
diff --git a/apps/server/src/capture-client.test.ts b/apps/server/src/capture-client.test.ts
index 13802ce0..39deb3a4 100644
--- a/apps/server/src/capture-client.test.ts
+++ b/apps/server/src/capture-client.test.ts
@@ -505,3 +505,74 @@ describe("capture worker", () => {
expect(results[1]).toEqual(results[0]!);
}, 60_000);
});
+
+describe("capture worker restarts", () => {
+ // The worker's test-only crash hook (capture-worker.ts) answers only with this set.
+ let crashSwitch: string | undefined;
+ beforeAll(() => {
+ crashSwitch = process.env.OMNIRUSH_CAPTURE_TEST_CRASH;
+ process.env.OMNIRUSH_CAPTURE_TEST_CRASH = "1";
+ });
+ afterAll(() => {
+ if (crashSwitch === undefined) delete process.env.OMNIRUSH_CAPTURE_TEST_CRASH;
+ else process.env.OMNIRUSH_CAPTURE_TEST_CRASH = crashSwitch;
+ });
+
+ function crashing(options: Partial<CaptureServiceOptions> = {}) {
+ const restarts: Array<Record<string, unknown>> = [];
+ const modes: string[] = [];
+ const capture = service({
+ stateDir: "",
+ sessionUploader: {},
+ log: (_level, message, attributes) => {
+ if (message.includes("starting a new") && attributes) restarts.push(attributes);
+ },
+ onModeChange: (mode) => modes.push(mode),
+ ...options,
+ });
+ const crash = async () => {
+ await until(() => capture.mode() === "worker", 10_000, "a ready worker");
+ capture.recordTrace("session-crash-0001", "omnirush.test.worker_crash");
+ await until(() => capture.mode() === "restarting", 10_000, "the worker's exit");
+ };
+ return { capture, restarts, modes, crash };
+ }
+
+ test("a worker that keeps exiting is replaced every time, after a pause that doubles up to its cap, and is \"down\" only once stopped", async () => {
+ const { capture, restarts, modes, crash } = crashing({ stateDir: await tempDir("state"), restartBackoffMs: { baseMs: 40, maxMs: 160 } });
+ for (let index = 0; index < 5; index += 1) await crash();
+ expect(restarts.map((item) => [item.code, item.attempt, item.delayMs])).toEqual([[70, 1, 40], [70, 2, 80], [70, 3, 160], [70, 4, 160], [70, 5, 160]]);
+ expect(capture.status()).toMatchObject({ mode: "restarting", restarts: 5 });
+ await until(() => capture.mode() === "worker", 10_000, "the sixth worker");
+ expect(await capture.diagnostics()).not.toBeNull();
+ expect(modes).toEqual([...Array.from({ length: 5 }, () => ["worker", "restarting", "starting"]).flat(), "worker"]);
+ await capture.stop();
+ expect(capture.mode()).toBe("down");
+ expect(modes.at(-1)).toBe("down");
+ }, 60_000);
+
+ test("a worker that stayed up long enough starts the backoff over", async () => {
+ const { capture, restarts, crash } = crashing({ stateDir: await tempDir("state"), restartBackoffMs: { baseMs: 40, maxMs: 1_000, stableMs: 300 } });
+ await crash();
+ await crash();
+ await until(() => capture.mode() === "worker", 10_000, "the third worker");
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 400));
+ await crash();
+ expect(restarts.map((item) => [item.attempt, item.delayMs])).toEqual([[1, 40], [2, 80], [1, 40]]);
+ expect(capture.status().restarts).toBe(3);
+ }, 30_000);
+
+ test("calls made while restarting reach the next worker", async () => {
+ const root = await syntheticWorkspace(5);
+ const sink = uploadSink();
+ const { capture, crash } = crashing({ stateDir: await tempDir("state"), sessionUploader: { upload: sink.upload }, restartBackoffMs: { baseMs: 400, maxMs: 400 } });
+ await crash();
+ capture.startSession("session-restart-0001", "workspace-restart", root);
+ const diagnostics = capture.diagnostics();
+ expect(capture.mode()).toBe("restarting");
+ expect(await diagnostics).not.toBeNull();
+ expect(capture.mode()).toBe("worker");
+ await capture.idle();
+ expect(sink.envelopes().map((item) => [item.session_id, item.snapshot_type])).toEqual([["session-restart-0001", "start"]]);
+ }, 30_000);
+});
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index f8aca0c2..6ac7f771 100644
--- a/apps/server/src/capture-client.ts
+++ b/apps/server/src/capture-client.ts
@@ -7,8 +7,8 @@
* and external egress. Opening or switching sessions never waits on a scan,
* a snapshot or an archive. If the worker cannot start (a runtime without
* worker support for this module, or OMNIRUSH_CAPTURE_WORKER=0) the same host
- * runs in-process; a worker that dies after starting is replaced, a bounded
- * number of times.
+ * runs in-process; a worker that dies after starting is replaced, again and
+ * again with a growing pause, and the calls made meanwhile wait for it.
*/
import { Worker } from "node:worker_threads";
import { lstat } from "node:fs/promises";
@@ -38,8 +38,14 @@ const MAX_TRACED_REQUEST_BYTES = 4 * 1024 * 1024;
const STOP_TIMEOUT_MS = 20_000;
/** Shutdown waits this long to learn whether the account is still there (for the final project archives), else packs none. */
const ACCOUNT_CHECK_TIMEOUT_MS = 1_000;
-/** A worker that exits unexpectedly is replaced at most this many times per server. */
-const MAX_WORKER_RESTARTS = 3;
+/** The pause before a new worker: `baseMs` doubled per consecutive exit, at most `maxMs`; `stableMs` up and ready starts over. */
+type RestartBackoff = { baseMs: number; maxMs: number; stableMs?: number };
+/** A worker that exits unexpectedly is replaced after 1 s, then 2 s, 4 s, ... at most 60 s. */
+const RESTART_BACKOFF: RestartBackoff = { baseMs: 1_000, maxMs: 60_000 };
+/** A worker that stayed up and ready this long starts the backoff over. */
+const RESTART_STABLE_MS = 5 * 60_000;
+/** Calls waiting for a worker to start; past this the oldest one nobody waits on is dropped. */
+const MAX_QUEUED_CALLS = 20_000;
const SESSION_ID_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/;
export type CaptureServiceOptions = Omit<CaptureHostOptions, "onSessionClosed"> & {
@@ -47,13 +53,26 @@ export type CaptureServiceOptions = Omit<CaptureHostOptions, "onSessionClosed">
worker?: boolean;
/** How long shutdown waits for the capture to stop; STOP_TIMEOUT_MS unless a test lowers it. */
stopTimeoutMs?: number;
+ /** RESTART_BACKOFF and RESTART_STABLE_MS unless a test lowers them. */
+ restartBackoffMs?: RestartBackoff;
+ /** Told each time the mode changes. */
+ onModeChange?: (mode: CaptureMode) => void;
};
+/**
+ * Where capture runs: "restarting" between a worker's exit and the next
+ * one's start, and "down" only once stopped. While "starting" or
+ * "restarting", calls wait for the worker.
+ */
+export type CaptureMode = "starting" | "worker" | "local" | "restarting" | "down";
+
export type CaptureService = {
/** The session uploader has an account to upload to (the sign-in gate's question). */
readonly uploadEnabled: boolean;
/** Where capture runs right now. */
- mode(): "starting" | "worker" | "local" | "down";
+ mode(): CaptureMode;
+ /** The mode, when it began, and how many times a worker was replaced (the app's status). */
+ status(): { mode: CaptureMode; since: Date; restarts: number };
/** Whether the session uploader is tracking this session (started and not finished). */
hasSession(sessionId: string): boolean;
startSession(sessionId: string, workspaceId: string, root: string): void;
@@ -110,7 +129,8 @@ type QueuedCall = { call: CaptureCall; transfer: ArrayBuffer[] };
class CaptureClient implements CaptureService {
readonly uploadEnabled: boolean;
- private current: "starting" | "worker" | "local" | "down" = "starting";
+ private current: CaptureMode = "starting";
+ private since = new Date();
private worker: Worker | null = null;
private local: CaptureHost | null = null;
private queue: QueuedCall[] = [];
@@ -122,6 +142,13 @@ class CaptureClient implements CaptureService {
/** Sessions the worker's session uploader tracks: true while live, false once finishing. */
private readonly sessions = new Map<string, boolean>();
private restarts = 0;
+ /** Exits since a worker last stayed up RESTART_STABLE_MS: the next pause doubles with each. */
+ private attempt = 0;
+ private readyAt = 0;
+ private restartTimer: ReturnType<typeof setTimeout> | null = null;
+ /** Only the first start falls back to capturing in-process; later failures start new workers. */
+ private canRunLocally = true;
+ private overflowing = false;
private stopping: Promise<void> | null = null;
constructor(private readonly options: CaptureServiceOptions) {
@@ -134,10 +161,21 @@ class CaptureClient implements CaptureService {
else this.runLocally(null);
}
- mode(): "starting" | "worker" | "local" | "down" {
+ mode(): CaptureMode {
return this.current;
}
+ status(): { mode: CaptureMode; since: Date; restarts: number } {
+ return { mode: this.current, since: this.since, restarts: this.restarts };
+ }
+
+ private setMode(mode: CaptureMode): void {
+ if (mode === this.current) return;
+ this.current = mode;
+ this.since = new Date();
+ this.options.onModeChange?.(mode);
+ }
+
hasSession(sessionId: string): boolean {
if (this.local) return this.local.sessionUploader.hasSession(sessionId);
return this.sessions.get(sessionId) === true;
@@ -233,6 +271,11 @@ class CaptureClient implements CaptureService {
private async shutdown(archiveFinals: boolean | Promise<boolean>): Promise<void> {
// First, and synchronously: archive uploads this thread makes for the worker are aborted now.
for (const { controller, channel } of this.served.values()) if (channel === "archive") controller.abort();
+ // Between workers: the next one starts now, so the queued calls and the stop reach it.
+ if (this.restartTimer) {
+ clearTimeout(this.restartTimer);
+ this.spawn();
+ }
const finals = await withinTimeout(archiveFinals, ACCOUNT_CHECK_TIMEOUT_MS);
const done = this.dispatch({ kind: "call", id: null, method: "stop", args: [{ archiveFinals: finals }] }, [], true);
const timeoutMs = this.options.stopTimeoutMs ?? STOP_TIMEOUT_MS;
@@ -252,7 +295,7 @@ class CaptureClient implements CaptureService {
if (late) this.local?.sessionUploader.abortUploads();
const worker = this.worker;
this.worker = null;
- this.current = "down";
+ this.setMode("down");
if (worker) await worker.terminate().catch(() => undefined);
// Also aborts the requests this thread was still serving for the worker.
this.settleOutstanding();
@@ -288,10 +331,34 @@ class CaptureClient implements CaptureService {
reply = new Promise((resolvePromise) => this.replies.set(id, resolvePromise));
}
if (this.current === "worker" && this.worker) this.post(this.worker, call, transfer);
- else this.queue.push({ call, transfer });
+ else this.enqueue({ call, transfer });
return reply;
}
+ /** Queues a call for the next worker; a full queue drops its oldest call nobody waits on (an awaited one only if all are). */
+ private enqueue(queued: QueuedCall): void {
+ if (this.queue.length >= MAX_QUEUED_CALLS) {
+ const [dropped] = this.queue.splice(Math.max(0, this.queue.findIndex((item) => item.call.id === null)), 1);
+ if (dropped && dropped.call.id !== null) {
+ this.replies.get(dropped.call.id)?.(null);
+ this.replies.delete(dropped.call.id);
+ }
+ if (!this.overflowing) {
+ this.overflowing = true;
+ this.options.log("warn", "OmniRush capture calls are queued past the limit while the capture worker starts; the oldest are dropped", { limit: MAX_QUEUED_CALLS });
+ }
+ }
+ this.queue.push(queued);
+ }
+
+ /** Hands the queued calls over (the worker is ready, or the host runs in-process). */
+ private takeQueue(): QueuedCall[] {
+ const queued = this.queue;
+ this.queue = [];
+ this.overflowing = false;
+ return queued;
+ }
+
/** Posts a call; one whose arguments cannot be cloned is dropped with a warn line, never thrown into the request. */
private post(worker: Worker, call: CaptureCall, transfer: ArrayBuffer[]): void {
try {
@@ -338,12 +405,14 @@ class CaptureClient implements CaptureService {
}
private spawn(): void {
- this.current = "starting";
+ this.restartTimer = null;
+ this.setMode("starting");
let worker: Worker;
try {
worker = new Worker(workerUrl(), { workerData: this.workerInit() });
} catch (error) {
- this.runLocally(error);
+ if (this.canRunLocally) this.runLocally(error);
+ else this.scheduleRestart("OmniRush capture worker could not start; starting a new one", { error: errorSummary(error) });
return;
}
// The server's listener keeps the process alive; the worker never holds it open on its own.
@@ -360,10 +429,10 @@ class CaptureClient implements CaptureService {
if (worker !== this.worker) return;
switch (message.kind) {
case "ready": {
- this.current = "worker";
- const queued = this.queue;
- this.queue = [];
- for (const { call, transfer } of queued) this.post(worker, call, transfer);
+ this.setMode("worker");
+ this.readyAt = Date.now();
+ this.canRunLocally = false;
+ for (const { call, transfer } of this.takeQueue()) this.post(worker, call, transfer);
return;
}
case "log":
@@ -392,20 +461,27 @@ class CaptureClient implements CaptureService {
this.worker = null;
this.settleOutstanding();
if (this.stopping) return;
- if (this.current === "starting") {
+ if (this.current === "starting" && this.canRunLocally) {
this.runLocally(new Error(`the capture worker exited with code ${code} before it was ready`));
return;
}
// Its sessions are gone with it; each resumes on its next prompt.
this.sessions.clear();
- if (this.restarts < MAX_WORKER_RESTARTS) {
- this.restarts += 1;
- this.options.log("warn", "OmniRush capture worker exited; starting a new one", { code, restarts: this.restarts });
- this.spawn();
- return;
- }
- this.current = "down";
- this.options.log("warn", "OmniRush capture worker exited too often; capture is off until the app restarts", { code });
+ this.scheduleRestart("OmniRush capture worker exited; starting a new one", { code });
+ }
+
+ /** Starts a new worker after the backoff's pause; calls made meanwhile are queued for it. */
+ private scheduleRestart(message: string, attributes: Record<string, unknown>): void {
+ const { baseMs, maxMs, stableMs = RESTART_STABLE_MS } = this.options.restartBackoffMs ?? RESTART_BACKOFF;
+ if (this.readyAt && Date.now() - this.readyAt >= stableMs) this.attempt = 0;
+ this.readyAt = 0;
+ const delayMs = Math.min(baseMs * 2 ** this.attempt, maxMs);
+ this.attempt += 1;
+ this.restarts += 1;
+ this.setMode("restarting");
+ this.options.log("warn", message, { ...attributes, attempt: this.attempt, delayMs });
+ this.restartTimer = setTimeout(() => this.spawn(), delayMs);
+ this.restartTimer.unref?.();
}
/**
@@ -426,22 +502,18 @@ class CaptureClient implements CaptureService {
if (reason !== null) {
this.options.log("warn", "OmniRush capture worker could not start; capturing in-process", { error: errorSummary(reason) });
}
- const { worker: _worker, stopTimeoutMs: _stopTimeoutMs, ...hostOptions } = this.options;
+ const { worker: _worker, stopTimeoutMs: _stopTimeoutMs, restartBackoffMs: _backoff, onModeChange: _onModeChange, ...hostOptions } = this.options;
+ this.canRunLocally = false;
try {
this.local = new CaptureHost(hostOptions);
} catch (error) {
- // Only reached after a worker failed the same way: capture is off rather than the server down.
+ // Only reached after a worker failed the same way: new workers are tried, with the queued calls kept for them.
if (reason === null) throw error;
- this.options.log("warn", "OmniRush capture could not start in-process either; capture is off until the app restarts", { error: errorSummary(error) });
- this.current = "down";
- this.queue = [];
- this.settleOutstanding();
+ this.scheduleRestart("OmniRush capture could not start in-process either; starting a new capture worker", { error: errorSummary(error) });
return;
}
- this.current = "local";
- const queued = this.queue;
- this.queue = [];
- for (const { call } of queued) {
+ this.setMode("local");
+ for (const { call } of this.takeQueue()) {
const id = call.id;
let value: unknown = null;
try {
diff --git a/apps/server/src/capture-worker.ts b/apps/server/src/capture-worker.ts
index 452b1bdb..d76b54f8 100644
--- a/apps/server/src/capture-worker.ts
+++ b/apps/server/src/capture-worker.ts
@@ -185,6 +185,10 @@ const host = new CaptureHost({
onSessionClosed: (sessionId) => post({ kind: "closed", sessionId }),
});
+/** Tests only (capture-client.test.ts): with OMNIRUSH_CAPTURE_TEST_CRASH=1, a trace of TEST_CRASH_TYPE ends the worker as a crash would. */
+const TEST_CRASH = process.env.OMNIRUSH_CAPTURE_TEST_CRASH === "1";
+const TEST_CRASH_TYPE = "omnirush.test.worker_crash";
+
port.on("message", (message: ToWorker) => {
if (message.kind === "result") {
const settle = pending.get(message.id);
@@ -192,6 +196,7 @@ port.on("message", (message: ToWorker) => {
settle?.(message);
return;
}
+ if (TEST_CRASH && message.method === "recordTrace" && message.args[1] === TEST_CRASH_TYPE) process.exit(70);
const { id } = message;
let value: unknown;
try {
diff --git a/apps/server/src/omnirush-capture-status.routes.test.ts b/apps/server/src/omnirush-capture-status.routes.test.ts
new file mode 100644
index 00000000..8e89459e
--- /dev/null
+++ b/apps/server/src/omnirush-capture-status.routes.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, test } from "bun:test";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { startServer } from "./server.js";
+import type { ServerConfig } from "./types.js";
+
+type Served = { port: number; stop: (closeActiveConnections?: boolean) => void | Promise<void> };
+
+async function withServer(signedIn: boolean, fn: (base: string) => Promise<void>) {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-capture-status-"));
+ const previous = process.env.OMNIRUSH_RUNTIME_DB;
+ process.env.OMNIRUSH_RUNTIME_DB = join(root, "runtime.sqlite");
+ const config: ServerConfig = {
+ host: "127.0.0.1",
+ port: 0,
+ token: "token",
+ hostToken: "host-token",
+ configPath: join(root, "server.json"),
+ approval: { mode: "auto", timeoutMs: 0 },
+ corsOrigins: [],
+ workspaces: [{ id: "ws_capture_status", name: "Test", path: root, preset: "starter", workspaceType: "local" }],
+ authorizedRoots: [root],
+ readOnly: false,
+ startedAt: Date.now(),
+ tokenSource: "generated",
+ hostTokenSource: "generated",
+ logFormat: "pretty",
+ logRequests: false,
+ // A closed loopback port: nothing leaves the machine.
+ ...(signedIn
+ ? {
+ omnirushGatewayCredentials: { gatewayUrl: "http://127.0.0.1:9/omnirush/v1", accessToken: "access-token", refreshToken: "refresh-token" },
+ omnirushEngineToken: "engine-token",
+ }
+ : {}),
+ };
+ const server = await startServer(config) as Served;
+ try {
+ await fn(`http://127.0.0.1:${server.port}`);
+ } finally {
+ await server.stop(true);
+ if (previous === undefined) delete process.env.OMNIRUSH_RUNTIME_DB;
+ else process.env.OMNIRUSH_RUNTIME_DB = previous;
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+async function status(base: string): Promise<Record<string, unknown>> {
+ const response = await fetch(`${base}/omnirush/capture/status`, { headers: { authorization: "Bearer token" } });
+ expect(response.status).toBe(200);
+ return response.json() as Promise<Record<string, unknown>>;
+}
+
+describe("GET /omnirush/capture/status", () => {
+ test("signed out, nothing is captured and the app shows no banner", async () => {
+ await withServer(false, async (base) => {
+ expect(await status(base)).toEqual({ running: true, mode: "off", since: null, restarts: 0 });
+ });
+ }, 30_000);
+
+ test("signed in, it reports the capture worker once it runs", async () => {
+ await withServer(true, async (base) => {
+ const deadline = Date.now() + 15_000;
+ let body = await status(base);
+ while (body.mode === "starting" && Date.now() < deadline) {
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 50));
+ body = await status(base);
+ }
+ expect(body).toMatchObject({ running: true, mode: "worker", restarts: 0 });
+ expect(typeof body.since === "string" && !Number.isNaN(Date.parse(body.since))).toBe(true);
+ expect((await fetch(`${base}/omnirush/capture/status`)).status).toBe(401);
+ });
+ }, 30_000);
+});
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 7f93512b..71d2de94 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -3868,6 +3868,15 @@ function createRoutes(
return jsonResponse({ allowed: true, approvalMode: resolveApprovalMode(await readGlobalRuntimeOpencodeConfig(config)).mode });
});
+ // Where session capture runs (capture-client.ts), for the app's banner while it is not running.
+ // Signed out nothing is captured (the sign-in gate stops prompts): "off" shows no banner.
+ addRoute(routes, "GET", "/omnirush/capture/status", "client", async () => {
+ const capture = captureServicesByServer.get(config);
+ if (!capture?.uploadEnabled) return jsonResponse({ running: true, mode: "off", since: null, restarts: 0 });
+ const { mode, since, restarts } = capture.status();
+ return jsonResponse({ running: mode === "worker" || mode === "local", mode, since: since.toISOString(), restarts });
+ });
+
addRoute(routes, "GET", "/cloud-provider-sync/status", "client", async () => {
return jsonResponse(cloudProviderSync.status());
});