Skip to content

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

37.4 KB
Raw Blame
// One stub plays the Admin's Boat relay and records every request, so each journey can say which calls a person's action cost.
import { randomUUID } from "node:crypto";
import { spawn, type ChildProcess } from "node:child_process";
import { createServer, type Server } from "node:http";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { CONTROL_WAITED, CONTROL_WAITED_HELD } from "./control-client.ts";
import { CLOUD_COMPUTER_DEAD_WAITING, CLOUD_COMPUTER_NEEDS_PERSON, CLOUD_COMPUTER_REPLACED_BY_PERSON, cloudComputerSetAsideNotice } from "../shared/cloud-computer-recovery.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { freePortBlock } from "./testing/ports.ts";
import { openSse, type SseRecorder } from "./testing/sse.ts";
import { withoutTurnClock } from "./testing/turn-clock-text.ts";

const ROOT = fileURLToPath(new URL("..", import.meta.url));
const FAKE_CLAUDE = join(ROOT, "server/testing/fake-claude-cli.ts");
const INCLUDED = `box_omb_${randomUUID()}`;
// A one-pixel JPEG: what the relay hands back as a screen frame.
const FRAME = Buffer.from("/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/wAALCAABAAEBAREA/8QAFAABAAAAAAAAAAAAAAAAAAAACf/EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAD8AKp//2Q==", "base64");

type Row = { id: string; name?: string; state: string };
type Request = { method: string; path: string };

describe("a cloud computer starts only when the bot uses it", () => {
  let home = "";
  let data = "";
  let dumpFile = "";
  let finishFile = "";
  let base = "";
  let child: ChildProcess | null = null;
  let output = "";
  let relay: Server;
  let events: SseRecorder;
  const rows: Row[] = [];
  /** Looks a waking computer still answers "resuming" to. */
  const wakeLooks = { left: 0 };
  /** The relay refuses every create the way the Admin does once a plan's
   * hours are used up. */
  const refuse = { creates: false };
  /** The relay stops a computer when asked; off, a stop is unknown here, as a provider that will not stop one. */
  const stops = { on: false };
  const requests: Request[] = [];
  /** Computers deleted at the relay: no longer listed, and a 404 to a direct read. */
  const gone = new Set<string>();
  /** Files the bots wrote on their computers, by path. */
  const written = new Map<string, string>();
  /** Boat ids in Boat's own alphabet, one per computer created. */
  const boxId = (n: number) => `bx_${"23456789abcdefgh"[n]}3456789`;

  const api = async (method: string, path: string, body?: unknown) => {
    const response = await fetch(base + path, {
      method, headers: { "content-type": "application/json" },
      ...(body === undefined ? {} : { body: JSON.stringify(body) }),
    });
    return { status: response.status, body: await response.json().catch(() => null) as any };
  };
  const apiOk = async (method: string, path: string, body?: unknown) => {
    const result = await api(method, path, body);
    expect(result.status, `${method} ${path}: ${JSON.stringify(result.body)}`).toBeLessThan(400);
    return result.body;
  };
  async function until<T>(read: () => T | Promise<T>, accept: (value: T) => boolean, ms = 20_000): Promise<T> {
    const end = Date.now() + ms;
    for (;;) {
      const value = await read();
      if (accept(value)) return value;
      if (Date.now() >= end) throw new Error(`Fixture wait expired: ${JSON.stringify(value)}\n${output.slice(-4000)}`);
      await new Promise(resolve => setTimeout(resolve, 40));
    }
  }
  const starts = (botId: string) => events.frames
    .filter(frame => frame.kind === "computer" && frame.botId === botId)
    .map(({ state, place }) => ({ state, place }));
  const creates = () => requests.filter(request => request.method === "POST" && request.path === "/boxes").length;
  const resumes = () => requests.filter(request => request.method === "POST" && request.path.endsWith("/resume")).length;
  const task = async (botId: string) =>
    (await apiOk("GET", "/api/bots?messages=40")).bots.find((bot: any) => bot.id === botId);
  const idle = (botId: string) => until(() => task(botId), bot => bot?.busy === false);
  const lastReply = async (botId: string) => (await task(botId))?.messages.findLast((message: any) => message.kind === "text" && message.role === "bot");
  const failedRow = (botId: string) => until<any>(
    async () => (await task(botId))?.messages.findLast((message: any) => message.tool?.name?.startsWith("error:")),
    Boolean,
  );
  const errorRows = async (threadId: string) =>
    (await apiOk("GET", `/api/threads/${threadId}/messages?limit=60`)).messages
      .filter((message: any) => message.tool?.name?.startsWith("error:"));
  const selectComputer = (sent: any, surface?: string) => {
    const agents = sent.mcpConfig.mcpServers.agents;
    const upstream = agents.env.OMB_GATE_UPSTREAM ? JSON.parse(agents.env.OMB_GATE_UPSTREAM).env : agents.env;
    return fetch(`${base}/api/internal/computer/select`, {
      method: surface ? "POST" : "GET",
      headers: { authorization: `Bearer ${upstream.OMB_COMMS_TOKEN}`, "content-type": "application/json" },
      ...(surface ? { body: JSON.stringify({ surface }) } : {}),
    }).then(response => response.json() as Promise<any>);
  };
  const dump = (): Promise<any> => until((): any => {
    if (!existsSync(dumpFile)) return null;
    try { return JSON.parse(readFileSync(dumpFile, "utf8")); } catch { return null; }
  }, Boolean);
  /** One JSON-RPC request on the mounted cloud computer, exactly as
   * harness-mcp-proxy sends it for the engine. */
  const computerCall = async (sent: any, method: string, params: unknown = {}) => {
    const env = sent.mcpConfig.mcpServers.computer.env;
    const response = await fetch(new URL("/api/internal/computer/mcp", env.OMB_HARNESS_URL), {
      method: "POST",
      headers: { "content-type": "application/json", authorization: `Bearer ${env.OMB_MCP_TOKEN_COMPUTER}` },
      body: JSON.stringify({ method, params }),
    });
    return { status: response.status, body: await response.json() as any };
  };
  const startTurn = async (botId: string, text: string) => {
    rmSync(dumpFile, { force: true });
    rmSync(finishFile, { force: true });
    await apiOk("POST", `/api/bots/${botId}/messages`, { text });
    return dump();
  };
  const finish = async (botId: string) => {
    writeFileSync(finishFile, "finish");
    await idle(botId);
  };
  const cloudBot = async (name: string, patch: Record<string, unknown> = {}) => {
    const { bot } = await apiOk("POST", "/api/bots", { name });
    await apiOk("PATCH", `/api/bots/${bot.id}`, {
      modelSelection: { instanceId: "claude", model: "claude-sonnet-5" }, browser: false, computer: "cloud", ...patch,
    });
    return bot as { id: string; name: string; threadId: string };
  };

  beforeAll(async () => {
    relay = createServer((req, res) => {
      const url = new URL(req.url ?? "/", "http://relay.test");
      let raw = "";
      req.on("data", chunk => { raw += chunk; });
      req.on("end", () => {
        const send = (status: number, payload: unknown) => {
          res.writeHead(status, { "content-type": "application/json" });
          res.end(JSON.stringify(payload));
        };
        // Every request is counted, a stray own-key one included.
        const path = url.pathname.replace(/^\/relay\/api\/box\/v1/, "");
        requests.push({ method: req.method ?? "GET", path });
        // The computer's own transfer links: no key, the file's path in the link.
        const linked = /^\/sandbox\/(get|put)\/([^/]+)$/.exec(url.pathname);
        if (linked) {
          if (req.headers.authorization) return send(400, { ok: false, message: "a transfer link takes no key" });
          const file = Buffer.from(linked[2]!, "base64url").toString("utf8");
          if (linked[1] === "put") { written.set(file, raw); res.writeHead(200); return res.end(); }
          res.writeHead(200, { "content-type": "application/octet-stream", "content-length": String(FRAME.length) });
          return res.end(FRAME);
        }
        if (req.headers.authorization !== `Bearer ${INCLUDED}` || !url.pathname.startsWith("/relay/api/box/v1")) {
          return send(401, { ok: false, code: "unauthorized", message: "Unauthorized" });
        }
        const body = raw ? JSON.parse(raw) : {};
        if (path === "/boxes" && req.method === "GET") return send(200, { ok: true, boxes: rows.filter(row => !gone.has(row.id)), pageInfo: { nextCursor: null } });
        if (path === "/boxes" && req.method === "POST") {
          if (refuse.creates) return send(402, { ok: false, code: "hours_used", message: "This month's 50 cloud computer hours are used up." });
          const row = { id: boxId(rows.length), state: "provisioning" };
          rows.push(row);
          return send(201, { ok: true, box: row });
        }
        const [, id = "", verb = ""] = /^\/boxes\/([^/]+)(?:\/(.+))?$/.exec(path) ?? [];
        const row = rows.find(candidate => candidate.id === id && !gone.has(candidate.id));
        if (!row) return send(404, { ok: false, code: "not_found", message: "Not found" });
        if (!verb && req.method === "DELETE") {
          if (req.headers["x-ascii-confirm-delete"] !== row.id) return send(409, { ok: false, code: "confirmation_required" });
          gone.add(row.id);
          return send(202, { ok: true, operation: { id: `bdop_${"0".repeat(24)}${row.id.slice(3)}`, kind: "box", targetId: row.id, status: "completed" } });
        }
        if (!verb && req.method === "PATCH") {
          row.name = body.name;
          return send(200, { ok: true, box: row });
        }
        if (!verb && req.method === "GET") {
          // A new computer is ready by the next look; a waking one takes longer than the gate's short wait, as a real wake can.
          const seen = { ...row };
          if (row.state === "provisioning") row.state = "ready";
          if (row.state === "resuming" && --wakeLooks.left <= 0) row.state = "ready";
          return send(200, { ok: true, box: seen });
        }
        if (verb === "stop" && req.method === "POST" && stops.on) {
          row.state = "archived";
          return send(200, { ok: true, box: row });
        }
        if (verb === "resume" && req.method === "POST") {
          row.state = "resuming";
          wakeLooks.left = 3;
          return send(200, { ok: true, box: row });
        }
        if (verb === "desktop" && req.method === "POST") return send(200, { desktopUrl: `https://desktop.invalid/${row.id}` });
        if (verb === "commands" && req.method === "POST") return send(200, { exitCode: 0, stdout: "captured", stderr: "" });
        if ((verb === "files/download-url" || verb === "files/upload-url") && req.method === "POST") {
          const get = verb === "files/download-url";
          return send(200, { ok: true, url: `http://${req.headers.host}/sandbox/${get ? "get" : "put"}/${Buffer.from(body.path).toString("base64url")}`,
            method: get ? "GET" : "PUT", path: body.path, expiresAt: new Date(Date.now() + 300_000).toISOString() });
        }
        if (verb === "artifacts" && req.method === "GET") {
          res.writeHead(200, { "content-type": "image/jpeg", "content-length": String(FRAME.length) });
          return res.end(FRAME);
        }
        send(404, { ok: false, code: "not_found", message: "Not found" });
      });
    });
    await new Promise<void>(resolve => relay.listen(0, "127.0.0.1", resolve));
    const relayBase = `http://127.0.0.1:${(relay.address() as { port: number }).port}`;

    home = mkdtempSync(join(tmpdir(), "omb-cloud-lazy-"));
    data = join(home, "data");
    dumpFile = join(home, "dump.json");
    finishFile = join(home, "finish");
    mkdirSync(data, { recursive: true });
    writeFileSync(join(data, "config.json"), JSON.stringify({ instances: {
      claude: {
        driver: "claudeAgent", config: { cli: FAKE_CLAUDE },
        environment: { FAKE_CLAUDE_MODE: "slow", FAKE_CLAUDE_DUMP: dumpFile, FAKE_CLAUDE_SLOW_FINISH_GATE: finishFile },
      },
      // The same CLI, whose every turn first takes one screenshot through
      // the cloud computer's tools, as a model's first computer call does.
      uses: {
        driver: "claudeAgent", config: { cli: FAKE_CLAUDE },
        environment: { FAKE_CLAUDE_USES_CLOUD_COMPUTER: "1" },
      },
      // The same CLI, signed out: what a Cloud with no AI sign-in yet runs.
      "claude-out": {
        driver: "claudeAgent", config: { cli: FAKE_CLAUDE },
        environment: { FAKE_CLAUDE_MODE: "not-logged-in", FAKE_CLAUDE_AUTH: "out" },
      },
    } }));
    const port = await freePortBlock([0, 1]);
    base = `http://127.0.0.1:${port}`;
    child = spawn(process.execPath, [join(ROOT, "server/index.ts")], {
      cwd: ROOT,
      env: {
        PATH: process.env.PATH, ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
        HOME: home, USERPROFILE: home, OMB_DATA_DIR: data, TEMP: home, TMP: home, TMPDIR: home,
        OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1),
        // An own key would go here; nothing may use it.
        OMB_BOAT_API: `${relayBase}/own-key-must-not-be-used`,
        OMB_CLOUD_BOAT_URL: `${relayBase}/relay/api/box/v1`,
        OMB_CLOUD_BOAT_TOKEN: INCLUDED,
        // The host's container daemon is not this test's subject: a hung
        // Docker Desktop answers the local-VM probe (`docker info`) only at
        // its 10 s timeout, once per select_computer call. A socket nobody
        // listens on makes the probe fail at once, as on a host without one.
        DOCKER_HOST: `unix://${join(home, "no-docker.sock")}`,
        CONTAINER_HOST: `unix://${join(home, "no-podman.sock")}`,
        // The provider's error is still read twice before a computer is deleted; here the reads need not be half an hour apart.
        OMB_CLOUD_COMPUTER_DEAD_CONFIRM_MS: "0",
      },
      stdio: ["ignore", "pipe", "pipe"],
    });
    child.stdout?.on("data", chunk => { output += chunk; });
    child.stderr?.on("data", chunk => { output += chunk; });
    await until(async () => {
      if (child!.exitCode !== null) throw new Error(`the server exited:\n${output}`);
      try { return (await fetch(`${base}/api/health`)).ok; } catch { return false; }
    }, Boolean, 30_000);
    // Chief first makes the seeded bot its team's Chief, which answers a teammate's failed run with a Problems to look at
    // turn of its own on Claude: its dump would stand in for the turn under test. Stepped down, each dump is the test's own.
    const seeded = (await apiOk("GET", "/api/bots?messages=0")).bots.find((bot: any) => bot.chiefOfStaff);
    await apiOk("PATCH", `/api/bots/${seeded.id}`, { chiefOfStaff: false });
    events = await openSse(`${base}/api/events`);
    await events.until(frame => frame.kind === "hello");
  }, 60_000);

  afterAll(async () => {
    events?.close();
    if (child) await waitForExit(child, { signal: "SIGTERM" });
    if (relay) await new Promise<void>(resolve => { relay.closeAllConnections(); relay.close(() => resolve()); });
    if (home) await removeTempDir(home);
  });

  it("choosing Cloud computer and opening the Computer panel create and wake nothing", async () => {
    const before = requests.length;
    const bot = await cloudBot("Chooser");
    const status = await apiOk("GET", `/api/bots/${bot.id}/computer?threadId=${bot.threadId}`);
    expect(status).toMatchObject({ surface: "cloud", backend: "box", configured: true, box: null });
    expect(creates()).toBe(0);
    expect(resumes()).toBe(0);
    expect(requests.slice(before).every(request => request.method === "GET")).toBe(true);
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  });

  it("a plain chat on Cloud computer makes no relay call at all", async () => {
    const bot = await cloudBot("Chatter");
    const before = requests.length;
    const sent = await startTurn(bot.id, "hi");
    expect(sent.mcpConfig.mcpServers.computer?.args).toEqual([expect.stringMatching(/harness-mcp-proxy\.(?:ts|js)$/), "computer"]);
    expect(sent.systemPrompt).toContain("assigned cloud computer");
    const listed = await computerCall(sent, "tools/list");
    expect(listed.body.result.tools.map((tool: { name: string }) => tool.name)).toContain("screenshot");
    await finish(bot.id);
    expect(withoutTurnClock((await lastReply(bot.id))?.text ?? "")).toContain("reply to: hi");
    expect(requests.slice(before)).toEqual([]);
    expect(starts(bot.id)).toEqual([]);
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 30_000);

  it("a second turn on Cloud computer runs in the engine the first one started, and its tools answer only while a turn runs", async () => {
    const bot = await cloudBot("Returner");
    const first = await startTurn(bot.id, "hi");
    await finish(bot.id);
    expect((await computerCall(first, "tools/list")).status).toBe(401);
    const second = await startTurn(bot.id, "again");
    expect(second.pid).toBe(first.pid);
    expect((await computerCall(first, "tools/list")).body.result.tools.map((tool: { name: string }) => tool.name)).toContain("screenshot");
    await finish(bot.id);
    expect((await computerCall(first, "tools/list")).status).toBe(401);
    // A stop ends the engine and the credential with it: the next turn starts its own, with a new one.
    const third = await startTurn(bot.id, "once more");
    expect(third.pid).toBe(first.pid);
    await apiOk("POST", `/api/bots/${bot.id}/interrupt`, { threadId: bot.threadId });
    await idle(bot.id);
    const fourth = await startTurn(bot.id, "after the stop");
    expect(fourth.pid).not.toBe(first.pid);
    expect(fourth.mcpConfig.mcpServers.computer.env.OMB_MCP_TOKEN_COMPUTER).not.toBe(first.mcpConfig.mcpServers.computer.env.OMB_MCP_TOKEN_COMPUTER);
    expect((await computerCall(first, "tools/list")).status).toBe(401);
    await finish(bot.id);
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 60_000);

  it("a room message to a member on Cloud computer makes no relay call either", async () => {
    const bot = await cloudBot("Room member");
    const { group } = await apiOk("POST", "/api/groups", { name: "Lazy room", memberIds: [bot.id] });
    await apiOk("PATCH", `/api/groups/${group.id}/setup`, { action: "skip" });
    const before = requests.length;
    rmSync(dumpFile, { force: true });
    rmSync(finishFile, { force: true });
    await apiOk("POST", `/api/groups/${group.id}/messages`, { text: "hi" });
    const sent = await dump();
    expect(sent.mcpConfig.mcpServers.computer?.args?.at(-1)).toBe("computer");
    await finish(bot.id);
    expect(requests.slice(before)).toEqual([]);
    await apiOk("DELETE", `/api/groups/${group.id}`);
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 30_000);

  it("the first computer call creates the cloud computer exactly once and says so in the chat", async () => {
    const bot = await cloudBot("Worker");
    const sent = await startTurn(bot.id, "Open the cloud desktop");
    expect(creates()).toBe(0);
    const first = await computerCall(sent, "tools/call", { name: "screenshot", arguments: {} });
    expect(first.status).toBe(200);
    expect(first.body.result.isError, JSON.stringify(first.body)).toBeFalsy();
    expect(first.body.result.content[0]).toMatchObject({ type: "image", mimeType: "image/jpeg" });
    expect(creates()).toBe(1);
    const second = await computerCall(sent, "tools/call", { name: "screenshot", arguments: {} });
    expect(second.body.result.isError).toBeFalsy();
    expect(creates()).toBe(1);
    expect(resumes()).toBe(0);
    expect(starts(bot.id)).toEqual([{ state: "provisioning", place: "cloud" }]);
    await finish(bot.id);

    // The wake (four looks, ten seconds) outlasts CONTROL_ACT_WITHIN_MS, so that call is answered unperformed and the next acts at once.
    rows.find(row => row.name && row.state === "ready")!.state = "archived";
    const next = await startTurn(bot.id, "Look again");
    expect(resumes()).toBe(0);
    const waited = await computerCall(next, "tools/call", { name: "screenshot", arguments: {} });
    expect(waited.body.result).toEqual({ isError: true, content: [{ type: "text", text: CONTROL_WAITED_HELD }] });
    expect(resumes()).toBe(1);
    const woken = await computerCall(next, "tools/call", { name: "screenshot", arguments: {} });
    expect(woken.body.result.isError, JSON.stringify(woken.body)).toBeFalsy();
    expect(woken.body.result.content[0]).toMatchObject({ type: "image", mimeType: "image/jpeg" });
    expect(resumes()).toBe(1);
    expect(creates()).toBe(1);
    expect(starts(bot.id)).toEqual([{ state: "provisioning", place: "cloud" }, { state: "waking", place: "cloud" }]);
    await finish(bot.id);
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 60_000);

  const callThroughWait = async (sent: any) => {
    let result = await computerCall(sent, "tools/call", { name: "screenshot", arguments: {} });
    for (let tries = 0; [CONTROL_WAITED, CONTROL_WAITED_HELD].includes(result.body.result.content?.[0]?.text) && tries < 3; tries++) {
      result = await computerCall(sent, "tools/call", { name: "screenshot", arguments: {} });
    }
    return result;
  };
  const recoveryLines = async (botId: string) => (await task(botId)).messages
    .filter((message: any) => message.tool?.name?.startsWith("recovery:")).map((message: any) => message.tool.name);
  const inboxNotices = (botId: string) => events.frames
    .filter((frame: any) => frame.kind === "notify" && frame.notification?.botId === botId && frame.notification.kind === "notice")
    .map((frame: any) => frame.notification.body);

  it("with automatic replacement switched off, a computer whose machine is gone is never deleted by itself: the bot and the person are told once, and Replace computer replaces it", async () => {
    await apiOk("PATCH", "/api/config", { features: { cloudComputerAutoReplace: false } });
    const bot = await cloudBot("Waiting");
    await apiOk("POST", `/api/bots/${bot.id}/computer/provision`);
    const dead = rows.at(-1)!;
    dead.state = "error";
    const before = requests.length, made = creates();
    const next = await startTurn(bot.id, "Look again");
    const held = await callThroughWait(next);
    expect(held.body.result.isError).toBe(true);
    expect(held.body.result.content[0].text).toContain(CLOUD_COMPUTER_NEEDS_PERSON);
    await computerCall(next, "tools/call", { name: "screenshot", arguments: {} });
    expect(requests.slice(before).filter(request => request.method === "DELETE")).toEqual([]);
    expect(creates()).toBe(made);
    const line = "Waiting's cloud computer stopped responding. Replace computer in the computer panel gives it a new one; files only on the old computer are lost.";
    expect(await recoveryLines(bot.id)).toEqual([`recovery: ${line}`]);
    expect(inboxNotices(bot.id)).toEqual([line]);

    // The person replaces it while the turn still waits on it.
    expect(await apiOk("POST", `/api/bots/${bot.id}/computer/recovery`, { action: "replace" })).toEqual({ replaced: true });
    expect(requests.slice(before).filter(request => request.method === "DELETE")).toEqual([{ method: "DELETE", path: `/boxes/${dead.id}` }]);
    await finish(bot.id);
    const after = await startTurn(bot.id, "Try again");
    const fresh = await callThroughWait(after);
    expect(fresh.body.result.isError, JSON.stringify(fresh.body)).toBeFalsy();
    expect(fresh.body.result.content[0]).toEqual({ type: "text", text: CLOUD_COMPUTER_REPLACED_BY_PERSON });
    expect(creates()).toBe(made + 1);
    await finish(bot.id);
    expect(await recoveryLines(bot.id)).toHaveLength(1);
    await apiOk("PATCH", "/api/config", { features: { cloudComputerAutoReplace: true } });
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 60_000);

  it("by default, a computer whose machine is gone is set aside (never deleted) on its next use for a new one, and the bot and the person are told once", async () => {
    stops.on = true;
    const bot = await cloudBot("Stranded");
    // Made from the panel, so no command has answered on it lately: one that has is kept for a few minutes.
    await apiOk("POST", `/api/bots/${bot.id}/computer/provision`);
    const dead = rows.at(-1)!;
    expect(dead.name).toBeTruthy();
    // What Boat reports once the host under a computer is lost.
    dead.state = "error";
    const before = requests.length, made = creates();
    const status = await apiOk("GET", `/api/bots/${bot.id}/computer?threadId=${bot.threadId}`);
    expect(status.box).toBeNull();

    // The first read of the provider's error only notes it; the next start, after a second read, replaces the computer.
    const first = await startTurn(bot.id, "Look");
    const noted = await callThroughWait(first);
    expect(noted.body.result.content[0].text).toContain(CLOUD_COMPUTER_DEAD_WAITING);
    expect(requests.slice(before).filter(request => request.method === "DELETE")).toEqual([]);
    await finish(bot.id);
    const next = await startTurn(bot.id, "Look again");
    const replaced = await callThroughWait(next);
    expect(replaced.body.result.isError, JSON.stringify(replaced.body)).toBeFalsy();
    const until = /until (\d{4}-\d{2}-\d{2})/.exec(replaced.body.result.content[0].text)?.[1] ?? "";
    expect(replaced.body.result.content[0]).toEqual({ type: "text", text: cloudComputerSetAsideNotice(until) });
    expect(replaced.body.result.content[1]).toMatchObject({ type: "image", mimeType: "image/jpeg" });
    const again = await computerCall(next, "tools/call", { name: "screenshot", arguments: {} });
    expect(again.body.result.content).toHaveLength(1);
    expect(requests.slice(before).filter(request => request.method === "DELETE")).toEqual([]);
    expect(dead).toMatchObject({ state: "archived", name: expect.stringMatching(/-set-aside-\d{4}-\d{2}-\d{2}$/) });
    expect(creates()).toBe(made + 1);
    await finish(bot.id);

    const waiting = "Stranded's cloud computer stopped responding. Replace computer in the computer panel gives it a new one; files only on the old computer are lost.";
    const line = `Stranded's cloud computer stopped responding, so MausBot gave it a new one. The old one is kept with its files until ${until} in Settings → Desktops & browser → Desktops, then deleted.`;
    expect(await recoveryLines(bot.id)).toEqual([`recovery: ${waiting}`, `recovery: ${line}`]);
    expect(inboxNotices(bot.id)).toEqual([waiting, line]);
    stops.on = false;
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 60_000);

  it("a signed-out engine fails with the existing sign-in row and no relay call", async () => {
    const bot = await cloudBot("Signed out", { modelSelection: { instanceId: "claude-out", model: "claude-sonnet-5" } });
    const before = requests.length;
    await apiOk("POST", `/api/bots/${bot.id}/messages`, { text: "hi" });
    const row = await failedRow(bot.id);
    await idle(bot.id);
    expect(row.tool).toMatchObject({ ok: false, setup: true });
    expect(row.tool.name).toMatch(/Not logged in/);
    expect(requests.slice(before)).toEqual([]);
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 30_000);

  it("a tool selection without the computer is refused before any relay call, and select_computer does not offer it", async () => {
    const bot = await cloudBot("Scribe", { toolScope: { deny: ["mcp:computer:*"] } });
    const before = requests.length;
    await apiOk("POST", `/api/bots/${bot.id}/messages`, { text: "hi" });
    const row = await failedRow(bot.id);
    expect(row.tool.name).toBe("error: What Scribe can use doesn't include a desktop. Change what Scribe can use in its settings.");
    expect(row.tool.place).toEqual({ state: "cc-tools-off", params: { bot: "Scribe" }, source: "works-on" });
    await idle(bot.id);
    expect(requests.slice(before)).toEqual([]);

    await apiOk("PATCH", `/api/bots/${bot.id}`, { computer: null });
    const sent = await startTurn(bot.id, "Which computers can you use?");
    const agents = sent.mcpConfig.mcpServers.agents;
    const upstream = agents.env.OMB_GATE_UPSTREAM ? JSON.parse(agents.env.OMB_GATE_UPSTREAM).env : agents.env;
    const selection = await fetch(`${base}/api/internal/computer/select`, {
      headers: { authorization: `Bearer ${upstream.OMB_COMMS_TOKEN}` },
    }).then(response => response.json() as Promise<any>);
    expect(selection.options.find((option: { surface: string }) => option.surface === "cloud")).toMatchObject({
      available: false, reason: "What Scribe can use doesn't include a desktop. Change what Scribe can use in its settings.",
    });
    await finish(bot.id);
    expect(requests.slice(before)).toEqual([]);
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 30_000);

  it("select_computer counts the cloud computer this turn mounted as chosen before it starts: no restart, no pin", async () => {
    const bot = await cloudBot("Selector");
    const before = creates();
    const sent = await startTurn(bot.id, "Check the weather site on your desktop");
    expect((await selectComputer(sent)).current).toBe("cloud");
    expect(await selectComputer(sent, "cloud")).toMatchObject({ status: "ready", surface: "cloud" });
    expect(await selectComputer(sent, "auto")).toMatchObject({ status: "ready", surface: "cloud" });
    rmSync(dumpFile, { force: true });
    await finish(bot.id);
    await new Promise(resolve => setTimeout(resolve, 750));
    expect(existsSync(dumpFile)).toBe(false);
    expect((await task(bot.id))?.busy).toBe(false);
    const thread = (await task(bot.id))?.tasks.find((candidate: any) => candidate.threadId === bot.threadId);
    expect(thread?.surface).toBeUndefined();
    expect(creates()).toBe(before);
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 30_000);

  it("work handed to a bot on Auto runs on that bot's own cloud computer; a consult, and a bot with none, get no computer", async () => {
    const auto = async (name: string) => {
      const bot = await cloudBot(name);
      const own = await startTurn(bot.id, "Open the cloud desktop");
      expect((await computerCall(own, "tools/call", { name: "screenshot", arguments: {} })).body.result.isError).toBeFalsy();
      await finish(bot.id);
      await apiOk("PATCH", `/api/bots/${bot.id}`, { computer: null });
      return bot;
    };
    const writer = await auto("Writer");
    const asked = await auto("Asked");
    const fresh = await cloudBot("Fresh", { computer: null });
    const sender = await cloudBot("Sender", { computer: null });
    const before = { creates: creates(), resumes: resumes() };
    const agents = (await startTurn(sender.id, "Hand the desktop check over")).mcpConfig.mcpServers.agents;
    const token = (agents.env.OMB_GATE_UPSTREAM ? JSON.parse(agents.env.OMB_GATE_UPSTREAM).env : agents.env).OMB_COMMS_TOKEN;
    const handed = async (botId: string, call: Record<string, unknown>) => {
      rmSync(dumpFile, { force: true });
      const response = await fetch(`${base}/api/internal/coordinate-bots`, {
        method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
        body: JSON.stringify({ botIds: [botId], ...call }),
      });
      expect(response.status, await response.clone().text()).toBe(200);
      const sent = await dump();
      expect(sent.cwd).toContain(botId);
      return sent;
    };
    const work = await handed(writer.id, { message: "Check the weather site on your desktop" });
    expect(work.mcpConfig.mcpServers.computer?.args).toEqual([expect.stringMatching(/harness-mcp-proxy\.(?:ts|js)$/), "computer"]);
    expect(work.systemPrompt).toContain("assigned cloud computer");
    const consult = await handed(asked.id, { message: "Which weather site do you use?", consult: true });
    expect(consult.mcpConfig.mcpServers.computer).toBeUndefined();
    const none = await handed(fresh.id, { message: "Check the weather site on your desktop" });
    expect(none.mcpConfig.mcpServers.computer).toBeUndefined();
    writeFileSync(finishFile, "finish");
    for (const bot of [writer, asked, fresh, sender]) await idle(bot.id);
    // Mounting is lazy: nothing was created or woken without a computer call.
    expect({ creates: creates(), resumes: resumes() }).toEqual(before);
    // A finished hand-off can still be settling its dispatch for a moment after the bot reads idle; the delete waits for it.
    for (const bot of [writer, asked, fresh, sender]) {
      const deleted = await until(() => api("DELETE", `/api/bots/${bot.id}`), (response) => response.status !== 409);
      expect(deleted.status).toBeLessThan(400);
    }
  }, 90_000);

  it("a room member whose cloud computer can't start says why in the room, once, under its own name", async () => {
    refuse.creates = true;
    try {
      const bot = await cloudBot("Roomie", { modelSelection: { instanceId: "uses", model: "claude-sonnet-5" } });
      const { group } = await apiOk("POST", "/api/groups", { name: "Refused room", memberIds: [bot.id] });
      await apiOk("PATCH", `/api/groups/${group.id}/setup`, { action: "skip" });
      await apiOk("POST", `/api/groups/${group.id}/messages`, { text: "take a screenshot of your desktop" });
      await until(() => errorRows(group.threadId), rows => rows.length > 0, 30_000);
      await idle(bot.id);
      await new Promise(resolve => setTimeout(resolve, 500));
      const rows = await errorRows(group.threadId);
      expect(rows).toHaveLength(1);
      expect(rows[0].from).toMatchObject({ botId: bot.id, name: "Roomie" });
      expect(rows[0].tool.name).toBe("error: This month's cloud desktop hours are used up. See your plan on the Plan page.");
      expect(rows[0].tool.place).toEqual({ state: "cc-no-hours", params: { bot: "Roomie" }, source: "room" });
      await apiOk("DELETE", `/api/groups/${group.id}`);
      await apiOk("DELETE", `/api/bots/${bot.id}`);
    } finally {
      refuse.creates = false;
    }
  }, 45_000);

  it("a cloud routine whose computer can't start records that cause on its run", async () => {
    refuse.creates = true;
    try {
      const { bot } = await apiOk("POST", "/api/bots", { name: "Runner" });
      await apiOk("PATCH", `/api/bots/${bot.id}`, { modelSelection: { instanceId: "uses", model: "claude-sonnet-5" }, browser: false });
      const { routine } = await apiOk("POST", "/api/routines", {
        name: "Cloud check", botId: bot.id, prompt: "Screenshot the desktop.", runOn: "cloud", enabled: false,
        schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 },
      });
      const { run } = await apiOk("POST", `/api/routines/${routine.id}/run`, {});
      const finished = await until(
        async () => (await apiOk("GET", "/api/routines")).runs.find((candidate: any) => candidate.id === run.id),
        (candidate: any) => Boolean(candidate) && !["queued", "running", "waiting"].includes(candidate.status),
        45_000,
      );
      const rows = await errorRows(finished.threadId);
      expect(rows).toHaveLength(1);
      expect(finished.status).toBe("failed");
      expect(`error: ${finished.error}`).toBe(rows[0].tool.name);
      expect(finished.error).toBe("This month's cloud desktop hours are used up. See your plan on the Plan page.");
      expect(rows[0].tool.place).toEqual({ state: "cc-no-hours", params: { bot: "Runner" }, source: "routine" });
      await until(() => task(bot.id), current => current?.busy === false && current.tasks.every((entry: any) => !entry.busy));
      await apiOk("DELETE", `/api/routines/${routine.id}`);
      await apiOk("DELETE", `/api/bots/${bot.id}`);
    } finally {
      refuse.creates = false;
    }
  }, 60_000);

  it("copies files between the cloud computer and the folder the turn works in, in a chat and in a room", async () => {
    const bot = await cloudBot("Copier");
    const sent = await startTurn(bot.id, "Bring the results back");
    const call = (turn: any, name: string, args: unknown) => computerCall(turn, "tools/call", { name, arguments: args });
    const brought = await call(sent, "copy_from_computer", { path: "/home/user/out/frame.jpg", to: "results/frame.jpg" });
    expect(brought.body.result, JSON.stringify(brought.body)).toEqual({ content: [{ type: "text", text: JSON.stringify({ path: join("results", "frame.jpg"), bytes: FRAME.length }) }] });
    expect(readFileSync(join(sent.cwd, "results", "frame.jpg"))).toEqual(FRAME);
    writeFileSync(join(sent.cwd, "query.sql"), "select 1;");
    expect((await call(sent, "copy_to_computer", { from: "query.sql", path: "/tmp/query.sql" })).body.result.isError).toBeFalsy();
    expect(written.get("/tmp/query.sql")).toBe("select 1;");
    expect((await call(sent, "copy_from_computer", { path: "/tmp/x", to: "../escaped" })).body.result.isError).toBe(true);
    expect(requests.filter(request => /files\/(download|upload)-url$|^\/sandbox\//.test(request.path)).map(request => `${request.method} ${request.path.split("/").slice(0, 3).join("/")}`))
      .toEqual([`POST /boxes/${rows.at(-1)!.id}`, "GET /sandbox/get", `POST /boxes/${rows.at(-1)!.id}`, "PUT /sandbox/put"]);
    expect(JSON.stringify([brought.body])).not.toContain("/sandbox/");
    await finish(bot.id);

    const { group } = await apiOk("POST", "/api/groups", { name: "Copy room", memberIds: [bot.id] });
    await apiOk("PATCH", `/api/groups/${group.id}/setup`, { action: "skip" });
    rmSync(dumpFile, { force: true });
    rmSync(finishFile, { force: true });
    await apiOk("POST", `/api/groups/${group.id}/messages`, { text: "Bring it here too" });
    const roomTurn = await dump();
    expect(roomTurn.cwd).not.toBe(sent.cwd);
    expect((await call(roomTurn, "copy_from_computer", { path: "/tmp/frame.jpg" })).body.result.isError).toBeFalsy();
    expect(readFileSync(join(roomTurn.cwd, "frame.jpg"))).toEqual(FRAME);
    await finish(bot.id);
    await apiOk("DELETE", `/api/groups/${group.id}`);
    await apiOk("DELETE", `/api/bots/${bot.id}`);
  }, 60_000);
});