Skip to content

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

Cloud computer: stay awake while a background command runs

milind-soni3ea32591dc93
diff --git a/apps/docs/content/docs/computers/cloud-and-vps.mdx b/apps/docs/content/docs/computers/cloud-and-vps.mdx
index 8d13ce8bd5..14f1cfb51e 100644
--- a/apps/docs/content/docs/computers/cloud-and-vps.mdx
+++ b/apps/docs/content/docs/computers/cloud-and-vps.mdx
@@ -34,10 +34,11 @@ A bot's `exec` call waits for its command to finish, so a long one (a big
download, a build, a data job) can run out of time while it keeps going on the
Boat. For those, the bot starts the command with `background: true`, which
answers at once with a process id, and follows it with `exec_status`, which shows
-whether it is still running, its exit code and the end of its output. When a
-plain `exec` runs out of time, the bot is told the command may still be running,
-so it checks instead of starting a second copy. This works with your own Boat key
-and with the cloud computers included in a Cloud plan.
+whether it is still running, its exit code and the end of its output. The Boat
+doesn't go to sleep while a background command runs, for up to two hours after it
+started. When a plain `exec` runs out of time, the bot is told the command may
+still be running, so it checks instead of starting a second copy. This works with
+your own Boat key and with the cloud computers included in a Cloud plan.
## Bring your own VPS
diff --git a/server/boat-auto-sleep.test.ts b/server/boat-auto-sleep.test.ts
index ab0697e877..840989bba8 100644
--- a/server/boat-auto-sleep.test.ts
+++ b/server/boat-auto-sleep.test.ts
@@ -17,6 +17,8 @@ let base = "";
let state = "ready";
/** Status the stub answers a stop with; a 2xx archives the computer. */
let stopStatus = 200;
+/** Whether the background command the stub started (process 7) still runs. */
+let jobRunning = false;
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"));
@@ -48,7 +50,9 @@ beforeAll(async () => {
const row = { id: boxId, name: machineName, state };
if (rest === root) return send(200, { ok: true, [many]: [row], pageInfo: { nextCursor: null } });
if (rest === `${root}/${boxId}` && req.method === "GET") return send(200, { ok: true, [one]: row });
+ if (rest === `${root}/${boxId}/commands` && body.detached === true) { jobRunning = true; return send(200, { ok: true, processId: 7 }); }
if (rest === `${root}/${boxId}/commands`) return send(200, { exitCode: 0, stdout: "", stderr: "" });
+ if (rest === `${root}/${boxId}/commands/7`) return send(200, { ok: true, processId: 7, status: jobRunning ? "running" : "exited", running: jobRunning, exitCode: jobRunning ? null : 0, stdout: "", stderr: "" });
if (rest === `${root}/${boxId}/stop`) {
if (stopStatus < 300) state = "archived";
return send(stopStatus, stopStatus < 300 ? { ok: true } : { ok: false, message: "Cloud computers are not available right now." });
@@ -89,6 +93,7 @@ describe("a cloud computer goes to sleep after its idle window", () => {
requests.length = 0;
state = "ready";
stopStatus = 200;
+ jobRunning = false;
logs = [];
busy = false;
vi.stubEnv("BOX_TOKEN", undefined);
@@ -147,6 +152,23 @@ describe("a cloud computer goes to sleep after its idle window", () => {
expect(requests.map(request => request.method)).toEqual(["GET"]);
});
+ it.each([
+ ["a person's own Boat key", { box: { token: OWN } }, "/boat/api/v1/sandboxes"],
+ ["the cloud computer a Cloud plan includes", {}, "/relay/api/box/v1/boxes"],
+ ])("with %s, stays on while a background command runs and sleeps once it has ended", async (_label, cfg, root) => {
+ await powerFor(cfg);
+ const background = await import("./cloud-computer-background.ts");
+ await background.startInBackground(cfg, boxId, "python3 job.py", new AbortController().signal);
+ power.used(botId);
+ await new Promise(resolve => setTimeout(resolve, 3_500));
+ expect(stops()).toEqual([]);
+ expect(requests.filter(request => request.path === `${root}/${boxId}/commands/7`).length).toBeGreaterThanOrEqual(2);
+ expect(power.awake()).toBe(true);
+ jobRunning = false;
+ await waitFor(() => stops().length === 1);
+ expect(stops()[0]?.path).toBe(`${root}/${boxId}/stop`);
+ });
+
it("a stop the relay refuses is logged and retried after a longer wait each time", async () => {
stopStatus = 503;
await powerFor({});
diff --git a/server/cloud-computer-background.test.ts b/server/cloud-computer-background.test.ts
index fa3c1d3c7e..c828f070e0 100644
--- a/server/cloud-computer-background.test.ts
+++ b/server/cloud-computer-background.test.ts
@@ -1,6 +1,6 @@
// One loopback stub plays Boat (/boat/api/v1, sandboxes) and the Admin's included-Boat relay (/relay/api/box/v1, boxes).
import { createServer, type Server } from "node:http";
-import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { AppConfig } from "./config.ts";
const BOX = "bx_23456789", OTHER_BOX = "bx_3456789a";
@@ -17,6 +17,7 @@ let nextProcessId = 41;
let hold = 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;
beforeAll(async () => {
server = createServer(async (req, res) => {
@@ -38,6 +39,7 @@ beforeAll(async () => {
}
if (req.method === "GET" && pid) {
if (hold) return;
+ 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." });
const running = process.polls++ < process.runningFor;
@@ -56,7 +58,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;
+ calls.length = 0; processes.clear(); hold = false; startReply = undefined; statusReply = undefined;
syncReply = { exitCode: 0, stdout: "done", stderr: "" };
});
@@ -201,6 +203,50 @@ describe.each([
expect(calls.filter(entry => entry.method === "POST")).toHaveLength(2);
});
+ describe("keeping the computer awake", () => {
+ /** Commands earlier tests left behind are gone from the fake, so this first check forgets them. */
+ beforeEach(async () => {
+ await background.backgroundCommandRunning(cfg, BOX);
+ await background.backgroundCommandRunning(cfg, OTHER_BOX);
+ calls.length = 0;
+ });
+ afterEach(() => { vi.restoreAllMocks(); });
+
+ it("while a background command runs, and not once it has ended", async () => {
+ const processId = await start();
+ processes.get(`${BOX}:${processId.split("-")[1]}`)!.runningFor = 2;
+ expect(await background.backgroundCommandRunning(cfg, BOX)).toBe(true);
+ expect(await background.backgroundCommandRunning(cfg, BOX)).toBe(true);
+ expect(await background.backgroundCommandRunning(cfg, OTHER_BOX)).toBe(false);
+ expect(await background.backgroundCommandRunning(cfg, BOX)).toBe(false);
+ const reads = calls.filter(entry => entry.method === "GET");
+ expect(reads.map(entry => [entry.path, entry.query, entry.authorization])).toEqual(Array(3).fill([`${root}/${BOX}/commands/${processId.split("-")[1]}`, "?tailBytes=1", authorization]));
+ calls.length = 0;
+ expect(await background.backgroundCommandRunning(cfg, BOX)).toBe(false);
+ expect(calls).toEqual([]);
+ });
+
+ it("not after exec_status saw the command end", async () => {
+ const processId = await start();
+ processes.get(`${BOX}:${processId.split("-")[1]}`)!.runningFor = 0;
+ expect(json(await call("exec_status", { process_id: processId }).done)).toMatchObject({ status: "finished" });
+ calls.length = 0;
+ expect(await background.backgroundCommandRunning(cfg, BOX)).toBe(false);
+ expect(calls).toEqual([]);
+ });
+
+ it("while the computer cannot say, but never past the cap", async () => {
+ await start();
+ statusReply = { status: 503, body: { ok: false, message: "unavailable" } };
+ expect(await background.backgroundCommandRunning(cfg, BOX)).toBe(true);
+ const now = Date.now();
+ vi.spyOn(Date, "now").mockReturnValue(now + background.BACKGROUND_KEEPS_AWAKE_MS);
+ calls.length = 0;
+ expect(await background.backgroundCommandRunning(cfg, BOX)).toBe(false);
+ expect(calls).toEqual([]);
+ });
+ });
+
it("tells the bot a plain exec that ran out of time may still be running, and not to repeat it blindly", async () => {
hold = true;
const late = await call("exec", { command: "sleep 600" }, BOX, 400).done;
diff --git a/server/cloud-computer-background.ts b/server/cloud-computer-background.ts
index ba02f25906..8933561df2 100644
--- a/server/cloud-computer-background.ts
+++ b/server/cloud-computer-background.ts
@@ -13,6 +13,10 @@ 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;
+/** 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;
+const AWAKE_CHECK_MS = 20_000;
const MAX_UTF8_BYTES_PER_UTF16_UNIT = 3;
const TAIL_BYTES = MAX_UTF8_BYTES_PER_UTF16_UNIT * STDOUT_TAIL_CHARS;
@@ -60,6 +64,41 @@ function ranInForeground(body: any): CloudComputerResult {
}), body.exitCode !== 0);
}
+/** Process ids started on each computer, by box id, with when they started: its idle sleep waits for them. */
+const started = new Map<string, Map<number, number>>();
+
+function track(boxId: string, processId: number): void {
+ const mine = started.get(boxId) ?? new Map<number, number>();
+ mine.set(processId, Date.now());
+ while (mine.size > MAX_TRACKED_PER_COMPUTER) mine.delete(mine.keys().next().value!);
+ started.set(boxId, mine);
+}
+
+function untrack(boxId: string, processId: number): void {
+ const mine = started.get(boxId);
+ mine?.delete(processId);
+ if (mine?.size === 0) started.delete(boxId);
+}
+
+/** An answer that does not say it ended counts as running; BACKGROUND_KEEPS_AWAKE_MS still ends the wait. */
+async function mayStillRun(cfg: AppConfig, boxId: string, processId: number): Promise<boolean> {
+ try {
+ const response = await boatFetch(cfg, `/sandboxes/${boxId}/commands/${processId}?tailBytes=1`, { signal: AbortSignal.timeout(AWAKE_CHECK_MS) });
+ const body: any = await response.json().catch(() => null);
+ return response.status !== 404 && !(response.ok && body?.running === false);
+ } catch {
+ return true;
+ }
+}
+
+export async function backgroundCommandRunning(cfg: AppConfig, boxId: string): Promise<boolean> {
+ for (const [processId, at] of started.get(boxId) ?? []) {
+ if (Date.now() - at < BACKGROUND_KEEPS_AWAKE_MS && await mayStillRun(cfg, boxId, processId)) return true;
+ untrack(boxId, processId);
+ }
+ return false;
+}
+
export async function startInBackground(cfg: AppConfig, boxId: string, command: string, signal: AbortSignal): Promise<CloudComputerResult> {
assertBoatNotDeleting(boxId);
const response = await boatFetch(cfg, `/sandboxes/${boxId}/commands`, {
@@ -73,6 +112,7 @@ export async function startInBackground(cfg: AppConfig, boxId: string, command:
const processId = body?.processId;
if (Number.isInteger(body?.exitCode) && processId === undefined) return ranInForeground(body);
if (!Number.isSafeInteger(processId) || processId < 1) return text(`The cloud computer did not say which process it started. The command may have started. ${CHECK_BEFORE_RERUN}.`, true);
+ track(boxId, processId);
return text(JSON.stringify({ processId: processIdOn(boxId, processId), status: "running", next: "It keeps running after this call. Follow it with exec_status." }));
}
@@ -105,6 +145,7 @@ export async function backgroundStatus(
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);
if (!body.running || Date.now() + POLL_MS > until) return describeStatus(args.process_id, body);
await delay(POLL_MS, undefined, { signal });
}
diff --git a/server/cloud-computer-tools.ts b/server/cloud-computer-tools.ts
index 97e7fd18bf..93a2a9508b 100644
--- a/server/cloud-computer-tools.ts
+++ b/server/cloud-computer-tools.ts
@@ -23,7 +23,7 @@ export const CLOUD_COMPUTER_TOOLS = [
tool("key_press", "Press an X11 key or shortcut.", { key: { type: "string", pattern: "^[A-Za-z0-9_+]+$", minLength: 1, maxLength: 100 } }, ["key"]),
tool("scroll", "Scroll at a point on the cloud desktop.", { x: coordinate, y: coordinate, direction: { type: "string", enum: ["up", "down", "left", "right"] }, amount: { type: "integer", minimum: 1, maximum: 30 } }, ["x", "y", "direction"]),
tool("open_url", "Request opening an HTTP or HTTPS URL in the cloud desktop browser; inspect the screen to confirm it loaded.", { url: { type: "string", pattern: "^https?://", maxLength: 2000 } }, ["url"]),
- tool("exec", "Run a shell command on the assigned cloud computer and wait for its result. For a command that may run long (downloads, installs, builds, data jobs), set background: true: it starts the command and answers at once with a process_id to follow with exec_status.", {
+ tool("exec", "Run a shell command on the assigned cloud computer and wait for its result. For a command that may run long (downloads, installs, builds, data jobs), set background: true: it starts the command and answers at once with a process_id to follow with exec_status, and the computer stays on for it for up to two hours.", {
command: { type: "string", minLength: 1, maxLength: 4000 },
background: { type: "boolean", description: "Start the command and answer at once with a process_id, instead of waiting for it to finish." },
}, ["command"]),
diff --git a/server/host/cloud-computer-power.ts b/server/host/cloud-computer-power.ts
index 2ef969546a..c89bee8501 100644
--- a/server/host/cloud-computer-power.ts
+++ b/server/host/cloud-computer-power.ts
@@ -4,6 +4,7 @@
import * as boat from "../boat.ts";
import { boatCreateRecoverySnapshot } from "../boat-create-idempotency.ts";
import { hasPendingBoatDeletionForBot } from "../boat-delete-journal.ts";
+import { backgroundCommandRunning } from "../cloud-computer-background.ts";
import { ComputerIdleTimer } from "../computer-idle.ts";
import type { AppConfig } from "../config.ts";
import { redactSecretsInText } from "../redact.ts";
@@ -66,6 +67,8 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {
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";
+ if (typeof machine?.id === "string" && await backgroundCommandRunning(cfg, machine.id)) return "busy";
+ if (closed) return;
let release: () => void;
try {
release = deps.claim(owner);