Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Tests: six flaky tests made deterministic (cloud computer, MCP zombie, team lease, boat recovery, updater, Antigravity) (#6785)
Milind Soni38d57c3c007d
diff --git a/electron/fixtures/updater-handoff.cjs b/electron/fixtures/updater-handoff.cjsindex 9bf8801d16..8da44d8f22 100644--- a/electron/fixtures/updater-handoff.cjs+++ b/electron/fixtures/updater-handoff.cjs@@ -13,6 +13,12 @@ function say(marker) {process.stdout.write(`${marker}\n`);}+// The hand-off returns once the terminal has spawned; the stand-in writes its receipt some time after that.+async function appears(file, ms = 15_000) {+ for (const end = Date.now() + ms; !existsSync(file) && Date.now() < end;) await new Promise((resolve) => setTimeout(resolve, 25));+ return existsSync(file);+}+async function main() {const { handOffDownloadedPackage } = await import("../updater.mjs");const { packageInstallCommand } = await import("../package-install-command.mjs");@@ -40,7 +46,7 @@ async function main() {if (clipboard.readText() === expected) say("clipboard-holds-the-install-command");else say(`clipboard-mismatch:${JSON.stringify(clipboard.readText())}`);- if (existsSync(receipt)) say("terminal-really-launched");+ if (await appears(receipt)) say("terminal-really-launched");if (result.terminalOpened === true) say("hand-off-reported-the-terminal");if (result.command === expected) say("hand-off-returned-the-command");diff --git a/server/boat-recovery.test.ts b/server/boat-recovery.test.tsindex c196a122fb..ceb076bf6f 100644--- a/server/boat-recovery.test.ts+++ b/server/boat-recovery.test.ts@@ -34,6 +34,8 @@ let deletesAllowed = false;const teamOwners = new Set<string>();const watched = new Set<string>();const deleteSpans: Array<{ boxId: string; start: number; end: number }> = [];+/** The recovery's requests to the stand-in: each answer is read whole before the recovery sees it. */+let inFlight = 0, sent = 0;const pendingDeletes = new Set<string>();const send = (res: import("node:http").ServerResponse, status: number, body: unknown) => {@@ -111,9 +113,18 @@ beforeAll(async () => {const { port } = server.address() as { port: number };vi.stubEnv("OMB_CLOUD_BOAT_URL", `http://127.0.0.1:${port}/relay/api/box/v1`);vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", "box_omb_synthetic");+ const realFetch = globalThis.fetch;+ vi.spyOn(globalThis, "fetch").mockImplementation(async (...args) => {+ inFlight++;+ try {+ const res = await realFetch(...args);+ return new Response(await res.arrayBuffer(), { status: res.status, statusText: res.statusText, headers: res.headers });+ } finally { inFlight--; sent++; }+ });});afterAll(async () => {vi.unstubAllEnvs();+ vi.restoreAllMocks();server.closeAllConnections();await new Promise<void>((resolve) => server.close(() => resolve()));});@@ -157,8 +168,9 @@ beforeEach(async () => {await load();start();});-afterEach(() => {+afterEach(async () => {recovery.close();+ await quiet();if (!deletesAllowed) expect(requests.filter((request) => request.method === "DELETE")).toEqual([]);});@@ -192,6 +204,20 @@ const until = async (check: () => boolean, ms = 20_000) => {for (const end = Date.now() + ms; Date.now() < end; await new Promise((resolve) => setTimeout(resolve, 20))) if (check()) return;throw new Error("timed out");};+/** A probe that is in flight while the clock jumps took that long, as far as the recovery can tell, so it counts as one+ * this process held up. The jump waits for a moment with no request in flight. */+const jump = async (ms: number) => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ await until(() => inFlight === 0);+ at += ms;+};+/** A closed recovery's work under way still finishes: the next test starts once it has sent nothing for a while. */+const quiet = async () => {+ for (let seen = -1, end = Date.now() + 10_000; (seen !== sent || inFlight > 0) && Date.now() < end;) {+ seen = sent;+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+};/** Three probes with no answer over more than ten minutes, as the health check records them. */const stopsAnswering = (boxId: string) => {health.unanswered(boxId);@@ -493,7 +519,7 @@ describe("a cloud computer that says it is ready but does not answer", () => {stopsAnswering(box.id);await until(() => recovery.status(botId)?.state === "needs-person");expect(stops()).toHaveLength(0);- at += DEAD_CONFIRM;+ await jump(DEAD_CONFIRM);health.answered(witness.box.id);health.unanswered(box.id);await until(() => recovery.status(botId)?.state === "replaced");@@ -584,7 +610,7 @@ describe("before a silent computer is restarted by itself", () => {await until(() => requests.filter((request) => request.path === `/boxes/${box.id}/commands`).length >= 3);expect(recovery.status(botId)?.state).toBe("not-responding");expect(stops()).toHaveLength(0);- at += 5 * 60_000;+ await jump(5 * 60_000);await until(() => recovery.status(botId)?.state === "restarted");expect(stops()).toHaveLength(1);});@@ -616,7 +642,7 @@ describe("before a silent computer is restarted by itself", () => {await until(() => requests.filter((request) => request.path === `/boxes/${box.id}/commands`).length >= 3);expect(recovery.status(botId)?.state).toBe("not-responding");expect(stops()).toHaveLength(0);- at += 11 * 60_000;+ await jump(11 * 60_000);health.answered(witness.box.id);await until(() => recovery.status(botId)?.state === "needs-person");expect(stops()).toHaveLength(0);@@ -652,7 +678,7 @@ describe("why a silent computer was left as it is", () => {await boat.findBoat(cfg, botId);stopsAnswering(box.id);await until(() => recovery.verdict(botId) === "restart-failed" && recovery.status(botId)?.state === "needs-person");- at += 20 * 60_000;+ await jump(20 * 60_000);health.unanswered(box.id);await until(() => recovery.status(botId)?.state === "not-responding");await until(() => recovery.status(botId)?.state === "needs-person");@@ -671,13 +697,13 @@ describe("why a silent computer was left as it is", () => {expect(recovery.verdict(botId)).toBeNull();resumeAnswers.delete(box.id);commandStatus.set(box.id, 502);- at += 20 * 60_000;+ await jump(20 * 60_000);stopsAnswering(box.id);await until(() => recovery.verdict(botId) === "restart-limited" && recovery.status(botId)?.state === "needs-person");expect(stops()).toHaveLength(1);commandStatus.delete(box.id);health.answered(box.id);- at += 61 * 60_000;+ await jump(61 * 60_000);expect(recovery.status(botId)).toBeNull();expect(recovery.verdict(botId)).toBeNull();});@@ -863,7 +889,7 @@ describe("with automatic replacement switched off", () => {expect(told).toEqual([[botId, "needsPerson"]]);expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_NEEDS_PERSON);expect(recovery.refusal(box.id, "before")).toBeNull();- at += 6 * 60_000;+ await jump(6 * 60_000);health.answered(witness.box.id);health.unanswered(box.id);expect(recovery.status(botId)?.state).toBe("not-responding");diff --git a/server/cloud-computer-background.test.ts b/server/cloud-computer-background.test.tsindex 755d1af4b8..e6c747860c 100644--- a/server/cloud-computer-background.test.ts+++ b/server/cloud-computer-background.test.ts@@ -16,6 +16,7 @@ const calls: Array<{ method: string; path: string; query: string; body: any; autlet nextProcessId = 41;let hold = false;let holdStatusAfterFirst = false;+let statusHeld: (() => void) | undefined;let syncReply: Record<string, unknown> = { exitCode: 0, stdout: "done", stderr: "" };let startReply: { status: number; body: unknown } | undefined;let statusReply: { status: number; body: unknown } | undefined;@@ -43,7 +44,7 @@ beforeAll(async () => {if (statusReply) return send(statusReply.status, statusReply.body);const process = processes.get(`${box}:${pid}`);if (!process) return send(404, { ok: false, code: "not_found", message: "No such process." });- if (holdStatusAfterFirst && process.polls > 0) return;+ if (holdStatusAfterFirst && process.polls > 0) return statusHeld?.();const running = process.polls++ < process.runningFor;return send(200, {ok: true, type: "command.status", success: true, processId: Number(pid), status: running ? "running" : process.lost ? "lost" : "exited", running,@@ -176,7 +177,7 @@ describe("background status deadlines", () => {});afterAll(async () => { vi.unstubAllEnvs(); server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); });beforeEach(() => {- calls.length = 0; processes.clear(); hold = false; holdStatusAfterFirst = false; startReply = undefined; statusReply = undefined;+ calls.length = 0; processes.clear(); hold = false; holdStatusAfterFirst = false; statusHeld = undefined; startReply = undefined; statusReply = undefined;syncReply = { exitCode: 0, stdout: "done", stderr: "" };});@@ -268,12 +269,14 @@ describe.each([it("propagates cancellation during a follow-up status read", async () => {const processId = await start();holdStatusAfterFirst = true;+ const held = new Promise<void>(resolve => { statusHeld = resolve; });+ const stoppedClock = { now: () => 0, sleep: async () => {}, timeout: () => new AbortController().signal };const controller = new AbortController();- const pending = background.backgroundStatus(cfg, BOX, { process_id: processId, wait_seconds: 1 }, controller.signal);- await expect.poll(() => calls.filter(entry => entry.method === "GET").length).toBe(2);+ const pending = background.backgroundStatus(cfg, BOX, { process_id: processId, wait_seconds: 1 }, controller.signal, stoppedClock);+ await held;+ expect(calls.filter(entry => entry.method === "GET")).toHaveLength(2);controller.abort();await expect(pending).rejects.toMatchObject({ name: "AbortError" });- server.closeAllConnections();});it("returns only the end of long output, and never half a character", async () => {diff --git a/server/drivers/antigravity.test.ts b/server/drivers/antigravity.test.tsindex 638e64bf02..88a8f55508 100644--- a/server/drivers/antigravity.test.ts+++ b/server/drivers/antigravity.test.ts@@ -193,8 +193,8 @@ describe("Antigravity sign-in lifecycle", () => {await instance.signOut!();} finally {await instance.dispose();- rmSync(profile, { recursive: true, force: true });- rmSync(antigravityProfileDirectory("antigravity-other"), { recursive: true, force: true });+ await removeTempDir(profile);+ await removeTempDir(antigravityProfileDirectory("antigravity-other"));}});diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex a48a29e1b1..97ac634da6 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -1,4 +1,5 @@import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { spawnSync } from "node:child_process";import { crc32 } from "node:zlib";import { tmpdir } from "node:os";import { join } from "node:path";@@ -112,8 +113,17 @@ async function expectSkipped(f: ReturnType<typeof fixture>, reason: RegExp) {} finally { warn.mockRestore(); }}+/** POSIX: signal 0 still reaches a zombie until whatever adopted it collects it, though it no longer runs. */function alive(pid: number): boolean {- try { process.kill(pid, 0); return true; } catch { return false; }+ try { process.kill(pid, 0); } catch { return false; }+ if (process.platform === "linux") {+ try { const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); return !["Z", "X"].includes(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0]!); } catch { return false; }+ }+ if (process.platform === "darwin") {+ const state = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" }).stdout.trim();+ return state !== "" && !state.startsWith("Z");+ }+ return true;}afterEach(async () => {diff --git a/server/index.test.ts b/server/index.test.tsindex 88856244e6..9d430157b1 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -3570,6 +3570,9 @@ describe("harness HTTP API", () => {}};type ComputerDump = { mcpConfig: { mcpServers: { computer?: { args?: string[] } } } };+ const loggedEvent = async (threadId: string, type: string) =>+ ((await api("GET", `/api/threads/${threadId}/events`)).body.entries as Array<{ kind: string; data: any }>)+ .find((entry) => entry.kind === "runtime" && entry.data.type === type)?.data;const promptsOnBoat = () => boatRouteCalls.filter(call => call.method === "POST" && call.path === `/sandboxes/${managedBoatCreateId}/prompt`).length;let promptBaseline = 0;const promptedOnTeamComputer = async (count: number, botId: string) => {@@ -3637,17 +3640,16 @@ describe("harness HTTP API", () => {expect(siblingMessages.some((message) => (message.tool?.name ?? "").startsWith("Waiting for its turn on this computer"))).toBe(true);const stoppedChip = siblingMessages.find((message) => (message.tool?.name ?? "").startsWith("Stopped waiting for the computer after "));expect(stoppedChip?.tool?.ok).toBe(true);- const siblingEvents = ((await api("GET", `/api/threads/${sibling.threadId}/events`)).body.entries as Array<{ kind: string; data: any }>)- .filter((entry) => entry.kind === "runtime").map((entry) => entry.data);- expect(siblingEvents.find((event) => event.type === "turn.wait_started")).toMatchObject({+ await expect.poll(() => loggedEvent(sibling.threadId, "turn.wait_ended"), { timeout: 5_000 }).toMatchObject({holder: { name: "Direct shared" },- resource: expect.stringMatching(/^computer:/),+ outcome: "stopped",+ waitedMs: expect.any(Number),});- expect(siblingEvents.find((event) => event.type === "turn.wait_ended")).toMatchObject({+ expect(await loggedEvent(sibling.threadId, "turn.wait_started")).toMatchObject({holder: { name: "Direct shared" },- outcome: "stopped",+ resource: expect.stringMatching(/^computer:/),});- expect(siblingEvents.find((event) => event.type === "turn.wait_ended").waitedMs).toBeGreaterThanOrEqual(0);+ expect((await loggedEvent(sibling.threadId, "turn.wait_ended")).waitedMs).toBeGreaterThanOrEqual(0);expect(claudePrompts().length - promptBaseline, "the sibling ran from the start").toBe(2);expect((await api("POST", `/api/bots/${botIds[0]}/tasks/${firstThread}`, {})).status).toBe(200);for (const action of ["sleep", "provision"]) {@@ -3673,14 +3675,12 @@ describe("harness HTTP API", () => {(group: { id: string }) => group.id === roomId,).messages;expect(roomMessages.some((message) => (message.tool?.name ?? "").startsWith("Waiting for its turn on this computer"))).toBe(true);- const roomEvents = ((await api("GET", `/api/threads/${room.threadId}/events`)).body.entries as Array<{ kind: string; data: any }>)- .filter((entry) => entry.kind === "runtime").map((entry) => entry.data);- expect(roomEvents.find((event) => event.type === "turn.wait_started")).toMatchObject({- resource: expect.stringMatching(/^computer:/),- });- expect(roomEvents.find((event) => event.type === "turn.wait_ended")).toMatchObject({+ await expect.poll(() => loggedEvent(room.threadId, "turn.wait_ended"), { timeout: 5_000 }).toMatchObject({outcome: "acquired",});+ expect(await loggedEvent(room.threadId, "turn.wait_started")).toMatchObject({+ resource: expect.stringMatching(/^computer:/),+ });expect(promptsOnBoat()).toBe(0);expect((await api("POST", `/api/team-computers/${requestId}/sleep`, {})).status).toBe(409);expect((await api("POST", `/api/groups/${roomId}/interrupt`, {})).status).toBe(200);