Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
The shared-VM e2e drives the real server against a stand-in Local VM: takes, waiting bots, lapsing phone holds, mode changes and sign-in requests
Xiaolei Shi4e6c20dca468
diff --git a/server/phone-shared-vm.e2e.test.ts b/server/phone-shared-vm.e2e.test.tsnew file mode 100644index 0000000000..cfae89a5d9--- /dev/null+++ b/server/phone-shared-vm.e2e.test.ts@@ -0,0 +1,607 @@+// The real server with the Local VM's container boundary replaced and a stub Boat: a person+// takes the one shared Local VM from a phone or the desktop, and every bot working on it waits until they hand it back.+import { spawn, type ChildProcess } from "node:child_process";+import { createHash, randomUUID } from "node:crypto";+import { createServer, type Server } from "node:http";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";++import { writeFileAtomic } from "./atomic.ts";+import { CONTROL_HANDED_BACK } from "./control-client.ts";+import { removeTempDir, waitForExit } from "./testing/cleanup.ts";+import { freePortBlock } from "./testing/ports.ts";+import { openSse, type SseRecorder } from "./testing/sse.ts";++const ROOT = fileURLToPath(new URL("..", import.meta.url));+/** Stands in for the 60 s grace, so an unbeaten phone hold lapses within a test. */+const GRACE_MS = 4_000;+const CALL_WAIT_MS = 3_000;+/** Stands in for the viewer proxy's 5 s re-check, so it beats inside the grace. */+const RECHECK_MS = 500;+const READY = { containers: ["shared"] };+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));+const lease = () => randomUUID().replaceAll("-", "");++describe("a person's hold on the shared Local VM", () => {+ let home = "";+ let base = "";+ let stateFile = "";+ let dumpFile = "";+ let finishFile = "";+ let output = "";+ let child: ChildProcess | null = null;+ let boatServer: Server;+ let boatRow: { id: string; name: string; state: string } | null = null;+ let holdBoatList: Promise<void> | null = null;+ let boatListHeld = false;+ let releaseBoat = () => {};+ let boatCall: Promise<unknown> | undefined;+ const boatCalls: string[] = [];+ let phoneToken = "";+ let witness = "";+ let sse: SseRecorder;+ let startServer = async () => {};+ const created: string[] = [];++ const vmState = (state: Record<string, unknown> = READY) => writeFileAtomic(stateFile, JSON.stringify(state));+ const call = async (method: string, path: string, body?: unknown, headers: Record<string, string> = {}) => {+ const response = await fetch(base + path, {+ method, headers: { "content-type": "application/json", ...headers },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ return { status: response.status, body: await response.json().catch(() => null) as any };+ };+ const api = (method: string, path: string, body?: unknown) => call(method, path, body);+ const phone = (method: string, path: string, body?: unknown) => call(method, path, body, { authorization: `Bearer ${phoneToken}` });+ const ok = async (method: string, path: string, body?: unknown) => {+ const result = await api(method, path, body);+ expect(result.status, `${method} ${path}: ${JSON.stringify(result.body)}`).toBeLessThan(400);+ return result.body;+ };+ async function until<T>(read: () => T | Promise<T>, accept: (value: T) => boolean, timeoutMs = 15_000): Promise<T> {+ const end = Date.now() + timeoutMs;+ for (;;) {+ const value = await read();+ if (accept(value)) return value;+ if (Date.now() >= end) throw new Error(`Fixture wait expired: ${JSON.stringify(value)}\n${output.slice(-3000)}`);+ await sleep(40);+ }+ }+ const query = (threadId?: string, extra: Record<string, string> = {}) => {+ const params = new URLSearchParams({ ...(threadId ? { threadId } : {}), ...extra }).toString();+ return params ? `?${params}` : "";+ };+ const control = (as: typeof api, botId: string, body?: Record<string, unknown>, threadId?: string) =>+ as(body ? "POST" : "GET", `/api/bots/${botId}/computer/control${query(threadId)}`, body);+ const held = async (botId: string, threadId?: string) => (await control(api, botId, undefined, threadId)).body.held as boolean;+ const joinVm = (botId: string, controlLeaseId: string, threadId?: string) =>+ phone("POST", `/api/bots/${botId}/local-computer/join${query(threadId, { controlLeaseId })}`, {});+ const viewer = (target: string, botId: string, controlLeaseId: string, threadId?: string) =>+ phone("GET", `/api/desktop-viewer/${target}${query(threadId, { botId, controlLeaseId })}`);+ const setMode = (mode: "shared" | "per-bot" | "pool") => ok("PATCH", "/api/config", { localVm: { mode } });+ /** The rig reads the window from the state file whenever the idle timer's window is set. */+ const setIdleMinutes = (idleTimeoutMinutes: number) => ok("PATCH", "/api/config", { localVm: { idleTimeoutMinutes } });+ const newBot = async (name: string, patch: Record<string, unknown> = {}) => {+ const { bot } = await ok("POST", "/api/bots", { name });+ await ok("PATCH", `/api/bots/${bot.id}`, { browser: false, computer: null, ...patch });+ created.push(bot.id);+ return bot as { id: string; threadId: string };+ };+ const newTask = async (botId: string, surface?: string) => {+ const { task } = await ok("POST", `/api/bots/${botId}/tasks`, {});+ if (surface) await ok("PATCH", `/api/bots/${botId}/tasks/${task.threadId}`, { surface });+ return task.threadId as string;+ };+ const dumpFor = (text: string) => until<any>(() => {+ if (!existsSync(dumpFile)) return null;+ try {+ const sent = JSON.parse(readFileSync(dumpFile, "utf8"));+ return JSON.stringify(sent.prompt ?? "").includes(text) ? sent : null;+ } catch { return null; }+ }, Boolean);+ const busy = async (botId: string, threadId: string) => (await ok("GET", "/api/bots?messages=0")).bots+ .find((bot: any) => bot.id === botId)?.tasks?.find((task: any) => task.threadId === threadId)?.busy === true;+ /** Starts a slow turn and answers with its MCP mounts once the fake engine has it. */+ const startTurn = async (botId: string, threadId: string) => {+ const text = `Work on the desktop ${randomUUID()}`;+ await ok("POST", `/api/bots/${botId}/messages`, { text, threadId });+ const servers = (await dumpFor(text)).mcpConfig.mcpServers;+ return { computer: servers.computer, comms: servers.agents.env.OMB_COMMS_TOKEN as string };+ };+ const finishTurns = async (...turns: Array<[string, string]>) => {+ writeFileSync(finishFile, "finish");+ for (const [botId, threadId] of turns) await until(() => busy(botId, threadId), value => !value);+ rmSync(finishFile, { force: true });+ };+ const gate = async (computer: any) => (await fetch(computer.env.OMB_CONTROL_URL, {+ headers: { authorization: `Bearer ${computer.env.OMB_CONTROL_TOKEN}` },+ })).json() as Promise<any>;+ const askSignIn = async (comms: string, site: string) => {+ const response = await fetch(`${base}/api/internal/request-sign-in`, {+ method: "POST", headers: { authorization: `Bearer ${comms}`, "content-type": "application/json" }, body: JSON.stringify({ site }),+ });+ expect(response.status).toBe(201);+ return ((await response.json()) as { messageId: string }).messageId;+ };+ /** The computer-control frames for this bot sent after `since` frames had arrived. */+ const framesFor = (botId: string, since: number) =>+ sse.frames.slice(since).filter(frame => frame.kind === "computer-control" && frame.botId === botId);++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), "omb-phone-shared-vm-"));+ stateFile = join(home, "vm.json");+ dumpFile = join(home, "dump.json");+ finishFile = join(home, "finish");+ vmState();+ const data = join(home, "data");+ const ui = join(home, "static");+ mkdirSync(data);+ mkdirSync(join(ui, "assets"), { recursive: true });+ writeFileSync(join(ui, "index.html"), "<title>Shared VM takeover</title>");+ writeFileSync(join(ui, "assets", "test.css"), "body{}");+ boatServer = createServer(async (req, res) => {+ const path = new URL(req.url ?? "/", "http://box.fixture").pathname;+ boatCalls.push(`${req.method} ${path}`);+ res.setHeader("content-type", "application/json");+ let raw = "";+ for await (const chunk of req) raw += chunk;+ const body = raw ? JSON.parse(raw) : {};+ if (path === "/sandboxes" && req.method === "POST") {+ boatRow = { id: "bx_23456789", name: body.name ?? "fixture-box", state: "idle" };+ return res.end(JSON.stringify({ sandbox: boatRow }));+ }+ if (path === "/sandboxes") {+ if (holdBoatList) { boatListHeld = true; await holdBoatList; }+ return res.end(JSON.stringify({ sandboxes: boatRow ? [boatRow] : [] }));+ }+ if (path.endsWith("/desktop")) return res.end(JSON.stringify({ desktopUrl: "https://desktop.fixture.invalid/" }));+ if (path.endsWith("/resume") && boatRow) { boatRow.state = "idle"; return res.end("{}"); }+ if (/^\/sandboxes\/bx_[^/]+$/.test(path)) {+ const row = boatRow?.id === path.slice("/sandboxes/".length) ? boatRow : null;+ if (req.method === "DELETE") { if (row) boatRow = null; return res.end("{}"); }+ if (!row) res.statusCode = 404;+ else if (req.method === "PATCH" && body.name) row.name = body.name;+ return res.end(JSON.stringify(row ? { sandbox: row } : { error: "missing" }));+ }+ return res.end("{}");+ });+ await new Promise<void>(resolve => boatServer.listen(0, "127.0.0.1", resolve));+ writeFileSync(join(data, "config.json"), JSON.stringify({ box: { token: "box_one" }, instances: { claude: {+ driver: "claudeAgent", config: { cli: join(ROOT, "server/testing/fake-claude-cli.ts") },+ environment: { FAKE_CLAUDE_MODE: "slow", FAKE_CLAUDE_DUMP: dumpFile, FAKE_CLAUDE_SLOW_FINISH_GATE: finishFile },+ } } }));+ const port = await freePortBlock([0, 1]);+ base = `http://127.0.0.1:${port}`;+ startServer = async () => {+ child = spawn(process.execPath, ["--import", pathToFileURL(join(ROOT, "server/testing/group-local-vm-hooks.mjs")).href,+ join(ROOT, "server/index.ts")], {+ cwd: ROOT, env: {+ PATH: dirname(process.execPath), ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),+ HOME: home, USERPROFILE: home, OMB_DATA_DIR: data,+ APPDATA: join(home, "appdata"), LOCALAPPDATA: join(home, "localappdata"),+ TEMP: home, TMP: home, TMPDIR: home,+ OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1), OMB_STATIC_DIR: ui, OMB_TEST_VM_STATE: stateFile,+ OMB_BOAT_API: `http://127.0.0.1:${(boatServer.address() as { port: number }).port}`,+ OMB_COMPUTER_CALL_WAIT_MS: String(CALL_WAIT_MS), OMB_TEST_LEASE_GRACE_MS: String(GRACE_MS),+ OMB_TEST_VIEWER_RECHECK_MS: String(RECHECK_MS),+ }, stdio: ["ignore", "pipe", "pipe"],+ });+ child.stdout!.on("data", chunk => { output += chunk; });+ child.stderr!.on("data", chunk => { output += chunk; });+ await until(async () => {+ if (child!.exitCode !== null) throw new Error(`the server exited:\n${output}`);+ try { return (await fetch(`${base}/api/health`)).ok; } catch { return false; }+ }, Boolean, 30_000);+ };+ await startServer();+ const seeded = (await ok("GET", "/api/bots?messages=0")).bots.find((bot: any) => bot.chiefOfStaff);+ if (seeded) await ok("PATCH", `/api/bots/${seeded.id}`, { chiefOfStaff: false });+ const { code } = await ok("POST", "/api/auth/pairing", {});+ const paired = await fetch(`${base}/api/auth/pair`, {+ method: "POST", headers: { "content-type": "application/json", "user-agent": "Fixture phone" }, body: JSON.stringify({ code }),+ });+ phoneToken = ((await paired.json()) as { token: string }).token;+ witness = (await newBot("Witness")).id;+ created.length = 0;+ sse = await openSse(`${base}/api/events`);+ }, 60_000);++ afterEach(async () => {+ holdBoatList = null;+ releaseBoat();+ await boatCall?.catch(() => {});+ boatCall = undefined;+ writeFileSync(finishFile, "finish");+ // A bot a person's hold reaches cannot be deleted, so every hold a test left goes first.+ await control(api, witness, { action: "release" });+ const bots = (await api("GET", "/api/bots?messages=0")).body?.bots ?? [];+ while (created.length) {+ const botId = created[0]!;+ const tasks: Array<{ threadId: string }> = bots.find((bot: any) => bot.id === botId)?.tasks ?? [];+ for (const threadId of [undefined, ...tasks.map(task => task.threadId)]) await control(api, botId, { action: "release" }, threadId);+ await api("POST", `/api/bots/${botId}/interrupt`, {});+ await until(() => api("DELETE", `/api/bots/${botId}`).then(response => response.status), status => status === 200 || status === 404);+ created.shift();+ }+ rmSync(finishFile, { force: true });+ rmSync(dumpFile, { force: true });+ vmState();+ await setMode("shared");+ await control(api, witness, { action: "release" });+ }, 30_000);++ afterAll(async () => {+ sse?.close();+ if (child) await waitForExit(child, { signal: "SIGTERM" });+ if (boatServer) await new Promise<void>(resolve => boatServer.close(() => resolve()));+ if (home) await removeTempDir(home);+ });++ it("a phone's take of one Auto bot holds the shared desktop for every bot, and its join and viewer open that desktop", async () => {+ const [a, b] = [await newBot("Ada"), await newBot("Bea")];+ const id = lease();+ expect((await control(phone, a.id, { action: "take", controlLeaseId: id })).body).toMatchObject({ held: true, owned: true });+ expect(await held(b.id)).toBe(true);+ const joined = await joinVm(a.id, id);+ expect(joined.status, JSON.stringify(joined.body)).toBe(200);+ expect(joined.body.socketPath).toMatch(/^api\/desktop-viewer\/local\/shared\/websockify\?/);+ expect(joined.body.password).toBe("fixture-vnc");+ expect(await viewer("local/shared", a.id, id)).toEqual({ status: 200, body: { password: "fixture-vnc" } });+ expect((await control(phone, a.id, { action: "release", controlLeaseId: id })).body.released).toBe(true);+ expect(await held(b.id)).toBe(false);+ });++ it.each(["shared", "per-bot"] as const)("a phone's Local VM hold in %s mode lapses a grace after its last beat; a desktop's and a phone's cloud hold do not", async mode => {+ await setMode(mode);+ const [a, desk, cloud] = [await newBot("Ada"), await newBot("Desk"), await newBot("Cumulus", { computer: "cloud" })];+ const [id, deskId, cloudId] = [lease(), lease(), lease()];+ const since = sse.frames.length;+ const takenAt = Date.now();+ expect((await control(phone, a.id, { action: "take", controlLeaseId: id })).body.owned).toBe(true);+ if (mode === "per-bot") expect((await control(api, desk.id, { action: "take", controlLeaseId: deskId })).body.owned).toBe(true);+ expect((await control(phone, cloud.id, { action: "take", controlLeaseId: cloudId })).body.owned).toBe(true);+ await sleep(GRACE_MS / 2);+ const beatAt = Date.now();+ expect((await control(phone, a.id, { action: "check", controlLeaseId: id })).body.owned).toBe(true);+ await sleep(takenAt + GRACE_MS + 600 - Date.now());+ expect(await held(a.id)).toBe(true);+ expect((await control(phone, a.id, { action: "check", controlLeaseId: lease() })).body).toMatchObject({ owned: false, held: true });+ await sleep(beatAt + GRACE_MS + 1_500 - Date.now());+ expect(await held(a.id), "a wrong lease's check must not keep the hold").toBe(false);+ await until(() => framesFor(a.id, since).at(-1)?.held, value => value === false);+ if (mode === "per-bot") expect(await held(desk.id)).toBe(true);+ expect(await held(cloud.id)).toBe(true);+ }, 30_000);++ it.each(["shared", "per-bot"] as const)("a take naming a VM bot's VPS desktop holds the bot's own key and never lapses, in %s mode", async (mode) => {+ await setMode(mode);+ const a = await newBot("Ada", { computer: "vm", cloudBackend: "vps" });+ const id = lease();+ expect((await control(phone, a.id, { action: "take", controlLeaseId: id, target: `vps/${a.id}` })).body.owned).toBe(true);+ expect(await held(witness)).toBe(false);+ await sleep(GRACE_MS + 1_000);+ expect(await held(a.id)).toBe(true);+ expect((await control(phone, a.id, { action: "release", controlLeaseId: id })).body.released).toBe(true);+ }, 20_000);++ it("a phone's take of a Local VM needs a lease, so its hold can lapse; a phone's cloud take and a desktop's take do not", async () => {+ const cloud = await newBot("Cumulus", { computer: "cloud" });+ const refused = await control(phone, witness, { action: "take" });+ expect(refused.status).toBe(400);+ expect(await held(witness)).toBe(false);+ expect((await control(phone, cloud.id, { action: "take" })).body.held).toBe(true);+ expect((await control(api, witness, { action: "take" })).body.held).toBe(true);+ }, 20_000);++ it("a desktop take of the shared desktop never lapses", async () => {+ const id = lease();+ expect((await control(api, witness, { action: "take", controlLeaseId: id })).body.owned).toBe(true);+ await sleep(GRACE_MS + 1_000);+ expect(await held(witness)).toBe(true);+ }, 20_000);++ it("a phone whose join finds the VM not ready still loses its hold a grace later", async () => {+ vmState({ ...READY, stopped: ["shared"] });+ const a = await newBot("Ada");+ const id = lease();+ expect((await control(phone, a.id, { action: "take", controlLeaseId: id })).body.owned).toBe(true);+ const refused = await joinVm(a.id, id);+ expect(refused.status).toBe(409);+ expect(refused.body.error).toBe("fixture desktop unavailable");+ await until(() => held(a.id), value => !value, GRACE_MS * 2);+ }, 20_000);++ it("a bot working on the shared VM waits through a person's hold, and the call that waited is not performed", async () => {+ const worker = await newBot("Worker", { computer: "vm" });+ const { computer } = await startTurn(worker.id, worker.threadId);+ expect(await gate(computer)).toEqual({ held: false, helpOpen: false });+ await control(api, witness, { action: "take" });+ expect(await gate(computer)).toMatchObject({ held: true, reason: "person" });+ const waiting = gate(computer);+ await sleep(500);+ await control(api, witness, { action: "release" });+ expect(await waiting).toMatchObject({ held: true, blockedReason: CONTROL_HANDED_BACK });+ expect(await gate(computer)).toEqual({ held: false, helpOpen: false });+ await finishTurns([worker.id, worker.threadId]);+ }, 30_000);++ it("a new turn that must start the shared VM waits for a person's hand-back as 'A person is using it', then claims it", async () => {+ vmState({ ...READY, stopped: ["shared"] });+ await control(api, witness, { action: "take" });+ const worker = await newBot("Worker", { computer: "vm" });+ const text = `Start the desktop ${randomUUID()}`;+ await ok("POST", `/api/bots/${worker.id}/messages`, { text, threadId: worker.threadId });+ await until(() => ok("GET", `/api/threads/${worker.threadId}/messages?limit=50`),+ page => JSON.stringify(page).includes("A person is using it."));+ expect(existsSync(dumpFile)).toBe(false);+ await control(api, witness, { action: "release" });+ expect((await dumpFor(text)).mcpConfig.mcpServers.computer).toBeTruthy();+ await finishTurns([worker.id, worker.threadId]);+ }, 30_000);++ it("a person's hold keeps the shared VM from its idle stop, and a take waits out its image update", async () => {+ vmState({ ...READY, idleMs: 300 });+ const id = lease();+ expect((await control(api, witness, { action: "take", controlLeaseId: id })).body.owned).toBe(true);+ expect((await call("POST", `/api/bots/${witness}/local-computer/join${query(undefined, { controlLeaseId: id })}`, {})).status).toBe(200);+ await setIdleMinutes(5);+ await sleep(1_500);+ expect(JSON.parse(readFileSync(stateFile, "utf8")).actions ?? []).toEqual([]);+ await control(api, witness, { action: "release", controlLeaseId: id });+ await until(() => JSON.parse(readFileSync(stateFile, "utf8")).stopped ?? [], stopped => stopped.includes("shared"));+ vmState();+ await setIdleMinutes(480);++ vmState({ ...READY, holdPull: true });+ const pulling = api("POST", "/api/local-computer/pull", {});+ await sleep(300);+ const refused = await control(api, witness, { action: "take" });+ expect(refused.status).toBe(409);+ expect(await held(witness)).toBe(false);+ vmState();+ expect((await pulling).status).toBe(200);+ expect((await control(api, witness, { action: "take" })).body.held).toBe(true);+ }, 30_000);++ it("a person's hold on the shared desktop refuses moving an Auto bot off it, and a take waits out a mode change", async () => {+ const a = await newBot("Ada");+ await control(api, a.id, { action: "take" });+ const moved = await api("PATCH", `/api/bots/${a.id}`, { computer: "cloud" });+ expect(moved.status).toBe(409);+ await control(api, a.id, { action: "release" });++ holdBoatList = new Promise(resolve => { releaseBoat = resolve; });+ boatListHeld = false;+ const changing = boatCall = api("PATCH", "/api/config", { box: { token: "box_two" }, localVm: { mode: "per-bot" } });+ await until(() => boatListHeld, Boolean);+ const refused = await control(api, a.id, { action: "take" });+ holdBoatList = null;+ releaseBoat();+ expect(refused.status).toBe(409);+ expect((await changing).status).toBe(200);+ }, 30_000);++ it("a Local VM mode change ends the shared desktop's hold and every hold whose key it changes, and keeps the rest", async () => {+ const [a, cloud] = [await newBot("Ada"), await newBot("Cumulus", { computer: "cloud" })];+ await control(api, a.id, { action: "take" });+ await control(api, cloud.id, { action: "take" });+ await setMode("per-bot");+ expect(await held(a.id)).toBe(false);+ expect(await held(witness)).toBe(false);+ expect(await held(cloud.id)).toBe(true);+ await control(api, a.id, { action: "take" });+ await setMode("shared");+ expect(await held(a.id)).toBe(false);+ expect(await held(cloud.id)).toBe(true);+ }, 30_000);++ it.each(["per-bot", "pool"] as const)("a change to %s mode tells every bot paused on the shared desktop that it is free", async (mode) => {+ const a = await newBot("Ada");+ await control(api, a.id, { action: "take" });+ const since = sse.frames.length;+ await setMode(mode);+ await until(() => framesFor(a.id, since).at(-1)?.held, value => value === false);+ expect(framesFor(witness, since).at(-1)?.held).toBe(false);+ }, 30_000);++ it.each(["stopped", "in a deleted conversation"] as const)("a sign-in card %s no longer keeps the shared desktop from going back on Done on another bot's card", async (how) => {+ const [a, b] = [await newBot("Ada", { computer: "vm" }), await newBot("Bea", { computer: "vm" })];+ const side = how === "stopped" ? a.threadId : await newTask(a.id);+ await askSignIn((await startTurn(a.id, side)).comms, "a.example");+ await finishTurns([a.id, side]);+ if (how === "stopped") await ok("POST", `/api/bots/${a.id}/interrupt`, { threadId: side });+ else await ok("DELETE", `/api/bots/${a.id}/tasks/${side}`);+ const asked = await startTurn(b.id, b.threadId);+ const card = await askSignIn(asked.comms, "b.example");+ await finishTurns([b.id, b.threadId]);+ await control(api, b.id, { action: "take" }, b.threadId);+ await ok("POST", `/api/bots/${b.id}/sign-in-cards/${card}/done`, { threadId: b.threadId });+ expect(await held(witness)).toBe(false);+ }, 60_000);++ it.each(["stopped", "in a deleted conversation"] as const)("a sign-in card %s asks no shared-desktop panel any more", async (how) => {+ const a = await newBot("Ada", { computer: "vm" });+ const side = how === "stopped" ? a.threadId : await newTask(a.id);+ await askSignIn((await startTurn(a.id, side)).comms, "a.example");+ await finishTurns([a.id, side]);+ expect((await control(api, witness)).body.helpReason).toBeTruthy();+ const since = sse.frames.length;+ if (how === "stopped") await ok("POST", `/api/bots/${a.id}/interrupt`, { threadId: side });+ else await ok("DELETE", `/api/bots/${a.id}/tasks/${side}`);+ await until(() => framesFor(witness, since).at(-1)?.helpReason, reason => reason === null);+ expect((await control(api, witness)).body.helpReason).toBeNull();+ }, 60_000);++ it("deleting a cloud bot's only conversation on the shared VM tells that bot its sign-in request is gone", async () => {+ const a = await newBot("Ada", { computer: "cloud" });+ const side = await newTask(a.id, "vm");+ await askSignIn((await startTurn(a.id, side)).comms, "a.example");+ await finishTurns([a.id, side]);+ await until(() => framesFor(a.id, 0).at(-1)?.helpReason, reason => typeof reason === "string");+ const since = sse.frames.length;+ await ok("DELETE", `/api/bots/${a.id}/tasks/${side}`);+ await until(() => framesFor(a.id, since).at(-1)?.helpReason, reason => reason === null);+ }, 60_000);++ it("every control answer carries the bot's sign-in request from another of its computers, as its frames do", async () => {+ const a = await newBot("Ada", { computer: "cloud" });+ const side = await newTask(a.id, "vm");+ const card = await askSignIn((await startTurn(a.id, side)).comms, "a.example");+ await finishTurns([a.id, side]);+ const id = lease();+ for (const body of [{ action: "take", controlLeaseId: id }, { action: "check", controlLeaseId: id }, { action: "release", controlLeaseId: id }, { action: "take" }, { action: "release" }]) {+ expect((await control(api, a.id, body)).body, JSON.stringify(body)).toMatchObject({ help: { messageId: card } });+ }+ }, 60_000);++ it("an edit that leaves a sign-in card's branch takes its request off every panel", async () => {+ const a = await newBot("Ada", { computer: "vm" });+ await askSignIn((await startTurn(a.id, a.threadId)).comms, "a.example");+ await finishTurns([a.id, a.threadId]);+ expect((await control(api, witness)).body.helpReason).toBeTruthy();+ const asked = (await ok("GET", `/api/threads/${a.threadId}/messages?limit=50`)).messages.find((message: any) => message.role === "user");+ const since = sse.frames.length;+ await ok("POST", `/api/bots/${a.id}/messages/${asked.id}/edit`, { text: `Edited ${randomUUID()}`, threadId: a.threadId });+ await until(() => framesFor(witness, since).at(-1)?.helpReason, reason => reason === null);+ expect((await control(api, witness)).body.helpReason).toBeNull();+ await finishTurns([a.id, a.threadId]);+ }, 60_000);++ it.each(["main conversation", "a room thread"] as const)("removing a bot from its room takes that bot's sign-in request in the %s off every panel", async (where) => {+ const [a, b] = [await newBot("Ada", { computer: "vm" }), await newBot("Bea", { computer: "vm" })];+ const group = (await ok("POST", "/api/groups", { name: `Room ${randomUUID().slice(0, 6)}`, memberIds: [a.id], setup: { bulletin: "", defaultResponder: { kind: "everyone" } } })).group;+ const threadId = where === "a room thread" ? (await ok("POST", `/api/groups/${group.id}/tasks`, {})).task.threadId : undefined;+ const text = `Work on the desktop ${randomUUID()}`;+ await ok("POST", `/api/groups/${group.id}/messages`, { text, ...(threadId ? { threadId } : {}) });+ await askSignIn((await dumpFor(text)).mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN, "a.example");+ writeFileSync(finishFile, "finish");+ expect((await control(api, witness)).body.helpReason).toBeTruthy();+ if (threadId) await until(() => api("POST", `/api/groups/${group.id}/tasks/${group.threadId}`, {}), response => response.status === 200);+ const since = sse.frames.length;+ await until(() => api("PATCH", `/api/groups/${group.id}`, { memberIds: [b.id] }), response => response.status === 200);+ await until(() => framesFor(witness, since).at(-1)?.helpReason, reason => reason === null);+ expect((await control(api, witness)).body.helpReason).toBeNull();+ }, 60_000);++ it.each(["the room", "a room thread", "room threads in bulk"] as const)("a room's sign-in card asks no panel once %s is deleted", async (how) => {+ const a = await newBot("Ada", { computer: "vm" });+ const group = (await ok("POST", "/api/groups", { name: `Room ${randomUUID().slice(0, 6)}`, memberIds: [a.id], setup: { bulletin: "", defaultResponder: { kind: "everyone" } } })).group;+ const threadId: string = how === "the room" ? group.threadId : (await ok("POST", `/api/groups/${group.id}/tasks`, {})).task.threadId;+ const text = `Work on the desktop ${randomUUID()}`;+ await ok("POST", `/api/groups/${group.id}/messages`, { text, ...(how === "the room" ? {} : { threadId }) });+ await askSignIn((await dumpFor(text)).mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN, "a.example");+ writeFileSync(finishFile, "finish");+ expect((await control(api, witness)).body.helpReason).toBeTruthy();+ const since = sse.frames.length;+ if (how === "room threads in bulk") {+ await until(() => api("POST", `/api/groups/${group.id}/tasks/delete`, { threadIds: [threadId] }), response => Boolean(response.body?.deleted?.includes(threadId)));+ } else {+ await until(() => api("DELETE", how === "the room" ? `/api/groups/${group.id}` : `/api/groups/${group.id}/tasks/${threadId}`), response => response.status === 200);+ }+ await until(() => framesFor(witness, since).at(-1)?.helpReason, reason => reason === null);+ expect((await control(api, witness)).body.helpReason).toBeNull();+ }, 60_000);++ it("only a person's Done on the shared desktop's last open sign-in card hands it back", async () => {+ const [a, b] = [await newBot("Ada", { computer: "vm" }), await newBot("Bea", { computer: "vm" })];+ const asked = await startTurn(b.id, b.threadId);+ await askSignIn(asked.comms, "b.example");+ await finishTurns([b.id, b.threadId]);+ const own = await startTurn(a.id, a.threadId);+ const [first, second] = [await askSignIn(own.comms, "a.example"), await askSignIn(own.comms, "c.example")];+ await finishTurns([a.id, a.threadId]);++ await control(api, a.id, { action: "take" });+ await ok("POST", `/api/bots/${b.id}/messages`, { text: "I signed in to b.example myself.", threadId: b.threadId });+ await until(() => ok("GET", `/api/threads/${b.threadId}/messages?limit=50`),+ page => page.messages.some((message: any) => message.signIn?.answeredInChat));+ expect(await held(a.id)).toBe(true);+ await ok("POST", `/api/bots/${a.id}/sign-in-cards/${first}/done`, { threadId: a.threadId });+ expect(await held(a.id)).toBe(true);+ await ok("POST", `/api/bots/${a.id}/sign-in-cards/${second}/done`, { threadId: a.threadId });+ expect(await held(a.id)).toBe(false);+ }, 60_000);++ it("a change on a bot's own key while the shared desktop is held still tells its panels it is held", async () => {+ const a = await newBot("Ada");+ const elsewhere = await newTask(a.id, "cloud");+ const start = sse.frames.length;+ await control(api, witness, { action: "take" });+ await until(() => framesFor(a.id, start), frames => frames.length === 1);+ await control(api, a.id, { action: "take" }, elsewhere);+ await until(() => framesFor(a.id, start), frames => frames.length === 2);+ const since = sse.frames.length;+ await control(api, a.id, { action: "release" }, elsewhere);+ await until(() => framesFor(a.id, since), frames => frames.length > 0);+ expect(framesFor(a.id, since).at(-1)).toMatchObject({ held: true });+ });++ it("deleting a bot takes its sign-in request off the shared desktop", async () => {+ const b = await newBot("Bea", { computer: "vm" });+ const asked = await startTurn(b.id, b.threadId);+ await askSignIn(asked.comms, "b.example");+ await finishTurns([b.id, b.threadId]);+ expect((await control(api, witness)).body.helpReason).toBe("sign in to b.example");+ await ok("DELETE", `/api/bots/${b.id}`);+ expect((await control(api, witness)).body.helpReason).toBeNull();+ }, 30_000);++ it("a cloud bot's conversation pinned to the shared VM takes, asks and pauses on the shared desktop", async () => {+ const books = await newBot("Books", { computer: "cloud" });+ const pinned = await newTask(books.id, "vm");+ const asked = await startTurn(books.id, pinned);+ const card = await askSignIn(asked.comms, "ledger.example");+ await finishTurns([books.id, pinned]);+ expect((await control(api, witness)).body.helpReason).toBe("sign in to ledger.example");++ const since = sse.frames.length;+ await control(api, books.id, { action: "take" }, pinned);+ expect(await held(witness)).toBe(true);+ await until(() => framesFor(books.id, since).at(-1)?.held, value => value === true);+ const worker = await newBot("Tickets", { computer: "vm" });+ const { computer } = await startTurn(worker.id, worker.threadId);+ expect(await gate(computer)).toMatchObject({ held: true, reason: "person" });+ await ok("POST", `/api/bots/${books.id}/sign-in-cards/${card}/done`, { threadId: pinned });+ expect(await held(witness)).toBe(false);+ expect(await gate(computer)).toEqual({ held: false, helpOpen: false });+ await until(() => busy(books.id, pinned), Boolean);+ await finishTurns([worker.id, worker.threadId], [books.id, pinned]);++ const own = lease();+ expect((await control(phone, books.id, { action: "take", controlLeaseId: own })).body.owned).toBe(true);+ expect((await joinVm(books.id, own)).status).toBe(409);+ expect((await control(phone, books.id, { action: "release", controlLeaseId: own })).body.released).toBe(true);++ const there = lease();+ expect((await control(phone, books.id, { action: "take", controlLeaseId: there }, pinned)).body.owned).toBe(true);+ expect(await held(witness)).toBe(true);+ await ok("PATCH", `/api/bots/${books.id}/tasks/${pinned}`, { surface: "cloud" });+ expect((await control(phone, books.id, { action: "release", controlLeaseId: there })).body.released).toBe(true);+ expect(await held(witness)).toBe(false);+ }, 60_000);++ it("a thread-less take of an Auto bot keeps its Boat in use and pauses its conversation on the cloud too", async () => {+ const a = await newBot("Ada");+ const scope = createHash("sha256").update(readFileSync(join(home, "data", "environment-id"), "utf8").trim()).digest("hex").slice(0, 12);+ const name = `ogb-${scope}-${a.id.slice(0, 8).replace(/[^a-z0-9]/g, "")}-${createHash("sha256").update(a.id).digest("hex").slice(0, 6)}`;+ boatRow = { id: "bx_abcdefgh", name, state: "idle" };+ try {+ const onCloud = await newTask(a.id, "cloud");+ const { computer } = await startTurn(a.id, onCloud);+ // A Boat's tools reach the gate through the harness proxy, with the turn's computer capability.+ const boatGate = () => gate({ env: { OMB_CONTROL_URL: `${base}/api/internal/computer-control?botId=${a.id}`, OMB_CONTROL_TOKEN: computer.env.OMB_MCP_TOKEN_COMPUTER } });+ expect(await boatGate()).toEqual({ held: false, helpOpen: false });+ await control(api, a.id, { action: "take" });+ expect(await boatGate()).toMatchObject({ held: true, reason: "person" });+ await finishTurns([a.id, onCloud]);+ const boxes = (await ok("GET", "/api/computers/boxes")).instances;+ expect(boxes.find((instance: { ownerBotId: string }) => instance.ownerBotId === a.id)).toMatchObject({ inUse: true });+ } finally {+ await control(api, a.id, { action: "release" });+ boatRow = null;+ }+ }, 30_000);+});diff --git a/server/testing/group-local-vm-hooks.mjs b/server/testing/group-local-vm-hooks.mjsindex 4a844eec31..fcb355780f 100644--- a/server/testing/group-local-vm-hooks.mjs+++ b/server/testing/group-local-vm-hooks.mjs@@ -42,12 +42,20 @@ registerHooks({` };if (url === mock) return { format: 'module', shortCircuit: true, source: `export * from ${JSON.stringify(actual)};- import { SHARED_LOCAL_VM_TARGET } from ${JSON.stringify(actual)};+ import { SHARED_LOCAL_VM_TARGET, containerComputerFrame as actualFrame } from ${JSON.stringify(actual)};import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { writeFileAtomic } from ${JSON.stringify(atomic)};const file = ${JSON.stringify(state)};const read = () => JSON.parse(readFileSync(file, 'utf8'));- export async function containerRuntimeStatus() { return { runtime: 'podman', daemonUp: true }; }+ export async function containerRuntimeStatus() {+ while (read().holdRuntime) { writeFileSync(file + '.runtime', '1'); await new Promise(r => setTimeout(r, 30)); }+ return { runtime: 'podman', daemonUp: true };+ }+ export async function containerComputerFrame(...args) {+ if (!read().frames) return actualFrame(...args);+ writeFileSync(file + '.frame', '1');+ return { png: 'iVBORw0KGgo=', format: 'png' };+ }export async function containerExec(target, command) {writeFileSync(file + '.exec', JSON.stringify({ target, command }));return { exitCode: 0, stdout: 'fixture command completed', stderr: '', timedOut: false };@@ -70,6 +78,7 @@ registerHooks({imageMatches: !outdated && image, network: 'loopback', security: 'hardened', persistence: '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',+ 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 };}export async function containerComputerAction(action, _run, _platform, target = SHARED_LOCAL_VM_TARGET) {@@ -102,6 +111,12 @@ registerHooks({}` };const result = nextLoad(url, context);+ if (url.endsWith('/computer-control.ts') && process.env.OMB_TEST_LEASE_GRACE_MS) {+ return { ...result, source: String(result.source).replace('const LEASE_GRACE_MS = 60_000;', `const LEASE_GRACE_MS = ${Number(process.env.OMB_TEST_LEASE_GRACE_MS)};`) };+ }+ if (url.endsWith('/routes/desktop-viewer.ts') && process.env.OMB_TEST_VIEWER_RECHECK_MS) {+ return { ...result, source: String(result.source).replace('const RECHECK_MS = 5_000;', `const RECHECK_MS = ${Number(process.env.OMB_TEST_VIEWER_RECHECK_MS)};`) };+ }if (url.endsWith('/computer-idle.ts')) {return { ...result, source: `import { readFileSync as readVmIdle } from 'node:fs';\n` +String(result.source).replaceAll('checkedIdleMs(idleMs)', `(JSON.parse(readVmIdle(${JSON.stringify(state)}, 'utf8')).idleMs ?? checkedIdleMs(idleMs))`) };