Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
test: six flaky tests wait on what they check, not on a clock or a lucky port (#3822)
Milind Sonia5b54625665f
diff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex 770bcc0274..17b89ebda8 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -2,7 +2,7 @@// The openmausbot headless verbs for verifying an isolated fixture. A verb that// changes something never runs on a server it merely found.import { spawn, type ChildProcess } from "node:child_process";-import { closeSync, mkdirSync, mkdtempSync, openSync, writeFileSync } from "node:fs";+import { closeSync, mkdirSync, mkdtempSync, openSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { delimiter, dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";@@ -13,6 +13,7 @@ import { runHeadlessCommand } from "../server/headless/main.ts";import type { handleToolCall, request } from "./mcp-server.ts";import { launchUi, runControlOmbUi } from "./testing/control-omb-ui.ts";import { removeTempDir, waitForExit } from "../server/testing/cleanup.ts";+import { hostTimeout } from "../server/testing/host-timeout.ts";import { freePortBlock } from "../server/testing/ports.ts";const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");@@ -345,12 +346,20 @@ export async function launchVerificationServer(});closeSync(log);- const deadline = Date.now() + 20_000;+ // A CI runner's temporary folder goes with the runner, so a failed start carries the end of the server's log.+ const logTail = () => {+ try {+ return `\n${readFileSync(logPath, "utf8").slice(-2_000)}`;+ } catch {+ return "";+ }+ };+ const deadline = Date.now() + hostTimeout(20_000);try {for (;;) {if (signal?.aborted) throw new ControlOmbError("verification launch cancelled");if (child.exitCode !== null || child.signalCode !== null) {- throw new Error(`verification server exited before it was ready; see ${logPath}`);+ throw new Error(`verification server exited before it was ready; see ${logPath}${logTail()}`);}try {const timeout = AbortSignal.timeout(1_000);@@ -361,7 +370,7 @@ export async function launchVerificationServer(if (body?.app === "openmausbot") break;} catch {}- if (Date.now() >= deadline) throw new Error(`verification server did not become ready; see ${logPath}`);+ if (Date.now() >= deadline) throw new Error(`verification server did not become ready; see ${logPath}${logTail()}`);await new Promise((resolve) => setTimeout(resolve, 150));}} catch (error) {diff --git a/server/boat-auto-sleep.test.ts b/server/boat-auto-sleep.test.tsindex d5722b41d4..ab0697e877 100644--- a/server/boat-auto-sleep.test.ts+++ b/server/boat-auto-sleep.test.ts@@ -4,6 +4,8 @@ import { createHash } from "node:crypto";import { createServer, type Server } from "node:http";import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { hostTimeout } from "./testing/host-timeout.ts";+const INCLUDED = "box_omb_included-relay-token";const OWN = "boat_own-key";const botId = "auto-sleep-test";@@ -18,7 +20,7 @@ let stopStatus = 200;const requests: Array<{ method: string; path: string; auth: string; command?: string; at: number }> = [];const stops = () => requests.filter(request => request.method === "POST" && request.path.endsWith("/stop"));-const waitFor = async (accept: () => boolean, ms = 5_000) => {+const waitFor = async (accept: () => boolean, ms = hostTimeout(5_000)) => {const end = Date.now() + ms;while (!accept()) {if (Date.now() > end) throw new Error(`timed out: ${JSON.stringify(requests)}`);@@ -139,7 +141,8 @@ describe("a cloud computer goes to sleep after its idle window", () => {expect(requests).toEqual([]);busy = false;state = "archived";- await new Promise(resolve => setTimeout(resolve, 1_800));+ // The first quiet look starts a full window; the look after it finds the computer asleep and lets its timer go.+ await waitFor(() => !power.awake());expect(stops()).toEqual([]);expect(requests.map(request => request.method)).toEqual(["GET"]);});@@ -148,7 +151,7 @@ describe("a cloud computer goes to sleep after its idle window", () => {stopStatus = 503;await powerFor({});power.used(botId);- await waitFor(() => stops().length === 3 && logs.length === 3, 10_000);+ await waitFor(() => stops().length === 3 && logs.length === 3, hostTimeout(10_000));for (const line of logs) {expect(line).toBe("cloud computer auto-sleep-test: could not go to sleep, retrying in 1 min: boat sleep failed: Cloud computers are not available right now.");}diff --git a/server/browser-evidence.test.ts b/server/browser-evidence.test.tsindex 6f3625d455..247c2249dc 100644--- a/server/browser-evidence.test.ts+++ b/server/browser-evidence.test.ts@@ -15,11 +15,14 @@ const GEN2 = "7a1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b";const roots: string[] = [];afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });-function store(options: { free?: number; now?: () => number } = {}) {+function store(options: { free?: number; now?: () => number; freeFloor?: number } = {}) {const root = join(mkdtempSync(join(tmpdir(), "omb-evidence-")), "evidence");roots.push(join(root, ".."));const free = options.free ?? 100 * 1024 ** 3;- return new BrowserEvidence({ root, statfs: async () => ({ bavail: free / 4096, bsize: 4096 }), ...(options.now ? { now: options.now } : {}) });+ return new BrowserEvidence({+ root, statfs: async () => ({ bavail: free / 4096, bsize: 4096 }),+ ...(options.now ? { now: options.now } : {}), ...(options.freeFloor ? { freeFloor: options.freeFloor } : {}),+ });}function step(evidence: BrowserEvidence, threadId: string, generation = GEN, extra: Partial<StepRecord> = {}): StepRecord {@@ -87,11 +90,12 @@ describe("the browser step store", () => {await low.sweep();expect((await shot(low, "thread-1", Buffer.from("x"))).imageSkipped).toBe("disk-low");expect(low.list("thread-1").steps).toHaveLength(1);- // A quarter of the free space caps the whole store: here, 1.25 GB free allows 320 MB.- const small = store({ free: 1.25 * 1024 ** 3 });+ // A quarter of the free space caps the whole store: here, with the floor scaled down a thousandfold, 1.25 MB free+ // allows 320 KB. Real sizes would need a 330 MB file, which a Windows runner can take over 40 s to write.+ const small = store({ free: 1.25 * 1024 ** 2, freeFloor: EVIDENCE_LIMITS.freeFloor / 1024 });await small.sweep();mkdirSync(join(small.root, "thread-old", GEN), { recursive: true });- fileOfSize(join(small.root, "thread-old", GEN, imageFileName(9)), 330 * 1024 ** 2);+ fileOfSize(join(small.root, "thread-old", GEN, imageFileName(9)), 330 * 1024);await small.sweep();// Over the cap: the oldest other conversation's screenshots go first, its steps stay.writeFileSync(join(small.root, "thread-old", GEN, "steps.jsonl"), `${JSON.stringify({ v: 1, step: 9, threadId: "thread-old", generation: GEN, image: imageFileName(9) })}\n`);@@ -129,12 +133,12 @@ describe("the browser step store", () => {it("never evicts a generation being written now", async () => {let now = Date.now();- const evidence = store({ free: 1.25 * 1024 ** 3, now: () => now });+ const evidence = store({ free: 1.25 * 1024 ** 2, now: () => now });await shot(evidence, "thread-busy", Buffer.from("live turn"));- // The store is over its 320 MB cap, and the busy turn holds most of it.- fileOfSize(join(evidence.root, "thread-busy", GEN, imageFileName(500)), 300 * 1024 ** 2);+ // The store is over its 320 KB cap, and the busy turn holds most of it.+ fileOfSize(join(evidence.root, "thread-busy", GEN, imageFileName(500)), 300 * 1024);mkdirSync(join(evidence.root, "thread-idle", GEN2), { recursive: true });- fileOfSize(join(evidence.root, "thread-idle", GEN2, imageFileName(7)), 40 * 1024 ** 2);+ fileOfSize(join(evidence.root, "thread-idle", GEN2, imageFileName(7)), 40 * 1024);now += 60_000;await evidence.sweep();expect(readdirSync(join(evidence.root, "thread-busy", GEN)).filter((name) => name.endsWith(".jpg"))).toHaveLength(2);diff --git a/server/browser-evidence.ts b/server/browser-evidence.tsindex e9b8e03051..0d6c7b78f0 100644--- a/server/browser-evidence.ts+++ b/server/browser-evidence.ts@@ -75,6 +75,7 @@ export class BrowserEvidence {readonly root: string;private statfs: Statfs;private now: () => number;+ private freeFloor: number;private counter: { next: number; reserved: number } | null = null;private threadBytes = new Map<string, number>();private stepBytes = new Map<string, number>();@@ -88,10 +89,12 @@ export class BrowserEvidence {private unsubscribe?: () => void;private sweeping: Promise<void> | null = null;- constructor(options: { root: string; statfs?: Statfs; now?: () => number }) {+ /** `freeFloor`: the free space below which no screenshot is kept, EVIDENCE_LIMITS.freeFloor unless a test scales it down. */+ constructor(options: { root: string; statfs?: Statfs; now?: () => number; freeFloor?: number }) {this.root = options.root;this.statfs = options.statfs ?? statfsAsync;this.now = options.now ?? Date.now;+ this.freeFloor = options.freeFloor ?? EVIDENCE_LIMITS.freeFloor;}attach(deps: EvidenceDeps): this {@@ -365,7 +368,7 @@ export class BrowserEvidence {try {const fs = await this.statfs(this.root).catch(() => this.statfs(join(this.root, "..")));const free = Number(fs.bavail) * Number(fs.bsize);- this.budget = { cap: Math.min(EVIDENCE_LIMITS.totalBytes, Math.floor(free * EVIDENCE_LIMITS.freeShare)), low: free < EVIDENCE_LIMITS.freeFloor };+ this.budget = { cap: Math.min(EVIDENCE_LIMITS.totalBytes, Math.floor(free * EVIDENCE_LIMITS.freeShare)), low: free < this.freeFloor };} catch {}const expired = this.now() - EVIDENCE_LIMITS.retentionMs;let total = 0;diff --git a/server/cli-service-trust.e2e.test.ts b/server/cli-service-trust.e2e.test.tsindex f7b33ec770..e53620691a 100644--- a/server/cli-service-trust.e2e.test.ts+++ b/server/cli-service-trust.e2e.test.ts@@ -8,13 +8,14 @@ import { promisify } from "node:util";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";+import { freePortBlock } from "./testing/ports.ts";const SERVER_DIR = dirname(fileURLToPath(import.meta.url));const ENTRY = join(SERVER_DIR, "openmausbot.ts");-const PORT = 38800 + Math.floor(Math.random() * 5_000);const run = promisify(execFile);let home: string;+let PORT: number;let serve: ChildProcess;let output = "";@@ -36,6 +37,7 @@ const cli = async (args: string[]) => {describe.skipIf(process.platform === "win32")("openmausbot serve under service loopback trust", () => {beforeAll(async () => {home = mkdtempSync(join(tmpdir(), "omb-cli-service-"));+ PORT = await freePortBlock([0, 1]);serve = spawn(process.execPath, ["--experimental-strip-types", ENTRY, "serve", "--port", String(PORT), "--data-dir", join(home, "data")], {env: environment(), stdio: ["ignore", "pipe", "pipe"],});diff --git a/server/comms.test.ts b/server/comms.test.tsindex 00775ab020..8f87c675aa 100644--- a/server/comms.test.ts+++ b/server/comms.test.ts@@ -6,7 +6,7 @@ import type { AddressInfo } from "node:net";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";import { ENVELOPE_MARK } from "./runtime/envelope.ts";@@ -101,6 +101,8 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {let child: ChildProcess;let home: string;let gateFile = "";+ // While it exists the plain helper holds every prompt unanswered (FAKE_ACP_HOLD_FILE).+ let holdFile = "";let stderr = "";// A loopback OpenAI-compatible engine under the workspace key: a request hangs until the engine is replaced ("hang"),// answers "ping from fake", loops on tool calls ("steps"), or is rate-limited ("limit").@@ -190,6 +192,7 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {chmodSync(FAKE_CLI, 0o755);home = mkdtempSync(join(tmpdir(), "omb-comms-test-"));gateFile = join(home, "helper-gate");+ holdFile = join(home, "helper-hold");const antigravityDirectory = join(home, "fake-antigravity");const antigravityCli = join(antigravityDirectory, "agy_acp_server.ts");const antigravityHarness = join(@@ -250,7 +253,7 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {// Plain helpers: a helper that consulted in turn would recurse until the depth limit.helper: {driver: "grokAgent",- environment: { FAKE_ACP_MODE: "happy", FAKE_ACP_DUMP: join(home, "helper.json"), FAKE_ACP_DUMP_PROMPT: "1" },+ environment: { FAKE_ACP_MODE: "happy", FAKE_ACP_DUMP: join(home, "helper.json"), FAKE_ACP_DUMP_PROMPT: "1", FAKE_ACP_HOLD_FILE: holdFile },config: { cli: FAKE_CLI, fullAuto: true },},// a helper that lists the tools of every MCP server its turn was@@ -382,6 +385,8 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {expect((await api("PATCH", `/api/bots/${starter.id}`, { name: "Comms fixture starter" })).status).toBe(200);}, 30_000);+ afterEach(() => rmSync(holdFile, { force: true }));+afterAll(async () => {await waitForExit(child, { signal: "SIGTERM" });compat.closeAllConnections();@@ -405,6 +410,8 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {const helper = await named("Helper", { modelSelection: HELPER });const asker = await named("Asker", { modelSelection: ASKER });+ // The helper answers at once, and the run's wait could end between two looks: it holds its answer until the wait is seen.+ writeFileSync(holdFile, "hold");const send = await startRoutine(asker.id, "hey @Helper ping");expect(send.status).toBe(201);const run = send.body.run;@@ -423,6 +430,8 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {const [consult] = assignments(helper.id, asker.id);expect(consult).toMatchObject({ mode: "consult", reply: "resume", text: "ping from fake" });expect(rows().find((node) => node.id === consult.parentId)).toMatchObject({ threadId: run.threadId, botId: asker.id });+ expect((await runState(run.id)).status).toBe("waiting");+ rmSync(holdFile);await waitUntil(async () => {askerBot = await bot(asker.id);diff --git a/server/computer-idle.test.ts b/server/computer-idle.test.tsindex 67b6344994..6417521fcb 100644--- a/server/computer-idle.test.ts+++ b/server/computer-idle.test.ts@@ -132,6 +132,27 @@ describe("ComputerIdleTimer", () => {expect(suspend).toHaveBeenCalledOnce();});+ type Stop = { promise: Promise<void | "busy">; resolve: (outcome: void | "busy") => void; reject: (error: Error) => void };+ it.each([+ ["fails", (stop: Stop) => stop.reject(new Error("provider 503"))],+ ["finds work arrived", (stop: Stop) => stop.resolve("busy")],+ ])("stays cancelled when a stop already under way %s", async (_, settle) => {+ const stop = {} as Stop;+ stop.promise = new Promise((resolve, reject) => Object.assign(stop, { resolve, reject }));+ const suspend = vi.fn(() => stop.promise);+ const failed = vi.fn();+ const idle = new ComputerIdleTimer(1_000, () => false, suspend, failed);++ idle.touch();+ await vi.advanceTimersByTimeAsync(1_000);+ expect(suspend).toHaveBeenCalledOnce();+ idle.cancel();+ settle(stop);+ await vi.advanceTimersByTimeAsync(10_000);+ expect(suspend).toHaveBeenCalledOnce();+ expect(failed).not.toHaveBeenCalled();+ });+it("does not arm a cancelled timer when the window changes", async () => {const suspend = vi.fn(async () => {});const idle = new ComputerIdleTimer(1_000, () => false, suspend);diff --git a/server/computer-idle.ts b/server/computer-idle.tsindex 25f37b4bbb..12ce239139 100644--- a/server/computer-idle.ts+++ b/server/computer-idle.ts@@ -8,6 +8,8 @@ export class ComputerIdleTimer {private lastActivityAt = 0;private failures = 0;private busySeen = false;+ /** Bumped by every cancel, so a stop still in flight from an earlier window neither re-arms nor reports. */+ private generation = 0;private idleMs: number;private readonly isBusy: () => boolean;private readonly suspend: () => Promise<void | "busy">;@@ -34,6 +36,7 @@ export class ComputerIdleTimer {}cancel(): void {+ this.generation += 1;if (this.timer) clearTimeout(this.timer);this.timer = null;}@@ -61,9 +64,12 @@ export class ComputerIdleTimer {this.touch();return;}+ const generation = this.generation;try {- if (await this.suspend() === "busy") this.touch();+ const outcome = await this.suspend();+ if (generation === this.generation && outcome === "busy") this.touch();} catch (error) {+ if (generation !== this.generation) return;this.failures += 1;const retryInMs = Math.min(this.idleMs * 2 ** (this.failures - 1), Math.max(this.idleMs, MAX_RETRY_MS));this.onFailure?.(error, retryInMs);diff --git a/server/host-lazy-claim.e2e.test.ts b/server/host-lazy-claim.e2e.test.tsindex a85e30d649..cf0393741b 100644--- a/server/host-lazy-claim.e2e.test.ts+++ b/server/host-lazy-claim.e2e.test.ts@@ -7,14 +7,16 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";import { writeFileAtomic } from "./atomic.ts";import { CONTROL_BUSY, CONTROL_HANDED_BACK, CONTROL_REFUSAL_PLAIN, CONTROL_WAITED, controlRefusal, createControlClient } from "./control-client.ts";import { computerPersonAwayText } from "./computer-wait.ts";+import { hostTimeout } from "./testing/host-timeout.ts";import { freePortBlock } from "./testing/ports.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";import { answerYourComputer, openYourComputerCard, withAnswer } from "./testing/your-computer.ts";import { YOUR_COMPUTER_WAITING } from "./your-computer-consent.ts";const ROOT = fileURLToPath(new URL("..", import.meta.url));-const CALL_WAIT_MS = 5_000;-const ACT_WITHIN_MS = 1_000;+// A first screen call must clear within ACT_WITHIN_MS, the person's answer to its card and the seat's claim included.+const CALL_WAIT_MS = hostTimeout(5_000);+const ACT_WITHIN_MS = hostTimeout(1_000);describe("lazy host claim and pin on use (issue #1650)", () => {let home = "";diff --git a/server/host/cloud-computer-power.ts b/server/host/cloud-computer-power.tsindex 9a42b77f3e..cafa75b9a1 100644--- a/server/host/cloud-computer-power.ts+++ b/server/host/cloud-computer-power.ts@@ -58,6 +58,7 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {if (!boat.boatConfigured(cfg) || hasPendingBoatDeletionForBot(owner)) return forget(owner);if (boatCreateRecoverySnapshot().some((entry) => entry.botId === owner && !entry.resolved)) return "busy";const machine = await boat.findBoat(cfg, owner);+ if (closed) return;const state = typeof machine?.state === "string" ? machine.state : null;if (!state || boat.SLEEPING_BOAT_STATES.has(state)) return forget(owner);if (boat.boatTurnLifecycleAction(state) !== "attach" || busy(owner)) return "busy";diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex e100d33aa9..feb56643cb 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -57,6 +57,7 @@// under it the reply is "tools: <server>=<count>,…"// FAKE_ACP_CANCEL_STOP_REASON the stopReason a cancelled hanging prompt answers (default cancelled; OpenCode answers end_turn)// FAKE_ACP_HANG_ONCE_FILE with FAKE_ACP_HANG_ON, only the first matching prompt hangs; it writes this file+// FAKE_ACP_HOLD_FILE while this file exists, a session/prompt waits before it is answeredimport { AsyncLocalStorage } from "node:async_hooks";import { spawn } from "node:child_process";import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";@@ -572,6 +573,17 @@ process.stdin.on("data", (c) => {}});+function heldByHoldFile(msg: any): boolean {+ const hold = process.env.FAKE_ACP_HOLD_FILE;+ if (!hold || !existsSync(hold)) return false;+ const poll = setInterval(() => {+ if (existsSync(hold)) return;+ clearInterval(poll);+ handle(msg);+ }, 50);+ return true;+}+function handle(msg: any) {if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined) && msg.id === pendingAskQuestionId) {pendingAskQuestionId = null;@@ -594,6 +606,7 @@ function handle(msg: any) {return;}if (!msg.method) return;+ if (msg.method === "session/prompt" && heldByHoldFile(msg)) return;recordMethod(msg.method);switch (msg.method) {