Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud computers: long commands run in the background past the provider's 30-second stop; ready means it answered; scheduled runs wait for their computer (#6001)
Milind Soni0f7abc72bef5
diff --git a/server/boat-auto-sleep.test.ts b/server/boat-auto-sleep.test.tsindex 840989bba8..383671cbf5 100644--- a/server/boat-auto-sleep.test.ts+++ b/server/boat-auto-sleep.test.ts@@ -69,6 +69,9 @@ afterAll(async () => {});describe("a cloud computer goes to sleep after its idle window", () => {+ /** One stop was sent and the sleep it belongs to has finished: a test that ended at the stop itself left that sleep's+ * log line to land in the next test's log. */+ const asleep = () => waitFor(() => stops().length === 1 && !power.awake());let power: ReturnType<typeof import("./host/cloud-computer-power.ts").createCloudComputerPower>;let logs: string[];let busy: boolean;@@ -113,7 +116,7 @@ describe("a cloud computer goes to sleep after its idle window", () => {power.used(botId);await new Promise(resolve => setTimeout(resolve, 600));expect(stops()).toEqual([]);- await waitFor(() => stops().length === 1);+ await asleep();expect(stops()[0]).toMatchObject({ path: `/boat/api/v1/sandboxes/${boxId}/stop`, auth: `Bearer ${OWN}` });const quiesce = requests.findIndex(request => request.path.endsWith("/commands"));expect(requests[quiesce]?.command).toContain("kill -TERM");@@ -125,7 +128,7 @@ describe("a cloud computer goes to sleep after its idle window", () => {it("with the cloud computer a Cloud plan includes, stops it through the Admin relay only", async () => {await powerFor({});power.used(botId);- await waitFor(() => stops().length === 1);+ await asleep();expect(stops()[0]).toMatchObject({ path: `/relay/api/box/v1/boxes/${boxId}/stop`, auth: `Bearer ${INCLUDED}` });expect(requests.every(request => request.path.startsWith("/relay/"))).toBe(true);});@@ -134,7 +137,7 @@ describe("a cloud computer goes to sleep after its idle window", () => {await powerFor({});await power.armRunning();expect(requests.map(request => `${request.method} ${request.path}`)).toEqual(["GET /relay/api/box/v1/boxes"]);- await waitFor(() => stops().length === 1);+ await asleep();expect(stops()[0]?.path).toBe(`/relay/api/box/v1/boxes/${boxId}/stop`);});@@ -165,7 +168,7 @@ describe("a cloud computer goes to sleep after its idle window", () => {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);+ await asleep();expect(stops()[0]?.path).toBe(`${root}/${boxId}/stop`);});diff --git a/server/boat-command.test.ts b/server/boat-command.test.tsnew file mode 100644index 0000000000..c885e4657b--- /dev/null+++ b/server/boat-command.test.ts@@ -0,0 +1,235 @@+// A loopback Boat with the provider's two real limits, scaled down a hundred times: a synchronous command is stopped at+// 30 s and answered 200 with `timedOut`, exit code 143 and SIGTERM; and the gateway answers 502 after 40 s when the+// computer is too slow to answer at all. No network, no real computer.+import { createServer, type Server, type ServerResponse } from "node:http";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import type { AppConfig } from "./config.ts";++/** The provider's 30 s, as 300 ms, and its gateway's 40 s, as 400 ms. */+const WALL_MS = 300;+const GATEWAY_MS = 400;+const BOX = "bx_23456789";+const cfg = { box: { token: "synthetic-box-key" } } as AppConfig;++type Process = { id: number; command: string; startedAt: number; endsAt: number; exitCode: number; stdout: string };+let server: Server;+let processes: Process[] = [];+let requests: Array<{ method: string; path: string; detached: boolean; command?: string; tail?: number }> = [];+/** Status reads the gateway fails before it answers again; `forgetsDetached`: a relay that drops the flag; `gone`: the computer restarted. */+let failReads = 0;+let forgetsDetached = false;+let gone = false;+let truncates = false;+/** The computer is too slow to answer, so the gateway gives up on every synchronous command. */+let tooSlow = false;+/** The status read answers 200 with `known: false`, as the provider does for a process it has no record of. */+let unknownProcess = false;++/** `sleep <ms>; exit <code>` in the fake's own words: `ms:<n>` and `exit:<n>` anywhere in the command. */+const spec = (command: string) => ({ ms: Number(/ms:(\d+)/.exec(command)?.[1] ?? 5), exitCode: Number(/exit:(\d+)/.exec(command)?.[1] ?? 0) });+const running = (process: Process) => Date.now() < process.endsAt;+const send = (res: ServerResponse, status: number, body: unknown) => { res.writeHead(status, { "content-type": "application/json", connection: "close" }); res.end(JSON.stringify(body)); };++beforeAll(async () => {+ server = createServer(async (req, res) => {+ let raw = "";+ for await (const part of req) raw += part;+ const url = new URL(req.url ?? "/", "http://boat.test");+ const body = raw ? JSON.parse(raw) : {};+ requests.push({ method: req.method ?? "GET", path: url.pathname, detached: body.detached === true, ...(typeof body.command === "string" ? { command: body.command } : {}), ...(url.searchParams.has("tailBytes") ? { tail: Number(url.searchParams.get("tailBytes")) } : {}) });+ const read = /\/commands\/(\d+)$/.exec(url.pathname);+ if (read && req.method === "GET") {+ if (failReads > 0) { failReads--; return send(res, 502, { ok: false }); }+ const found = processes.find((process) => process.id === Number(read[1]));+ if (!found || gone) return send(res, 404, { ok: false, code: "not_found" });+ if (unknownProcess) return send(res, 200, { known: false, running: false, status: "unknown", exitCode: null, stdout: "", stderr: "" });+ const live = running(found);+ return send(res, 200, { running: live, status: live ? "running" : "exited", exitCode: live ? null : found.exitCode, stdout: live ? "partial" : found.stdout, stderr: "", ...(truncates ? { stdoutTruncated: true } : {}) });+ }+ if (!url.pathname.endsWith("/commands") || req.method !== "POST") return send(res, 404, { ok: false });+ const { ms, exitCode } = spec(String(body.command));+ const started: Process = { id: processes.length + 1, command: String(body.command), startedAt: Date.now(), endsAt: Date.now() + ms, exitCode, stdout: `ran ${ms}` };+ processes.push(started);+ if (body.detached === true && !forgetsDetached) return send(res, 200, { processId: started.id });+ if (tooSlow) { started.endsAt = started.startedAt; return void setTimeout(() => send(res, 502, { ok: false, code: "upstream_unavailable" }), GATEWAY_MS); }+ // Synchronous: the answer waits for the command, and at the limit the provider stops the process and says so.+ if (ms > WALL_MS) {+ started.endsAt = started.startedAt + WALL_MS;+ return void setTimeout(() => send(res, 200, { exitCode: 143, signal: "SIGTERM", timedOut: true, stdout: "", stderr: "" }), WALL_MS);+ }+ setTimeout(() => send(res, 200, { exitCode, stdout: started.stdout, stderr: "" }), ms);+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ vi.stubEnv("OMB_BOAT_API", `http://127.0.0.1:${(server.address() as { port: number }).port}`);+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", undefined);+});+afterAll(async () => { vi.unstubAllEnvs(); server.closeAllConnections(); await new Promise<void>((resolve) => server.close(() => resolve())); });++let boat: typeof import("./boat.ts");+let command: typeof import("./boat-command.ts");+let health: typeof import("./boat-health.ts");+beforeEach(async () => {+ processes = []; requests = []; failReads = 0; forgetsDetached = false; gone = false; truncates = false; tooSlow = false; unknownProcess = false;+ vi.resetModules();+ boat = await import("./boat.ts");+ command = await import("./boat-command.ts");+ health = await import("./boat-health.ts");+});+const posts = () => requests.filter((request) => request.method === "POST");+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++describe("the provider's limits on a synchronous command", () => {+ it("stops a command at 30 s and says so: the result is marked as the provider's limit, not the command's own failure", async () => {+ const out = await boat.runCommand(cfg, BOX, `build ms:${WALL_MS * 2}`, { timeoutMs: command.COMMAND_WALL.syncSafeMs });+ expect(out).toMatchObject({ ok: false, exitCode: 143, timedOut: true, providerLimit: true });+ expect(posts()).toEqual([expect.objectContaining({ detached: false })]);+ await sleep(20);+ expect(running(processes[0]!)).toBe(false);+ });++ it("is never reached by a command sent the synchronous way: its caller gives up five seconds earlier", () => {+ expect(command.COMMAND_WALL.syncSafeMs).toBeLessThanOrEqual(25_000);+ });++ it("a gateway that gives up on a slow computer does not make it count as not responding: only a short probe that fails does", async () => {+ const silent: string[] = [];+ health.boatHealth.onNotResponding((boxId) => silent.push(boxId));+ tooSlow = true;+ for (let builds = 0; builds < 3; builds++) {+ expect(await boat.runCommand(cfg, BOX, "ls ms:5", { timeoutMs: command.COMMAND_WALL.syncSafeMs })).toMatchObject({ ok: false, exitCode: null, unanswered: true });+ }+ tooSlow = false;+ await sleep(150);+ expect(processes.some((process) => process.command === "true")).toBe(true);+ expect(silent).toEqual([]);+ expect(health.boatHealth.notRespondingSince(BOX)).toBeNull();+ });+});++describe("the commands a bot's exec calls left running", () => {+ const start = async (ms: number) => {+ const response = await fetch(`${process.env.OMB_BOAT_API}/sandboxes/${BOX}/commands`, { method: "POST", body: JSON.stringify({ command: `serve ms:${ms}`, detached: true }) });+ return (await response.json() as { processId: number }).processId;+ };++ it("are counted while they run, and forgotten once they end", async () => {+ const server1 = await start(60_000), server2 = await start(60_000);+ command.noteLeftRunning(BOX, server1);+ command.noteLeftRunning(BOX, server2);+ expect(await command.commandsLeftRunning(cfg, BOX)).toBe(2);+ processes[0]!.endsAt = Date.now() - 1;+ expect(await command.commandsLeftRunning(cfg, BOX)).toBe(1);+ processes[0]!.endsAt = Date.now() + 60_000;+ expect(await command.commandsLeftRunning(cfg, BOX)).toBe(1);+ });++ it("are not counted when their status cannot be read, so a failing gateway never holds a bot at the limit", async () => {+ command.noteLeftRunning(BOX, await start(60_000));+ failReads = 1;+ expect(await command.commandsLeftRunning(cfg, BOX)).toBe(0);+ expect(await command.commandsLeftRunning(cfg, BOX)).toBe(1);+ });++ it("stop counting after two hours, the same time they may keep the computer awake", async () => {+ command.noteLeftRunning(BOX, await start(10 * 60 * 60_000));+ const now = Date.now();+ const clock = vi.spyOn(Date, "now").mockReturnValue(now + command.COMMAND_WALL.leftRunningMs);+ expect(await command.commandsLeftRunning(cfg, BOX)).toBe(0);+ clock.mockRestore();+ expect(await command.commandsLeftRunning(cfg, BOX)).toBe(0);+ });+});++describe("a command that may run long", () => {+ it("runs to its end however far past the provider's limit, once, with its own exit code and output", async () => {+ const out = await boat.runCommand(cfg, BOX, `build ms:${WALL_MS * 3} exit:2`);+ expect(out).toEqual({ ok: false, exitCode: 2, stdout: `ran ${WALL_MS * 3}`, stderr: "" });+ expect(requests.filter((request) => request.method === "GET" && request.tail === command.COMMAND_WALL.tailBytes)).toHaveLength(1);+ expect(posts()).toEqual([expect.objectContaining({ detached: true })]);+ expect(processes).toHaveLength(1);+ expect(command.trackedProcesses(BOX).size).toBe(0);+ });++ it("keeps a quick command quick: about a tenth of a second and a few status reads on top of its own time", async () => {+ const took: number[] = [];+ for (let run = 0; run < 5; run++) {+ const before = Date.now();+ expect((await boat.runCommand(cfg, BOX, "pwd ms:200")).ok).toBe(true);+ took.push(Date.now() - before - 200);+ }+ const typical = [...took].sort((a, b) => a - b)[2]!;+ expect(typical).toBeLessThan(400);+ expect(requests.filter((request) => request.method === "GET").length).toBeLessThanOrEqual(5 * 4);+ });++ it("hands back a command still running when the caller's time is up: timed out, with its process id, not stopped", async () => {+ const out = await boat.runCommand(cfg, BOX, "build ms:60000", { timeoutMs: command.COMMAND_WALL.syncSafeMs + 1 });+ expect(out).toMatchObject({ ok: false, exitCode: null, timedOut: true, processId: 1, stdout: "partial" });+ expect(running(processes[0]!)).toBe(true);+ expect(posts()).toHaveLength(1);+ expect(command.trackedProcesses(BOX).has(1)).toBe(true);+ // Whoever only runs a helper command (the console, a meeting) adds nothing to a bot's count.+ expect(await command.commandsLeftRunning(cfg, BOX)).toBe(0);+ }, 45_000);++ it("reads a small tail while the command runs and the whole tail once, when it has ended", async () => {+ await boat.runCommand(cfg, BOX, "build ms:700");+ const tails = requests.filter((request) => request.method === "GET").map((request) => request.tail);+ expect(tails.length).toBeGreaterThanOrEqual(3);+ expect(tails.at(-1)).toBe(command.COMMAND_WALL.tailBytes);+ expect(tails.slice(0, -1).every((tail) => tail === command.COMMAND_WALL.runningTailBytes)).toBe(true);+ expect(command.COMMAND_WALL.runningTailBytes).toBeLessThanOrEqual(12_000);+ });++ it("reads the status again when the gateway fails a read, without starting the command again", async () => {+ failReads = 3;+ const out = await boat.runCommand(cfg, BOX, "build ms:50");+ expect(out).toMatchObject({ ok: true, exitCode: 0 });+ expect(processes).toHaveLength(1);+ });++ it("says the command was lost when the computer no longer knows it", async () => {+ const pending = boat.runCommand(cfg, BOX, "build ms:2000");+ await sleep(100);+ gone = true;+ await expect(pending).resolves.toMatchObject({ ok: false, exitCode: null, lost: true, stderr: command.COMMAND_LOST });+ });++ it("says when only the end of the output came back", async () => {+ truncates = true;+ await expect(boat.runCommand(cfg, BOX, "cat ms:10")).resolves.toMatchObject({ ok: true, outputCut: true });+ });++ it("takes the result as it comes from a relay that does not forward the detached flag, the provider's limit included", async () => {+ forgetsDetached = true;+ await expect(boat.runCommand(cfg, BOX, "pwd ms:20")).resolves.toEqual({ ok: true, exitCode: 0, stdout: "ran 20", stderr: "" });+ expect(requests.filter((request) => request.method === "GET")).toHaveLength(0);+ await expect(boat.runCommand(cfg, BOX, `build ms:${WALL_MS * 2}`)).resolves.toMatchObject({ ok: false, exitCode: 143, timedOut: true, providerLimit: true });+ });++ it("takes a process the provider says it does not know as lost", async () => {+ const pending = boat.runCommand(cfg, BOX, "build ms:2000");+ await sleep(100);+ unknownProcess = true;+ await expect(pending).resolves.toMatchObject({ ok: false, lost: true });+ });++ it("stops following, and throws, when the caller gives up", async () => {+ const abort = new AbortController();+ const pending = boat.runCommand(cfg, BOX, "build ms:5000", { signal: abort.signal });+ const rejected = expect(pending).rejects.toThrow();+ await sleep(100);+ expect(command.trackedProcesses(BOX).size).toBe(1);+ abort.abort();+ await rejected;+ // Nobody follows it any more, so it no longer keeps the computer awake.+ expect(command.trackedProcesses(BOX).size).toBe(0);+ });++ it("is sent the direct way when its caller gives it no more than the sync-safe time, and the probe always is", async () => {+ await boat.runCommand(cfg, BOX, "click ms:5", { timeoutMs: command.COMMAND_WALL.syncSafeMs });+ await boat.probeBoat(cfg, BOX);+ expect(posts().filter((request) => request.command === "click ms:5" || request.command === "true").map((request) => request.detached)).toEqual([false, false]);+ });+});diff --git a/server/boat-command.ts b/server/boat-command.tsnew file mode 100644index 0000000000..7c66ab50f5--- /dev/null+++ b/server/boat-command.ts@@ -0,0 +1,197 @@+// Boat stops a synchronous POST /sandboxes/{id}/commands after 30 s: it answers 200 with `timedOut: true`,+// `exitCode: 143` and `signal: "SIGTERM"`, and the process is gone (checked on a real sandbox 2026-11-15). Apart from+// that, its gateway answers 502 after about 40 s when a sandbox is too slow to answer at all. So a command that may run+// that long is never sent that way: it is started `detached`, which answers at once with a processId, and followed with+// GET /sandboxes/{id}/commands/{id} (`running`, `status`, `exitCode`, `stdout`, `stderr`, `stdoutTruncated`,+// `stderrTruncated`, `known`) until it ends or the caller's own time is up. The same check found a detached command to+// run with the same folder, user, HOME, shell and PATH as a synchronous one, and no tty either way. A relay that does+// not forward `detached` runs the command synchronously and answers with its result, which is taken as it comes.+// Unverified: how many bytes of output `tailBytes` may ask for. A longer output arrives cut, and says so.+import { setTimeout as delay } from "node:timers/promises";++import { assertBoatNotDeleting, boatFetch, probeBoat } from "./boat.ts";+import { boatHealth, unansweredStatus } from "./boat-health.ts";+import type { AppConfig } from "./config.ts";++export const COMMAND_WALL = {+ /** A command given no more time than this by its caller is sent the synchronous way, in one round trip: its caller+ * gives up five seconds before the provider would stop it at 30 s. */+ syncSafeMs: 25_000,+ /** The end of each output stream that is read back once the command has ended: 256 KiB. */+ tailBytes: 262_144,+ /** While it runs only this much is read, since each read is thrown away but the last. */+ runningTailBytes: 12_000,+ /** Before each status read: short at first, so a command that takes a fifth of a second gains about a tenth. */+ pollMs: [40, 80, 150, 300, 600, 1_200, 2_000],+ readTimeoutMs: 15_000,+ /** Commands a bot's exec calls may leave running on one computer after their time ran out; one more is stopped instead. */+ leftRunningMax: 5,+ /** A command left running counts toward that for this long, the same two hours it may keep the computer awake. */+ leftRunningMs: 2 * 60 * 60_000,+} as const;++export interface CommandOutcome {+ ok: boolean;+ exitCode: number | null;+ stdout: string;+ stderr: string;+ /** The caller's time ran out. With `processId`, the command is still running on the computer and was not stopped. */+ timedOut?: true;+ processId?: number;+ /** The gateway could not reach the machine (502, 504, 52x) when the command was sent. */+ unanswered?: true;+ /** A 503, which may be a relay's account-wide refusal rather than this machine. */+ busy?: true;+ /** The provider stopped a synchronous command at its 30 s limit: not the command's own failure, and it no longer runs. */+ providerLimit?: true;+ /** Only the end of the output came back. */+ outputCut?: true;+ /** The computer restarted or lost track of the command, so how it ended is not known. */+ lost?: true;+}++export const COMMAND_LOST = "The cloud computer restarted or lost track of this command, so its exit code is unknown. Look at the files it writes to see how far it got.";++/** Process ids started on each computer, with when: its idle sleep waits for them, up to a limit the reader sets. */+const started = new Map<string, Map<number, number>>();+const MAX_TRACKED_PER_COMPUTER = 20;+/** The ones a bot's exec call handed back still running, with when. */+const leftRunning = new Map<string, Map<number, number>>();++export function trackProcess(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);+}++export function untrackProcess(boxId: string, processId: number): void {+ const mine = started.get(boxId);+ mine?.delete(processId);+ if (mine?.size === 0) started.delete(boxId);+ forgetLeftRunning(boxId, processId);+}++function forgetLeftRunning(boxId: string, processId: number): void {+ const left = leftRunning.get(boxId);+ left?.delete(processId);+ if (left?.size === 0) leftRunning.delete(boxId);+}++/** A bot's exec call ran out of time and this command was handed back to it still running. */+export function noteLeftRunning(boxId: string, processId: number): void {+ const left = leftRunning.get(boxId) ?? new Map<number, number>();+ left.set(processId, Date.now());+ leftRunning.set(boxId, left);+}++export const trackedProcesses = (boxId: string): ReadonlyMap<number, number> => started.get(boxId) ?? new Map();++/** An answer that does not say it ended counts as running. */+export async function processMayStillRun(cfg: AppConfig, boxId: string, processId: number, timeoutMs = 20_000): Promise<boolean> {+ try {+ const response = await boatFetch(cfg, `/sandboxes/${boxId}/commands/${processId}?tailBytes=1`, { signal: AbortSignal.timeout(timeoutMs) });+ const body: any = await response.json().catch(() => null);+ return response.status !== 404 && !(response.ok && (body?.running === false || body?.known === false));+ } catch {+ return true;+ }+}++/** How many commands a bot's exec calls left running still run. One that ended, or was left longer ago than+ * COMMAND_WALL.leftRunningMs, is forgotten; one whose status could not be read is not counted, so a failing gateway+ * never holds a bot at the limit. */+export async function commandsLeftRunning(cfg: AppConfig, boxId: string): Promise<number> {+ const seen = await Promise.all([...(leftRunning.get(boxId) ?? [])].map(async ([processId, at]) => {+ if (Date.now() - at >= COMMAND_WALL.leftRunningMs) { forgetLeftRunning(boxId, processId); return false; }+ try {+ const response = await boatFetch(cfg, `/sandboxes/${boxId}/commands/${processId}?tailBytes=1`, { signal: AbortSignal.timeout(5_000) });+ const body: any = await response.json().catch(() => null);+ if (response.status === 404 || (response.ok && (body?.running === false || body?.known === false))) { forgetLeftRunning(boxId, processId); return false; }+ return response.ok && body?.running === true;+ } catch {+ return false;+ }+ }));+ return seen.filter(Boolean).length;+}++const text = (value: unknown): string => (typeof value === "string" ? value : "");++/** Runs `command` to its end however long it takes, within `timeoutMs`. Whether it ran is always known once it started:+ * the provider's processId answers that, so nothing here sends a command twice. */+export async function runToEnd(+ cfg: AppConfig, boxId: string, command: string, { timeoutMs, signal }: { timeoutMs: number; signal?: AbortSignal },+): Promise<CommandOutcome> {+ assertBoatNotDeleting(boxId);+ const deadline = Date.now() + timeoutMs;+ const within = (ms: number) => { const limit = AbortSignal.timeout(Math.max(1, ms)); return signal ? AbortSignal.any([signal, limit]) : limit; };+ const suspect = () => { if (!signal?.aborted) boatHealth.suspect(boxId, () => probeBoat(cfg, boxId)); };+ const res = await boatFetch(cfg, `/sandboxes/${boxId}/commands`, { method: "POST", body: JSON.stringify({ command, detached: true }), signal: within(timeoutMs) })+ .catch((error: unknown) => { suspect(); throw error; });+ const body: any = await res.json().catch(() => null);+ if (unansweredStatus(res.status)) {+ suspect();+ return { ok: false, exitCode: null, stdout: "", stderr: "", unanswered: true };+ }+ if (!res.ok) return { ok: false, exitCode: null, stdout: text(body?.stdout), stderr: text(body?.stderr), ...(res.status === 503 ? { busy: true as const } : {}) };+ const processId = body?.processId;+ if (processId === undefined && (typeof body?.exitCode === "number" || body?.timedOut === true)) {+ if (typeof body.exitCode === "number") boatHealth.answered(boxId);+ return { ok: body.exitCode === 0, exitCode: body.exitCode ?? null, stdout: text(body.stdout), stderr: text(body.stderr), ...(body.timedOut === true ? { timedOut: true as const, providerLimit: true as const } : {}) };+ }+ if (!Number.isSafeInteger(processId) || processId < 1) {+ return { ok: false, exitCode: null, stdout: "", stderr: "The cloud computer did not say which process it started, so the command may be running." };+ }+ trackProcess(boxId, processId);+ let last: any = null;+ for (let read = 0; ; read++) {+ const pause = COMMAND_WALL.pollMs[Math.min(read, COMMAND_WALL.pollMs.length - 1)]!;+ await delay(Math.min(pause, Math.max(0, deadline - Date.now())), undefined, { signal }).catch(() => undefined);+ // The caller gave up (the turn was stopped): nobody follows this process any more, so it must not keep the+ // computer awake. Stopping it is the caller's, which knows how it was started.+ if (signal?.aborted) untrackProcess(boxId, processId);+ signal?.throwIfAborted();+ if (Date.now() >= deadline) {+ return { ok: false, exitCode: null, stdout: text(last?.stdout), stderr: text(last?.stderr), timedOut: true, processId };+ }+ let status: Response;+ let seen: any;+ try {+ status = await boatFetch(cfg, `/sandboxes/${boxId}/commands/${processId}?tailBytes=${COMMAND_WALL.runningTailBytes}`,+ { signal: within(Math.min(COMMAND_WALL.readTimeoutMs, deadline - Date.now())) });+ seen = await status.json().catch(() => null);+ } catch {+ if (signal?.aborted) untrackProcess(boxId, processId);+ signal?.throwIfAborted();+ continue;+ }+ if (status.status === 404 || (status.ok && seen?.known === false)) {+ untrackProcess(boxId, processId);+ return { ok: false, exitCode: null, stdout: text(last?.stdout), stderr: COMMAND_LOST, lost: true };+ }+ // A read the gateway failed says nothing about the command: it is read again.+ if (!status.ok || typeof seen?.running !== "boolean") continue;+ last = seen;+ if (seen.running) continue;+ untrackProcess(boxId, processId);+ // It has ended: one more read for the whole tail. If that read fails, the short tail stands and is marked cut.+ let whole = false;+ try {+ const full = await boatFetch(cfg, `/sandboxes/${boxId}/commands/${processId}?tailBytes=${COMMAND_WALL.tailBytes}`, { signal: within(COMMAND_WALL.readTimeoutMs) });+ const body: any = await full.json().catch(() => null);+ if (full.ok && body?.running === false) { seen = body; whole = true; }+ } catch {+ signal?.throwIfAborted();+ }+ const exitCode = Number.isInteger(seen.exitCode) ? seen.exitCode as number : null;+ const lost = seen.status === "lost";+ // Only the machine's own answer counts toward its health: an exit code it reported.+ if (exitCode !== null && !lost) boatHealth.answered(boxId);+ return {+ ok: exitCode === 0, exitCode, stdout: text(seen.stdout), stderr: lost && !text(seen.stderr) ? COMMAND_LOST : text(seen.stderr),+ ...(seen.stdoutTruncated === true || seen.stderrTruncated === true || (!whole && (text(seen.stdout).length >= COMMAND_WALL.runningTailBytes || text(seen.stderr).length >= COMMAND_WALL.runningTailBytes)) ? { outputCut: true as const } : {}),+ ...(lost ? { lost: true as const } : {}),+ };+ }+}diff --git a/server/boat-health.ts b/server/boat-health.tsindex 7ee7a3a09e..b8aeb33b23 100644--- a/server/boat-health.ts+++ b/server/boat-health.ts@@ -101,9 +101,16 @@ export function createBoatHealth(now: () => number = Date.now) {const at = boxes.get(boxId)?.lastAnsweredAt;return at !== null && at !== undefined && now() - at <= ms;},+ lastAnsweredAt: (boxId: string): number | null => boxes.get(boxId)?.lastAnsweredAt ?? null,/** Some other computer answered recently, so the provider and the path to it work. */otherAnsweredWithin: (boxId: string, ms: number): boolean =>[...boxes].some(([id, health]) => id !== boxId && health.lastAnsweredAt !== null && now() - health.lastAnsweredAt <= ms),+ /** Some other computer was probed recently and none of them answered: the trouble is on the provider's side. */+ othersSilentWithin: (boxId: string, ms: number): boolean => {+ const others = [...boxes].filter(([id]) => id !== boxId).map(([, health]) => health);+ return others.some((health) => health.lastFailureAt !== null && now() - health.lastFailureAt <= ms)+ && !others.some((health) => health.lastAnsweredAt !== null && now() - health.lastAnsweredAt <= ms);+ },/** A person opened this computer's desktop. */personUsed: (boxId: string) => { entry(boxId).personAt = now(); },personUsedWithin: (boxId: string, ms: number): boolean => {diff --git a/server/boat-ready.test.ts b/server/boat-ready.test.tsnew file mode 100644index 0000000000..ba103e1c08--- /dev/null+++ b/server/boat-ready.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";++import { createBoatHealth } from "./boat-health.ts";+import { boatSignals, createBoatReadiness, READY_WAIT } from "./boat-ready.ts";+import { createCloudComputerCounters } from "./cloud-computer-counters.ts";+import type { AppConfig } from "./config.ts";++const cfg = {} as AppConfig;+const BOX = "bx_23456789";++/** A clock that only moves when the wait sleeps or a probe takes its time. */+function harness(probe: (at: number, call: number) => boolean | null, sandbox: (at: number) => unknown = () => ({ state: "idle", health: "ok" })) {+ let at = 1_000_000;+ let probes = 0;+ const now = () => at;+ const health = createBoatHealth(now);+ const counters = createCloudComputerCounters(now);+ const phases: string[] = [];+ const readiness = createBoatReadiness({+ probe: async () => {+ const answered = probe(at, probes++);+ if (answered === false) at += READY_WAIT.probeTimeoutMs;+ return answered;+ },+ read: async () => sandbox(at), health, counters, now,+ sleep: async (ms) => { at += ms; },+ });+ return { readiness, health, counters, phases, now, probes: () => probes, advance: (ms: number) => { at += ms; }, start: at };+}++describe("what the provider says about a sandbox", () => {+ it("reads a disk restore from any of the fields seen on a silent computer", () => {+ expect(boatSignals({ state: "idle", health: "ok", hydrated: false, lastSnapshotStatus: "in_progress" })).toEqual({ restoring: true, degraded: false });+ expect(boatSignals({ hydrated: true, lastSnapshotStatus: "in_progress" }).restoring).toBe(true);+ expect(boatSignals({ hydration: { status: "pending" } }).restoring).toBe(true);+ expect(boatSignals({ hydration: "hydrating" }).restoring).toBe(true);+ expect(boatSignals({ hydrated: true, lastSnapshotStatus: "completed" }).restoring).toBe(false);+ });++ it("treats a field that is not there as unknown, never as healthy", () => {+ expect(boatSignals({ state: "idle" })).toEqual({ restoring: null, degraded: null });+ expect(boatSignals(null)).toEqual({ restoring: null, degraded: null });+ expect(boatSignals({ lastSnapshotStatus: "completed" }).restoring).toBeNull();+ });++ it("reads trouble from health and degradedSince", () => {+ expect(boatSignals({ health: "degraded" }).degraded).toBe(true);+ expect(boatSignals({ health: "ok", degradedSince: "2026-11-14T10:00:00Z" }).degraded).toBe(true);+ expect(boatSignals({ health: "ok" }).degraded).toBe(false);+ });+});++describe("waiting for a cloud computer to answer", () => {+ it("asks nothing of a computer that answered a command a moment ago", async () => {+ const h = harness(() => true);+ h.health.answered(BOX);+ h.advance(READY_WAIT.freshMs - 1);+ await expect(h.readiness.awaitAnswer(cfg, BOX)).resolves.toEqual({ ok: true, waitedMs: 0 });+ expect(h.probes()).toBe(0);+ });++ it("probes one that answered longer ago, and one that was just woken however recently it answered", async () => {+ const h = harness(() => true);+ h.health.answered(BOX);+ await h.readiness.awaitAnswer(cfg, BOX, { woke: true });+ expect(h.probes()).toBe(1);+ h.advance(READY_WAIT.freshMs + 1);+ await h.readiness.awaitAnswer(cfg, BOX);+ expect(h.probes()).toBe(2);+ });++ it("keeps probing a computer the provider calls ready until it answers, and says it was waking meanwhile", async () => {+ const h = harness((at) => at >= h.start + 40_000);+ const phases: string[] = [];+ const answer = await h.readiness.awaitAnswer(cfg, BOX, { woke: true, onPhase: (phase) => phases.push(phase) });+ expect(answer.ok).toBe(true);+ expect(answer.waitedMs).toBeGreaterThanOrEqual(40_000);+ expect(answer.waitedMs).toBeLessThan(READY_WAIT.answerPatienceMs);+ expect(phases).toEqual(["waking"]);+ expect(h.readiness.waitingOn(BOX)).toBeNull();+ expect(h.health.answeredWithin(BOX, 1)).toBe(true);+ expect(h.counters.snapshot(BOX)).toMatchObject({ wakes: 1, restoreWaits: 0 });+ });++ it("gives up after a minute and a half when the provider gives no reason for the silence", async () => {+ const h = harness(() => false);+ const answer = await h.readiness.awaitAnswer(cfg, BOX, { woke: true });+ expect(answer).toMatchObject({ ok: false, phase: "waking" });+ expect(answer.waitedMs).toBeLessThanOrEqual(READY_WAIT.answerPatienceMs + READY_WAIT.probeTimeoutMs);+ expect(answer.waitedMs).toBeGreaterThan(READY_WAIT.answerPatienceMs - READY_WAIT.probeTimeoutMs - READY_WAIT.probeGapMs);+ });++ it("waits up to ten minutes while the provider says the disk is being restored, and reports that", async () => {+ const restoring = { state: "idle", health: "ok", hydrated: false, lastSnapshotStatus: "in_progress" };+ const slow = harness((at) => at >= slow.start + 6 * 60_000, () => restoring);+ const phases: string[] = [];+ const answer = await slow.readiness.awaitAnswer(cfg, BOX, { woke: true, onPhase: (phase) => phases.push(phase) });+ expect(answer.ok).toBe(true);+ expect(answer.waitedMs).toBeGreaterThanOrEqual(6 * 60_000);+ expect(phases).toEqual(["restoring"]);+ expect(slow.counters.snapshot(BOX)).toMatchObject({ restoreWaits: 1 });++ const never = harness(() => false, () => restoring);+ const gaveUp = await never.readiness.awaitAnswer(cfg, BOX, { woke: true });+ expect(gaveUp).toMatchObject({ ok: false, phase: "restoring" });+ expect(gaveUp.waitedMs).toBeLessThanOrEqual(READY_WAIT.restorePatienceMs + READY_WAIT.probeTimeoutMs);+ expect(gaveUp.waitedMs).toBeGreaterThan(READY_WAIT.answerPatienceMs);+ });++ it("never waits past the caller's deadline, restore or not", async () => {+ const h = harness(() => false, () => ({ hydrated: false }));+ const answer = await h.readiness.awaitAnswer(cfg, BOX, { woke: true, deadline: h.start + 20_000 });+ expect(answer.ok).toBe(false);+ expect(answer.waitedMs).toBeLessThanOrEqual(20_000);+ });++ it("lets the call through when the probe is turned away rather than unanswered", async () => {+ const h = harness(() => null);+ await expect(h.readiness.awaitAnswer(cfg, BOX, { woke: true })).resolves.toMatchObject({ ok: true });+ expect(h.probes()).toBe(1);+ expect(h.health.answeredWithin(BOX, 60_000)).toBe(false);+ });++ it("counts its unanswered probes toward the computer's health, so a silent one is noticed with no command running", async () => {+ const h = harness(() => false);+ const silent: string[] = [];+ h.health.onNotResponding((boxId) => silent.push(boxId));+ await h.readiness.awaitAnswer(cfg, BOX, { woke: true });+ expect(silent).toEqual([BOX]);+ expect(h.health.notRespondingSince(BOX)).not.toBeNull();+ });+});diff --git a/server/boat-ready.ts b/server/boat-ready.tsnew file mode 100644index 0000000000..d79d9d8d2f--- /dev/null+++ b/server/boat-ready.ts@@ -0,0 +1,154 @@+// Boat's `state` says a sandbox is ready; it does not say that its command agent answers. Its gateway answers 502 after+// about 40 s when a sandbox is too slow to answer, which was seen on sandboxes that had just been resumed, with+// `hydrated: false` and a snapshot `in_progress`. So the provider's state alone never means ready here: a short `true`+// has to come back as well.+// Unverified: that `hydrated`, `hydration`, `lastSnapshotStatus`, `health` and `degradedSince` are sent on every read. They+// only lengthen the wait when present; absent, the wait is the short one.+import { setTimeout as delay } from "node:timers/promises";++import { transientClaimFailure } from "./auto-vm-claims.ts";+import { boatAccount, boatFetch, runCommand } from "./boat.ts";+import { boatHealth, type BoatHealth } from "./boat-health.ts";+import { relayBody } from "./boat-relay.ts";+import { cloudComputerCounters, type CloudComputerCounters } from "./cloud-computer-counters.ts";+import type { AppConfig } from "./config.ts";++export const READY_WAIT = {+ /** A live machine answers `true` in about 0.2 s. Eight seconds is forty times that, and well under the 40 s the provider's+ * gateway holds a command to a sandbox that does not answer, so a probe that hangs costs a turn seconds, not most of a minute. */+ probeTimeoutMs: 8_000,+ /** Between probes that got no answer. */+ probeGapMs: 3_000,+ /** A computer that answered a command this recently is not probed again. Shorter than any stop and resume takes+ * (about 13 s at the fastest) plus the ten idle minutes before this app stops one. */+ freshMs: 60_000,+ /** With the provider saying ready and giving no reason for the silence: a resume takes about 8 s, so this is ten of them. */+ answerPatienceMs: 90_000,+ /** With the provider saying the disk is still being restored. Restores of 5 to 30 minutes were seen; past ten the+ * computer is restarted instead, once. */+ restorePatienceMs: 10 * 60_000,+ readTimeoutMs: 10_000,+} as const;++export type BoatWaitPhase = "waking" | "restoring";++/** What the provider says about a sandbox beyond its state; null where it says nothing. */+export interface BoatSignals {+ restoring: boolean | null;+ degraded: boolean | null;+}++const UNDER_WAY = /^(in[_-]?progress|pending|running|hydrating|restoring)$/i;+const statusOf = (value: unknown): string | null =>+ typeof value === "string" ? value : value && typeof value === "object" && typeof (value as { status?: unknown }).status === "string"+ ? (value as { status: string }).status : null;++export function boatSignals(sandbox: unknown): BoatSignals {+ const box = (sandbox && typeof sandbox === "object" ? sandbox : {}) as Record<string, unknown>;+ const hydration = statusOf(box.hydration), snapshot = statusOf(box.lastSnapshotStatus);+ const restoring = box.hydrated === false || (hydration !== null && UNDER_WAY.test(hydration)) || (snapshot !== null && UNDER_WAY.test(snapshot))+ ? true : box.hydrated === true ? false : null;+ const degraded = (typeof box.health === "string" && box.health !== "ok") || Boolean(box.degradedSince)+ ? true : box.health === "ok" ? false : null;+ return { restoring, degraded };+}++export type BoatAnswer =+ | { ok: true; waitedMs: number }+ | { ok: false; phase: BoatWaitPhase; waitedMs: number };++export interface BoatReadinessDeps {+ /** true: answered; false: no answer; null: turned away (a limit, a missing computer), which says nothing about the machine. */+ probe(cfg: AppConfig, boxId: string, signal?: AbortSignal): Promise<boolean | null>;+ /** The provider's sandbox object, or null when it could not be read. */+ read(cfg: AppConfig, boxId: string): Promise<unknown>;+ health: BoatHealth;+ counters: CloudComputerCounters;+ now(): number;+ sleep(ms: number, signal?: AbortSignal): Promise<void>;+}++export interface AwaitAnswerOptions {+ /** The computer was just created, woken or restarted, so an earlier answer says nothing about it now. */+ woke?: boolean;+ /** Never waits past this, whatever the provider says. */+ deadline?: number;+ signal?: AbortSignal;+ onPhase?(phase: BoatWaitPhase): void;+}++async function probeOnce(cfg: AppConfig, boxId: string, signal?: AbortSignal): Promise<boolean | null> {+ try {+ const out = await runCommand(cfg, boxId, "true", { timeoutMs: READY_WAIT.probeTimeoutMs, probe: true, signal });+ return out.ok ? true : out.unanswered ? false : null;+ } catch (error) {+ return transientClaimFailure(error) ? false : null;+ }+}++/** The provider's own object for one sandbox, or null when it could not be read. */+export async function readBoat(cfg: AppConfig, boxId: string): Promise<unknown> {+ try {+ const res = await boatFetch(cfg, `/sandboxes/${boxId}`, { signal: AbortSignal.timeout(READY_WAIT.readTimeoutMs) });+ const body = relayBody(boatAccount(cfg), await res.json().catch(() => null));+ return res.ok ? body?.sandbox ?? null : null;+ } catch {+ return null;+ }+}++export function createBoatReadiness(overrides: Partial<BoatReadinessDeps> = {}) {+ const deps: BoatReadinessDeps = {+ probe: probeOnce, read: readBoat, health: boatHealth, counters: cloudComputerCounters, now: Date.now,+ sleep: (ms, signal) => delay(ms, undefined, { signal }).catch(() => undefined),+ ...overrides,+ };+ const waiting = new Map<string, { phase: BoatWaitPhase; since: number }>();++ /** Resolves once the computer answers a command, or says which wait ran out. A probe that is turned away counts as+ * an answer: the call that follows gets the provider's own refusal. */+ async function awaitAnswer(cfg: AppConfig, boxId: string, opts: AwaitAnswerOptions = {}): Promise<BoatAnswer> {+ if (!opts.woke && deps.health.answeredWithin(boxId, READY_WAIT.freshMs)) return { ok: true, waitedMs: 0 };+ const started = deps.now();+ const hardStop = opts.deadline ?? Infinity;+ let phase = "waking" as BoatWaitPhase;+ let failures = 0;+ const enter = (next: BoatWaitPhase) => {+ if (next === phase && waiting.has(boxId)) return;+ phase = next;+ waiting.set(boxId, { phase, since: started });+ opts.onPhase?.(phase);+ };+ const done = (answer: BoatAnswer): BoatAnswer => {+ waiting.delete(boxId);+ if (failures > 0 || opts.woke) deps.counters.count(boxId, phase === "restoring" ? "restoreWaits" : "wakes", answer.waitedMs);+ return answer;+ };+ for (;;) {+ const answered = await deps.probe(cfg, boxId, opts.signal);+ if (opts.signal?.aborted) return done({ ok: false, phase, waitedMs: deps.now() - started });+ if (answered !== false) {+ if (answered) deps.health.answered(boxId);+ return done({ ok: true, waitedMs: deps.now() - started });+ }+ failures += 1;+ deps.health.unanswered(boxId);+ enter(boatSignals(await deps.read(cfg, boxId)).restoring === true ? "restoring" : phase);+ const patience = phase === "restoring" ? READY_WAIT.restorePatienceMs : READY_WAIT.answerPatienceMs;+ // The patience may be overrun by one probe; the caller's deadline never is.+ const next = deps.now() + READY_WAIT.probeGapMs;+ if (next >= started + patience || next + READY_WAIT.probeTimeoutMs > hardStop) return done({ ok: false, phase, waitedMs: deps.now() - started });+ await deps.sleep(READY_WAIT.probeGapMs, opts.signal);+ }+ }++ return {+ awaitAnswer,+ /** What a wait under way is waiting for, for the computer's own state line. */+ waitingOn: (boxId: string): { phase: BoatWaitPhase; since: number } | null => waiting.get(boxId) ?? null,+ };+}++export type BoatReadiness = ReturnType<typeof createBoatReadiness>;++export const boatReadiness = createBoatReadiness();diff --git a/server/boat-recovery.test.ts b/server/boat-recovery.test.tsindex 2cac587c07..facf9e560b 100644--- a/server/boat-recovery.test.ts+++ b/server/boat-recovery.test.ts@@ -7,7 +7,7 @@ import { join } from "node:path";import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type { AppConfig } from "./config.ts";-type Box = { id: string; name: string; state: string; error?: string };+type Box = { id: string; name: string; state: string; error?: string; hydrated?: boolean; lastSnapshotStatus?: string };type Seen = { method: string; path: string; headers: IncomingMessage["headers"] };const ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz";@@ -132,8 +132,10 @@ async function load() {function start() {told = [];health = healthModule.createBoatHealth(now);- recovery = recoveryModule.createBoatRecovery({ cfg: () => cfg, tell: (owner, line) => told.push([owner, line]), log: () => {}, file, now, health, pollMs: 5,- autoReplace: () => autoOn, eligible: (owner) => !teamOwners.has(owner), personActive: (owner) => watched.has(owner) });+ recovery = recoveryModule.createBoatRecovery({ cfg: () => cfg, tell: (owner, line) => told.push([owner, line]), log: () => {}, file, now, health, pollMs: 5, recheckMs: 20,+ autoReplace: () => autoOn, eligible: (owner) => !teamOwners.has(owner), personActive: (owner) => watched.has(owner),+ // One probe stands for the wait, so a restart that does not help is judged at once.+ readiness: { awaitAnswer: async (_cfg, boxId) => ((await boat.probeBoat(cfg, boxId)) === true ? { ok: true, waitedMs: 0 } : { ok: false, phase: "waking", waitedMs: 0 }) } });}beforeEach(async () => {@@ -346,13 +348,14 @@ describe("a cloud computer that says it is ready but does not answer", () => {expect(deletes()).toHaveLength(0);});- it("is neither restarted nor deleted when no other computer answers: it waits for the person", async () => {+ it("is restarted, which keeps its files, but never deleted when no other computer answers: it then waits for the person", async () => {const { botId, box } = await botWith("ready");commandStatus.set(box.id, 502);await boat.findBoat(cfg, botId);stopsAnswering(box.id);await until(() => recovery.status(botId)?.state === "needs-person");- expect(stops()).toHaveLength(0);+ expect(stops().map((request) => request.path)).toEqual([`/boxes/${box.id}/stop`]);+ expect(recovery.verdict(botId)).toBe("restart-failed");expect(deletes()).toHaveLength(0);expect(told).toEqual([[botId, "needsPerson"]]);expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_NEEDS_PERSON);@@ -440,6 +443,193 @@ describe("a cloud computer that says it is ready but does not answer", () => {});});+describe("a cloud computer that is ready, silent, and still restoring its disk", () => {+ /** Three probes with no answer over a little more than a minute: silent, and not for long. */+ const justStoppedAnswering = (boxId: string) => {+ health.unanswered(boxId);+ at += 35_000;+ health.unanswered(boxId);+ at += 35_000;+ health.unanswered(boxId);+ };++ it("is waited for, not restarted, and the bot is told it is restoring", async () => {+ const { botId, box } = await botWith("ready", { hydrated: false, lastSnapshotStatus: "in_progress" });+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ justStoppedAnswering(box.id);+ await until(() => recovery.status(botId)?.state === "restoring");+ expect(stops()).toHaveLength(0);+ expect(recovery.refusal(box.id, "before")).toBe(words.CLOUD_COMPUTER_RESTORING);+ expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_STILL_RESTORING);+ expect(recovery.verdict(botId)).toBeNull();+ expect(told).toEqual([]);+ expect(recovery.stuck(botId)).toBe(true);+ });++ it("is restarted once the restore has taken more than ten minutes", async () => {+ const { botId, box } = await botWith("ready", { hydrated: false, lastSnapshotStatus: "in_progress" });+ commandStatus.set(box.id, 502);+ resumeAnswers.add(box.id);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ await until(() => recovery.status(botId)?.state === "restarted");+ expect(stops().map((request) => request.path)).toEqual([`/boxes/${box.id}/stop`]);+ expect(deletes()).toHaveLength(0);+ });++ it("is restarted without that wait when the provider does not say it is restoring", async () => {+ const { botId, box } = await botWith("ready", { hydrated: true });+ const witness = await botWith("ready");+ commandStatus.set(box.id, 502);+ resumeAnswers.add(box.id);+ await boat.findBoat(cfg, botId);+ justStoppedAnswering(box.id);+ health.answered(witness.box.id);+ await until(() => recovery.status(botId)?.state === "restarted");+ expect(stops()).toHaveLength(1);+ });+});++describe("before a silent computer is restarted by itself", () => {+ const silentForAMinute = (boxId: string) => {+ health.unanswered(boxId);+ at += 35_000;+ health.unanswered(boxId);+ at += 35_000;+ health.unanswered(boxId);+ };++ it("nothing is restarted when the installation's other computers were probed and none answered: the trouble is the provider's", async () => {+ const { botId, box } = await botWith("ready");+ const other = await botWith("ready");+ commandStatus.set(box.id, 502);+ commandStatus.set(other.box.id, 502);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ health.unanswered(other.box.id);+ await until(() => recovery.status(botId)?.state === "unreachable");+ expect(stops()).toHaveLength(0);+ expect(told).toEqual([[botId, "unreachable"]]);+ expect(recovery.verdict(botId)).toBeNull();+ });++ it("with no other computer to compare against, it waits for five minutes of silence, looking again meanwhile", async () => {+ const { botId, box } = await botWith("ready");+ commandStatus.set(box.id, 502);+ resumeAnswers.add(box.id);+ await boat.findBoat(cfg, botId);+ silentForAMinute(box.id);+ 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 until(() => recovery.status(botId)?.state === "restarted");+ expect(stops()).toHaveLength(1);+ });++ it("with another computer answering, it is restarted after the first minute", async () => {+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ commandStatus.set(box.id, 502);+ resumeAnswers.add(box.id);+ await boat.findBoat(cfg, botId);+ silentForAMinute(box.id);+ health.answered(witness.box.id);+ await until(() => recovery.status(botId)?.state === "restarted");+ expect(stops()).toHaveLength(1);+ });++ it("a state that cannot be read is unknown, never a reason to restart", async () => {+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ recovery.close();+ told = [];+ recovery = recoveryModule.createBoatRecovery({ cfg: () => cfg, tell: (owner, line) => told.push([owner, line]), log: () => {}, file, now, health, pollMs: 5, recheckMs: 20,+ autoReplace: () => false, read: async () => null,+ readiness: { awaitAnswer: async () => ({ ok: false, phase: "waking", waitedMs: 0 }) } });+ silentForAMinute(box.id);+ health.answered(witness.box.id);+ 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;+ health.answered(witness.box.id);+ await until(() => recovery.status(botId)?.state === "needs-person");+ expect(stops()).toHaveLength(0);+ expect(deletes()).toHaveLength(0);+ });+});++describe("why a silent computer was left as it is", () => {+ it("dates its answer, so a wait that began later does not take it for its own", async () => {+ const { botId, box } = await botWith("ready");+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ await until(() => recovery.verdict(botId) === "restart-failed");+ expect(recovery.verdict(botId, at)).toBe("restart-failed");+ expect(recovery.verdict(botId, at + 1)).toBeNull();+ });++ it("says a person was using it", async () => {+ const { botId, box } = await botWith("ready");+ commandStatus.set(box.id, 502);+ watched.add(botId);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ await until(() => recovery.verdict(botId) === "person-busy");+ expect(stops()).toHaveLength(0);+ });++ it("says a restart did not help, and keeps saying that while the computer stays silent", async () => {+ const { botId, box } = await botWith("ready");+ commandStatus.set(box.id, 502);+ 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;+ health.unanswered(box.id);+ await until(() => recovery.status(botId)?.state === "not-responding");+ await until(() => recovery.status(botId)?.state === "needs-person");+ expect(recovery.verdict(botId)).toBe("restart-failed");+ expect(stops()).toHaveLength(1);+ });++ it("says it was restarted too recently when it goes silent again within the hour, and nothing once it answers", async () => {+ const { botId, box } = await botWith("ready");+ commandStatus.set(box.id, 502);+ resumeAnswers.add(box.id);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ await until(() => recovery.status(botId)?.state === "restarted");+ expect(recovery.verdict(botId)).toBeNull();+ resumeAnswers.delete(box.id);+ commandStatus.set(box.id, 502);+ at += 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;+ expect(recovery.status(botId)).toBeNull();+ expect(recovery.verdict(botId)).toBeNull();+ });++ it("says a team's shared computer is never restarted by itself", async () => {+ const { botId, box } = await botWith("ready");+ teamOwners.add(botId);+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ await until(() => recovery.verdict(botId) === "shared");+ expect(stops()).toHaveLength(0);+ });+});+describe("a team's shared cloud computer", () => {for (const on of [false, true]) {it(`is never stopped or deleted by itself, with automatic replacement ${on ? "on" : "off"}`, async () => {diff --git a/server/boat-recovery.ts b/server/boat-recovery.tsindex 93e6a4cd5c..051964559b 100644--- a/server/boat-recovery.ts+++ b/server/boat-recovery.ts@@ -1,5 +1,6 @@-// A cloud computer that stopped answering: restarted once, then replaced (its deletion frees the plan's place, and the next-// use creates a new one), and the bot and the person are told once. Nothing here asks the person anything.+// A cloud computer that stopped answering: waited for while the provider is still restoring its disk, restarted once, then+// replaced (its deletion frees the plan's place, and the next use creates a new one) or, with automatic replacement off,+// left for the person. The bot and the person are told once. Nothing here asks the person anything.import { existsSync, readFileSync } from "node:fs";import { join } from "node:path";@@ -7,11 +8,14 @@ import { writeFileAtomic } from "./atomic.ts";import * as boat from "./boat.ts";import { BOAT_DELETING, BOAT_DELETION_FINISHED, getBoatDeletion } from "./boat-delete-journal.ts";import { boatHealth, DEAD_COMPUTER, type BoatHealth } from "./boat-health.ts";+import { boatReadiness, boatSignals, readBoat, READY_WAIT, type BoatReadiness } from "./boat-ready.ts";+import { cloudComputerCounters } from "./cloud-computer-counters.ts";import { cloudFailureOf } from "./boat-limit.ts";import { DATA_DIR, type AppConfig } from "./config.ts";import {CLOUD_COMPUTER_CAPPED, CLOUD_COMPUTER_DEAD_WAITING, CLOUD_COMPUTER_NEEDS_PERSON, CLOUD_COMPUTER_NOT_RESPONDING, CLOUD_COMPUTER_REPLACED,- CLOUD_COMPUTER_REPLACED_BY_PERSON, CLOUD_COMPUTER_RESTARTED, CLOUD_COMPUTER_TEAM_NOT_RESPONDING, CLOUD_COMPUTER_UNREACHABLE, recoveryUnderWay,+ CLOUD_COMPUTER_REPLACED_BY_PERSON, CLOUD_COMPUTER_RESTARTED, CLOUD_COMPUTER_RESTARTING, CLOUD_COMPUTER_RESTARTING_UNANSWERED, CLOUD_COMPUTER_RESTORING,+ CLOUD_COMPUTER_STILL_RESTORING, CLOUD_COMPUTER_TEAM_NOT_RESPONDING, CLOUD_COMPUTER_UNREACHABLE, recoveryUnderWay,type CloudComputerPersonLine, type CloudComputerRecovery, type CloudComputerRecoveryState,} from "../shared/cloud-computer-recovery.ts";@@ -23,6 +27,12 @@ const WAKE_BUDGET_MS = 120_000;const POLL_MS = 2_500;/** A restart or replacement no longer running after this long has ended where the next start picks it up. */const STALE_MS = 15 * 60_000;+/** How often a computer that is waited on before a restart (a disk restore, too short a silence, an unread state) is looked at again. */+const RECHECK_MS = 30_000;+/** With no other computer to compare against, a silent one is restarted only after this long without one answer. */+const SOLO_SILENCE_MS = 5 * 60_000;+/** A restart the person asked for answers the panel within this, however long the disk takes. */+const MANUAL_ANSWER_WAIT_MS = 3 * 60_000;const READY = new Set(["idle", "ready", "running"]);/** One replacement, written before its delete is sent: a crash after it still counts against the hourly limit and still@@ -61,8 +71,15 @@ export interface BoatRecoveryDeps {health?: BoatHealth;pollMs?: number;autoReplace?: () => boolean;+ readiness?: Pick<BoatReadiness, "awaitAnswer">;+ /** The provider's sandbox object, for its state and what it says about a disk restore; null when it could not be read. */+ read?(cfg: AppConfig, boxId: string): Promise<unknown>;+ recheckMs?: number;}+/** Why a computer that is not answering was left as it is, for a run that waited on it. */+export type RecoveryVerdict = "restart-failed" | "person-busy" | "restart-limited" | "shared";+type Dead = { boxId: string; name: string };type ReplaceOutcome = "confirmed" | "pending" | "kept" | "held" | "waiting" | "capped" | "failed";@@ -73,6 +90,13 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {const pollMs = deps.pollMs ?? POLL_MS;const autoReplace = deps.autoReplace ?? (() => cloudComputerAutoReplace(deps.cfg()));const eligible = (owner: string) => deps.eligible?.(owner) ?? true;+ const readiness = deps.readiness ?? boatReadiness;+ const read = deps.read ?? readBoat;+ /** When each computer was first seen not answering with its disk still being restored. */+ const restoringSince = new Map<string, number>();+ const recheckMs = deps.recheckMs ?? RECHECK_MS;+ const verdicts = new Map<string, { boxId: string; why: RecoveryVerdict; at: number }>();+ const judge = (owner: string, boxId: string, why: RecoveryVerdict) => verdicts.set(owner, { boxId, why, at: now() });const states = new Map<string, CloudComputerRecovery & { boxId: string }>();const lanes = new Map<string, Promise<unknown>>();const restarts = new Map<string, number>();@@ -108,6 +132,8 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {deps.changed?.(owner);};const clear = (owner: string, boxId: string) => {+ if (verdicts.get(owner)?.boxId === boxId) verdicts.delete(owner);+ restoringSince.delete(boxId);told.delete(boxId);errorSeen.delete(boxId);if (states.get(owner)?.boxId !== boxId) return;@@ -122,8 +148,10 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {lines.add(line);deps.tell(owner, line);};- const needsPerson = (owner: string, boxId: string) =>+ const needsPerson = (owner: string, boxId: string) => {+ if (!eligible(owner)) judge(owner, boxId, "shared");tellOnce(owner, boxId, "needs-person", eligible(owner) ? "needsPerson" : "teamNotResponding");+ };const personBusy = (owner: string, boxId: string) =>deps.personActive?.(owner) === true || health.personUsedWithin(boxId, DEAD_COMPUTER.personGraceMs);/** The provider's `error`, seen now: true once it was also seen at least DEAD_COMPUTER.deadConfirmMs earlier. */@@ -147,6 +175,7 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {const cfg = deps.cfg();set(owner, boxId, "restarting", manual);restarts.set(boxId, now());+ const started = now();try {const stopped = await boat.boatFetch(cfg, `/sandboxes/${boxId}/stop`, { method: "POST", signal: AbortSignal.timeout(30_000) });await stopped.body?.cancel().catch(() => undefined);@@ -162,7 +191,10 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {}const woken = await boat.readyBoat(cfg, owner, WAKE_BUDGET_MS).catch(() => null);if (!woken || woken.id !== boxId) return "no-answer";- if ((await boat.probeBoat(cfg, boxId)) !== true) return "no-answer";+ // The provider reports a resumed computer ready before it answers, so one probe right after the resume proves nothing.+ const answer = await readiness.awaitAnswer(cfg, boxId, { woke: true, ...(manual ? { deadline: now() + MANUAL_ANSWER_WAIT_MS } : {}) });+ cloudComputerCounters.count(boxId, "restarts", now() - started);+ if (!answer.ok) return "no-answer";health.answered(boxId);return "answers";}@@ -239,8 +271,11 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {return outcome;}- /** A fresh probe that got no answer, with the provider's list working; null when that is not so (the outcome is reported). */- async function stillDown(owner: string, boxId: string, cfg: AppConfig): Promise<boolean> {+ /** A fresh probe that got no answer, with the provider's list working; false when that is not so (the outcome is+ * reported). `witness`: before a delete, another computer of this installation must have answered as well. A restart+ * keeps the files, so the provider's own list answering is enough for it: an installation with one computer in use has+ * no witness, and would otherwise never be restarted. */+ async function stillDown(owner: string, boxId: string, cfg: AppConfig, witness = true): Promise<boolean> {const probe = await boat.probeBoat(cfg, boxId);if (probe !== false) {if (probe) health.answered(boxId);@@ -249,7 +284,7 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {}if (!(await listWorks(cfg))) { unreachable(owner, boxId); return false; }// An installation whose other computers do not answer either cannot tell a dead machine from its own outage.- if (!health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs)) { needsPerson(owner, boxId); return false; }+ if (witness && !health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs)) { needsPerson(owner, boxId); return false; }return true;}@@ -288,10 +323,42 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {return clear(owner, boxId);}// Every guard before a stop: it closes the person's programs, and three failed probes can be this home's own outage.- if (!(await stillDown(owner, boxId, cfg))) return;+ if (!(await stillDown(owner, boxId, cfg, false))) return;+ const since = Math.min(health.notRespondingSince(boxId) ?? now(), restoringSince.get(boxId) ?? now());+ restoringSince.set(boxId, since);+ /** Looks again shortly instead of restarting now. */+ const later = (state: "restoring" | "not-responding") => {+ set(owner, boxId, state);+ const timer = setTimeout(() => {+ timers.delete(owner);+ if (!closed) void lane(owner, () => notResponding(owner, boxId)).catch((error) => deps.log(`cloud computer ${owner}: ${String(error)}`));+ }, recheckMs);+ timer.unref?.();+ timers.set(owner, timer);+ };+ // The provider's command gateway can fail for every computer while its API still calls each one ready. Then a+ // restart helps nobody and stops work that is still running, so one is made only when this computer alone is silent.+ const witnessed = health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs);+ if (!witnessed && health.othersSilentWithin(boxId, DEAD_COMPUTER.witnessMs)) {+ deps.log(`cloud computer ${owner}: ${boxId} is not responding, and neither are this installation's other computers; nothing was restarted`);+ return unreachable(owner, boxId);+ }+ const box = await read(cfg, boxId);+ const state = box && typeof box === "object" ? (box as { state?: unknown }).state : undefined;+ // A state that could not be read is unknown, never a reason to restart.+ if (typeof state !== "string" || !READY.has(state)) return now() - since < DEAD_COMPUTER.replaceAfterMs ? later("not-responding") : decide(owner, boxId);+ if (boatSignals(box).restoring === true && now() - since < READY_WAIT.restorePatienceMs) return later("restoring");+ if (!witnessed && now() - since < SOLO_SILENCE_MS) return later("not-responding");const lastRestart = restarts.get(boxId);- if ((lastRestart === undefined || now() - lastRestart >= HOUR_MS) && now() - lastAutoRestartAt >= DEAD_COMPUTER.restartGapMs && !personBusy(owner, boxId)) {+ const limited = (lastRestart !== undefined && now() - lastRestart < HOUR_MS) || now() - lastAutoRestartAt < DEAD_COMPUTER.restartGapMs;+ if (limited || personBusy(owner, boxId)) {+ // A restart that just failed stays the reason: it says more than the limit that restart itself set off.+ const failed = verdicts.get(owner);+ if (!(limited && failed?.boxId === boxId && failed.why === "restart-failed")) judge(owner, boxId, limited ? "restart-limited" : "person-busy");+ deps.log(`cloud computer ${owner}: ${boxId} is not responding and was not restarted: ${limited ? "a restart was made too recently" : "a person is using it"}`);+ } else {lastAutoRestartAt = now();+ deps.log(`cloud computer ${owner}: ${boxId} is not responding though the provider reports it ready; restarting it`);const restarted = await restart(owner, boxId);if (restarted === "answers") {set(owner, boxId, "restarted");@@ -303,6 +370,8 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {restartedOwners.add(owner);return;}+ judge(owner, boxId, "restart-failed");+ deps.log(`cloud computer ${owner}: ${boxId} still does not answer after a restart`);}return decide(owner, boxId);}@@ -353,6 +422,8 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {if (retired.has(boxId)) return CLOUD_COMPUTER_NOT_RESPONDING;const owner = boat.boatOwnerOf(boxId);const found = owner ? states.get(owner) : undefined;+ if (found?.boxId === boxId && found.state === "restarting") return phase === "before" ? CLOUD_COMPUTER_RESTARTING : CLOUD_COMPUTER_RESTARTING_UNANSWERED;+ if (found?.boxId === boxId && found.state === "restoring") return phase === "before" ? CLOUD_COMPUTER_RESTORING : CLOUD_COMPUTER_STILL_RESTORING;if (found?.boxId === boxId && recoveryUnderWay(found.state)) return CLOUD_COMPUTER_NOT_RESPONDING;if (phase === "before") return null;if (found?.boxId === boxId && found.state === "unreachable") return CLOUD_COMPUTER_UNREACHABLE;@@ -384,6 +455,12 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {return (state !== undefined && state !== "restarted" && state !== "replaced") || boat.deadBoatOf(owner) !== null|| (box !== null && health.notRespondingSince(box) !== null);},+ /** Why this owner's computer, not answering, was left as it is; null while that is not decided, once it answers, or+ * when it was decided before `since`. Written before the state moves to one that has ended. */+ verdict: (owner: string, since = -Infinity): RecoveryVerdict | null => {+ const found = verdicts.get(owner);+ return found && found.at >= since ? found.why : null;+ },/** The panel's Restart computer: the same restart the automatic path tries first. */async restart(owner: string): Promise<{ answers: boolean }> {const found = await boat.findBoat(deps.cfg(), owner);diff --git a/server/boat.ts b/server/boat.tsindex 160c4b568c..92323d5bc9 100644--- a/server/boat.ts+++ b/server/boat.ts@@ -7,7 +7,7 @@ import { createHash } from "node:crypto";import { DATA_DIR, type AppConfig } from "./config.ts";import { loadEnvironmentId } from "./environment.ts";import { boatCredential, boatProviderApi, type ServiceCredential } from "./included-services.ts";-import { relayBody, relayPath } from "./boat-relay.ts";+import { relayBody, relayPath } from "./boat-relay.ts"; import { COMMAND_WALL, runToEnd, type CommandOutcome } from "./boat-command.ts";import { boatHealth, DEAD_COMPUTER, unansweredStatus } from "./boat-health.ts";import { CLOUD_COMPUTER_NO_ANSWER } from "../shared/cloud-computer-recovery.ts";import { cloudLimitFromBody, type CloudLimit } from "../shared/place-view.ts";@@ -350,9 +350,9 @@ export async function boatNameMatchesBot(botId: string, name: string): Promise<breturn name === await boatNameFor(botId) || name === legacyBoatNameFor(botId);}-/** `probe`: the health check itself, which records nothing; any other command that gets no answer starts one. */-export async function runCommand(cfg: AppConfig, boxId: string, command: string, { timeoutMs = 120_000, signal, probe = false }: { timeoutMs?: number; signal?: AbortSignal; probe?: boolean } = {}) {- assertBoatNotDeleting(boxId);+/** `probe`: the health check itself, which records nothing; any other command that gets no answer starts one. A command given more than COMMAND_WALL.syncSafeMs is started detached and followed to its end (boat-command.ts). */+export async function runCommand(cfg: AppConfig, boxId: string, command: string, { timeoutMs = 120_000, signal, probe = false }: { timeoutMs?: number; signal?: AbortSignal; probe?: boolean } = {}): Promise<CommandOutcome> {+ assertBoatNotDeleting(boxId); if (!probe && timeoutMs > COMMAND_WALL.syncSafeMs) return runToEnd(cfg, boxId, command, { timeoutMs, signal });const suspect = () => { if (!probe && !signal?.aborted) boatHealth.suspect(boxId, () => probeBoat(cfg, boxId)); };const res = await boatFetch(cfg, `/sandboxes/${boxId}/commands`, { method: "POST", body: JSON.stringify({ command }),signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) }).catch((error: unknown) => { suspect(); throw error; });@@ -361,7 +361,7 @@ export async function runCommand(cfg: AppConfig, boxId: string, command: string,if (unanswered) suspect(); else if (!probe && res.ok && typeof body?.exitCode === "number") boatHealth.answered(boxId);return {ok: res.ok && body?.exitCode === 0, exitCode: body?.exitCode ?? null, stdout: body?.stdout ?? "",- stderr: body?.stderr ?? "", ...(body?.timedOut === true ? { timedOut: true as const } : {}), ...(unanswered ? { unanswered: true as const } : {}),+ stderr: body?.stderr ?? "", ...(body?.timedOut === true ? { timedOut: true as const, providerLimit: true as const } : {}), ...(unanswered ? { unanswered: true as const } : {}), ...(res.status === 503 ? { busy: true as const } : {}),};}@@ -1243,7 +1243,7 @@ export async function screenshotBoat(cfg: AppConfig, botId: string, knownBoatId?}const framePath = options?.nativeSize ? PANEL_PATH + ".model.jpg" : PANEL_PATH;const out = await runCommand(cfg, boxId, options?.nativeSize ? panelShotCommand({ framePath, nativeSize: true }) : SHOT_CMD,- { timeoutMs: 60_000, signal: options?.signal });+ { timeoutMs: 25_000, signal: options?.signal });if (!/captured/.test(out.stdout)) {throw new Error(out.unanswered ? CLOUD_COMPUTER_NO_ANSWER : out.stderr.slice(0, 200) || "screen capture failed on the cloud computer");}diff --git a/server/cloud-computer-background.test.ts b/server/cloud-computer-background.test.tsindex f1af38383d..755d1af4b8 100644--- a/server/cloud-computer-background.test.ts+++ b/server/cloud-computer-background.test.ts@@ -403,8 +403,11 @@ describe.each([expect(background.EXEC_LATE).toMatch(/may still be running.*do not run it again blindly.*background: true.*exec_status/s);server.closeAllConnections();hold = false;- syncReply = { exitCode: null, stdout: "", stderr: "", timedOut: true };- expect(await call("exec", { command: "sleep 600" }).done).toEqual({ isError: true, content: [{ type: "text", text: background.EXEC_LATE }] });+ // A relay that does not forward the detached flag runs the command itself, and the provider stops it at its limit.+ startReply = { status: 200, body: { exitCode: 143, signal: "SIGTERM", stdout: "", stderr: "", timedOut: true } };+ const stopped = await call("exec", { command: "sleep 600" }).done;+ expect(stopped).toEqual({ isError: true, content: [{ type: "text", text: (await import("./cloud-computer-tools.ts")).EXEC_STOPPED_AT_LIMIT }] });+ expect((stopped as { content: Array<{ text: string }> }).content[0]!.text).toMatch(/stopped this command after 30 seconds.*no longer running.*background: true/s);expect(calls.filter(entry => entry.method === "POST")).toHaveLength(2);});diff --git a/server/cloud-computer-background.ts b/server/cloud-computer-background.tsindex 43c0ce6a3b..f900159646 100644--- a/server/cloud-computer-background.ts+++ b/server/cloud-computer-background.ts@@ -4,6 +4,7 @@import { createHash } from "node:crypto";import { setTimeout as delay } from "node:timers/promises";import { assertBoatNotDeleting, boatAccount, boatErrorMessage, boatFetch, isolatedRemoteCommand } from "./boat.ts";+import { processMayStillRun, trackedProcesses, trackProcess, untrackProcess } from "./boat-command.ts";import type { CloudComputerResult } from "./cloud-computer-tools.ts";import type { AppConfig } from "./config.ts";@@ -16,7 +17,6 @@ const POLL_MS = 2_000;const MAX_LAST_READ_WINDOW_MS = 1_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;@@ -77,36 +77,11 @@ 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;- }-}+const track = trackProcess, untrack = untrackProcess;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;+ for (const [processId, at] of trackedProcesses(boxId)) {+ if (Date.now() - at < BACKGROUND_KEEPS_AWAKE_MS && await processMayStillRun(cfg, boxId, processId, AWAKE_CHECK_MS)) return true;untrack(boxId, processId);}return false;diff --git a/server/cloud-computer-counters.test.ts b/server/cloud-computer-counters.test.tsnew file mode 100644index 0000000000..01f364bbc8--- /dev/null+++ b/server/cloud-computer-counters.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";++import { createCloudComputerCounters } from "./cloud-computer-counters.ts";+import { buildDevsReport } from "./devs-report.ts";++describe("cloud computer counts", () => {+ it("keeps numbers and waiting time per computer, and says them in one line each, most recent first", () => {+ let at = Date.UTC(2026, 10, 14, 10, 0, 0);+ const counters = createCloudComputerCounters(() => at);+ counters.count("bx_aaaaaaaa", "wakes", 41_200);+ counters.count("bx_aaaaaaaa", "unanswered");+ counters.count("bx_aaaaaaaa", "unanswered");+ counters.count("bx_aaaaaaaa", "resent");+ at += 60_000;+ counters.count("bx_bbbbbbbb", "restoreWaits", 312_000);+ counters.count("bx_bbbbbbbb", "restarts", 20_000);+ expect(counters.lines()).toEqual([+ "bx_bbbbbbbb: 1 waits on a disk restore (312s in all), 1 restarts (20s in all); last 2026-11-14T10:01:00.000Z",+ "bx_aaaaaaaa: 1 waits for an answer after waking (41s in all), 2 calls unanswered, 1 calls sent again; last 2026-11-14T10:00:00.000Z",+ ]);+ expect(counters.snapshot("bx_aaaaaaaa")).toMatchObject({ unanswered: 2, lostAnswers: 0 });+ });++ it("keeps at most twenty computers, dropping the one heard from longest ago", () => {+ let at = 0;+ const counters = createCloudComputerCounters(() => at++);+ for (let index = 0; index < 21; index++) counters.count(`bx_${String(index).padStart(8, "0")}`, "wakes");+ expect(counters.lines()).toHaveLength(20);+ expect(counters.snapshot("bx_00000000")).toBeNull();+ });++ it("reach the bug report's diagnostics, and only when there is something to say", () => {+ const input = {+ installId: "install", appVersion: "0.0.0", platform: "darwin", os: "darwin", runsOn: "desktop", node: "v0", uptimeSeconds: 60, now: 0,+ threadId: "thread", messageId: "message", where: "a chat", message: "@devs the computer got stuck", bots: [], problems: [], log: [], noSummary: "none",+ } as unknown as Parameters<typeof buildDevsReport>[0];+ expect(buildDevsReport(input, []).diagnostics).not.toContain("Cloud computers since the server started");+ const report = buildDevsReport({ ...input, cloudComputers: ["bx_aaaaaaaa: 52 calls unanswered; last 2026-11-14T10:00:00.000Z"] }, []);+ expect(report.diagnostics).toContain("## Cloud computers since the server started\nbx_aaaaaaaa: 52 calls unanswered");+ });+});diff --git a/server/cloud-computer-counters.ts b/server/cloud-computer-counters.tsnew file mode 100644index 0000000000..f073e66fb1--- /dev/null+++ b/server/cloud-computer-counters.ts@@ -0,0 +1,58 @@+/** How often each cloud computer was woken, waited for, went unanswered, was sent a call again or was restarted, since the+ * server started. Security: only the provider's opaque computer id and numbers are kept, never a command or its output,+ * so the lines are safe in a bug report. */+export type CloudComputerCount = "wakes" | "restoreWaits" | "unanswered" | "resent" | "lostAnswers" | "restarts";++interface Row {+ counts: Record<CloudComputerCount, number>;+ /** Milliseconds spent waiting, by what was waited for. */+ waited: { wakes: number; restoreWaits: number; restarts: number };+ lastAt: number;+}++const MAX_COMPUTERS = 20;+const LABELS: Array<[CloudComputerCount, string]> = [+ ["wakes", "waits for an answer after waking"], ["restoreWaits", "waits on a disk restore"], ["unanswered", "calls unanswered"],+ ["resent", "calls sent again"], ["lostAnswers", "answers lost after the call ran"], ["restarts", "restarts"],+];++export function createCloudComputerCounters(now: () => number = Date.now) {+ const rows = new Map<string, Row>();++ function count(boxId: string, what: CloudComputerCount, waitedMs = 0): void {+ let row = rows.get(boxId);+ if (!row) {+ if (rows.size >= MAX_COMPUTERS) {+ const oldest = [...rows].sort(([, a], [, b]) => a.lastAt - b.lastAt)[0];+ if (oldest) rows.delete(oldest[0]);+ }+ rows.set(boxId, row = {+ counts: { wakes: 0, restoreWaits: 0, unanswered: 0, resent: 0, lostAnswers: 0, restarts: 0 },+ waited: { wakes: 0, restoreWaits: 0, restarts: 0 }, lastAt: now(),+ });+ }+ row.counts[what] += 1;+ if (what in row.waited) row.waited[what as keyof Row["waited"]] += Math.max(0, Math.round(waitedMs));+ row.lastAt = now();+ }++ return {+ count,+ snapshot: (boxId: string): Row["counts"] | null => rows.get(boxId)?.counts ?? null,+ /** One line per computer, most recent first. */+ lines(): string[] {+ return [...rows].sort(([, a], [, b]) => b.lastAt - a.lastAt).map(([boxId, row]) => {+ const parts = LABELS.filter(([key]) => row.counts[key] > 0).map(([key, label]) => {+ const waited = key in row.waited ? row.waited[key as keyof Row["waited"]] : 0;+ return `${row.counts[key]} ${label}${waited ? ` (${Math.round(waited / 1_000)}s in all)` : ""}`;+ });+ return `${boxId}: ${parts.join(", ")}; last ${new Date(row.lastAt).toISOString()}`;+ });+ },+ clear: () => rows.clear(),+ };+}++export type CloudComputerCounters = ReturnType<typeof createCloudComputerCounters>;++export const cloudComputerCounters = createCloudComputerCounters();diff --git a/server/cloud-computer-once.test.ts b/server/cloud-computer-once.test.tsnew file mode 100644index 0000000000..d15b9331c3--- /dev/null+++ b/server/cloud-computer-once.test.ts@@ -0,0 +1,268 @@+// The claim script is run for real, by this machine's own sh in a throwaway folder, standing in for the computer's shell.+import { execFileSync, spawn } from "node:child_process";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { onceCommand, RESEND, retryRead, runOnce, stopCommand, type OnceDeps } from "./cloud-computer-once.ts";+import { createCloudComputerCounters } from "./cloud-computer-counters.ts";+import type { AppConfig } from "./config.ts";++const cfg = {} as AppConfig;+const BOX = "bx_23456789";+const KEY = "0123456789abcdef";+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++/** A computer: one folder for its disk, and a log each run of the user's command appends to. */+function computer() {+ const root = mkdtempSync(join(tmpdir(), "omb-once-"));+ dirs.push(root);+ const log = join(root, "ran.log");+ const claims = { disk: join(root, "disk", "omb-once"), memory: join(root, "shm", "omb-once") };+ const sh = (script: string) => {+ try {+ return { exitCode: 0, stdout: execFileSync("/bin/sh", ["-c", script], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) };+ } catch (error) {+ const failed = error as { status?: number; stdout?: string };+ return { exitCode: failed.status ?? 1, stdout: failed.stdout ?? "" };+ }+ };+ return {+ root, claims, log, sh,+ command: `echo ran >> '${log}'; echo done`,+ runs: () => (existsSync(log) ? readFileSync(log, "utf8").split("\n").filter(Boolean).length : 0),+ };+}++describe("a call's claim on the computer", () => {+ it("lets the first copy of a call run and stops every later copy before the command", () => {+ const pc = computer();+ const first = pc.sh(onceCommand(KEY, 1, pc.command, pc.claims));+ expect(first).toEqual({ exitCode: 0, stdout: "done\n" });+ const late = pc.sh(onceCommand(KEY, 1, pc.command, pc.claims));+ const resent = pc.sh(onceCommand(KEY, 2, pc.command, pc.claims));+ expect(late).toEqual({ exitCode: 75, stdout: `omb-once:${KEY}:taken\n` });+ expect(resent).toEqual(late);+ expect(pc.runs()).toBe(1);+ });++ it("gives each call its own claim", () => {+ const pc = computer();+ pc.sh(onceCommand(KEY, 1, pc.command, pc.claims));+ expect(pc.sh(onceCommand("fedcba9876543210", 1, pc.command, pc.claims)).exitCode).toBe(0);+ expect(pc.runs()).toBe(2);+ });++ it("claims in memory when the disk refuses, and a later copy still finds that claim", () => {+ const pc = computer();+ writeFileSync(join(pc.root, "disk"), "a file where the folder would go");+ expect(pc.sh(onceCommand(KEY, 2, pc.command, pc.claims)).exitCode).toBe(0);+ expect(pc.sh(onceCommand(KEY, 2, pc.command, pc.claims)).exitCode).toBe(75);+ expect(pc.runs()).toBe(1);+ });++ it("with nowhere to claim, runs a first send as it always did and never runs a resend", () => {+ const pc = computer();+ writeFileSync(join(pc.root, "disk"), "");+ writeFileSync(join(pc.root, "shm"), "");+ expect(pc.sh(onceCommand(KEY, 2, pc.command, pc.claims))).toEqual({ exitCode: 76, stdout: `omb-once:${KEY}:unclaimed\n` });+ expect(pc.runs()).toBe(0);+ expect(pc.sh(onceCommand(KEY, 1, pc.command, pc.claims)).exitCode).toBe(0);+ expect(pc.runs()).toBe(1);+ });++ it("passes the command's own exit code and output through", () => {+ const pc = computer();+ expect(pc.sh(onceCommand(KEY, 1, "echo out; exit 3", pc.claims))).toEqual({ exitCode: 3, stdout: "out\n" });+ });++ it("refuses a key that is not its own kind, since the key is written into the shell", () => {+ expect(() => onceCommand("$(reboot)", 1, "true")).toThrow(RangeError);+ });+});++describe("stopping the command a call started", () => {+ const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };+ const until = async (check: () => boolean, ms = 10_000) => {+ for (const end = Date.now() + ms; Date.now() < end; await new Promise((resolve) => setTimeout(resolve, 25))) if (check()) return true;+ return false;+ };++ it("ends the command and what it started, by the process id the call recorded, and nothing else", async () => {+ const pc = computer();+ const bystander = spawn("/bin/sh", ["-c", "sleep 30"], { stdio: "ignore" });+ const shell = spawn("/bin/sh", ["-c", onceCommand(KEY, 1, "sleep 30 & sleep 30; wait", pc.claims)], { stdio: "ignore" });+ const pidFile = join(pc.claims.disk, KEY, "pid");+ expect(await until(() => existsSync(pidFile) && readFileSync(pidFile, "utf8").trim() !== "")).toBe(true);+ expect(Number(readFileSync(pidFile, "utf8"))).toBe(shell.pid);+ const children = () => execFileSync("/bin/sh", ["-c", `pgrep -P ${shell.pid} || true`], { encoding: "utf8" }).split("\n").filter(Boolean).map(Number);+ expect(await until(() => children().length >= 1)).toBe(true);+ const started = children();+ expect(pc.sh(stopCommand(KEY, pc.claims)).exitCode).toBe(0);+ expect(await until(() => !alive(shell.pid!) && started.every((pid) => !alive(pid)))).toBe(true);+ expect(alive(bystander.pid!)).toBe(true);+ bystander.kill();+ });++ it("does nothing, quietly, for a call that recorded no process", () => {+ const pc = computer();+ expect(pc.sh(stopCommand(KEY, pc.claims))).toEqual({ exitCode: 0, stdout: "" });+ expect(() => stopCommand("$(reboot)")).toThrow(RangeError);+ });+});++type Sent = { ok: boolean; exitCode: number | null; stdout: string; stderr: string; unanswered?: true; busy?: true };+const UNANSWERED: Sent = { ok: false, exitCode: null, stdout: "", stderr: "", unanswered: true };++/** `gateway(send)` decides, per send, whether the command reaches the computer and whether its answer comes back. */+function relay(gateway: (send: number) => { delivered: boolean; answered: boolean; status?: 503 }, answersProbe: () => boolean = () => true) {+ const pc = computer();+ const counters = createCloudComputerCounters();+ let at = 0, sends = 0, probes = 0;+ const waits: number[] = [];+ const deps: Partial<OnceDeps> = {+ key: () => KEY, counters, now: () => at, random: () => 0.5,+ sleep: async (ms) => { waits.push(ms); at += ms; },+ run: async (_cfg, _box, script) => {+ const { delivered, answered, status } = gateway(sends++);+ // What reaches the computer is the script with the test's own claim folders in place of the real ones.+ const out = delivered ? pc.sh(script.replace('a="${HOME:-/tmp}/.cache/omb-once"; b="/dev/shm/omb-once"', `a="${pc.claims.disk}"; b="${pc.claims.memory}"`)) : null;+ if (status === 503) return { ok: false, exitCode: null, stdout: "", stderr: "", busy: true as const };+ if (!answered || !out) return UNANSWERED;+ return { ok: out.exitCode === 0, exitCode: out.exitCode, stdout: out.stdout, stderr: "" };+ },+ awaitAnswer: async () => {+ probes++;+ at += 4_000;+ return answersProbe() ? { ok: true, waitedMs: 4_000 } : { ok: false, phase: "restoring", waitedMs: 90_000 };+ },+ };+ const call = () => runOnce(cfg, BOX, pc.command, { signal: new AbortController().signal, deadline: 120_000 }, deps);+ return { pc, call, counters, sends: () => sends, probes: () => probes, waits };+}++describe("a call the computer did not answer", () => {+ it("is sent again once the computer answers a probe, and runs once when the first copy never arrived", async () => {+ const r = relay((send) => ({ delivered: send > 0, answered: send > 0 }));+ const outcome = await r.call();+ expect(outcome).toMatchObject({ kind: "ran", resent: 1, result: { ok: true, stdout: "done\n" } });+ expect(r.pc.runs()).toBe(1);+ expect(r.probes()).toBe(1);+ expect(r.counters.snapshot(BOX)).toMatchObject({ unanswered: 1, resent: 1 });+ });++ it("is not run a second time when the first copy did arrive and only its answer was lost", async () => {+ const r = relay((send) => ({ delivered: true, answered: send > 0 }));+ await expect(r.call()).resolves.toEqual({ kind: "lost" });+ expect(r.pc.runs()).toBe(1);+ expect(r.counters.snapshot(BOX)).toMatchObject({ lostAnswers: 1 });+ });++ it("is not run a second time when the first copy arrives late, after the resend already ran", async () => {+ const r = relay((send) => ({ delivered: send > 0, answered: send > 0 }));+ await r.call();+ // The hung first send finally reaches the machine.+ const late = r.pc.sh(onceCommand(KEY, 1, r.pc.command, r.pc.claims));+ expect(late.exitCode).toBe(75);+ expect(r.pc.runs()).toBe(1);+ });++ it("rides out a burst of gateway errors with a growing, varied pause, within its three resends", async () => {+ const r = relay((send) => ({ delivered: send === 3, answered: send === 3 }));+ await expect(r.call()).resolves.toMatchObject({ kind: "ran", resent: 3 });+ expect(r.waits).toEqual(RESEND.backoffMs);+ expect(r.pc.runs()).toBe(1);+ });++ it("stops after three resends and says the computer did not answer", async () => {+ const r = relay(() => ({ delivered: false, answered: false }));+ await expect(r.call()).resolves.toEqual({ kind: "unanswered", phase: "waking" });+ expect(r.sends()).toBe(1 + RESEND.max);+ expect(r.pc.runs()).toBe(0);+ });++ it("does not send again while the computer still gives no answer, and says what it is waiting on", async () => {+ const r = relay(() => ({ delivered: false, answered: false }), () => false);+ await expect(r.call()).resolves.toEqual({ kind: "unanswered", phase: "restoring" });+ expect(r.sends()).toBe(1);+ });++ it("sends again after a 503, and reports cloud computers as unreachable when it never clears", async () => {+ const clears = relay((send) => send === 0 ? { delivered: false, answered: false, status: 503 } : { delivered: true, answered: true });+ await expect(clears.call()).resolves.toMatchObject({ kind: "ran", resent: 1 });+ const stays = relay(() => ({ delivered: false, answered: false, status: 503 }));+ await expect(stays.call()).resolves.toEqual({ kind: "unanswered", phase: "unreachable" });+ });++ it("returns a command that ran and failed as it is, with no resend", async () => {+ const pc = computer();+ let sends = 0;+ const outcome = await runOnce(cfg, BOX, "exit 2", { signal: new AbortController().signal, deadline: Date.now() + 60_000 }, {+ key: () => KEY,+ run: async (_cfg, _box, script) => { sends++; const out = pc.sh(script.replace(/a="[^"]*"; b="[^"]*"/, `a="${pc.claims.disk}"; b="${pc.claims.memory}"`)); return { ok: false, exitCode: out.exitCode, stdout: out.stdout, stderr: "" }; },+ });+ expect(outcome).toMatchObject({ kind: "ran", resent: 0, result: { exitCode: 2 } });+ expect(sends).toBe(1);+ });++ it("answers that the call ran out of time, not a raw error, when a send hangs with no reply until the call's time is up", async () => {+ let at = 0;+ const outcome = await runOnce(cfg, BOX, "make", { signal: new AbortController().signal, deadline: 120_000 }, {+ key: () => KEY, now: () => at,+ run: async (_cfg, _box, _script, opts) => { at += opts.timeoutMs!; throw Object.assign(new Error("The operation was aborted due to timeout"), { name: "TimeoutError" }); },+ });+ expect(outcome).toEqual({ kind: "late" });+ });++ it("stops the command it was following when the person stops the turn, and not when only the call's time runs out", async () => {+ const sentFor = async (stoppedByPerson: boolean) => {+ const turn = new AbortController(), call = new AbortController();+ const sent: string[] = [];+ const pending = runOnce(cfg, BOX, "make", { signal: AbortSignal.any([turn.signal, call.signal]), deadline: Date.now() + 120_000, stopped: turn.signal }, {+ key: () => KEY,+ run: async (_cfg, _box, script, opts) => {+ sent.push(script);+ if (script === stopCommand(KEY)) return { ok: true, exitCode: 0, stdout: "", stderr: "" };+ await new Promise<void>((_resolve, reject) => opts.signal!.addEventListener("abort", () => reject(opts.signal!.reason)));+ throw new Error("unreachable");+ },+ });+ const rejected = expect(pending).rejects.toBeDefined();+ await new Promise((resolve) => setTimeout(resolve, 10));+ (stoppedByPerson ? turn : call).abort();+ await rejected;+ await new Promise((resolve) => setTimeout(resolve, 10));+ return sent.includes(stopCommand(KEY));+ };+ expect(await sentFor(true)).toBe(true);+ expect(await sentFor(false)).toBe(false);+ });++ it("does not treat a refusal thrown before the send as the computer's silence", async () => {+ const refusal = Object.assign(new Error("this cloud computer is being deleted"), { status: 409 });+ await expect(runOnce(cfg, BOX, "true", { signal: new AbortController().signal, deadline: Date.now() + 60_000 }, {+ run: async () => { throw refusal; },+ })).rejects.toBe(refusal);+ });+});++describe("a read the computer did not answer", () => {+ const options = { signal: new AbortController().signal, deadline: 120_000 };+ const quick: Partial<OnceDeps> = { now: () => 0, sleep: async () => {}, random: () => 0.5, counters: createCloudComputerCounters() };++ it("is tried again once the computer answers", async () => {+ let reads = 0;+ const read = async () => { if (reads++ < 2) throw new Error("no answer"); return "frame"; };+ await expect(retryRead(cfg, BOX, read, () => true, options, { ...quick, awaitAnswer: async () => ({ ok: true, waitedMs: 0 }) })).resolves.toEqual({ value: "frame" });+ expect(reads).toBe(3);+ });++ it("says what it was waiting on when the computer never answers, and passes any other error on", async () => {+ await expect(retryRead(cfg, BOX, async () => { throw new Error("no answer"); }, () => true, options,+ { ...quick, awaitAnswer: async () => ({ ok: false, phase: "restoring", waitedMs: 0 }) })).resolves.toEqual({ phase: "restoring" });+ const other = new Error("screen capture failed");+ await expect(retryRead(cfg, BOX, async () => { throw other; }, () => false, options, quick)).rejects.toBe(other);+ });+});diff --git a/server/cloud-computer-once.ts b/server/cloud-computer-once.tsnew file mode 100644index 0000000000..934b402b25--- /dev/null+++ b/server/cloud-computer-once.ts@@ -0,0 +1,186 @@+// A call that got no answer when it was sent (a gateway's 502, a dropped connection) may or may not have reached the+// machine, and a copy that hung can still be delivered after the caller gave up. A long command is followed by its+// processId once it has started (boat-command.ts), which settles whether it ran; a short one, and the start of a long+// one, return nothing to look up, and this app knows of no idempotency key for them (unverified against Boat's own+// docs; nothing here depends on one). So each call carries its own key and claims it on the computer with `mkdir`,+// which is atomic: whichever copy arrives first runs, and every other copy, however late, stops before the command.+// A call is sent again only on that footing.+import { randomBytes } from "node:crypto";+import { setTimeout as delay } from "node:timers/promises";++import { transientClaimFailure } from "./auto-vm-claims.ts";+import { runCommand } from "./boat.ts";+import type { CommandOutcome } from "./boat-command.ts";+import { boatReadiness, type BoatAnswer, type BoatWaitPhase } from "./boat-ready.ts";+import { cloudComputerCounters, type CloudComputerCounters } from "./cloud-computer-counters.ts";+import type { AppConfig } from "./config.ts";++export const RESEND = {+ /** A call is sent again at most this many times. */+ max: 3,+ /** Before each resend, after the computer answered a probe; each varies by a quarter either way. */+ backoffMs: [1_000, 3_000, 8_000],+ jitter: 0.25,+ /** Left of the call's own time for the answer to reach the bot. */+ reserveMs: 5_000,+} as const;++const STOP_MS = 10_000;+const TAKEN_EXIT = 75;+const UNCLAIMED_EXIT = 76;+const KEY = /^[0-9a-f]{16}$/;+const takenMark = (key: string) => `omb-once:${key}:taken`;+const unclaimedMark = (key: string) => `omb-once:${key}:unclaimed`;++/** Shell words, expanded on the computer. */+const CLAIM_DIRS = { disk: "${HOME:-/tmp}/.cache/omb-once", memory: "/dev/shm/omb-once" };++export const newCallKey = (): string => randomBytes(8).toString("hex");++/** `command` behind its claim. The claim lives on the computer's disk, which outlasts a stop and resume, and in+ * /dev/shm when the disk refuses it (full, read-only). A first send runs even with no claim, as it always did; a+ * resend that cannot claim does not run. */+export function onceCommand(key: string, attempt: number, command: string, dirs: { disk: string; memory: string } = CLAIM_DIRS): string {+ if (!KEY.test(key)) throw new RangeError("a call key is 16 hex characters");+ return [+ `k=${key}; a="${dirs.disk}"; b="${dirs.memory}"`,+ `taken() { echo ${takenMark(key)}; exit ${TAKEN_EXIT}; }`,+ 'if [ -d "$a/$k" ] || [ -d "$b/$k" ]; then taken; fi',+ 'mkdir -p "$a" 2>/dev/null',+ 'if ! mkdir "$a/$k" 2>/dev/null; then',+ ' if [ -d "$a/$k" ]; then taken; fi',+ ' mkdir -p "$b" 2>/dev/null',+ ' if ! mkdir "$b/$k" 2>/dev/null; then',+ ' if [ -d "$b/$k" ]; then taken; fi',+ attempt > 1 ? ` echo ${unclaimedMark(key)}; exit ${UNCLAIMED_EXIT}` : " :",+ " fi",+ "fi",+ // The shell's own process id, kept beside the claim: `exec` below keeps it, so it names the command.+ 'echo $$ > "$a/$k/pid" 2>/dev/null || echo $$ > "$b/$k/pid" 2>/dev/null',+ ...(key.endsWith("0") ? ['find "$a" "$b" -mindepth 1 -maxdepth 1 -type d -mmin +1440 -exec rmdir {} + 2>/dev/null'] : []),+ command,+ ].join("\n");+}++/** Ends the command a call started and everything it started, by the process id the call recorded: Boat has no call+ * this app knows of that stops a command by its processId (unverified). Only that process and its descendants are+ * signalled, never a process group, which could hold the computer's own agent. */+export function stopCommand(key: string, dirs: { disk: string; memory: string } = CLAIM_DIRS): string {+ if (!KEY.test(key)) throw new RangeError("a call key is 16 hex characters");+ return [+ `k=${key}; p=; for d in "${dirs.disk}" "${dirs.memory}"; do if [ -f "$d/$k/pid" ]; then p=$(cat "$d/$k/pid"); break; fi; done`,+ '[ -n "$p" ] || exit 0',+ 'stop() { for c in $(pgrep -P "$1" 2>/dev/null); do stop "$c"; done; kill -TERM "$1" 2>/dev/null; }',+ 'stop "$p"; exit 0',+ ].join("\n");+}++type CommandResult = CommandOutcome;++export type OnceOutcome =+ /** The command ran in this call and this is its own result. `stop()` ends it, for a result that says it still runs. */+ | { kind: "ran"; result: CommandResult; resent: number; stop(): Promise<void> }+ /** A send got no reply at all and the call's time is up: the command may have started. */+ | { kind: "late" }+ /** An earlier copy of this call ran (or is still running); its answer never came back. */+ | { kind: "lost" }+ /** No copy of this call is known to have run, and the computer did not answer in time to send it again. */+ | { kind: "unanswered"; phase: BoatWaitPhase | "unreachable" };++export interface OnceDeps {+ run(cfg: AppConfig, boxId: string, command: string, opts: { timeoutMs?: number; signal?: AbortSignal }): Promise<CommandResult>;+ awaitAnswer(cfg: AppConfig, boxId: string, opts: { woke: true; deadline: number; signal?: AbortSignal }): Promise<BoatAnswer>;+ counters: CloudComputerCounters;+ now(): number;+ sleep(ms: number, signal?: AbortSignal): Promise<void>;+ random(): number;+ key(): string;+}++const defaults: OnceDeps = {+ run: runCommand, awaitAnswer: (cfg, boxId, opts) => boatReadiness.awaitAnswer(cfg, boxId, opts), counters: cloudComputerCounters,+ now: Date.now, sleep: (ms, signal) => delay(ms, undefined, { signal }).catch(() => undefined), random: Math.random, key: newCallKey,+};++export interface OnceOptions {+ signal: AbortSignal;+ /** When the call this command belongs to must have answered. */+ deadline: number;+ /** The most one send may take, when that is less than what is left of the call. */+ timeoutMs?: number;+ /** Aborts when the person stops the turn, as opposed to the call's own time running out. */+ stopped?: AbortSignal;+}++const backoff = (resend: number, random: () => number): number => {+ const base = RESEND.backoffMs[Math.min(resend, RESEND.backoffMs.length - 1)]!;+ return Math.round(base * (1 - RESEND.jitter + 2 * RESEND.jitter * random()));+};++/** Runs `command` at most once on the computer. A gateway's 502, 503 or 504, a 52x, or no reply at all is waited out+ * and the call sent again; a command that ran and failed is returned as it is. */+export async function runOnce(cfg: AppConfig, boxId: string, command: string, opts: OnceOptions, overrides: Partial<OnceDeps> = {}): Promise<OnceOutcome> {+ const deps = { ...defaults, ...overrides };+ const key = deps.key();+ const lastSend = () => opts.deadline - RESEND.reserveMs;+ /** Best effort, on its own short clock: the caller that asks has usually given up already. */+ const stop = async () => { await deps.run(cfg, boxId, stopCommand(key), { timeoutMs: STOP_MS }).catch(() => undefined); };+ for (let resent = 0; ; resent++) {+ let result: CommandResult | null = null;+ try {+ // The command's own limit ends before the call's, so a long one is handed back still running instead of cut off.+ result = await deps.run(cfg, boxId, onceCommand(key, resent + 1, command), {+ signal: opts.signal, timeoutMs: Math.max(1_000, Math.min(opts.timeoutMs ?? Infinity, lastSend() - deps.now())),+ });+ } catch (error) {+ // The person stopped the turn: its foreground command is stopped with it, as Ctrl-C would, since nobody is left to follow it.+ if (opts.stopped?.aborted) void stop();+ if (opts.signal.aborted || !transientClaimFailure(error)) throw error;+ if (deps.now() >= lastSend()) return { kind: "late" };+ }+ if (result && !result.unanswered && !result.busy) {+ if (result.exitCode === TAKEN_EXIT && result.stdout.includes(takenMark(key))) {+ deps.counters.count(boxId, "lostAnswers");+ return { kind: "lost" };+ }+ if (result.exitCode === UNCLAIMED_EXIT && result.stdout.includes(unclaimedMark(key))) return { kind: "unanswered", phase: "waking" };+ return { kind: "ran", result, resent, stop };+ }+ deps.counters.count(boxId, "unanswered");+ if (resent >= RESEND.max) return { kind: "unanswered", phase: result?.busy ? "unreachable" : "waking" };+ const answer = await deps.awaitAnswer(cfg, boxId, { woke: true, deadline: lastSend(), signal: opts.signal });+ opts.signal.throwIfAborted();+ if (!answer.ok) return { kind: "unanswered", phase: answer.phase };+ const pause = backoff(resent, deps.random);+ if (deps.now() + pause >= lastSend()) return { kind: "unanswered", phase: "waking" };+ await deps.sleep(pause, opts.signal);+ opts.signal.throwIfAborted();+ deps.counters.count(boxId, "resent");+ }+}++/** For a read that changes nothing on the computer (a screenshot): tried again whenever `unanswered(error)` says the+ * computer gave no answer, once it answers a probe. */+export async function retryRead<T>(+ cfg: AppConfig, boxId: string, read: () => Promise<T>, unanswered: (error: unknown) => boolean, opts: OnceOptions, overrides: Partial<OnceDeps> = {},+): Promise<{ value: T } | { phase: BoatWaitPhase }> {+ const deps = { ...defaults, ...overrides };+ const lastSend = () => opts.deadline - RESEND.reserveMs;+ for (let resent = 0; ; resent++) {+ try {+ return { value: await read() };+ } catch (error) {+ if (opts.signal.aborted || !unanswered(error)) throw error;+ }+ deps.counters.count(boxId, "unanswered");+ if (resent >= RESEND.max) return { phase: "waking" };+ const answer = await deps.awaitAnswer(cfg, boxId, { woke: true, deadline: lastSend(), signal: opts.signal });+ opts.signal.throwIfAborted();+ if (!answer.ok) return { phase: answer.phase };+ const pause = backoff(resent, deps.random);+ if (deps.now() + pause >= lastSend()) return { phase: "waking" };+ await deps.sleep(pause, opts.signal);+ opts.signal.throwIfAborted();+ deps.counters.count(boxId, "resent");+ }+}diff --git a/server/cloud-computer-tools.test.ts b/server/cloud-computer-tools.test.tsindex 4a8cd3782e..75fadaa7f1 100644--- a/server/cloud-computer-tools.test.ts+++ b/server/cloud-computer-tools.test.ts@@ -9,6 +9,12 @@ let tools: typeof import("./cloud-computer-tools.ts");let holdCommand = false;let commandStatus = 200;let commandExit = 0;+/** This many commands in a row get the gateway's 502 before the machine answers again. */+let unansweredFirst = 0;+/** The Boat starts a detached command whose text says `forever` and reports it running until it is stopped; any other one has ended by the first read. */+let neverEnds = false;+const forever = new Set<number>();+let nextProcess = 100;let commandStarted: (() => void) | undefined;const calls: Array<{ path: string; body: any; authorization?: string }> = [];const cfg: AppConfig = { box: { token: "synthetic-box-key" } } as AppConfig;@@ -22,8 +28,20 @@ beforeAll(async () => {for await (const part of req) body += part;const path = req.url ?? "";calls.push({ path, body: body ? JSON.parse(body) : null, authorization: req.headers.authorization });+ const read = /\/commands\/(\d+)\?/.exec(path);+ if (neverEnds && read) {+ res.end(JSON.stringify(forever.has(Number(read[1])) ? { running: true, status: "running", stdout: "compiling", stderr: "" } : { running: false, status: "exited", exitCode: 0, stdout: "captured", stderr: "" }));+ return;+ }+ if (neverEnds && path.endsWith("/commands") && JSON.parse(body).detached === true) {+ const id = nextProcess++;+ if (String(JSON.parse(body).command).includes("forever")) forever.add(id);+ res.end(JSON.stringify({ processId: id }));+ return;+ }if (path.endsWith("/commands")) {commandStarted?.();+ if (unansweredFirst > 0) { unansweredFirst--; res.writeHead(502); res.end(JSON.stringify({ ok: false, code: "upstream_unavailable" })); return; }if (commandStatus !== 200) { res.writeHead(commandStatus); res.end(JSON.stringify({ ok: false, code: "upstream_unavailable" })); return; }if (!holdCommand) res.end(JSON.stringify({ exitCode: commandExit, stdout: "captured", stderr: "" }));return;@@ -38,17 +56,17 @@ beforeAll(async () => {vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", undefined);tools = await import("./cloud-computer-tools.ts");});-beforeEach(() => { calls.length = 0; holdCommand = false; commandStarted = undefined; commandStatus = 200; commandExit = 0; });+beforeEach(() => { calls.length = 0; holdCommand = false; commandStarted = undefined; commandStatus = 200; commandExit = 0; unansweredFirst = 0; neverEnds = false; forever.clear(); });afterAll(async () => { vi.unstubAllEnvs(); server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); });type Recovery = NonNullable<Parameters<typeof import("./cloud-computer-tools.ts").cloudComputerRpc>[1]["recovery"]>;-const rpc = (request: unknown, gate: { held: boolean; reason?: "person"; blockedReason?: string } = { held: false }, signal = new AbortController().signal, recovery?: Recovery) => {+const rpc = (request: unknown, gate: { held: boolean; reason?: "person"; blockedReason?: string } = { held: false }, signal = new AbortController().signal, recovery?: Recovery, budgetMs?: number, settled?: (answered: boolean) => void) => {let gated = 0;let checks = 0;const done = tools.cloudComputerRpc(request as never, {cfg, boxId: () => "bx_23456789", signal,gate: async () => { gated++; return gate; },- assertActive: () => { checks++; }, recovery,+ assertActive: () => { checks++; }, recovery, ...(budgetMs === undefined ? {} : { budgetMs }), ...(settled ? { settled } : {}),});return { done, gated: () => gated, checks: () => checks };};@@ -199,7 +217,9 @@ describe("cloud computer tools", () => {await started;abort.abort();await rejected;- expect(calls.filter(entry => entry.path.endsWith("/commands"))).toHaveLength(1);+ expect(calls.filter(entry => entry.path.endsWith("/commands") && String(entry.body.command).includes("printf fixture"))).toHaveLength(1);+ // The person stopped the turn, so the command it was waiting on is stopped too, by the call's own key.+ await vi.waitFor(() => expect(calls.some(entry => entry.path.endsWith("/commands") && String(entry.body.command).includes("kill -TERM"))).toBe(true));server.closeAllConnections();});@@ -213,19 +233,116 @@ describe("cloud computer tools", () => {expect(result).toEqual({ isError: true, content: [{ type: "text", text: (await import("./cloud-computer-background.ts")).EXEC_LATE }] });expect(Date.now() - started).toBeGreaterThanOrEqual(550);expect(Date.now() - started).toBeLessThan(1_500);- expect(calls.filter(entry => entry.path.endsWith("/commands"))).toHaveLength(1);+ expect(calls.filter(entry => entry.path.endsWith("/commands") && String(entry.body.command).includes("sleep 600"))).toHaveLength(1);+ expect(calls.some(entry => String(entry.body?.command).includes("kill -TERM"))).toBe(false);server.closeAllConnections();});+ it("hands a command that outlasts its call back still running, with a process id exec_status follows, instead of an error", async () => {+ neverEnds = true;+ const result = await tools.cloudComputerRpc({ method: "tools/call", params: { name: "exec", arguments: { command: "make forever" } } }, {+ cfg, boxId: () => "bx_23456789", signal: new AbortController().signal, budgetMs: 32_000, assertActive: () => {}, gate: async () => ({ held: false }),+ }) as { isError?: boolean; content: Array<{ type: string; text?: string }> };+ expect(result.isError).toBeFalsy();+ const handed = JSON.parse(result.content[0]!.text!);+ expect(handed).toMatchObject({ status: "running", stdout: "compiling", next: tools.EXEC_STILL_RUNNING });+ expect(calls.filter(entry => entry.path.endsWith("/commands") && entry.body?.detached === true)).toHaveLength(1);+ const status = await tools.cloudComputerRpc({ method: "tools/call", params: { name: "exec_status", arguments: { process_id: handed.processId } } }, {+ cfg, boxId: () => "bx_23456789", signal: new AbortController().signal, assertActive: () => {}, gate: async () => ({ held: false }),+ }) as { content: Array<{ text?: string }> };+ expect(JSON.parse(status.content[0]!.text!)).toMatchObject({ status: "running", processId: handed.processId });+ }, 60_000);++ it("sends pointer calls, key calls and screenshots the direct way, in one round trip, and exec the way that survives a long run", async () => {+ await rpc({ method: "tools/call", params: { name: "click", arguments: { x: 1, y: 2 } } }).done;+ await rpc({ method: "tools/call", params: { name: "screenshot", arguments: {} } }).done;+ await rpc({ method: "tools/call", params: { name: "exec", arguments: { command: "pwd" } } }).done;+ expect(calls.filter(entry => entry.path.endsWith("/commands")).map(entry => entry.body.detached === true)).toEqual([false, false, true]);+ });++ it("answers that the command ran out of time, as a result and before the call's own limit, when its start gets no reply", async () => {+ holdCommand = true;+ const before = Date.now();+ const result = await tools.cloudComputerRpc({ method: "tools/call", params: { name: "exec", arguments: { command: "make" } } }, {+ cfg, boxId: () => "bx_23456789", signal: new AbortController().signal, budgetMs: 8_000, assertActive: () => {}, gate: async () => ({ held: false }),+ });+ expect(result).toEqual({ isError: true, content: [{ type: "text", text: (await import("./cloud-computer-background.ts")).EXEC_LATE }] });+ expect(Date.now() - before).toBeLessThan(7_000);+ server.closeAllConnections();+ }, 20_000);++ describe("with five long-running commands already left on the computer by earlier exec calls", () => {+ const exec = (command: string, budgetMs?: number) => tools.cloudComputerRpc({ method: "tools/call", params: { name: "exec", arguments: { command } } }, {+ cfg, boxId: () => "bx_23456789", signal: new AbortController().signal, assertActive: () => {}, gate: async () => ({ held: false }), ...(budgetMs ? { budgetMs } : {}),+ }) as Promise<{ isError?: boolean; content: Array<{ type: string; text?: string }> }>;+ const fiveDevServers = async () => {+ neverEnds = true;+ const { noteLeftRunning } = await import("./boat-command.ts");+ for (const id of [1, 2, 3, 4, 5]) { forever.add(id); noteLeftRunning("bx_23456789", id); }+ };++ it("still runs the command that stops them, and any other short command", async () => {+ await fiveDevServers();+ const stopped = await exec("pkill -f devserver");+ expect(stopped.isError).toBeFalsy();+ expect(JSON.parse(stopped.content[0]!.text!)).toMatchObject({ ok: true, exitCode: 0 });+ expect((await exec("ls")).isError).toBeFalsy();+ const click = await rpc({ method: "tools/call", params: { name: "click", arguments: { x: 1, y: 2 } } }).done as { isError?: boolean };+ expect(click.isError).toBeFalsy();+ });++ it("stops a sixth one when its call's time runs out, instead of leaving it, and says how to see and stop the others", async () => {+ await fiveDevServers();+ const sixth = await exec("devserver forever", 32_000);+ expect(sixth).toEqual({ isError: true, content: [{ type: "text", text: tools.TOO_MANY_LEFT_RUNNING }] });+ expect(tools.TOO_MANY_LEFT_RUNNING).toMatch(/background: true.*ps -eo.*kill <pid>/s);+ const sent = calls.filter(entry => entry.path.endsWith("/commands")).map(entry => String(entry.body.command));+ const key = /^k=([0-9a-f]{16});/.exec(sent.find(command => command.includes("devserver forever"))!)![1]!;+ expect(sent.some(command => command.startsWith(`k=${key}; p=;`) && command.includes("kill -TERM"))).toBe(true);+ // With one of the five gone, the next long command is handed back as usual.+ forever.delete(5);+ const next = await exec("watcher forever", 32_000);+ expect(next.isError).toBeFalsy();+ expect(JSON.parse(next.content[0]!.text!)).toMatchObject({ status: "running" });+ }, 120_000);+ });+describe("a computer that stopped answering", () => {const words = () => import("../shared/cloud-computer-recovery.ts");- const call = (name: string, args: Record<string, unknown>, recovery?: Recovery) =>- rpc({ method: "tools/call", params: { name, arguments: args } }, { held: false }, new AbortController().signal, recovery).done as Promise<{ isError?: boolean; content: Array<{ type: string; text?: string }> }>;+ /** A call with little time left, so a computer that never answers is given up on at once. */+ const SHORT = 6_000;+ const call = (name: string, args: Record<string, unknown>, recovery?: Recovery, budgetMs: number | undefined = SHORT, settled?: (answered: boolean) => void) =>+ rpc({ method: "tools/call", params: { name, arguments: args } }, { held: false }, new AbortController().signal, recovery, budgetMs, settled).done as Promise<{ isError?: boolean; content: Array<{ type: string; text?: string }> }>;it("says a call got no answer, instead of an empty failed result", async () => {commandStatus = 502;- const result = await call("click", { x: 1, y: 2 });- expect(result).toEqual({ isError: true, content: [{ type: "text", text: (await words()).CLOUD_COMPUTER_NO_ANSWER }] });+ const outcomes: boolean[] = [];+ const result = await call("click", { x: 1, y: 2 }, undefined, SHORT, (answered) => outcomes.push(answered));+ expect(result).toEqual({ isError: true, content: [{ type: "text", text: (await words()).CLOUD_COMPUTER_STILL_WAKING }] });+ expect(outcomes).toEqual([false]);+ });++ it("rides out a short burst of gateway errors inside the call: the bot gets the result, and the command ran once", async () => {+ unansweredFirst = 2;+ const outcomes: boolean[] = [];+ const result = await call("exec", { command: "printf fixture" }, undefined, 60_000, (answered) => outcomes.push(answered));+ expect(result.isError).toBeFalsy();+ expect(JSON.parse(result.content[0]!.text!)).toMatchObject({ ok: true, exitCode: 0, stdout: "captured" });+ const sent = calls.filter(entry => entry.path.endsWith("/commands")).map(entry => String(entry.body.command));+ const copies = sent.filter(command => command.includes("printf fixture"));+ const key = /^k=([0-9a-f]{16});/.exec(copies[0]!)?.[1];+ expect(key).toBeDefined();+ // Every copy of the call carries the same claim, so the computer runs at most one of them.+ expect(copies.length).toBeGreaterThanOrEqual(2);+ expect(copies.every(command => command.startsWith(`k=${key};`))).toBe(true);+ expect(sent.filter(command => command === "true").length).toBeGreaterThanOrEqual(1);+ expect(outcomes).toEqual([true]);+ });++ it("takes a screenshot again once the computer answers, since a screenshot changes nothing", async () => {+ unansweredFirst = 1;+ const result = await call("screenshot", {}, undefined, 60_000);+ expect(result.content[0]).toMatchObject({ type: "image", mimeType: "image/jpeg" });});it("refuses calls without touching the computer while it is being restarted or replaced", async () => {diff --git a/server/cloud-computer-tools.ts b/server/cloud-computer-tools.tsindex dfb961aba0..24b52c1862 100644--- a/server/cloud-computer-tools.ts+++ b/server/cloud-computer-tools.ts@@ -1,16 +1,21 @@// Served at POST /api/internal/computer/mcp behind a turn-scoped capability, so the Boat credential never leaves this server.import type { ValidateFunction } from "ajv";-import { isolatedRemoteCommand, runCommand, screenshotBoat } from "./boat.ts";+import { isolatedRemoteCommand, screenshotBoat } from "./boat.ts";import { isRedditAddress, REDDIT_REFUSAL } from "./browser/egress/reddit.ts";import {- backgroundStatus, commandLateText, EXEC_LATE, PROCESS_ID_PATTERN, startInBackground, STATUS_WAIT_MAX_SECONDS, STDERR_TAIL_CHARS, STDOUT_TAIL_CHARS,+ backgroundStatus, commandLateText, EXEC_LATE, PROCESS_ID_PATTERN, processIdOn, startInBackground, STATUS_WAIT_MAX_SECONDS, STDERR_TAIL_CHARS, STDOUT_TAIL_CHARS,} from "./cloud-computer-background.ts";+import { COMMAND_WALL, commandsLeftRunning, noteLeftRunning, untrackProcess } from "./boat-command.ts";import { copyFromComputer, copyToComputer } from "./cloud-computer-files.ts";+import { retryRead, runOnce } from "./cloud-computer-once.ts";import type { AppConfig } from "./config.ts";import { controlRefusal, type ControlState } from "./control-client.ts";import { COMPUTER_COPY_BUDGET_MS, HARNESS_CALL_BUDGET_MS } from "./harness-budget.ts";import { compileToolSchema } from "./mcp-schema-validator.ts";-import { CLOUD_COMPUTER_NO_ANSWER } from "../shared/cloud-computer-recovery.ts";+import {+ CLOUD_COMPUTER_ANSWER_LOST, CLOUD_COMPUTER_EXEC_ANSWER_LOST, CLOUD_COMPUTER_NO_ANSWER, CLOUD_COMPUTER_STILL_RESTORING, CLOUD_COMPUTER_STILL_WAKING,+ CLOUD_COMPUTER_UNREACHABLE,+} from "../shared/cloud-computer-recovery.ts";const coordinate = { type: "integer", minimum: 0, maximum: 32767 };const tool = (name: string, description: string, properties: Record<string, unknown> = {}, required: string[] = []) =>@@ -46,6 +51,17 @@ export const CLOUD_COMPUTER_TOOLS = [export const CLOUD_COMPUTER_NOT_READY = "The cloud computer is not ready. This call was not performed. Take a fresh screenshot in a moment.";export const CLOUD_COMPUTER_LATE = "The cloud computer did not answer in time. This call may still have run; take a fresh screenshot before repeating it.";export const CLOUD_COMPUTER_COPY_LATE = "The copy did not finish within 9 minutes and was stopped; nothing was changed. Make the file smaller on the cloud computer first (filter, compress or split it), then copy the parts.";+/** A command that outlasted its call: it is left running, since stopping a build half-way is worse, and handed back to follow. */+export const EXEC_STILL_RUNNING = "The command is still running on the cloud computer; it was not stopped and was not started twice. Follow it with exec_status and this "+ + "processId (wait_seconds up to 60) until it finishes, then check its exit code and output. Do not run it again. Start a command that may run long with background: true.";+export const TOO_MANY_LEFT_RUNNING = `This command ran past this call's time limit, and this cloud computer already has ${COMMAND_WALL.leftRunningMax} commands left running from earlier exec calls, `+ + "so this one was stopped. Start a command that keeps running (a server, a watcher, a long build) with background: true. To see what is running, exec "+ + "`ps -eo pid,etime,args --sort=start_time | tail -n 30`; to stop one, exec `kill <pid>`. Short commands like these always run.";+/** Only reached through a relay that does not start commands in the background: the provider itself ended the command. */+export const EXEC_STOPPED_AT_LIMIT = "The cloud computer's provider stopped this command after 30 seconds, its limit for a command run this way. The command did not fail by itself and is "+ + "no longer running; what it had done up to then stays. Start it again with background: true, then follow it with exec_status.";+/** Pointer moves, clicks, keys and the like take well under a second; this ends five seconds before the provider would stop a direct command at 30 s. */+const QUICK_CALL_MS = 25_000;const COPY_TOOLS = new Set(["copy_from_computer", "copy_to_computer"]);export const cloudComputerCallBudgetMs = (name: unknown): number =>typeof name === "string" && COPY_TOOLS.has(name) ? COMPUTER_COPY_BUDGET_MS : HARNESS_CALL_BUDGET_MS;@@ -73,7 +89,17 @@ export type CloudComputerResult = {isError?: boolean;};-/** The caller has already checked the arguments and the person's control. `folder` is the bot's working folder for this turn. */+/** What a call that was sent again until its time ran out tells the bot; each is also how such a call is recognised. */+const UNANSWERED_TEXT = { waking: CLOUD_COMPUTER_STILL_WAKING, restoring: CLOUD_COMPUTER_STILL_RESTORING, unreachable: CLOUD_COMPUTER_UNREACHABLE } as const;+const UNANSWERED_TEXTS = new Set<string>([CLOUD_COMPUTER_NO_ANSWER, ...Object.values(UNANSWERED_TEXT)]);+const unansweredResult = (phase: keyof typeof UNANSWERED_TEXT): CloudComputerResult => ({ isError: true, content: [{ type: "text", text: UNANSWERED_TEXT[phase] }] });+/** The call got no answer from the computer, as opposed to an answer that reports a failure. */+export const cloudComputerUnanswered = (result: CloudComputerResult): boolean =>+ result.isError === true && result.content.some((part) => part.type === "text" && UNANSWERED_TEXTS.has(part.text));++/** The caller has already checked the arguments and the person's control. `folder` is the bot's working folder for this+ * turn. `deadline`: when the whole call must have answered; a call the computer did not answer is sent again inside it.+ * `stopped`: aborts when the person stops the turn, which also stops a command this call is still following. */export async function runCloudComputerTool(cfg: AppConfig,boxId: string,@@ -81,6 +107,8 @@ export async function runCloudComputerTool(args: Record<string, unknown>,signal: AbortSignal,folder?: string | null,+ deadline = Date.now() + HARNESS_CALL_BUDGET_MS,+ stopped?: AbortSignal,): Promise<CloudComputerResult> {const problem = cloudComputerCallProblem(name, args);if (problem) return { isError: true, content: [{ type: "text", text: problem }] };@@ -93,9 +121,11 @@ export async function runCloudComputerTool(return "error" in copied ? { isError: true, content: [{ type: "text", text: copied.error }] } : { content: [{ type: "text", text: JSON.stringify(copied) }] };}if (name === "screenshot") {- const shot = await screenshotBoat(cfg, "", boxId, { signal, nativeSize: true });+ const shot = await retryRead(cfg, boxId, () => screenshotBoat(cfg, "", boxId, { signal, nativeSize: true }),+ (error) => error instanceof Error && error.message === CLOUD_COMPUTER_NO_ANSWER, { signal, deadline });signal.throwIfAborted();- return { content: [{ type: "image", mimeType: "image/jpeg", data: shot.png }] };+ if ("phase" in shot) return unansweredResult(shot.phase);+ return { content: [{ type: "image", mimeType: "image/jpeg", data: shot.value.png }] };}const a = args;const mouse = `xdotool mousemove --sync ${a.x} ${a.y}`;@@ -113,11 +143,29 @@ export async function runCloudComputerTool(case "exec_status": return backgroundStatus(cfg, boxId, a as { process_id: string; wait_seconds?: number }, signal);default: return { isError: true, content: [{ type: "text", text: "Unknown cloud computer tool." }] };}- const result = await runCommand(cfg, boxId, isolatedRemoteCommand(command), { signal });+ // Only exec may run long. Every other call is a quick one, sent the direct way so it answers in one round trip.+ const sent = await runOnce(cfg, boxId, isolatedRemoteCommand(command), { signal, deadline, ...(stopped ? { stopped } : {}), ...(name === "exec" ? {} : { timeoutMs: QUICK_CALL_MS }) });signal.throwIfAborted();+ if (sent.kind === "unanswered") return unansweredResult(sent.phase);+ if (sent.kind === "late") return { isError: true, content: [{ type: "text", text: commandLateText(name, a) ?? CLOUD_COMPUTER_LATE }] };+ if (sent.kind === "lost") return { isError: true, content: [{ type: "text", text: name === "exec" ? CLOUD_COMPUTER_EXEC_ANSWER_LOST : CLOUD_COMPUTER_ANSWER_LOST }] };+ const result = sent.result;if (name === "open_url" && result.ok) return { content: [{ type: "text", text: "Browser launch requested. Page loading is not confirmed; inspect the screen before continuing." }] };+ if (name === "exec" && result.timedOut && result.processId !== undefined) {+ // The limit applies here, to the command that would be one too many, and never to a command before it is sent: a+ // short command, such as the one that stops the others, always goes through.+ if (await commandsLeftRunning(cfg, boxId) >= COMMAND_WALL.leftRunningMax) {+ await sent.stop();+ untrackProcess(boxId, result.processId);+ return { isError: true, content: [{ type: "text", text: TOO_MANY_LEFT_RUNNING }] };+ }+ noteLeftRunning(boxId, result.processId);+ return { content: [{ type: "text", text: JSON.stringify({+ status: "running", processId: processIdOn(boxId, result.processId), stdout: result.stdout.slice(-STDOUT_TAIL_CHARS), stderr: result.stderr.slice(-STDERR_TAIL_CHARS), next: EXEC_STILL_RUNNING,+ }) }] };+ }+ if (name === "exec" && result.providerLimit) return { isError: true, content: [{ type: "text", text: EXEC_STOPPED_AT_LIMIT }] };if (name === "exec" && result.timedOut) return { isError: true, content: [{ type: "text", text: EXEC_LATE }] };- if (result.unanswered) return { isError: true, content: [{ type: "text", text: CLOUD_COMPUTER_NO_ANSWER }] };return { isError: !result.ok, content: [{ type: "text", text: JSON.stringify(result) }] };}@@ -138,6 +186,8 @@ export async function cloudComputerRpc(budgetMs?: number;/** A computer that stopped answering (server/boat-recovery.ts): what the bot is told instead, and once after it was replaced. */recovery?: { refusal(boxId: string, phase: "before" | "after"): string | null; notice(boxId: string): string | null };+ /** Whether the computer answered this call: a call refused before it was sent, or one that got no answer, did not. */+ settled?(answered: boolean): void;},): Promise<{ tools: typeof CLOUD_COMPUTER_TOOLS } | CloudComputerResult> {const started = Date.now();@@ -163,21 +213,22 @@ export async function cloudComputerRpc(return text ? { isError: true, content: [{ type: "text", text }] } : null;};const before = refused("before");- if (before) return before;+ if (before) { deps.settled?.(false); return before; }const late = AbortSignal.timeout(Math.max(1, deadline - Date.now()));let result: CloudComputerResult;try {- result = await runCloudComputerTool(deps.cfg, boxId, params.name as string, args as Record<string, unknown>, AbortSignal.any([deps.signal, late]), deps.folder?.());+ result = await runCloudComputerTool(deps.cfg, boxId, params.name as string, args as Record<string, unknown>, AbortSignal.any([deps.signal, late]), deps.folder?.(), deadline, deps.signal);} catch (error) {if (deps.signal.aborted) throw error;const after = refused("after");- if (after) return after;+ if (after) { deps.settled?.(false); return after; }if (!late.aborted) throw error;return { isError: true, content: [{ type: "text", text: commandLateText(params.name, args) ?? (copy ? CLOUD_COMPUTER_COPY_LATE : CLOUD_COMPUTER_LATE) }] };}deps.assertActive();- const unanswered = result.isError && result.content.some((part) => part.type === "text" && part.text === CLOUD_COMPUTER_NO_ANSWER);+ const unanswered = cloudComputerUnanswered(result);if (unanswered) result = refused("after") ?? result;+ deps.settled?.(!unanswered);const notice = deps.recovery?.notice(boxId);return notice ? { ...result, content: [{ type: "text", text: notice }, ...result.content] } : result;}diff --git a/server/cloud-computer-unattended.test.ts b/server/cloud-computer-unattended.test.tsnew file mode 100644index 0000000000..09dfae2e8f--- /dev/null+++ b/server/cloud-computer-unattended.test.ts@@ -0,0 +1,255 @@+// A scheduled run and a cloud computer that is reported ready but does not answer, through the real scheduler, run gate,+// recovery, health check, readiness wait and Boat client, against a loopback stand-in for the Cloud's relay. The clock is+// the test's own; no server process and no AI engine is started, and nothing leaves this machine.+import { mkdtempSync, rmSync } from "node:fs";+import { createServer, type Server, type ServerResponse } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import { RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts";+import type { AppConfig } from "./config.ts";+import type { RuntimeEvent } from "../shared/runtime-events.ts";++/** The fields are the provider's own, as seen on a silent computer. */+type Box = { id: string; name: string; state: string; health: string; hydrated?: boolean; lastSnapshotStatus?: string };++const BOX_ID = "bx_23456789";+const BOT = "bugfix-bot";+const cfg = {} as AppConfig;++let server: Server;+let box: Box;+/** Whether the machine behind the provider's "ready" answers commands, and whether a stop and resume fixes it. */+let answers = true;+let resumeFixes = false;+let requests: string[] = [];++const send = (res: ServerResponse, status: number, body: unknown) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(body));+};++beforeAll(async () => {+ server = createServer((req, res) => {+ req.resume();+ req.on("end", () => {+ const path = new URL(req.url ?? "/", "http://relay.test").pathname.replace(/^\/relay\/api\/box\/v1/, "");+ requests.push(`${req.method} ${path}`);+ if (path === "/boxes") return send(res, 200, { ok: true, boxes: [box], pageInfo: { nextCursor: null } });+ const [, id, action] = /^\/boxes\/([^/]+)(?:\/(stop|resume|commands))?$/.exec(path) ?? [];+ if (id !== box.id) return send(res, 404, { ok: false, code: "not_found" });+ if (!action) return send(res, 200, { ok: true, box });+ if (action === "stop") { box.state = "archived"; return send(res, 200, { ok: true, box }); }+ if (action === "resume") {+ box.state = "idle";+ if (resumeFixes) { answers = true; box.hydrated = true; box.lastSnapshotStatus = "completed"; }+ return send(res, 200, { ok: true, box });+ }+ // The provider keeps saying idle and ok; only the command gets the relay's 502.+ if (!answers || box.state !== "idle") return send(res, 502, { ok: false, code: "upstream_unavailable", message: "Cloud computers could not be reached." });+ return send(res, 200, { exitCode: 0, stdout: "", stderr: "" });+ });+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `http://127.0.0.1:${(server.address() as { port: number }).port}/relay/api/box/v1`);+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", "box_omb_synthetic");+});+afterAll(async () => {+ vi.unstubAllEnvs();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+});++const dirs: string[] = [];+let close: (() => void) | null = null;+afterEach(() => {+ close?.();+ close = null;+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});+beforeEach(() => { answers = true; resumeFixes = false; requests = []; });++async function world(watched = false) {+ vi.resetModules();+ const boat = await import("./boat.ts");+ const { createBoatHealth } = await import("./boat-health.ts");+ const { createBoatReadiness } = await import("./boat-ready.ts");+ const { createBoatRecovery } = await import("./boat-recovery.ts");+ const { cloudComputerCounters, createCloudComputerCounters } = await import("./cloud-computer-counters.ts");+ const { createRunComputerGate } = await import("./host/cloud-computer-run-gate.ts");+ const { RoutineManager } = await import("./routines.ts");++ const dir = mkdtempSync(join(tmpdir(), "omb-unattended-"));+ dirs.push(dir);+ box = { id: BOX_ID, name: await boat.boatNameFor(BOT), state: "idle", health: "ok", hydrated: true, lastSnapshotStatus: "completed" };+ let at = new Date(2026, 10, 14, 8, 0, 0).getTime();+ const now = () => at;+ const health = createBoatHealth(now);+ const counters = createCloudComputerCounters(now);+ const readiness = createBoatReadiness({ health, counters, now,+ // A little real time passes with each wait, so the test's clock cannot run through the run's twenty minutes while+ // the recovery's own steps (real requests, a real pause between two reads of a waking computer) are still under way.+ sleep: async (ms) => { at += ms; await new Promise((resolve) => setTimeout(resolve, 25)); },+ });+ const told: string[] = [];+ const logged: string[] = [];+ const recovery = createBoatRecovery({+ cfg: () => cfg, tell: (_owner, line) => told.push(line), log: (line) => logged.push(line), file: join(dir, "boat-replacements.json"),+ now, health, pollMs: 5, recheckMs: 20, readiness, autoReplace: () => false, personActive: () => watched,+ });+ let manager: InstanceType<typeof RoutineManager>;+ const gate = createRunComputerGate({+ computerOf: () => BOT, find: (owner) => boat.findBoat(cfg, owner), wake: (owner, budgetMs) => boat.readyBoat(cfg, owner, budgetMs),+ awaitAnswer: (boxId, opts) => readiness.awaitAnswer(cfg, boxId, opts), verdict: (owner, since) => recovery.verdict(owner, since),+ recoveryState: (owner) => recovery.status(owner)?.state ?? null, used: () => {},+ routineOf: (botId, threadId) => { const run = manager.activeRunForBot(botId); return run?.threadId === threadId ? run.routineId : null; },+ log: (line) => logged.push(line), now,+ });+ const started: string[] = [];+ let tasks = 0;+ manager = new RoutineManager({+ file: join(dir, "routines.json"), now, botState: () => "ready",+ createTask: () => ({ threadId: `thread-${++tasks}` }),+ startTurn: async (_botId, threadId) => { started.push(threadId); },+ prepareRun: (run, signal) => gate.prepare(run, signal), preparing: RUN_COMPUTER_LINES.waking,+ });+ close = () => { recovery.close(); manager.close?.(); };+ const event = (threadId: string, body: Record<string, unknown>) =>+ manager.handleRuntimeEvent({ eventId: `event-${Math.random()}`, provider: "fake", threadId, createdAt: new Date(0).toISOString(), ...body } as RuntimeEvent);+ const routine = manager.create({ name: "Fix bugs", prompt: "Fix the next bug on the cloud computer", botId: BOT, runOn: "cloud", schedule: { type: "interval", everyMinutes: 60, anchorAt: at } });+ const until = async (check: () => boolean, what: string, ms = 80_000) => {+ for (const end = Date.now() + ms; Date.now() < end; await new Promise((resolve) => setTimeout(resolve, 10))) if (check()) return;+ throw new Error(`timed out waiting for ${what}\n${logged.join("\n")}\n${JSON.stringify(manager.listRuns().map(({ status, error, attention }) => ({ status, error, attention })))}`);+ };+ /** The next scheduled occurrence comes due. */+ const occurrence = async () => {+ const before = new Set(manager.listRuns().map((run) => run.id));+ at = manager.listRoutines().find((candidate) => candidate.id === routine.id)!.nextRunAt!;+ await manager.tick();+ return manager.listRuns().find((run) => run.routineId === routine.id && !before.has(run.id))!;+ };+ const run = (id: string) => manager.listRuns().find((candidate) => candidate.id === id)!;+ /** As the turn's computer calls and its end reach the server. */+ const notes: string[] = [];+ const finishTurn = (threadId: string, lastCallAnswered = true) => {+ gate.callSettled(BOT, threadId, lastCallAnswered);+ const note = gate.turnEnded(threadId, true);+ if (note) notes.push(note);+ event(threadId, { type: "item.completed", itemType: "assistant_text", text: "Fixed." });+ event(threadId, { type: "turn.completed", ok: true });+ };+ const routineNow = () => manager.listRoutines().find((candidate) => candidate.id === routine.id)!;+ return { notes, boat, manager, gate, recovery, health, counters, restarts: () => cloudComputerCounters.snapshot(BOX_ID)?.restarts ?? 0, started, told, logged, occurrence, run, finishTurn, until, routineNow, advance: (ms: number) => { at += ms; }, now };+}++/** Each scenario makes a few hundred loopback requests; this leaves room on a busy machine. */+const SCENARIO_MS = 90_000;+const count = (line: string) => requests.filter((request) => request === line).length;++describe("a scheduled run whose cloud computer says ready but does not answer", () => {+ it("is held, the computer is restarted once, and the run then starts and completes", async () => {+ const w = await world();+ const first = await w.occurrence();+ expect(w.run(first.id).status).toBe("running");+ w.finishTurn(first.threadId!);+ expect(w.run(first.id).status).toBe("completed");++ answers = false;+ resumeFixes = true;+ const second = await w.occurrence();+ expect(w.run(second.id)).toMatchObject({ status: "queued", attention: RUN_COMPUTER_LINES.waking });+ expect(w.started).toHaveLength(1);+ await w.until(() => w.run(second.id).status === "running", "the held run to start");+ expect(count(`POST /boxes/${BOX_ID}/stop`)).toBe(1);+ expect(count(`POST /boxes/${BOX_ID}/resume`)).toBe(1);+ expect(requests.some((request) => request.startsWith("DELETE"))).toBe(false);+ expect(w.started).toHaveLength(2);+ await w.until(() => w.recovery.status(BOT)?.state === "restarted", "the restart to be judged");+ expect(w.restarts()).toBe(1);+ expect(w.told).toEqual(["restarted"]);+ w.finishTurn(second.threadId ?? w.run(second.id).threadId!);+ expect(w.run(second.id).status).toBe("completed");+ expect(w.routineNow().enabled).toBe(true);+ }, SCENARIO_MS);++ it("ends with the reason when a restart does not help, deletes nothing, and the next occurrence runs normally", async () => {+ const w = await world();+ const first = await w.occurrence();+ w.finishTurn(first.threadId!);++ answers = false;+ const second = await w.occurrence();+ await w.until(() => w.run(second.id).status === "failed", "the held run to fail");+ expect(w.run(second.id).error).toBe(RUN_COMPUTER_LINES.afterRestart);+ expect(w.started).toHaveLength(1);+ expect(count(`POST /boxes/${BOX_ID}/stop`)).toBe(1);+ expect(requests.some((request) => request.startsWith("DELETE"))).toBe(false);+ expect(w.routineNow()).toMatchObject({ enabled: true });+ expect(w.routineNow().nextRunAt).toBeGreaterThan(w.now());++ answers = true;+ const third = await w.occurrence();+ await w.until(() => w.run(third.id).status === "running", "the next occurrence to start");+ w.finishTurn(w.run(third.id).threadId!);+ expect(w.run(third.id).status).toBe("completed");+ expect(count(`POST /boxes/${BOX_ID}/stop`)).toBe(1);+ }, SCENARIO_MS);++ it("waits out a disk restore the provider reports, without a restart, when the computer answers inside ten minutes", async () => {+ const w = await world();+ const first = await w.occurrence();+ w.finishTurn(first.threadId!);++ answers = false;+ box.hydrated = false;+ box.lastSnapshotStatus = "in_progress";+ const second = await w.occurrence();+ const heldAt = w.now();+ await w.until(() => w.recovery.status(BOT)?.state === "restoring", "the recovery to see the restore");+ expect(w.recovery.refusal(BOX_ID, "before")).toMatch(/restoring its disk/);+ answers = true;+ await w.until(() => w.run(second.id).status === "running", "the held run to start");+ expect(w.now() - heldAt).toBeLessThan(10 * 60_000);+ expect(count(`POST /boxes/${BOX_ID}/stop`)).toBe(0);+ }, SCENARIO_MS);++ it("is not restarted under a person who is using it: the run says why and the schedule goes on", async () => {+ const w = await world(true);+ const first = await w.occurrence();+ w.finishTurn(first.threadId!);++ answers = false;+ const second = await w.occurrence();+ await w.until(() => w.run(second.id).status === "failed", "the held run to fail");+ expect(w.run(second.id).error).toBe(RUN_COMPUTER_LINES.personBusy);+ expect(count(`POST /boxes/${BOX_ID}/stop`)).toBe(0);+ expect(w.routineNow().enabled).toBe(true);+ }, SCENARIO_MS);++ it("leaves a run that finished as finished, with a note, when its last computer call got no answer: nothing is done twice", async () => {+ const w = await world();+ const first = await w.occurrence();+ w.finishTurn(first.threadId!);++ const second = await w.occurrence();+ await w.until(() => w.run(second.id).status === "running", "the run to start");+ w.finishTurn(w.run(second.id).threadId!, false);+ expect(w.run(second.id).status).toBe("completed");+ expect(w.run(second.id).retried).toBeUndefined();+ expect(w.notes).toEqual([RUN_COMPUTER_LINES.lastCallUnanswered]);+ expect(w.started).toHaveLength(2);+ }, SCENARIO_MS);++ it("starts a run a person asked for at once, without waiting on a silent computer", async () => {+ const w = await world();+ const first = await w.occurrence();+ w.finishTurn(first.threadId!);++ answers = false;+ const manual = w.manager.runNow(w.routineNow().id)!;+ await w.manager.tick();+ expect(w.run(manual.id)).toMatchObject({ status: "running", threadId: expect.any(String) });+ expect(w.started).toHaveLength(2);+ }, SCENARIO_MS);+});diff --git a/server/devs-report.ts b/server/devs-report.tsindex f64a54fc43..07b41263e8 100644--- a/server/devs-report.ts+++ b/server/devs-report.ts@@ -66,6 +66,8 @@ export interface DevsReportInput {noSummary?: string;problems: string[];log: string[];+ /** One line per cloud computer used since the server started: its opaque id and counts, nothing it ran. */+ cloudComputers?: string[];contactEmail?: string;}@@ -151,6 +153,7 @@ function diagnose(input: DevsReportInput, redact: (text: string) => string): strlines.push("", "## Recent problems in this conversation, newest last");const problems = input.problems.slice(-DEVS_REPORT_LIMITS.problems).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.problemChars));lines.push(...(problems.length ? problems : ["(none)"]));+ if (input.cloudComputers?.length) lines.push("", "## Cloud computers since the server started", ...input.cloudComputers.slice(0, DEVS_REPORT_LIMITS.problems).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.problemChars)));lines.push("", "## Server warnings and errors, newest last");const log = input.log.slice(-DEVS_REPORT_LIMITS.logLines).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.logLineChars));lines.push(...(log.length ? log : ["(none since the server started)"]));diff --git a/server/host/cloud-computer-power.test.ts b/server/host/cloud-computer-power.test.tsindex 490a0eae2e..bb3c63e858 100644--- a/server/host/cloud-computer-power.test.ts+++ b/server/host/cloud-computer-power.test.ts@@ -524,4 +524,43 @@ describe("cloud computer power", () => {expect(sleeps().sort()).toEqual(["elsewhere", "paused", "unscheduled"]);});});+ describe("a computer the provider calls ready", () => {+ type Wait = { woke?: boolean; onPhase?: (phase: "waking" | "restoring") => void };+ const withReadiness = (awaitAnswer: (boxId: string, opts: Wait) => Promise<{ ok: true; waitedMs: number } | { ok: false; phase: "waking" | "restoring"; waitedMs: number }>) =>+ createCloudComputerPower({+ cfg: { box: { token: "box_test" } }, busy: () => false, claim: () => () => {}, owners: () => [], routines: () => [], routineComputer: () => null,+ broadcast: () => {}, log: () => {}, readiness: { awaitAnswer: (_cfg, boxId, opts = {}) => awaitAnswer(boxId, opts) },+ });++ it("has to answer before the turn uses it: one this process woke is asked afresh, one already on is asked as usual", async () => {+ const asked: Array<[string, boolean]> = [];+ const local = withReadiness(async (boxId, opts) => { asked.push([boxId, opts.woke === true]); return { ok: true, waitedMs: 0 }; });+ fake.states.set("asleep", "archived");+ fake.states.set("awake", "ready");+ const woken = await local.start(bot("asleep"), turn("t1"));+ await local.answering(woken!.id);+ await local.answering(woken!.id);+ const on = await local.start(bot("awake"), turn("t2"));+ await local.answering(on!.id);+ expect(asked).toEqual([[boxIdOf("asleep"), true], [boxIdOf("asleep"), false], [boxIdOf("awake"), false]]);+ local.close();+ });++ it("fails the start in passing words when it stays silent, never as a computer that did not start", async () => {+ const { cloudRefusal } = await import("../../shared/place-view.ts");+ const { cloudFailureOf } = await import("../boat-limit.ts");+ const { transientClaimFailure } = await import("../auto-vm-claims.ts");+ for (const phase of ["waking", "restoring"] as const) {+ const local = withReadiness(async (_boxId, opts) => { opts.onPhase?.(phase); return { ok: false, phase, waitedMs: 90_000 }; });+ let restoring = 0;+ const error = await local.answering("bx_silent", { woke: true, onRestoring: () => { restoring++; } }).catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(Error);+ expect(transientClaimFailure(error)).toBe(true);+ expect(cloudRefusal(cloudFailureOf(error), true).state).toBe("cc-unavailable");+ expect(cloudRefusal(cloudFailureOf(error), false).state).toBe("cc-unavailable");+ expect(restoring).toBe(phase === "restoring" ? 1 : 0);+ local.close();+ }+ });+ });});diff --git a/server/host/cloud-computer-power.ts b/server/host/cloud-computer-power.tsindex 8bf713ef57..161ec63bb8 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 { BOAT_DELETING, BOAT_DELETION_FINISHED, hasPendingBoatDeletionForBot } from "../boat-delete-journal.ts";+import { boatReadiness, type BoatReadiness } from "../boat-ready.ts";import { backgroundCommandRunning } from "../cloud-computer-background.ts";import { ComputerIdleTimer } from "../computer-idle.ts";import type { AppConfig } from "../config.ts";@@ -21,6 +22,10 @@ const MAX_LISTING_RETRY_MS = 60 * 60_000;export const CLOUD_COMPUTER_START_BUDGET_MS = Math.max(1_000, Number(process.env.OMB_CLOUD_COMPUTER_START_BUDGET_MS) || 150_000);export const CLOUD_COMPUTER_STARTING = "The cloud computer is still starting. This call was not performed. Take a fresh screenshot in a moment.";export const CLOUD_COMPUTER_DID_NOT_START = "the cloud computer didn't start in time";+/** The provider says ready and the computer is silent. Worded apart from a start that failed, and passing: three runs in+ * a row that fail on a start turn their routine off, and a computer that is only slow to answer must not count as one. */+export const CLOUD_COMPUTER_NOT_ANSWERING_YET = "the cloud computer is awake but is not answering yet";+export const CLOUD_COMPUTER_DISK_NOT_BACK_YET = "the cloud computer is awake but still restoring its disk";const REMOVAL_POLL_MS = 3_000;type ScheduledRoutine = Pick<Routine, "botId" | "runOn" | "enabled" | "nextRunAt">;@@ -38,6 +43,7 @@ export interface CloudComputerPowerDeps {routineComputer(routine: ScheduledRoutine): string | null;broadcast(payload: Record<string, unknown>): void;log(line: string): void;+ readiness?: Pick<BoatReadiness, "awaitAnswer">;}export function createCloudComputerPower(deps: CloudComputerPowerDeps) {@@ -46,6 +52,9 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {const turnOwners = new Map<string, { generation: string; owner: string }>();/** A start can outlive the turn that asked for it; stopping a computer mid-create would make provisionBoat delete it. */const starting = new Map<string, number>();+ const readiness = deps.readiness ?? boatReadiness;+ /** Computers this process created or woke and has not yet heard answer. */+ const unheard = new Set<string>();let listingRetry: ReturnType<typeof setTimeout> | null = null;let closed = false;@@ -136,12 +145,14 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {await provisionOnceRemoved(bot, deadline);b = await boat.findBoat(cfg, bot.id);lifecycle = lifecycleOf();+ if (typeof b?.id === "string") unheard.add(b.id);}// An archived Boat answers every action with an error until it resumes: wake it once here.if (lifecycle === "wake") {broadcast({ kind: "computer", botId: bot.id, state: "waking", place: "cloud" });b = (await boat.readyBoat(cfg, bot.id, Math.max(1_000, deadline - Date.now()))) ?? b;lifecycle = lifecycleOf();+ if (typeof b?.id === "string") unheard.add(b.id);}return b && lifecycle === "attach" ? b : null;}@@ -176,8 +187,22 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {}}+ /** After a start, before the turn's first call is sent: the computer has to answer a command, not only be reported+ * ready. One that answered moments ago is not asked again. The failure is passing, so the turn's next call tries again. */+ async function answering(boxId: string, opts: { woke?: boolean; onRestoring?: () => void } = {}): Promise<void> {+ const answer = await readiness.awaitAnswer(cfg, boxId, {+ woke: opts.woke === true || unheard.has(boxId),+ onPhase: (phase) => { if (phase === "restoring") opts.onRestoring?.(); },+ });+ if (!answer.ok) {+ throw Object.assign(new Error(answer.phase === "restoring" ? CLOUD_COMPUTER_DISK_NOT_BACK_YET : CLOUD_COMPUTER_NOT_ANSWERING_YET), { status: 503, transient: true });+ }+ unheard.delete(boxId);+ }+return {start,+ answering,attached,released,used,diff --git a/server/host/cloud-computer-run-gate.test.ts b/server/host/cloud-computer-run-gate.test.tsnew file mode 100644index 0000000000..3957b202a3--- /dev/null+++ b/server/host/cloud-computer-run-gate.test.ts@@ -0,0 +1,151 @@+import { describe, expect, it } from "vitest";++import { RUN_COMPUTER_LINES, type CloudComputerRecoveryState } from "../../shared/cloud-computer-recovery.ts";+import type { BoatAnswer } from "../boat-ready.ts";+import type { RecoveryVerdict } from "../boat-recovery.ts";+import { createRunComputerGate, RUN_COMPUTER_WAIT_MS } from "./cloud-computer-run-gate.ts";++const RUN = { routineId: "routine-1", botId: "bot-1", target: "bot", runOn: "cloud" };++function harness(over: { state?: string; answers?: (wait: number) => boolean; wakes?: boolean } = {}) {+ let at = 0;+ const seen = { finds: 0, wakes: 0, waits: [] as boolean[], signals: [] as Array<AbortSignal | undefined>, used: 0 };+ const world = { verdict: null as RecoveryVerdict | null, verdictAt: 0, routine: "routine-1" as string | null, recovery: null as CloudComputerRecoveryState | null, machine: { id: "bx_23456789", state: over.state ?? "idle" } as { id: string; state: string } | null };+ const gate = createRunComputerGate({+ computerOf: () => "bot-1",+ find: async () => { seen.finds++; return world.machine; },+ wake: async () => { seen.wakes++; return over.wakes === false ? null : { id: "bx_23456789", state: "idle" }; },+ awaitAnswer: async (_boxId, opts): Promise<BoatAnswer> => {+ seen.waits.push(opts.woke);+ seen.signals.push(opts.signal);+ if (over.answers?.(seen.waits.length) ?? true) return { ok: true, waitedMs: 0 };+ at += 90_000;+ return { ok: false, phase: "waking", waitedMs: 90_000 };+ },+ verdict: (_owner, since) => (world.verdict && world.verdictAt >= since ? world.verdict : null), recoveryState: () => world.recovery,+ used: () => { seen.used++; }, routineOf: () => world.routine, log: () => {}, now: () => at,+ });+ return { gate, seen, world, used: () => gate.callSettled("bot-1", "thread-1", true), now: () => at, advance: (ms: number) => { at += ms; } };+}++describe("an unattended run and its cloud computer", () => {+ it("wakes nothing for a routine that has not used the computer, or a run that is not a bot's", async () => {+ const h = harness();+ expect(h.gate.prepare(RUN)).toBeNull();+ h.used();+ expect(h.gate.prepare({ ...RUN, target: "room-goal" })).toBeNull();+ expect(h.seen.finds).toBe(0);+ });++ it("starts at once when the computer is awake and answers", async () => {+ const h = harness();+ h.used();+ await expect(h.gate.prepare(RUN)).resolves.toBeNull();+ expect(h.seen).toMatchObject({ wakes: 0, waits: [false], used: 1 });+ });++ it("wakes a sleeping computer and waits for its answer, however recently it answered", async () => {+ const h = harness({ state: "archived" });+ h.used();+ await expect(h.gate.prepare(RUN)).resolves.toBeNull();+ expect(h.seen).toMatchObject({ wakes: 1, waits: [true] });+ });++ it("leaves a bot with no computer yet to its turn", async () => {+ const h = harness();+ h.used();+ h.world.machine = null;+ await expect(h.gate.prepare(RUN)).resolves.toBeNull();+ expect(h.seen.waits).toEqual([]);+ });++ it("says so when the computer does not wake", async () => {+ const h = harness({ state: "archived", wakes: false });+ h.used();+ await expect(h.gate.prepare(RUN)).resolves.toBe(RUN_COMPUTER_LINES.noWake);+ });++ it("keeps waiting while the recovery works on a silent computer, and starts once it answers", async () => {+ const h = harness({ answers: (wait) => wait >= 4 });+ h.used();+ await expect(h.gate.prepare(RUN)).resolves.toBeNull();+ expect(h.seen.waits).toEqual([false, true, true, true]);+ expect(h.seen.used).toBe(4);+ });++ it.each<[RecoveryVerdict, string]>([+ ["restart-failed", RUN_COMPUTER_LINES.afterRestart], ["person-busy", RUN_COMPUTER_LINES.personBusy],+ ["restart-limited", RUN_COMPUTER_LINES.restartLimited], ["shared", RUN_COMPUTER_LINES.shared],+ ])("ends with the reason once the recovery left the computer as it is (%s)", async (verdict, line) => {+ const h = harness({ answers: () => false });+ h.used();+ h.world.verdict = verdict;+ h.world.verdictAt = 1;+ await expect(h.gate.prepare(RUN)).resolves.toBe(line);+ });++ it("does not take a verdict from an earlier silence for this wait's", async () => {+ const h = harness({ answers: (wait) => wait >= 2 });+ h.used();+ h.world.verdict = "restart-failed";+ h.world.verdictAt = 500;+ h.advance(60_000);+ await expect(h.gate.prepare(RUN)).resolves.toBeNull();+ expect(h.seen.waits).toHaveLength(2);+ });++ it("reads the verdict once more when the recovery has ended, so a reason written a moment later is not missed", async () => {+ let reads = 0;+ const gate = createRunComputerGate({+ computerOf: () => "bot-1", find: async () => ({ id: "bx_23456789", state: "idle" }), wake: async () => null,+ awaitAnswer: async () => ({ ok: false, phase: "waking", waitedMs: 90_000 }),+ // Nothing at the first read; written by the time the state reads as ended.+ verdict: () => (++reads >= 2 ? "restart-failed" : null), recoveryState: () => "needs-person",+ used: () => {}, routineOf: () => "routine-1", log: () => {}, now: () => 0,+ });+ gate.callSettled("bot-1", "thread-1", true);+ await expect(gate.prepare(RUN)).resolves.toBe(RUN_COMPUTER_LINES.afterRestart);+ });++ it("stops waiting, and wakes nothing more, once the run it waits for is gone", async () => {+ const stop = new AbortController();+ const h = harness({ answers: () => { stop.abort(); return false; } });+ h.used();+ await expect(h.gate.prepare(RUN, stop.signal)).resolves.toBeNull();+ expect(h.seen.waits).toHaveLength(1);+ expect(h.seen.signals[0]).toBe(stop.signal);+ const gone = new AbortController();+ gone.abort();+ const asleep = harness({ state: "archived" });+ asleep.used();+ await asleep.gate.prepare(RUN, gone.signal);+ expect(asleep.seen.wakes).toBe(0);+ });++ it("gives up after twenty minutes whatever the recovery is doing", async () => {+ const h = harness({ answers: () => false });+ h.used();+ await expect(h.gate.prepare(RUN)).resolves.toBe(RUN_COMPUTER_LINES.noAnswer);+ expect(h.now()).toBeGreaterThanOrEqual(RUN_COMPUTER_WAIT_MS - 5_000);+ expect(h.now()).toBeLessThanOrEqual(RUN_COMPUTER_WAIT_MS + 90_000);+ });++ it("leaves a run that ended well as done, with a note, when its last computer call got no answer: it is not run again", () => {+ const h = harness();+ h.gate.callSettled("bot-1", "thread-1", false);+ expect(h.gate.turnEnded("thread-1", true)).toBe(RUN_COMPUTER_LINES.lastCallUnanswered);+ expect(h.gate.turnEnded("thread-1", true)).toBeNull();+ h.gate.callSettled("bot-1", "thread-1", false);+ h.gate.callSettled("bot-1", "thread-1", true);+ expect(h.gate.turnEnded("thread-1", true)).toBeNull();+ });++ it("says nothing for a turn that failed, which the scheduler starts once more as it does any failed run, or for a person's own turn", () => {+ const h = harness();+ h.gate.callSettled("bot-1", "thread-1", false);+ expect(h.gate.turnEnded("thread-1", false)).toBeNull();+ h.world.routine = null;+ h.gate.callSettled("bot-1", "thread-2", false);+ expect(h.gate.turnEnded("thread-2", true)).toBeNull();+ });+});diff --git a/server/host/cloud-computer-run-gate.ts b/server/host/cloud-computer-run-gate.tsnew file mode 100644index 0000000000..af5458cdb4--- /dev/null+++ b/server/host/cloud-computer-run-gate.ts@@ -0,0 +1,117 @@+// An unattended run (a routine, an automation, a webhook) has nobody watching a computer that is awake but silent. Before+// such a run starts, its cloud computer is woken and has to answer; while it does not, the recovery in boat-recovery.ts+// waits for a disk restore and restarts it once, and the run either starts or ends with the reason. A run whose computer+// ended well but whose last computer call got no answer is left as done, with a note: starting it again could repeat+// what it already did (a message sent, a pull request opened). Only a run nobody started by hand is held.+//+// Waking costs computer time, and many routines never touch the bot's cloud computer, so only a routine whose earlier+// run used the computer is woken for; the first run after a server start is not, and waits at its first computer call.+import { RUN_COMPUTER_LINES, type CloudComputerRecoveryState } from "../../shared/cloud-computer-recovery.ts";+import type { BoatAnswer } from "../boat-ready.ts";+import type { RecoveryVerdict } from "../boat-recovery.ts";++/** The longest a run waits for its computer before it starts: one minute to notice the silence, up to ten for a disk+ * restore the provider reports, then one restart (stop, wake, and the wait for an answer) with room to spare. */+export const RUN_COMPUTER_WAIT_MS = 20 * 60_000;+const WAKE_BUDGET_MS = 150_000;+const MAX_ROUTINES = 500;+const ENDED = new Set<CloudComputerRecoveryState>(["needs-person", "unreachable", "capped"]);+const SLEEPING = new Set(["archived", "archiving"]);++interface RunLike { routineId: string; botId: string; target: string; runOn?: string }+interface Machine { id: string; state: string }++export interface RunComputerGateDeps {+ /** The owner key of the cloud computer this run's turns use, or null when they use none. */+ computerOf(run: RunLike): string | null;+ find(owner: string): Promise<Machine | null>;+ /** Wakes the owner's sleeping computer, never creates one; null when it did not wake in time. */+ wake(owner: string, budgetMs: number): Promise<Machine | null>;+ awaitAnswer(boxId: string, opts: { woke: boolean; deadline: number; signal?: AbortSignal }): Promise<BoatAnswer>;+ /** Why the recovery left the owner's silent computer as it is, when it decided that at or after `since`. */+ verdict(owner: string, since: number): RecoveryVerdict | null;+ recoveryState(owner: string): CloudComputerRecoveryState | null;+ /** Restarts the owner's idle window, so the wait itself does not put the computer to sleep. */+ used(owner: string): void;+ /** The routine whose run is active in this bot's thread, if one is. */+ routineOf(botId: string, threadId: string): string | null;+ log(line: string): void;+ now?(): number;+}++const VERDICT_LINE: Record<RecoveryVerdict, string> = {+ "restart-failed": RUN_COMPUTER_LINES.afterRestart, "person-busy": RUN_COMPUTER_LINES.personBusy,+ "restart-limited": RUN_COMPUTER_LINES.restartLimited, shared: RUN_COMPUTER_LINES.shared,+};++export function createRunComputerGate(deps: RunComputerGateDeps) {+ const now = deps.now ?? Date.now;+ /** Routines whose runs have used the cloud computer since the server started. */+ const usesComputer = new Set<string>();+ /** Threads whose latest computer call got no answer, with the bot whose turn it was. */+ const silent = new Map<string, string>();++ async function ready(owner: string, signal?: AbortSignal): Promise<string | null> {+ const began = now();+ let machine = await deps.find(owner).catch(() => null);+ if (!machine || signal?.aborted) return null;+ let woke = false;+ if (SLEEPING.has(machine.state)) {+ machine = await deps.wake(owner, WAKE_BUDGET_MS).catch(() => null);+ if (!machine) return RUN_COMPUTER_LINES.noWake;+ woke = true;+ }+ const deadline = now() + RUN_COMPUTER_WAIT_MS;+ for (;;) {+ if (signal?.aborted) return null;+ deps.used(owner);+ const answer = await deps.awaitAnswer(machine.id, { woke, deadline, ...(signal ? { signal } : {}) });+ if (answer.ok || signal?.aborted) return null;+ // A verdict from before this wait belongs to an earlier silence, not this one.+ const why = deps.verdict(owner, began);+ if (why) return VERDICT_LINE[why];+ const state = deps.recoveryState(owner);+ if ((state && ENDED.has(state)) || now() >= deadline - 5_000) {+ // The recovery writes its verdict before it ends; read once more in case it ended between the two reads above.+ const late = deps.verdict(owner, began);+ return late ? VERDICT_LINE[late] : RUN_COMPUTER_LINES.noAnswer;+ }+ woke = true;+ }+ }++ return {+ /** null: nothing to wait for. Otherwise resolves null once the computer answers, or with why the run cannot start. */+ prepare(run: RunLike, signal?: AbortSignal): Promise<string | null> | null {+ if (run.target !== "bot" || !usesComputer.has(run.routineId)) return null;+ const owner = deps.computerOf(run);+ if (!owner) return null;+ return ready(owner, signal).then((reason) => {+ if (reason) deps.log(`routine ${run.routineId}: its cloud computer (${owner}) was not ready: ${reason}`);+ return reason;+ }, (error) => {+ // A lookup that fails is the turn's to report in its own words.+ deps.log(`routine ${run.routineId}: could not check its cloud computer: ${error instanceof Error ? error.message : String(error)}`);+ return null;+ });+ },+ /** After each computer call of a turn: whether the computer answered it. */+ callSettled(botId: string, threadId: string, answered: boolean): void {+ if (!answered) { silent.set(threadId, botId); return; }+ silent.delete(threadId);+ const routineId = deps.routineOf(botId, threadId);+ if (!routineId || usesComputer.has(routineId)) return;+ if (usesComputer.size >= MAX_ROUTINES) usesComputer.clear();+ usesComputer.add(routineId);+ },+ /** When a turn ends: the note for an unattended run that ended well although its last computer call got no answer.+ * The run stays done. A turn that failed is the scheduler's to start once more, as any failed run is. */+ turnEnded(threadId: string, ok: boolean): string | null {+ const botId = silent.get(threadId);+ silent.delete(threadId);+ return ok && botId !== undefined && deps.routineOf(botId, threadId) ? RUN_COMPUTER_LINES.lastCallUnanswered : null;+ },+ };+}++export type RunComputerGate = ReturnType<typeof createRunComputerGate>;diff --git a/server/host/devs-reports.ts b/server/host/devs-reports.tsindex 19c4a6e4b5..bb526617b9 100644--- a/server/host/devs-reports.ts+++ b/server/host/devs-reports.ts@@ -33,6 +33,7 @@ import { personKey } from "../person-key.ts";import type { RecentLog } from "../recent-log.ts";import { PASS } from "../routes/table.ts";import { serverLine, type LineLanguage } from "../server-lines.ts";+import { cloudComputerCounters } from "../cloud-computer-counters.ts";import type { PublicSession } from "../sessions.ts";import type { BotRecord, Message, Store, StoreChange } from "../store.ts";import { droppedLine, fullLine, laterLine, notYetLine, refusedLine, sentLine } from "./devs-report-words.ts";@@ -348,7 +349,7 @@ export function createDevsReports(deps: DevsReportsDeps) {threadId: entry.threadId, messageId: entry.messageId, ...(groupId ? { groupId } : {}), where, message: entry.text, words: entry.words,bots: bots.map((bot) => reported(bot, entry.threadId)),...("bot" in author ? { summary: { by: author.bot.name, text: author.summary } } : { noSummary: author.why }),- problems: conversationProblems(store.activePath(entry.threadId)), log: deps.recentLog(), contactEmail: contact,+ problems: conversationProblems(store.activePath(entry.threadId)), log: deps.recentLog(), cloudComputers: cloudComputerCounters.lines(), contactEmail: contact,}, secrets());return { payload, ...(contact ? { contact } : {}) };}diff --git a/server/index.ts b/server/index.tsindex b62fd6f6c0..10d9906098 100644--- a/server/index.ts+++ b/server/index.ts@@ -94,7 +94,7 @@ import type { DirectSendInput, DirectSendReceipt } from "./direct-send.ts";import { finishedWithoutSummaryLine, ROOM_SUMMARY_REASK, roomTurnNarrationIds, roomTurnReply } from "./room-reply.ts";import { chosenPlace, pickComputer } from "./computer-selection.ts";import * as boat from "./boat.ts"; import { keyHint, keyStatus, nestedKeyStatus, withoutKeyHints } from "./key-hint.ts";-import { cloudComputerRpc } from "./cloud-computer-tools.ts"; import { createBoatRecovery } from "./boat-recovery.ts"; import { CLOUD_COMPUTER_PERSON_LINES } from "../shared/cloud-computer-recovery.ts";+import { cloudComputerRpc } from "./cloud-computer-tools.ts"; import { createBoatRecovery } from "./boat-recovery.ts"; import { CLOUD_COMPUTER_PERSON_LINES, CLOUD_COMPUTER_RESTORING, RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts"; import { boatReadiness } from "./boat-ready.ts"; import { createRunComputerGate } from "./host/cloud-computer-run-gate.ts";import { chartRenderer, compileChart, dataEngine, validateVegaLite } from "./data/deps.ts";import { BUILT_IN_DATA_SYSTEM_PROMPT } from "./data/instructions.ts";import { DATA_INTERNAL_MCP_PATH, dataRpc } from "./data/rpc.ts";@@ -5673,7 +5673,7 @@ const meetingsHost = createMeetingsHost({ cfg, dataDir: DATA_DIR, store, startTuroutineComputer: routine => { const bot = store.bot(routine.botId); return bot && turnProvider(bot, routine.runOn) === "box" ? botComputerControlKey(bot) : null; },busy: owner => computerProviderConfigTransitions.has("box") || boatLifecycleBusyBots.has(owner) || managedBoatOwners().some(entry => entry.botId === owner && entry.inUse) || meetingsHost.keepsAwake(owner),claim: owner => { const team = teamComputers.list().find(entry => teamComputerOwner(entry.id) === owner); return team ? claimTeamComputerLifecycle(team) : claimBotComputerLifecycle(owner); },-}); const boatRecovery = createBoatRecovery({ cfg: () => cfg, log: line => console.warn(line), eligible: owner => { const bot = store.bot(owner); return Boolean(bot) && botComputerControlKey(bot!) === owner; }, personActive: owner => computerControl.snapshot(owner).held || desktopViewer.viewing(owner) > 0, tell: (owner, key) => { const team = teamComputers.list().find(entry => teamComputerOwner(entry.id) === owner); if (team) { teamComputers.setProblem(team.id, serverLine(appLanguage(), CLOUD_COMPUTER_PERSON_LINES.teamNotResponding, { name: team.name })); return; } const bot = store.bot(owner); if (!bot) return; const text = serverLine(conversationLanguage(bot.threadId), CLOUD_COMPUTER_PERSON_LINES[key], { name: bot.name }); store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${text}`, ok: true } }); notify(buildNoticeNotification(bot, bot.threadId, text)); } });+}); const boatRecovery = createBoatRecovery({ cfg: () => cfg, log: line => console.warn(line), eligible: owner => { const bot = store.bot(owner); return Boolean(bot) && botComputerControlKey(bot!) === owner; }, personActive: owner => computerControl.snapshot(owner).held || desktopViewer.viewing(owner) > 0, tell: (owner, key) => { const team = teamComputers.list().find(entry => teamComputerOwner(entry.id) === owner); if (team) { teamComputers.setProblem(team.id, serverLine(appLanguage(), CLOUD_COMPUTER_PERSON_LINES.teamNotResponding, { name: team.name })); return; } const bot = store.bot(owner); if (!bot) return; const text = serverLine(conversationLanguage(bot.threadId), CLOUD_COMPUTER_PERSON_LINES[key], { name: bot.name }); store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${text}`, ok: true } }); notify(buildNoticeNotification(bot, bot.threadId, text)); } }); const runComputers = createRunComputerGate({ computerOf: (run) => { const bot = store.bot(run.botId); return bot && turnProvider(bot, run.runOn as RoutineRunOn | undefined) === "box" ? botComputerControlKey(bot) : null; }, find: (owner) => boat.findBoat(cfg, owner), wake: (owner, budgetMs) => boat.readyBoat(cfg, owner, budgetMs), awaitAnswer: (boxId, opts) => boatReadiness.awaitAnswer(cfg, boxId, opts), verdict: (owner, since) => boatRecovery.verdict(owner, since), recoveryState: (owner) => boatRecovery.status(owner)?.state ?? null, used: (owner) => cloudComputerPower.used(owner), routineOf: (botId, threadId) => { const run = routines?.activeRunForBot(botId); return run?.threadId === threadId ? run.routineId : null; }, log: (line) => console.warn(line) });function inheritedTeamComputer(bot: Pick<BotRecord, "section" | "computer" | "cloudBackend">): TeamComputerRecord | undefined {return teamComputers.forBot(bot);@@ -5794,7 +5794,7 @@ async function attachTeamBoat(computer: TeamComputerRecord, owner: TurnOwner, onif (!machine || boat.boatTurnLifecycleAction(typeof machine.state === "string" ? machine.state : null) !== "attach") {throw new Error("The team computer is not ready; check it in the Team map");}- if (turnResourceOwners.get(owner.threadId)?.generation !== owner.generation ||+ await cloudComputerPower.answering(machine.id as string, { woke: action === "wake" }); if (turnResourceOwners.get(owner.threadId)?.generation !== owner.generation ||!turnResources.owns(`computer:box:${machine.id}`, owner)) throw new Error("This computer turn ended while its machine was starting");return { boxId: machine.id as string, capture: () => boat.screenshotBoat(cfg, ownerId, machine!.id) };}@@ -5900,7 +5900,7 @@ function mountBotBoat(try {attached = await attachBotBoat(bot, owner, {budgetMs: CLOUD_COMPUTER_START_BUDGET_MS,- onSeated: () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; }, existingOnly: opts.existingOnly,+ onSeated: () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; }, onRestoring: () => { slot.pendingReason = CLOUD_COMPUTER_RESTORING; }, existingOnly: opts.existingOnly,});if (!attached) throw new Error(opts.existingOnly ? "this bot no longer has a cloud computer of its own" : "the cloud computer could not be created or reached");} catch (error) {@@ -5922,12 +5922,12 @@ function claimedBoatId(capability: InternalCapability): string | undefined {}/** The Cloud place is the consent boundary to create or wake a Boat (which un-pauses billing); Auto never reaches here. */-async function attachBotBoat(bot: BotRecord, owner: TurnOwner, start: { budgetMs: number; onSeated: () => void; existingOnly?: boolean }) {+async function attachBotBoat(bot: BotRecord, owner: TurnOwner, start: { budgetMs: number; onSeated: () => void; onRestoring?: () => void; existingOnly?: boolean }) {// Claim before any network await so setup itself cannot race another turn.await bindTurnComputer(owner, `computer:box-bot:${bot.id}`, true);start.onSeated();const machine = await withinBudget(cloudComputerPower.start(bot, owner, { existingOnly: start.existingOnly, budgetMs: start.budgetMs }), start.budgetMs, CLOUD_COMPUTER_DID_NOT_START);- if (!machine) return null;+ if (!machine) return null; await cloudComputerPower.answering(machine.id as string, { onRestoring: start.onRestoring });await bindTurnComputer(owner, `computer:box:${machine.id}`);return {boxId: machine.id as string,@@ -6370,7 +6370,7 @@ bus.subscribe((event: RuntimeEvent) => {const publicEvent = event.type === "request.opened" ? { ...event, command: undefined, commandLine: undefined, reads: undefined } : publicReplyEvent(event, groupSpeakers.get(event.threadId)?.botId);broadcast({ kind: "runtime", event: publicEvent });}- const routineRun = privateImageEvent ? null : (routines?.handleRuntimeEvent(event) ?? null);+ if (event.type === "turn.completed") { const note = runComputers.turnEnded(event.threadId, event.ok); if (note) store.appendMessage(event.threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${note}`, ok: true } }); } const routineRun = privateImageEvent ? null : (routines?.handleRuntimeEvent(event) ?? null);const replayed = savedSteps.dispatch.answering(event); limitClock.noteRuntimeEvent(replayed ? undefined : runningTurnEngines.get(event.threadId)?.instanceId, event);const ownerBot = store.botByThread(event.threadId); // A quick route's model is the one this turn ran on, so its holds and its working turns are that model's.const bot = ownerBot ? botForThread(ownerBot.id, event.threadId) ?? undefined : undefined; if (bot && !replayed) limitTakeover.noteRuntimeEvent(bot.id, { ...bot.modelSelection, model: quickFallback.routedModel(event.threadId) ?? bot.modelSelection.model }, event);@@ -8789,7 +8789,7 @@ routines = new RoutineManager({limitBackup: (botId, scope) => { const bot = store.bot(botId); return quotaSwitchEnabled() ? Boolean(bot && limitTakeover.backups(botId, bot.modelSelection, scope, approvalModeFor(bot)).length) : Boolean(bot && startupBackups(bot, cfg.automaticRecovery).length); },launchId: DESKTOP_MANAGED && /^[\w-]{1,100}$/.test(process.env.OMB_DESKTOP_LAUNCH_ID ?? "")? process.env.OMB_DESKTOP_LAUNCH_ID : undefined,- skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), // a Cloud home waking from a sleep it was stopped for+ skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), prepareRun: (run, signal) => runComputers.prepare(run, signal), preparing: RUN_COMPUTER_LINES.waking, // a Cloud home waking from a sleep it was stopped forhasPendingDelegations: runtimeWorkPending, refusedHandoff: refusedHandoffs.take, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined, personTurn: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "user",botState: unattendedDispatchState, pausedText: (botId) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? starterCaps.pausedText(botId, threadLanguage(store.bot(botId)?.threadId ?? "")), held: (botId) => botHolds.held(botId),@@ -13091,7 +13091,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {cfg, signal: abort.signal, folder: () => messageFileRootsForThread(internalCapability.botId, internalCapability.threadId)[0],boxId: () => internalCapability.boxId ?? claimedBoatId(internalCapability),gate: () => computerCallGate(internalCapability, abort.signal),- assertActive: requireActiveInternalCapability, recovery: boatRecovery,+ assertActive: requireActiveInternalCapability, recovery: boatRecovery, settled: (answered) => runComputers.callSettled(internalCapability.botId, internalCapability.threadId, answered),}) });}// DuckDB runs here on the bot's own database; the agent process holds only the turn's capability.diff --git a/server/routes/cloud-computer-recovery.test.ts b/server/routes/cloud-computer-recovery.test.tsindex 1fdbf3f6b8..899848ac67 100644--- a/server/routes/cloud-computer-recovery.test.ts+++ b/server/routes/cloud-computer-recovery.test.ts@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from "vitest";import { json, readBody } from "../harness/http.ts";import { requiredScope } from "../request-auth.ts";import type { BotRecord } from "../store.ts";-import { createCloudComputerRecoveryRoutes, type CloudComputerRecoveryRouteDeps } from "./cloud-computer-recovery.ts";+import { cloudComputerAnswering, createCloudComputerRecoveryRoutes, type CloudComputerRecoveryRouteDeps } from "./cloud-computer-recovery.ts";import { dispatchRoutes } from "./table.ts";const servers: Server[] = [];@@ -45,6 +45,29 @@ async function serve(deps: Partial<CloudComputerRecoveryRouteDeps> = {}, actionsconst post = (url: string, body: unknown, contentType = "application/json") =>fetch(url, { method: "POST", headers: { "content-type": contentType }, body: JSON.stringify(body) });+describe("whether a cloud computer answers", () => {+ const health = (silentSince: number | null, lastAnsweredAt: number | null) => ({ notRespondingSince: () => silentSince, lastAnsweredAt: () => lastAnsweredAt });+ const waiting = (on: { phase: "waking" | "restoring"; since: number } | null) => ({ waitingOn: () => on });++ it("says nothing about a computer this server has not used", () => {+ expect(cloudComputerAnswering(null, health(null, null), waiting(null))).toBeNull();+ expect(cloudComputerAnswering("bx_23456789", health(null, null), waiting(null))).toBeNull();+ });++ it("is awake once a command was answered, with when", () => {+ expect(cloudComputerAnswering("bx_23456789", health(null, 500), waiting(null))).toEqual({ state: "awake", lastAnsweredAt: 500 });+ });++ it("is waking or restoring its disk while a call waits for its first answer", () => {+ expect(cloudComputerAnswering("bx_23456789", health(null, 500), waiting({ phase: "waking", since: 900 }))).toEqual({ state: "waking", since: 900, lastAnsweredAt: 500 });+ expect(cloudComputerAnswering("bx_23456789", health(null, null), waiting({ phase: "restoring", since: 900 }))).toEqual({ state: "restoring", since: 900, lastAnsweredAt: null });+ });++ it("is not responding, since when, once it counts as silent, whatever is waiting on it", () => {+ expect(cloudComputerAnswering("bx_23456789", health(700, 500), waiting({ phase: "waking", since: 900 }))).toEqual({ state: "not-responding", since: 700, lastAnsweredAt: 500 });+ });+});+describe("the computer panel's recovery routes", () => {it("are for admins only", () => {expect(requiredScope("GET", "/api/bots/bot-1/computer/recovery")).toBe("admin");@@ -55,7 +78,7 @@ describe("the computer panel's recovery routes", () => {const { base } = await serve();const response = await fetch(`${base}/bot-1/computer/recovery`);expect(response.headers.get("cache-control")).toContain("no-store");- expect(await response.json()).toEqual({ recovery: { state: "replaced", at: 1 } });+ expect(await response.json()).toEqual({ recovery: { state: "replaced", at: 1 }, answering: null });expect((await fetch(`${base}/nobody/computer/recovery`)).status).toBe(404);});diff --git a/server/routes/cloud-computer-recovery.ts b/server/routes/cloud-computer-recovery.tsindex 5136deb316..0208615c1c 100644--- a/server/routes/cloud-computer-recovery.ts+++ b/server/routes/cloud-computer-recovery.ts@@ -1,3 +1,7 @@+import type { CloudComputerAnswering } from "../../shared/cloud-computer-recovery.ts";+import { boatIdOf } from "../boat.ts";+import { boatHealth, type BoatHealth } from "../boat-health.ts";+import { boatReadiness, type BoatReadiness } from "../boat-ready.ts";import type { BoatRecovery } from "../boat-recovery.ts";import type { BotRecord, Store } from "../store.ts";import type { RemoteComputerProvider } from "./config.ts";@@ -14,8 +18,21 @@ export interface CloudComputerRecoveryRouteDeps {cloudComputerUsed(owner: string): void;}+/** Whether a computer this server has used answers its commands; null for one it has not used since it started. */+export function cloudComputerAnswering(+ boxId: string | null, health: Pick<BoatHealth, "notRespondingSince" | "lastAnsweredAt"> = boatHealth, readiness: Pick<BoatReadiness, "waitingOn"> = boatReadiness,+): CloudComputerAnswering | null {+ if (!boxId) return null;+ const lastAnsweredAt = health.lastAnsweredAt(boxId);+ const silentSince = health.notRespondingSince(boxId);+ if (silentSince !== null) return { state: "not-responding", since: silentSince, lastAnsweredAt };+ const waiting = readiness.waitingOn(boxId);+ if (waiting) return { state: waiting.phase, since: waiting.since, lastAnsweredAt };+ return lastAnsweredAt === null ? null : { state: "awake", lastAnsweredAt };+}+/** GET and POST /api/bots/:id/computer/recovery: what MausBot is doing about a bot's cloud computer that stopped answering,- * and the computer panel's Restart computer and Replace computer. Admin-only like every computer route. */+ * whether it answers now, and the computer panel's Restart computer and Replace computer. Admin-only like every computer route. */export function createCloudComputerRecoveryRoutes(deps: CloudComputerRecoveryRouteDeps): RouteHandler {return async ({ req, res, path, method, json, readBody }) => {const m = path.match(/^\/api\/bots\/([\w-]+)\/computer\/recovery$/);@@ -25,7 +42,7 @@ export function createCloudComputerRecoveryRoutes(deps: CloudComputerRecoveryRouconst owner = deps.botComputerControlKey(bot);if (method === "GET") {res.setHeader("cache-control", "private, no-store");- return json(res, 200, { recovery: owner === bot.id ? deps.boatRecovery.status(owner) : null });+ return json(res, 200, { recovery: owner === bot.id ? deps.boatRecovery.status(owner) : null, answering: owner === bot.id ? cloudComputerAnswering(boatIdOf(owner)) : null });}if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {return json(res, 415, { error: "content-type must be application/json" });diff --git a/server/routine-run-gate.test.ts b/server/routine-run-gate.test.tsnew file mode 100644index 0000000000..3b52421450--- /dev/null+++ b/server/routine-run-gate.test.ts@@ -0,0 +1,140 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { createRunGate } from "./routine-run-gate.ts";+import { RoutineManager } from "./routines.ts";++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });+const settle = () => new Promise((resolve) => setTimeout(resolve, 5));++describe("holding a run while something it needs is made ready", () => {+ it("starts a run nothing is prepared for, holds one being prepared, and reads each result once", async () => {+ let finish!: (reason: string | null) => void;+ let settled = 0;+ const gate = createRunGate<{ id: string; slow?: true }>((run) => run.slow ? new Promise((resolve) => { finish = resolve; }) : null, () => { settled++; });+ expect(gate.hold({ id: "quick" })).toBe(false);+ expect(gate.hold({ id: "slow", slow: true })).toBe(true);+ expect(gate.hold({ id: "slow", slow: true })).toBe(true);+ expect(gate.waiting("slow")).toBe(true);+ finish("its computer did not answer");+ await settle();+ expect(settled).toBe(1);+ expect(gate.hold({ id: "slow", slow: true })).toBe("its computer did not answer");+ expect(gate.waiting("slow")).toBe(false);+ });++ it("starts the run when the preparation itself breaks: the run reports its own trouble", async () => {+ const gate = createRunGate<{ id: string }>(() => Promise.reject(new Error("lookup failed")), () => {});+ expect(gate.hold({ id: "a" })).toBe(true);+ await settle();+ expect(gate.hold({ id: "a" })).toBe(false);+ });+});++describe("stopping the work for a run that no longer waits", () => {+ it("aborts it and forgets its result, and leaves a run that still waits alone", async () => {+ const signals = new Map<string, AbortSignal>();+ const finish = new Map<string, (reason: string | null) => void>();+ let settled = 0;+ const gate = createRunGate<{ id: string }>((run, signal) => { signals.set(run.id, signal); return new Promise((resolve) => finish.set(run.id, resolve)); }, () => { settled++; });+ gate.hold({ id: "cancelled" });+ gate.hold({ id: "waiting" });+ gate.sweep((id) => id === "waiting");+ expect(signals.get("cancelled")!.aborted).toBe(true);+ expect(signals.get("waiting")!.aborted).toBe(false);+ expect(gate.waiting("cancelled")).toBe(false);+ finish.get("cancelled")!("its computer did not answer");+ await settle();+ expect(settled).toBe(0);+ // Asked again under the same id it is prepared afresh, never answered with the stale reason.+ expect(gate.hold({ id: "cancelled" })).toBe(true);+ });+});++describe("the scheduler and a run that is being made ready", () => {+ const START = new Date(2026, 10, 14, 8, 0, 0).getTime();+ function harness() {+ const dir = mkdtempSync(join(tmpdir(), "omb-run-gate-"));+ dirs.push(dir);+ let at = START;+ const started: string[] = [];+ const prepared: Array<{ runId: string; signal: AbortSignal }> = [];+ const release = new Map<string, (reason: string | null) => void>();+ let tasks = 0;+ const manager = new RoutineManager({+ file: join(dir, "routines.json"), now: () => at, botState: () => "ready",+ createTask: (botId) => ({ threadId: `${botId}-thread-${++tasks}` }),+ startTurn: async (botId) => { started.push(botId); },+ prepareRun: (run, signal) => {+ if (run.botId !== "cloud-bot") return null;+ prepared.push({ runId: run.id, signal });+ return new Promise((resolve) => release.set(run.id, resolve));+ },+ preparing: "Waiting for its cloud computer",+ });+ const routine = (botId: string) => manager.create({ name: `${botId} sweep`, prompt: "Sweep", botId, schedule: { type: "interval", everyMinutes: 60, anchorAt: START } });+ /** The routines' next scheduled occurrence comes due; answers the runs it made. */+ const due = async () => {+ const before = new Set(manager.listRuns().map((run) => run.id));+ at = Math.max(...manager.listRoutines().map((entry) => entry.nextRunAt ?? at));+ await manager.tick();+ return manager.listRuns().filter((run) => !before.has(run.id));+ };+ return { manager, started, prepared, release, routine, due };+ }+ const runOf = (h: ReturnType<typeof harness>, id: string) => h.manager.listRuns().find((run) => run.id === id)!;++ it("does not hold up other bots' runs, shows why the held one waits, and starts it once ready", async () => {+ const h = harness();+ h.routine("cloud-bot");+ h.routine("other-bot");+ const held = (await h.due()).find((run) => run.botId === "cloud-bot")!;+ expect(h.started).toEqual(["other-bot"]);+ expect(runOf(h, held.id)).toMatchObject({ status: "queued", attention: "Waiting for its cloud computer" });+ h.release.get(held.id)!(null);+ await settle();+ await h.manager.tick();+ expect(h.started).toEqual(["other-bot", "cloud-bot"]);+ expect(runOf(h, held.id).status).toBe("running");+ });++ it("fails the run with the reason, before any turn starts, and leaves the routine on", async () => {+ const h = harness();+ const routine = h.routine("cloud-bot");+ const [held] = await h.due();+ h.release.get(held!.id)!("The cloud computer did not answer after a restart, so this run did not start.");+ await settle();+ await h.manager.tick();+ expect(h.started).toEqual([]);+ expect(runOf(h, held!.id)).toMatchObject({ status: "failed", error: "The cloud computer did not answer after a restart, so this run did not start." });+ expect(h.manager.listRoutines().find((candidate) => candidate.id === routine.id)).toMatchObject({ enabled: true });+ });++ it("never holds a run a person started by hand: its conversation opens at once", async () => {+ const h = harness();+ const run = h.manager.runNow(h.routine("cloud-bot").id)!;+ await h.manager.tick();+ expect(h.prepared).toEqual([]);+ expect(h.started).toEqual(["cloud-bot"]);+ expect(runOf(h, run.id)).toMatchObject({ status: "running", threadId: expect.any(String) });+ });++ it("stops the work for a held run that is cancelled, and never starts it", async () => {+ const h = harness();+ h.routine("cloud-bot");+ const [held] = await h.due();+ expect(h.prepared[0]!.signal.aborted).toBe(false);+ await h.manager.cancelRun(held!.id);+ await settle();+ await h.manager.tick();+ expect(h.prepared[0]!.signal.aborted).toBe(true);+ h.release.get(held!.id)!(null);+ await settle();+ await h.manager.tick();+ expect(h.started).toEqual([]);+ expect(runOf(h, held!.id).status).toBe("cancelled");+ });+});diff --git a/server/routine-run-gate.ts b/server/routine-run-gate.tsnew file mode 100644index 0000000000..7996e85094--- /dev/null+++ b/server/routine-run-gate.ts@@ -0,0 +1,47 @@+/** Holds a queued run back while something it needs is made ready (its cloud computer is woken and has to answer),+ * without holding up the other runs: the work goes on beside the scheduler, which looks again when it settles.+ * `signal` aborts once the run is no longer waiting to start (cancelled, deleted, paused), so the work stops with it. */+export type RunPreparation<R> = (run: R, signal: AbortSignal) => Promise<string | null> | null;++const MAX_SETTLED = 200;++export function createRunGate<R extends { id: string }>(prepare: RunPreparation<R> | undefined, settled: () => void) {+ const pending = new Map<string, AbortController>();+ /** null: ready to start. A string: why it cannot. Read once. */+ const results = new Map<string, string | null>();++ return {+ /** false: start it. true: still being made ready. A string: it cannot start, and why. */+ hold(run: R): boolean | string {+ if (results.has(run.id)) {+ const reason = results.get(run.id)!;+ results.delete(run.id);+ return reason ?? false;+ }+ if (pending.has(run.id)) return true;+ const stop = new AbortController();+ const work = prepare?.(run, stop.signal);+ if (!work) return false;+ pending.set(run.id, stop);+ void work.catch(() => null).then((reason) => {+ if (pending.get(run.id) !== stop) return;+ pending.delete(run.id);+ if (stop.signal.aborted) return;+ if (results.size >= MAX_SETTLED) results.delete(results.keys().next().value!);+ results.set(run.id, reason);+ settled();+ });+ return true;+ },+ /** Stops the work for every held run that `waiting` no longer vouches for, and forgets its result. */+ sweep(waiting: (runId: string) => boolean): void {+ for (const [runId, stop] of pending) {+ if (waiting(runId)) continue;+ stop.abort();+ pending.delete(runId);+ }+ for (const runId of results.keys()) if (!waiting(runId)) results.delete(runId);+ },+ waiting: (runId: string): boolean => pending.has(runId),+ };+}diff --git a/server/routines.ts b/server/routines.tsindex 9b3e6a7cdc..2c92c918dd 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -27,7 +27,7 @@ import {dispatchRefusal, engineFacts, loadOwnerNotices, nextScheduledRun, recoverRun, requeueOnce, weekRuns, type RoutineAlert, type RoutineFailureFacts, type RoutineOwnerNotice,} from "./routine-recovery.ts";import { activeMs, askOf, settleAsk, waitingFor, type RoutineRunAsk } from "./routine-waits.ts";-import { failsLikeLastOutcome, offAfterNoStarts, outcomesNewestFirst } from "./routine-outcomes.ts";+import { failsLikeLastOutcome, offAfterNoStarts, outcomesNewestFirst } from "./routine-outcomes.ts"; import { createRunGate, type RunPreparation } from "./routine-run-gate.ts";import { EVENT_RETRY_WINDOW_MS, loadEventReceipts, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts";import { attachmentPathsOf, attachmentsMalformed, cloneAttachments } from "./routine-attachments.ts";import { loadInstalledPackage, loadRequestReceipts, loadRoutine, loadRun } from "./routine-load.ts";@@ -274,7 +274,7 @@ export interface RoutineManagerOptions {handedOffWorkLive?: (threadId: string) => boolean;launchId?: string;/** A Cloud home woken from a sleep it was stopped for (server/cloud-power.ts): not a startup, so no "run on startup". */- skipStartupRuns?: boolean;+ skipStartupRuns?: boolean; /** What a run needs before it starts (its cloud computer awake and answering): null when nothing, else resolves null when ready or with why the run cannot start. `preparing` is the run's line meanwhile. Only a run nobody started by hand is held; the signal aborts once the run no longer waits to start. */ prepareRun?: RunPreparation<RoutineRun>; preparing?: string;checks?: RoutineChecks;}@@ -322,7 +322,7 @@ export class RoutineManager {private unreadable = false; private malformedAttachments = false;private frozenPending = false;private readonly bootedAt: number;- private readonly checking = new Set<string>(); private readonly progress = new RunProgressSave(() => this.file, () => this.save());+ private readonly checking = new Set<string>(); private readonly progress = new RunProgressSave(() => this.file, () => this.save()); private readonly gate = createRunGate<RoutineRun>((run, signal) => this.options.prepareRun?.(cloneRun(run), signal) ?? null, () => this.tickInBackground());constructor(options: RoutineManagerOptions) {this.options = options;@@ -987,7 +987,7 @@ export class RoutineManager {if (this.closing || this.ticking) return;this.ticking = true;try {- const now = this.now();+ const now = this.now(); this.gate.sweep((id) => this.runs.some((run) => run.id === id && run.status === "queued"));for (const run of this.runs) {if (!["running", "waiting"].includes(run.status) || run.startedAt == null || run.timeoutMinutes == null ||activeMs(run, now) < run.timeoutMinutes * 60_000) continue;@@ -1113,7 +1113,7 @@ export class RoutineManager {}if (state === "missing") { this.failRun(run, this.missingTargetMessage(run.target)); continue; }const paused = run.target === "room-goal" ? null : this.options.pausedText?.(run.botId);- if (paused) { if (triggerSource !== "manual" && this.options.held?.(run.botId)) void this.cancelRun(run.id, paused); else this.failRun(run, paused); continue; }+ if (paused) { if (triggerSource !== "manual" && this.options.held?.(run.botId)) void this.cancelRun(run.id, paused); else this.failRun(run, paused); continue; } const gated = triggerSource === "manual" ? false : this.gate.hold(run); if (gated === true) { if (this.options.preparing && run.attention !== this.options.preparing) { run.attention = this.options.preparing; this.emitRun(run); } continue; } if (gated) { this.failRun(run, gated); continue; }const startedAt = this.now();const suffix = ` · ${new Date(startedAt).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}`;const title = `${run.routineName.slice(0, 80 - suffix.length).trimEnd()}${suffix}`;diff --git a/shared/cloud-computer-recovery.ts b/shared/cloud-computer-recovery.tsindex b740c55145..b7fc214b1f 100644--- a/shared/cloud-computer-recovery.ts+++ b/shared/cloud-computer-recovery.ts@@ -1,7 +1,8 @@/** What MausBot is doing about a cloud computer that stopped answering, as `GET /api/bots/:id/computer/recovery` reports it.- * `not-responding`, `restarting` and `replacing` are under way; the others are how it ended. */+ * `not-responding`, `restoring`, `restarting` and `replacing` are under way; the others are how it ended. `restoring`: the+ * provider says the computer's disk is still being put back after a wake, so it is waited for before any restart. */export const CLOUD_COMPUTER_RECOVERY_STATES = [- "not-responding", "restarting", "replacing", "restarted", "replaced", "unreachable", "capped", "needs-person",+ "not-responding", "restoring", "restarting", "replacing", "restarted", "replaced", "unreachable", "capped", "needs-person",] as const;export type CloudComputerRecoveryState = (typeof CLOUD_COMPUTER_RECOVERY_STATES)[number];@@ -13,11 +14,27 @@ export interface CloudComputerRecovery {}export const recoveryUnderWay = (state: CloudComputerRecoveryState): boolean =>- state === "not-responding" || state === "restarting" || state === "replacing";+ state === "not-responding" || state === "restoring" || state === "restarting" || state === "replacing";++/** Whether the computer answers commands, beside `recovery`, on the same route. `since`: when the wait or the silence began. */+export interface CloudComputerAnswering {+ state: "awake" | "waking" | "restoring" | "not-responding";+ since?: number;+ /** When a command last got an answer, since the server started. */+ lastAnsweredAt: number | null;+}/** What the bot is told, in place of a computer call, while its computer is being restarted or replaced. */export const CLOUD_COMPUTER_NOT_RESPONDING ="This bot's cloud computer isn't responding; MausBot is replacing it. Try again in a minute. Do not retry now.";+/** While it is being stopped and started again, which keeps its files. */+export const CLOUD_COMPUTER_RESTARTING =+ "This bot's cloud computer stopped responding and MausBot is restarting it; its files are kept. This call was not performed. Try again in a minute.";+export const CLOUD_COMPUTER_RESTARTING_UNANSWERED =+ "This bot's cloud computer stopped responding and MausBot is restarting it; its files are kept. This call got no answer and most likely did not run. Try again in a minute.";+/** While the provider is still putting its disk back after a wake. */+export const CLOUD_COMPUTER_RESTORING =+ "This bot's cloud computer is awake but still restoring its disk, so it is not answering yet. This call was not performed. Try again in a minute.";/** Told once, on the bot's first computer call after the replacement. */export const CLOUD_COMPUTER_REPLACED ="This bot's cloud computer stopped responding and was replaced with a new one. Files that were only on the old computer are gone.";@@ -42,6 +59,30 @@ export const CLOUD_COMPUTER_DEAD_WAITING =export const CLOUD_COMPUTER_NO_ANSWER ="The cloud computer did not answer this call, so it may not have run. Take a fresh screenshot in a moment before repeating it.";+/** The call was sent again until its time ran out and no copy of it is known to have run. */+export const CLOUD_COMPUTER_STILL_WAKING =+ "The cloud computer is awake but not answering yet, so this call got no answer and most likely did not run. Try again in a minute, and take a fresh screenshot first.";+export const CLOUD_COMPUTER_STILL_RESTORING =+ "The cloud computer is still restoring its disk after waking, so this call got no answer and most likely did not run. Try again in a minute, and take a fresh screenshot first.";+/** The call ran on the computer, once, but its answer never came back. */+export const CLOUD_COMPUTER_ANSWER_LOST =+ "The cloud computer ran this call, but its answer was lost on the way back. It was not run a second time. Take a fresh screenshot to see what it did before repeating it.";+export const CLOUD_COMPUTER_EXEC_ANSWER_LOST =+ "The cloud computer started this command, but its answer was lost on the way back, so it may still be running or may have finished. It was not "+ + "started a second time. Do not run it again blindly: check first, for example with exec `pgrep -af '<part of the command>'` or by looking at the files it writes.";++/** Why an unattended run did not start because of its cloud computer, and the note on one that finished unsure of it. */+export const RUN_COMPUTER_LINES = {+ waking: "Waiting for its cloud computer to wake and answer",+ noWake: "The cloud computer did not wake, so this run did not start. The next scheduled run tries again.",+ noAnswer: "The cloud computer did not answer in time, so this run did not start. The next scheduled run tries again.",+ afterRestart: "The cloud computer did not answer after a restart, so this run did not start. The next scheduled run tries again; Restart computer or Replace computer in the computer panel fixes it sooner.",+ personBusy: "The cloud computer is not answering, and it was not restarted because someone is using it, so this run did not start. The next scheduled run tries again.",+ restartLimited: "The cloud computer is not answering, and it was already restarted within the last hour, so this run did not start. The next scheduled run tries again.",+ shared: "The team's shared cloud computer is not answering, so this run did not start. A team admin can look at it in the Team map.",+ lastCallUnanswered: "This run finished, but its last cloud computer call got no answer, so check that what it did on the computer is complete. It was not run again.",+} as const;+/** The person's one line in the chat and the Inbox, by its language pack key; each takes the bot's `{name}`. */export const CLOUD_COMPUTER_PERSON_LINES = {replaced: "server.cloudComputer.replaced",diff --git a/src/components/CloudComputerRecovery.dom.test.ts b/src/components/CloudComputerRecovery.dom.test.tsindex c15a6730a7..77a899ef3c 100644--- a/src/components/CloudComputerRecovery.dom.test.ts+++ b/src/components/CloudComputerRecovery.dom.test.ts@@ -6,12 +6,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const calls: Array<{ path: string; init?: { method?: string; body?: string } }> = [];let status: unknown = null;+let answering: unknown = null;let answer: unknown = { answers: true };vi.mock("@/state/store", async (original) => ({...await original<typeof import("@/state/store")>(),api: vi.fn(async (path: string, init?: { method?: string; body?: string }) => {calls.push({ path, init });- return init?.method === "POST" ? answer : { recovery: status };+ return init?.method === "POST" ? answer : { recovery: status, answering };}),}));@@ -23,6 +24,7 @@ let root: Root;beforeEach(() => {calls.length = 0;status = null;+ answering = null;answer = { answers: true };host = document.createElement("div");document.body.append(host);@@ -39,6 +41,41 @@ const render = async (always = true) => {};const button = (label: string) => [...host.querySelectorAll("button")].find((candidate) => candidate.textContent?.includes(label))!;+describe("the computer's own state line", () => {+ const line = () => host.querySelector("[data-testid=cloud-computer-answering]")?.textContent ?? null;++ it("says a silent computer is not responding and since when, in Simple mode too, without asking anything", async () => {+ const since = new Date(2026, 10, 14, 14, 5).getTime();+ answering = { state: "not-responding", since, lastAnsweredAt: since - 60_000 };+ await render(false);+ expect(line()).toContain("Not responding since");+ expect(line()).toContain(new Date(since).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" }));+ expect(host.querySelector("[role=dialog]")).toBeNull();+ });++ it("says when it is waking or restoring its disk", async () => {+ answering = { state: "restoring", since: 1, lastAnsweredAt: null };+ await render(false);+ expect(line()).toBe("Restoring its disk after waking. This can take a few minutes.");+ });++ it("stays quiet about an awake computer in Simple mode, and shows its last answer in Advanced", async () => {+ answering = { state: "awake", lastAnsweredAt: new Date(2026, 10, 14, 14, 2).getTime() };+ await render(false);+ expect(host.querySelector("[data-testid=cloud-computer-recovery]")).toBeNull();+ await render(true);+ expect(line()).toContain("Awake. It last answered at");+ });++ it("leaves the line to the recovery while MausBot is restarting the computer", async () => {+ answering = { state: "not-responding", since: 1, lastAnsweredAt: null };+ status = { state: "restarting", at: 2 };+ await render(false);+ expect(line()).toBeNull();+ expect(host.textContent).toContain("MausBot is restarting it");+ });+});+describe("the computer panel's recovery row", () => {it("shows nothing in Simple mode while the computer is fine", async () => {await render(false);diff --git a/src/components/CloudComputerRecovery.tsx b/src/components/CloudComputerRecovery.tsxindex 2f4dc4a2a6..80e00f5e9a 100644--- a/src/components/CloudComputerRecovery.tsx+++ b/src/components/CloudComputerRecovery.tsx@@ -3,12 +3,13 @@ import { Loader2, RefreshCw, RotateCcw } from "lucide-react";import { api } from "@/state/store";import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";-import { recoveryUnderWay, type CloudComputerRecovery, type CloudComputerRecoveryState } from "../../shared/cloud-computer-recovery";+import { recoveryUnderWay, type CloudComputerAnswering, type CloudComputerRecovery, type CloudComputerRecoveryState } from "../../shared/cloud-computer-recovery";const POLL_MS = 15_000;const LINES: Record<CloudComputerRecoveryState, LocaleKey> = {"not-responding": "computer.recovery.notResponding",+ restoring: "computer.recovery.restoring",restarting: "computer.recovery.restarting",replacing: "computer.recovery.replacing",restarted: "server.cloudComputer.restarted",@@ -25,17 +26,28 @@ export function recoveryLine(recovery: CloudComputerRecovery, name: string): strreturn t(LINES[recovery.state], { name });}+const clock = (at: number) => new Date(at).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });++/** Whether the computer answers its commands, in one line; nothing while it is awake and `quiet`, or was never asked. */+export function answeringLine(answering: CloudComputerAnswering | null, quiet: boolean): string | null {+ if (!answering) return null;+ if (answering.state === "awake") return quiet || answering.lastAnsweredAt === null ? null : t("computer.answering.awake", { time: clock(answering.lastAnsweredAt) });+ if (answering.state === "not-responding") return t("computer.answering.notResponding", { time: clock(answering.since ?? Date.now()) });+ return t(answering.state === "restoring" ? "computer.answering.restoring" : "computer.answering.waking");+}+/** What MausBot is doing about a cloud computer that stopped answering, and the person's Restart computer and Replace computer. *//** `always`: the buttons show even while nothing is wrong (Advanced); otherwise only once MausBot is dealing with the computer. */export function CloudComputerRecoveryRow({ botId, name, always }: { botId: string; name: string; always?: boolean }) {const [recovery, setRecovery] = useState<CloudComputerRecovery | null>(null);+ const [answering, setAnswering] = useState<CloudComputerAnswering | null>(null);const [pending, setPending] = useState<"restart" | "replace" | null>(null);const [result, setResult] = useState<string | null>(null);const path = `/api/bots/${botId}/computer/recovery`;const refresh = useCallback(() => {- api<{ recovery: CloudComputerRecovery | null }>(path, { background: true })- .then((body) => setRecovery(body.recovery ?? null))+ api<{ recovery: CloudComputerRecovery | null; answering?: CloudComputerAnswering | null }>(path, { background: true })+ .then((body) => { setRecovery(body.recovery ?? null); setAnswering(body.answering ?? null); }).catch(() => {});}, [path]);@@ -61,9 +73,12 @@ export function CloudComputerRecoveryRow({ botId, name, always }: { botId: strin};const busy = pending !== null || Boolean(recovery && recoveryUnderWay(recovery.state));- if (!always && !recovery && !result) return null;+ // While MausBot is dealing with the computer its own line says more than this one.+ const state = recovery && recoveryUnderWay(recovery.state) ? null : answeringLine(answering, !always);+ if (!always && !recovery && !result && !state) return null;return (<div className="mt-3" data-testid="cloud-computer-recovery">+ {state && <p className="text-[12px] leading-5 text-ink-secondary" role="status" data-testid="cloud-computer-answering">{state}</p>}{recovery && <p className="text-[12px] leading-5 text-ink-secondary" role="status">{recoveryLine(recovery, name)}</p>}{result && <p className="text-[12px] leading-5 text-danger" role="alert">{result}</p>}<div className="mt-2 flex flex-wrap gap-2">diff --git a/src/locales/en.json b/src/locales/en.jsonindex b68de68e59..b039eb520f 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -8383,6 +8383,11 @@"server.cloudComputer.teamNotResponding": "{name} isn't responding. Delete it in Settings → Computers, then create it again from the Team map; files only on it are lost.","computer.recovery.notResponding": "This cloud computer isn't responding. MausBot is checking it and will restart or replace it.","computer.recovery.restarting": "This cloud computer isn't responding. MausBot is restarting it.",+ "computer.recovery.restoring": "This cloud computer is on but still restoring its disk, so it isn't answering yet. MausBot is waiting for it, and restarts it if that takes more than ten minutes.",+ "computer.answering.awake": "Awake. It last answered at {time}.",+ "computer.answering.waking": "Waking: it is on but not answering yet.",+ "computer.answering.restoring": "Restoring its disk after waking. This can take a few minutes.",+ "computer.answering.notResponding": "Not responding since {time}.","computer.recovery.replacing": "This cloud computer isn't responding. MausBot is replacing it.","computer.recovery.replacedManual": "Replaced. {name} gets a new cloud computer the next time it needs one.","computer.recovery.restartedManual": "Restarted. The cloud computer answers again.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex ed5bc36018..b23cf93af5 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10874,6 +10874,11 @@"server.cloudComputer.teamNotResponding": "{name} não está respondendo. Exclua em Configurações → Computadores e crie de novo pelo mapa da equipe; os arquivos que estão só nele são perdidos.","computer.recovery.notResponding": "Este computador na nuvem não está respondendo. O MausBot está verificando e vai reiniciá-lo ou substituí-lo.","computer.recovery.restarting": "Este computador na nuvem não está respondendo. O MausBot está reiniciando ele.",+ "computer.recovery.restoring": "Este computador na nuvem está ligado, mas ainda está restaurando o disco, então ainda não responde. O MausBot está esperando e reinicia o computador se isso levar mais de dez minutos.",+ "computer.answering.awake": "Acordado. Respondeu pela última vez às {time}.",+ "computer.answering.waking": "Acordando: já está ligado, mas ainda não responde.",+ "computer.answering.restoring": "Restaurando o disco depois de acordar. Isso pode levar alguns minutos.",+ "computer.answering.notResponding": "Sem resposta desde as {time}.","computer.recovery.replacing": "Este computador na nuvem não está respondendo. O MausBot está substituindo ele.","computer.recovery.replacedManual": "Substituído. {name} vai ganhar um computador na nuvem novo na próxima vez que precisar.","computer.recovery.restartedManual": "Reiniciado. O computador na nuvem voltou a responder.",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 346866c61e..f1d211c58d 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -36727,6 +36727,11 @@"server.cloudComputer.teamNotResponding": "f24cba1860c52c915789b0cffa60e755bb108e6f802fcde1638f77338d3ccad0","computer.recovery.notResponding": "06b405a52e66e462ddb658696023226df0f4dd219bced234fb269ab63851ee32","computer.recovery.restarting": "57bad813adf047aa6349bea91e258c6640061ba9c7291529664be72d76b66324",+ "computer.recovery.restoring": "c18f110a459bb11717423a04b513c623fa029c1f38a3358fcab6a250c09a929f",+ "computer.answering.awake": "b6c6a4dcdcd492c63d48e2e5436c873073e56d31e087130b292abccb10839e8c",+ "computer.answering.waking": "edd023e590a242628afcaa239b4c23bc19b0e29e3cccb05d719fc2e8345167c8",+ "computer.answering.restoring": "8219705e0d6d9b3fdaf986a9fbc3e4033322cc520c7d9255f235e9f61ad93f94",+ "computer.answering.notResponding": "df22a5c2fea7c72d1405dea804d6c19fb9e356575bf568d2c4f859bd71afd9c7","computer.recovery.replacing": "22a588f592054bbca3087a6ad277d5bec9f916bac3b3d471f993f57a7a985198","computer.recovery.replacedManual": "26a82b5476745f6eba22896cfbe1c98f2e602299de847fb77c61d8f8481bfc5a","computer.recovery.restartedManual": "8125a758e2f8a3ce409b37e373ed913abb58f0a44ef573f00c2c0c619d8cf9c4",@@ -44936,6 +44941,11 @@"server.cloudComputer.teamNotResponding": "f24cba1860c52c915789b0cffa60e755bb108e6f802fcde1638f77338d3ccad0","computer.recovery.notResponding": "06b405a52e66e462ddb658696023226df0f4dd219bced234fb269ab63851ee32","computer.recovery.restarting": "57bad813adf047aa6349bea91e258c6640061ba9c7291529664be72d76b66324",+ "computer.recovery.restoring": "c18f110a459bb11717423a04b513c623fa029c1f38a3358fcab6a250c09a929f",+ "computer.answering.awake": "b6c6a4dcdcd492c63d48e2e5436c873073e56d31e087130b292abccb10839e8c",+ "computer.answering.waking": "edd023e590a242628afcaa239b4c23bc19b0e29e3cccb05d719fc2e8345167c8",+ "computer.answering.restoring": "8219705e0d6d9b3fdaf986a9fbc3e4033322cc520c7d9255f235e9f61ad93f94",+ "computer.answering.notResponding": "df22a5c2fea7c72d1405dea804d6c19fb9e356575bf568d2c4f859bd71afd9c7","computer.recovery.replacing": "22a588f592054bbca3087a6ad277d5bec9f916bac3b3d471f993f57a7a985198","computer.recovery.replacedManual": "26a82b5476745f6eba22896cfbe1c98f2e602299de847fb77c61d8f8481bfc5a","computer.recovery.restartedManual": "8125a758e2f8a3ce409b37e373ed913abb58f0a44ef573f00c2c0c619d8cf9c4",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex f5bbf6b963..02583b3f9e 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -10144,6 +10144,11 @@"server.cloudComputer.teamNotResponding": "{name} 没有响应。请在“设置 → 电脑”中删除它,然后在团队地图中重新创建;只在它上面的文件会丢失。","computer.recovery.notResponding": "这台云电脑没有响应。MausBot 正在检查,并会重启或替换它。","computer.recovery.restarting": "这台云电脑没有响应。MausBot 正在重启它。",+ "computer.recovery.restoring": "这台云电脑已开机,但仍在恢复磁盘,所以暂时没有响应。MausBot 正在等待;如果超过十分钟,会重启它。",+ "computer.answering.awake": "已唤醒。上次响应时间:{time}。",+ "computer.answering.waking": "正在唤醒:已开机,但暂时没有响应。",+ "computer.answering.restoring": "唤醒后正在恢复磁盘,可能需要几分钟。",+ "computer.answering.notResponding": "自 {time} 起没有响应。","computer.recovery.replacing": "这台云电脑没有响应。MausBot 正在替换它。","computer.recovery.replacedManual": "已替换。{name} 下次需要时会获得一台新的云电脑。","computer.recovery.restartedManual": "已重启。云电脑已恢复响应。",