Skip to content

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

fix(local-vm): start a stopped Podman machine on a Mac instead of failing the turn (#4241)

Aditya Umaleef2210793edb
diff --git a/server/container-computer.ts b/server/container-computer.ts
index ffd97680f0..6869c73332 100644
--- a/server/container-computer.ts
+++ b/server/container-computer.ts
@@ -184,7 +184,7 @@ LABEL ${MANAGED_LABEL}="1" \\
`;
}
-async function sh(cmd: string, args: string[], timeout = 8000): Promise<{ stdout: string }> {
+export async function sh(cmd: string, args: string[], timeout = 8000): Promise<{ stdout: string }> {
const resolved = resolveCliSpawn(cmd, args);
const { stdout } = await run(resolved.command, resolved.args, {
timeout,
diff --git a/server/index.ts b/server/index.ts
index 4a5116c6ec..1b40ca4a77 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -496,6 +496,7 @@ import {
import { OrgLibrary } from "./org-library.ts";
import { shouldMountLocalComputer } from "./local-routing.ts";
import { autoLocalVmAttachable, type ContainerComputerStatus } from "./container-computer.ts";
+import { startStoppedPodmanMachine } from "./podman-machine.ts";
import { keepTransient, lazyClaimRetryText, settledWithin, startAutoVmClaim, withinBudget, type AutoVmClaimSlot, type AutoVmClaimTable } from "./auto-vm-claims.ts";
import { CONTROL_ACT_WITHIN_MS, CONTROL_BUSY, CONTROL_HANDED_BACK, CONTROL_WAIT_MS, CONTROL_WAITED, controlRefusal, type ControlState } from "./control-client.ts";
import { computerFreeAfterText, computerParkedText, computerPersonAwayText, computerStoppedWaitingText, computerWaitingText, type ComputerHolder } from "./computer-wait.ts";
@@ -11809,6 +11810,7 @@ async function readyLocalVmForTurn(botId: string, target: LocalVmTarget, isCurre
let status: ContainerComputerStatus;
try {
status = await containerComputerStatus(undefined, undefined, target);
+ status = await startStoppedPodmanMachine(status, () => containerComputerStatus(undefined, undefined, target), () => broadcast({ kind: "computer", botId, state: "provisioning" }));
noteLocalVmSeen(target, status);
if (!isCurrent()) return status;
const action = localVmWakeAction(status);
diff --git a/server/podman-machine.test.ts b/server/podman-machine.test.ts
new file mode 100644
index 0000000000..c9e7875f7e
--- /dev/null
+++ b/server/podman-machine.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from "vitest";
+
+import type { CommandRunner } from "./container-computer.ts";
+import { startStoppedPodmanMachine } from "./podman-machine.ts";
+
+type Status = { runtime: "docker" | "podman" | null; daemonUp: boolean; problem: string | null };
+const down: Status = { runtime: "podman", daemonUp: false, problem: "Start podman first" };
+const up: Status = { runtime: "podman", daemonUp: true, problem: null };
+const recheck = async () => up;
+
+function podman(machines: unknown[], bootMachine: (name: string) => void | Promise<void> = () => {}) {
+ const calls: string[] = [];
+ const run: CommandRunner = async (command, args) => {
+ calls.push([command, ...args].join(" "));
+ if (args.join(" ") === "machine list --format json") return { stdout: JSON.stringify(machines) };
+ if (args[0] === "machine" && args[1] === "start") {
+ await bootMachine(args[2]!);
+ return { stdout: "Machine started successfully\n" };
+ }
+ throw new Error(`unexpected ${command} ${args.join(" ")}`);
+ };
+ const shown: string[] = [];
+ const start = (status = down, platform: NodeJS.Platform = "darwin", now = Date.now, check = recheck) =>
+ startStoppedPodmanMachine(status, check, () => shown.push("starting"), { runner: run, platform, now, pause: async () => {} });
+ return { run, calls, shown, start };
+}
+
+describe("starting a stopped Podman machine on a Mac", () => {
+ it("starts the machine that is set up but stopped, so a bot's Local VM can come up", async () => {
+ const fake = podman([
+ { Name: "other", Default: false, Running: false, Starting: false },
+ { Name: "podman-machine-default", Default: true, Running: false, Starting: false },
+ ]);
+ await expect(fake.start()).resolves.toBe(up);
+ expect(fake.calls).toEqual(["podman machine list --format json", "podman machine start podman-machine-default"]);
+ expect(fake.shown).toEqual(["starting"]);
+ });
+
+ it("starts the only machine when none is marked default", async () => {
+ const fake = podman([{ Name: "mine", Running: false }]);
+ await expect(fake.start()).resolves.toBe(up);
+ expect(fake.calls.at(-1)).toBe("podman machine start mine");
+ });
+
+ it.each([
+ ["Linux", down, "linux"],
+ ["Windows", down, "win32"],
+ ["Docker", { ...down, runtime: "docker" }, "darwin"],
+ ["no runtime", { ...down, runtime: null }, "darwin"],
+ ["Podman already answering", up, "darwin"],
+ ] as const)("leaves %s alone", async (_label, status: Status, platform) => {
+ const fake = podman([{ Name: "podman-machine-default", Default: true, Running: false }]);
+ await expect(fake.start(status, platform)).resolves.toBe(status);
+ expect(fake.calls).toEqual([]);
+ });
+
+ it.each([
+ ["no machine was ever set up", []],
+ ["a machine is already running", [{ Name: "podman-machine-default", Default: true, Running: true }]],
+ ["a machine is already starting", [{ Name: "podman-machine-default", Default: true, Starting: true }]],
+ ["several machines and none is the default", [{ Name: "a" }, { Name: "b" }]],
+ ])("never creates or restarts one when %s", async (_label, machines) => {
+ const fake = podman(machines);
+ await expect(fake.start()).resolves.toBe(down);
+ expect(fake.calls).toEqual(["podman machine list --format json"]);
+ expect(fake.shown).toEqual([]);
+ });
+
+ it("says what went wrong when the machine does not start, and does not retry it on every turn", async () => {
+ let clock = 0;
+ const failing = podman([{ Name: "podman-machine-default", Default: true }], () => {
+ throw Object.assign(new Error("Command failed: podman machine start podman-machine-default"), {
+ stderr: 'Starting machine "podman-machine-default"\nError: vfkit exited unexpectedly\n',
+ });
+ });
+ const problem = 'The Podman machine "podman-machine-default" did not start (Error: vfkit exited unexpectedly); run podman machine start';
+ await expect(failing.start(down, "darwin", () => clock)).resolves.toEqual({ ...down, problem });
+ clock = 60_000;
+ await expect(failing.start(down, "darwin", () => clock)).resolves.toEqual({ ...down, problem });
+ expect(failing.calls.filter((call) => call.includes("machine start"))).toHaveLength(1);
+
+ clock = 6 * 60_000;
+ const fixed = podman([{ Name: "podman-machine-default", Default: true }]);
+ await expect(fixed.start(down, "darwin", () => clock)).resolves.toBe(up);
+ });
+
+ it("waits a moment for Podman to answer after the machine starts", async () => {
+ const fake = podman([{ Name: "podman-machine-default", Default: true }]);
+ const answers = [down, down, up];
+ await expect(fake.start(down, "darwin", Date.now, async () => answers.shift()!)).resolves.toBe(up);
+ expect(answers).toEqual([]);
+ });
+
+ it("does not hold a failed status check against later turns", async () => {
+ const fake = podman([{ Name: "podman-machine-default", Default: true }]);
+ await expect(fake.start(down, "darwin", Date.now, async () => { throw new Error("inspect failed"); })).rejects.toThrow("inspect failed");
+ await expect(fake.start()).resolves.toBe(up);
+ });
+
+ it("starts the machine once for turns that arrive together", async () => {
+ let release!: () => void;
+ const fake = podman([{ Name: "podman-machine-default", Default: true }], () => new Promise<void>((resolve) => { release = resolve; }));
+ const first = fake.start();
+ const second = fake.start();
+ await expect.poll(() => fake.calls.length).toBe(2);
+ release();
+ await expect(Promise.all([first, second])).resolves.toEqual([up, up]);
+ expect(fake.calls.filter((call) => call.includes("machine start"))).toHaveLength(1);
+ });
+});
diff --git a/server/podman-machine.ts b/server/podman-machine.ts
new file mode 100644
index 0000000000..c1d065a54e
--- /dev/null
+++ b/server/podman-machine.ts
@@ -0,0 +1,72 @@
+// On a Mac, Podman runs containers inside its own small VM (a "Podman machine"), which stays stopped after the Mac
+// restarts. A bot that needs the Local VM starts that machine itself instead of failing with "Start podman first".
+import { sh, type CommandRunner, type ContainerComputerStatus } from "./container-computer.ts";
+
+const MACHINE_START_TIMEOUT_MS = 3 * 60_000;
+/** After a failed start, turns get the same message for a while instead of each waiting on another failing start. */
+const FAILED_START_BACKOFF_MS = 5 * 60_000;
+const RECHECK_TRIES = 5;
+
+type MachineEntry = { Name?: unknown; Default?: unknown; Running?: unknown; Starting?: unknown };
+type RuntimeStatus = Pick<ContainerComputerStatus, "runtime" | "daemonUp" | "problem">;
+
+let starting: Promise<boolean> | null = null;
+let lastFailure: { at: number; problem: string } | null = null;
+
+type Seams = { runner?: CommandRunner; platform?: NodeJS.Platform; now?: () => number; pause?: (ms: number) => Promise<void> };
+const pauseFor = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Mac only: when Podman is the runtime and does not answer because its machine is set up but stopped, starts that
+ * machine (calling `onStart` first, so the person sees it starting) and returns `recheck()`'s fresh status. Otherwise
+ * returns `status` unchanged: not a Mac, Podman is not the runtime, it already answers, no machine was ever set up
+ * (this never creates or installs one), or one is already running or starting. When the start fails, returns
+ * `status` with a problem the person can act on.
+ */
+export async function startStoppedPodmanMachine<S extends RuntimeStatus>(
+ status: S,
+ recheck: () => Promise<S>,
+ onStart: () => void = () => {},
+ { runner = sh, platform = process.platform, now = Date.now, pause = pauseFor }: Seams = {},
+): Promise<S> {
+ if (platform !== "darwin" || status.runtime !== "podman" || status.daemonUp) return status;
+ if (lastFailure && now() - lastFailure.at < FAILED_START_BACKOFF_MS) return { ...status, problem: lastFailure.problem };
+ // Turns that arrive together share one start.
+ starting ??= startMachine(runner, onStart).finally(() => { starting = null; });
+ try {
+ if (!(await starting)) return status;
+ } catch (error) {
+ lastFailure = { at: now(), problem: (error as Error).message };
+ return { ...status, problem: lastFailure.problem };
+ }
+ // Podman's API socket can answer a moment after `machine start` returns.
+ let fresh = await recheck();
+ for (let tries = 1; tries < RECHECK_TRIES && !fresh.daemonUp; tries++) {
+ await pause(1_000);
+ fresh = await recheck();
+ }
+ return fresh;
+}
+
+async function startMachine(runner: CommandRunner, onStart: () => void): Promise<boolean> {
+ let machines: MachineEntry[];
+ try {
+ const parsed: unknown = JSON.parse((await runner("podman", ["machine", "list", "--format", "json"], 10_000)).stdout);
+ machines = Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return false;
+ }
+ if (machines.some((machine) => machine.Running === true || machine.Starting === true)) return false;
+ const machine = machines.find((entry) => entry.Default === true) ?? (machines.length === 1 ? machines[0] : undefined);
+ if (typeof machine?.Name !== "string" || !machine.Name) return false;
+ onStart();
+ try {
+ await runner("podman", ["machine", "start", machine.Name], MACHINE_START_TIMEOUT_MS);
+ } catch (error) {
+ // execFile's message starts with the whole command line; Podman's own last stderr line says what went wrong.
+ const detail = String((error as { stderr?: unknown }).stderr ?? "").trim().split("\n").at(-1)?.trim();
+ throw new Error(`The Podman machine "${machine.Name}" did not start${detail ? ` (${detail})` : ""}; run podman machine start`, { cause: error });
+ }
+ lastFailure = null;
+ return true;
+}