Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bound background status polling reads
WAI LOK HOeff4ecbd5c63
diff --git a/server/cloud-computer-background.test.ts b/server/cloud-computer-background.test.tsindex 2fa8bb71a5..df856dae32 100644--- a/server/cloud-computer-background.test.ts+++ b/server/cloud-computer-background.test.ts@@ -15,6 +15,7 @@ const processes = new Map<string, Process>();const calls: Array<{ method: string; path: string; query: string; body: any; authorization?: string }> = [];let nextProcessId = 41;let hold = false;+let holdStatusAfterFirst = false;let syncReply: Record<string, unknown> = { exitCode: 0, stdout: "done", stderr: "" };let startReply: { status: number; body: unknown } | undefined;let statusReply: { status: number; body: unknown } | undefined;@@ -42,6 +43,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;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,@@ -58,7 +60,7 @@ beforeAll(async () => {});afterAll(async () => { vi.unstubAllEnvs(); server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); });beforeEach(() => {- calls.length = 0; processes.clear(); hold = false; startReply = undefined; statusReply = undefined;+ calls.length = 0; processes.clear(); hold = false; holdStatusAfterFirst = false; startReply = undefined; statusReply = undefined;syncReply = { exitCode: 0, stdout: "done", stderr: "" };});@@ -144,11 +146,33 @@ describe.each([Object.assign(processes.get(`${BOX}:${processId.split("-")[1]}`)!, { runningFor: finishes ? 1 : 100, exitCode: 3 });const began = Date.now();const result = json(await call("exec_status", { process_id: processId, wait_seconds: 1 }).done);- expect(Date.now() - began).toBeGreaterThanOrEqual(900);+ expect(Date.now() - began).toBeGreaterThanOrEqual(700);expect(result).toMatchObject({ status: finishes ? "finished" : "running", exitCode: finishes ? 3 : null });expect(calls.filter(entry => entry.method === "GET")).toHaveLength(2);});+ it("bounds a stalled follow-up status read by the requested wait", async () => {+ const processId = await start();+ holdStatusAfterFirst = true;+ const began = Date.now();+ const result = await call("exec_status", { process_id: processId, wait_seconds: 1 }).done;+ expect(Date.now() - began).toBeLessThan(3_000);+ expect(result).toMatchObject({ isError: true, content: [{ text: expect.stringContaining("Nothing was changed; call exec_status again") }] });+ expect(calls.filter(entry => entry.method === "GET")).toHaveLength(2);+ server.closeAllConnections();+ });++ it("propagates cancellation during a follow-up status read", async () => {+ const processId = await start();+ holdStatusAfterFirst = true;+ 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);+ 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 () => {const processId = await start();// 6,003 UTF-16 units: the last 4,000 begin on the second half of an emoji.diff --git a/server/cloud-computer-background.ts b/server/cloud-computer-background.tsindex bf92063297..f320fb5dae 100644--- a/server/cloud-computer-background.ts+++ b/server/cloud-computer-background.ts@@ -13,6 +13,7 @@ export const STATUS_WAIT_MAX_SECONDS = 60;export const STDOUT_TAIL_CHARS = 4_000;export const STDERR_TAIL_CHARS = 2_000;const POLL_MS = 2_000;+const LAST_READ_WINDOW_MS = 250;/** Bounds what a forgotten background server can cost: Boat bills while a computer is on. */export const BACKGROUND_KEEPS_AWAKE_MS = 2 * 60 * 60_000;const MAX_TRACKED_PER_COMPUTER = 20;@@ -138,17 +139,29 @@ export async function backgroundStatus(const processId = processIdFrom(boxId, args.process_id);if (processId === null) return text(OTHER_COMPUTER, true);const until = Date.now() + Math.min(args.wait_seconds ?? 0, STATUS_WAIT_MAX_SECONDS) * 1_000;+ let firstRead = true;for (;;) {assertBoatNotDeleting(boxId);- const response = await boatFetch(cfg, `/sandboxes/${boxId}/commands/${processId}?tailBytes=${TAIL_BYTES}`, { signal });- const body: any = await response.json().catch(() => null);+ const deadline = firstRead ? null : AbortSignal.timeout(Math.max(1, until - Date.now()));+ const readSignal = deadline ? AbortSignal.any([signal, deadline]) : signal;+ let response: Response, body: any;+ try {+ response = await boatFetch(cfg, `/sandboxes/${boxId}/commands/${processId}?tailBytes=${TAIL_BYTES}`, { signal: readSignal });+ body = await response.json().catch(() => null);+ readSignal.throwIfAborted();+ } catch (error) {+ signal.throwIfAborted();+ if (deadline?.aborted) return text(STATUS_LATE, true);+ throw error;+ }if (response.status === 404) return text(UNKNOWN_PROCESS, true);if (!response.ok) return text(boatErrorMessage(response.status, "Reading the command's status", body, included(cfg)), true);if (typeof body?.running !== "boolean") return text("The cloud computer gave an unreadable answer about this command. Call exec_status again.", true);if (!body.running) untrack(boxId, processId);const remaining = until - Date.now();- if (!body.running || remaining <= 0) return describeStatus(args.process_id, body);- await delay(Math.min(POLL_MS, remaining), undefined, { signal });+ if (!body.running || remaining <= LAST_READ_WINDOW_MS) return describeStatus(args.process_id, body);+ await delay(Math.min(POLL_MS, remaining - LAST_READ_WINDOW_MS), undefined, { signal });+ firstRead = false;}}