Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

perf(engines): start a conversation's engine when it is opened or typed in

milind-soni3074da592db8
diff --git a/electron/cloud-focus-wake.mjs b/electron/cloud-focus-wake.mjs
new file mode 100644
index 0000000000..0ad73c1963
--- /dev/null
+++ b/electron/cloud-focus-wake.mjs
@@ -0,0 +1,54 @@
+// A person who uses My Cloud comes back to the app: when its window gets focus while My Cloud sleeps on a plan that
+// sleeps, My Cloud is asked to wake through the Admin, so the first message the person sends it does not wait for the
+// wake. Off unless OMB_CLOUD_FOCUS_WAKE=1: a wake nobody follows keeps the Cloud awake until it is idle again (at least
+// CLOUD_IDLE_AWAKE_MS, 2 minutes, plus the Admin's next power read, server/cloud-power.ts).
+//
+// "Uses My Cloud" is read from this computer alone: the window showed My Cloud's page when it got or lost focus in the
+// last 7 days. With no such record nothing is woken.
+
+export const CLOUD_FOCUS_WAKE_FILE = "cloud-focus-wake.json";
+/** Fewer wakes than this apart, however often the window is focused. */
+export const FOCUS_WAKE_GAP_MS = 15 * 60_000;
+export const USED_WITHIN_MS = 7 * 24 * 60 * 60_000;
+/** The use record is written at most this often. */
+const USED_WRITE_MS = 60 * 60_000;
+
+export const focusWakeEnabled = (env = process.env) => env.OMB_CLOUD_FOCUS_WAKE === "1";
+
+/**
+ * `account()`: the Cloud account client (`power()`, the Admin's word on My Cloud; `wakeHome()`, the Admin's wake for
+ * My Cloud only). `pref`: a JSON file (`read`, `write`) for the use record.
+ */
+export function createCloudFocusWake({ enabled = focusWakeEnabled, account, pref, now = Date.now, log = () => {} }) {
+ let lastWake = -Infinity, usedAt;
+ const readUsed = () => {
+ if (usedAt !== undefined) return usedAt;
+ try { const at = pref.read()?.usedAt; usedAt = Number.isFinite(at) ? at : null; } catch { usedAt = null; }
+ return usedAt;
+ };
+ const used = () => {
+ const at = now(), before = readUsed();
+ if (before !== null && at - before < USED_WRITE_MS) return;
+ usedAt = at;
+ try { pref.write({ usedAt: at }); } catch {}
+ };
+ return {
+ /** The window got focus. `shown`: it is on screen, neither hidden nor minimized. `showingCloud`: it shows My Cloud's
+ * page, which wakes My Cloud itself on focus. Returns whether a wake was asked for. */
+ focused({ shown, showingCloud }) {
+ if (showingCloud) { used(); return false; }
+ if (!enabled() || !shown) return false;
+ const at = now(), since = readUsed();
+ if (since === null || at - since > USED_WITHIN_MS || at - lastWake < FOCUS_WAKE_GAP_MS) return false;
+ const client = account();
+ if (client?.power()?.state !== "asleep") return false;
+ lastWake = at;
+ void Promise.resolve().then(() => client.wakeHome()).then((state) => log(`cloud: asked My Cloud to wake on focus (${state ?? "no answer"})`), () => {});
+ return true;
+ },
+ /** The window lost focus. */
+ blurred({ showingCloud }) {
+ if (showingCloud) used();
+ },
+ };
+}
diff --git a/electron/cloud-focus-wake.node-test.mjs b/electron/cloud-focus-wake.node-test.mjs
new file mode 100644
index 0000000000..f52b5d17f9
--- /dev/null
+++ b/electron/cloud-focus-wake.node-test.mjs
@@ -0,0 +1,85 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { createCloudFocusWake, FOCUS_WAKE_GAP_MS, focusWakeEnabled, USED_WITHIN_MS } from "./cloud-focus-wake.mjs";
+
+const DAY = 24 * 60 * 60_000;
+
+function fixture({ enabled = true, state = "asleep", usedAt = undefined, client = true } = {}) {
+ const world = { now: 10 * DAY, wakes: 0, writes: [], stored: usedAt === undefined ? null : { usedAt }, state };
+ const account = { power: () => (world.state ? { state: world.state, since: 1, sleeps: true } : null), wakeHome: async () => { world.wakes += 1; return "awake"; } };
+ const wake = createCloudFocusWake({
+ enabled: () => enabled,
+ account: () => (client ? account : null),
+ pref: { read: () => { if (!world.stored) throw new Error("ENOENT"); return world.stored; }, write: (value) => { world.writes.push(value); world.stored = value; } },
+ now: () => world.now,
+ });
+ return { world, wake };
+}
+const settle = () => new Promise((resolve) => setImmediate(resolve));
+
+test("off unless OMB_CLOUD_FOCUS_WAKE is 1", () => {
+ assert.equal(focusWakeEnabled({}), false);
+ assert.equal(focusWakeEnabled({ OMB_CLOUD_FOCUS_WAKE: "0" }), false);
+ assert.equal(focusWakeEnabled({ OMB_CLOUD_FOCUS_WAKE: "1" }), true);
+});
+
+test("wakes My Cloud once on focus when it sleeps and the person used it this week", async () => {
+ const { world, wake } = fixture({ usedAt: 10 * DAY - 6 * DAY });
+ assert.equal(wake.focused({ shown: true, showingCloud: false }), true);
+ await settle();
+ assert.equal(world.wakes, 1);
+});
+
+test("never on a window that is hidden or minimized, never when switched off, never for a Cloud that is awake or unknown", async () => {
+ const recent = 10 * DAY - DAY;
+ for (const [options, focus] of [
+ [{ usedAt: recent }, { shown: false, showingCloud: false }],
+ [{ usedAt: recent, enabled: false }, { shown: true, showingCloud: false }],
+ [{ usedAt: recent, state: "awake" }, { shown: true, showingCloud: false }],
+ [{ usedAt: recent, state: null }, { shown: true, showingCloud: false }],
+ [{ usedAt: recent, client: false }, { shown: true, showingCloud: false }],
+ ]) {
+ const { world, wake } = fixture(options);
+ assert.equal(wake.focused(focus), false, JSON.stringify(options));
+ await settle();
+ assert.equal(world.wakes, 0);
+ }
+});
+
+test("never for a person with no record of using My Cloud here, or none in the last 7 days", async () => {
+ for (const usedAt of [undefined, 10 * DAY - USED_WITHIN_MS - 1]) {
+ const { world, wake } = fixture({ usedAt });
+ assert.equal(wake.focused({ shown: true, showingCloud: false }), false);
+ await settle();
+ assert.equal(world.wakes, 0);
+ }
+});
+
+test("asks again only after FOCUS_WAKE_GAP_MS, however often the window is focused", async () => {
+ const { world, wake } = fixture({ usedAt: 10 * DAY - DAY });
+ assert.equal(wake.focused({ shown: true, showingCloud: false }), true);
+ world.now += FOCUS_WAKE_GAP_MS - 1;
+ assert.equal(wake.focused({ shown: true, showingCloud: false }), false);
+ world.now += 1;
+ assert.equal(wake.focused({ shown: true, showingCloud: false }), true);
+ await settle();
+ assert.equal(world.wakes, 2);
+});
+
+test("records a use when the window shows My Cloud as it gets or loses focus, and wakes nothing itself then", async () => {
+ const { world, wake } = fixture();
+ assert.equal(wake.focused({ shown: true, showingCloud: false }), false);
+ assert.equal(wake.focused({ shown: true, showingCloud: true }), false);
+ assert.deepEqual(world.writes, [{ usedAt: 10 * DAY }]);
+ world.now += 60_000;
+ wake.blurred({ showingCloud: true });
+ assert.equal(world.writes.length, 1, "written at most hourly");
+ world.now += 60 * 60_000;
+ wake.blurred({ showingCloud: true });
+ wake.blurred({ showingCloud: false });
+ assert.equal(world.writes.length, 2);
+ assert.equal(wake.focused({ shown: true, showingCloud: false }), true);
+ await settle();
+ assert.equal(world.wakes, 1);
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index 7075920e16..d5fbf65457 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -99,7 +99,7 @@ import { CHECKOUT_SOURCES, cloudMenuSublabel, cloudTarget, createCloudAccountCli
import { installCloudPlanIpc } from "./cloud-plan-ipc.mjs";
import { cloudLinkOpensSheet, colorDotIcons, createCloudLook, createCloudReadyNotice, installCloudBuy, lookFile } from "./cloud-buy.mjs"; import { unreadBadgeIcon } from "./color-dot.mjs";
import { createTrialNotices } from "./cloud-trial-notice.mjs";
-import { createDesktopText, DESKTOP_PORTS, jsonFile, registerDesktopPrefs, relabelDesktop } from "./desktop-prefs.mjs";
+import { createDesktopText, DESKTOP_PORTS, jsonFile, registerDesktopPrefs, relabelDesktop } from "./desktop-prefs.mjs"; import { CLOUD_FOCUS_WAKE_FILE, createCloudFocusWake } from "./cloud-focus-wake.mjs";
import { createDesktopIncludedX } from "./included-x.mjs"; import { createDesktopIncludedPages } from "./included-pages.mjs"; import { createPhoneLinkFact } from "./phone-link-fact.mjs"; import { createPhonePushAccessSync } from "./phone-push-access.mjs";
import { cloudPageSenderAllowed, cloudPlanDisk, cloudUnreachableText, createCloudPowerGate, isCloudHomeEntry, myCloudOrigin, rememberedCloudHome, savedCloudHomeOrigin, signInCloudSession, withCloudHome } from "./cloud-home.mjs";
import { installCloudFiles } from "./cloud-sync-main.mjs";
@@ -288,7 +288,7 @@ let companyRestoreCommitting = false;
let companyBackupConfigurationRevision = 0;
const managedDesktopRelay = createManagedDesktopRelay();
const includedX = createDesktopIncludedX({ account: () => cloudAccount, server: () => serverProc, log: slog }), includedPages = createDesktopIncludedPages({ account: () => cloudAccount, server: () => serverProc, log: slog }), phoneLinkFact = createPhoneLinkFact({ retired: () => companionTunnelRetired(secureCredentialState?.read() ?? secureCredentials), server: () => (serverReady ? serverProc : null), log: slog }), phonePushAccess = createPhonePushAccessSync({ server: () => (serverReady ? serverProc : null), credentials: () => secureCredentialState?.read() ?? secureCredentials, controlPlane: () => resolveCompanionControlPlaneURL({ isPackaged: app.isPackaged, environment: process.env }), log: slog });
-const cloudPower = createCloudPowerGate({ power: () => cloudAccount?.power() ?? null, wanted: () => Boolean(cloudSync?.running() || computerSharing?.lendingToCloud()) });
+const cloudPower = createCloudPowerGate({ power: () => cloudAccount?.power() ?? null, wanted: () => Boolean(cloudSync?.running() || computerSharing?.lendingToCloud()) }); const focusWakeFile = () => jsonFile(path.join(app.getPath("userData"), CLOUD_FOCUS_WAKE_FILE)), cloudFocusWake = createCloudFocusWake({ account: () => cloudAccount, pref: { read: () => focusWakeFile().read(), write: (value) => focusWakeFile().write(value) }, log: slog });
const utilityServerExits = new WeakMap(), systemProxy = createSystemProxyCache(), bootHeadStart = createBootHeadStart({ credentials: () => launchRecord.span("keychain", () => loadSecureCredentials()), proxy: () => systemProxy.refresh() }); launchRecord.mark("mainImported"); // A Mac app opened from Finder never gets the shell's proxy.
const UTILITY_SERVER_STOP_TIMEOUT_MS = 9_500; // the server's shutdown deadline (8 s, server/graceful-shutdown.ts) and its 1 s log flush
const trustedApprovalMode = createTrustedApprovalModeCoordinator({ randomId: randomUUID, t: (...args) => nativeT(...args) });
@@ -1952,7 +1952,7 @@ function createWindow({ deferNavigation = false } = {}) {
});
mainWindow = win; hiddenStart = false; chromeRail.attach(win);
win.on("show", () => desktopTray?.windowShown(win));
- win.on("focus", () => { if (cloudAccount?.checkoutPending()) void cloudAccount.refresh().catch(() => {}); });
+ win.on("focus", () => { if (cloudAccount?.checkoutPending()) void cloudAccount.refresh().catch(() => {}); cloudFocusWake.focused({ shown: !desktopRemoteAccess && win.isVisible() && !win.isMinimized(), showingCloud: placeShown() === "cloud" }); }); win.on("blur", () => cloudFocusWake.blurred({ showingCloud: placeShown() === "cloud" }));
win.on("close", (event) => {
if (process.platform === "win32" && !desktopShutdownStarted && desktopTray) {
event.preventDefault();
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index c87b72c5fc..c7d914be48 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -11,7 +11,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_ACP_QUIET_TICK_MS", "OMB_TASK_WORKSPACE_RETENTION", "OMB_CONVERSATION_FOLDER_CLEANUP", "OMB_ORPHAN_SWEEP", "OMB_ORPHAN_SWEEP_MAX_SHARE", "OMB_IDLE_RECLAIM", "OMB_ACP_SESSION_IDLE_", "OMB_ACP_SHARED_RECYCLE_MS", "OMB_ADMIN_", "OMB_ADMIN_MEMBERSHIP",
"OMB_ADMIN_URL", "OMB_ADMIN_WORKSPACE", "OMB_AGENT_BROWSER_PATH", "OMB_AI_CHECKS", "OMB_ANTHROPIC_API_KEY", "OMB_ANTIGRAVITY_NATIVE_CLI",
"OMB_ANTHROPIC_API_URL", "OMB_APP_VERSION", "OMB_ATTACHMENTS_MAX_BYTES", "OMB_AZURE_OPENAI_LIVE_DEPLOYMENT",
- "OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BENCH", "OMB_BOAT_API", "OMB_BOTS_FULL_SAVE", "OMB_BOTS_SAVE_CHECK", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE",
+ "OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BENCH", "OMB_BOAT_API", "OMB_CLOUD_FOCUS_WAKE", "OMB_ENGINE_PRESTART", "OMB_BOTS_FULL_SAVE", "OMB_BOTS_SAVE_CHECK", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE",
"OMB_BROWSER_CGROUP", "OMB_BROWSER_CONNECTION", "OMB_BROWSER_HOLD_IDLE_MS", "OMB_BROWSER_IDLE_HANDOVER_MS", "OMB_BROWSER_LANG", "OMB_BROWSER_LEGACY_SHELL",
"OMB_BROWSER_MAX_RUNNING", "OMB_BROWSER_MEMORY_MAX", "OMB_BROWSER_SANDBOX", "OMB_BROWSER_SCREEN", "OMB_BROWSER_TIMEZONE", "OMB_BROWSER_TIMING",
"OMB_BUG_REPORT_URL", "OMB_CACHE_CAP_APP", "OMB_CACHE_CAP_TOOLS", "OMB_CACHE_ROOT", "OMB_CACHE_SWEEP", "OMB_CADDY_PATH", "OMB_CHECKPOINT_GIT_MAX", "OMB_CHROME_PATH", "OMB_CLAUDE_AUTOCOMPACT",
diff --git a/server/contracts.ts b/server/contracts.ts
index dbefbf8ffa..3e644e66f6 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -350,13 +350,15 @@ export interface ProviderAdapter {
* still on that session takes it: otherwise `ok` is false and nothing was sent to the engine. `usage` is null when the
* engine reports none for the compaction. */
compactSession?(threadId: ThreadId, options: { botId?: string; session: string; model?: string | null; selectionNow?: () => { instanceId: string; model: string | null } | undefined; signal?: AbortSignal }): Promise<EngineCompactResult>;
- /** Starting a thread's engine before its first message, so that message finds it running. `start` launches the process
- * exactly as a turn with this input would and sends it nothing; it resolves true once the process is launched. The next
- * sendTurn on the thread takes that process when its launch would have been the same and it has started up (`ready`),
- * and replaces it otherwise. `held`: one is launching or waiting. `drop` stops one that no turn took; a taken one is
- * the turn's own. */
+ /** Starting a thread's engine before its next message, so that message finds it running. `start` launches the process
+ * exactly as a turn with this input would and sends it nothing; it resolves true once the process is launched, and the
+ * process closes by itself after `waitMs` (a driver default when absent) with no turn. The next sendTurn on the thread
+ * takes that process when its launch would have been the same, it resumes the same engine session (or none, for a
+ * process started without one), it has started up (`ready`) and it is not older than its wait by the wall clock (it
+ * waited through a sleep); it is replaced otherwise. `held`: one is launching or waiting. `drop` stops one that no turn
+ * took; a taken one is the turn's own. */
prestart?: {
- start(input: SendTurnInput): Promise<boolean>;
+ start(input: SendTurnInput, waitMs?: number): Promise<boolean>;
held(threadId: ThreadId): boolean;
ready(threadId: ThreadId): boolean;
drop(threadId: ThreadId): void;
diff --git a/server/crash-guard.ts b/server/crash-guard.ts
index a0caa4f399..42792aea85 100644
--- a/server/crash-guard.ts
+++ b/server/crash-guard.ts
@@ -37,7 +37,7 @@ export function withTurnScope<I extends Pick<ProviderInstance, "adapter">>(insta
...adapter,
sendTurn: (input) => runInTurn({ botId: input.botId ?? "", threadId: input.threadId }, () => adapter.sendTurn(input)),
// An engine started ahead of its first turn is that conversation's too: what it throws later belongs to the turn that took it.
- ...(adapter.prestart ? { prestart: { ...adapter.prestart, start: (input) => runInTurn({ botId: input.botId ?? "", threadId: input.threadId }, () => adapter.prestart!.start(input)) } } : {}),
+ ...(adapter.prestart ? { prestart: { ...adapter.prestart, start: (input, waitMs) => runInTurn({ botId: input.botId ?? "", threadId: input.threadId }, () => adapter.prestart!.start(input, waitMs)) } } : {}),
onEvent: (listener) => adapter.onEvent((event) => outsideTurn(() => listener(event))),
};
return instance;
diff --git a/server/drivers/claude-prestart.test.ts b/server/drivers/claude-prestart.test.ts
index 058d294c3d..9c9304884e 100644
--- a/server/drivers/claude-prestart.test.ts
+++ b/server/drivers/claude-prestart.test.ts
@@ -257,6 +257,63 @@ describe("ClaudeDriver: a process started before the first message (fake CLI)",
expect(recorder.events).toEqual([]);
});
+ it("resuming a session, is taken only by a turn that resumes that same session", async () => {
+ expect(await started("t-resumed", 1, { resumeCursor: "session-old" })).toBe(true);
+ expect(lines(launches)[0].argv).toEqual(expect.arrayContaining(["--resume", "session-old"]));
+ await instance.adapter.sendTurn(turn("t-resumed", { resumeCursor: "session-old" }));
+ await recorder.until((e) => e.type === "turn.completed" && e.threadId === "t-resumed");
+ expect(pids()).toHaveLength(1);
+ expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
+
+ for (const [threadId, cursor] of [["t-new-session", undefined], ["t-other-session", "session-other"]] as const) {
+ const before = pids().length;
+ expect(await started(threadId, before + 1, { resumeCursor: "session-old" })).toBe(true);
+ const [spare] = pids().slice(-1);
+ await instance.adapter.sendTurn(turn(threadId, cursor ? { resumeCursor: cursor } : {}));
+ await recorder.until((e) => e.type === "turn.completed" && e.threadId === threadId);
+ expect(pids()).toHaveLength(before + 2);
+ await until(() => !alive(spare!), "the unused process to exit");
+ expect(lines(launches).at(-1).argv).not.toContain("session-old");
+ }
+ expect(recorder.events.filter((e) => e.type === "runtime.error")).toEqual([]);
+ });
+
+ it("waits as long as it was started to wait", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ expect(await instance.adapter.prestart!.start(turn("t-longer", { text: "" }), 180_000)).toBe(true);
+ vi.advanceTimersByTime(PRESTART_IDLE_MS);
+ expect(instance.adapter.prestart!.held("t-longer")).toBe(true);
+ vi.advanceTimersByTime(180_000 - PRESTART_IDLE_MS);
+ vi.useRealTimers();
+ await until(() => !instance.adapter.prestart!.held("t-longer"), "the driver to close it");
+ await until(() => pids().every((pid) => !alive(pid)), "the process to exit");
+ expect(recorder.events).toEqual([]);
+ });
+
+ it("is never taken once it waited past its time by the wall clock (the machine slept)", async () => {
+ expect(await started("t-slept", 1)).toBe(true);
+ const [spare] = pids();
+ const now = Date.now();
+ const clock = vi.spyOn(Date, "now").mockReturnValue(now + PRESTART_IDLE_MS + 60 * 60_000);
+ try {
+ await instance.adapter.sendTurn(turn("t-slept"));
+ } finally { clock.mockRestore(); }
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(pids()).toHaveLength(2);
+ await until(() => !alive(spare!), "the stale process to exit");
+ expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
+ });
+
+ it("is no session to keep warm, ping or summarize: nothing is sent to the engine for it", async () => {
+ expect(await started("t-quiet", 1, { resumeCursor: "session-quiet" })).toBe(true);
+ const ping = await instance.adapter.cacheKeepWarm!.ping("t-quiet");
+ expect(ping).toMatchObject({ ok: false });
+ expect(instance.adapter.cacheKeepWarm!.hold("t-quiet", Date.now() + 600_000)).toBe(false);
+ expect(lines(prompts)).toEqual([]);
+ expect(pids()).toHaveLength(1);
+ expect(recorder.events).toEqual([]);
+ });
+
it("says nothing when it cannot start", async () => {
await instance.adapter.prestart!.start(turn("t-nowhere", { text: "", cwd: join(scratch, "no-such-folder") }));
await until(() => !instance.adapter.prestart!.held("t-nowhere"), "the driver to forget it");
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index 7325002e34..442f391461 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -812,8 +812,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
closing: boolean;
unconfirmedStopWarned?: boolean;
/** Started before any message was sent (the adapter's `prestart`) and not yet taken by a turn: it says nothing in the chat.
- * `take` makes the turn that takes it the one its launch is counted as. */
- spare?: boolean;
+ * `take` makes the turn that takes it the one its launch is counted as. It waits `spareMs` from `spareAt` (wall clock), on the session it `resumed`. */
+ spare?: boolean; spareMs?: number; spareAt?: number; resumed?: string;
take?: (turnId: string) => void;
tools?: ClaudePrestartTools;
/** The engine could not start the `agents` MCP server: retired after this turn so the next one reconnects. */
@@ -862,7 +862,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
const s = sessions.get(threadId);
if (!s || s.closing) return;
s.closing = true;
- forks.closed(threadId, why, s.sessionId);
+ if (!s.spare) forks.closed(threadId, why, s.sessionId);
stopIdleClose(`${instanceId}\0${threadId}`, s.idleTimer);
// Close the broker before a replacement binds the same socket; a late close must not unlink it.
const broker = s.broker;
@@ -882,12 +882,12 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (!s) return;
if (s.idleTimer) clearTimeout(s.idleTimer);
const held = (warmHolds.get(threadId) ?? 0) - Date.now();
- s.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, s.spare ? PRESTART_IDLE_MS : Math.min(2_147_483_647, Math.max(engineIdleMs(threadId, sessionIdle), held)), { close: () => closeSession(threadId, s.spare ? "never used" : "idle"), threadId, policy: sessionIdle, spare: () => s.spare === true, // per-chat
+ s.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, s.spare ? s.spareMs ?? PRESTART_IDLE_MS : Math.min(2_147_483_647, Math.max(engineIdleMs(threadId, sessionIdle), held)), { close: () => closeSession(threadId, s.spare ? "never used" : "idle"), threadId, policy: sessionIdle, spare: () => s.spare === true, // per-chat
idle: () => sessions.get(threadId) === s && !s.closing && !s.turn && !active.has(threadId), held: () => (warmHolds.get(threadId) ?? 0) > Date.now() });
};
// Keep-warm pings and warm summaries fork a thread's session with its live launch contract (claude-warm-summary.ts).
const forks = claudeForks({ cli: config.cli, contracts: warmContracts, holds: warmHolds, armIdle, supports: (flag) => cliVersion === null || claudeCliSupports(cliVersion, flag),
- live: (threadId) => { const s = sessions.get(threadId); return s && !s.closing && s.child.exitCode === null ? { sessionId: s.sessionId, turn: Boolean(s.turn), busy: Boolean(s.turn) || active.has(threadId) } : null; },
+ live: (threadId) => { const s = sessions.get(threadId); return s && !s.spare && !s.closing && s.child.exitCode === null ? { sessionId: s.sessionId, turn: Boolean(s.turn), busy: Boolean(s.turn) || active.has(threadId) } : null; },
summarized: (threadId, run) => { const cost = claudeCostSnapshot(run.costTotal, run.modelUsage); if (cost) recordCostState(run.session, cost); closeSession(threadId, "summarized while idle"); } });
const writeUser = (s: Session, threadId: string, promptMsg: ClaudeUserMessage): Promise<boolean> => {
if (!s.child.stdin.writable || s.child.stdin.destroyed) return Promise.resolve(false);
@@ -927,7 +927,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
const retryState = new Map<string, { attempt: number; cancelled: boolean; rebuilt?: boolean }>();
/** `spare`: launch the thread's process as this turn would and stop there: nothing is written to it and no turn starts. */
- const sendTurn = async (turn: SendTurnInput, logicalTurnId?: string, spare = false) => {
+ const sendTurn = async (turn: SendTurnInput, logicalTurnId?: string, spare = false, spareMs?: number) => {
if (startupModelRefresh) await startupModelRefresh;
turn = { ...turn, toolScope: assertToolScopeSupported(DRIVER_KIND, turn.toolScope) };
if (config.managedModels && (!turn.model || !config.managedModels.includes(turn.model))) throw new Error("This model is not assigned to this workspace.");
@@ -1159,11 +1159,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
// A process started ahead is taken once it has started up and has listed again the tools the harness serves only during a turn.
const ahead = sessions.get(threadId);
- if (!spare && ahead?.spare && !ahead.closing && ahead.argsKey === argsKey && !(ahead.tools?.ready && await ahead.tools.relist(Object.keys(mcpServers)))) closeSession(threadId, "never used");
+ if (!spare && ahead?.spare && !ahead.closing && (Date.now() - (ahead.spareAt ?? 0) > (ahead.spareMs ?? PRESTART_IDLE_MS) + 5_000 || (ahead.argsKey === argsKey && !(ahead.tools?.ready && await ahead.tools.relist(Object.keys(mcpServers)))))) closeSession(threadId, "never used");
const live = sessions.get(threadId);
- if (!turn.sessionReset && live && !live.turn && !live.closing && live.child.exitCode === null && live.argsKey === argsKey && (!sessionId || sessionId === live.sessionId)) {
+ if (!turn.sessionReset && live && !live.turn && !live.closing && live.child.exitCode === null && live.argsKey === argsKey && (sessionId ? sessionId === live.sessionId : !live.resumed)) {
stopIdleClose(`${instanceId}\0${threadId}`, live.idleTimer); // busy again: no longer idle
- if (live.spare) { live.spare = false; live.take?.(turnId); appendNative(threadId, { dir: "out", source: "claude.session", msg: { took: "prestarted" } }); }
+ if (live.spare) { live.spare = false; live.resumed = undefined; live.take?.(turnId); appendNative(threadId, { dir: "out", source: "claude.session", msg: { took: "prestarted" } }); }
live.turn = { turnId, input: turn, retryAbort, settled: false, sawStreamDelta: false, awaitingInit: true, pendingSteers: new Set(), deferred: null, continuationGrace: null, continuationSilence: null };
active.set(threadId, { stop: () => {
if (live.turn) live.turn.stopRequested = true;
@@ -1324,7 +1324,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
replaysUserMessages,
turn: spare ? null : { turnId, input: turn, retryAbort, settled: false, sawStreamDelta: false, pendingSteers: new Set(), deferred: null, continuationGrace: null, continuationSilence: null },
idleTimer: null,
- closing: false, spare, take: (taker) => { turnId = taker; }, ...(spare ? { tools: spareTools.forProcess((frame) => writeControlFrame(child.stdin, frame)) } : {}),
+ closing: false, spare, take: (taker) => { turnId = taker; }, ...(spare ? { tools: spareTools.forProcess((frame) => writeControlFrame(child.stdin, frame)), spareMs, spareAt: Date.now(), ...(sessionId ? { resumed: sessionId } : {}) } : {}),
stderr: "",
costTotal: undefined,
};
@@ -1975,9 +1975,9 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
enginePid: (threadId) => (active.has(threadId) ? sessions.get(threadId)?.child.pid : undefined),
cacheKeepWarm: forks.adapter,
prestart: {
- start: (turn) => {
+ start: (turn, waitMs) => {
if (!spareTools.usable) return Promise.resolve(false);
- const launch = sendTurn(turn, undefined, true).then(() => sessions.get(turn.threadId)?.spare === true, () => false).finally(() => { if (spares.get(turn.threadId) === launch) spares.delete(turn.threadId); });
+ const launch = sendTurn(turn, undefined, true, waitMs).then(() => sessions.get(turn.threadId)?.spare === true, () => false).finally(() => { if (spares.get(turn.threadId) === launch) spares.delete(turn.threadId); });
spares.set(turn.threadId, launch);
return launch;
},
diff --git a/server/drivers/session-idle.test.ts b/server/drivers/session-idle.test.ts
index f7df5d29a7..45df69d905 100644
--- a/server/drivers/session-idle.test.ts
+++ b/server/drivers/session-idle.test.ts
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { forgetPresence, personAsks, sawThread, seenWithin } from "../thread-presence.ts";
import {
- armedIdleCount, armIdleClose, engineIdleMs, idleEngineCap, idleEnginesAllowed, keepWarm, PRESTART_IDLE_MS, PRESTART_MOST, prestartAllowed, sessionIdlePolicy, SMALL_BOX_BYTES,
+ armedIdleCount, armIdleClose, engineIdleMs, idleEngineCap, idleEnginesAllowed, keepWarm, OPENED_PRESTART_IDLE_MS, PRESTART_ENGINE_BYTES, PRESTART_IDLE_MS, PRESTART_MOST, prestartAllowed, sessionIdlePolicy, SMALL_BOX_BYTES,
SMALL_BOX_IDLE_ENGINES, SMALL_BOX_IDLE_MS, stopIdleClose, sweepIdleEngines,
UNWATCHED_IDLE_MS, warmEngineKeys, type WarmEngine, EXPENSIVE_IDLE_MS, EXPENSIVE_UNWATCHED_IDLE_MS, roomBesideIdle,
} from "./session-idle.ts";
@@ -305,14 +305,35 @@ describe("engines started before a first message", () => {
afterEach(() => { for (const key of warmEngineKeys()) stopIdleClose(key, null); });
it("are for hosts where memory is not rationed: none on a small box, none where turns wait for room", () => {
- expect(prestartAllowed({ bytes: DESKTOP }, { enabled: false })).toBe(true);
- expect(prestartAllowed({ bytes: SMALL_BOX_BYTES }, { enabled: false })).toBe(false);
- expect(prestartAllowed({ bytes: GB }, { enabled: false })).toBe(false);
- expect(prestartAllowed({ bytes: DESKTOP }, { enabled: true })).toBe(false);
+ const roomy = () => 8 * GB;
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: false }, roomy, undefined)).toBe(true);
+ expect(prestartAllowed({ bytes: SMALL_BOX_BYTES }, { enabled: false }, roomy, undefined)).toBe(false);
+ expect(prestartAllowed({ bytes: GB }, { enabled: false }, roomy, undefined)).toBe(false);
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: true }, roomy, undefined)).toBe(false);
});
- it("wait no longer than an engine nobody is looking at is kept, and only a couple at once", () => {
+ it("are not started while one more waiting engine would take free memory below the floor admission keeps", () => {
+ // 16 GB: the floor is a tenth, 1.6 GB, and a waiting engine counts as PRESTART_ENGINE_BYTES.
+ const floor = 0.1 * DESKTOP;
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: false }, () => floor + PRESTART_ENGINE_BYTES, undefined)).toBe(true);
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: false }, () => floor + PRESTART_ENGINE_BYTES - 1, undefined)).toBe(false);
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: false }, () => 300 * 1024 ** 2, undefined)).toBe(false);
+ // 4 GB: the floor is 409.6 MB, above the 320 MB minimum.
+ expect(prestartAllowed({ bytes: 4 * GB }, { enabled: false }, () => 0.39 * GB + PRESTART_ENGINE_BYTES, undefined)).toBe(false);
+ expect(prestartAllowed({ bytes: 4 * GB }, { enabled: false }, () => 0.41 * GB + PRESTART_ENGINE_BYTES, undefined)).toBe(true);
+ });
+
+ it("are off with OMB_ENGINE_PRESTART=0, and skip only the free-memory reading when it is `unmetered`", () => {
+ const short = () => 0;
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: false }, () => 8 * GB, "0")).toBe(false);
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: false }, short, "unmetered")).toBe(true);
+ expect(prestartAllowed({ bytes: SMALL_BOX_BYTES }, { enabled: false }, short, "unmetered")).toBe(false);
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: true }, short, "unmetered")).toBe(false);
+ });
+
+ it("wait no longer than an engine nobody is looking at is kept, a few minutes for a conversation opened, and only a couple at once", () => {
expect(PRESTART_IDLE_MS).toBe(UNWATCHED_IDLE_MS);
+ expect(OPENED_PRESTART_IDLE_MS).toBe(3 * 60_000);
expect(PRESTART_MOST).toBe(2);
});
diff --git a/server/drivers/session-idle.ts b/server/drivers/session-idle.ts
index 3aba8b8f90..64a524151d 100644
--- a/server/drivers/session-idle.ts
+++ b/server/drivers/session-idle.ts
@@ -16,7 +16,7 @@
// closes as another goes idle, and its conversation's next turn resumes its session by id.
import { availableMemory, boxMemory, type BoxMemory } from "../box-memory.ts";
import { stoppedForBotMemory } from "../bot-memory-cap.ts";
-import { ENGINE_MAX_BYTES, engineMemory, type EngineMemory } from "../engine-memory.ts";
+import { ENGINE_MAX_BYTES, engineMemory, memoryFloor, type EngineMemory } from "../engine-memory.ts";
import { onThreadSeen, seenWithin } from "../thread-presence.ts";
export type IdleScope = "per-chat" | "per-bot" | "shared";
@@ -233,13 +233,22 @@ export const UNWATCHED_IDLE_MS = 30_000;
/** An engine started before any message (a person just made a conversation) waits this long for the first one: the time
* an engine nobody is looking at is already kept, and longer than writing a first line usually takes. */
export const PRESTART_IDLE_MS = UNWATCHED_IDLE_MS;
+/** An engine started because a person opened a conversation or began typing in it waits this long for their message:
+ * reading the conversation and writing a reply can take a few minutes. */
+export const OPENED_PRESTART_IDLE_MS = 3 * 60_000;
/** Each waiting engine holds 250 to 450 MB, so only this many wait at once. */
export const PRESTART_MOST = 2;
+/** What one waiting engine and its MCP servers take at most. */
+export const PRESTART_ENGINE_BYTES = 450 * 1024 ** 2;
-/** Engines start ahead of a message only where memory is not rationed: never on a small box, and never where turns wait
- * for room (a Cloud home, a self-hosted server), whose admission counts the engines a turn starts. */
-export function prestartAllowed(box: Pick<BoxMemory, "bytes"> = boxMemory(), memory: Pick<EngineMemory, "enabled"> = engineMemory): boolean {
- return !memory.enabled && box.bytes > SMALL_BOX_BYTES;
+/** Engines start ahead of a message only where memory is not rationed: never on a small box, never where turns wait for
+ * room (a Cloud home, a self-hosted server), whose admission counts the engines a turn starts, and never while free memory
+ * would sink below the floor admission keeps (engine-memory.ts) with one more waiting engine. OMB_ENGINE_PRESTART=0 turns
+ * it off; `unmetered` leaves out the free-memory reading only, for tests on machines whose free memory varies. */
+export function prestartAllowed(box: Pick<BoxMemory, "bytes"> = boxMemory(), memory: Pick<EngineMemory, "enabled"> = engineMemory,
+ available: () => number = availableMemory, setting: string | undefined = process.env.OMB_ENGINE_PRESTART): boolean {
+ if (setting === "0" || memory.enabled || box.bytes <= SMALL_BOX_BYTES) return false;
+ return setting === "unmetered" || available() - memoryFloor(box.bytes) >= PRESTART_ENGINE_BYTES;
}
/**
diff --git a/server/engine-homes/engine-homes.ts b/server/engine-homes/engine-homes.ts
index 968b0b5034..6f3f8ea783 100644
--- a/server/engine-homes/engine-homes.ts
+++ b/server/engine-homes/engine-homes.ts
@@ -115,7 +115,7 @@ export function withEngineHomes(instance: ProviderInstance, homes: EngineHomes =
...adapter,
sendTurn: (input) => homes.within(input.threadId, () => adapter.sendTurn(input), input.botId),
...(adapter.compactSession ? { compactSession: (threadId, options) => homes.within(threadId, () => adapter.compactSession!(threadId, options), options.botId) } : {}),
- ...(adapter.prestart ? { prestart: { ...adapter.prestart, start: (input) => homes.within(input.threadId, () => adapter.prestart!.start(input), input.botId) } } : {}),
+ ...(adapter.prestart ? { prestart: { ...adapter.prestart, start: (input, waitMs) => homes.within(input.threadId, () => adapter.prestart!.start(input, waitMs), input.botId) } } : {}),
...(warm ? { cacheKeepWarm: {
...warm,
ping: (threadId, options) => homes.within(threadId, () => warm.ping(threadId, options)),
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index 7bfdc81e60..cdc84f1aa2 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -25,6 +25,8 @@ export const ENGINE_MAX_BYTES = 1500 * MB;
/** One more session in a running shared process: OpenCode 1.19.3 grew about 110 MB a session with three stdio MCP
* servers after a prompt; more MCP servers cost more. */
export const SESSION_BYTES = 200 * MB;
+/** Memory the server, Chrome and the page cache keep: below it a machine without swap starts to thrash. */
+export const memoryFloor = (totalBytes: number): number => Math.max(320 * MB, totalBytes * 0.1);
/** One bot's browser (agent-browser's daemon and its Chrome) on a page or two: 270 to 390 MB per bot on an 8 GB Cloud home,
* 2026-10-21. It runs outside the engine's process group, so an engine's measured size never includes it. */
export const BROWSER_BYTES = 400 * MB;
@@ -721,8 +723,7 @@ export class EngineMemory {
/** Runs on every tick (every couple of seconds while engines run): the idle policy closes what it kept too long. */
useIdleSweep(sweep: () => void): void { this.idleSweep = sweep; }
- /** Memory the server, Chrome and the page cache keep: below it a machine without swap starts to thrash. */
- private floor(memory: HostMemory): number { return Math.max(320 * MB, memory.totalBytes * 0.1); }
+ private floor(memory: HostMemory): number { return memoryFloor(memory.totalBytes); }
private free(memory: HostMemory): number { return memory.availableBytes + memory.swapFreeBytes / 2; }
diff --git a/server/engine-prestart-opened.e2e.test.ts b/server/engine-prestart-opened.e2e.test.ts
new file mode 100644
index 0000000000..3773b665d4
--- /dev/null
+++ b/server/engine-prestart-opened.e2e.test.ts
@@ -0,0 +1,83 @@
+import { spawn, type ChildProcess } from "node:child_process";
+import { closeSync, existsSync, openSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb, verificationServerEnvironment } from "../scripts/control-omb.ts";
+import { waitForExit } from "./testing/cleanup.ts";
+
+const alive = (pid: number): boolean => { try { process.kill(pid, 0); return true; } catch { return false; } };
+
+it("opening a conversation whose engine has closed starts it again, resuming its session, and the next message runs in it", async () => {
+ const fixture = await launchVerificationServer();
+ const { dataDir, url, logPath } = fixture.info;
+ let server: ChildProcess | undefined;
+ const launchesFile = join(dataDir, "launches.jsonl"), promptsFile = join(dataDir, "prompts.jsonl");
+ const evidence: unknown[] = [{ url, dataDir }];
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(url + path, {
+ method, headers: { "content-type": "application/json", origin: url },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),
+ });
+ const value = await response.json() as any;
+ expect(response.status, `${method} ${path}: ${JSON.stringify(value)}`).toBe(200);
+ return value;
+ };
+ const control = async (...args: string[]) => {
+ const result = await runControlOmb([...args, "--url", url]) as any;
+ evidence.push({ command: args, result });
+ return result;
+ };
+ const jsonLines = (file: string): any[] => existsSync(file) ? readFileSync(file, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
+ const launches = () => (jsonLines(launchesFile) as Array<{ pid: number; argv: string[] }>).filter((launch) => launch.argv.includes("--input-format"));
+ try {
+ // Restarted with an idle time short enough to see the engine close, and without the free-memory reading so the
+ // runner's free memory does not decide the outcome.
+ await waitForExit(fixture.child, { signal: "SIGTERM" });
+ const log = openSync(logPath, "a", 0o600);
+ server = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {
+ cwd: fileURLToPath(new URL("..", import.meta.url)),
+ env: { ...verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), OMB_SESSION_IDLE_MS: "10000", OMB_ENGINE_PRESTART: "unmetered",
+ FAKE_CLAUDE_LAUNCHES: launchesFile, FAKE_CLAUDE_PROMPTS: promptsFile, FAKE_CLAUDE_MCP_RECONNECT: join(dataDir, "relists.jsonl") },
+ stdio: ["ignore", log, log],
+ });
+ closeSync(log);
+ await expect.poll(async () => {
+ try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }
+ }, { timeout: 30_000 }).toBe(true);
+
+ const { bot } = await control("new-bot", "--name", "Prestart bot");
+ const threadId = bot.activeTaskId as string;
+ const send = async (text: string) => {
+ await control("send", "--bot", bot.id, "--task", threadId, "--text", text);
+ expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");
+ };
+ const messages = async () => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];
+ const closed = () => expect.poll(() => launches().every((launch) => !alive(launch.pid)), { timeout: 30_000, interval: 250 }).toBe(true);
+
+ await send("FIRST_PRESTART_1");
+ expect(launches(), JSON.stringify(launches())).toHaveLength(1);
+ await closed();
+
+ const before = await messages();
+ await api("POST", `/api/bots/${bot.id}/tasks/${threadId}?messages=0`);
+ await expect.poll(() => launches().length, { timeout: 15_000 }).toBe(2);
+ const spare = launches()[1]!;
+ expect(spare.argv).toContain("--resume");
+ expect(alive(spare.pid)).toBe(true);
+ // Started, and nothing said: no prompt reached the engine, nothing was written to the conversation.
+ expect(jsonLines(promptsFile)).toHaveLength(1);
+ expect(await messages()).toEqual(before);
+
+ await send("SECOND_PRESTART_2");
+ expect(launches()).toHaveLength(2);
+ expect(jsonLines(promptsFile)).toHaveLength(2);
+ expect((await messages()).filter((message) => message.role === "user").map((message) => message.text)).toEqual(["FIRST_PRESTART_1", "SECOND_PRESTART_2"]);
+ expect((await messages()).findLast((message) => message.role === "bot" && message.kind === "text")?.turnSucceeded).toBe(true);
+ evidence.push({ launches: launches(), messages: await messages() });
+ } finally {
+ writeFileSync(`${logPath}.prestart-opened.json`, JSON.stringify(evidence, null, 2));
+ await waitForExit(server, { signal: "SIGTERM" });
+ await fixture.close();
+ }
+}, 120_000);
diff --git a/server/engine-prestart.test.ts b/server/engine-prestart.test.ts
index 8318c7244b..13f9e2aad6 100644
--- a/server/engine-prestart.test.ts
+++ b/server/engine-prestart.test.ts
@@ -1,8 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { SendTurnInput } from "./contracts.ts";
-import { PRESTART_IDLE_MS, PRESTART_MOST } from "./drivers/session-idle.ts";
-import { createEnginePrestart, type EnginePrestartDeps, type SessionCredentials } from "./engine-prestart.ts";
+import { OPENED_PRESTART_IDLE_MS, PRESTART_IDLE_MS, PRESTART_MOST } from "./drivers/session-idle.ts";
+import { createEnginePrestart, OPENED_AGAIN_AFTER_MS, OPENED_SETTLE_MS, type EnginePrestartDeps, type SessionCredentials } from "./engine-prestart.ts";
const FIRST = "11111111-aaaa-4aaa-8aaa-111111111111";
const NEXT = "22222222-bbbb-4bbb-8bbb-222222222222";
@@ -15,21 +15,23 @@ function host(overrides: Partial<EnginePrestartDeps> = {}) {
["bot agents", { grants: grantsOf(FIRST, "agents", "full"), token: "a".repeat(48) }],
["bot data", { grants: grantsOf(FIRST, "data", "full"), token: "d".repeat(48) }],
])]]);
- const started: SendTurnInput[] = [], dropped: string[] = [];
+ const started: SendTurnInput[] = [], dropped: string[] = [], waits: Array<number | undefined> = [];
const held = new Set<string>();
- const state = { allowed: true, blank: true, busy: false, refused: false, shape: "sonnet/full" as string | null, up: true, folder: `/work/bot/${NEXT}` as string | null };
+ const state = { allowed: true, blank: true, busy: false, refused: false, shape: "sonnet/full" as string | null, up: true, folder: `/work/bot/${NEXT}` as string | null,
+ bot: "bot" as string | null, cursors: { [FIRST]: "session-1", [NEXT]: "session-2" } as Record<string, string | undefined>, clock: 1_000_000 };
const prestart = createEnginePrestart({
adapter: (id) => (id === "claude" ? { prestart: {
- start: async (input) => { started.push(input); if (state.up) held.add(input.threadId); return state.up; },
+ start: async (input, waitMs) => { started.push(input); waits.push(waitMs); if (state.up) held.add(input.threadId); return state.up; },
held: (threadId) => held.has(threadId), ready: (threadId) => held.has(threadId),
drop: (threadId) => { dropped.push(threadId); held.delete(threadId); },
} } : undefined),
credentials,
allowed: () => state.allowed, blank: () => state.blank, busy: () => state.busy, refused: () => state.refused,
shape: () => state.shape, approval: () => "full", folder: () => state.folder,
+ botOf: () => state.bot, cursor: (_bot, threadId, instanceId) => (instanceId === "claude" ? state.cursors[threadId] : undefined), now: () => state.clock,
...overrides,
});
- return { prestart, credentials, started, dropped, held, state };
+ return { prestart, credentials, started, dropped, held, state, waits };
}
const firstTurn = (extra: Partial<SendTurnInput> = {}): SendTurnInput => ({
@@ -220,3 +222,161 @@ describe("starting a new conversation's engine from the bot's last launch", () =
expect(drop).toHaveBeenCalledTimes(2);
});
});
+
+describe("starting the engine of a conversation a person opens or types in", () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ /** The bot's last turn was in FIRST, and its engine has closed since. */
+ const afterATurn = (overrides: Partial<EnginePrestartDeps> = {}) => {
+ const setup = host(overrides);
+ setup.state.blank = false;
+ setup.prestart.note("claude", firstTurn(), true);
+ return setup;
+ };
+ const opened = (setup: ReturnType<typeof host>, threadId: string) => {
+ setup.prestart.threadSeen(threadId);
+ vi.advanceTimersByTime(OPENED_SETTLE_MS);
+ };
+
+ it("starts it as its next turn would: its own bearers, resuming its session, never inline, and waiting a few minutes", () => {
+ const setup = afterATurn({ folder: (_bot, threadId) => `/work/bot/${threadId}` });
+ setup.prestart.threadSeen(FIRST);
+ expect(setup.started).toEqual([]);
+ vi.advanceTimersByTime(OPENED_SETTLE_MS);
+ expect(setup.started).toHaveLength(1);
+ const launch = setup.started[0]!;
+ expect(launch).toMatchObject({ threadId: FIRST, text: "", resumeCursor: "session-1", cwd: `/work/bot/${FIRST}`, systemStable: "You are Testy." });
+ expect(launch.sessionReset).toBeUndefined();
+ expect(launch.integrations).toEqual(firstTurn().integrations);
+ expect(setup.waits).toEqual([OPENED_PRESTART_IDLE_MS]);
+ expect(setup.prestart.waiting()).toEqual([FIRST]);
+ });
+
+ it("starts another conversation of the bot for its own id, folder, bearers and session", () => {
+ const setup = afterATurn();
+ opened(setup, NEXT);
+ const launch = setup.started[0]!;
+ expect(launch).toMatchObject({ threadId: NEXT, resumeCursor: "session-2", cwd: `/work/bot/${NEXT}` });
+ expect(JSON.stringify(launch)).not.toContain(FIRST);
+ expect(launch.integrations!.agents!.env.OMB_COMMS_TOKEN).toBe(setup.credentials.get(NEXT)!.get("bot agents")!.token);
+ });
+
+ it("resumes nothing when the conversation has no session on that engine", () => {
+ const setup = afterATurn();
+ setup.state.cursors[NEXT] = undefined;
+ opened(setup, NEXT);
+ expect(setup.started[0]!.resumeCursor).toBeUndefined();
+ });
+
+ it("starts only the conversation the person settles on when they click through several", () => {
+ const setup = afterATurn({ folder: (_bot, threadId) => `/work/bot/${threadId}` });
+ for (const threadId of ["t-1", "t-2", NEXT]) {
+ setup.prestart.threadSeen(threadId);
+ vi.advanceTimersByTime(OPENED_SETTLE_MS / 2);
+ }
+ vi.advanceTimersByTime(OPENED_SETTLE_MS);
+ expect(setup.started.map((launch) => launch.threadId)).toEqual([NEXT]);
+ // Seen again while it settles or waits (the presence ping as they type): still one.
+ setup.prestart.threadSeen(NEXT);
+ vi.advanceTimersByTime(OPENED_SETTLE_MS);
+ expect(setup.started).toHaveLength(1);
+ });
+
+ it.each([
+ ["the host does not start engines ahead (memory short, a Cloud home)", { allowed: false }],
+ ["a turn is already being set up or running there", { busy: true }],
+ ["its next message would be refused (paused, archived, over a limit or budget, signed out)", { refused: true }],
+ ["its model, approval level or folder rule differs from the last launch's", { shape: "opus/ask" }],
+ ["it is not a bot's conversation", { bot: null }],
+ ])("starts nothing when %s", (_why, change) => {
+ const setup = afterATurn();
+ Object.assign(setup.state, change);
+ opened(setup, NEXT);
+ expect(setup.started).toEqual([]);
+ expect(setup.prestart.waiting()).toEqual([]);
+ });
+
+ it("starts nothing for a bot with no launch to go by", () => {
+ const setup = host();
+ setup.state.blank = false;
+ opened(setup, NEXT);
+ expect(setup.started).toEqual([]);
+ });
+
+ it("stops an engine no message came for and keeps the conversation's bearers, then leaves it alone a while", () => {
+ const setup = afterATurn();
+ opened(setup, NEXT);
+ const bearers = setup.credentials.get(NEXT);
+ vi.advanceTimersByTime(OPENED_PRESTART_IDLE_MS + 5_000);
+ expect(setup.dropped).toEqual([NEXT]);
+ expect(setup.credentials.get(NEXT)).toBe(bearers);
+ expect(setup.prestart.waiting()).toEqual([]);
+ setup.held.clear();
+ setup.state.clock += OPENED_AGAIN_AFTER_MS - 1;
+ opened(setup, NEXT);
+ expect(setup.started).toHaveLength(1);
+ setup.state.clock += 1;
+ opened(setup, NEXT);
+ expect(setup.started).toHaveLength(2);
+ });
+
+ it("starts it again at once after a message was sent there", () => {
+ const setup = afterATurn();
+ opened(setup, NEXT);
+ vi.advanceTimersByTime(OPENED_PRESTART_IDLE_MS + 5_000);
+ setup.held.clear();
+ setup.prestart.note("claude", firstTurn({ threadId: NEXT, cwd: `/work/bot/${NEXT}` }), true);
+ opened(setup, NEXT);
+ expect(setup.started.map((launch) => launch.threadId)).toEqual([NEXT, NEXT]);
+ });
+
+ it("keeps the conversation's bearers when its engine could not start (one already runs there)", async () => {
+ const setup = afterATurn();
+ setup.state.up = false;
+ opened(setup, FIRST);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(setup.prestart.waiting()).toEqual([]);
+ expect(setup.credentials.get(FIRST)!.get("bot agents")!.token).toBe("a".repeat(48));
+ });
+
+ it("keeps a couple at once: the conversation opened longest ago gives way to the one in front of the person", () => {
+ const setup = afterATurn({ folder: (_bot, threadId) => `/work/bot/${threadId}` });
+ for (const threadId of ["t-1", "t-2", "t-3"]) opened(setup, threadId);
+ expect(setup.started.map((launch) => launch.threadId)).toEqual(["t-1", "t-2", "t-3"]);
+ expect(setup.dropped).toEqual(["t-1"]);
+ expect(setup.prestart.waiting()).toEqual(["t-2", "t-3"]);
+ expect(setup.prestart.waiting().length).toBeLessThanOrEqual(PRESTART_MOST);
+ });
+
+ it("never pushes out an engine a turn is being set up on", () => {
+ const busy = new Set<string>();
+ const setup = afterATurn({ folder: (_bot, threadId) => `/work/bot/${threadId}`, busy: (_bot, threadId) => busy.has(threadId) });
+ opened(setup, "t-1");
+ opened(setup, "t-2");
+ busy.add("t-1");
+ opened(setup, "t-3");
+ expect(setup.dropped).toEqual(["t-2"]);
+ expect(setup.prestart.waiting()).toEqual(["t-1", "t-3"]);
+ });
+
+ it("frees the place of one that waited through a sleep: its timer stood still, the wall clock did not", () => {
+ const setup = afterATurn({ folder: (_bot, threadId) => `/work/bot/${threadId}` });
+ opened(setup, "t-1");
+ opened(setup, "t-2");
+ setup.state.clock += OPENED_PRESTART_IDLE_MS + 60 * 60_000;
+ setup.state.blank = true;
+ setup.prestart.threadMade("bot", "t-new");
+ expect(setup.dropped).toEqual(["t-1", "t-2"]);
+ expect(setup.prestart.waiting()).toEqual(["t-new"]);
+ expect(setup.credentials.has("t-1")).toBe(true);
+ });
+
+ it("forgets a pending open on a drop", () => {
+ const setup = afterATurn();
+ setup.prestart.threadSeen(NEXT);
+ setup.prestart.drop(NEXT);
+ vi.advanceTimersByTime(OPENED_SETTLE_MS);
+ expect(setup.started).toEqual([]);
+ });
+});
diff --git a/server/engine-prestart.ts b/server/engine-prestart.ts
index d88dcf929c..3c475ce8dd 100644
--- a/server/engine-prestart.ts
+++ b/server/engine-prestart.ts
@@ -6,13 +6,17 @@
// the process for the first turn only when that turn's own launch comes out identical, and replaces it otherwise
// so a wrong guess costs a process that was never used, never a wrong one that was.
//
+// A conversation that already has messages starts the same way when a person opens it or types in it: the bot's last
+// launch, for this conversation, resuming the engine session its next turn would resume. Its bearers are its own and stay
+// when that engine goes unused, since its next turn launches with them.
+//
// Not started ahead: a bot's very first conversation (no launch to go by), a launch that mounts anything beyond
// OpenMausBot's own tool servers (a person's MCP servers, connected apps, a browser or a computer would be started
-// early), a guest's or tool-scoped turn, and any host where engines wait for memory.
+// early), a guest's or tool-scoped turn, and any host where engines wait for memory or memory is short.
import { randomBytes } from "node:crypto";
import type { ProviderAdapter, SendTurnInput } from "./contracts.ts";
-import { PRESTART_IDLE_MS, PRESTART_MOST } from "./drivers/session-idle.ts";
+import { OPENED_PRESTART_IDLE_MS, PRESTART_IDLE_MS, PRESTART_MOST } from "./drivers/session-idle.ts";
/** Each conversation's bearers: per slot, what the bearer grants and the bearer. */
export type SessionCredentials = Map<string, Map<string, { grants: string; token: string }>>;
@@ -49,6 +53,12 @@ export interface EnginePrestartDeps {
refused(botId: string, threadId: string): boolean;
/** How long a started engine waits; the bearers made for it are retired a little after. */
idleMs?: number;
+ /** The bot whose conversation this is; null for anything else (a room). */
+ botOf(threadId: string): string | null;
+ /** The engine session this conversation's next turn on `instanceId` would resume, if it would resume one. */
+ cursor(botId: string, threadId: string, instanceId: string): SendTurnInput["resumeCursor"];
+ /** Wall-clock time: timers stand still while the machine sleeps. */
+ now?: () => number;
}
interface Launch {
@@ -70,13 +80,23 @@ function startsOnlyOwnServers(input: SendTurnInput): boolean {
}
const RELEASE_AFTER_MS = 5_000;
+/** An open is acted on once the conversation stayed in front of the person this long, so clicking through conversations
+ * starts nothing, and the switch itself never waits on the work. */
+export const OPENED_SETTLE_MS = 1_000;
+/** An opened conversation whose engine went unused is not started again this soon, though the person stays active in it. */
+export const OPENED_AGAIN_AFTER_MS = 15 * 60_000;
/** One launch per bot, for the bots a person wrote to most recently. */
const LAUNCHES_KEPT = 32;
export function createEnginePrestart(deps: EnginePrestartDeps) {
+ const now = deps.now ?? Date.now;
const launches = new Map<string, Launch>();
- /** Conversations given bearers ahead of any turn, until a turn uses them or they are retired. */
- const reserved = new Map<string, { botId: string; instanceId: string; timer: ReturnType<typeof setTimeout> }>();
+ /** Conversations given an engine ahead of any turn, until a turn uses it or it is retired. `opened`: one that had
+ * messages already, whose bearers are its own. */
+ const reserved = new Map<string, { botId: string; instanceId: string; timer: ReturnType<typeof setTimeout>; opened: boolean; at: number; waitMs: number }>();
+ /** Opened conversations whose engine went unused, and when. */
+ const unused = new Map<string, number>();
+ let settling: { threadId: string; timer: ReturnType<typeof setTimeout> } | null = null;
const release = (threadId: string, retire: boolean) => {
const held = reserved.get(threadId);
@@ -85,17 +105,58 @@ export function createEnginePrestart(deps: EnginePrestartDeps) {
reserved.delete(threadId);
if (!retire) return;
deps.adapter(held.instanceId)?.prestart?.drop(threadId);
- deps.credentials.delete(threadId);
+ if (!held.opened) deps.credentials.delete(threadId);
};
const bearerFor = (botId: string, threadId: string, slot: string, grantedElsewhere: string): string =>
bearerForGrants(deps.credentials, threadId, slot, JSON.stringify({ ...JSON.parse(grantedElsewhere), threadId, approval: deps.approval(botId, threadId) }));
+ /** Frees the places of engines that no longer wait (taken, closed, or past their wait by the wall clock: a sleep), then
+ * when `opened` and still full, the place of the conversation opened longest ago. Whether one is free now. */
+ const room = (opened: boolean): boolean => {
+ for (const [other, held] of reserved) {
+ const stale = now() - held.at > held.waitMs + RELEASE_AFTER_MS;
+ if (stale || !deps.adapter(held.instanceId)?.prestart?.held(other)) release(other, !deps.busy(held.botId, other));
+ }
+ if (opened && reserved.size >= PRESTART_MOST) {
+ const oldest = [...reserved].find(([other, held]) => held.opened && !deps.busy(held.botId, other));
+ if (oldest) release(oldest[0], true);
+ }
+ return reserved.size < PRESTART_MOST;
+ };
+
+ /** Starts `threadId`'s engine from the bot's last launch; `opened`: the conversation has messages already. */
+ const start = (botId: string, threadId: string, opened: boolean): void => {
+ const from = launches.get(botId);
+ const adapter = from && deps.adapter(from.instanceId)?.prestart;
+ if (!from || !adapter || reserved.has(threadId) || !deps.allowed() || deps.busy(botId, threadId)
+ || deps.shape(botId, threadId) !== from.shape || deps.refused(botId, threadId)) return;
+ if (!room(opened)) return;
+ let input = from.input.replaceAll(from.threadId, threadId);
+ const cwd = (JSON.parse(input) as SendTurnInput).cwd;
+ if (!cwd || deps.folder(botId, threadId) !== cwd) return;
+ for (const bearer of from.bearers) input = input.replaceAll(bearer.token, bearerFor(botId, threadId, bearer.slot, bearer.grants));
+ const cursor = opened ? deps.cursor(botId, threadId, from.instanceId) : undefined;
+ const launch = { ...(JSON.parse(input) as SendTurnInput), text: "", ...(cursor ? { resumeCursor: cursor } : {}) };
+ const waitMs = opened ? OPENED_PRESTART_IDLE_MS : deps.idleMs ?? PRESTART_IDLE_MS;
+ const timer = setTimeout(() => {
+ if (opened && !deps.busy(botId, threadId)) unused.set(threadId, now());
+ release(threadId, !deps.busy(botId, threadId));
+ }, waitMs + RELEASE_AFTER_MS);
+ timer.unref?.();
+ const reservation = { botId, instanceId: from.instanceId, timer, opened, at: now(), waitMs };
+ reserved.set(threadId, reservation);
+ const releaseOwn = (retire: boolean) => { if (reserved.get(threadId) === reservation) release(threadId, retire); };
+ void adapter.start(launch, waitMs).then((up) => { if (!up && !deps.busy(botId, threadId)) releaseOwn(true); },
+ () => releaseOwn(!deps.busy(botId, threadId)));
+ };
+
return {
/** Called with every turn's input as it goes to its engine; returns it unchanged. A person's own turn becomes what
* the bot's next new conversation is started from. */
note(instanceId: string, input: SendTurnInput, person: boolean): SendTurnInput {
release(input.threadId, false);
+ unused.delete(input.threadId);
const botId = input.botId;
if (!botId) return input;
const shape = person && startsOnlyOwnServers(input) ? deps.shape(botId, input.threadId) : null;
@@ -116,29 +177,31 @@ export function createEnginePrestart(deps: EnginePrestartDeps) {
/** A person made a conversation: its engine starts now when the bot's last launch says how. */
threadMade(botId: string, threadId: string): void {
- const from = launches.get(botId);
- const adapter = from && deps.adapter(from.instanceId)?.prestart;
- if (!from || !adapter || from.threadId === threadId || !deps.allowed() || !deps.blank(threadId) || deps.busy(botId, threadId)
- || deps.shape(botId, threadId) !== from.shape || deps.refused(botId, threadId)) return;
- for (const [other, held] of reserved) if (!deps.adapter(held.instanceId)?.prestart?.held(other)) release(other, !deps.busy(held.botId, other));
- if (reserved.size >= PRESTART_MOST || reserved.has(threadId)) return;
- let input = from.input.replaceAll(from.threadId, threadId);
- const cwd = (JSON.parse(input) as SendTurnInput).cwd;
- if (!cwd || deps.folder(botId, threadId) !== cwd) return;
- for (const bearer of from.bearers) input = input.replaceAll(bearer.token, bearerFor(botId, threadId, bearer.slot, bearer.grants));
- const launch = { ...(JSON.parse(input) as SendTurnInput), text: "" };
- const timer = setTimeout(() => release(threadId, !deps.busy(botId, threadId)), (deps.idleMs ?? PRESTART_IDLE_MS) + RELEASE_AFTER_MS);
+ if (launches.get(botId)?.threadId === threadId || !deps.blank(threadId)) return;
+ start(botId, threadId, false);
+ },
+
+ /** A person opened a conversation or is typing in it: once it stays in front of them for a moment, its engine starts
+ * the way its next turn would start it. Never inline: the open itself must not wait. */
+ threadSeen(threadId: string): void {
+ if (settling?.threadId === threadId) return;
+ if (settling) clearTimeout(settling.timer);
+ settling = null;
+ const botId = deps.botOf(threadId);
+ if (!botId || reserved.has(threadId) || now() - (unused.get(threadId) ?? -Infinity) < OPENED_AGAIN_AFTER_MS) return;
+ const timer = setTimeout(() => {
+ if (settling?.timer === timer) settling = null;
+ try { start(botId, threadId, !deps.blank(threadId)); } catch (error) { console.warn(`engine prestart: ${(error as Error).message}`); }
+ }, OPENED_SETTLE_MS);
timer.unref?.();
- const reservation = { botId, instanceId: from.instanceId, timer };
- reserved.set(threadId, reservation);
- const releaseOwn = (retire: boolean) => { if (reserved.get(threadId) === reservation) release(threadId, retire); };
- void adapter.start(launch).then((up) => { if (!up && !deps.busy(botId, threadId)) releaseOwn(true); },
- () => releaseOwn(!deps.busy(botId, threadId)));
+ settling = { threadId, timer };
},
/** The conversation's bearers were retired (a Stop, a delete): an engine started ahead with them goes too. */
drop(threadId: string): void {
+ if (settling?.threadId === threadId) { clearTimeout(settling.timer); settling = null; }
release(threadId, true);
+ unused.delete(threadId);
},
waiting: (): string[] => [...reserved.keys()],
diff --git a/server/index.ts b/server/index.ts
index c8f555fa1b..4ed2d6ff87 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -1653,7 +1653,7 @@ const sessionCredentials = new Map<string, Map<string, { grants: string; token:
const enginePrestart = createEnginePrestart({ adapter: (id) => registry.get(id)?.adapter, credentials: sessionCredentials, allowed: prestartAllowed, blank: (threadId) => store.messagesFor(threadId).length === 0, busy: (botId, threadId) => threadBusy(botId, threadId), approval: (botId, threadId) => { const thread = botForThread(botId, threadId); return thread ? approvalModeFor(thread) : null; },
shape: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId), task = store.taskByThread(botId, threadId); return bot && task ? JSON.stringify([bot.modelSelection, approvalModeForTurn(bot, false, threadId), task.projectId ?? null, task.cwd?.includes(threadId) ? null : task.cwd ?? null]) : null; },
folder: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId), instance = bot && registry.get(bot.modelSelection.instanceId); if (!bot || !instance || !supportsWorkspaceFiles(instance.driverKind)) return null; ensureWorkspace(botId, appLanguage()); return ensureTaskWorkspaceWithSkills(botId, threadId, skillsHost.turnImports(bot, threadId, instance)) ?? null; },
- refused: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId); try { assertWithinBudget(cfg, DATA_DIR); } catch { return true; } return !bot || Boolean(bot.approvalGrant) || providerInstancesChanging.has(bot.modelSelection.instanceId) || limitTakeover.stillSignedOut(bot.modelSelection.instanceId) || botAtThreadCapacity(botId, threadId) || Boolean(botHolds.text(botId, threadLanguage(threadId)) ?? starterCaps.pausedText(botId, threadLanguage(threadId), threadId)); } }); onThreadMade(enginePrestart.threadMade);
+ refused: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId); try { assertWithinBudget(cfg, DATA_DIR); } catch { return true; } return !bot || Boolean(bot.approvalGrant) || providerInstancesChanging.has(bot.modelSelection.instanceId) || limitTakeover.stillSignedOut(bot.modelSelection.instanceId) || botAtThreadCapacity(botId, threadId) || Boolean(botHolds.text(botId, threadLanguage(threadId)) ?? starterCaps.pausedText(botId, threadLanguage(threadId), threadId)) || store.taskByThread(botId, threadId)?.archivedAt !== undefined || registry.lastSnapshot(bot.modelSelection.instanceId)?.authenticated === false || registry.lastSnapshot(bot.modelSelection.instanceId)?.state === "unavailable"; }, botOf: (threadId) => store.botByThread(threadId)?.id ?? null, cursor: (botId, threadId, instanceId) => { const task = store.taskByThread(botId, threadId); return task?.lastInstanceId === instanceId ? task.resumeCursors[instanceId] : undefined; } }); onThreadMade(enginePrestart.threadMade); onThreadSeen(enginePrestart.threadSeen);
function sessionGrants({ generation: _turn, depth: _depth, roomHandoffId: _handoff, skillAuthoring: _skills, ...grants }: Omit<InternalCapability, "orphanExpiresAt">): string {
const thread = botForThread(grants.botId, grants.threadId);
diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.ts
index 23bfbcb982..442db5cd70 100755
--- a/server/testing/fake-claude-cli.ts
+++ b/server/testing/fake-claude-cli.ts
@@ -22,6 +22,8 @@
// FAKE_CLAUDE_MCP_RECONNECT JSON-lines file: an mcp_reconnect control_request is appended to it and answered with
// success, as Claude Code 2.1.321 answers once the server is connected again; "refuse" answers it as a failure
// FAKE_CLAUDE_LAUNCHES JSON-lines file every stream-json process appends its {pid, argv} to as it starts
+// FAKE_CLAUDE_STARTUP_MS ms a stream-json process takes to start up before it reads its input, as the real CLI takes
+// seconds to load and connect its MCP servers
// FAKE_CLAUDE_EXIT_AFTER_TURN 1: exit once the turn is answered, so later turns relaunch with --resume
// FAKE_CLAUDE_SIGNED_OUT_FILE path: while it exists, every turn answers as not-logged-in (a sign-in that lapses and comes back)
// FAKE_CLAUDE_AUTH_AFTER_TURN 1: from the second turn, answer as not-logged-in; FAKE_CLAUDE_AUTH_AFTER_WORK 1: not-logged-in
@@ -1431,6 +1433,11 @@ process.stdin.on("data", (c) => {
}
}
});
+const startupMs = Number(process.env.FAKE_CLAUDE_STARTUP_MS);
+if (startupMs > 0) {
+ process.stdin.pause();
+ setTimeout(() => process.stdin.resume(), startupMs);
+}
process.stdin.on("end", () => {
stdinEnded = true;
finishIfDone();