Skip to content

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

Keep the last observed background status

WAI LOK HObaa5ea63d75a
diff --git a/server/cloud-computer-background.test.ts b/server/cloud-computer-background.test.ts
index 628057ef73..f32914c2d5 100644
--- a/server/cloud-computer-background.test.ts
+++ b/server/cloud-computer-background.test.ts
@@ -58,6 +58,68 @@ beforeAll(async () => {
background = await import("./cloud-computer-background.ts");
journal = await import("./boat-delete-journal.ts");
});
+
+describe("background status deadlines", () => {
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });
+
+ it("reports an initial read timeout without inventing a status", async () => {
+ vi.useFakeTimers();
+ const clock = {
+ now: () => Date.now(),
+ sleep: (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)),
+ timeout: (ms: number) => {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), ms);
+ return controller.signal;
+ },
+ };
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(init.signal!.reason), { once: true });
+ }));
+ const pending = background.backgroundStatus({ box: { token: OWN_KEY } } as AppConfig, BOX,
+ { process_id: background.processIdOn(BOX, 41), wait_seconds: 1 }, new AbortController().signal, clock);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(await pending).toMatchObject({ isError: true, content: [{ text: expect.stringContaining("call exec_status again") }] });
+ });
+
+ it.each(["finished", "running", "timeout"] as const)("checks a short wait on a controlled clock: %s", async outcome => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
+ const clock = {
+ now: () => Date.now(),
+ sleep: (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)),
+ timeout: (ms: number) => {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), ms);
+ return controller.signal;
+ },
+ };
+ const fetchStatus = vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => {
+ if (fetchStatus.mock.calls.length === 1) return Response.json({ running: true, stdout: "partial", stderr: "" });
+ if (outcome !== "timeout") return Response.json({ running: outcome === "running", exitCode: 3, stdout: "final", stderr: "" });
+ return new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(init.signal!.reason), { once: true });
+ });
+ });
+ const processId = background.processIdOn(BOX, 41);
+ const pending = background.backgroundStatus({ box: { token: OWN_KEY } } as AppConfig, BOX,
+ { process_id: processId, wait_seconds: 1 }, new AbortController().signal, clock);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(fetchStatus).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(749);
+ expect(fetchStatus).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(fetchStatus).toHaveBeenCalledTimes(2);
+ if (outcome === "timeout") await vi.advanceTimersByTimeAsync(250);
+ const result = json(await pending);
+ if (outcome === "timeout") {
+ expect(result).toMatchObject({ status: "running", exitCode: null, stdout: "partial", observedAt: "2026-01-01T00:00:00.000Z", note: expect.stringContaining("may have changed") });
+ } else {
+ expect(result).toMatchObject({ status: outcome, exitCode: outcome === "finished" ? 3 : null, stdout: "final" });
+ expect(result.observedAt).toBeUndefined();
+ }
+ });
+});
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;
@@ -128,9 +190,7 @@ describe.each([
it("waits for the command to finish when asked, polling the computer rather than the bot", async () => {
const processId = await start();
Object.assign(processes.get(`${BOX}:${processId.split("-")[1]}`)!, { runningFor: 2, stdout: "loaded\n" });
- const began = Date.now();
expect(json(await call("exec_status", { process_id: processId, wait_seconds: 30 }).done)).toMatchObject({ status: "finished", exitCode: 0, stdout: "loaded\n" });
- expect(Date.now() - began).toBeGreaterThanOrEqual(3_500);
expect(calls.filter(entry => entry.method === "GET")).toHaveLength(3);
});
@@ -138,26 +198,15 @@ describe.each([
const processId = await start();
processes.get(`${BOX}:${processId.split("-")[1]}`)!.runningFor = 100;
expect(json(await call("exec_status", { process_id: processId, wait_seconds: 3 }).done)).toMatchObject({ status: "running", exitCode: null });
- expect(calls.filter(entry => entry.method === "GET")).toHaveLength(3);
- });
-
- it.each([true, false])("honors a one-second wait and reports whether the command finished: %s", async (finishes) => {
- const processId = await start();
- 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(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();
+ processes.get(`${BOX}:${processId.split("-")[1]}`)!.stdout = "partial output";
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") }] });
+ const result = await call("exec_status", { process_id: processId, wait_seconds: 3 }).done;
+ expect(result.isError).not.toBe(true);
+ expect(json(result)).toMatchObject({ status: "running", stdout: "partial output", observedAt: expect.any(String), note: expect.stringContaining("may have changed") });
expect(calls.filter(entry => entry.method === "GET")).toHaveLength(2);
server.closeAllConnections();
});
@@ -165,9 +214,7 @@ describe.each([
it("bounds a stalled initial status read by the requested wait", async () => {
const processId = await start();
hold = 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") }] });
server.closeAllConnections();
});
diff --git a/server/cloud-computer-background.ts b/server/cloud-computer-background.ts
index 49023b4284..f4d2d91636 100644
--- a/server/cloud-computer-background.ts
+++ b/server/cloud-computer-background.ts
@@ -32,6 +32,18 @@ const UNKNOWN_PROCESS = "This cloud computer has no background command with that
+ "Look at the files the command writes to see how far it got.";
const LOST = "The cloud computer restarted or lost track of this command, so its exit code may be unknown. Look at the files it writes to see how far it got.";
const CUT = "Only the end of the output is shown. Write long output to a file and read the part you need with exec.";
+const STALE = "The follow-up status read timed out. This is the last observed status; it may have changed. Call exec_status again.";
+
+type StatusClock = {
+ now: () => number;
+ sleep: (ms: number, signal: AbortSignal) => Promise<void>;
+ timeout: (ms: number) => AbortSignal;
+};
+const statusClock: StatusClock = {
+ now: Date.now,
+ sleep: (ms, signal) => delay(ms, undefined, { signal }),
+ timeout: ms => AbortSignal.timeout(ms),
+};
const text = (value: string, isError = false): CloudComputerResult => ({ ...(isError ? { isError } : {}), content: [{ type: "text", text: value }] });
const included = (cfg: AppConfig) => boatAccount(cfg)?.included === true;
@@ -117,7 +129,7 @@ export async function startInBackground(cfg: AppConfig, boxId: string, command:
return text(JSON.stringify({ processId: processIdOn(boxId, processId), status: "running", next: "It keeps running after this call, but its completion will not automatically resume this turn or notify a delegator. If its result is needed for this task, use exec_status with wait_seconds in this turn until it finishes, then check its exit code and output. If you cannot finish checking in this turn, report it as unfinished with the process_id; do not start another copy blindly." }));
}
-function describeStatus(processId: string, body: any): CloudComputerResult {
+function describeStatus(processId: string, body: any, observedAt?: number): CloudComputerResult {
const stdout = tail(body.stdout, STDOUT_TAIL_CHARS), stderr = tail(body.stderr, STDERR_TAIL_CHARS);
const status = body.running ? "running" : body.status === "lost" ? "lost" : "finished";
return text(JSON.stringify({
@@ -127,6 +139,7 @@ function describeStatus(processId: string, body: any): CloudComputerResult {
stdout: stdout.text, stderr: stderr.text,
...(stdout.cut || stderr.cut || body.stdoutTruncated === true || body.stderrTruncated === true ? { outputCut: CUT } : {}),
...(status === "lost" ? { note: LOST } : {}),
+ ...(observedAt === undefined ? {} : { observedAt: new Date(observedAt).toISOString(), note: STALE }),
}));
}
@@ -135,14 +148,16 @@ export async function backgroundStatus(
boxId: string,
args: { process_id: string; wait_seconds?: number },
signal: AbortSignal,
+ clock: StatusClock = statusClock,
): Promise<CloudComputerResult> {
const processId = processIdFrom(boxId, args.process_id);
if (processId === null) return text(OTHER_COMPUTER, true);
const waitMs = Math.min(args.wait_seconds ?? 0, STATUS_WAIT_MAX_SECONDS) * 1_000;
- const until = Date.now() + waitMs;
+ const until = clock.now() + waitMs;
+ let last: { body: any; observedAt: number } | undefined;
for (;;) {
assertBoatNotDeleting(boxId);
- const deadline = waitMs ? AbortSignal.timeout(Math.max(1, until - Date.now())) : null;
+ const deadline = waitMs ? clock.timeout(Math.max(1, until - clock.now())) : null;
const readSignal = deadline ? AbortSignal.any([signal, deadline]) : signal;
let response: Response, body: any;
try {
@@ -151,16 +166,18 @@ export async function backgroundStatus(
readSignal.throwIfAborted();
} catch (error) {
signal.throwIfAborted();
- if (deadline?.aborted) return text(STATUS_LATE, true);
+ if (deadline?.aborted) return last ? describeStatus(args.process_id, last.body, last.observedAt) : 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();
+ const observedAt = clock.now();
+ last = { body, observedAt };
+ const remaining = until - observedAt;
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 });
+ await clock.sleep(Math.min(POLL_MS, remaining - LAST_READ_WINDOW_MS), signal);
}
}