Skip to content

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

fix(local-vm): wait for scheduled VM readiness before dispatch

vincented020447beec
diff --git a/server/container-computer.ts b/server/container-computer.ts
index b72081f431..a04093515a 100644
--- a/server/container-computer.ts
+++ b/server/container-computer.ts
@@ -34,6 +34,7 @@ import {
} from "./container-isolation.ts";
import { SPAWNED_PROXIES } from "./proxy-paths.ts";
import { runtimeHealthy } from "./container-runtime-probe.ts";
+import { canProbeLocalVmDesktop } from "./local-vm-availability.ts";
// Its own group: a timeout also ends the docker CLI plugins and credential helpers it started.
const run = execFileInGroupAsync;
@@ -585,14 +586,7 @@ export async function containerComputerStatus(
} catch {
}
- const canProbe = options.probeDesktop !== false &&
- status.container === "running" &&
- status.imageMatches &&
- status.managed &&
- status.network === "loopback" &&
- status.security === "hardened" &&
- status.persistence === "durable";
- if (canProbe) {
+ if (options.probeDesktop !== false && canProbeLocalVmDesktop(status)) {
try {
const expected = `cua-driver ${CUA_DRIVER_VERSION}`;
const version = await runner(status.runtime, cuaExecArgs(["--version"], { container: target.containerName }), 8000);
diff --git a/server/group-local-vm.e2e.test.ts b/server/group-local-vm.e2e.test.ts
index 985976b094..cec22fc0f7 100644
--- a/server/group-local-vm.e2e.test.ts
+++ b/server/group-local-vm.e2e.test.ts
@@ -232,6 +232,73 @@ describe("Local VM stop and resume", () => {
});
});
+describe("scheduled Local VM readiness", () => {
+ afterAll(async () => {
+ // The scheduled pool run leaves thread affinity in memory, which changes the next cold pool's seat order.
+ await waitForExit(child, { signal: "SIGTERM" });
+ await startServer();
+ });
+
+ it.each([
+ { initial: "ready", mode: "pool" },
+ { initial: "booting", mode: "shared" },
+ { initial: "stopped", mode: "per-bot" },
+ { initial: "missing mount", mode: "shared", failure: "missing its durable folder" },
+ { initial: "start failed", mode: "shared", failure: "could not start the Local VM" },
+ ])("uses the configured $mode target when $initial", async ({ initial, mode, failure }) => {
+ const { bot } = await api("POST", "/api/bots", { name: `Scheduled VM ${initial}`, useDefaults: false,
+ settings: { computer: "vm", browser: false } });
+ expect(bot.computer).toBe("vm");
+ for (const path of [dumpFile, finishFile, stateFile + ".booting"]) rmSync(path, { force: true });
+ const target = mode === "per-bot" ? `bot:${createHash("sha256").update(bot.id).digest("hex")}` : mode === "pool" ? "pool:0" : "shared";
+ const stopped = initial === "stopped" || initial === "start failed";
+ const booting = initial === "booting" || initial === "stopped";
+ let routineId: string | undefined;
+ try {
+ vmState({ containers: [] });
+ await api("PATCH", "/api/config", { localVm: { mode, maxInstances: 2 } });
+ vmState({ containers: [target], stopped: stopped ? [target] : [], booting, missingMount: initial === "missing mount", failStart: initial === "start failed" });
+ const { routine } = await api("POST", "/api/routines", { name: "Check the VM workspace", prompt: "Check the fixture workspace.",
+ botId: bot.id, runOn: "maus", schedule: { type: "once", at: Date.now() + 1_000 } });
+ routineId = routine.id;
+ const run = async () => (await api("GET", "/api/routines")).runs.find((row: any) => row.routineId === routineId);
+ const started = await until(run, row => Boolean(row?.threadId));
+ expect(started).toMatchObject({ triggerSource: "schedule", manual: false });
+ if (failure) {
+ const failed = await until(run, row => row?.status === "failed");
+ expect(failed).toMatchObject({ id: started.id, error: expect.stringContaining(failure) });
+ expect(existsSync(dumpFile)).toBe(false);
+ return;
+ }
+ if (booting) {
+ await until(() => existsSync(stateFile + ".booting"), Boolean);
+ // Give an early dispatch or an early terminal failure time to reach the routine ledger.
+ await new Promise(resolve => setTimeout(resolve, 350));
+ expect(await run()).toMatchObject({ id: started.id, status: "running" });
+ expect(existsSync(dumpFile)).toBe(false);
+ vmState({ ...JSON.parse(readFileSync(stateFile, "utf8")), booting: false });
+ }
+ const mounted: any = await dump();
+ expect(computer(mounted)).toBeTruthy();
+ const token = mounted.mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN;
+ const execution = await fetch(base + "/api/internal/vm-exec", { method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ command: "pwd" }) });
+ expect(execution.status, await execution.text()).toBe(200);
+ expect(JSON.parse(readFileSync(stateFile + ".exec", "utf8"))).toMatchObject({ target: { key: target }, command: "pwd" });
+ expect(JSON.parse(readFileSync(stateFile, "utf8")).actions ?? []).toEqual(stopped ? [{ action: "start", target }] : []);
+ writeFileSync(finishFile, "finish");
+ expect(await until(run, row => row?.status === "completed")).toMatchObject({ id: started.id, threadId: started.threadId });
+ } finally {
+ writeFileSync(finishFile, "finish");
+ await api("POST", `/api/bots/${bot.id}/interrupt`, {}); await idle(bot.id);
+ if (routineId) await api("DELETE", `/api/routines/${routineId}`);
+ await api("DELETE", `/api/bots/${bot.id}`);
+ vmState({ containers: [] });
+ await api("PATCH", "/api/config", { localVm: { mode: "shared", maxInstances: 2 } });
+ }
+ }, 30_000);
+});
+
describe("Group Local VM ownership on the real isolated server", () => {
it("cleans the remaining rooms after one cleanup operation fails", async () => {
rooms.set("missing-fixture-room", []);
diff --git a/server/index.ts b/server/index.ts
index 2d5930c9d1..41f0ad166c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -282,7 +282,7 @@ import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { m
import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { createTeamFilesHost } from "./host/team-files-host.ts"; import { createTeamFilesRoutes } from "./routes/team-files.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createPersonNames } from "./host/person-names.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; import { createTeamSlackHost } from "./host/team-slack-host.ts"; import { createTeamSlackMessages } from "./team-slack.ts"; import { createTeamSlackRoutes } from "./routes/team-slack.ts";
import { createCloudMoveRoutes } from "./cloud-move-http.ts";
import { RESTART_EXIT_CODE } from "./restart.ts"; import { installCrashGuard, SERVER_ERROR_CAUSE } from "./crash-guard.ts"; import { markRequestArrival } from "./perf/loop-stalls.ts"; import { createThreadMaps, keepThreadEntry } from "./host/thread-maps.ts"; import { botLimitRefusal } from "./bot-limit.ts";
-import { applyIncludedXMessage, holdIncludedServices, hostingCredential, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts"; import { applyPhoneLinkMessage, phoneLinkPart } from "./phone-link.ts"; import { createLocalVmAvailability } from "./local-vm-availability.ts"; import { createResearchAvailability } from "./research.ts";
+import { applyIncludedXMessage, holdIncludedServices, hostingCredential, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts"; import { applyPhoneLinkMessage, phoneLinkPart } from "./phone-link.ts"; import { createLocalVmAvailability, waitForLocalVmDesktop } from "./local-vm-availability.ts"; import { createResearchAvailability } from "./research.ts";
import { CloudCreditProvider } from "./cloud-credit-provider.ts";
import { createCreditMoves } from "./cloud-credit-moves.ts"; import { createRoutineHoldsHost } from "./host/routine-holds-host.ts"; import { tellTurnedBackOn } from "./host/routines-turned-back-on.ts";
import { TRIAL_CREDIT_OWN_AI, TRIAL_KEY_HELD } from "./trial-credit.ts"; import { createHeldKeys } from "./cloud-held-keys.ts";
@@ -5604,7 +5604,6 @@ const boatInventoryRequestsBusyIds = new Set<string>();
type RemoteComputerProvider = "box" | "vps";
const computerProviderConfigTransitions = new Set<RemoteComputerProvider>();
const localVmIdleMs = () => localVmIdleTimeoutMinutes(cfg) * 60_000;
-const LOCAL_VM_DESKTOP_WAIT_MS = 90_000;
const localVmIdles = new Map<string, ComputerIdleTimer>();
const { activeVpsThreads, vpsThreadStarted, vpsThreadEnded, vpsIdles, vpsIdleMs, cancelVpsIdle, touchVpsIdle, vpsServerSwitched, recover: recoverVpsIdles, cancelAll: cancelAllVpsIdles } = createVpsIdleHost({ cfg, store, botHasActiveTurn, hasActiveRoutine: (id) => Boolean(routines?.activeRunForBot(id)), isSharedVmHeld: (id) => sharedVm.snapshot(id).held, hasComputerPreview: (id) => computerPreviews.has(id), isVpsConfigTransitioning: () => computerProviderConfigTransitions.has("vps"), isLifecycleBusy: (id) => boatLifecycleBusyBots.has(id), claimBotComputerLifecycle, isShuttingDown: () => companyShutdown });
@@ -7898,7 +7897,9 @@ async function beginTurn(
};
let localVm: Awaited<ReturnType<typeof readyLocalVmForTurn>>;
try {
- localVm = await readyLocalVmForTurn(bot.id, localVmTarget);
+ const isCurrent = () => activeInternalGenerationByThread.get(claimThreadId) === resourceOwner.generation && !companyShutdown;
+ localVm = await readyLocalVmForTurn(bot.id, localVmTarget, isCurrent, opts?.automationSource === "schedule");
+ if (!isCurrent()) throw new DirectTurnSetupCancelled("turn stopped while its Local VM was being prepared");
} catch (error) {
dropLease();
throw error;
@@ -7971,7 +7972,7 @@ async function beginTurn(
const localVmTarget = { ...localVmTargetForThread(bot.id, threadId) };
let lazyReadyVm: { runtime: Runtime } | null = null;
if (strict) {
- const seen = await containerComputerStatus(undefined, undefined, localVmTarget).catch(() => null);
+ const seen = opts?.automationSource === "schedule" ? null : await containerComputerStatus(undefined, undefined, localVmTarget).catch(() => null);
if (seen?.ready && seen.runtime && !localVmUpdates.observe(localVmTarget, seen) && !localVmImageBusy && !localVmModeChangeBusy && !localVmLifecycleBusy.has(localVmTarget.key)) lazyReadyVm = { runtime: seen.runtime };
} else {
if (!localVmSeen.has(localVmTarget.key) && !opts?.automationSource) return false;
@@ -11490,7 +11491,7 @@ async function localVmPayload(target: LocalVmTarget, auth: RequestAuth) {
};
}
-async function readyLocalVmForTurn(botId: string, target: LocalVmTarget, isCurrent = () => true) {
+async function readyLocalVmForTurn(botId: string, target: LocalVmTarget, isCurrent: () => boolean, waitForRunning = false) {
localVmLifecycleBusy.add(target.key);
// Fence before the first await, so two concurrent turns cannot both pass the per-bot limit between count and create.
const pooled = target.key.startsWith("pool:");
@@ -11503,7 +11504,8 @@ async function readyLocalVmForTurn(botId: string, target: LocalVmTarget, isCurre
noteLocalVmSeen(target, status);
if (!isCurrent()) return status;
const action = localVmWakeAction(status);
- if (status.ready || !action || !status.runtime) return status;
+ if (status.ready || !status.runtime) return status;
+ if (!action) return waitForRunning ? waitForLocalVmDesktop(status, () => containerComputerStatus(undefined, undefined, target), isCurrent) : status;
if (action === "run" && target.key.startsWith("bot:")) {
const limit = perBotLocalVmLimitProblem(cfg, await existingPerBotLocalVmCount(status.runtime));
if (!isCurrent() || limit) return { ...status, problem: limit ?? status.problem };
@@ -11517,7 +11519,7 @@ async function readyLocalVmForTurn(botId: string, target: LocalVmTarget, isCurre
} catch {
// `run` can throw after the container exists, so arm the idle backstop anyway.
localVmIdleFor(target).touch();
- return status;
+ return { ...status, problem: "The container runtime could not start the Local VM. Check the runtime and try again" };
}
} finally {
if (ownsProvision) localVmProvisionBusy = false;
@@ -11525,14 +11527,7 @@ async function readyLocalVmForTurn(botId: string, target: LocalVmTarget, isCurre
}
localVmIdleFor(target).touch();
- // The container is up before Cua Driver is: wait rather than fail the turn.
- const deadline = Date.now() + LOCAL_VM_DESKTOP_WAIT_MS;
- while (isCurrent() && !status.ready && status.container === "running" && Date.now() < deadline) {
- await new Promise((resolve) => setTimeout(resolve, 2_000));
- if (!isCurrent()) break;
- status = await containerComputerStatus(undefined, undefined, target);
- }
- return status;
+ return waitForLocalVmDesktop(status, () => containerComputerStatus(undefined, undefined, target), isCurrent);
}
async function existingPerBotLocalVmCount(runtime: Runtime) {
diff --git a/server/local-vm-availability.test.ts b/server/local-vm-availability.test.ts
index 6a388bc14f..2e8230452b 100644
--- a/server/local-vm-availability.test.ts
+++ b/server/local-vm-availability.test.ts
@@ -1,6 +1,33 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
-import { createLocalVmAvailability } from "./local-vm-availability.ts";
+import type { ContainerComputerStatus } from "./container-computer.ts";
+import { createLocalVmAvailability, waitForLocalVmDesktop } from "./local-vm-availability.ts";
+
+it("bounds the Local VM readiness wait and preserves the probe's failure reason", async () => {
+ const status = {
+ image: true, imageMatches: true, managed: true, container: "running",
+ network: "loopback", security: "hardened", persistence: "durable",
+ ready: false, problem: "Cua Driver is starting",
+ } as ContainerComputerStatus;
+ vi.useFakeTimers();
+ try {
+ const probe = vi.fn(async () => status);
+ const result = waitForLocalVmDesktop(status, probe, () => true);
+ await vi.advanceTimersByTimeAsync(90_000);
+ expect(await result).toMatchObject({ ready: false, problem: "Timed out waiting for the Local VM desktop. Cua Driver is starting" });
+ expect(probe).toHaveBeenCalledTimes(44);
+
+ let current = true;
+ probe.mockClear();
+ const cancelled = waitForLocalVmDesktop(status, probe, () => current);
+ current = false;
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(await cancelled).toBe(status);
+ expect(probe).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+});
const flush = () => new Promise((resolve) => setImmediate(resolve));
diff --git a/server/local-vm-availability.ts b/server/local-vm-availability.ts
index 056e711cd4..c7a4519808 100644
--- a/server/local-vm-availability.ts
+++ b/server/local-vm-availability.ts
@@ -1,3 +1,29 @@
+import type { ContainerComputerStatus } from "./container-computer.ts";
+
+const DESKTOP_WAIT_MS = 90_000;
+const DESKTOP_POLL_MS = 2_000;
+
+export function canProbeLocalVmDesktop(status: ContainerComputerStatus): boolean {
+ return status.container === "running" && status.imageMatches && status.managed &&
+ status.network === "loopback" && status.security === "hardened" && status.persistence === "durable";
+}
+
+export async function waitForLocalVmDesktop(
+ status: ContainerComputerStatus,
+ probe: () => Promise<ContainerComputerStatus>,
+ isCurrent: () => boolean,
+): Promise<ContainerComputerStatus> {
+ const deadline = Date.now() + DESKTOP_WAIT_MS;
+ while (isCurrent() && !status.ready && status.image && canProbeLocalVmDesktop(status)) {
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) return { ...status, problem: `Timed out waiting for the Local VM desktop. ${status.problem ?? ""}`.trim() };
+ await new Promise<void>(resolve => setTimeout(resolve, Math.min(remaining, DESKTOP_POLL_MS)));
+ if (!isCurrent()) break;
+ if (Date.now() < deadline) status = await probe();
+ }
+ return status;
+}
+
// Whether this server can give a bot a Local VM: a supported container runtime is installed on the host. A runtime
// whose daemon is down still counts, since a turn that needs the VM starts a stopped Podman machine itself. The answer
// is kept, so the tools a conversation is listed do not change from turn to turn; while it is "no" it is read again at
diff --git a/server/testing/group-local-vm-hooks.mjs b/server/testing/group-local-vm-hooks.mjs
index a77dd65543..e1271c8bb9 100644
--- a/server/testing/group-local-vm-hooks.mjs
+++ b/server/testing/group-local-vm-hooks.mjs
@@ -72,12 +72,14 @@ registerHooks({
// An old desktop: made by OpenMausBot, on an image this release no longer runs (and maybe not yet rebuilt).
const image = !read().imageMissing;
const outdated = !missing && Boolean(read().outdated?.includes(target.key));
- const ready = !missing && !stopped && !outdated && image && !read().failed;
+ const { booting, missingMount, failed } = read();
+ const ready = !missing && !stopped && !outdated && image && !failed && !booting && !missingMount;
+ if (booting && !stopped) writeFileSync(file + '.booting', target.key);
return { runtime: 'podman', daemonUp: true, image, create_supported: true, managed: !missing,
container: missing ? 'missing' : stopped ? 'stopped' : 'running', ready,
- imageMatches: !outdated && image, network: 'loopback', security: 'hardened', persistence: 'durable', resumable: Boolean(stopped) && !outdated && image,
+ imageMatches: !outdated && image, network: 'loopback', security: 'hardened', persistence: missingMount ? 'unsafe' : 'durable', resumable: Boolean(stopped) && !outdated && image,
stopped_at: stopped ? read().stoppedAt : null,
- problem: ready ? null : outdated ? 'The existing Local VM uses an older desktop or Cua Driver; recreate it' : 'fixture desktop unavailable',
+ problem: ready ? null : missingMount ? 'The existing Local VM is missing its durable folder; recreate it' : outdated ? 'The existing Local VM uses an older desktop or Cua Driver; recreate it' : 'fixture desktop unavailable',
viewer_port: ready ? (read().viewerPort ?? 6080) : null, viewer_url: ready ? 'http://127.0.0.1:' + (read().viewerPort ?? 6080) + '/vnc.html#autoconnect=true&resize=scale&password=fixture-vnc' : '',
container_name: target.containerName, target_key: target.key, workspace_path: target.workspaceDir };
}
@@ -100,6 +102,7 @@ registerHooks({
state.stopped = [...(state.stopped ?? []), target.key];
state.stoppedAt = new Date().toISOString();
} else if (action === 'start') {
+ if (state.failStart) throw new Error('Fixture runtime refused to start');
state.stopped = (state.stopped ?? []).filter(key => key !== target.key);
} else {
state.containers = state.containers.filter(key => key !== target.key);