Skip to content

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

fix(engines): opened-conversation starts only under the desktop app, never at a running engine's cost

milind-soni5bbb927920b0
diff --git a/server/contracts.ts b/server/contracts.ts
index 3e644e66f6..45b0692825 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -355,11 +355,13 @@ export interface ProviderAdapter {
* 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. */
+ * waited through a sleep); it is replaced otherwise. `held`: one is launching or waiting. `running`: the thread has a
+ * process up of any kind (one waiting, or one a turn used and kept), so there is nothing to start. `drop` stops one that
+ * no turn took; a taken one is the turn's own. */
prestart?: {
start(input: SendTurnInput, waitMs?: number): Promise<boolean>;
held(threadId: ThreadId): boolean;
+ running(threadId: ThreadId): boolean;
ready(threadId: ThreadId): boolean;
drop(threadId: ThreadId): void;
};
diff --git a/server/drivers/claude-prestart.test.ts b/server/drivers/claude-prestart.test.ts
index 29ed629ddd..206b816269 100644
--- a/server/drivers/claude-prestart.test.ts
+++ b/server/drivers/claude-prestart.test.ts
@@ -325,6 +325,18 @@ describe("ClaudeDriver: a process started before the first message (fake CLI)",
expect(recorder.events).toEqual([]);
});
+ it("says a conversation's engine is up while one waits or a turn kept one, and not once it is gone", async () => {
+ expect(instance.adapter.prestart!.running("t-up")).toBe(false);
+ expect(await started("t-up", 1)).toBe(true);
+ expect(instance.adapter.prestart!.running("t-up")).toBe(true);
+ await instance.adapter.sendTurn(turn("t-up"));
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(instance.adapter.prestart!.held("t-up")).toBe(false);
+ expect(instance.adapter.prestart!.running("t-up")).toBe(true);
+ await instance.adapter.stopAll();
+ expect(instance.adapter.prestart!.running("t-up")).toBe(false);
+ });
+
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 0556bfb7dd..7545b76f4e 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -1981,7 +1981,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
spares.set(turn.threadId, launch);
return launch;
},
- held: (threadId) => spares.has(threadId) || sessions.get(threadId)?.spare === true, ready: (threadId) => sessions.get(threadId)?.spare === true && sessions.get(threadId)?.tools?.ready === true,
+ held: (threadId) => spares.has(threadId) || sessions.get(threadId)?.spare === true, running: (threadId) => spares.has(threadId) || (sessions.get(threadId)?.closing === false && sessions.get(threadId)?.child.exitCode === null), ready: (threadId) => sessions.get(threadId)?.spare === true && sessions.get(threadId)?.tools?.ready === true,
drop: (threadId) => {
const close = () => { const s = sessions.get(threadId); if (s?.spare) { closeSession(threadId, "never used"); stopSession(s); } };
close();
diff --git a/server/drivers/session-idle.test.ts b/server/drivers/session-idle.test.ts
index 45df69d905..b0dddd0e19 100644
--- a/server/drivers/session-idle.test.ts
+++ b/server/drivers/session-idle.test.ts
@@ -288,12 +288,28 @@ describe("the cap on idle engines", () => {
expect(warmEngineKeys()).toEqual(["theirs", "routine"]);
});
- it("keeps an engine started ahead of a first message as the most recent, and never closes a held one", () => {
+ it("never lets an engine started ahead of a message close a used one, nor closes a held one: past the cap it closes itself", () => {
const [used, held, spare] = [engine("used"), engine("held"), engine("spare")];
capped(1)("held", { ...held.warm, held: () => true });
capped(1)("used", used.warm);
capped(1)("spare", { ...spare.warm, spare: () => true });
- expect([used.state.closed, held.state.closed, spare.state.closed]).toEqual([1, 0, 0]);
+ expect([used.state.closed, held.state.closed, spare.state.closed]).toEqual([0, 0, 1]);
+ expect(warmEngineKeys()).toEqual(["used"]);
+ });
+
+ it("closes engines started ahead of a message first, even one in front of the person, when a used engine goes idle past the cap", () => {
+ const [unwatched, spare, older, next] = [engine("unwatched"), engine("spare"), engine("older-spare"), engine("next")];
+ sawThread("spare");
+ capped(3)("unwatched", unwatched.warm);
+ capped(3)("older-spare", { ...older.warm, spare: () => true });
+ capped(3)("spare", { ...spare.warm, spare: () => true });
+ capped(3)("next", next.warm);
+ expect([unwatched.state.closed, older.state.closed, spare.state.closed, next.state.closed]).toEqual([0, 1, 0, 0]);
+ // A waiting engine past the cap closes an older waiting one before itself, and never a used one.
+ const another = engine("another-spare");
+ capped(3)("another-spare", { ...another.warm, spare: () => true });
+ expect([unwatched.state.closed, spare.state.closed, next.state.closed, another.state.closed]).toEqual([0, 1, 0, 0]);
+ expect(warmEngineKeys()).toEqual(["unwatched", "next", "another-spare"]);
});
});
diff --git a/server/drivers/session-idle.ts b/server/drivers/session-idle.ts
index 64a524151d..a366aa28c8 100644
--- a/server/drivers/session-idle.ts
+++ b/server/drivers/session-idle.ts
@@ -124,9 +124,10 @@ export function idleEngineCap(env: Record<string, string | undefined> = process.
* person opens or reads its conversation. */
const warmEngines = new Map<string, WarmEngine>();
-/** An engine went idle: when the box allows fewer idle engines than are up, the ones idle longest close now (an engine
- * started ahead of a first message before them); past the cap on idle engines, the least recently used close now (one
- * whose conversation no person has had in front of them before them). Never one with a turn running, nor one held. */
+/** An engine went idle: when the box allows fewer idle engines than are up, the ones idle longest close now; past the cap
+ * on idle engines, the least recently used close now (one whose conversation no person has had in front of them before
+ * them). Engines started ahead of a message close before any a turn has used, and one of them never makes a used engine
+ * close: past either limit it closes itself instead. Never one with a turn running, nor one held. */
export function keepWarm(key: string, engine: WarmEngine, box: Pick<BoxMemory, "bytes"> = boxMemory(),
available: () => number = availableMemory, fits: () => number = () => engineMemory.idleEnginesAllowed(),
cap: () => number = () => idleEngineCap(process.env, box.bytes)): void {
@@ -135,9 +136,12 @@ export function keepWarm(key: string, engine: WarmEngine, box: Pick<BoxMemory, "
for (const [other, warm] of warmEngines) if (other !== key && (!warm.idle() || warm.held?.())) warmEngines.delete(other);
const most = fits();
const roomAllows = box.bytes > SMALL_BOX_BYTES && most === Infinity ? Infinity : idleEnginesAllowed(box, available(), most);
- const idleBefore = () => [...warmEngines].filter(([other]) => other !== key);
- closeKept(sparesFirst(idleBefore()).slice(0, Math.max(0, warmEngines.size - roomAllows)));
- closeKept(unwatchedFirst(idleBefore()).slice(0, Math.max(0, warmEngines.size - Math.max(1, cap()))));
+ const closable = (order: (engines: Array<[string, WarmEngine]>) => Array<[string, WarmEngine]>): Array<[string, WarmEngine]> => {
+ const others = [...warmEngines].filter(([other]) => other !== key);
+ return engine.spare?.() ? [...others.filter(([, warm]) => warm.spare?.()), [key, engine]] : sparesFirst(order(others));
+ };
+ closeKept(closable((engines) => engines).slice(0, Math.max(0, warmEngines.size - roomAllows)));
+ closeKept(closable(unwatchedFirst).slice(0, Math.max(0, warmEngines.size - Math.max(1, cap()))));
}
function closeKept(engines: Array<[string, WarmEngine]>): void {
diff --git a/server/engine-prestart-opened.e2e.test.ts b/server/engine-prestart-opened.e2e.test.ts
index c3dff95f23..dd3ce31b4d 100644
--- a/server/engine-prestart-opened.e2e.test.ts
+++ b/server/engine-prestart-opened.e2e.test.ts
@@ -1,9 +1,10 @@
import { spawn, type ChildProcess } from "node:child_process";
+import { randomBytes } from "node:crypto";
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 { launchVerificationServer, runControlOmb, verificationServerArgs, 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; } };
@@ -30,18 +31,19 @@ it("opening a conversation whose engine has closed starts it from the bot's last
};
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"));
+ // Run as the desktop app runs its server (only there does opening a conversation start its engine): every request
+ // carries the app's owner capability.
+ const owner = randomBytes(32).toString("base64url");
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (input, init = {}) => realFetch(input, { ...init, headers: { ...Object.fromEntries(new Headers(init.headers)), "x-openmausbot-desktop-owner": owner } });
try {
- // Restarted with an idle time short enough to see the engine close, without the free-memory reading so the runner's
- // free memory does not decide the outcome, and with turns not waiting for room (a Linux runner can count as a server
- // whose engines do, where nothing starts ahead).
+ // 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", OMB_TURNS_MAX_RUNNING: "off",
- FAKE_CLAUDE_LAUNCHES: launchesFile, FAKE_CLAUDE_PROMPTS: promptsFile, FAKE_CLAUDE_MCP_RECONNECT: join(dataDir, "relists.jsonl") },
- stdio: ["ignore", log, log],
- });
+ const env = { ...verificationServerEnvironment({ OMB_TEST_DESKTOP_OWNER_TOKEN: owner }, 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") };
+ server = spawn(process.execPath, verificationServerArgs(env), { cwd: fileURLToPath(new URL("..", import.meta.url)), env, 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; }
@@ -89,6 +91,7 @@ it("opening a conversation whose engine has closed starts it from the bot's last
expect(launches(), "an archived conversation starts nothing").toHaveLength(launched + 1);
evidence.push({ launches: launches(), first: await messages(first) });
} finally {
+ globalThis.fetch = realFetch;
writeFileSync(`${logPath}.prestart-opened.json`, JSON.stringify(evidence, null, 2));
await waitForExit(server, { signal: "SIGTERM" });
await fixture.close();
diff --git a/server/engine-prestart.test.ts b/server/engine-prestart.test.ts
index 06862bee3c..21bc4e78dc 100644
--- a/server/engine-prestart.test.ts
+++ b/server/engine-prestart.test.ts
@@ -18,17 +18,17 @@ function host(overrides: Partial<EnginePrestartDeps> = {}) {
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,
- bot: "bot" as string | null, cursors: { [FIRST]: "session-1", [NEXT]: "session-2" } as Record<string, string | undefined>, clock: 1_000_000 };
+ bot: "bot" as string | null, desktop: true, running: new Set<string>(), folders: 0, 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, 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),
+ held: (threadId) => held.has(threadId), ready: (threadId) => held.has(threadId), running: (threadId) => held.has(threadId) || state.running.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,
+ shape: () => state.shape, approval: () => "full", folder: () => { state.folders += 1; return state.folder; },
+ desktop: () => state.desktop, botOf: () => state.bot, cursor: (_bot, threadId, instanceId) => (instanceId === "claude" ? state.cursors[threadId] : undefined), now: () => state.clock,
...overrides,
});
return { prestart, credentials, started, dropped, held, state, waits };
@@ -197,7 +197,7 @@ describe("starting a new conversation's engine from the bot's last launch", () =
const { prestart, credentials } = host({
adapter: () => ({ prestart: {
start: () => new Promise<boolean>((resolve, reject) => pending.push({ resolve, reject })),
- held: () => true, ready: () => false, drop,
+ held: () => true, ready: () => false, running: () => false, drop,
} }),
});
prestart.note("claude", firstTurn(), true);
@@ -297,6 +297,47 @@ describe("starting the engine of a conversation a person opens or types in", ()
expect(setup.prestart.waiting()).toEqual([]);
});
+ it("starts nothing, and closes no other waiting engine, for a conversation whose engine is already up; again and again", () => {
+ const setup = afterATurn({ folder: (_bot, threadId) => { setup.state.folders += 1; return `/work/bot/${threadId}`; } });
+ opened(setup, "t-1");
+ opened(setup, "t-2");
+ setup.state.running.add("t-answered");
+ const folders = setup.state.folders;
+ for (let ping = 0; ping < 3; ping++) {
+ setup.prestart.threadSeen("t-answered");
+ vi.advanceTimersByTime(OPENED_SETTLE_MS);
+ setup.prestart.threadSeen("t-1");
+ vi.advanceTimersByTime(OPENED_SETTLE_MS);
+ }
+ expect(setup.started.map((launch) => launch.threadId)).toEqual(["t-1", "t-2"]);
+ expect(setup.dropped).toEqual([]);
+ expect(setup.state.folders, "no folder or skills work for it").toBe(folders);
+ expect(setup.prestart.waiting()).toEqual(["t-1", "t-2"]);
+ });
+
+ it("closes no waiting engine for a conversation whose folder is not where the launch would be, and does not redo that work", () => {
+ const setup = afterATurn({ folder: (_bot, threadId) => { setup.state.folders += 1; return threadId === "t-moved" ? "/elsewhere" : `/work/bot/${threadId}`; } });
+ opened(setup, "t-1");
+ opened(setup, "t-2");
+ opened(setup, "t-moved");
+ const folders = setup.state.folders;
+ expect(setup.dropped).toEqual([]);
+ expect(setup.prestart.waiting()).toEqual(["t-1", "t-2"]);
+ opened(setup, "t-1");
+ opened(setup, "t-moved");
+ expect(setup.state.folders).toBe(folders);
+ });
+
+ it("starts nothing for an opened conversation unless this server runs under the desktop app, while a new one still starts", () => {
+ const setup = afterATurn();
+ setup.state.desktop = false;
+ opened(setup, NEXT);
+ expect(setup.started).toEqual([]);
+ setup.state.blank = true;
+ setup.prestart.threadMade("bot", NEXT);
+ expect(setup.started.map((launch) => launch.threadId)).toEqual([NEXT]);
+ });
+
it("starts nothing for a bot with no launch to go by", () => {
const setup = host();
setup.state.blank = false;
diff --git a/server/engine-prestart.ts b/server/engine-prestart.ts
index 2a45598b4d..a4bc4e7bc7 100644
--- a/server/engine-prestart.ts
+++ b/server/engine-prestart.ts
@@ -53,6 +53,9 @@ 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;
+ /** This server runs under the desktop app, for the person at that computer: only there does opening a conversation
+ * start its engine. */
+ desktop(): boolean;
/** 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. */
@@ -137,12 +140,15 @@ export function createEnginePrestart(deps: EnginePrestartDeps) {
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)
+ if (!from || !adapter || reserved.has(threadId) || adapter.running(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;
+ if (!cwd || deps.folder(botId, threadId) !== cwd) {
+ if (opened) unused.set(threadId, now());
+ return;
+ }
+ if (!room(opened)) 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 } : {}) };
@@ -195,7 +201,7 @@ export function createEnginePrestart(deps: EnginePrestartDeps) {
if (settling?.threadId === threadId) return;
if (settling) clearTimeout(settling.timer);
settling = null;
- const botId = deps.botOf(threadId);
+ const botId = deps.desktop() ? deps.botOf(threadId) : null;
if (!botId || reserved.has(threadId) || now() - (unused.get(threadId) ?? -Infinity) < OPENED_AGAIN_AFTER_MS) return;
const timer = setTimeout(() => {
if (settling?.timer === timer) settling = null;
diff --git a/server/index.ts b/server/index.ts
index 5ca0f9415c..c1d572a8df 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)) || prestartClosed(bot, store.taskByThread(botId, threadId), registry.lastSnapshot(bot.modelSelection.instanceId)); }, 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);
+ 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)) || prestartClosed(bot, store.taskByThread(botId, threadId), registry.lastSnapshot(bot.modelSelection.instanceId)); }, desktop: () => DESKTOP_MANAGED, 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);